Method from org.codehaus.groovy.runtime.DefaultGroovyMethods Detail: |
public static int abs(Number number) {
return Math.abs(number.intValue());
}
|
public static long abs(Long number) {
return Math.abs(number.longValue());
}
|
public static float abs(Float number) {
return Math.abs(number.floatValue());
}
|
public static double abs(Double number) {
return Math.abs(number);
}
|
public static Socket accept(ServerSocket serverSocket,
Closure closure) throws IOException {
final Socket socket = serverSocket.accept();
new Thread(new Runnable() {
public void run() {
try {
closure.call(socket);
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
LOG.warning("Caught exception closing socket: " + e);
}
}
}
}
}).start();
return socket;
}
Accepts a connection and passes the resulting Socket to the closure
which runs in a new Thread. |
public static void addShutdownHook(Object self,
Closure closure) {
Runtime.getRuntime().addShutdownHook(new Thread(closure));
}
Allows the usage of addShutdownHook without getting the runtime first. |
public static Number and(Number left,
Number right) {
return NumberMath.and(left, right);
}
Bitwise AND together two Numbers. |
public static BitSet and(BitSet left,
BitSet right) {
BitSet result = (BitSet) left.clone();
result.and(right);
return result;
}
Bitwise AND together two BitSets. |
public static Boolean and(Boolean left,
Boolean right) {
return left && right;
}
Logical conjunction of two boolean operators. |
public static boolean any(Object self) {
for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext();) {
if (DefaultTypeTransformation.castToBoolean(iter.next())) {
return true;
}
}
return false;
}
Iterates over the elements of a collection, and checks whether at least
one element is true according to the Groovy Truth.
Equivalent to self.any({element -> element}) |
public static boolean any(Object self,
Closure closure) {
for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext();) {
if (DefaultTypeTransformation.castToBoolean(closure.call(iter.next()))) {
return true;
}
}
return false;
}
Iterates over the contents of an object or collection, and checks whether a
predicate is valid for at least one element. |
public static boolean any(Map<K, V> self,
Closure closure) {
for (Map.Entry entry : self.entrySet()) {
if (DefaultTypeTransformation.castToBoolean(callClosureForMapEntry(closure, entry))) {
return true;
}
}
return false;
}
Iterates over the entries of a map, and checks whether a predicate is
valid for at least one entry. If the
closure takes one parameter then it will be passed the Map.Entry
otherwise if the closure takes two parameters then it will be
passed the key and the value. |
public static void append(File file,
Object text) throws IOException {
BufferedWriter writer = null;
try {
writer = newWriter(file, true);
InvokerHelper.write(writer, text);
writer.flush();
Writer temp = writer;
writer = null;
temp.close();
} finally {
closeWithWarning(writer);
}
}
Append the text at the end of the File. |
public static void append(File file,
byte[] bytes) throws IOException {
BufferedOutputStream stream = null;
try {
stream = new BufferedOutputStream( new FileOutputStream(file,true) );
stream.write(bytes, 0, bytes.length);
stream.flush();
OutputStream temp = stream;
stream = null;
temp.close();
} finally {
closeWithWarning(stream);
}
}
Append bytes to the end of a File. |
public static void append(File self,
InputStream stream) throws IOException {
OutputStream out = new FileOutputStream( self, true );
try {
leftShift( out, stream );
}
finally {
closeWithWarning( out );
}
}
Append binary data to the file. It will not be
interpreted as text. |
public static void append(File file,
Object text,
String charset) throws IOException {
BufferedWriter writer = null;
try {
writer = newWriter(file, charset, true);
InvokerHelper.write(writer, text);
writer.flush();
Writer temp = writer;
writer = null;
temp.close();
} finally {
closeWithWarning(writer);
}
}
Append the text at the end of the File, using a specified encoding. |
public static boolean asBoolean(Object object) {
return object != null;
}
Coerce an object instance to a boolean value.
An object is coerced to true if it's not null, to false if it is null. |
public static boolean asBoolean(Boolean bool) {
return bool.booleanValue();
}
Coerce an Boolean instance to a boolean value. |
public static boolean asBoolean(Matcher matcher) {
RegexSupport.setLastMatcher(matcher);
return matcher.find();
}
Coerce a Matcher instance to a boolean value. |
public static boolean asBoolean(Collection collection) {
return !collection.isEmpty();
}
Coerce a collection instance to a boolean value.
A collection is coerced to false if it's empty, and to true otherwise. |
public static boolean asBoolean(Map map) {
return !map.isEmpty();
}
Coerce a map instance to a boolean value.
A map is coerced to false if it's empty, and to true otherwise. |
public static boolean asBoolean(Iterator iterator) {
return iterator.hasNext();
}
Coerce an iterator instance to a boolean value.
An iterator is coerced to false if there are no more elements to iterate over,
and to true otherwise. |
public static boolean asBoolean(Enumeration enumeration) {
return enumeration.hasMoreElements();
}
Coerce an enumeration instance to a boolean value.
An enumeration is coerced to false if there are no more elements to enumerate,
and to true otherwise. |
public static boolean asBoolean(CharSequence string) {
return string.length() > 0;
}
Coerce a string (an instance of CharSequence) to a boolean value.
A string is coerced to false if it is of length 0,
and to true otherwise. |
public static boolean asBoolean(Object[] array) {
return array.length > 0;
}
Coerce an Object array to a boolean value.
An Object array is false if the array is of length 0.
and to true otherwise |
public static boolean asBoolean(Character character) {
return character.charValue() != 0;
}
Coerce a character to a boolean value.
A character is coerced to false if it's character value is equal to 0,
and to true otherwise. |
public static boolean asBoolean(Number number) {
return number.doubleValue() != 0;
}
Coerce a number to a boolean value.
A number is coerced to false if its double value is equal to 0, and to true otherwise,
and to true otherwise. |
public static boolean asBoolean(GroovyResultSet grs) {
//TODO: check why this asBoolean() method is needed for SqlTest to pass with custom boolean coercion in place
return true;
}
Coerce a GroovyResultSet to a boolean value.
A GroovyResultSet is coerced to false if there are no more rows to iterate over,
and to true otherwise. |
public static Map<K, V> asImmutable(Map<? extends K, ? extends V> self) {
return Collections.unmodifiableMap(self);
}
A convenience method for creating an immutable map. |
public static SortedMap<K, V> asImmutable(SortedMap<K, ? extends V> self) {
return Collections.unmodifiableSortedMap(self);
}
A convenience method for creating an immutable sorted map. |
public static List<T> asImmutable(List<? extends T> self) {
return Collections.unmodifiableList(self);
}
A convenience method for creating an immutable list |
public static Set<T> asImmutable(Set<? extends T> self) {
return Collections.unmodifiableSet(self);
}
A convenience method for creating an immutable list. |
public static SortedSet<T> asImmutable(SortedSet<T> self) {
return Collections.unmodifiableSortedSet(self);
}
A convenience method for creating an immutable sorted set. |
public static Collection<T> asImmutable(Collection<? extends T> self) {
return Collections.unmodifiableCollection(self);
}
A convenience method for creating an immutable Collection. |
public static List<T> asList(Collection<T> self) {
if (self instanceof List) {
return (List< T >) self;
} else {
return new ArrayList< T >(self);
}
}
Converts this collection to a List. |
public static Map<K, V> asSynchronized(Map<K, V> self) {
return Collections.synchronizedMap(self);
}
A convenience method for creating a synchronized Map. |
public static SortedMap<K, V> asSynchronized(SortedMap<K, V> self) {
return Collections.synchronizedSortedMap(self);
}
A convenience method for creating a synchronized SortedMap. |
public static Collection<T> asSynchronized(Collection<T> self) {
return Collections.synchronizedCollection(self);
}
A convenience method for creating a synchronized Collection. |
public static List<T> asSynchronized(List<T> self) {
return Collections.synchronizedList(self);
}
A convenience method for creating a synchronized List. |
public static Set<T> asSynchronized(Set<T> self) {
return Collections.synchronizedSet(self);
}
A convenience method for creating a synchronized Set. |
public static SortedSet<T> asSynchronized(SortedSet<T> self) {
return Collections.synchronizedSortedSet(self);
}
A convenience method for creating a synchronized SortedSet. |
public static Object asType(Collection col,
Class clazz) {
if (col.getClass() == clazz) {
return col;
}
if (clazz == List.class) {
return asList(col);
}
if (clazz == Set.class) {
if (col instanceof Set) return col;
return new HashSet(col);
}
if (clazz == SortedSet.class) {
if (col instanceof SortedSet) return col;
return new TreeSet(col);
}
if (clazz == Queue.class) {
if (col instanceof Queue) return col;
return new LinkedList(col);
}
if (clazz == Stack.class) {
if (col instanceof Stack) return col;
final Stack stack = new Stack();
stack.addAll(col);
return stack;
}
Object[] args = {col};
try {
return InvokerHelper.invokeConstructorOf(clazz, args);
} catch (Exception e) {
// ignore
}
return asType((Object) col, clazz);
}
Converts the given collection to another type. A default concrete
type is used for List, Set, or SortedSet. If the given type has
a constructor taking a collection, that is used. Otherwise, the
call is deferred to {link #asType(Object,Class)}. If this
collection is already of the given type, the same instance is
returned. |
public static Object asType(Object[] ary,
Class clazz) {
if (clazz == List.class) {
return new ArrayList(Arrays.asList(ary));
}
if (clazz == Set.class) {
return new HashSet(Arrays.asList(ary));
}
if (clazz == SortedSet.class) {
return new TreeSet(Arrays.asList(ary));
}
return asType((Object) ary, clazz);
}
Converts the given array to either a List, Set, or
SortedSet. If the given class is something else, the
call is deferred to {link #asType(Object,Class)}. |
public static Object asType(Closure cl,
Class clazz) {
if (clazz.isInterface() && !(clazz.isInstance(cl))) {
return Proxy.newProxyInstance(
clazz.getClassLoader(),
new Class[]{clazz},
new ConvertedClosure(cl));
}
try {
return asType((Object) cl, clazz);
} catch (GroovyCastException ce) {
try {
return ProxyGenerator.INSTANCE.instantiateAggregateFromBaseClass(cl, clazz);
} catch (GroovyRuntimeException cause) {
throw new GroovyCastException("Error casting closure to " + clazz.getName() +
", Reason: " + cause.getMessage());
}
}
}
Coerces the closure to an implementation of the given class. The class
is assumed to be an interface or class with a single method definition.
The closure is used as the implementation of that single method. |
public static Object asType(Map map,
Class clazz) {
if (!(clazz.isInstance(map)) && clazz.isInterface()) {
return Proxy.newProxyInstance(
clazz.getClassLoader(),
new Class[]{clazz},
new ConvertedMap(map));
}
try {
return asType((Object) map, clazz);
} catch (GroovyCastException ce) {
try {
return ProxyGenerator.INSTANCE.instantiateAggregateFromBaseClass(map, clazz);
} catch (GroovyRuntimeException cause) {
throw new GroovyCastException("Error casting map to " + clazz.getName() +
", Reason: " + cause.getMessage());
}
}
}
Coerces this map to the given type, using the map's keys as the public
method names, and values as the implementation. Typically the value
would be a closure which behaves like the method implementation. |
public static Object asType(Number self,
Class c) {
if (c == BigDecimal.class) {
return toBigDecimal(self);
} else if (c == BigInteger.class) {
return toBigInteger(self);
} else if (c == Double.class) {
return toDouble(self);
} else if (c == Float.class) {
return toFloat(self);
}
return asType((Object) self, c);
}
Transform this number to a the given type, using the 'as' operator. The
following types are supported in addition to the default
#asType(Object,Class) :
- BigDecimal
- BigInteger
- Double
- Float
|
public static Object asType(File f,
Class c) {
if (c == Writable.class) {
return asWritable(f);
}
return asType((Object) f, c);
}
|
public static Object asType(GString self,
Class c) {
if (c == File.class) {
return new File(self.toString());
} else if (Number.class.isAssignableFrom(c)) {
return asType(self.toString(), c);
}
return asType((Object) self, c);
}
|
public static Object asType(String self,
Class c) {
if (c == List.class) {
return toList(self);
} else if (c == BigDecimal.class) {
return toBigDecimal(self);
} else if (c == BigInteger.class) {
return toBigInteger(self);
} else if (c == Long.class || c == Long.TYPE) {
return toLong(self);
} else if (c == Integer.class || c == Integer.TYPE) {
return toInteger(self);
} else if (c == Short.class || c == Short.TYPE) {
return toShort(self);
} else if (c == Byte.class || c == Byte.TYPE) {
return Byte.valueOf(self.trim());
} else if (c == Character.class || c == Character.TYPE) {
return toCharacter(self);
} else if (c == Double.class || c == Double.TYPE) {
return toDouble(self);
} else if (c == Float.class || c == Float.TYPE) {
return toFloat(self);
} else if (c == File.class) {
return new File(self);
} else if (DefaultTypeTransformation.isEnumSubclass(c)) {
return InvokerHelper.invokeMethod(c, "valueOf", new Object[]{ self });
}
return asType((Object) self, c);
}
Provides a method to perform custom 'dynamic' type conversion
to the given class using the as operator.
Example: '123' as Double
By default, the following types are supported:
- List
- BigDecimal
- BigInteger
- Long
- Integer
- Short
- Byte
- Character
- Double
- Float
- File
- Subclasses of Enum (Java 5 and above)
If any other type is given, the call is delegated to
#asType(Object,Class) .
|
public static Object asType(Object obj,
Class type) {
if (String.class == type) {
return InvokerHelper.toString(obj);
}
try {
return DefaultTypeTransformation.castToType(obj, type);
}
catch (GroovyCastException e) {
MetaClass mc = InvokerHelper.getMetaClass(obj);
if (mc instanceof ExpandoMetaClass) {
ExpandoMetaClass emc = (ExpandoMetaClass) mc;
Object mixedIn = emc.castToMixedType(obj, type);
if (mixedIn != null)
return mixedIn;
}
throw e;
}
}
Converts a given object to a type. This method is used through
the "as" operator and is overloadable as any other operator. |
public static File asWritable(File file) {
return new WritableFile(file);
}
|
public static File asWritable(File file,
String encoding) {
return new WritableFile(file, encoding);
}
Allows a file to return a Writable implementation that can output itself
to a Writer stream. |
public static Pattern bitwiseNegate(String self) {
return Pattern.compile(self);
}
Turns a String into a regular expression Pattern |
public static BitSet bitwiseNegate(BitSet self) {
BitSet result = (BitSet) self.clone();
result.flip(0, result.size() - 1);
return result;
}
|
protected static Object callClosureForLine(Closure closure,
String line,
int counter) {
if (closure.getMaximumNumberOfParameters() == 2) {
return closure.call(new Object[]{line, counter});
}
return closure.call(line);
}
|
protected static Object callClosureForMapEntry(Closure closure,
Entry entry) {
if (closure.getMaximumNumberOfParameters() == 2) {
return closure.call(new Object[]{entry.getKey(), entry.getValue()});
}
return closure.call(entry);
}
|
protected static Object callClosureForMapEntryAndCounter(Closure closure,
Entry entry,
int counter) {
if (closure.getMaximumNumberOfParameters() == 3) {
return closure.call(new Object[]{entry.getKey(), entry.getValue(), counter});
}
if (closure.getMaximumNumberOfParameters() == 2) {
return closure.call(new Object[]{entry, counter});
}
return closure.call(entry);
}
|
public static String center(String self,
Number numberOfChars) {
return center(self, numberOfChars, " ");
}
Center a String and pad it with spaces appended around it |
public static String center(String self,
Number numberOfChars,
String padding) {
int numChars = numberOfChars.intValue();
if (numChars < = self.length()) {
return self;
} else {
int charsToAdd = numChars - self.length();
String semiPad = charsToAdd % 2 == 1 ?
getPadding(padding, charsToAdd / 2 + 1) :
getPadding(padding, charsToAdd / 2);
if (charsToAdd % 2 == 0)
return semiPad + self + semiPad;
else
return semiPad.substring(0, charsToAdd / 2) + self + semiPad;
}
}
Center a String and pad it with the characters appended around it |
public static List collect(Object self,
Closure closure) {
return (List) collect(self, new ArrayList(), closure);
}
Iterates through this object transforming each value into a new value using the
closure as a transformer, returning a list of transformed values.
Example:
def list = [1, 'a', 1.23, true ]
def types = list.collect { it.class }
|
public static List collect(Collection self,
Closure closure) {
return (List) collect(self, new ArrayList(self.size()), closure);
}
Iterates through this collection transforming each entry into a new value using the closure
as a transformer, returning a list of transformed values. |
public static List collect(Map self,
Closure closure) {
return (List) collect(self, new ArrayList(self.size()), closure);
}
Iterates through this Map transforming each entry into a new value using the closure
as a transformer, returning a list of transformed values. |
public static Collection collect(Object self,
Collection collection,
Closure closure) {
for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext();) {
collection.add(closure.call(iter.next()));
}
return collection;
}
Iterates through this object transforming each object into a new value using the closure
as a transformer and adding it to the collection, returning the resulting collection. |
public static Collection collect(Collection self,
Collection collection,
Closure closure) {
for (Iterator iter = self.iterator(); iter.hasNext();) {
collection.add(closure.call(iter.next()));
if (closure.getDirective() == Closure.DONE) {
break;
}
}
return collection;
}
Iterates through this collection transforming each value into a new value using the closure
as a transformer, returning an initial collection plus the transformed values. |
public static Collection collect(Map self,
Collection collection,
Closure closure) {
boolean isTwoParams = (closure.getParameterTypes().length == 2);
for (Iterator iter = self.entrySet().iterator(); iter.hasNext();) {
if (isTwoParams) {
Map.Entry entry = (Map.Entry) iter.next();
collection.add(closure.call(new Object[]{entry.getKey(), entry.getValue()}));
} else {
collection.add(closure.call(iter.next()));
}
}
return collection;
}
Iterates through this Map transforming each entry into a new value using the closure
as a transformer, returning a list of transformed values. |
public static List collectAll(Collection self,
Closure closure) {
return (List) collectAll(self, new ArrayList(self.size()), closure);
}
Recursively iterates through this collection transforming each non-Collection value
into a new value using the closure as a transformer. Returns a potentially nested
list of transformed values. |
public static Collection collectAll(Collection self,
Collection collection,
Closure closure) {
for (Iterator iter = self.iterator(); iter.hasNext();) {
final Object o = iter.next();
if (o instanceof Collection) {
Collection c = (Collection) o;
collection.add(collectAll(c, createSimilarCollection(collection, c.size()), closure));
} else {
collection.add(closure.call(o));
}
if (closure.getDirective() == Closure.DONE) {
break;
}
}
return collection;
}
Recursively iterates through this collection transforming each non-Collection value
into a new value using the closure as a transformer. Returns a potentially nested
collection of transformed values. |
public static List combinations(Collection self) {
return GroovyCollections.combinations(self);
}
Adds GroovyCollections#combinations(Collection) as a method on collections. |
public static int compareTo(Character left,
Number right) {
return compareTo(Integer.valueOf(left), right);
}
Compare a Character and a Number. The ordinal value of the Character
is used in the comparison (the ordinal value is the unicode
value which for simple character sets is the ASCII value). |
public static int compareTo(Number left,
Character right) {
return compareTo(left, Integer.valueOf(right));
}
Compare a Number and a Character. The ordinal value of the Character
is used in the comparison (the ordinal value is the unicode
value which for simple character sets is the ASCII value). |
public static int compareTo(Character left,
Character right) {
return compareTo(Integer.valueOf(left), right);
}
Compare two Characters. The ordinal values of the Characters
are compared (the ordinal value is the unicode
value which for simple character sets is the ASCII value). |
public static int compareTo(Number left,
Number right) {
/** @todo maybe a double dispatch thing to handle new large numbers? */
return NumberMath.compareTo(left, right);
}
Compare two Numbers. Equality (==) for numbers dispatches to this. |
public static Thread consumeProcessErrorStream(Process self,
StringBuffer error) {
Thread thread = new Thread(new TextDumper(self.getErrorStream(), error));
thread.start();
return thread;
}
Gets the error stream from a process and reads it
to keep the process from blocking due to a full buffer.
The processed stream data is appended to the supplied StringBuffer.
A new Thread is started, so this method will return immediately. |
public static Thread consumeProcessErrorStream(Process self,
OutputStream err) {
Thread thread = new Thread(new ByteDumper(self.getErrorStream(), err));
thread.start();
return thread;
}
Gets the error stream from a process and reads it
to keep the process from blocking due to a full buffer.
The processed stream data is appended to the supplied OutputStream.
A new Thread is started, so this method will return immediately. |
public static Thread consumeProcessErrorStream(Process self,
Writer err) {
Thread thread = new Thread(new TextDumper(self.getErrorStream(), err));
thread.start();
return thread;
}
Gets the error stream from a process and reads it
to keep the process from blocking due to a full buffer.
The processed stream data is appended to the supplied Writer.
A new Thread is started, so this method will return immediately. |
public static void consumeProcessOutput(Process self) {
consumeProcessOutput(self, (OutputStream)null, (OutputStream)null);
}
Gets the output and error streams from a process and reads them
to keep the process from blocking due to a full output buffer.
The stream data is thrown away but blocking due to a full output buffer is avoided.
Use this method if you don't care about the standard or error output and just
want the process to run silently - use carefully however, because since the stream
data is thrown away, it might be difficult to track down when something goes wrong.
For this, two Threads are started, so this method will return immediately. |
public static void consumeProcessOutput(Process self,
StringBuffer output,
StringBuffer error) {
consumeProcessOutputStream(self, output);
consumeProcessErrorStream(self, error);
}
Gets the output and error streams from a process and reads them
to keep the process from blocking due to a full output buffer.
The processed stream data is appended to the supplied StringBuffer.
For this, two Threads are started, so this method will return immediately. |
public static void consumeProcessOutput(Process self,
OutputStream output,
OutputStream error) {
consumeProcessOutputStream(self, output);
consumeProcessErrorStream(self, error);
}
Gets the output and error streams from a process and reads them
to keep the process from blocking due to a full output buffer.
The processed stream data is appended to the supplied OutputStream.
For this, two Threads are started, so this method will return immediately. |
public static Thread consumeProcessOutputStream(Process self,
StringBuffer output) {
Thread thread = new Thread(new TextDumper(self.getInputStream(), output));
thread.start();
return thread;
}
Gets the output stream from a process and reads it
to keep the process from blocking due to a full output buffer.
The processed stream data is appended to the supplied StringBuffer.
A new Thread is started, so this method will return immediately. |
public static Thread consumeProcessOutputStream(Process self,
OutputStream output) {
Thread thread = new Thread(new ByteDumper(self.getInputStream(), output));
thread.start();
return thread;
}
Gets the output stream from a process and reads it
to keep the process from blocking due to a full output buffer.
The processed stream data is appended to the supplied OutputStream.
A new Thread is started, so this method will return immediately. |
public static Thread consumeProcessOutputStream(Process self,
Writer output) {
Thread thread = new Thread(new TextDumper(self.getInputStream(), output));
thread.start();
return thread;
}
Gets the output stream from a process and reads it
to keep the process from blocking due to a full output buffer.
The processed stream data is appended to the supplied Writer.
A new Thread is started, so this method will return immediately. |
public static boolean contains(String self,
String text) {
int idx = self.indexOf(text);
return idx >= 0;
}
Provide an implementation of contains() like
Collection#contains(Object) to make Strings more polymorphic.
This method is not required on JDK 1.5 onwards |
public static Number count(Iterator self,
Object value) {
long answer = 0;
while (self.hasNext()) {
if (DefaultTypeTransformation.compareEqual(self.next(), value)) {
++answer;
}
}
// for b/c with Java return an int if we can
if (answer < = Integer.MAX_VALUE) return new Long(answer).intValue();
return answer;
}
Counts the number of occurrences of the given value from the
items within this Iterator.
Comparison is done using Groovy's == operator (using
compareTo(value) == 0 or equals(value) ).
The iterator will become exhausted of elements after determining the count value. |
public static Number count(Collection self,
Object value) {
return count(self.iterator(), value);
}
Counts the number of occurrences of the given value inside this collection.
Comparison is done using Groovy's == operator (using
compareTo(value) == 0 or equals(value) ). |
public static Number count(Object[] self,
Object value) {
return count(Arrays.asList(self), value);
}
Counts the number of occurrences of the given value inside this array.
Comparison is done using Groovy's == operator (using
compareTo(value) == 0 or equals(value) ). |
public static Number count(int[] self,
Object value) {
return count(InvokerHelper.asIterator(self), value);
}
Counts the number of occurrences of the given value inside this array.
Comparison is done using Groovy's == operator (using
compareTo(value) == 0 or equals(value) ). |
public static Number count(long[] self,
Object value) {
return count(InvokerHelper.asIterator(self), value);
}
Counts the number of occurrences of the given value inside this array.
Comparison is done using Groovy's == operator (using
compareTo(value) == 0 or equals(value) ). |
public static Number count(short[] self,
Object value) {
return count(InvokerHelper.asIterator(self), value);
}
Counts the number of occurrences of the given value inside this array.
Comparison is done using Groovy's == operator (using
compareTo(value) == 0 or equals(value) ). |
public static Number count(char[] self,
Object value) {
return count(InvokerHelper.asIterator(self), value);
}
Counts the number of occurrences of the given value inside this array.
Comparison is done using Groovy's == operator (using
compareTo(value) == 0 or equals(value) ). |
public static Number count(boolean[] self,
Object value) {
return count(InvokerHelper.asIterator(self), value);
}
Counts the number of occurrences of the given value inside this array.
Comparison is done using Groovy's == operator (using
compareTo(value) == 0 or equals(value) ). |
public static Number count(double[] self,
Object value) {
return count(InvokerHelper.asIterator(self), value);
}
Counts the number of occurrences of the given value inside this array.
Comparison is done using Groovy's == operator (using
compareTo(value) == 0 or equals(value) ). |
public static Number count(float[] self,
Object value) {
return count(InvokerHelper.asIterator(self), value);
}
Counts the number of occurrences of the given value inside this array.
Comparison is done using Groovy's == operator (using
compareTo(value) == 0 or equals(value) ). |
public static Number count(byte[] self,
Object value) {
return count(InvokerHelper.asIterator(self), value);
}
Counts the number of occurrences of the given value inside this array.
Comparison is done using Groovy's == operator (using
compareTo(value) == 0 or equals(value) ). |
public static int count(String self,
String text) {
int answer = 0;
for (int idx = 0; true; idx++) {
idx = self.indexOf(text, idx);
if (idx >= 0) {
++answer;
} else {
break;
}
}
return answer;
}
Count the number of occurencies of a substring. |
protected static StringBufferWriter createStringBufferWriter(StringBuffer self) {
return new StringBufferWriter(self);
}
|
protected static StringWriter createStringWriter(String self) {
StringWriter answer = new StringWriter();
answer.write(self);
return answer;
}
|
public static byte[] decodeBase64(String value) {
int byteShift = 4;
int tmp = 0;
boolean done = false;
final StringBuilder buffer = new StringBuilder();
for (int i = 0; i != value.length(); i++) {
final char c = value.charAt(i);
final int sixBit = (c < 123) ? TRANSLATE_TABLE[c] : 66;
if (sixBit < 64) {
if (done)
throw new RuntimeException("= character not at end of base64 value"); // TODO: change this exception type
tmp = (tmp < < 6) | sixBit;
if (byteShift-- != 4) {
buffer.append((char) ((tmp > > (byteShift * 2)) & 0XFF));
}
} else if (sixBit == 64) {
byteShift--;
done = true;
} else if (sixBit == 66) {
// RFC 2045 says that I'm allowed to take the presence of
// these characters as evedence of data corruption
// So I will
throw new RuntimeException("bad character in base64 value"); // TODO: change this exception type
}
if (byteShift == 0) byteShift = 4;
}
try {
return buffer.toString().getBytes("ISO-8859-1");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("Base 64 decode produced byte values > 255"); // TODO: change this exception type
}
}
Decode the String from Base64 into a byte array. |
public static boolean deleteDir(File self) {
if (!self.exists())
return true;
if (!self.isDirectory())
return false;
File[] files = self.listFiles();
if (files == null)
// couldn't access files
return false;
// delete contained files
boolean result = true;
for (File file : files) {
if (file.isDirectory()) {
if (!deleteDir(file))
result = false;
} else {
if (!file.delete())
result = false;
}
}
// now delete directory itself
if(!self.delete())
result = false;
return result;
}
Deletes a directory with all contained files and subdirectories.
The method returns
- true, when deletion was successful
- true, when it is called for a non existing directory
- false, when it is called for a file which isn't a directory
- false, when directory couldn't be deleted
|
public static String denormalize(String self) {
// Don't do this in static initializer because we may never be needed.
// TODO: Put this lineSeparator property somewhere everyone can use it.
if (lineSeparator == null) {
final StringWriter sw = new StringWriter(2);
try {
// We use BufferedWriter rather than System.getProperty because
// it has the security manager rigamarole to deal with the possible exception.
final BufferedWriter bw = new BufferedWriter(sw);
bw.newLine();
bw.flush();
lineSeparator = sw.toString();
} catch (IOException ioe) {
// This shouldn't happen, but this is the same default used by
// BufferedWriter on a security exception.
lineSeparator = "\n";
}
}
final int len = self.length();
if (len < 1) {
return self;
}
final StringBuilder sb = new StringBuilder((110 * len) / 100);
int i = 0;
while (i < len) {
final char ch = self.charAt(i++);
switch (ch) {
case '\r':
sb.append(lineSeparator);
// Eat the following LF if any.
if ((i < len) && (self.charAt(i) == '\n')) {
++i;
}
break;
case '\n':
sb.append(lineSeparator);
break;
default:
sb.append(ch);
break;
}
}
return sb.toString();
}
Return a String with lines (separated by LF, CR/LF, or CR)
terminated by the platform specific line separator. |
public static boolean disjoint(Collection left,
Collection right) {
if (left.isEmpty() || right.isEmpty())
return true;
Collection pickFrom = new TreeSet(new NumberAwareComparator());
pickFrom.addAll(right);
for (final Object o : left) {
if (pickFrom.contains(o))
return false;
}
return true;
}
Returns true if the intersection of two collections is empty. |
public static Number div(Character left,
Number right) {
return NumberNumberDiv.div(Integer.valueOf(left), right);
}
Divide a Character by a Number. The ordinal value of the Character
is used in the division (the ordinal value is the unicode
value which for simple character sets is the ASCII value). |
public static Number div(Number left,
Character right) {
return NumberNumberDiv.div(left, Integer.valueOf(right));
}
Divide a Number by a Character. The ordinal value of the Character
is used in the division (the ordinal value is the unicode
value which for simple character sets is the ASCII value). |
public static Number div(Character left,
Character right) {
return div(Integer.valueOf(left), right);
}
Divide one Character by another. The ordinal values of the Characters
are used in the division (the ordinal value is the unicode
value which for simple character sets is the ASCII value). |
public static void downto(Number self,
Number to,
Closure closure) {
int self1 = self.intValue();
int to1 = to.intValue();
if (self1 >= to1) {
for (int i = self1; i >= to1; i--) {
closure.call(i);
}
} else
throw new GroovyRuntimeException("Infinite loop in " + self + ".downto(" + to + ")");
}
Iterates from this number down to the given number, inclusive,
decrementing by one each time. |
public static void downto(long self,
Number to,
Closure closure) {
long to1 = to.longValue();
if (self >= to1) {
for (long i = self; i >= to1; i--) {
closure.call(i);
}
} else
throw new GroovyRuntimeException("Infinite loop in " + self + ".downto(" + to + ")");
}
Iterates from this number down to the given number, inclusive,
decrementing by one each time. |
public static void downto(Long self,
Number to,
Closure closure) {
long to1 = to.longValue();
if (self >= to1) {
for (long i = self; i >= to1; i--) {
closure.call(i);
}
} else
throw new GroovyRuntimeException("Infinite loop in " + self + ".downto(" + to + ")");
}
Iterates from this number down to the given number, inclusive,
decrementing by one each time. |
public static void downto(float self,
Number to,
Closure closure) {
float to1 = to.floatValue();
if (self >= to1) {
for (float i = self; i >= to1; i--) {
closure.call(i);
}
} else
throw new GroovyRuntimeException("Infinite loop in " + self + ".downto(" + to + ")");
}
Iterates from this number down to the given number, inclusive,
decrementing by one each time. |
public static void downto(Float self,
Number to,
Closure closure) {
float to1 = to.floatValue();
if (self >= to1) {
for (float i = self; i >= to1; i--) {
closure.call(i);
}
} else
throw new GroovyRuntimeException("Infinite loop in " + self + ".downto(" + to + ")");
}
Iterates from this number down to the given number, inclusive,
decrementing by one each time. |
public static void downto(double self,
Number to,
Closure closure) {
double to1 = to.doubleValue();
if (self >= to1) {
for (double i = self; i >= to1; i--) {
closure.call(i);
}
} else
throw new GroovyRuntimeException("Infinite loop in " + self + ".downto(" + to + ")");
}
Iterates from this number down to the given number, inclusive,
decrementing by one each time. |
public static void downto(Double self,
Number to,
Closure closure) {
double to1 = to.doubleValue();
if (self >= to1) {
for (double i = self; i >= to1; i--) {
closure.call(i);
}
} else
throw new GroovyRuntimeException("Infinite loop in " + self + ".downto(" + to + ")");
}
Iterates from this number down to the given number, inclusive,
decrementing by one each time. |
public static void downto(BigInteger self,
Number to,
Closure closure) {
if (to instanceof BigDecimal) {
final BigDecimal one = BigDecimal.valueOf(10, 1); // That's what you get for "1.0".
final BigDecimal to1 = (BigDecimal) to;
final BigDecimal selfD = new BigDecimal(self);
if (selfD.compareTo(to1) >= 0) {
for (BigDecimal i = selfD; i.compareTo(to1) >= 0; i = i.subtract(one)) {
closure.call(i.toBigInteger());
}
} else
throw new GroovyRuntimeException("Infinite loop in " + self + ".downto(" + to + ")");
} else if (to instanceof BigInteger) {
final BigInteger one = BigInteger.valueOf(1);
final BigInteger to1 = (BigInteger) to;
if (self.compareTo(to1) >= 0) {
for (BigInteger i = self; i.compareTo(to1) >= 0; i = i.subtract(one)) {
closure.call(i);
}
} else
throw new GroovyRuntimeException("Infinite loop in " + self + ".downto(" + to + ")");
} else {
final BigInteger one = BigInteger.valueOf(1);
final BigInteger to1 = new BigInteger(to.toString());
if (self.compareTo(to1) >= 0) {
for (BigInteger i = self; i.compareTo(to1) >= 0; i = i.subtract(one)) {
closure.call(i);
}
} else
throw new GroovyRuntimeException("Infinite loop in " + self + ".downto(" + to + ")");
}
}
Iterates from this number down to the given number, inclusive,
decrementing by one each time. |
public static void downto(BigDecimal self,
Number to,
Closure closure) {
final BigDecimal one = BigDecimal.valueOf(10, 1); // Quick way to get "1.0".
if (to instanceof BigDecimal) {
BigDecimal to1 = (BigDecimal) to;
if (self.compareTo(to1) >= 0) {
for (BigDecimal i = self; i.compareTo(to1) >= 0; i = i.subtract(one)) {
closure.call(i);
}
} else
throw new GroovyRuntimeException("Infinite loop in " + self + ".downto(" + to + ")");
} else if (to instanceof BigInteger) {
BigDecimal to1 = new BigDecimal((BigInteger) to);
if (self.compareTo(to1) >= 0) {
for (BigDecimal i = self; i.compareTo(to1) >= 0; i = i.subtract(one)) {
closure.call(i);
}
} else
throw new GroovyRuntimeException("Infinite loop in " + self + ".downto(" + to + ")");
} else {
BigDecimal to1 = new BigDecimal(to.toString());
if (self.compareTo(to1) >= 0) {
for (BigDecimal i = self; i.compareTo(to1) >= 0; i = i.subtract(one)) {
closure.call(i);
}
} else
throw new GroovyRuntimeException("Infinite loop in " + self + ".downto(" + to + ")");
}
}
Iterates from this number down to the given number, inclusive,
decrementing by one each time. Each number is passed to the closure.
Example:
10.5.downto(0) {
println it
}
Prints numbers 10.5, 9.5 ... to 0.5. |
public static String dump(Object self) {
if (self == null) {
return "null";
}
StringBuilder buffer = new StringBuilder("< ");
Class klass = self.getClass();
buffer.append(klass.getName());
buffer.append("@");
buffer.append(Integer.toHexString(self.hashCode()));
boolean groovyObject = self instanceof GroovyObject;
/*jes this may be rewritten to use the new getProperties() stuff
* but the original pulls out private variables, whereas getProperties()
* does not. What's the real use of dump() here?
*/
while (klass != null) {
for (final Field field : klass.getDeclaredFields()) {
if ((field.getModifiers() & Modifier.STATIC) == 0) {
if (groovyObject && field.getName().equals("metaClass")) {
continue;
}
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
field.setAccessible(true);
return null;
}
});
buffer.append(" ");
buffer.append(field.getName());
buffer.append("=");
try {
buffer.append(InvokerHelper.toString(field.get(self)));
} catch (Exception e) {
buffer.append(e);
}
}
}
klass = klass.getSuperclass();
}
/* here is a different implementation that uses getProperties(). I have left
* it commented out because it returns a slightly different list of properties;
* i.e. it does not return privates. I don't know what dump() really should be doing,
* although IMO showing private fields is a no-no
*/
/*
List props = getProperties(self);
for(Iterator itr = props.keySet().iterator(); itr.hasNext(); ) {
String propName = itr.next().toString();
// the original skipped this, so I will too
if(pv.getName().equals("class")) continue;
if(pv.getName().equals("metaClass")) continue;
buffer.append(" ");
buffer.append(propName);
buffer.append("=");
try {
buffer.append(InvokerHelper.toString(props.get(propName)));
}
catch (Exception e) {
buffer.append(e);
}
}
*/
buffer.append(" >");
return buffer.toString();
}
Generates a detailed dump string of an object showing its class,
hashCode and fields. |
public static T each(T self,
Closure closure) {
each(InvokerHelper.asIterator(self), closure);
return self;
}
Iterates through an aggregate type or data structure,
passing each item to the given closure. Custom types may utilize this
method by simply providing an "iterator()" method. The items returned
from the resulting iterator will be passed to the closure. |
public static Map<K, V> each(Map<K, V> self,
Closure closure) {
for (Map.Entry entry : self.entrySet()) {
callClosureForMapEntry(closure, entry);
}
return self;
}
Allows a Map to be iterated through using a closure. If the
closure takes one parameter then it will be passed the Map.Entry
otherwise if the closure takes two parameters then it will be
passed the key and the value. |
public static void eachByte(File self,
Closure closure) throws IOException {
BufferedInputStream is = newInputStream(self);
eachByte(is, closure);
}
Traverse through each byte of this File |
public static void eachByte(Byte[] self,
Closure closure) {
each(self, closure);
}
Traverse through each byte of this Byte array. Alias for each. |
public static void eachByte(byte[] self,
Closure closure) {
each(self, closure);
}
Traverse through each byte of this byte array. Alias for each. |
public static void eachByte(InputStream is,
Closure closure) throws IOException {
try {
while (true) {
int b = is.read();
if (b == -1) {
break;
} else {
closure.call((byte) b);
}
}
InputStream temp = is;
is = null;
temp.close();
} finally {
closeWithWarning(is);
}
}
Traverse through each byte of the specified stream. The
stream is closed after the closure returns. |
public static void eachByte(URL url,
Closure closure) throws IOException {
InputStream is = url.openConnection().getInputStream();
eachByte(is, closure);
}
Reads the InputStream from this URL, passing each byte to the given
closure. The URL stream will be closed before this method returns. |
public static void eachDir(File self,
Closure closure) throws FileNotFoundException, IllegalArgumentException {
eachFile(self, closure, true);
}
Invokes the closure for each subdirectory in this directory,
ignoring regular files. |
public static void eachDirMatch(File self,
Object filter,
Closure closure) throws FileNotFoundException, IllegalArgumentException {
eachFileMatch(self, filter, closure, true);
}
Invokes the closure for each subdirectory whose name (dir.name) matches the given filter in the given directory
- calling the isCase() method to determine if a match occurs. This method can be used
with different kinds of filters like regular expressions, classes, ranges etc.
Only subdirectories are matched; regular files are ignored. |
public static void eachDirRecurse(File self,
Closure closure) throws FileNotFoundException, IllegalArgumentException {
eachFileRecurse(self, closure, true);
}
Invokes the closure for each descendant directory of this directory.
Sub-directories are recursively searched in a depth-first fashion.
Only subdirectories are passed to the closure; regular files are ignored. |
public static void eachFile(File self,
Closure closure) throws FileNotFoundException, IllegalArgumentException {
eachFile(self, closure, false);
}
Invokes the closure for each 'child' file in this 'parent' folder/directory.
Both regular files and subfolders/subdirectories are processed. |
public static void eachFileMatch(File self,
Object filter,
Closure closure) throws FileNotFoundException, IllegalArgumentException {
eachFileMatch(self, filter, closure, false);
}
Invokes the closure for each file whose name (file.name) matches the given filter in the given directory
- calling the isCase() method to determine if a match occurs. This method can be used
with different kinds of filters like regular expressions, classes, ranges etc.
Both regular files and subdirectories are matched. |
public static void eachFileRecurse(File self,
Closure closure) throws FileNotFoundException, IllegalArgumentException {
eachFileRecurse(self, closure, false);
}
Invokes the closure for each descendant file in this directory.
Sub-directories are recursively searched in a depth-first fashion.
Both regular files and subdirectories are passed to the closure. |
public static Object eachLine(String self,
Closure closure) throws IOException {
return eachLine(self, 0, closure);
}
Iterates through this String line by line. Each line is passed
to the given 1 or 2 arg closure. If a 2 arg closure is found
the line count is passed as the second argument. |
public static Object eachLine(File self,
Closure closure) throws IOException {
return eachLine(self, 1, closure);
}
Iterates through this file line by line. Each line is passed to the
given 1 or 2 arg closure. The file is read using a reader which
is closed before this method returns. |
public static Object eachLine(InputStream stream,
Closure closure) throws IOException {
return eachLine(stream, 1, closure);
}
Iterates through this stream, passing each line to the given 1 or 2 arg closure.
The stream is closed before this method returns. |
public static Object eachLine(URL url,
Closure closure) throws IOException {
return eachLine(url, 1, closure);
}
Iterates through the lines read from the URL's associated input stream passing each
line to the given 1 or 2 arg closure. The stream is closed before this method returns. |
public static Object eachLine(Reader self,
Closure closure) throws IOException {
return eachLine(self, 1, closure);
}
Iterates through the given reader line by line. Each line is passed to the
given 1 or 2 arg closure. If the closure has two arguments, the line count is passed
as the second argument. The Reader is closed before this method returns. |
public static Object eachLine(String self,
int firstLine,
Closure closure) throws IOException {
int count = firstLine;
String line = null;
for (Object o : readLines(self)) {
line = (String) o;
callClosureForLine(closure, line, count);
count++;
}
return line;
}
Iterates through this String line by line. Each line is passed
to the given 1 or 2 arg closure. If a 2 arg closure is found
the line count is passed as the second argument. |
public static Object eachLine(File self,
int firstLine,
Closure closure) throws IOException {
return eachLine(newReader(self), firstLine, closure);
}
Iterates through this file line by line. Each line is passed
to the given 1 or 2 arg closure. The file is read using a reader
which is closed before this method returns. |
public static Object eachLine(InputStream stream,
String charset,
Closure closure) throws IOException {
return eachLine(stream, charset, 1, closure);
}
Iterates through this stream reading with the provided charset, passing each line to the
given 1 or 2 arg closure. The stream is closed before this method returns. |
public static Object eachLine(InputStream stream,
int firstLine,
Closure closure) throws IOException {
return eachLine(new InputStreamReader(stream), firstLine, closure);
}
Iterates through this stream, passing each line to the given 1 or 2 arg closure.
The stream is closed before this method returns. |
public static Object eachLine(URL url,
int firstLine,
Closure closure) throws IOException {
return eachLine(url.openConnection().getInputStream(), firstLine, closure);
}
Iterates through the lines read from the URL's associated input stream passing each
line to the given 1 or 2 arg closure. The stream is closed before this method returns. |
public static Object eachLine(URL url,
String charset,
Closure closure) throws IOException {
return eachLine(url, charset, 1, closure);
}
Iterates through the lines read from the URL's associated input stream passing each
line to the given 1 or 2 arg closure. The stream is closed before this method returns. |
public static Object eachLine(Reader self,
int firstLine,
Closure closure) throws IOException {
BufferedReader br;
int count = firstLine;
Object result = null;
if (self instanceof BufferedReader)
br = (BufferedReader) self;
else
br = new BufferedReader(self);
try {
while (true) {
String line = br.readLine();
if (line == null) {
break;
} else {
result = callClosureForLine(closure, line, count);
count++;
}
}
Reader temp = self;
self = null;
temp.close();
return result;
} finally {
closeWithWarning(self);
closeWithWarning(br);
}
}
Iterates through the given reader line by line. Each line is passed to the
given 1 or 2 arg closure. If the closure has two arguments, the line count is passed
as the second argument. The Reader is closed before this method returns. |
public static Object eachLine(InputStream stream,
String charset,
int firstLine,
Closure closure) throws IOException {
return eachLine(new InputStreamReader(stream, charset), firstLine, closure);
}
Iterates through this stream reading with the provided charset, passing each line to
the given 1 or 2 arg closure. The stream is closed after this method returns. |
public static Object eachLine(URL url,
String charset,
int firstLine,
Closure closure) throws IOException {
return eachLine(new InputStreamReader(url.openConnection().getInputStream(), charset), firstLine, closure);
}
Iterates through the lines read from the URL's associated input stream passing each
line to the given 1 or 2 arg closure. The stream is closed before this method returns. |
public static String eachMatch(String self,
String regex,
Closure closure) {
return eachMatch(self, Pattern.compile(regex), closure);
}
Process each regex group matched substring of the given string. If the closure
parameter takes one argument, an array with all match groups is passed to it.
If the closure takes as many arguments as there are match groups, then each
parameter will be one match group. |
public static String eachMatch(String self,
Pattern pattern,
Closure closure) {
Matcher m = pattern.matcher(self);
each(m, closure);
return self;
}
Process each regex group matched substring of the given pattern. If the closure
parameter takes one argument, an array with all match groups is passed to it.
If the closure takes as many arguments as there are match groups, then each
parameter will be one match group. |
public static void eachObject(File self,
Closure closure) throws IOException, ClassNotFoundException {
eachObject(newObjectInputStream(self), closure);
}
Iterates through the given file object by object. |
public static void eachObject(ObjectInputStream ois,
Closure closure) throws IOException, ClassNotFoundException {
try {
while (true) {
try {
Object obj = ois.readObject();
// we allow null objects in the object stream
closure.call(obj);
} catch (EOFException e) {
break;
}
}
InputStream temp = ois;
ois = null;
temp.close();
} finally {
closeWithWarning(ois);
}
}
Iterates through the given object stream object by object. The
ObjectInputStream is closed afterwards. |
public static Iterator<T> eachPermutation(Collection<T> self,
Closure closure) {
Iterator< List< T > > generator = new PermutationGenerator< T >(self);
while (generator.hasNext()) {
closure.call(generator.next());
}
return generator;
}
Iterates over all permutations of a collection, running a closure for each iteration.
E.g. [1, 2, 3].eachPermutation{ println it } would print:
[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
[2, 3, 1]
[3, 1, 2]
[3, 2, 1] |
public static Object eachWithIndex(Object self,
Closure closure) {
int counter = 0;
for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext();) {
closure.call(new Object[]{iter.next(), counter++});
}
return self;
}
Iterates through an aggregate type or data structure,
passing each item and the item's index (a counter starting at
zero) to the given closure. |
public static Map<K, V> eachWithIndex(Map<K, V> self,
Closure closure) {
int counter = 0;
for (Map.Entry entry : self.entrySet()) {
callClosureForMapEntryAndCounter(closure, entry, counter++);
}
return self;
}
Allows a Map to be iterated through using a closure. If the
closure takes two parameters then it will be passed the Map.Entry and
the item's index (a counter starting at zero) otherwise if the closure
takes three parameters then it will be passed the key, the value, and
the index. |
public static Writable encodeBase64(Byte[] data) {
return encodeBase64(DefaultTypeTransformation.convertToByteArray(data), false);
}
Produce a Writable object which writes the Base64 encoding of the byte array.
Calling toString() on the result returns the encoding as a String. For more
information on Base64 encoding and chunking see RFC 4648 . |
public static Writable encodeBase64(byte[] data) {
return encodeBase64(data, false);
}
Produce a Writable object which writes the Base64 encoding of the byte array.
Calling toString() on the result returns the encoding as a String. For more
information on Base64 encoding and chunking see RFC 4648 . |
public static Writable encodeBase64(Byte[] data,
boolean chunked) {
return encodeBase64(DefaultTypeTransformation.convertToByteArray(data), chunked);
}
Produce a Writable object which writes the Base64 encoding of the byte array.
Calling toString() on the result returns the encoding as a String. For more
information on Base64 encoding and chunking see RFC 4648 . |
public static Writable encodeBase64(byte[] data,
boolean chunked) {
return new Writable() {
public Writer writeTo(final Writer writer) throws IOException {
int charCount = 0;
final int dLimit = (data.length / 3) * 3;
for (int dIndex = 0; dIndex != dLimit; dIndex += 3) {
int d = ((data[dIndex] & 0XFF) < < 16) | ((data[dIndex + 1] & 0XFF) < < 8) | (data[dIndex + 2] & 0XFF);
writer.write(T_TABLE[d > > 18]);
writer.write(T_TABLE[(d > > 12) & 0X3F]);
writer.write(T_TABLE[(d > > 6) & 0X3F]);
writer.write(T_TABLE[d & 0X3F]);
if (chunked && ++charCount == 19) {
writer.write(CHUNK_SEPARATOR);
charCount = 0;
}
}
if (dLimit != data.length) {
int d = (data[dLimit] & 0XFF) < < 16;
if (dLimit + 1 != data.length) {
d |= (data[dLimit + 1] & 0XFF) < < 8;
}
writer.write(T_TABLE[d > > 18]);
writer.write(T_TABLE[(d > > 12) & 0X3F]);
writer.write((dLimit + 1 < data.length) ? T_TABLE[(d > > 6) & 0X3F] : '=');
writer.write('=');
if (chunked && charCount != 0) {
writer.write(CHUNK_SEPARATOR);
}
}
return writer;
}
public String toString() {
StringWriter buffer = new StringWriter();
try {
writeTo(buffer);
} catch (IOException e) {
throw new StringWriterIOException(e);
}
return buffer.toString();
}
};
}
Produce a Writable object which writes the Base64 encoding of the byte array.
Calling toString() on the result returns the encoding as a String. For more
information on Base64 encoding and chunking see RFC 4648 . |
public static boolean equals(int[] left,
int[] right) {
if (left == null) {
return right == null;
}
if (right == null) {
return false;
}
if (left.length != right.length) {
return false;
}
for (int i = 0; i < left.length; i++) {
if (left[i] != right[i]) return false;
}
return true;
}
Compare the contents of this array to the contents of the given array. |
public static boolean equals(Object[] left,
List right) {
return coercedEquals(left, right);
}
Determines if the contents of this array are equal to the
contents of the given list, in the same order. This returns
false if either collection is null . |
public static boolean equals(List left,
Object[] right) {
return coercedEquals(right, left);
}
Determines if the contents of this list are equal to the
contents of the given array in the same order. This returns
false if either collection is null . |
public static boolean equals(List left,
List right) {
if (left == null) {
return right == null;
}
if (right == null) {
return false;
}
if (left.size() != right.size()) {
return false;
}
final NumberAwareComparator numberAwareComparator = new NumberAwareComparator();
final Iterator it1 = left.iterator(), it2 = right.iterator();
while (it1.hasNext()) {
final Object o1 = it1.next();
final Object o2 = it2.next();
if (o1 == null) {
if (o2 != null) return false;
} else {
if (o1 instanceof Number) {
if (!(o2 instanceof Number && numberAwareComparator.compare(o1, o2) == 0)) {
return false;
}
} else {
if (!DefaultTypeTransformation.compareEqual(o1, o2)) return false;
}
}
}
return true;
}
Compare the contents of two Lists. Order matters.
If numbers exist in the Lists, then they are compared as numbers,
for example 2 == 2L. If either list is null , the result
is false . |
public static boolean every(Object self) {
for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext();) {
if (!DefaultTypeTransformation.castToBoolean(iter.next())) {
return false;
}
}
return true;
}
Iterates over every element of a collection, and checks whether all
elements are true according to the Groovy Truth.
Equivalent to self.every({element -> element}) |
public static boolean every(Object self,
Closure closure) {
for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext();) {
if (!DefaultTypeTransformation.castToBoolean(closure.call(iter.next()))) {
return false;
}
}
return true;
}
Used to determine if the given predicate closure is valid (i.e.&nsbp;returns
true for all items in this data structure).
A simple example for a list:
def list = [3,4,5]
def greaterThanTwo = list.every { it > 2 }
|
public static boolean every(Map<K, V> self,
Closure closure) {
for (Map.Entry entry : self.entrySet()) {
if (!DefaultTypeTransformation.castToBoolean(callClosureForMapEntry(closure, entry))) {
return false;
}
}
return true;
}
Iterates over the entries of a map, and checks whether a predicate is
valid for all entries. If the
closure takes one parameter then it will be passed the Map.Entry
otherwise if the closure takes two parameters then it will be
passed the key and the value. |
public static Process execute(String self) throws IOException {
return Runtime.getRuntime().exec(self);
}
Executes the given string as a command line process. For more control
over the process mechanism in JDK 1.5 you can use java.lang.ProcessBuilder. |
public static Process execute(String[] commandArray) throws IOException {
return Runtime.getRuntime().exec(commandArray);
}
Executes the command specified by the String array that is the parameter.
The first item in the array is the command the others are the parameters. For more
control over the process mechanism in JDK 1.5 you can use
java.lang.ProcessBuilder . |
public static Process execute(List commandList) throws IOException {
final String[] commandArray = new String[commandList.size()];
Iterator it = commandList.iterator();
for (int i = 0; it.hasNext(); ++i) {
commandArray[i] = it.next().toString();
}
return execute(commandArray);
}
Executes the command specified by the String list that is the parameter.
The first item in the array is the command the others are the parameters. All entries
must be String s. For more control over the process mechanism in JDK 1.5 you
can use java.lang.ProcessBuilder . |
public static Process execute(String self,
String[] envp,
File dir) throws IOException {
return Runtime.getRuntime().exec(self, envp, dir);
}
Executes the command specified by the self with environments envp
under the working directory dir .
For more control over the process mechanism in JDK 1.5 you can use java.lang.ProcessBuilder . |
public static Process execute(String self,
List envp,
File dir) throws IOException {
if (envp == null) {
return execute(self, (String[]) null, dir);
}
String[] commandArray = new String[envp.size()];
Iterator it = envp.iterator();
for (int i = 0; it.hasNext(); ++i) {
commandArray[i] = it.next().toString();
}
return execute(self, commandArray, dir);
}
Executes the command specified by the self with environments envp
under the working directory dir .
For more control over the process mechanism in JDK 1.5 you can use java.lang.ProcessBuilder . |
public static Writable filterLine(File self,
Closure closure) throws IOException {
return filterLine(newReader(self), closure);
}
Filters the lines of a File and creates a Writeable in return to
stream the filtered lines. |
public static Writable filterLine(Reader reader,
Closure closure) {
final BufferedReader br = new BufferedReader(reader);
return new Writable() {
public Writer writeTo(Writer out) throws IOException {
BufferedWriter bw = new BufferedWriter(out);
String line;
while ((line = br.readLine()) != null) {
if (DefaultTypeTransformation.castToBoolean(closure.call(line))) {
bw.write(line);
bw.newLine();
}
}
bw.flush();
return out;
}
public String toString() {
StringWriter buffer = new StringWriter();
try {
writeTo(buffer);
} catch (IOException e) {
throw new StringWriterIOException(e);
}
return buffer.toString();
}
};
}
Filter the lines from this Reader, and return a Writable which can be
used to stream the filtered lines to a destination. The closure should
return true if the line should be passed to the writer. |
public static Writable filterLine(InputStream self,
Closure predicate) {
return filterLine(newReader(self), predicate);
}
Filter lines from an input stream using a closure predicate. The closure
will be passed each line as a String, and it should return
true if the line should be passed to the writer. |
public static void filterLine(Reader reader,
Writer writer,
Closure closure) throws IOException {
BufferedReader br = new BufferedReader(reader);
BufferedWriter bw = new BufferedWriter(writer);
String line;
try {
while ((line = br.readLine()) != null) {
if (DefaultTypeTransformation.castToBoolean(closure.call(line))) {
bw.write(line);
bw.newLine();
}
}
bw.flush();
Writer temp2 = writer;
writer = null;
temp2.close();
Reader temp1 = reader;
reader = null;
temp1.close();
} finally {
closeWithWarning(br);
closeWithWarning(reader);
closeWithWarning(bw);
closeWithWarning(writer);
}
}
Filter the lines from a reader and write them on the writer,
according to a closure which returns true if the line should be included.
Both Reader and Writer are closed after the operation. |
public static void filterLine(File self,
Writer writer,
Closure closure) throws IOException {
filterLine(newReader(self), writer, closure);
}
Filter the lines from this File, and write them to the given writer based
on the given closure predicate. |
public static void filterLine(InputStream self,
Writer writer,
Closure predicate) throws IOException {
filterLine(newReader(self), writer, predicate);
}
Uses a closure to filter lines from this InputStream and pass them to
the given writer. The closure will be passed each line as a String, and
it should return true if the line should be passed to the
writer. |
public static Object find(Object self,
Closure closure) {
for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext();) {
Object value = iter.next();
if (DefaultTypeTransformation.castToBoolean(closure.call(value))) {
return value;
}
}
return null;
}
Finds the first value matching the closure condition |
public static T find(Collection<T> self,
Closure closure) {
for (T value : self) {
if (DefaultTypeTransformation.castToBoolean(closure.call(value))) {
return value;
}
}
return null;
}
Finds the first value matching the closure condition. Example:
def list = [1,2,3]
list.find { it > 1 } // returns 2
|
public static Entry<K, V> find(Map<K, V> self,
Closure closure) {
for (Map.Entry< K, V > entry : self.entrySet()) {
if (DefaultTypeTransformation.castToBoolean(callClosureForMapEntry(closure, entry))) {
return entry;
}
}
return null;
}
Finds the first entry matching the closure condition. If the closure takes
two parameters, the entry key and value are passed. If the closure takes
one parameter, the Map.Entry object is passed. |
public static String find(String self,
String regex) {
return find(self, Pattern.compile(regex));
}
Finds the first occurrence of a regular expression String within a String.
If the regex doesn't match, null will be returned.
For example, if the regex doesn't match the result is null:
assert null == "New York, NY".find(/\d{5}/)
If it does match, we get the matching string back:
assert "10292" == "New York, NY 10292-0098".find(/\d{5}/)
If we have capture groups in our expression, we still get back the full match
assert "10292-0098" == "New York, NY 10292-0098".find(/(\d{5})-?(\d{4})/)
|
public static String find(String self,
Pattern pattern) {
Matcher matcher = pattern.matcher(self);
if (matcher.find()) {
return matcher.group(0);
}
return null;
}
Finds the first occurrence of a compiled regular expression Pattern within a String.
If the pattern doesn't match, null will be returned.
For example, if the pattern doesn't match the result is null:
assert null == "New York, NY".find(~/\d{5}/)
If it does match, we get the matching string back:
assert "10292" == "New York, NY 10292-0098".find(~/\d{5}/)
If we have capture groups in our expression, the groups are ignored and
we get back the full match:
assert "10292-0098" == "New York, NY 10292-0098".find(~/(\d{5})-?(\d{4})/)
If you need to work with capture groups, then use the closure version
of this method or use Groovy's matcher operators or use eachMatch.
|
public static String find(String self,
String regex,
Closure closure) {
return find(self, Pattern.compile(regex), closure);
}
Finds the first occurrence of a regular expression String within a String.
If the regex doesn't match, the closure will not be called and find will return null.
For example, if the regex doesn't match, the result is null:
assert null == "New York, NY".find(~/\d{5}/) { match -> return "-$match-"}
If it does match and we don't have any capture groups in our regex, there is a single parameter
on the closure that the match gets passed to:
assert "-10292-" == "New York, NY 10292-0098".find(~/\d{5}/) { match -> return "-$match-"}
If we have capture groups in our expression, our closure has one parameter for the match, followed by
one for each of the capture groups:
assert "10292" == "New York, NY 10292-0098".find(~/(\d{5})-?(\d{4})/) { match, zip, plusFour ->
assert match == "10292-0098"
assert zip == "10292"
assert plusFour == "0098"
return zip
}
If we have capture groups in our expression, and our closure has one parameter,
the closure will be passed an array with the first element corresponding to the whole match,
followed by an element for each of the capture groups:
assert "10292" == "New York, NY 10292-0098".find(~/(\d{5})-?(\d{4})/) { match, zip, plusFour ->
assert array[0] == "10292-0098"
assert array[1] == "10292"
assert array[2] == "0098"
return array[1]
}
If a capture group is optional, and doesn't match, then the corresponding value
for that capture group passed to the closure will be null as illustrated here:
assert "2339999" == "adsf 233-9999 adsf".find(~/(\d{3})?-?(\d{3})-(\d{4})/) { match, areaCode, exchange, stationNumber ->
assert "233-9999" == match
assert null == areaCode
assert "233" == exchange
assert "9999" == stationNumber
return "$exchange$stationNumber"
}
|
public static String find(String self,
Pattern pattern,
Closure closure) {
Matcher matcher = pattern.matcher(self);
if (matcher.find()) {
if (hasGroup(matcher)) {
int count = matcher.groupCount();
List groups = new ArrayList(count);
for (int i = 0; i < = count; i++) {
groups.add(matcher.group(i));
}
return InvokerHelper.toString(closure.call(groups));
} else {
return InvokerHelper.toString(closure.call(matcher.group(0)));
}
}
return null;
}
Finds the first occurrence of a compiled regular expression Pattern within a String.
If the pattern doesn't match, the closure will not be called and find will return null.
For example, if the pattern doesn't match, the result is null:
assert null == "New York, NY".find(~/\d{5}/) { match -> return "-$match-"}
If it does match and we don't have any capture groups in our regex, there is a single parameter
on the closure that the match gets passed to:
assert "-10292-" == "New York, NY 10292-0098".find(~/\d{5}/) { match -> return "-$match-"}
If we have capture groups in our expression, our closure has one parameter for the match, followed by
one for each of the capture groups:
assert "10292" == "New York, NY 10292-0098".find(~/(\d{5})-?(\d{4})/) { match, zip, plusFour ->
assert match == "10292-0098"
assert zip == "10292"
assert plusFour == "0098"
return zip
}
If we have capture groups in our expression, and our closure has one parameter,
the closure will be passed an array with the first element corresponding to the whole match,
followed by an element for each of the capture groups:
assert "10292" == "New York, NY 10292-0098".find(~/(\d{5})-?(\d{4})/) { match, zip, plusFour ->
assert array[0] == "10292-0098"
assert array[1] == "10292"
assert array[2] == "0098"
return array[1]
}
If a capture group is optional, and doesn't match, then the corresponding value
for that capture group passed to the closure will be null as illustrated here:
assert "2339999" == "adsf 233-9999 adsf".find(~/(\d{3})?-?(\d{3})-(\d{4})/) { match, areaCode, exchange, stationNumber ->
assert "233-9999" == match
assert null == areaCode
assert "233" == exchange
assert "9999" == stationNumber
return "$exchange$stationNumber"
}
|
public static Collection<T> findAll(Collection<T> self,
Closure closure) {
Collection< T > answer = createSimilarCollection(self);
Iterator< T > iter = self.iterator();
return findAll(closure, answer, iter);
}
Finds all values matching the closure condition. |
public static Collection findAll(Object self,
Closure closure) {
List answer = new ArrayList();
Iterator iter = InvokerHelper.asIterator(self);
return findAll(closure, answer, iter);
}
Finds all items matching the closure condition. |
public static Map<K, V> findAll(Map<K, V> self,
Closure closure) {
Map< K, V > answer = createSimilarMap(self);
for (Map.Entry< K, V > entry : self.entrySet()) {
if (DefaultTypeTransformation.castToBoolean(callClosureForMapEntry(closure, entry))) {
answer.put(entry.getKey(), entry.getValue());
}
}
return answer;
}
Finds all entries matching the closure condition. If the
closure takes one parameter then it will be passed the Map.Entry.
Otherwise if the closure should take two parameters, which will be
the key and the value.
If the self map is one of TreeMap, LinkedHashMap, Hashtable
or Properties, the returned Map will preserve that type, otherwise a HashMap will
be returned. |
public static List findAll(String self,
String regex) {
return findAll(self, Pattern.compile(regex));
}
Finds all occurrences of a regular expression string within a String. A List is returned containing all full matches or
an empty list if there are no matches within the string.
For example, if the regex doesn't match, it returns an empty list:
assert [] == "foo".findAll(/(\w*) Fish/)
Any regular expression matches are returned in a list, and all regex capture groupings are ignored, only the full match is returned:
def expected = ["One Fish", "Two Fish", "Red Fish", "Blue Fish"]
assert expected == "One Fish, Two Fish, Red Fish, Blue Fish".findAll(/(\w*) Fish/)
If you need to work with capture groups, then use the closure version
of this method or use Groovy's matcher operators or use eachMatch.
|
public static List findAll(String self,
Pattern pattern) {
Matcher matcher = pattern.matcher(self);
List list = new ArrayList();
for (Iterator iter = iterator(matcher); iter.hasNext();) {
if (hasGroup(matcher)) {
list.add(((List) iter.next()).get(0));
} else {
list.add(iter.next());
}
}
return list;
}
Finds all occurrences of a regular expression Pattern within a String. A List is returned containing all full matches or
an empty list if there are no matches within the string.
For example, if the pattern doesn't match, it returns an empty list:
assert [] == "foo".findAll(~/(\w*) Fish/)
Any regular expression matches are returned in a list, and all regex capture groupings are ignored, only the full match is returned:
def expected = ["One Fish", "Two Fish", "Red Fish", "Blue Fish"]
assert expected == "One Fish, Two Fish, Red Fish, Blue Fish".findAll(~/(\w*) Fish/)
|
public static List findAll(String self,
String regex,
Closure closure) {
return findAll(self, Pattern.compile(regex), closure);
}
Finds all occurrences of a regular expression string within a String. Any matches are passed to the specified closure. The closure
is expected to have the full match in the first parameter. If there are any capture groups, they will be placed in subsequent parameters.
If there are no matches, the closure will not be called, and an empty List will be returned.
For example, if the regex doesn't match, it returns an empty list:
assert [] == "foo".findAll(/(\w*) Fish/) { match, firstWord -> return firstWord }
Any regular expression matches are passed to the closure, if there are no capture groups, there will be one parameter for the match:
assert ["couldn't", "wouldn't"] == "I could not, would not, with a fox.".findAll(/.ould/) { match -> "${match}n't"}
If there are capture groups, the first parameter will be the match followed by one parameter for each capture group:
def orig = "There's a Wocket in my Pocket"
assert ["W > Wocket", "P > Pocket"] == orig.findAll(/(.)ocket/) { match, firstLetter -> "$firstLetter > $match" }
|
public static List findAll(String self,
Pattern pattern,
Closure closure) {
Matcher matcher = pattern.matcher(self);
return collect(matcher, closure);
}
Finds all occurrences of a compiled regular expression Pattern within a String. Any matches are passed to the specified closure. The closure
is expected to have the full match in the first parameter. If there are any capture groups, they will be placed in subsequent parameters.
If there are no matches, the closure will not be called, and an empty List will be returned.
For example, if the pattern doesn't match, it returns an empty list:
assert [] == "foo".findAll(~/(\w*) Fish/) { match, firstWord -> return firstWord }
Any regular expression matches are passed to the closure, if there are no capture groups, there will be one parameter for the match:
assert ["couldn't", "wouldn't"] == "I could not, would not, with a fox.".findAll(~/.ould/) { match -> "${match}n't"}
If there are capture groups, the first parameter will be the match followed by one parameter for each capture group:
def orig = "There's a Wocket in my Pocket"
assert ["W > Wocket", "P > Pocket"] == orig.findAll(~/(.)ocket/) { match, firstLetter -> "$firstLetter > $match" }
|
public static int findIndexOf(Object self,
Closure closure) {
return findIndexOf(self, 0, closure);
}
Iterates over the elements of an iterable collection of items and returns
the index of the first item that matches the condition specified in the closure. |
public static int findIndexOf(Object self,
int startIndex,
Closure closure) {
int result = -1;
int i = 0;
for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext(); i++) {
Object value = iter.next();
if (i < startIndex) {
continue;
}
if (DefaultTypeTransformation.castToBoolean(closure.call(value))) {
result = i;
break;
}
}
return result;
}
Iterates over the elements of an iterable collection of items, starting from a
specified startIndex, and returns the index of the first item that matches the
condition specified in the closure. |
public static List<Number> findIndexValues(Object self,
Closure closure) {
return findIndexValues(self, 0, closure);
}
Iterates over the elements of an iterable collection of items and returns
the index values of the items that match the condition specified in the closure. |
public static List<Number> findIndexValues(Object self,
Number startIndex,
Closure closure) {
List< Number > result = new ArrayList< Number >();
long count = 0;
long startCount = startIndex.longValue();
for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext(); count++) {
Object value = iter.next();
if (count < startCount) {
continue;
}
if (DefaultTypeTransformation.castToBoolean(closure.call(value))) {
result.add(count);
}
}
return result;
}
Iterates over the elements of an iterable collection of items, starting from
a specified startIndex, and returns the index values of the items that match
the condition specified in the closure. |
public static int findLastIndexOf(Object self,
Closure closure) {
return findLastIndexOf(self, 0, closure);
}
Iterates over the elements of an iterable collection of items and returns
the index of the last item that matches the condition specified in the closure. |
public static int findLastIndexOf(Object self,
int startIndex,
Closure closure) {
int result = -1;
int i = 0;
for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext(); i++) {
Object value = iter.next();
if (i < startIndex) {
continue;
}
if (DefaultTypeTransformation.castToBoolean(closure.call(value))) {
result = i;
}
}
return result;
}
Iterates over the elements of an iterable collection of items, starting
from a specified startIndex, and returns the index of the last item that
matches the condition specified in the closure. |
public static T first(List<T> self) {
if (self.isEmpty()) {
throw new NoSuchElementException("Cannot access first() element from an empty List");
}
return self.get(0);
}
Returns the first item from the List. |
public static Collection flatten(Collection self) {
return flatten(self, createSimilarCollection(self));
}
Flatten a collection. This collection and any nested arrays or
collections have their contents (recursively) added to the new collection. |
public static Collection flatten(Object[] self) {
return flatten(toList(self), new ArrayList());
}
Flatten an array. This array and any nested arrays or
collections have their contents (recursively) added to the new collection. |
public static Collection flatten(boolean[] self) {
return flatten(toList(self), new ArrayList());
}
Flatten an array. This array and any nested arrays or
collections have their contents (recursively) added to the new collection. |
public static Collection flatten(byte[] self) {
return flatten(toList(self), new ArrayList());
}
Flatten an array. This array and any nested arrays or
collections have their contents (recursively) added to the new collection. |
public static Collection flatten(char[] self) {
return flatten(toList(self), new ArrayList());
}
Flatten an array. This array and any nested arrays or
collections have their contents (recursively) added to the new collection. |
public static Collection flatten(short[] self) {
return flatten(toList(self), new ArrayList());
}
Flatten an array. This array and any nested arrays or
collections have their contents (recursively) added to the new collection. |
public static Collection flatten(int[] self) {
return flatten(toList(self), new ArrayList());
}
Flatten an array. This array and any nested arrays or
collections have their contents (recursively) added to the new collection. |
public static Collection flatten(long[] self) {
return flatten(toList(self), new ArrayList());
}
Flatten an array. This array and any nested arrays or
collections have their contents (recursively) added to the new collection. |
public static Collection flatten(float[] self) {
return flatten(toList(self), new ArrayList());
}
Flatten an array. This array and any nested arrays or
collections have their contents (recursively) added to the new collection. |
public static Collection flatten(double[] self) {
return flatten(toList(self), new ArrayList());
}
Flatten an array. This array and any nested arrays or
collections have their contents (recursively) added to the new collection. |
public static Collection flatten(Collection self,
Closure flattenUsing) {
return flatten(self, createSimilarCollection(self), flattenUsing);
}
Flatten a collection. This collection and any nested arrays or
collections have their contents (recursively) added to the new collection.
For any non-Array, non-Collection object which represents some sort
of collective type, the supplied closure should yield the contained items;
otherwise, the closure should just return any element which corresponds to a leaf. |
public static String format(Date self,
String format) {
return new SimpleDateFormat( format ).format( self );
}
Create a String representation of this date according to the given
format pattern.
For example, if the system timezone is GMT,
new Date(0).format('MM/dd/yy') would return the string
"01/01/70" . See documentation for SimpleDateFormat
for format pattern use.
Note that a new DateFormat instance is created for every
invocation of this method (for thread safety).
|
public static String format(Calendar self,
String pattern) {
SimpleDateFormat sdf = new SimpleDateFormat( pattern );
sdf.setTimeZone( self.getTimeZone() );
return sdf.format( self.getTime() );
}
Shortcut for SimpleDateFormat to output a String representation
of this calendar instance. This method respects the Calendar's assigned
TimeZone , whereas calling cal.time.format('HH:mm:ss')
would use the system timezone.
Note that Calendar equivalents of date.getDateString()
and variants do not exist because those methods are Locale-dependent.
Although a Calendar may be assigned a Locale , that information is
lost and therefore cannot be used to control the default date/time formats
provided by these methods. Instead, the system Locale would always be
used. The alternative is to simply call
DateFormat#getDateInstance(int, Locale) and pass the same Locale
that was used for the Calendar.
|
public static V get(Map<K, V> map,
K key,
V defaultValue) {
if (!map.containsKey(key)) {
map.put(key, defaultValue);
}
return map.get(key);
}
Looks up an item in a Map for the given key and returns the value - unless
there is no entry for the given key in which case add the default value
to the map and return that. |
public static Object getAt(Object self,
String property) {
return InvokerHelper.getProperty(self, property);
}
Allows the subscript operator to be used to lookup dynamic property values.
bean[somePropertyNameExpression] . The normal property notation
of groovy is neater and more concise but only works with compile-time known
property names. |
public static CharSequence getAt(CharSequence text,
int index) {
index = normaliseIndex(index, text.length());
return text.subSequence(index, index + 1);
}
Support the subscript operator for CharSequence. |
public static String getAt(String text,
int index) {
index = normaliseIndex(index, text.length());
return text.substring(index, index + 1);
}
Support the subscript operator for String. |
public static CharSequence getAt(CharSequence text,
Range range) {
int from = normaliseIndex(DefaultTypeTransformation.intUnbox(range.getFrom()), text.length());
int to = normaliseIndex(DefaultTypeTransformation.intUnbox(range.getTo()), text.length());
boolean reverse = range.isReverse();
// If this is a backwards range, reverse the arguments to substring.
if (from > to) {
int tmp = from;
from = to;
to = tmp;
reverse = !reverse;
}
CharSequence sequence = text.subSequence(from, to + 1);
return reverse ? reverse((String) sequence) : sequence;
}
Support the range subscript operator for CharSequence |
public static CharSequence getAt(CharSequence text,
IntRange range) {
return getAt(text, (Range) range);
}
Support the range subscript operator for CharSequence or StringBuffer with IntRange |
public static CharSequence getAt(CharSequence text,
EmptyRange range) {
return "";
}
Support the range subscript operator for CharSequence or StringBuffer with EmptyRange |
public static String getAt(String text,
IntRange range) {
return getAt(text, (Range) range);
}
Support the range subscript operator for String with IntRange |
public static String getAt(String text,
EmptyRange range) {
return "";
}
Support the range subscript operator for String with EmptyRange |
public static String getAt(String text,
Range range) {
int from = normaliseIndex(DefaultTypeTransformation.intUnbox(range.getFrom()), text.length());
int to = normaliseIndex(DefaultTypeTransformation.intUnbox(range.getTo()), text.length());
// If this is a backwards range, reverse the arguments to substring.
boolean reverse = range.isReverse();
if (from > to) {
int tmp = to;
to = from;
from = tmp;
reverse = !reverse;
}
String answer = text.substring(from, to + 1);
if (reverse) {
answer = reverse(answer);
}
return answer;
}
Support the range subscript operator for String |
public static Object getAt(Matcher matcher,
int idx) {
try {
int count = getCount(matcher);
if (idx < -count || idx >= count) {
throw new IndexOutOfBoundsException("index is out of range " + (-count) + ".." + (count - 1) + " (index = " + idx + ")");
}
idx = normaliseIndex(idx, count);
Iterator iter = iterator(matcher);
Object result = null;
for (int i = 0; i < = idx; i++) {
result = iter.next();
}
return result;
}
catch (IllegalStateException ex) {
return null;
}
}
Support the subscript operator, e.g. matcher[index], for a regex Matcher.
For an example using no group match,
def p = /ab[d|f]/
def m = "abcabdabeabf" =~ p
assert 2 == m.count
assert 2 == m.size() // synonym for m.getCount()
assert ! m.hasGroup()
assert 0 == m.groupCount()
def matches = ["abd", "abf"]
for (i in 0..<m.count) {
assert m[i] == matches[i]
}
For an example using group matches,
def p = /(?:ab([c|d|e|f]))/
def m = "abcabdabeabf" =~ p
assert 4 == m.count
assert m.hasGroup()
assert 1 == m.groupCount()
def matches = [["abc", "c"], ["abd", "d"], ["abe", "e"], ["abf", "f"]]
for (i in 0..<m.count) {
assert m[i] == matches[i]
}
For another example using group matches,
def m = "abcabdabeabfabxyzabx" =~ /(?:ab([d|x-z]+))/
assert 3 == m.count
assert m.hasGroup()
assert 1 == m.groupCount()
def matches = [["abd", "d"], ["abxyz", "xyz"], ["abx", "x"]]
for (i in 0..<m.count) {
assert m[i] == matches[i]
}
|
public static List<T> getAt(List<T> self,
Range range) {
RangeInfo info = subListBorders(self.size(), range);
List< T > answer = self.subList(info.from, info.to); // sublist is always exclusive, but Ranges are not
if (info.reverse) {
answer = reverse(answer);
}
return answer;
}
Support the range subscript operator for a List |
public static List<T> getAt(List<T> self,
EmptyRange range) {
return new ArrayList< T > ();
}
Support the range subscript operator for a List |
public static List<T> getAt(List<T> self,
Collection indices) {
List< T > answer = new ArrayList< T >(indices.size());
for (Object value : indices) {
if (value instanceof Range) {
answer.addAll(getAt(self, (Range) value));
} else if (value instanceof List) {
answer.addAll(getAt(self, (List) value));
} else {
int idx = DefaultTypeTransformation.intUnbox(value);
answer.add(getAt(self, idx));
}
}
return answer;
}
Select a List of items from a List using a Collection to
identify the indices to be selected. |
public static List<T> getAt(T[] self,
Collection indices) {
List< T > answer = new ArrayList< T >(indices.size());
for (Object value : indices) {
if (value instanceof Range) {
answer.addAll(getAt(self, (Range) value));
} else if (value instanceof Collection) {
answer.addAll(getAt(self, (Collection) value));
} else {
int idx = DefaultTypeTransformation.intUnbox(value);
answer.add(getAtImpl(self, idx));
}
}
return answer;
}
Select a List of items from an Object array using a Collection to
identify the indices to be selected. |
public static CharSequence getAt(CharSequence self,
Collection indices) {
StringBuilder answer = new StringBuilder();
for (Object value : indices) {
if (value instanceof Range) {
answer.append(getAt(self, (Range) value));
} else if (value instanceof Collection) {
answer.append(getAt(self, (Collection) value));
} else {
int idx = DefaultTypeTransformation.intUnbox(value);
answer.append(getAt(self, idx));
}
}
return answer.toString();
}
Select a List of characters from a CharSequence using a Collection
to identify the indices to be selected. |
public static String getAt(String self,
Collection indices) {
return (String) getAt((CharSequence) self, indices);
}
Select a List of characters from a String using a Collection
to identify the indices to be selected. |
public static List getAt(Matcher self,
Collection indices) {
List result = new ArrayList();
for (Object value : indices) {
if (value instanceof Range) {
result.addAll(getAt(self, (Range) value));
} else {
int idx = DefaultTypeTransformation.intUnbox(value);
result.add(getAt(self, idx));
}
}
return result;
}
Select a List of values from a Matcher using a Collection
to identify the indices to be selected. |
public static List<T> getAt(T[] array,
Range range) {
List< T > list = Arrays.asList(array);
return getAt(list, range);
}
Support the range subscript operator for an Array |
public static List<T> getAt(T[] array,
IntRange range) {
List< T > list = Arrays.asList(array);
return getAt(list, range);
}
|
public static List<T> getAt(T[] array,
EmptyRange range) {
return new ArrayList< T >();
}
|
public static List<T> getAt(T[] array,
ObjectRange range) {
List< T > list = Arrays.asList(array);
return getAt(list, range);
}
|
public static T getAt(List<T> self,
int idx) {
int size = self.size();
int i = normaliseIndex(idx, size);
if (i < size) {
return self.get(i);
} else {
return null;
}
}
Support the subscript operator for a List. |
public static int getAt(Date self,
int field) {
Calendar cal = Calendar.getInstance();
cal.setTime(self);
return cal.get(field);
}
Support the subscript operator for a Date. |
public static V getAt(Map<K, V> self,
K key) {
return self.get(key);
}
Support the subscript operator for a Map. |
public static List getAt(Collection coll,
String property) {
List answer = new ArrayList(coll.size());
for (Object item : coll) {
if (item == null) continue;
Object value;
try {
value = InvokerHelper.getProperty(item, property);
} catch (MissingPropertyExceptionNoStack mpe) {
String causeString = new MissingPropertyException(mpe.getProperty(), mpe.getType()).toString();
throw new MissingPropertyException("Exception evaluating property '" + property +
"' for " + coll.getClass().getName() + ", Reason: " + causeString);
}
answer.add(value);
}
return answer;
}
Support the subscript operator for List |
public static List<Byte> getAt(byte[] array,
Range range) {
return primitiveArrayGet(array, range);
}
Support the subscript operator with a range for a byte array |
public static List<Character> getAt(char[] array,
Range range) {
return primitiveArrayGet(array, range);
}
Support the subscript operator with a range for a char array |
public static List<Short> getAt(short[] array,
Range range) {
return primitiveArrayGet(array, range);
}
Support the subscript operator with a range for a short array |
public static List<Integer> getAt(int[] array,
Range range) {
return primitiveArrayGet(array, range);
}
Support the subscript operator with a range for an int array |
public static List<Long> getAt(long[] array,
Range range) {
return primitiveArrayGet(array, range);
}
Support the subscript operator with a range for a long array |
public static List<Float> getAt(float[] array,
Range range) {
return primitiveArrayGet(array, range);
}
Support the subscript operator with a range for a float array |
public static List<Double> getAt(double[] array,
Range range) {
return primitiveArrayGet(array, range);
}
Support the subscript operator with a range for a double array |
public static List<Boolean> getAt(boolean[] array,
Range range) {
return primitiveArrayGet(array, range);
}
Support the subscript operator with a range for a boolean array |
public static List<Byte> getAt(byte[] array,
IntRange range) {
return primitiveArrayGet(array, range);
}
Support the subscript operator with an IntRange for a byte array |
public static List<Character> getAt(char[] array,
IntRange range) {
return primitiveArrayGet(array, range);
}
Support the subscript operator with an IntRange for a char array |
public static List<Short> getAt(short[] array,
IntRange range) {
return primitiveArrayGet(array, range);
}
Support the subscript operator with an IntRange for a short array |
public static List<Integer> getAt(int[] array,
IntRange range) {
return primitiveArrayGet(array, range);
}
Support the subscript operator with an IntRange for an int array |
public static List<Long> getAt(long[] array,
IntRange range) {
return primitiveArrayGet(array, range);
}
Support the subscript operator with an IntRange for a long array |
public static List<Float> getAt(float[] array,
IntRange range) {
return primitiveArrayGet(array, range);
}
Support the subscript operator with an IntRange for a float array |
public static List<Double> getAt(double[] array,
IntRange range) {
return primitiveArrayGet(array, range);
}
Support the subscript operator with an IntRange for a double array |
public static List<Boolean> getAt(boolean[] array,
IntRange range) {
return primitiveArrayGet(array, range);
}
Support the subscript operator with an IntRange for a boolean array |
public static List<Byte> getAt(byte[] array,
ObjectRange range) {
return primitiveArrayGet(array, range);
}
Support the subscript operator with an ObjectRange for a byte array |
public static List<Character> getAt(char[] array,
ObjectRange range) {
return primitiveArrayGet(array, range);
}
Support the subscript operator with an ObjectRange for a char array |
public static List<Short> getAt(short[] array,
ObjectRange range) {
return primitiveArrayGet(array, range);
}
Support the subscript operator with an ObjectRange for a short array |
public static List<Integer> getAt(int[] array,
ObjectRange range) {
return primitiveArrayGet(array, range);
}
Support the subscript operator with an ObjectRange for an int array |
public static List<Long> getAt(long[] array,
ObjectRange range) {
return primitiveArrayGet(array, range);
}
Support the subscript operator with an ObjectRange for a long array |
public static List<Float> getAt(float[] array,
ObjectRange range) {
return primitiveArrayGet(array, range);
}
Support the subscript operator with an ObjectRange for a float array |
public static List<Double> getAt(double[] array,
ObjectRange range) {
return primitiveArrayGet(array, range);
}
Support the subscript operator with an ObjectRange for a double array |
public static List<Boolean> getAt(boolean[] array,
ObjectRange range) {
return primitiveArrayGet(array, range);
}
Support the subscript operator with an ObjectRange for a byte array |
public static List<Byte> getAt(byte[] array,
Collection indices) {
return primitiveArrayGet(array, indices);
}
Support the subscript operator with a collection for a byte array |
public static List<Character> getAt(char[] array,
Collection indices) {
return primitiveArrayGet(array, indices);
}
Support the subscript operator with a collection for a char array |
public static List<Short> getAt(short[] array,
Collection indices) {
return primitiveArrayGet(array, indices);
}
Support the subscript operator with a collection for a short array |
public static List<Integer> getAt(int[] array,
Collection indices) {
return primitiveArrayGet(array, indices);
}
Support the subscript operator with a collection for an int array |
public static List<Long> getAt(long[] array,
Collection indices) {
return primitiveArrayGet(array, indices);
}
Support the subscript operator with a collection for a long array |
public static List<Float> getAt(float[] array,
Collection indices) {
return primitiveArrayGet(array, indices);
}
Support the subscript operator with a collection for a float array |
public static List<Double> getAt(double[] array,
Collection indices) {
return primitiveArrayGet(array, indices);
}
Support the subscript operator with a collection for a double array |
public static List<Boolean> getAt(boolean[] array,
Collection indices) {
return primitiveArrayGet(array, indices);
}
Support the subscript operator with a collection for a boolean array |
public static boolean getAt(BitSet self,
int index) {
return self.get(index);
}
Support the subscript operator for a Bitset |
public static BitSet getAt(BitSet self,
IntRange range) {
int from = DefaultTypeTransformation.intUnbox(range.getFrom());
int to = DefaultTypeTransformation.intUnbox(range.getTo());
BitSet result = new BitSet();
int numberOfBits = to - from + 1;
int adjuster = 1;
int offset = from;
if (range.isReverse()) {
adjuster = -1;
offset = to;
}
for (int i = 0; i < numberOfBits; i++) {
result.set(i, self.get(offset + (adjuster * i)));
}
return result;
}
Support retrieving a subset of a BitSet using a Range |
public static char[] getChars(String self) {
return self.toCharArray();
}
Converts the given String into an array of characters.
Alias for toCharArray. |
public static int getCount(Matcher matcher) {
int counter = 0;
matcher.reset();
while (matcher.find()) {
counter++;
}
return counter;
}
Find the number of Strings matched to the given Matcher. |
public static String getDateString(Date self) {
return DateFormat.getDateInstance(DateFormat.SHORT).format( self );
}
Return a string representation of the 'day' portion of this date
according to the locale-specific DateFormat#SHORT default format.
For an "en_UK" system locale, this would be dd/MM/yy .
Note that a new DateFormat instance is created for every
invocation of this method (for thread safety).
|
public static String getDateTimeString(Date self) {
return DateFormat.getDateTimeInstance(DateFormat.SHORT,DateFormat.MEDIUM).format( self );
}
Return a string representation of the date and time time portion of
this Date instance, according to the locale-specific format used by
DateFormat . This method uses the DateFormat#SHORT
preset for the day portion and DateFormat#MEDIUM for the time
portion of the output string.
Note that a new DateFormat instance is created for every
invocation of this method (for thread safety).
|
public static InputStream getErr(Process self) {
return self.getErrorStream();
}
An alias method so that a process appears similar to System.out, System.in, System.err;
you can use process.in, process.out, process.err in a similar fashion. |
public static InputStream getIn(Process self) {
return self.getInputStream();
}
An alias method so that a process appears similar to System.out, System.in, System.err;
you can use process.in, process.out, process.err in a similar fashion. |
public static MetaClass getMetaClass(Class c) {
MetaClassRegistry metaClassRegistry = GroovySystem.getMetaClassRegistry();
MetaClass mc = metaClassRegistry.getMetaClass(c);
if (mc instanceof ExpandoMetaClass
|| mc instanceof DelegatingMetaClass && ((DelegatingMetaClass) mc).getAdaptee() instanceof ExpandoMetaClass)
return mc;
else {
return new HandleMetaClass(mc);
}
}
Adds a "metaClass" property to all class objects so you can use the syntax
String.metaClass.myMethod = { println "foo" } |
public static MetaClass getMetaClass(Object obj) {
MetaClass mc = InvokerHelper.getMetaClass(obj);
return new HandleMetaClass(mc, obj);
}
Obtains a MetaClass for an object either from the registry or in the case of
a GroovyObject from the object itself. |
public static MetaClass getMetaClass(GroovyObject obj) {
// we need this method as trick to guarantee correct method selection
return getMetaClass((Object)obj);
}
Obtains a MetaClass for an object either from the registry or in the case of
a GroovyObject from the object itself. |
public static List<PropertyValue> getMetaPropertyValues(Object self) {
MetaClass metaClass = InvokerHelper.getMetaClass(self);
List< MetaProperty > mps = metaClass.getProperties();
List< PropertyValue > props = new ArrayList< PropertyValue >(mps.size());
for (MetaProperty mp : mps) {
props.add(new PropertyValue(self, mp));
}
return props;
}
Retrieves the list of MetaProperty objects for 'self' and wraps it
in a list of PropertyValue objects that additionally provide
the value for each property of 'self'. |
public static OutputStream getOut(Process self) {
return self.getOutputStream();
}
An alias method so that a process appears similar to System.out, System.in, System.err;
you can use process.in, process.out, process.err in a similar fashion. |
public static Map getProperties(Object self) {
List< PropertyValue > metaProps = getMetaPropertyValues(self);
Map< String, Object > props = new LinkedHashMap< String, Object >(metaProps.size());
for (PropertyValue mp : metaProps) {
try {
props.put(mp.getName(), mp.getValue());
} catch (Exception e) {
LOG.throwing(self.getClass().getName(), "getProperty(" + mp.getName() + ")", e);
}
}
return props;
}
Convenience method that calls #getMetaPropertyValues(Object) (self)
and provides the data in form of simple key/value pairs, i.e.&nsbp;without
type() information. |
public static ClassLoader getRootLoader(ClassLoader self) {
while (true) {
if (self == null) return null;
if (isRootLoaderClassOrSubClass(self)) return self;
self = self.getParent();
}
}
Iterates through the classloader parents until it finds a loader with a class
named "org.codehaus.groovy.tools.RootLoader". If there is no such class
null will be returned. The name is used for comparison because
a direct comparison using == may fail as the class may be loaded through
different classloaders. |
protected static List getSubList(List self,
List splice) {
int left /* = 0 */;
int right = 0;
boolean emptyRange = false;
if (splice.size() == 2) {
left = DefaultTypeTransformation.intUnbox(splice.get(0));
right = DefaultTypeTransformation.intUnbox(splice.get(1));
} else if (splice instanceof IntRange) {
IntRange range = (IntRange) splice;
left = range.getFromInt();
right = range.getToInt();
} else if (splice instanceof EmptyRange) {
RangeInfo info = subListBorders(self.size(), (EmptyRange) splice);
left = info.from;
emptyRange = true;
} else {
throw new IllegalArgumentException("You must specify a list of 2 indexes to create a sub-list");
}
int size = self.size();
left = normaliseIndex(left, size);
right = normaliseIndex(right, size);
List sublist /* = null */;
if (!emptyRange) {
sublist = self.subList(left, right + 1);
} else {
sublist = self.subList(left, left);
}
return sublist;
}
|
public static String getText(File file) throws IOException {
return getText(newReader(file));
}
Read the content of the File and returns it as a String. |
public static String getText(URL url) throws IOException {
return getText(url, CharsetToolkit.getDefaultSystemCharset().toString());
}
Read the content of this URL and returns it as a String. |
public static String getText(InputStream is) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
return getText(reader);
}
Read the content of this InputStream and return it as a String.
The stream is closed before this method returns. |
public static String getText(Reader reader) throws IOException {
BufferedReader bufferedReader = new BufferedReader(reader);
return getText(bufferedReader);
}
Read the content of the Reader and return it as a String. The reader
is closed before this method returns. |
public static String getText(BufferedReader reader) throws IOException {
StringBuilder answer = new StringBuilder();
// reading the content of the file within a char buffer
// allow to keep the correct line endings
char[] charBuffer = new char[8192];
int nbCharRead /* = 0*/;
try {
while ((nbCharRead = reader.read(charBuffer)) != -1) {
// appends buffer
answer.append(charBuffer, 0, nbCharRead);
}
Reader temp = reader;
reader = null;
temp.close();
} finally {
closeWithWarning(reader);
}
return answer.toString();
}
Read the content of the BufferedReader and return it as a String.
The BufferedReader is closed afterwards. |
public static String getText(Process self) throws IOException {
return getText(new BufferedReader(new InputStreamReader(self.getInputStream())));
}
Read the text of the output stream of the Process. |
public static String getText(File file,
String charset) throws IOException {
return getText(newReader(file, charset));
}
Read the content of the File using the specified encoding and return it
as a String. |
public static String getText(URL url,
String charset) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openConnection().getInputStream(), charset));
return getText(reader);
}
Read the data from this URL and return it as a String. The connection
stream is closed before this method returns. |
public static String getText(InputStream is,
String charset) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, charset));
return getText(reader);
}
Read the content of this InputStream using specified charset and return
it as a String. The stream is closed before this method returns. |
public static String getTimeString(Date self) {
return DateFormat.getTimeInstance(DateFormat.MEDIUM).format( self );
}
Return a string representation of the time portion of this date
according to the locale-specific DateFormat#MEDIUM default format.
For an "en_UK" system locale, this would be HH:MM:ss .
Note that a new DateFormat instance is created for every
invocation of this method (for thread safety).
|
public static Collection grep(Object self,
Object filter) {
Collection answer = createSimilarOrDefaultCollection(self);
MetaClass metaClass = InvokerHelper.getMetaClass(filter);
for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext();) {
Object object = iter.next();
if (DefaultTypeTransformation.castToBoolean(metaClass.invokeMethod(filter, "isCase", object))) {
answer.add(object);
}
}
return answer;
}
Iterates over every element of the collection and returns each item that matches
the given filter - calling the #isCase(Object,Object)
method used by switch statements. This method can be used with different
kinds of filters like regular expressions, classes, ranges etc.
Example:
def list = ['a', 'b', 'aa', 'bc' ]
def filtered = list.grep( ~/a+/ ) //contains 'a' and 'aa'
|
protected static void groupAnswer(Map<T> answer,
T element,
Object value) {
if (answer.containsKey(value)) {
answer.get(value).add(element);
} else {
List< T > groupedElements = new ArrayList< T >();
groupedElements.add(element);
answer.put(value, groupedElements);
}
}
Groups the current element according to the value |
public static Map<T> groupBy(Collection<T> self,
Closure closure) {
Map< Object, List< T > > answer = new LinkedHashMap< Object, List< T > >();
for (T element : self) {
Object value = closure.call(element);
groupAnswer(answer, element, value);
}
return answer;
}
Sorts all collection members into groups determined by the
supplied mapping closure. The closure should return the key that this
item should be grouped by. The returned LinkedHashMap will have an entry for each
distinct key returned from the closure, with each value being a list of
items for that group. |
public static Map<K, V> groupBy(Map<K, V> self,
Closure closure) {
final Map< Object, List< Map.Entry< K, V > > > initial = groupEntriesBy(self, closure);
final Map< Object, Map< K, V > > answer = new LinkedHashMap< Object, Map< K, V > >();
for (Map.Entry< Object, List< Map.Entry< K, V > > > outer : initial.entrySet()) {
Object key = outer.getKey();
List< Map.Entry< K, V > > entries = outer.getValue();
Map< K, V > target = createSimilarMap(self);
putAll(target, entries);
answer.put(key, target);
}
return answer;
}
Groups the members of a map into sub maps determined by the
supplied mapping closure. The closure will be passed a Map.Entry or
key and value (depending on the number of parameters the closure accepts)
and should return the key that each item should be grouped under. The
resulting map will have an entry for each 'group' key returned by the
closure, with values being the map members from the original map that
belong to each group.
If the self map is one of TreeMap, LinkedHashMap, Hashtable
or Properties, the returned Map will preserve that type, otherwise a HashMap will
be returned. |
public static Map<K, V> groupEntriesBy(Map<K, V> self,
Closure closure) {
final Map< Object, List< Map.Entry< K, V > > > answer = new LinkedHashMap< Object, List< Map.Entry< K, V > > >();
for (Map.Entry< K, V > entry : self.entrySet()) {
Object value = callClosureForMapEntry(closure, entry);
groupAnswer(answer, entry, value);
}
return answer;
}
Groups all map entries into groups determined by the
supplied mapping closure. The closure will be passed a Map.Entry or
key and value (depending on the number of parameters the closure accepts)
and should return the key that each item should be grouped under. The
resulting map will have an entry for each 'group' key returned by the
closure, with values being the list of map entries that belong to each
group. |
public static boolean hasGroup(Matcher matcher) {
return matcher.groupCount() > 0;
}
Check whether a Matcher contains a group or not. |
public static MetaProperty hasProperty(Object self,
String name) {
return InvokerHelper.getMetaClass(self).hasProperty(self, name);
}
Returns true of the implementing MetaClass has a property of the given name
Note that this method will only return true for realised properties and does not take into
account implementation of getProperty or propertyMissing
|
public static T head(List<T> self) {
return first(self);
}
Returns the first item from the List. |
public static Object identity(Object self,
Closure closure) {
return DefaultGroovyMethods.with(self, closure);
}
Allows the closure to be called for the object reference self
synonym for 'with()'. |
public static Object inject(Collection self,
Object value,
Closure closure) {
return inject(self.iterator(), value, closure);
}
Iterates through the given collection, passing in the initial value to
the closure along with the current iterated item then passing into the
next iteration the value of the previous closure. |
public static Object inject(Iterator self,
Object value,
Closure closure) {
Object[] params = new Object[2];
while (self.hasNext()) {
Object item = self.next();
params[0] = value;
params[1] = item;
value = closure.call(params);
}
return value;
}
Iterates through the given iterator, passing in the initial value to
the closure along with the current iterated item then passing into the
next iteration the value of the previous closure. |
public static Object inject(Object self,
Object value,
Closure closure) {
Iterator iter = InvokerHelper.asIterator(self);
return inject(iter, value, closure);
}
Iterates through the given object, passing in the initial value to
the closure along with the current iterated item then passing into the
next iteration the value of the previous closure. |
public static Object inject(Object[] self,
Object initialValue,
Closure closure) {
Object[] params = new Object[2];
Object value = initialValue;
for (Object next : self) {
params[0] = value;
params[1] = next;
value = closure.call(params);
}
return value;
}
Iterates through the given array of objects, passing in the initial value to
the closure along with the current iterated item then passing into the
next iteration the value of the previous closure. |
public static String inspect(Object self) {
return InvokerHelper.inspect(self);
}
Inspects returns the String that matches what would be typed into a
terminal to create this object. |
public static Number intdiv(Character left,
Number right) {
return intdiv(Integer.valueOf(left), right);
}
Integer Divide a Character by a Number. The ordinal value of the Character
is used in the division (the ordinal value is the unicode
value which for simple character sets is the ASCII value). |
public static Number intdiv(Number left,
Character right) {
return intdiv(left, Integer.valueOf(right));
}
Integer Divide a Number by a Character. The ordinal value of the Character
is used in the division (the ordinal value is the unicode
value which for simple character sets is the ASCII value). |
public static Number intdiv(Character left,
Character right) {
return intdiv(Integer.valueOf(left), right);
}
Integer Divide two Characters. The ordinal values of the Characters
are used in the division (the ordinal value is the unicode
value which for simple character sets is the ASCII value). |
public static Number intdiv(Number left,
Number right) {
return NumberMath.intdiv(left, right);
}
Integer Divide two Numbers. |
public static Collection<T> intersect(Collection<T> left,
Collection<T> right) {
if (left.isEmpty())
return createSimilarCollection(left, 0);
if (left.size() < right.size()) {
Collection< T > swaptemp = left;
left = right;
right = swaptemp;
}
// TODO optimise if same type?
// boolean nlgnSort = sameType(new Collection[]{left, right});
Collection< T > result = createSimilarCollection(left, left.size());
//creates the collection to look for values.
Collection< T > pickFrom = new TreeSet< T >(new NumberAwareComparator< T >());
pickFrom.addAll(left);
for (final T t : right) {
if (pickFrom.contains(t))
result.add(t);
}
return result;
}
Create a Collection composed of the intersection of both collections. Any
elements that exist in both collections are added to the resultant collection. |
public static Object invokeMethod(Object object,
String method,
Object arguments) {
return InvokerHelper.invokeMethod(object, method, arguments);
}
Provide a dynamic method invocation method which can be overloaded in
classes to implement dynamic proxies easily. |
public static boolean is(Object self,
Object other) {
return self == other;
}
Identity check. Since == is overridden in Groovy with the meaning of equality
we need some fallback to check for object identity. Invoke using the
'is' operator, like so: def same = (this is that) |
public static boolean isBigDecimal(String self) {
try {
new BigDecimal(self.trim());
return true;
} catch (NumberFormatException nfe) {
return false;
}
}
Determine if a String can be parsed into a BigDecimal. |
public static boolean isBigInteger(String self) {
try {
new BigInteger(self.trim());
return true;
} catch (NumberFormatException nfe) {
return false;
}
}
Determine if a String can be parsed into a BigInteger. |
public static boolean isCase(Object caseValue,
Object switchValue) {
if (caseValue.getClass().isArray()) {
return isCase(DefaultTypeTransformation.asCollection(caseValue), switchValue);
}
return caseValue.equals(switchValue);
}
Method for overloading the behavior of the 'case' method in switch statements.
The default implementation handles arrays types but otherwise simply delegates
to Object#equals, but this may be overridden for other types. In this example:
switch( a ) {
case b: //some code
}
"some code" is called when b.isCase( a ) returns
true . |
public static boolean isCase(String caseValue,
Object switchValue) {
if (switchValue == null) {
return caseValue == null;
}
return caseValue.equals(switchValue.toString());
}
'Case' implementation for a String, which uses String#equals(Object)
in order to allow Strings to be used in switch statements.
For example:
switch( str ) {
case 'one' :
// etc...
}
Note that this returns true for the case where both the
'switch' and 'case' operand is null . |
public static boolean isCase(GString caseValue,
Object switchValue) {
return isCase(caseValue.toString(), switchValue);
}
'Case' implementation for a GString, which simply calls the equivalet method for String. |
public static boolean isCase(Class caseValue,
Object switchValue) {
if (switchValue instanceof Class) {
Class val = (Class) switchValue;
return caseValue.isAssignableFrom(val);
}
return caseValue.isInstance(switchValue);
}
Special 'Case' implementation for Class, which allows testing
for a certain class in a switch statement.
For example:
switch( obj ) {
case List :
// obj is a list
break;
case Set :
// etc
} |
public static boolean isCase(Collection caseValue,
Object switchValue) {
return caseValue.contains(switchValue);
}
'Case' implementation for collections which tests if the 'switch'
operand is contained in any of the 'case' values.
For example:
switch( item ) {
case firstList :
// item is contained in this list
// etc
} |
public static boolean isCase(Pattern caseValue,
Object switchValue) {
if (switchValue == null) {
return caseValue == null;
}
final Matcher matcher = caseValue.matcher(switchValue.toString());
if (matcher.matches()) {
RegexSupport.setLastMatcher(matcher);
return true;
} else {
return false;
}
}
'Case' implementation for the Pattern class, which allows
testing a String against a number of regular expressions.
For example:
switch( str ) {
case ~/one/ :
// the regex 'one' matches the value of str
}
Note that this returns true for the case where both the pattern and
the 'switch' values are null . |
public static boolean isCase(Number caseValue,
Number switchValue) {
return NumberMath.compareTo(caseValue, switchValue) == 0;
}
Special 'case' implementation for all numbers, which delegates to the
compareTo() method for comparing numbers of different
types. |
public static boolean isDigit(Character self) {
return Character.isDigit(self);
}
Determines if a character is a digit.
Synonym for 'Character.isDigit(this)'. |
public static boolean isDouble(String self) {
try {
Double.valueOf(self.trim());
return true;
} catch (NumberFormatException nfe) {
return false;
}
}
Determine if a String can be parsed into a Double. |
public static boolean isFloat(String self) {
try {
Float.valueOf(self.trim());
return true;
} catch (NumberFormatException nfe) {
return false;
}
}
Determine if a String can be parsed into a Float. |
public static boolean isInteger(String self) {
try {
Integer.valueOf(self.trim());
return true;
} catch (NumberFormatException nfe) {
return false;
}
}
Determine if a String can be parsed into an Integer. |
public static boolean isLetter(Character self) {
return Character.isLetter(self);
}
Determines if a character is a letter.
Synonym for 'Character.isLetter(this)'. |
public static boolean isLetterOrDigit(Character self) {
return Character.isLetterOrDigit(self);
}
Determines if a character is a letter or digit.
Synonym for 'Character.isLetterOrDigit(this)'. |
public static boolean isLong(String self) {
try {
Long.valueOf(self.trim());
return true;
} catch (NumberFormatException nfe) {
return false;
}
}
Determine if a String can be parsed into a Long. |
public static boolean isLowerCase(Character self) {
return Character.isLowerCase(self);
}
Determine if a Character is lowercase.
Synonym for 'Character.isLowerCase(this)'. |
public static boolean isNumber(String self) {
return isBigDecimal(self);
}
Determine if a String can be parsed into a Number.
Synonym for 'isBigDecimal()'. |
public static boolean isUpperCase(Character self) {
return Character.isUpperCase(self);
}
Determine if a Character is uppercase.
Synonym for 'Character.isUpperCase(this)'. |
public static boolean isWhitespace(Character self) {
return Character.isWhitespace(self);
}
Determines if a character is a whitespace character.
Synonym for 'Character.isWhitespace(this)'. |
public static Iterator<T> iterator(T[] a) {
return DefaultTypeTransformation.asCollection(a).iterator();
}
Attempts to create an Iterator for the given object by first
converting it to a Collection. |
public static Iterator iterator(Object o) {
return DefaultTypeTransformation.asCollection(o).iterator();
}
Attempts to create an Iterator for the given object by first
converting it to a Collection. |
public static Iterator<T> iterator(Enumeration<T> enumeration) {
return new Iterator< T >() {
private T last;
public boolean hasNext() {
return enumeration.hasMoreElements();
}
public T next() {
last = enumeration.nextElement();
return last;
}
public void remove() {
throw new UnsupportedOperationException("Cannot remove() from an Enumeration");
}
};
}
Allows an Enumeration to behave like an Iterator. Note that the
remove() method is unsupported since the
underlying Enumeration does not provide a mechanism for removing items. |
public static Iterator<Node> iterator(NodeList nodeList) {
return XmlGroovyMethods.iterator(nodeList);
} Deprecated! moved - to org.codehaus.groovy.runtime.XmlGroovyMethods
Makes org.w3c.dom.NodeList iterable by returning a read-only Iterator which traverses
over each Node. |
public static Iterator iterator(Matcher matcher) {
matcher.reset();
return new Iterator() {
private boolean found /* = false */;
private boolean done /* = false */;
public boolean hasNext() {
if (done) {
return false;
}
if (!found) {
found = matcher.find();
if (!found) {
done = true;
}
}
return found;
}
public Object next() {
if (!found) {
if (!hasNext()) {
throw new NoSuchElementException();
}
}
found = false;
if (hasGroup(matcher)) {
// are we using groups?
// yes, so return the specified group as list
List list = new ArrayList(matcher.groupCount());
for (int i = 0; i < = matcher.groupCount(); i++) {
list.add(matcher.group(i));
}
return list;
} else {
// not using groups, so return the nth
// occurrence of the pattern
return matcher.group();
}
}
public void remove() {
throw new UnsupportedOperationException();
}
};
}
Returns an Iterator which traverses each match. |
public static Iterator<String> iterator(Reader self) {
final BufferedReader bufferedReader;
if (self instanceof BufferedReader)
bufferedReader = (BufferedReader) self;
else
bufferedReader = new BufferedReader(self);
return new Iterator< String >() {
String nextVal /* = null */;
boolean nextMustRead = true;
boolean hasNext = true;
public boolean hasNext() {
if (nextMustRead && hasNext) {
try {
nextVal = readNext();
nextMustRead = false;
} catch (IOException e) {
hasNext = false;
}
}
return hasNext;
}
public String next() {
String retval = null;
if (nextMustRead) {
try {
retval = readNext();
} catch (IOException e) {
hasNext = false;
}
} else
retval = nextVal;
nextMustRead = true;
return retval;
}
private String readNext() throws IOException {
String nv = bufferedReader.readLine();
if (nv == null)
hasNext = false;
return nv;
}
public void remove() {
throw new UnsupportedOperationException("Cannot remove() from a Reader Iterator");
}
};
}
Creates an iterator which will traverse through the reader a line at a time. |
public static Iterator<Byte> iterator(InputStream self) {
return iterator(new DataInputStream(self));
}
Standard iterator for a input stream which iterates through the stream
content in a byte-based fashion. |
public static Iterator<Byte> iterator(DataInputStream self) {
return new Iterator< Byte >() {
Byte nextVal;
boolean nextMustRead = true;
boolean hasNext = true;
public boolean hasNext() {
if (nextMustRead && hasNext) {
try {
nextVal = self.readByte();
nextMustRead = false;
} catch (IOException e) {
hasNext = false;
}
}
return hasNext;
}
public Byte next() {
Byte retval = null;
if (nextMustRead) {
try {
retval = self.readByte();
} catch (IOException e) {
hasNext = false;
}
} else
retval = nextVal;
nextMustRead = true;
return retval;
}
public void remove() {
throw new UnsupportedOperationException("Cannot remove() from a DataInputStream Iterator");
}
};
}
Standard iterator for a data input stream which iterates through the
stream content a Byte at a time. |
public static Iterator iterator(File self) throws IOException {
throw new DeprecationException(
"Iterators on files are not supported any more. " +
"Use File.eachLine() instead. Alternatively you can use FileReader.iterator() " +
"and provide your own exception handling."
);
} Deprecated! use - File#eachLine instead please
Just throws a DeprecationException. DO NOT USE. It used to provide an iterator for text file content
one line at a time. |
public static Iterator<T> iterator(Iterator<T> self) {
return self;
}
An identity function for iterators, supporting 'duck-typing' when trying to get an
iterator for each object within a collection, some of which may already be iterators. |
public static String join(Iterator self,
String separator) {
return join(toList(self), separator);
}
Concatenates the toString() representation of each
item from the iterator, with the given String as a separator between
each item. The iterator will become exhausted of elements after
determining the resulting conjoined value. |
public static String join(Collection self,
String separator) {
StringBuilder buffer = new StringBuilder();
boolean first = true;
if (separator == null) separator = "";
for (Object value : self) {
if (first) {
first = false;
} else {
buffer.append(separator);
}
buffer.append(InvokerHelper.toString(value));
}
return buffer.toString();
}
Concatenates the toString() representation of each
item in this collection, with the given String as a separator between
each item. |
public static String join(Object[] self,
String separator) {
StringBuilder buffer = new StringBuilder();
boolean first = true;
if (separator == null) separator = "";
for (Object next : self) {
String value = InvokerHelper.toString(next);
if (first) {
first = false;
} else {
buffer.append(separator);
}
buffer.append(value);
}
return buffer.toString();
}
Concatenates the toString() representation of each
items in this array, with the given String as a separator between each
item. |
public static T last(List<T> self) {
if (self.isEmpty()) {
throw new NoSuchElementException("Cannot access last() element from an empty List");
}
return self.get(self.size() - 1);
}
Returns the last item from the List. |
public static Collection<T> leftShift(Collection<T> self,
T value) {
self.add(value);
return self;
}
Overloads the left shift operator to provide an easy way to append
objects to a Collection. |
public static Map<K, V> leftShift(Map<K, V> self,
Entry<K, V> entry) {
self.put(entry.getKey(), entry.getValue());
return self;
}
Overloads the left shift operator to provide an easy way to append
Map.Entry values to a Map. |
public static StringBuffer leftShift(String self,
Object value) {
return new StringBuffer(self).append(value);
}
Overloads the left shift operator to provide an easy way to append multiple
objects as string representations to a String. |
public static StringBuffer leftShift(StringBuffer self,
Object value) {
self.append(value);
return self;
}
Overloads the left shift operator to provide an easy way to append multiple
objects as string representations to a StringBuffer. |
public static Writer leftShift(Writer self,
Object value) throws IOException {
InvokerHelper.write(self, value);
return self;
}
Overloads the left shift operator to provide a mechanism to append
values to a writer. |
public static Number leftShift(Number self,
Number operand) {
return NumberMath.leftShift(self, operand);
}
Implementation of the left shift operator for integral types. Non integral
Number types throw UnsupportedOperationException. |
public static Writer leftShift(OutputStream self,
Object value) throws IOException {
OutputStreamWriter writer = new FlushingStreamWriter(self);
leftShift(writer, value);
return writer;
}
Overloads the leftShift operator to provide an append mechanism to add values to a stream. |
public static void leftShift(ObjectOutputStream self,
Object value) throws IOException {
self.writeObject(value);
}
Overloads the leftShift operator to add objects to an ObjectOutputStream. |
public static OutputStream leftShift(OutputStream self,
InputStream in) throws IOException {
byte[] buf = new byte[1024];
while (true) {
int count = in.read(buf, 0, buf.length);
if (count == -1) break;
if (count == 0) {
Thread.yield();
continue;
}
self.write(buf, 0, count);
}
self.flush();
return self;
}
Pipe an InputStream into an OutputStream for efficient stream copying. |
public static OutputStream leftShift(OutputStream self,
byte[] value) throws IOException {
self.write(value);
self.flush();
return self;
}
Overloads the leftShift operator to provide an append mechanism to add bytes to a stream. |
public static File leftShift(File file,
Object text) throws IOException {
append(file, text);
return file;
}
Write the text to the File. |
public static File leftShift(File file,
byte[] bytes) throws IOException {
append(file, bytes);
return file;
}
|
public static File leftShift(File file,
InputStream data) throws IOException {
append(file, data);
return file;
}
|
public static Writer leftShift(Socket self,
Object value) throws IOException {
return leftShift(self.getOutputStream(), value);
}
Overloads the left shift operator to provide an append mechanism to
add things to the output stream of a socket |
public static OutputStream leftShift(Socket self,
byte[] value) throws IOException {
return leftShift(self.getOutputStream(), value);
}
Overloads the left shift operator to provide an append mechanism
to add bytes to the output stream of a socket |
public static Writer leftShift(Process self,
Object value) throws IOException {
return leftShift(self.getOutputStream(), value);
}
Overloads the left shift operator (<<) to provide an append mechanism
to pipe data to a Process. |
public static OutputStream leftShift(Process self,
byte[] value) throws IOException {
return leftShift(self.getOutputStream(), value);
}
Overloads the left shift operator to provide an append mechanism
to pipe into a Process |
public static boolean matches(String self,
Pattern pattern) {
return pattern.matcher(self).matches();
}
Tells whether or not self matches the given
compiled regular expression Pattern. |
public static T max(Collection<T> self) {
return GroovyCollections.max(self);
}
Adds max() method to Collection objects. |
public static T max(Iterator<T> self) {
return max(toList(self));
}
Adds max() method to Iterator objects. The iterator will become
exhausted of elements after determining the maximum value. |
public static T max(T[] self) {
return max(toList(self));
}
Adds max() method to Object arrays. |
public static T max(Collection<T> self,
Closure closure) {
int params = closure.getMaximumNumberOfParameters();
if (params != 1) {
return max(self, new ClosureComparator< T >(closure));
}
T answer = null;
Object answerValue = null;
for (T item : self) {
Object value = closure.call(item);
if (answer == null || ScriptBytecodeAdapter.compareLessThan(answerValue, value)) {
answer = item;
answerValue = value;
}
}
return answer;
}
Selects the maximum value found in the collection
using the closure to determine the correct ordering.
If the closure has two parameters
it is used like a traditional Comparator. I.e. it should compare
its two parameters for order, returning a negative integer,
zero, or a positive integer when the first parameter is less than,
equal to, or greater than the second respectively. Otherwise,
the Closure is assumed to take a single parameter and return a
Comparable (typically an Integer) which is then used for
further comparison. |
public static T max(Iterator<T> self,
Closure closure) {
return max(toList(self), closure);
}
Selects the maximum value found from the Iterator
using the closure to determine the correct ordering.
The iterator will become exhausted of elements after this operation.
If the closure has two parameters
it is used like a traditional Comparator. I.e. it should compare
its two parameters for order, returning a negative integer,
zero, or a positive integer when the first parameter is less than,
equal to, or greater than the second respectively. Otherwise,
the Closure is assumed to take a single parameter and return a
Comparable (typically an Integer) which is then used for
further comparison. |
public static T max(T[] self,
Closure closure) {
return max(toList(self), closure);
}
Selects the maximum value found from the Object array
using the closure to determine the correct ordering.
If the closure has two parameters
it is used like a traditional Comparator. I.e. it should compare
its two parameters for order, returning a negative integer,
zero, or a positive integer when the first parameter is less than,
equal to, or greater than the second respectively. Otherwise,
the Closure is assumed to take a single parameter and return a
Comparable (typically an Integer) which is then used for
further comparison. |
public static T max(Collection<T> self,
Comparator<T> comparator) {
T answer = null;
for (T value : self) {
if (answer == null || comparator.compare(value, answer) > 0) {
answer = value;
}
}
return answer;
}
Selects the maximum value found in the collection using the given comparator. |
public static T max(Iterator<T> self,
Comparator<T> comparator) {
return max(toList(self), comparator);
}
Selects the maximum value found from the Iterator using the given comparator. |
public static T max(T[] self,
Comparator<T> comparator) {
return max(toList(self), comparator);
}
Selects the maximum value found from the Object array using the given comparator. |
public static MetaClass metaClass(Class self,
Closure closure) {
MetaClassRegistry metaClassRegistry = GroovySystem.getMetaClassRegistry();
MetaClass mc = metaClassRegistry.getMetaClass(self);
if (mc instanceof ExpandoMetaClass) {
((ExpandoMetaClass) mc).define(closure);
return mc;
}
else {
if (mc instanceof DelegatingMetaClass && ((DelegatingMetaClass) mc).getAdaptee() instanceof ExpandoMetaClass) {
((ExpandoMetaClass)((DelegatingMetaClass) mc).getAdaptee()).define(closure);
return mc;
}
else {
if (mc instanceof DelegatingMetaClass && ((DelegatingMetaClass) mc).getAdaptee().getClass() == MetaClassImpl.class) {
ExpandoMetaClass emc = new ExpandoMetaClass(self, false, true);
emc.initialize();
emc.define(closure);
((DelegatingMetaClass) mc).setAdaptee(emc);
return mc;
}
else {
if (mc.getClass() == MetaClassImpl.class) {
// default case
mc = new ExpandoMetaClass(self, false, true);
mc.initialize();
((ExpandoMetaClass)mc).define(closure);
metaClassRegistry.setMetaClass(self, mc);
return mc;
}
else {
throw new GroovyRuntimeException("Can't add methods to custom meta class " + mc);
}
}
}
}
}
Sets/updates the metaclass for a given class to a closure. |
public static MetaClass metaClass(Object self,
Closure closure) {
MetaClass emc = hasPerInstanceMetaClass(self);
if (emc == null) {
final ExpandoMetaClass metaClass = new ExpandoMetaClass(self.getClass(), false, true);
metaClass.initialize();
metaClass.define(closure);
setMetaClass(self, metaClass);
return metaClass;
}
else {
if (emc instanceof ExpandoMetaClass) {
((ExpandoMetaClass)emc).define(closure);
return emc;
}
else {
if (emc instanceof DelegatingMetaClass && ((DelegatingMetaClass)emc).getAdaptee() instanceof ExpandoMetaClass) {
((ExpandoMetaClass)((DelegatingMetaClass)emc).getAdaptee()).define(closure);
return emc;
}
else {
throw new RuntimeException("Can't add methods to non-ExpandoMetaClass " + emc);
}
}
}
}
Sets/updates the metaclass for a given object to a closure. |
public static T min(Collection<T> self) {
return GroovyCollections.min(self);
}
Adds min() method to Collection objects. |
public static T min(Iterator<T> self) {
return min(toList(self));
}
Adds min() method to Iterator objects. The iterator will become
exhausted of elements after determining the minimum value. |
public static T min(T[] self) {
return min(toList(self));
}
Adds min() method to Object arrays. |
public static T min(Collection<T> self,
Comparator<T> comparator) {
T answer = null;
for (T value : self) {
if (answer == null || comparator.compare(value, answer) < 0) {
answer = value;
}
}
return answer;
}
Selects the minimum value found in the collection using the given comparator. |
public static T min(Iterator<T> self,
Comparator<T> comparator) {
return min(toList(self), comparator);
}
Selects the minimum value found from the Iterator using the given comparator. |
public static T min(T[] self,
Comparator<T> comparator) {
return min(toList(self), comparator);
}
Selects the minimum value found from the Object array using the given comparator. |
public static T min(Collection<T> self,
Closure closure) {
int params = closure.getMaximumNumberOfParameters();
if (params != 1) {
return min(self, new ClosureComparator< T >(closure));
}
T answer = null;
Object answer_value = null;
for (T item : self) {
Object value = closure.call(item);
if (answer == null || ScriptBytecodeAdapter.compareLessThan(value, answer_value)) {
answer = item;
answer_value = value;
}
}
return answer;
}
Selects the minimum value found in the collection
using the closure to determine the correct ordering.
If the closure has two parameters
it is used like a traditional Comparator. I.e. it should compare
its two parameters for order, returning a negative integer,
zero, or a positive integer when the first parameter is less than,
equal to, or greater than the second respectively. Otherwise,
the Closure is assumed to take a single parameter and return a
Comparable (typically an Integer) which is then used for
further comparison. |
public static T min(Iterator<T> self,
Closure closure) {
return min(toList(self), closure);
}
Selects the minimum value found from the Iterator
using the closure to determine the correct ordering.
The iterator will become
exhausted of elements after this operation.
If the closure has two parameters
it is used like a traditional Comparator. I.e. it should compare
its two parameters for order, returning a negative integer,
zero, or a positive integer when the first parameter is less than,
equal to, or greater than the second respectively. Otherwise,
the Closure is assumed to take a single parameter and return a
Comparable (typically an Integer) which is then used for
further comparison. |
public static T min(T[] self,
Closure closure) {
return min(toList(self), closure);
}
Selects the minimum value found from the Object array
using the closure to determine the correct ordering.
If the closure has two parameters
it is used like a traditional Comparator. I.e. it should compare
its two parameters for order, returning a negative integer,
zero, or a positive integer when the first parameter is less than,
equal to, or greater than the second respectively. Otherwise,
the Closure is assumed to take a single parameter and return a
Comparable (typically an Integer) which is then used for
further comparison. |
public static Set<T> minus(Set<T> self,
Collection operands) {
final Set< T > ansSet = createSimilarSet(self);
ansSet.addAll(self);
if (self.size() > 0) {
ansSet.removeAll(operands);
}
return ansSet;
}
Create a Set composed of the elements of the first set minus the
elements of the given collection.
TODO: remove using number comparator? |
public static Set<T> minus(Set<T> self,
Object operand) {
final Set< T > ansSet = createSimilarSet(self);
Comparator numberComparator = new NumberAwareComparator();
for (T t : self) {
if (numberComparator.compare(t, operand) != 0) ansSet.add(t);
}
return ansSet;
}
Create a Set composed of the elements of the first set minus the operand. |
public static T[] minus(T[] self,
Collection<T> removeMe) {
return (T[]) minus(toList(self), removeMe).toArray();
}
Create an array composed of the elements of the first array minus the
elements of the given collection. |
public static T[] minus(T[] self,
T[] removeMe) {
return (T[]) minus(toList(self), toList(removeMe)).toArray();
}
Create an array composed of the elements of the first array minus the
elements of the given array. |
public static List<T> minus(List<T> self,
Collection<T> removeMe) {
if (self.size() == 0)
return new ArrayList< T >();
boolean nlgnSort = sameType(new Collection[]{self, removeMe});
// We can't use the same tactic as for intersection
// since AbstractCollection only does a remove on the first
// element it encounters.
Comparator< T > numberComparator = new NumberAwareComparator< T >();
if (nlgnSort && (self.get(0) instanceof Comparable)) {
//n*LOG(n) version
Set< T > answer;
if (Number.class.isInstance(self.get(0))) {
answer = new TreeSet< T >(numberComparator);
answer.addAll(self);
for (T t : self) {
if (Number.class.isInstance(t)) {
for (T t2 : removeMe) {
if (Number.class.isInstance(t2)) {
if (numberComparator.compare(t, t2) == 0)
answer.remove(t);
}
}
} else {
if (removeMe.contains(t))
answer.remove(t);
}
}
} else {
answer = new TreeSet< T >(numberComparator);
answer.addAll(self);
answer.removeAll(removeMe);
}
List< T > ansList = new ArrayList< T >();
for (T o : self) {
if (answer.contains(o))
ansList.add(o);
}
return ansList;
} else {
//n*n version
List< T > tmpAnswer = new LinkedList< T >(self);
for (Iterator< T > iter = tmpAnswer.iterator(); iter.hasNext();) {
T element = iter.next();
boolean elementRemoved = false;
for (Iterator< T > iterator = removeMe.iterator(); iterator.hasNext() && !elementRemoved;) {
T elt = iterator.next();
if (numberComparator.compare(element, elt) == 0) {
iter.remove();
elementRemoved = true;
}
}
}
//remove duplicates
//can't use treeset since the base classes are different
return new ArrayList< T >(tmpAnswer);
}
}
Create a List composed of the elements of the first list minus the
elements of the given collection. |
public static List<T> minus(List<T> self,
Object operand) {
Comparator numberComparator = new NumberAwareComparator();
List< T > ansList = new ArrayList< T >();
for (T t : self) {
if (numberComparator.compare(t, operand) != 0) ansList.add(t);
}
return ansList;
}
Create a new List composed of the elements of the first list minus the
operand. |
public static T[] minus(T[] self,
Object operand) {
return (T[]) minus(toList(self), operand).toArray();
}
Create a new object array composed of the elements of the first array
minus the operand. |
public static String minus(String self,
Object target) {
if (target instanceof Pattern) {
return ((Pattern)target).matcher(self).replaceFirst("");
}
String text = toString(target);
int index = self.indexOf(text);
if (index == -1) return self;
int end = index + text.length();
if (self.length() > end) {
return self.substring(0, index) + self.substring(end);
}
return self.substring(0, index);
}
Remove a part of a String. This replaces the first occurrence
of target within self with '' and returns the result. If
target is a regex Pattern, the first occurrence of that
pattern will be removed (using regex matching), otherwise
the first occurrence of target.toString() will be removed. |
public static Number minus(Character left,
Number right) {
return NumberNumberMinus.minus(Integer.valueOf(left), right);
}
Subtract a Number from a Character. The ordinal value of the Character
is used in the subtraction (the ordinal value is the unicode
value which for simple character sets is the ASCII value). |
public static Number minus(Number left,
Character right) {
return NumberNumberMinus.minus(left, Integer.valueOf(right));
}
Subtract a Character from a Number. The ordinal value of the Character
is used in the subtraction (the ordinal value is the unicode
value which for simple character sets is the ASCII value). |
public static Number minus(Character left,
Character right) {
return minus(Integer.valueOf(left), right);
}
Subtract one Character from another. The ordinal values of the Characters
is used in the comparison (the ordinal value is the unicode
value which for simple character sets is the ASCII value). |
public static Date minus(Date self,
int days) {
return plus(self, -days);
}
Subtract a number of days from this date and returns the new date. |
public static Date minus(Date self,
int days) {
return new java.sql.Date(minus((Date) self, days).getTime());
}
Subtract a number of days from this date and returns the new date. |
public static int minus(Calendar self,
Calendar then) {
Calendar a = self;
Calendar b = then;
boolean swap = a.before(b);
if (swap) {
Calendar t = a;
a = b;
b = t;
}
int days = 0;
b = (Calendar) b.clone();
while (a.get(Calendar.YEAR) > b.get(Calendar.YEAR)) {
days += 1 + (b.getActualMaximum(Calendar.DAY_OF_YEAR) - b.get(Calendar.DAY_OF_YEAR));
b.set(Calendar.DAY_OF_YEAR, 1);
b.add(Calendar.YEAR, 1);
}
days += a.get(Calendar.DAY_OF_YEAR) - b.get(Calendar.DAY_OF_YEAR);
if (swap) days = -days;
return days;
}
Subtract another date from this one and return the number of days of the difference.
Date self = Date then + (Date self - Date then)
IOW, if self is before then the result is a negative value. |
public static int minus(Date self,
Date then) {
Calendar a = (Calendar) Calendar.getInstance().clone();
a.setTime(self);
Calendar b = (Calendar) Calendar.getInstance().clone();
b.setTime(then);
return minus(a, b);
}
Subtract another Date from this one and return the number of days of the difference.
Date self = Date then + (Date self - Date then)
IOW, if self is before then the result is a negative value. |
public static void mixin(MetaClass self,
List<Class> categoryClasses) {
MixinInMetaClass.mixinClassesToMetaClass(self, categoryClasses);
}
Extend object with category methods.
All methods for given class and all super classes will be added to the object. |
public static void mixin(Class self,
List<Class> categoryClasses) {
mixin(getMetaClass(self), categoryClasses);
}
Extend class globally with category methods.
All methods for given class and all super classes will be added to the class. |
public static void mixin(Class self,
Class categoryClass) {
mixin(getMetaClass(self), Collections.singletonList(categoryClass));
}
Extend class globally with category methods. |
public static void mixin(Class self,
Class[] categoryClass) {
mixin(getMetaClass(self), Arrays.asList(categoryClass));
}
Extend class globally with category methods. |
public static void mixin(MetaClass self,
Class categoryClass) {
mixin(self, Collections.singletonList(categoryClass));
}
Extend class globally with category methods. |
public static void mixin(MetaClass self,
Class[] categoryClass) {
mixin(self, Arrays.asList(categoryClass));
}
Extend class globally with category methods. |
public static Number mod(Number left,
Number right) {
return NumberMath.mod(left, right);
}
Performs a division modulus operation. Called by the '%' operator. |
public static List<T> multiply(Collection<T> self,
Number factor) {
int size = factor.intValue();
List< T > answer = new ArrayList< T >(self.size() * size);
for (int i = 0; i < size; i++) {
answer.addAll(self);
}
return answer;
}
Create a List composed of the elements of this list, repeated
a certain number of times. Note that for non-primitive
elements, multiple references to the same instance will be added. |
public static String multiply(String self,
Number factor) {
int size = factor.intValue();
if (size == 0)
return "";
else if (size < 0) {
throw new IllegalArgumentException("multiply() should be called with a number of 0 or greater not: " + size);
}
StringBuilder answer = new StringBuilder(self);
for (int i = 1; i < size; i++) {
answer.append(self);
}
return answer.toString();
}
Repeat a String a certain number of times. |
public static Number multiply(Character left,
Number right) {
return NumberNumberMultiply.multiply(Integer.valueOf(left), right);
}
Multiply a Character by a Number. The ordinal value of the Character
is used in the multiplcation (the ordinal value is the unicode
value which for simple character sets is the ASCII value). |
public static Number multiply(Number left,
Character right) {
return NumberNumberMultiply.multiply(Integer.valueOf(right), left);
}
Multiply a Number by a Character. The ordinal value of the Character
is used in the multiplication (the ordinal value is the unicode
value which for simple character sets is the ASCII value). |
public static Number multiply(Character left,
Character right) {
return multiply(Integer.valueOf(left), right);
}
Multiply two Characters. The ordinal values of the Characters
are used in the multiplication (the ordinal value is the unicode
value which for simple character sets is the ASCII value). |
public static Number multiply(BigDecimal left,
Double right) {
return NumberMath.multiply(left, right);
}
Multiply a BigDecimal and a Double.
Note: This method was added to enforce the Groovy rule of
BigDecimal*Double == Double. Without this method, the
multiply(BigDecimal) method in BigDecimal would respond
and return a BigDecimal instead. Since BigDecimal is preferred
over Number, the Number*Number method is not chosen as in older
versions of Groovy. |
public static Number multiply(BigDecimal left,
BigInteger right) {
return NumberMath.multiply(left, right);
}
Multiply a BigDecimal and a BigInteger.
Note: This method was added to enforce the Groovy rule of
BigDecimal*long == long. Without this method, the
multiply(BigDecimal) method in BigDecimal would respond
and return a BigDecimal instead. Since BigDecimal is preferred
over Number, the Number*Number method is not chosen as in older
versions of Groovy. BigInteger is the fallback for all integer
types in Groovy |
public static DataInputStream newDataInputStream(File file) throws FileNotFoundException {
return new DataInputStream(new FileInputStream(file));
}
Create a data input stream for this file |
public static DataOutputStream newDataOutputStream(File file) throws IOException {
return new DataOutputStream(new FileOutputStream(file));
}
Creates a new data output stream for this file. |
public static BufferedInputStream newInputStream(File file) throws FileNotFoundException {
return new BufferedInputStream(new FileInputStream(file));
}
Creates a buffered input stream for this file. |
public static BufferedInputStream newInputStream(URL url) throws MalformedURLException, IOException {
return new BufferedInputStream(url.openConnection().getInputStream());
}
Creates a buffered input stream for this URL. |
public static Object newInstance(Class c) {
return InvokerHelper.invokeConstructorOf(c, null);
}
Convenience method to dynamically create a new instance of this
class. Calls the default constructor. |
public static Object newInstance(Class c,
Object[] args) {
if (args == null) args = new Object[]{null};
return InvokerHelper.invokeConstructorOf(c, args);
}
Helper to construct a new instance from the given arguments.
The constructor is called based on the number and types in the
args array. Use newInstance(null) or simply
newInstance() for the default (no-arg) constructor. |
public static ObjectInputStream newObjectInputStream(File file) throws IOException {
return new ObjectInputStream(new FileInputStream(file));
}
Create an object input stream for this file. |
public static ObjectInputStream newObjectInputStream(InputStream inputStream) throws IOException {
return new ObjectInputStream(inputStream);
}
Create an object input stream for this input stream. |
public static ObjectInputStream newObjectInputStream(InputStream inputStream,
ClassLoader classLoader) throws IOException {
return new ObjectInputStream(inputStream) {
protected Class< ? > resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException {
return Class.forName(desc.getName(), true, classLoader);
}
};
}
Create an object input stream for this input stream using the given class loader. |
public static ObjectInputStream newObjectInputStream(File file,
ClassLoader classLoader) throws IOException {
return newObjectInputStream(new FileInputStream(file), classLoader);
}
Create an object input stream for this file using the given class loader. |
public static ObjectOutputStream newObjectOutputStream(File file) throws IOException {
return new ObjectOutputStream(new FileOutputStream(file));
}
Create an object output stream for this file. |
public static ObjectOutputStream newObjectOutputStream(OutputStream outputStream) throws IOException {
return new ObjectOutputStream(outputStream);
}
Create an object output stream for this output stream. |
public static BufferedOutputStream newOutputStream(File file) throws IOException {
return new BufferedOutputStream(new FileOutputStream(file));
}
Create a buffered output stream for this file. |
public static PrintWriter newPrintWriter(File file) throws IOException {
return new GroovyPrintWriter(newWriter(file));
}
Create a new PrintWriter for this file. |
public static PrintWriter newPrintWriter(Writer writer) {
return new GroovyPrintWriter(writer);
}
Create a new PrintWriter for this file, using specified
charset. |
public static PrintWriter newPrintWriter(File file,
String charset) throws IOException {
return new GroovyPrintWriter(newWriter(file, charset));
}
Create a new PrintWriter for this file, using specified
charset. |
public static BufferedReader newReader(File file) throws IOException {
CharsetToolkit toolkit = new CharsetToolkit(file);
return toolkit.getReader();
}
Create a buffered reader for this file. |
public static BufferedReader newReader(InputStream self) {
return new BufferedReader(new InputStreamReader(self));
}
Creates a reader for this input stream. |
public static BufferedReader newReader(URL url) throws MalformedURLException, IOException {
return newReader(url.openConnection().getInputStream());
}
Creates a buffered reader for this URL. |
public static BufferedReader newReader(File file,
String charset) throws FileNotFoundException, UnsupportedEncodingException {
return new BufferedReader(new InputStreamReader(new FileInputStream(file), charset));
}
Create a buffered reader for this file, using the specified
charset as the encoding. |
public static BufferedReader newReader(InputStream self,
String charset) throws UnsupportedEncodingException {
return new BufferedReader(new InputStreamReader(self, charset));
}
Creates a reader for this input stream, using the specified
charset as the encoding. |
public static BufferedReader newReader(URL url,
String charset) throws MalformedURLException, IOException {
return new BufferedReader(new InputStreamReader(url.openConnection().getInputStream(), charset));
}
Creates a buffered reader for this URL using the given encoding. |
public static BufferedWriter newWriter(File file) throws IOException {
return new BufferedWriter(new FileWriter(file));
}
Create a buffered writer for this file. |
public static BufferedWriter newWriter(File file,
boolean append) throws IOException {
return new BufferedWriter(new FileWriter(file, append));
}
Creates a buffered writer for this file, optionally appending to the
existing file content. |
public static BufferedWriter newWriter(File file,
String charset) throws IOException {
return newWriter(file, charset, false);
}
Creates a buffered writer for this file, writing data using the given
encoding. |
public static BufferedWriter newWriter(File file,
String charset,
boolean append) throws IOException {
if (append) {
return new EncodingAwareBufferedWriter(new OutputStreamWriter(new FileOutputStream(file, append), charset));
} else {
// first write the Byte Order Mark for Unicode encodings
FileOutputStream stream = new FileOutputStream(file);
if ("UTF-16BE".equals(charset)) {
writeUtf16Bom(stream, true);
} else if ("UTF-16LE".equals(charset)) {
writeUtf16Bom(stream, false);
}
return new EncodingAwareBufferedWriter(new OutputStreamWriter(stream, charset));
}
}
Helper method to create a buffered writer for a file. If the given
charset is "UTF-16BE" or "UTF-16LE", the requisite byte order mark is
written to the stream before the writer is returned. |
public static String next(String self) {
StringBuilder buffer = new StringBuilder(self);
if (buffer.length() == 0) {
buffer.append(Character.MIN_VALUE);
} else {
char last = buffer.charAt(buffer.length() - 1);
if (last == Character.MAX_VALUE) {
buffer.append(Character.MIN_VALUE);
} else {
char next = last;
next++;
buffer.setCharAt(buffer.length() - 1, next);
}
}
return buffer.toString();
}
This method is called by the ++ operator for the class String.
It increments the last character in the given string. If the
character in the string is Character.MAX_VALUE a Character.MIN_VALUE
will be appended. The empty string is incremented to a string
consisting of the character Character.MIN_VALUE. |
public static Character next(Character self) {
return (char) (self + 1);
}
Increment a Character by one. |
public static Number next(Number self) {
return NumberNumberPlus.plus(self, ONE);
}
Increment a Number by one. |
public static Date next(Date self) {
return plus(self, 1);
}
Increment a Date by one day. |
public static Date next(Date self) {
return new java.sql.Date(next((Date) self).getTime());
}
Increment a java.sql.Date by one day. |
public static String normalize(String self) {
int nx = self.indexOf('\r');
if (nx < 0) {
return self;
}
final int len = self.length();
final StringBuilder sb = new StringBuilder(len);
int i = 0;
do {
sb.append(self, i, nx);
sb.append('\n');
if ((i = nx + 1) >= len) break;
if (self.charAt(i) == '\n') {
// skip the LF in CR LF
if (++i >= len) break;
}
nx = self.indexOf('\r', i);
} while (nx > 0);
sb.append(self, i, len);
return sb.toString();
}
Return a String with linefeeds and carriage returns normalized to linefeeds. |
public static int numberAwareCompareTo(Comparable self,
Comparable other) {
NumberAwareComparator< Comparable > numberAwareComparator = new NumberAwareComparator< Comparable >();
return numberAwareComparator.compare(self, other);
}
Provides a method that compares two comparables using Groovy's
default number aware comparator. |
public static Number or(Number left,
Number right) {
return NumberMath.or(left, right);
}
Bitwise OR together two numbers. |
public static BitSet or(BitSet left,
BitSet right) {
BitSet result = (BitSet) left.clone();
result.or(right);
return result;
}
Bitwise OR together two BitSets. Called when the '|' operator is used
between two bit sets. |
public static Boolean or(Boolean left,
Boolean right) {
return left || right;
}
Logical disjunction of two boolean operators |
public static Process or(Process left,
Process right) throws IOException {
return pipeTo(left, right);
}
Overrides the or operator to allow one Process to asynchronously
pipe data to another Process. |
public static String padLeft(String self,
Number numberOfChars) {
return padLeft(self, numberOfChars, " ");
}
Pad a String with the spaces appended to the left |
public static String padLeft(String self,
Number numberOfChars,
String padding) {
int numChars = numberOfChars.intValue();
if (numChars < = self.length()) {
return self;
} else {
return getPadding(padding, numChars - self.length()) + self;
}
}
Pad a String with the characters appended to the left |
public static String padRight(String self,
Number numberOfChars) {
return padRight(self, numberOfChars, " ");
}
Pad a String with the spaces appended to the right |
public static String padRight(String self,
Number numberOfChars,
String padding) {
int numChars = numberOfChars.intValue();
if (numChars < = self.length()) {
return self;
} else {
return self + getPadding(padding, numChars - self.length());
}
}
Pad a String with the characters appended to the right |
public static Set<T> permutations(List<T> self) {
Set< List< T > > ans = new HashSet< List< T > >();
PermutationGenerator< T > generator = new PermutationGenerator< T >(self);
while (generator.hasNext()) {
ans.add(generator.next());
}
return ans;
}
Finds all permutations of a collection.
E.g. [1, 2, 3].permutations() would be:
[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]] |
public static Process pipeTo(Process left,
Process right) throws IOException {
new Thread(new Runnable() {
public void run() {
InputStream in = new BufferedInputStream(getIn(left));
OutputStream out = new BufferedOutputStream(getOut(right));
byte[] buf = new byte[8192];
int next;
try {
while ((next = in.read(buf)) != -1) {
out.write(buf, 0, next);
}
} catch (IOException e) {
throw new GroovyRuntimeException("exception while reading process stream", e);
} finally {
closeWithWarning(out);
}
}
}).start();
return right;
}
Allows one Process to asynchronously pipe data to another Process. |
public static Map<K, V> plus(Map<K, V> left,
Map<K, V> right) {
Map< K, V > map = cloneSimilarMap(left);
map.putAll(right);
return map;
}
Returns a new Map containing all entries from left and right ,
giving precedence to right . Any keys appearing in both Maps
will appear in the resultant map with values from the right
operand. If the left map is one of TreeMap, LinkedHashMap, Hashtable
or Properties, the returned Map will preserve that type, otherwise a HashMap will
be returned.
Roughly equivalent to Map m = new HashMap(); m.putAll(left); m.putAll(right); return m;
but with some additional logic to preserve the left Map type for common cases as
described above.
|
public static Map<K, V> plus(Map<K, V> self,
Collection<K, V> entries) {
Map< K, V > map = cloneSimilarMap(self);
putAll(map, entries);
return map;
}
Returns a new Map containing all entries from self and entries ,
giving precedence to entries . Any keys appearing in both Maps
will appear in the resultant map with values from the entries
operand. If self map is one of TreeMap, LinkedHashMap, Hashtable
or Properties, the returned Map will preserve that type, otherwise a HashMap will
be returned.
|
public static Collection<T> plus(Collection<T> left,
Collection<T> right) {
final Collection< T > answer = cloneSimilarCollection(left, left.size() + right.size());
answer.addAll(right);
return answer;
}
Create a Collection as a union of two collections. If the left collection
is a Set, then the returned collection will be a Set otherwise a List.
This operation will always create a new object for the result,
while the operands remain unchanged. |
public static Collection<T> plus(Collection<T> left,
T right) {
final Collection< T > answer = cloneSimilarCollection(left, left.size() + 1);
answer.add(right);
return answer;
}
Create a collection as a union of a Collection and an Object. If the collection
is a Set, then the returned collection will be a Set otherwise a List.
This operation will always create a new object for the result,
while the operands remain unchanged. |
public static String plus(String left,
Object value) {
return left + toString(value);
}
Appends the String representation of the given operand to this string. |
public static String plus(Number value,
String right) {
return toString(value) + right;
}
Appends a String to the string representation of this number. |
public static String plus(StringBuffer left,
String value) {
return left + value;
}
Appends a String to this StringBuffer. |
public static Number plus(Character left,
Number right) {
return NumberNumberPlus.plus(Integer.valueOf(left), right);
}
Add a Character and a Number. The ordinal value of the Character
is used in the addition (the ordinal value is the unicode
value which for simple character sets is the ASCII value).
This operation will always create a new object for the result,
while the operands remain unchanged. |
public static Number plus(Number left,
Character right) {
return NumberNumberPlus.plus(left, Integer.valueOf(right));
}
Add a Number and a Character. The ordinal value of the Character
is used in the addition (the ordinal value is the unicode
value which for simple character sets is the ASCII value). |
public static Number plus(Character left,
Character right) {
return plus(Integer.valueOf(left), right);
}
Add one Character to another. The ordinal values of the Characters
are used in the addition (the ordinal value is the unicode
value which for simple character sets is the ASCII value).
This operation will always create a new object for the result,
while the operands remain unchanged. |
public static Date plus(Date self,
int days) {
Calendar calendar = (Calendar) Calendar.getInstance().clone();
calendar.setTime(self);
calendar.add(Calendar.DAY_OF_YEAR, days);
return calendar.getTime();
}
Add a number of days to this date and returns the new date. |
public static Date plus(Date self,
int days) {
return new java.sql.Date(plus((Date) self, days).getTime());
}
Add a number of days to this date and returns the new date. |
public static T pop(List<T> self) {
if (self.isEmpty()) {
throw new NoSuchElementException("Cannot pop() an empty List");
}
return self.remove(self.size() - 1);
}
Removes the last item from the List. Using add() and pop()
is similar to push and pop on a Stack. |
public static Number power(Number self,
Number exponent) {
double base, exp, answer;
base = self.doubleValue();
exp = exponent.doubleValue();
answer = Math.pow(base, exp);
if ((double) ((int) answer) == answer) {
return (int) answer;
} else if ((double) ((long) answer) == answer) {
return (long) answer;
} else {
return answer;
}
}
Power of a Number to a certain exponent. Called by the '**' operator. |
public static String previous(String self) {
StringBuilder buffer = new StringBuilder(self);
if (buffer.length() == 0) throw new IllegalArgumentException("the string is empty");
char last = buffer.charAt(buffer.length() - 1);
if (last == Character.MIN_VALUE) {
buffer.deleteCharAt(buffer.length() - 1);
} else {
char next = last;
next--;
buffer.setCharAt(buffer.length() - 1, next);
}
return buffer.toString();
}
This method is called by the -- operator for the class String.
It decrements the last character in the given string. If the
character in the string is Character.MIN_VALUE it will be deleted.
The empty string can't be decremented. |
public static Character previous(Character self) {
return (char) (self - 1);
}
Decrement a Character by one. |
public static Number previous(Number self) {
return NumberNumberMinus.minus(self, ONE);
}
Decrement a Number by one. |
public static Date previous(Date self) {
return minus(self, 1);
}
Decrement a Date by one day. |
public static Date previous(Date self) {
return new java.sql.Date(previous((Date) self).getTime());
}
Decrement a java.sql.Date by one day. |
protected static Object primitiveArrayGet(Object self,
int idx) {
return Array.get(self, normaliseIndex(idx, Array.getLength(self)));
}
Implements the getAt(int) method for primitve type arrays. |
protected static List primitiveArrayGet(Object self,
Range range) {
List answer = new ArrayList();
for (Object next : range) {
int idx = DefaultTypeTransformation.intUnbox(next);
answer.add(primitiveArrayGet(self, idx));
}
return answer;
}
Implements the getAt(Range) method for primitve type arrays. |
protected static List primitiveArrayGet(Object self,
Collection indices) {
List answer = new ArrayList();
for (Object value : indices) {
if (value instanceof Range) {
answer.addAll(primitiveArrayGet(self, (Range) value));
} else if (value instanceof List) {
answer.addAll(primitiveArrayGet(self, (List) value));
} else {
int idx = DefaultTypeTransformation.intUnbox(value);
answer.add(primitiveArrayGet(self, idx));
}
}
return answer;
}
Implements the getAt(Collection) method for primitve type arrays. Each
value in the collection argument is assumed to be a valid array index.
The value at each index is then added to a list which is returned. |
protected static Object primitiveArrayPut(Object self,
int idx,
Object newValue) {
Array.set(self, normaliseIndex(idx, Array.getLength(self)), newValue);
return newValue;
}
Implements the setAt(int idx) method for primitve type arrays. |
public static void print(Object self,
Object value) {
// we won't get here if we are a PrintWriter
if (self instanceof Writer) {
try {
((Writer) self).write(InvokerHelper.toString(value));
} catch (IOException e) {
// TODO: Should we have some unified function like PrintWriter.checkError()?
}
} else {
System.out.print(InvokerHelper.toString(value));
}
}
Print a value formatted Groovy style to self if it
is a Writer, otherwise to the standard output stream. |
public static void print(PrintWriter self,
Object value) {
self.print(InvokerHelper.toString(value));
}
Print a value formatted Groovy style to the print writer. |
public static void print(PrintStream self,
Object value) {
self.print(InvokerHelper.toString(value));
}
Print a value formatted Groovy style to the print stream. |
public static void print(Closure self,
Object value) {
Object owner = getClosureOwner(self);
InvokerHelper.invokeMethod(owner, "print", new Object[]{value});
}
Print a value to the standard output stream.
This method delegates to the owner to execute the method. |
public static void print(Object self,
PrintWriter out) {
if (out == null) {
out = new PrintWriter(System.out);
}
out.print(InvokerHelper.toString(self));
}
Print to a console in interactive format. |
public static void printf(Object self,
String format,
Object[] values) {
if (self instanceof PrintStream)
((PrintStream)self).printf(format, values);
else
System.out.printf(format, values);
}
Printf to a console (Only works with JDK1.5 or later). |
public static void printf(Object self,
String format,
Object arg) {
if (self instanceof PrintStream)
printf((PrintStream) self, format, arg);
else
printf(System.out, format, arg);
}
Prints a formatted string using the specified format string and
arguments.
For examples,
printf ( "Hello, %s!\n" , [ "world" ] as String[] )
printf ( "Hello, %s!\n" , [ "Groovy" ])
printf ( "%d + %d = %d\n" , [ 1 , 2 , 1+2 ] as Integer[] )
printf ( "%d + %d = %d\n" , [ 3 , 3 , 3+3 ])
( 1..5 ).each { printf ( "-- %d\n" , [ it ] as Integer[] ) }
( 1..5 ).each { printf ( "-- %d\n" , [ it ] as int[] ) }
( 0x41..0x45 ).each { printf ( "-- %c\n" , [ it ] as char[] ) }
( 07..011 ).each { printf ( "-- %d\n" , [ it ] as byte[] ) }
( 7..11 ).each { printf ( "-- %d\n" , [ it ] as short[] ) }
( 7..11 ).each { printf ( "-- %d\n" , [ it ] as long[] ) }
( 7..11 ).each { printf ( "-- %5.2f\n" , [ it ] as float[] ) }
( 7..11 ).each { printf ( "-- %5.2g\n" , [ it ] as double[] ) }
|
public static void println(Object self) {
// we won't get here if we are a PrintWriter
if (self instanceof Writer) {
PrintWriter pw = new GroovyPrintWriter((Writer) self);
pw.println();
} else {
System.out.println();
}
}
Print a linebreak to the standard output stream. |
public static void println(Closure self) {
Object owner = getClosureOwner(self);
InvokerHelper.invokeMethod(owner, "println", new Object[0]);
}
Print a linebreak to the standard output stream.
This method delegates to the owner to execute the method. |
public static void println(Object self,
Object value) {
// we won't get here if we are a PrintWriter
if (self instanceof Writer) {
final PrintWriter pw = new GroovyPrintWriter((Writer) self);
pw.println(value);
} else {
System.out.println(InvokerHelper.toString(value));
}
}
Print a value formatted Groovy style (followed by a newline) to self
if it is a Writer, otherwise to the standard output stream. |
public static void println(PrintWriter self,
Object value) {
self.println(InvokerHelper.toString(value));
}
Print a value formatted Groovy style (followed by a newline) to the print writer. |
public static void println(PrintStream self,
Object value) {
self.println(InvokerHelper.toString(value));
}
Print a value formatted Groovy style (followed by a newline) to the print stream. |
public static void println(Closure self,
Object value) {
Object owner = getClosureOwner(self);
InvokerHelper.invokeMethod(owner, "println", new Object[]{value});
}
Print a value (followed by a newline) to the standard output stream.
This method delegates to the owner to execute the method. |
public static void println(Object self,
PrintWriter out) {
if (out == null) {
out = new PrintWriter(System.out);
}
out.println(InvokerHelper.toString(self));
}
Print to a console in interactive format. |
public static boolean push(List<T> self,
T value) {
return self.add(value);
}
Appends an item to the List. Synonym for add(). |
public static Map<K, V> putAll(Map<K, V> self,
Collection<K, V> entries) {
for (Map.Entry< K, V > entry : entries) {
self.put(entry.getKey(), entry.getValue());
}
return self;
}
Provides an easy way to append multiple Map.Entry values to a Map. |
public static void putAt(Object self,
String property,
Object newValue) {
InvokerHelper.setProperty(self, property, newValue);
}
Allows the subscript operator to be used to set dynamically named property values.
bean[somePropertyNameExpression] = foo . The normal property notation
of groovy is neater and more concise but only works with property names which
are known at compile time. |
public static void putAt(List<T> self,
int idx,
T value) {
int size = self.size();
idx = normaliseIndex(idx, size);
if (idx < size) {
self.set(idx, value);
} else {
while (size < idx) {
self.add(size++, null);
}
self.add(idx, value);
}
}
A helper method to allow lists to work with subscript operators. |
public static void putAt(StringBuffer self,
IntRange range,
Object value) {
RangeInfo info = subListBorders(self.length(), range);
self.replace(info.from, info.to, value.toString());
}
Support the range subscript operator for StringBuffer. Index values are
treated as characters within the buffer. |
public static void putAt(StringBuffer self,
EmptyRange range,
Object value) {
RangeInfo info = subListBorders(self.length(), range);
self.replace(info.from, info.to, value.toString());
}
Support the range subscript operator for StringBuffer. |
public static void putAt(List self,
EmptyRange range,
Object value) {
RangeInfo info = subListBorders(self.size(), range);
List sublist = self.subList(info.from, info.to);
sublist.clear();
if (value instanceof Collection) {
Collection col = (Collection) value;
if (col.isEmpty()) return;
sublist.addAll(col);
} else {
sublist.add(value);
}
}
A helper method to allow lists to work with subscript operators. |
public static void putAt(List self,
EmptyRange range,
Collection value) {
putAt(self, range, (Object)value);
}
A helper method to allow lists to work with subscript operators. |
public static void putAt(List self,
IntRange range,
Collection col) {
List sublist = resizeListWithRangeAndGetSublist(self, range);
if (col.isEmpty()) return;
sublist.addAll(col);
}
List subscript assignment operator when given a range as the index and
the assignment operand is a collection.
Example: myList[3..5] = anotherList . Items in the given
range are relaced with items from the collection. |
public static void putAt(List self,
IntRange range,
Object value) {
List sublist = resizeListWithRangeAndGetSublist(self, range);
sublist.add(value);
}
List subscript assignment operator when given a range as the index.
Example: myList[3..5] = newItem . Items in the given
range are relaced with the operand. The value operand is
always treated as a single value. |
public static void putAt(List self,
List splice,
List values) {
if (splice.isEmpty()) {
if ( ! values.isEmpty() )
throw new IllegalArgumentException("Trying to replace 0 elements with "+values.size()+" elements");
return;
}
Object first = splice.iterator().next();
if (first instanceof Integer) {
if (values.size() != splice.size())
throw new IllegalArgumentException("Trying to replace "+splice.size()+" elements with "+values.size()+" elements");
Iterator< ? > valuesIter = values.iterator();
for (Object index : splice) {
putAt(self, (Integer) index, valuesIter.next());
}
} else {
throw new IllegalArgumentException("Can only index a List with another List of Integers, not a List of "+first.getClass().getName());
}
}
A helper method to allow lists to work with subscript operators. |
public static void putAt(List self,
List splice,
Object value) {
if (splice.isEmpty()) {
return;
}
Object first = splice.iterator().next();
if (first instanceof Integer) {
for (Object index : splice) {
self.set((Integer) index, value);
}
} else {
throw new IllegalArgumentException("Can only index a List with another List of Integers, not a List of "+first.getClass().getName());
}
}
A helper method to allow lists to work with subscript operators. |
public static V putAt(Map<K, V> self,
K key,
V value) {
self.put(key, value);
return value;
}
A helper method to allow lists to work with subscript operators |
public static void putAt(BitSet self,
IntRange range,
boolean value) {
int from = DefaultTypeTransformation.intUnbox(range.getFrom());
int to = DefaultTypeTransformation.intUnbox(range.getTo());
// If this is a backwards range, reverse the arguments to set.
if (from > to) {
int tmp = to;
to = from;
from = tmp;
}
self.set(from, to + 1, value);
}
Support assigning a range of values with a single assignment statement. |
public static void putAt(BitSet self,
int index,
boolean value) {
self.set(index, value);
}
Support subscript-style assignment for a BitSet. |
public static byte[] readBytes(File file) throws IOException {
byte[] bytes = new byte[(int) file.length()];
FileInputStream fileInputStream = new FileInputStream(file);
DataInputStream dis = new DataInputStream(fileInputStream);
try {
dis.readFully(bytes);
InputStream temp = dis;
dis = null;
temp.close();
} finally {
closeWithWarning(dis);
}
return bytes;
}
Reads the content of the file into a byte array. |
public static String readLine(Reader self) throws IOException {
if (self instanceof BufferedReader) {
BufferedReader br = (BufferedReader) self;
return br.readLine();
}
if (self.markSupported()) {
return readLineFromReaderWithMark(self);
}
return readLineFromReaderWithoutMark(self);
}
Read a single, whole line from the given Reader. |
public static String readLine(InputStream stream) throws IOException {
throw new DeprecationException(
"readLine() on InputStream is no longer supported. " +
"Either use a Reader or encapsulate the InputStream" +
" with a BufferedReader and an InputStreamReader."
);
} Deprecated! use - Reader#readLine instead please
Just throws a DeprecationException. DO NOT USE. It used to read a single, whole line from the given InputStream. |
public static List<String> readLines(String self) throws IOException {
return readLines(new StringReader(self));
}
Return the lines of a String as a List of Strings. |
public static List readLines(File file) throws IOException {
IteratorClosureAdapter closure = new IteratorClosureAdapter(file);
eachLine(file, closure);
return closure.asList();
}
Reads the file into a list of Strings, with one item for each line. |
public static List<String> readLines(Reader reader) throws IOException {
IteratorClosureAdapter closure = new IteratorClosureAdapter(reader);
eachLine(reader, closure);
return closure.asList();
}
Reads the reader into a list of Strings, with one entry for each line.
The reader is closed before this method returns. |
public static List readLines(InputStream stream) throws IOException {
return readLines(new BufferedReader(new InputStreamReader(stream)));
}
Reads the stream into a list, with one element for each line. |
public static String replaceAll(String self,
Pattern pattern,
String replacement) {
return pattern.matcher(self).replaceAll(replacement);
}
Replaces all substrings of a String that match the given
compiled regular expression with the given replacement.
Note that backslashes (\) and dollar signs ($) in the
replacement string may cause the results to be different than if it were
being treated as a literal replacement string; see
java.util.regex.Matcher#replaceAll .
Use java.util.regex.Matcher#quoteReplacement to suppress the special
meaning of these characters, if desired. |
public static String replaceAll(String self,
String regex,
Closure closure) {
final Matcher matcher = Pattern.compile(regex).matcher(self);
if (matcher.find()) {
final StringBuffer sb = new StringBuffer(self.length() + 16);
do {
int count = matcher.groupCount();
List groups = new ArrayList();
for (int i = 0; i < = count; i++) {
groups.add(matcher.group(i));
}
final String replacement = InvokerHelper.toString(closure.call(groups.toArray()));
matcher.appendReplacement(sb, Matcher.quoteReplacement(replacement));
} while (matcher.find());
matcher.appendTail(sb);
return sb.toString();
} else {
return self;
}
}
Replaces all occurrences of a captured group by the result of a closure on that text.
For examples,
assert "FOOBAR-FOOBAR-" == "foobar-FooBar-".replaceAll("(([fF][oO]{2})[bB]ar)", { Object[] it -> it[0].toUpperCase() })
Here,
it[0] is the global string of the matched group
it[1] is the first string in the matched group
it[2] is the second string in the matched group
assert "FOO-FOO-" == "foobar-FooBar-".replaceAll("(([fF][oO]{2})[bB]ar)", { x, y, z -> z.toUpperCase() })
Here,
x is the global string of the matched group
y is the first string in the matched group
z is the second string in the matched group
Note that unlike String.replaceAll(String regex, String replacement), where the replacement string
treats '$' and '\' specially (for group substitution), the result of the closure is converted to a string
and that value is used literally for the replacement. |
public static String replaceFirst(String self,
Pattern pattern,
String replacement) {
return pattern.matcher(self).replaceFirst(replacement);
}
Replaces the first substring of a String that matches the given
compiled regular expression with the given replacement.
Note that backslashes (\) and dollar signs ($) in the
replacement string may cause the results to be different than if it were
being treated as a literal replacement string; see
java.util.regex.Matcher#replaceFirst .
Use java.util.regex.Matcher#quoteReplacement to suppress the special
meaning of these characters, if desired. |
public static List respondsTo(Object self,
String name) {
return InvokerHelper.getMetaClass(self).respondsTo(self, name);
}
Returns an object satisfying Groovy truth if the implementing MetaClass responds to
a method with the given name regardless of the arguments.
Note that this method's return value is based on realised methods and does not take into account
objects or classes that implement invokeMethod or methodMissing
This method is "safe" in that it will always return a value and never throw an exception
|
public static List respondsTo(Object self,
String name,
Object[] argTypes) {
return InvokerHelper.getMetaClass(self).respondsTo(self, name, argTypes);
}
Returns an object satisfying Groovy truth if the implementing MetaClass responds to
a method with the given name and arguments types.
Note that this method's return value is based on realised methods and does not take into account
objects or classes that implement invokeMethod or methodMissing
This method is "safe" in that it will always return a value and never throw an exception
|
public static T[] reverse(T[] self) {
return (T[]) toList(new ReverseListIterator< T >(Arrays.asList(self))).toArray();
}
Reverse the items in an Object array. |
public static String reverse(String self) {
return new StringBuilder(self).reverse().toString();
}
Creates a new string which is the reverse (backwards) of this string |
public static List<T> reverse(List<T> self) {
int size = self.size();
List< T > answer = new ArrayList< T >(size);
ListIterator< T > iter = self.listIterator(size);
while (iter.hasPrevious()) {
answer.add(iter.previous());
}
return answer;
}
Reverses the list. The result is a new List with the identical contents
in reverse order. |
public static Iterator<T> reverse(Iterator<T> self) {
return new ReverseListIterator< T >(toList(self));
}
Reverses the iterator. The original iterator will become
exhausted of elements after determining the reversed values.
A new iterator for iterating through the reversed values is returned. |
public static List<T> reverseEach(List<T> self,
Closure closure) {
each(new ReverseListIterator< T >(self), closure);
return self;
}
Iterate over each element of the list in the reverse order. |
public static T[] reverseEach(T[] self,
Closure closure) {
each(new ReverseListIterator< T >(Arrays.asList(self)), closure);
return self;
}
Iterate over each element of the array in the reverse order. |
public static Number rightShift(Number self,
Number operand) {
return NumberMath.rightShift(self, operand);
}
Implementation of the right shift operator for integral types. Non integral
Number types throw UnsupportedOperationException. |
public static Number rightShiftUnsigned(Number self,
Number operand) {
return NumberMath.rightShiftUnsigned(self, operand);
}
Implementation of the right shift (unsigned) operator for integral types. Non integral
Number types throw UnsupportedOperationException. |
public static int round(Float number) {
return Math.round(number.floatValue());
}
|
public static long round(Double number) {
return Math.round(number);
}
|
public static float round(Float number,
int precision) {
return (float)(Math.floor(number.doubleValue()*Math.pow(10,precision)+0.5)/Math.pow(10,precision));
}
|
public static double round(Double number,
int precision) {
return Math.floor(number *Math.pow(10,precision)+0.5)/Math.pow(10,precision);
}
|
public static TimerTask runAfter(Timer timer,
int delay,
Closure closure) {
TimerTask timerTask = new TimerTask() {
public void run() {
closure.call();
}
};
timer.schedule(timerTask, delay);
return timerTask;
}
Allows a simple syntax for using timers. This timer will execute the
given closure after the given delay. |
public static void setIndex(Matcher matcher,
int idx) {
int count = getCount(matcher);
if (idx < -count || idx >= count) {
throw new IndexOutOfBoundsException("index is out of range " + (-count) + ".." + (count - 1) + " (index = " + idx + ")");
}
if (idx == 0) {
matcher.reset();
} else if (idx > 0) {
matcher.reset();
for (int i = 0; i < idx; i++) {
matcher.find();
}
} else if (idx < 0) {
matcher.reset();
idx += getCount(matcher);
for (int i = 0; i < idx; i++) {
matcher.find();
}
}
}
Set the position of the given Matcher to the given index. |
public static void setMetaClass(Class self,
MetaClass metaClass) {
final MetaClassRegistry metaClassRegistry = GroovySystem.getMetaClassRegistry();
if (metaClass == null)
metaClassRegistry.removeMetaClass(self);
else {
if (metaClass instanceof HandleMetaClass) {
metaClassRegistry.setMetaClass(self, ((HandleMetaClass)metaClass).getAdaptee());
} else {
metaClassRegistry.setMetaClass(self, metaClass);
}
if (self==NullObject.class) {
NullObject.getNullObject().setMetaClass(metaClass);
}
}
}
Sets the metaclass for a given class. |
public static void setMetaClass(Object self,
MetaClass metaClass) {
if (metaClass instanceof HandleMetaClass)
metaClass = ((HandleMetaClass)metaClass).getAdaptee();
if (self instanceof GroovyObject) {
((GroovyObject)self).setMetaClass(metaClass);
} else if (self instanceof Class) {
((MetaClassRegistryImpl)GroovySystem.getMetaClassRegistry()).setMetaClass((Class)self, metaClass);
} else {
((MetaClassRegistryImpl)GroovySystem.getMetaClassRegistry()).setMetaClass(self, metaClass);
}
}
Set the metaclass for an object |
public static void setText(File file,
String text) throws IOException {
write(file, text);
}
Synonym for write(text) allowing file.text = 'foo'. |
public static int size(Iterator self) {
int count = 0;
while (self.hasNext()) {
self.next();
count++;
}
return count;
}
Provide the standard Groovy size() method for Iterator .
The iterator will become exhausted of elements after determining the size value. |
public static int size(String text) {
return text.length();
}
Provide the standard Groovy size() method for String . |
public static int size(StringBuffer buffer) {
return buffer.length();
}
Provide the standard Groovy size() method for StringBuffer . |
public static long size(File self) {
return self.length();
}
Provide the standard Groovy size() method for File . |
public static long size(Matcher self) {
return getCount(self);
}
Provide the standard Groovy size() method for Matcher . |
public static int size(Object[] self) {
return self.length;
}
Provide the standard Groovy size() method for an array. |
public static int size(boolean[] array) {
return Array.getLength(array);
}
Allows arrays to behave similar to collections. |
public static int size(byte[] array) {
return Array.getLength(array);
}
Allows arrays to behave similar to collections. |
public static int size(char[] array) {
return Array.getLength(array);
}
Allows arrays to behave similar to collections. |
public static int size(short[] array) {
return Array.getLength(array);
}
Allows arrays to behave similar to collections. |
public static int size(int[] array) {
return Array.getLength(array);
}
Allows arrays to behave similar to collections. |
public static int size(long[] array) {
return Array.getLength(array);
}
Allows arrays to behave similar to collections. |
public static int size(float[] array) {
return Array.getLength(array);
}
Allows arrays to behave similar to collections. |
public static int size(double[] array) {
return Array.getLength(array);
}
Allows arrays to behave similar to collections. |
public static List<T> sort(Collection<T> self) {
List< T > answer = asList(self);
Collections.sort(answer, new NumberAwareComparator< T >());
return answer;
}
Sorts the given collection into a sorted list. The collection items are
assumed to be comparable. |
public static T[] sort(T[] self) {
Arrays.sort(self, new NumberAwareComparator< T >());
return self;
}
Sorts the given Object array into sorted order. The array items are
assumed to be comparable. |
public static Iterator<T> sort(Iterator<T> self) {
return sort(toList(self)).listIterator();
}
Sorts the given iterator items into a sorted iterator. The items are
assumed to be comparable. The original iterator will become
exhausted of elements after completing this method call. A new iterator
is produced that traverses the items in sorted order. |
public static SortedSet<T> sort(SortedSet<T> self) {
return self;
}
Avoids doing unnecessary work when sorting an already sorted set. |
public static Map<K, V> sort(Map<K, V> self,
Closure closure) {
Map< K, V > result = new LinkedHashMap< K, V >();
List< Map.Entry< K, V > > entries = asList(self.entrySet());
sort(entries, closure);
for (Map.Entry< K, V > entry : entries) {
result.put(entry.getKey(), entry.getValue());
}
return result;
}
Sorts the given map into a sorted map using
the closure as a comparator. |
public static Iterator<T> sort(Iterator<T> self,
Comparator<T> comparator) {
return sort(toList(self), comparator).listIterator();
}
Sorts the given iterator items into a sorted iterator using
the comparator. |
public static List<T> sort(Collection<T> self,
Comparator<T> comparator) {
List< T > list = asList(self);
Collections.sort(list, comparator);
return list;
}
Sorts the Collection using the given comparator. The elements are
sorted into a new list, and the existing collection is unchanged. |
public static T[] sort(T[] self,
Comparator<T> comparator) {
Arrays.sort(self, comparator);
return self;
}
Sorts the given Object array into sorted order using the given comparator. |
public static Iterator<T> sort(Iterator<T> self,
Closure closure) {
return sort(toList(self), closure).listIterator();
}
Sorts the given iterator items into a sorted iterator using
the Closure to determine the correct ordering. The original
iterator will be fully processed after the method call.
If the closure has two parameters
it is used like a traditional Comparator. I.e. it should compare
its two parameters for order, returning a negative integer,
zero, or a positive integer when the first parameter is less than,
equal to, or greater than the second respectively. Otherwise,
the Closure is assumed to take a single parameter and return a
Comparable (typically an Integer) which is then used for
further comparison. |
public static T[] sort(T[] self,
Closure closure) {
return (T[]) sort(toList(self), closure).toArray();
}
Sorts the given Object array into a newly created array using
the Closure to determine the correct ordering.
If the closure has two parameters
it is used like a traditional Comparator. I.e. it should compare
its two parameters for order, returning a negative integer,
zero, or a positive integer when the first parameter is less than,
equal to, or greater than the second respectively. Otherwise,
the Closure is assumed to take a single parameter and return a
Comparable (typically an Integer) which is then used for
further comparison. |
public static List<T> sort(Collection<T> self,
Closure closure) {
List< T > list = asList(self);
// use a comparator of one item or two
int params = closure.getMaximumNumberOfParameters();
if (params == 1) {
Collections.sort(list, new OrderBy< T >(closure));
} else {
Collections.sort(list, new ClosureComparator< T >(closure));
}
return list;
}
Sorts this Collection using
the closure to determine the correct ordering.
If the closure has two parameters
it is used like a traditional Comparator. I.e. it should compare
its two parameters for order, returning a negative integer,
zero, or a positive integer when the first parameter is less than,
equal to, or greater than the second respectively. Otherwise,
the Closure is assumed to take a single parameter and return a
Comparable (typically an Integer) which is then used for
further comparison. |
public static String[] split(String self) {
StringTokenizer st = new StringTokenizer(self);
String[] strings = new String[st.countTokens()];
for (int i = 0; i < strings.length; i++) {
strings[i] = st.nextToken();
}
return strings;
}
Convenience method to split a string (with whitespace as delimiter)
Like tokenize, but returns an Array of Strings instead of a List |
public static String[] split(GString self) {
return split(self.toString());
}
Convenience method to split a GString (with whitespace as delimiter). |
public static Collection split(Object self,
Closure closure) {
List accept = new ArrayList();
List reject = new ArrayList();
return split(closure, accept, reject, InvokerHelper.asIterator(self));
}
Splits all items into two lists based on the closure condition.
The first list contains all items matching the closure expression.
The second list all those that don't. |
public static Collection<T> split(Collection<T> self,
Closure closure) {
Collection< T > accept = createSimilarCollection(self);
Collection< T > reject = createSimilarCollection(self);
Iterator< T > iter = self.iterator();
return split(closure, accept, reject, iter);
}
Splits all items into two collections based on the closure condition.
The first list contains all items which match the closure expression.
The second list all those that don't. |
public static Object splitEachLine(File self,
String regex,
Closure closure) throws IOException {
return splitEachLine(newReader(self), regex, closure);
}
Iterates through this file line by line, splitting each line using
the given regex separator. For each line, the given closure is called with
a single parameter being the list of strings computed by splitting the line
around matches of the given regular expression.
Finally the resources used for processing the file are closed. |
public static Object splitEachLine(Reader self,
String regex,
Closure closure) throws IOException {
BufferedReader br;
Object result = null;
if (self instanceof BufferedReader)
br = (BufferedReader) self;
else
br = new BufferedReader(self);
try {
while (true) {
String line = br.readLine();
if (line == null) {
break;
} else {
List vals = Arrays.asList(line.split(regex));
result = closure.call(vals);
}
}
Reader temp = self;
self = null;
temp.close();
return result;
} finally {
closeWithWarning(self);
closeWithWarning(br);
}
}
Iterates through the given reader line by line, splitting each line using
the given regex separator. For each line, the given closure is called with
a single parameter being the list of strings computed by splitting the line
around matches of the given regular expression. The Reader is closed afterwards.
Here is an example:
def s = 'The 3 quick\nbrown 4 fox'
def result = ''
new StringReader(s).splitEachLine(/\d/){ parts ->
result += "${parts[0]}_${parts[1]}|"
}
assert result == 'The _ quick|brown _ fox|'
|
public static Object splitEachLine(InputStream stream,
String sep,
Closure closure) throws IOException {
return splitEachLine(new BufferedReader(new InputStreamReader(stream)), sep, closure);
}
Iterates through the given InputStream line by line, splitting each line using
the given separator. The list of tokens for each line is then passed to
the given closure. The stream is closed before the method returns. |
public static Object splitEachLine(String self,
String sep,
Closure closure) throws IOException {
final List< String > list = readLines(self);
Object result = null;
for (String line : list) {
List vals = Arrays.asList(line.split(sep));
result = closure.call(vals);
}
return result;
}
Iterates through the given String line by line, splitting each line using
the given separator. The list of tokens for each line is then passed to
the given closure. |
public static Object splitEachLine(InputStream stream,
String sep,
String charset,
Closure closure) throws IOException {
return splitEachLine(new BufferedReader(new InputStreamReader(stream, charset)), sep, closure);
}
Iterates through the given InputStream line by line using the specified
encoding, splitting each line using the given separator. The list of tokens
for each line is then passed to the given closure. Finally, the stream
is closed. |
public static SpreadMap spread(Map self) {
return toSpreadMap(self);
}
|
public static String sprintf(Object self,
String format,
Object[] values) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
PrintStream out = new PrintStream(outputStream);
out.printf(format, values);
return outputStream.toString();
}
Sprintf to a string (Only works with JDK1.5 or later). |
public static String sprintf(Object self,
String format,
Object arg) {
if (arg instanceof Object[]) {
return sprintf(self, format, (Object[]) arg);
}
if (arg instanceof List) {
return sprintf(self, format, ((List) arg).toArray());
}
if (!arg.getClass().isArray()) {
Object[] o = (Object[]) java.lang.reflect.Array.newInstance(arg.getClass(), 1);
o[0] = arg;
return sprintf(self, format, o);
}
Object[] ans;
String elemType = arg.getClass().getName();
if (elemType.equals("[I")) {
int[] ia = (int[]) arg;
ans = new Integer[ia.length];
for (int i = 0; i < ia.length; i++) {
ans[i] = ia[i];
}
} else if (elemType.equals("[C")) {
char[] ca = (char[]) arg;
ans = new Character[ca.length];
for (int i = 0; i < ca.length; i++) {
ans[i] = ca[i];
}
} else if (elemType.equals("[Z")) {
boolean[] ba = (boolean[]) arg;
ans = new Boolean[ba.length];
for (int i = 0; i < ba.length; i++) {
ans[i] = ba[i];
}
} else if (elemType.equals("[B")) {
byte[] ba = (byte[]) arg;
ans = new Byte[ba.length];
for (int i = 0; i < ba.length; i++) {
ans[i] = ba[i];
}
} else if (elemType.equals("[S")) {
short[] sa = (short[]) arg;
ans = new Short[sa.length];
for (int i = 0; i < sa.length; i++) {
ans[i] = sa[i];
}
} else if (elemType.equals("[F")) {
float[] fa = (float[]) arg;
ans = new Float[fa.length];
for (int i = 0; i < fa.length; i++) {
ans[i] = fa[i];
}
} else if (elemType.equals("[J")) {
long[] la = (long[]) arg;
ans = new Long[la.length];
for (int i = 0; i < la.length; i++) {
ans[i] = la[i];
}
} else if (elemType.equals("[D")) {
double[] da = (double[]) arg;
ans = new Double[da.length];
for (int i = 0; i < da.length; i++) {
ans[i] = da[i];
}
} else {
throw new RuntimeException("sprintf(String," + arg + ")");
}
return sprintf(self, format, ans);
}
Returns a formatted string using the specified format string and
arguments.
|
public static void step(Number self,
Number to,
Number stepNumber,
Closure closure) {
if (self instanceof BigDecimal || to instanceof BigDecimal || stepNumber instanceof BigDecimal) {
final BigDecimal zero = BigDecimal.valueOf(0, 1); // Same as "0.0".
BigDecimal self1 = (self instanceof BigDecimal) ? (BigDecimal) self : new BigDecimal(self.toString());
BigDecimal to1 = (to instanceof BigDecimal) ? (BigDecimal) to : new BigDecimal(to.toString());
BigDecimal stepNumber1 = (stepNumber instanceof BigDecimal) ? (BigDecimal) stepNumber : new BigDecimal(stepNumber.toString());
if (stepNumber1.compareTo(zero) > 0 && to1.compareTo(self1) > 0) {
for (BigDecimal i = self1; i.compareTo(to1) < 0; i = i.add(stepNumber1)) {
closure.call(i);
}
} else if (stepNumber1.compareTo(zero) < 0 && to1.compareTo(self1) < 0) {
for (BigDecimal i = self1; i.compareTo(to1) > 0; i = i.add(stepNumber1)) {
closure.call(i);
}
} else
throw new GroovyRuntimeException("Infinite loop in " + self1 + ".step(" + to1 + ", " + stepNumber1 + ")");
} else if (self instanceof BigInteger || to instanceof BigInteger || stepNumber instanceof BigInteger) {
final BigInteger zero = BigInteger.valueOf(0);
BigInteger self1 = (self instanceof BigInteger) ? (BigInteger) self : new BigInteger(self.toString());
BigInteger to1 = (to instanceof BigInteger) ? (BigInteger) to : new BigInteger(to.toString());
BigInteger stepNumber1 = (stepNumber instanceof BigInteger) ? (BigInteger) stepNumber : new BigInteger(stepNumber.toString());
if (stepNumber1.compareTo(zero) > 0 && to1.compareTo(self1) > 0) {
for (BigInteger i = self1; i.compareTo(to1) < 0; i = i.add(stepNumber1)) {
closure.call(i);
}
} else if (stepNumber1.compareTo(zero) < 0 && to1.compareTo(self1) < 0) {
for (BigInteger i = self1; i.compareTo(to1) > 0; i = i.add(stepNumber1)) {
closure.call(i);
}
} else
throw new GroovyRuntimeException("Infinite loop in " + self1 + ".step(" + to1 + ", " + stepNumber1 + ")");
} else {
int self1 = self.intValue();
int to1 = to.intValue();
int stepNumber1 = stepNumber.intValue();
if (stepNumber1 > 0 && to1 > self1) {
for (int i = self1; i < to1; i += stepNumber1) {
closure.call(i);
}
} else if (stepNumber1 < 0 && to1 < self1) {
for (int i = self1; i > to1; i += stepNumber1) {
closure.call(i);
}
} else
throw new GroovyRuntimeException("Infinite loop in " + self1 + ".step(" + to1 + ", " + stepNumber1 + ")");
}
}
Iterates from this number up to the given number using a step increment.
Each intermediate number is passed to the given closure. Example:
0.step( 10, 2 ) {
println it
}
Prints even numbers 0 through 8. |
public static Map<K, V> subMap(Map<K, V> map,
Collection<K> keys) {
Map< K, V > answer = new LinkedHashMap< K, V >(keys.size());
for (K key : keys) {
answer.put(key, map.get(key));
}
return answer;
}
Creates a sub-Map containing the given keys. This method is similar to
List.subList() but uses keys rather than index ranges. |
public static Set<T> subsequences(List<T> self) {
return GroovyCollections.subsequences(self);
}
Finds all non-null subsequences of a list.
E.g. [1, 2, 3].subsequences() would be:
[[1, 2, 3], [1, 3], [2, 3], [1, 2], [1], [2], [3]] |
public static Object sum(Collection self) {
return sum(self, null, true);
}
Sums the items in a collection. This is equivalent to invoking the
"plus" method on all items in the collection. |
public static Object sum(Iterator self) {
return sum(toList(self), null, true);
}
Sums the items from an Iterator. This is equivalent to invoking the
"plus" method on all items from the Iterator. The iterator will become
exhausted of elements after determining the sum value. |
public static Object sum(Collection self,
Object initialValue) {
return sum(self, initialValue, false);
}
Sums the items in a collection, adding the result to some initial value. |
public static Object sum(Iterator self,
Object initialValue) {
return sum(toList(self), initialValue, false);
}
Sums the items from an Iterator. This is equivalent to invoking the
"plus" method on all items from the Iterator. |
public static Object sum(Collection self,
Closure closure) {
return sum(self, null, closure, true);
}
Sums the result of apply a closure to each item of a collection.
coll.sum(closure) is equivalent to:
coll.collect(closure).sum() . |
public static Object sum(Collection self,
Object initialValue,
Closure closure) {
return sum(self, initialValue, closure, false);
}
Sums the result of apply a closure to each item of a collection to sum intial value.
coll.sum(closure) is equivalent to:
coll.collect(closure).sum() . |
public static List<T> tail(List<T> self) {
if (self.isEmpty()) {
throw new NoSuchElementException("Cannot access tail() for an empty List");
}
List< T > result = new ArrayList< T >(self);
result.remove(0);
return result;
}
Returns the items from the List excluding the first item. |
public static void times(Number self,
Closure closure) {
for (int i = 0, size = self.intValue(); i < size; i++) {
closure.call(i);
if (closure.getDirective() == Closure.DONE) {
break;
}
}
}
Executes the closure this many times, starting from zero. The current
index is passed to the closure each time.
Example:
10.times {
println it
}
Prints the numbers 0 through 9. |
public static String toArrayString(Object[] self) {
return (self == null) ? "null" : InvokerHelper.toArrayString(self);
}
Returns the string representation of the given array. The string
displays the contents of the array, similar to an array literal, i.e.
{1, 2, "a"} . |
public static BigDecimal toBigDecimal(String self) {
return new BigDecimal(self.trim());
}
Parse a String into a BigDecimal |
public static BigDecimal toBigDecimal(Number self) {
// Quick method for scalars.
if ((self instanceof Long)
|| (self instanceof Integer)
|| (self instanceof Short)
|| (self instanceof Byte))
{
return BigDecimal.valueOf(self.longValue());
}
return new BigDecimal(self.toString());
}
Transform a Number into a BigDecimal |
public static BigInteger toBigInteger(String self) {
return new BigInteger(self.trim());
}
Parse a String into a BigInteger |
public static BigInteger toBigInteger(Number self) {
if (self instanceof BigInteger) {
return (BigInteger) self;
} else if (self instanceof BigDecimal) {
return ((BigDecimal) self).toBigInteger();
} else if (self instanceof Double) {
return new BigDecimal((Double)self).toBigInteger();
} else if (self instanceof Float) {
return new BigDecimal((Float)self).toBigInteger();
} else {
return new BigInteger(Long.toString(self.longValue()));
}
}
Transform this Number into a BigInteger. |
public static Boolean toBoolean(String self) {
final String trimmed = self.trim();
if ("true".equalsIgnoreCase(trimmed) || "y".equalsIgnoreCase(trimmed) || "1".equals(trimmed)) {
return Boolean.TRUE;
} else {
return Boolean.FALSE;
}
}
Converts the given string into a Boolean object.
If the trimmed string is "true", "y" or "1" (ignoring case)
then the result is true othewrwise it is false. |
public static Character toCharacter(String self) {
return self.charAt(0);
}
Converts the given string into a Character object
using the first character in the string. |
public static Double toDouble(String self) {
return Double.valueOf(self.trim());
}
Parse a String into a Double |
public static Double toDouble(Number self) {
// Conversions in which all decimal digits are known to be good.
if ((self instanceof Double)
|| (self instanceof Long)
|| (self instanceof Integer)
|| (self instanceof Short)
|| (self instanceof Byte))
{
return self.doubleValue();
}
// Chances are this is a Float or a Big.
// With Float we're extending binary precision and that gets ugly in decimal.
// If we used Float.doubleValue() on 0.1f we get 0.10000000149011612.
// Note that this is different than casting '(double) 0.1f' which will do the
// binary extension just like in Java.
// With Bigs and other unkowns, this is likely to be the same.
return Double.valueOf(self.toString());
}
Transform a Number into a Double |
public static Float toFloat(String self) {
return Float.valueOf(self.trim());
}
Parse a String into a Float |
public static Float toFloat(Number self) {
return self.floatValue();
}
Transform a Number into a Float |
public static Integer toInteger(String self) {
return Integer.valueOf(self.trim());
}
Parse a String into an Integer |
public static Integer toInteger(Number self) {
return self.intValue();
}
Transform a Number into an Integer |
public static List<T> toList(Collection<T> self) {
List< T > answer = new ArrayList< T >(self.size());
answer.addAll(self);
return answer;
}
Convert a collection to a List. |
public static List<T> toList(Iterator<T> self) {
List< T > answer = new ArrayList< T >();
while (self.hasNext()) {
answer.add(self.next());
}
return answer;
}
Convert an iterator to a List. The iterator will become
exhausted of elements after making this conversion. |
public static List<T> toList(Enumeration<T> self) {
List< T > answer = new ArrayList< T >();
while (self.hasMoreElements()) {
answer.add(self.nextElement());
}
return answer;
}
Convert an enumeration to a List. |
public static List<T> toList(T[] array) {
return new ArrayList< T >(Arrays.asList(array));
}
Allows conversion of arrays into a mutable List. |
public static List<Byte> toList(byte[] array) {
return DefaultTypeTransformation.primitiveArrayToList(array);
}
Converts this array to a List of the same size, with each element
added to the list. |
public static List<Boolean> toList(boolean[] array) {
return DefaultTypeTransformation.primitiveArrayToList(array);
}
Converts this array to a List of the same size, with each element
added to the list. |
public static List<Character> toList(char[] array) {
return DefaultTypeTransformation.primitiveArrayToList(array);
}
Converts this array to a List of the same size, with each element
added to the list. |
public static List<Short> toList(short[] array) {
return DefaultTypeTransformation.primitiveArrayToList(array);
}
Converts this array to a List of the same size, with each element
added to the list. |
public static List<Integer> toList(int[] array) {
return DefaultTypeTransformation.primitiveArrayToList(array);
}
Converts this array to a List of the same size, with each element
added to the list. |
public static List<Long> toList(long[] array) {
return DefaultTypeTransformation.primitiveArrayToList(array);
}
Converts this array to a List of the same size, with each element
added to the list. |
public static List<Float> toList(float[] array) {
return DefaultTypeTransformation.primitiveArrayToList(array);
}
Converts this array to a List of the same size, with each element
added to the list. |
public static List<Double> toList(double[] array) {
return DefaultTypeTransformation.primitiveArrayToList(array);
}
Converts this array to a List of the same size, with each element
added to the list. |
public static List<String> toList(String self) {
int size = self.length();
List< String > answer = new ArrayList< String >(size);
for (int i = 0; i < size; i++) {
answer.add(self.substring(i, i + 1));
}
return answer;
}
Converts the given String into a List of strings of one character. |
public static String toListString(Collection self) {
return (self == null) ? "null" : InvokerHelper.toListString(self);
}
Returns the string representation of the given list. The string
displays the contents of the list, similar to a list literal, i.e.
[1, 2, a] . |
public static Long toLong(String self) {
return Long.valueOf(self.trim());
}
Parse a String into a Long |
public static Long toLong(Number self) {
return self.longValue();
}
Transform a Number into a Long |
public static char toLowerCase(Character self) {
return Character.toLowerCase(self);
}
Converts the character to lowercase.
Synonym for 'Character.toLowerCase(this)'. |
public static String toMapString(Map self) {
return (self == null) ? "null" : InvokerHelper.toMapString(self);
}
Returns the string representation of this map. The string displays the
contents of the map, i.e. [one:1, two:2, three:3] . |
public static GroovyRowResult toRowResult(ResultSet rs) throws SQLException {
return SqlGroovyMethods.toRowResult(rs);
} Deprecated! moved - to org.codehaus.groovy.runtime.SqlGroovyMethods#toRowResult(java.sql.ResultSet)
Returns a GroovyRowResult given a ResultSet. |
public static Short toShort(String self) {
return Short.valueOf(self.trim());
}
Parse a String into a Short |
public static SpreadMap toSpreadMap(Map self) {
if (self == null)
throw new GroovyRuntimeException("Fail to convert Map to SpreadMap, because it is null.");
else
return new SpreadMap(self);
}
Returns a new SpreadMap from this map.
For examples, if there is defined a function like as
def fn(a, b, c, d) { return a + b + c + d }
, then all of the following three have the same meaning.
println fn(a:1, [b:2, c:3].toSpreadMap(), d:4)
println fn(a:1, *:[b:2, c:3], d:4)
println fn(a:1, b:2, c:3, d:4)
|
public static SpreadMap toSpreadMap(Object[] self) {
if (self == null)
throw new GroovyRuntimeException("Fail to convert Object[] to SpreadMap, because it is null.");
else if (self.length % 2 != 0)
throw new GroovyRuntimeException("Fail to convert Object[] to SpreadMap, because it's size is not even.");
else
return new SpreadMap(self);
}
Creates a spreadable map from this array. |
public static String toString(boolean[] self) {
return InvokerHelper.toString(self);
}
Returns the string representation of the given array. |
public static String toString(byte[] self) {
return InvokerHelper.toString(self);
}
Returns the string representation of the given array. |
public static String toString(char[] self) {
return InvokerHelper.toString(self);
}
Returns the string representation of the given array. |
public static String toString(short[] self) {
return InvokerHelper.toString(self);
}
Returns the string representation of the given array. |
public static String toString(int[] self) {
return InvokerHelper.toString(self);
}
Returns the string representation of the given array. |
public static String toString(long[] self) {
return InvokerHelper.toString(self);
}
Returns the string representation of the given array. |
public static String toString(float[] self) {
return InvokerHelper.toString(self);
}
Returns the string representation of the given array. |
public static String toString(double[] self) {
return InvokerHelper.toString(self);
}
Returns the string representation of the given array. |
public static String toString(AbstractMap self) {
return toMapString(self);
}
Returns the string representation of the given map. |
public static String toString(AbstractCollection self) {
return toListString(self);
}
Returns the string representation of the given collection. The string
displays the contents of the collection, i.e.
[1, 2, a] . |
public static String toString(Object[] self) {
return toArrayString(self);
}
Returns the string representation of this array's contents. |
public static String toString(Object value) {
return InvokerHelper.toString(value);
}
Create a String representation of this object. |
public static URI toURI(String self) throws URISyntaxException {
return new URI(self);
}
Transforms a String representing a URI into a URI object. |
public static URL toURL(String self) throws MalformedURLException {
return new URL(self);
}
Transforms a String representing a URL into a URL object. |
public static char toUpperCase(Character self) {
return Character.toUpperCase(self);
}
Converts the character to uppercase.
Synonym for 'Character.toUpperCase(this)'. |
public static List tokenize(String self) {
return InvokerHelper.asList(new StringTokenizer(self));
}
Tokenize a String (with a whitespace as the delimiter). |
public static List tokenize(String self,
String token) {
return InvokerHelper.asList(new StringTokenizer(self, token));
}
Tokenize a String based on the given string delimiter. |
public static void transformChar(Reader self,
Writer writer,
Closure closure) throws IOException {
int c;
try {
char[] chars = new char[1];
while ((c = self.read()) != -1) {
chars[0] = (char) c;
writer.write((String) closure.call(new String(chars)));
}
writer.flush();
Writer temp2 = writer;
writer = null;
temp2.close();
Reader temp1 = self;
self = null;
temp1.close();
} finally {
closeWithWarning(self);
closeWithWarning(writer);
}
}
Transforms each character from this reader by passing it to the given
closure. The Closure should return each transformed character, which
will be passed to the Writer. The reader and writer will be both be
closed before this method returns. |
public static void transformLine(Reader reader,
Writer writer,
Closure closure) throws IOException {
BufferedReader br = new BufferedReader(reader);
BufferedWriter bw = new BufferedWriter(writer);
String line;
try {
while ((line = br.readLine()) != null) {
Object o = closure.call(line);
if (o != null) {
bw.write(o.toString());
bw.newLine();
}
}
bw.flush();
Writer temp2 = writer;
writer = null;
temp2.close();
Reader temp1 = reader;
reader = null;
temp1.close();
} finally {
closeWithWarning(br);
closeWithWarning(reader);
closeWithWarning(bw);
closeWithWarning(writer);
}
}
Transforms the lines from a reader with a Closure and
write them to a writer. Both Reader and Writer are
closed after the operation. |
public static List transpose(List self) {
return GroovyCollections.transpose(self);
}
Adds GroovyCollections#transpose(List) as a method on lists. |
public static float trunc(Float number) {
return (float)Math.floor(number.doubleValue());
}
|
public static double trunc(Double number) {
return Math.floor(number);
}
|
public static float trunc(Float number,
int precision) {
return (float)(Math.floor(number.doubleValue()*Math.pow(10,precision))/Math.pow(10,precision));
}
|
public static double trunc(Double number,
int precision) {
return Math.floor(number *Math.pow(10,precision))/Math.pow(10,precision);
}
|
public static Number unaryMinus(Number left) {
return NumberMath.unaryMinus(left);
}
Negates the number. Equivalent to the '-' operator when it preceeds
a single operand, i.e. -10 |
public static Iterator<T> unique(Iterator<T> self) {
return toList(unique(toList(self))).listIterator();
}
Returns an iterator equivalent to this iterator all duplicated items removed
by using the default comparator. The original iterator will become
exhausted of elements after determining the unique values. A new iterator
for the unique values will be returned. |
public static Collection<T> unique(Collection<T> self) {
if (self instanceof Set)
return self;
List< T > answer = new ArrayList< T >();
NumberAwareComparator< T > numberAwareComparator = new NumberAwareComparator< T >();
for (T t : self) {
boolean duplicated = false;
for (T t2 : answer) {
if (numberAwareComparator.compare(t, t2) == 0) {
duplicated = true;
break;
}
}
if (!duplicated)
answer.add(t);
}
self.clear();
self.addAll(answer);
return self;
}
Modifies this collection to remove all duplicated items, using the
default comparator. |
public static Iterator<T> unique(Iterator<T> self,
Closure closure) {
return toList(unique(toList(self), closure)).listIterator();
}
Returns an iterator equivalent to this iterator but with all duplicated items
removed by using a Closure to determine duplicate (equal) items.
The original iterator will be fully processed after the call.
If the closure takes a
single parameter, the argument passed will be each element, and the
closure should return a value used for comparison (either using
Comparable#compareTo(Object) or Object#equals(Object) ).
If the closure takes two parameters, two items from the Iterator
will be passed as arguments, and the closure should return an
int value (with 0 indicating the items are not unique). |
public static Collection<T> unique(Collection<T> self,
Closure closure) {
// use a comparator of one item or two
int params = closure.getMaximumNumberOfParameters();
if (params == 1) {
unique(self, new OrderBy< T >(closure));
} else {
unique(self, new ClosureComparator< T >(closure));
}
return self;
}
A convenience method for making a collection unique using a Closure
to determine duplicate (equal) items.
If the closure takes a single parameter, the
argument passed will be each element, and the closure
should return a value used for comparison (either using
Comparable#compareTo(Object) or Object#equals(Object) ).
If the closure takes two parameters, two items from the collection
will be passed as arguments, and the closure should return an
int value (with 0 indicating the items are not unique). |
public static Iterator<T> unique(Iterator<T> self,
Comparator<T> comparator) {
return toList(unique(toList(self), comparator)).listIterator();
}
Returns an iterator equivalent to this iterator with all duplicated
items removed by using the supplied comparator. |
public static Collection<T> unique(Collection<T> self,
Comparator<T> comparator) {
List< T > answer = new ArrayList< T >();
for (T t : self) {
boolean duplicated = false;
for (T t2 : answer) {
if (comparator.compare(t, t2) == 0) {
duplicated = true;
break;
}
}
if (!duplicated)
answer.add(t);
}
self.clear();
self.addAll(answer);
return self;
}
Remove all duplicates from a given Collection.
Works on the receiver object and returns it.
The order of members in the Collection are compared by the given Comparator.
For each duplicate, the first member which is returned
by the given Collection's iterator is retained, but all other ones are removed.
The given Collection's original order is preserved.
class Person {
def fname, lname
public String toString() {
return fname + " " + lname
}
}
class PersonComparator implements Comparator {
public int compare(Object o1, Object o2) {
Person p1 = (Person) o1
Person p2 = (Person) o2
if (p1.lname != p2.lname)
return p1.lname.compareTo(p2.lname)
else
return p1.fname.compareTo(p2.fname)
}
public boolean equals(Object obj) {
return this.equals(obj)
}
}
Person a = new Person(fname:"John", lname:"Taylor")
Person b = new Person(fname:"Clark", lname:"Taylor")
Person c = new Person(fname:"Tom", lname:"Cruz")
Person d = new Person(fname:"Clark", lname:"Taylor")
def list = [a, b, c, d]
List list2 = list.unique(new PersonComparator())
assert( list2 == list && list == [a, b, c] )
|
public static void upto(Number self,
Number to,
Closure closure) {
int self1 = self.intValue();
int to1 = to.intValue();
if (self1 < = to1) {
for (int i = self1; i < = to1; i++) {
closure.call(i);
}
} else
throw new GroovyRuntimeException("Infinite loop in " + self + ".upto(" + to + ")");
}
Iterates from this number up to the given number, inclusive,
incrementing by one each time. |
public static void upto(long self,
Number to,
Closure closure) {
long to1 = to.longValue();
if (self < = to1) {
for (long i = self; i < = to1; i++) {
closure.call(i);
}
} else
throw new GroovyRuntimeException("Infinite loop in " + self + ".upto(" + to + ")");
}
Iterates from this number up to the given number, inclusive,
incrementing by one each time. |
public static void upto(Long self,
Number to,
Closure closure) {
long to1 = to.longValue();
if (self < = to1) {
for (long i = self; i < = to1; i++) {
closure.call(i);
}
} else
throw new GroovyRuntimeException("Infinite loop in " + self + ".upto(" + to + ")");
}
Iterates from this number up to the given number, inclusive,
incrementing by one each time. |
public static void upto(float self,
Number to,
Closure closure) {
float to1 = to.floatValue();
if (self < = to1) {
for (float i = self; i < = to1; i++) {
closure.call(i);
}
} else
throw new GroovyRuntimeException("Infinite loop in " + self + ".upto(" + to + ")");
}
Iterates from this number up to the given number, inclusive,
incrementing by one each time. |
public static void upto(Float self,
Number to,
Closure closure) {
float to1 = to.floatValue();
if (self < = to1) {
for (float i = self; i < = to1; i++) {
closure.call(i);
}
} else
throw new GroovyRuntimeException("Infinite loop in " + self + ".upto(" + to + ")");
}
Iterates from this number up to the given number, inclusive,
incrementing by one each time. |
public static void upto(double self,
Number to,
Closure closure) {
double to1 = to.doubleValue();
if (self < = to1) {
for (double i = self; i < = to1; i++) {
closure.call(i);
}
} else
throw new GroovyRuntimeException("Infinite loop in " + self + ".upto(" + to + ")");
}
Iterates from this number up to the given number, inclusive,
incrementing by one each time. |
public static void upto(Double self,
Number to,
Closure closure) {
double to1 = to.doubleValue();
if (self < = to1) {
for (double i = self; i < = to1; i++) {
closure.call(i);
}
} else
throw new GroovyRuntimeException("Infinite loop in " + self + ".upto(" + to + ")");
}
Iterates from this number up to the given number, inclusive,
incrementing by one each time. |
public static void upto(BigInteger self,
Number to,
Closure closure) {
if (to instanceof BigDecimal) {
final BigDecimal one = BigDecimal.valueOf(10, 1);
BigDecimal self1 = new BigDecimal(self);
BigDecimal to1 = (BigDecimal) to;
if (self1.compareTo(to1) < = 0) {
for (BigDecimal i = self1; i.compareTo(to1) < = 0; i = i.add(one)) {
closure.call(i);
}
} else
throw new GroovyRuntimeException("Infinite loop in " + self + ".upto(" + to + ")");
} else if (to instanceof BigInteger) {
final BigInteger one = BigInteger.valueOf(1);
BigInteger to1 = (BigInteger) to;
if (self.compareTo(to1) < = 0) {
for (BigInteger i = self; i.compareTo(to1) < = 0; i = i.add(one)) {
closure.call(i);
}
} else
throw new GroovyRuntimeException("Infinite loop in " + self + ".upto(" + to + ")");
} else {
final BigInteger one = BigInteger.valueOf(1);
BigInteger to1 = new BigInteger(to.toString());
if (self.compareTo(to1) < = 0) {
for (BigInteger i = self; i.compareTo(to1) < = 0; i = i.add(one)) {
closure.call(i);
}
} else
throw new GroovyRuntimeException("Infinite loop in " + self + ".upto(" + to + ")");
}
}
Iterates from this number up to the given number, inclusive,
incrementing by one each time. Example:
0.upto( 10 ) {
println it
}
Prints numbers 0 to 10 |
public static void upto(BigDecimal self,
Number to,
Closure closure) {
final BigDecimal one = BigDecimal.valueOf(10, 1); // That's what you get for "1.0".
if (to instanceof BigDecimal) {
BigDecimal to1 = (BigDecimal) to;
if (self.compareTo(to1) < = 0) {
for (BigDecimal i = self; i.compareTo(to1) < = 0; i = i.add(one)) {
closure.call(i);
}
} else
throw new GroovyRuntimeException("Infinite loop in " + self + ".upto(" + to + ")");
} else if (to instanceof BigInteger) {
BigDecimal to1 = new BigDecimal((BigInteger) to);
if (self.compareTo(to1) < = 0) {
for (BigDecimal i = self; i.compareTo(to1) < = 0; i = i.add(one)) {
closure.call(i);
}
} else
throw new GroovyRuntimeException("Infinite loop in " + self + ".upto(" + to + ")");
} else {
BigDecimal to1 = new BigDecimal(to.toString());
if (self.compareTo(to1) < = 0) {
for (BigDecimal i = self; i.compareTo(to1) < = 0; i = i.add(one)) {
closure.call(i);
}
} else
throw new GroovyRuntimeException("Infinite loop in " + self + ".upto(" + to + ")");
}
}
Iterates from this number up to the given number, inclusive,
incrementing by one each time.
0.1.upto( 10 ) {
println it
}
Prints numbers 0.1, 1.1, 2.1... to 9.1 |
public static Object use(Object self,
Object[] array) {
if (array.length < 2)
throw new IllegalArgumentException(
"Expecting at least 2 arguments, a category class and a Closure");
Closure closure;
try {
closure = (Closure) array[array.length - 1];
} catch (ClassCastException e) {
throw new IllegalArgumentException("Expecting a Closure to be the last argument");
}
List< Class > list = new ArrayList< Class >(array.length - 1);
for (int i = 0; i < array.length - 1; ++i) {
Class categoryClass;
try {
categoryClass = (Class) array[i];
} catch (ClassCastException e) {
throw new IllegalArgumentException("Expecting a Category Class for argument " + i);
}
list.add(categoryClass);
}
return GroovyCategorySupport.use(list, closure);
}
Allows you to use a list of categories, specifying the list as varargs.
use(CategoryClass1, CategoryClass2) { ... }
This method saves having to wrap the the category
classes in a list. |
public static Object use(Object self,
Class categoryClass,
Closure closure) {
return GroovyCategorySupport.use(categoryClass, closure);
}
|
public static Object use(Object self,
List<Class> categoryClassList,
Closure closure) {
return GroovyCategorySupport.use(categoryClassList, closure);
}
Scoped use method with list of categories. |
public static void waitForOrKill(Process self,
long numberOfMillis) {
ProcessRunner runnable = new ProcessRunner(self);
Thread thread = new Thread(runnable);
thread.start();
runnable.waitForOrKill(numberOfMillis);
}
Wait for the process to finish during a certain amount of time, otherwise stops the process. |
public static void waitForProcessOutput(Process self) {
waitForProcessOutput(self, (OutputStream)null, (OutputStream)null);
}
Gets the output and error streams from a process and reads them
to keep the process from blocking due to a full output buffer.
The stream data is thrown away but blocking due to a full output buffer is avoided.
Use this method if you don't care about the standard or error output and just
want the process to run silently - use carefully however, because since the stream
data is thrown away, it might be difficult to track down when something goes wrong.
For this, two Threads are started, but join()ed, so we wait. |
public static void waitForProcessOutput(Process self,
StringBuffer output,
StringBuffer error) {
Thread tout = consumeProcessOutputStream(self, output);
Thread terr = consumeProcessErrorStream(self, error);
try { tout.join(); } catch (InterruptedException ignore) {}
try { terr.join(); } catch (InterruptedException ignore) {}
}
Gets the output and error streams from a process and reads them
to keep the process from blocking due to a full output buffer.
The processed stream data is appended to the supplied StringBuffer.
For this, two Threads are started, but join()ed, so we wait. |
public static void waitForProcessOutput(Process self,
OutputStream output,
OutputStream error) {
Thread tout = consumeProcessOutputStream(self, output);
Thread terr = consumeProcessErrorStream(self, error);
try { tout.join(); } catch (InterruptedException ignore) {}
try { terr.join(); } catch (InterruptedException ignore) {}
}
Gets the output and error streams from a process and reads them
to keep the process from blocking due to a full output buffer.
The processed stream data is appended to the supplied OutputStream.
For this, two Threads are started, but join()ed, so we wait. |
public static Object with(Object self,
Closure closure) {
final Closure clonedClosure = (Closure) closure.clone();
clonedClosure.setResolveStrategy(Closure.DELEGATE_FIRST);
clonedClosure.setDelegate(self);
return clonedClosure.call(self);
}
Allows the closure to be called for the object reference self |
public static Object withDataInputStream(File file,
Closure closure) throws IOException {
return withStream(newDataInputStream(file), closure);
}
Create a new DataInputStream for this file and passes it into the closure.
This method ensures the stream is closed after the closure returns. |
public static Object withDataOutputStream(File file,
Closure closure) throws IOException {
return withStream(newDataOutputStream(file), closure);
}
Create a new DataOutputStream for this file and passes it into the closure.
This method ensures the stream is closed after the closure returns. |
public static Object withInputStream(File file,
Closure closure) throws IOException {
return withStream(newInputStream(file), closure);
}
Create a new InputStream for this file and passes it into the closure.
This method ensures the stream is closed after the closure returns. |
public static Object withInputStream(URL url,
Closure closure) throws IOException {
return withStream(newInputStream(url), closure);
}
Creates a new InputStream for this URL and passes it into the closure.
This method ensures the stream is closed after the closure returns. |
public static Object withObjectInputStream(File file,
Closure closure) throws IOException {
return withStream(newObjectInputStream(file), closure);
}
Create a new ObjectInputStream for this file and pass it to the closure.
This method ensures the stream is closed after the closure returns. |
public static Object withObjectInputStream(InputStream inputStream,
Closure closure) throws IOException {
return withStream(newObjectInputStream(inputStream), closure);
}
Create a new ObjectInputStream for this file and pass it to the closure.
This method ensures the stream is closed after the closure returns. |
public static Object withObjectInputStream(File file,
ClassLoader classLoader,
Closure closure) throws IOException {
return withStream(newObjectInputStream(file, classLoader), closure);
}
Create a new ObjectInputStream for this file associated with the given class loader and pass it to the closure.
This method ensures the stream is closed after the closure returns. |
public static Object withObjectInputStream(InputStream inputStream,
ClassLoader classLoader,
Closure closure) throws IOException {
return withStream(newObjectInputStream(inputStream, classLoader), closure);
}
Create a new ObjectInputStream for this file and pass it to the closure.
This method ensures the stream is closed after the closure returns. |
public static Object withObjectOutputStream(File file,
Closure closure) throws IOException {
return withStream(newObjectOutputStream(file), closure);
}
Create a new ObjectOutputStream for this file and then pass it to the
closure. This method ensures the stream is closed after the closure
returns. |
public static Object withObjectOutputStream(OutputStream outputStream,
Closure closure) throws IOException {
return withStream(newObjectOutputStream(outputStream), closure);
}
Create a new ObjectOutputStream for this output stream and then pass it to the
closure. This method ensures the stream is closed after the closure
returns. |
public static Object withObjectStreams(Socket socket,
Closure closure) throws IOException {
InputStream input = socket.getInputStream();
OutputStream output = socket.getOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(output);
ObjectInputStream ois = new ObjectInputStream(input);
try {
Object result = closure.call(new Object[]{ois, oos});
InputStream temp1 = ois;
ois = null;
temp1.close();
temp1 = input;
input = null;
temp1.close();
OutputStream temp2 = oos;
oos = null;
temp2.close();
temp2 = output;
output = null;
temp2.close();
return result;
} finally {
closeWithWarning(ois);
closeWithWarning(input);
closeWithWarning(oos);
closeWithWarning(output);
}
}
Creates an InputObjectStream and an OutputObjectStream from a Socket, and
passes them to the closure. The streams will be closed after the closure
returns, even if an exception is thrown. |
public static Object withOutputStream(File file,
Closure closure) throws IOException {
return withStream(newOutputStream(file), closure);
}
Creates a new OutputStream for this file and passes it into the closure.
This method ensures the stream is closed after the closure returns. |
public static void withOutputStream(Process self,
Closure closure) {
new Thread(new Runnable() {
public void run() {
try {
withStream(new BufferedOutputStream(getOut(self)), closure);
} catch (IOException e) {
throw new GroovyRuntimeException("exception while reading process stream", e);
}
}
}).start();
}
Creates a new buffered OutputStream as stdin for this process,
passes it to the closure, and ensures the stream is flushed
and closed after the closure returns.
A new Thread is started, so this method will return immediately. |
public static Object withPrintWriter(File file,
Closure closure) throws IOException {
return withWriter(newPrintWriter(file), closure);
}
Create a new PrintWriter for this file which is then
passed it into the given closure. This method ensures its the writer
is closed after the closure returns. |
public static Object withPrintWriter(Writer writer,
Closure closure) throws IOException {
return withWriter(newPrintWriter(writer), closure);
}
Create a new PrintWriter with a specified charset for
this file. The writer is passed to the closure, and will be closed
before this method returns. |
public static Object withPrintWriter(File file,
String charset,
Closure closure) throws IOException {
return withWriter(newPrintWriter(file, charset), closure);
}
Create a new PrintWriter with a specified charset for
this file. The writer is passed to the closure, and will be closed
before this method returns. |
public static Object withReader(File file,
Closure closure) throws IOException {
return withReader(newReader(file), closure);
}
Create a new BufferedReader for this file and then
passes it into the closure, ensuring the reader is closed after the
closure returns. |
public static Object withReader(Reader reader,
Closure closure) throws IOException {
try {
Object result = closure.call(reader);
Reader temp = reader;
reader = null;
temp.close();
return result;
} finally {
closeWithWarning(reader);
}
}
Allows this reader to be used within the closure, ensuring that it
is closed before this method returns. |
public static Object withReader(URL url,
Closure closure) throws IOException {
return withReader(url.openConnection().getInputStream(), closure);
}
Helper method to create a new BufferedReader for a URL and then
passes it to the closure. The reader is closed after the closure returns. |
public static Object withReader(InputStream in,
Closure closure) throws IOException {
return withReader(new InputStreamReader(in), closure);
}
Helper method to create a new Reader for a stream and then
passes it into the closure. The reader (and this stream) is closed after
the closure returns. |
public static Object withReader(File file,
String charset,
Closure closure) throws IOException {
return withReader(newReader(file, charset), closure);
}
Create a new BufferedReader for this file using the specified charset and then
passes it into the closure, ensuring the reader is closed after the
closure returns. |
public static Object withReader(URL url,
String charset,
Closure closure) throws IOException {
return withReader(url.openConnection().getInputStream(), charset, closure);
}
Helper method to create a new Reader for a URL and then
passes it to the closure. The reader is closed after the closure returns. |
public static Object withReader(InputStream in,
String charset,
Closure closure) throws IOException {
return withReader(new InputStreamReader(in, charset), closure);
}
Helper method to create a new Reader for a stream and then
passes it into the closure. The reader (and this stream) is closed after
the closure returns. |
public static Object withStream(InputStream stream,
Closure closure) throws IOException {
try {
Object result = closure.call(stream);
InputStream temp = stream;
stream = null;
temp.close();
return result;
} finally {
closeWithWarning(stream);
}
}
Allows this input stream to be used within the closure, ensuring that it
is flushed and closed before this method returns. |
public static Object withStream(OutputStream os,
Closure closure) throws IOException {
try {
Object result = closure.call(os);
os.flush();
OutputStream temp = os;
os = null;
temp.close();
return result;
} finally {
closeWithWarning(os);
}
}
Passes this OutputStream to the closure, ensuring that the stream
is closed after the closure returns, regardless of errors. |
public static Object withStreams(Socket socket,
Closure closure) throws IOException {
InputStream input = socket.getInputStream();
OutputStream output = socket.getOutputStream();
try {
Object result = closure.call(new Object[]{input, output});
InputStream temp1 = input;
input = null;
temp1.close();
OutputStream temp2 = output;
output = null;
temp2.close();
return result;
} finally {
closeWithWarning(input);
closeWithWarning(output);
}
}
Passes the Socket's InputStream and OutputStream to the closure. The
streams will be closed after the closure returns, even if an exception
is thrown. |
public static Object withWriter(File file,
Closure closure) throws IOException {
return withWriter(newWriter(file), closure);
}
Creates a new BufferedWriter for this file, passes it to the closure, and
ensures the stream is flushed and closed after the closure returns. |
public static Object withWriter(Writer writer,
Closure closure) throws IOException {
try {
Object result = closure.call(writer);
try {
writer.flush();
} catch (IOException e) {
// try to continue even in case of error
}
Writer temp = writer;
writer = null;
temp.close();
return result;
} finally {
closeWithWarning(writer);
}
}
Allows this writer to be used within the closure, ensuring that it
is flushed and closed before this method returns. |
public static Object withWriter(OutputStream stream,
Closure closure) throws IOException {
return withWriter(new OutputStreamWriter(stream), closure);
}
Creates a writer from this stream, passing it to the given closure.
This method ensures the stream is closed after the closure returns. |
public static void withWriter(Process self,
Closure closure) {
new Thread(new Runnable() {
public void run() {
try {
withWriter(new BufferedOutputStream(getOut(self)), closure);
} catch (IOException e) {
throw new GroovyRuntimeException("exception while reading process stream", e);
}
}
}).start();
}
Creates a new BufferedWriter as stdin for this process,
passes it to the closure, and ensures the stream is flushed
and closed after the closure returns.
A new Thread is started, so this method will return immediately. |
public static Object withWriter(File file,
String charset,
Closure closure) throws IOException {
return withWriter(newWriter(file, charset), closure);
}
Creates a new BufferedWriter for this file, passes it to the closure, and
ensures the stream is flushed and closed after the closure returns.
The writer will use the given charset encoding. |
public static Object withWriter(OutputStream stream,
String charset,
Closure closure) throws IOException {
return withWriter(new OutputStreamWriter(stream, charset), closure);
}
Creates a writer from this stream, passing it to the given closure.
This method ensures the stream is closed after the closure returns. |
public static Object withWriterAppend(File file,
Closure closure) throws IOException {
return withWriter(newWriter(file, true), closure);
}
Create a new BufferedWriter for this file in append mode. The writer
is passed to the closure and is closed after the closure returns. |
public static Object withWriterAppend(File file,
String charset,
Closure closure) throws IOException {
return withWriter(newWriter(file, charset, true), closure);
}
Create a new BufferedWriter which will append to this
file. The writer is passed to the closure and will be closed before
this method returns. |
public static void write(Writer self,
Writable writable) throws IOException {
writable.writeTo(self);
}
A helper method so that dynamic dispatch of the writer.write(object) method
will always use the more efficient Writable.writeTo(writer) mechanism if the
object implements the Writable interface. |
public static void write(File file,
String text) throws IOException {
BufferedWriter writer = null;
try {
writer = newWriter(file);
writer.write(text);
writer.flush();
Writer temp = writer;
writer = null;
temp.close();
} finally {
closeWithWarning(writer);
}
}
Write the text to the File. |
public static void write(File file,
String text,
String charset) throws IOException {
BufferedWriter writer = null;
try {
writer = newWriter(file, charset);
writer.write(text);
writer.flush();
Writer temp = writer;
writer = null;
temp.close();
} finally {
closeWithWarning(writer);
}
}
Write the text to the File, using the specified encoding. |
public static void writeLine(BufferedWriter writer,
String line) throws IOException {
writer.write(line);
writer.newLine();
}
Write the text and append a newline (using the platform's line-ending). |
public static BitSet xor(BitSet left,
BitSet right) {
BitSet result = (BitSet) left.clone();
result.xor(right);
return result;
}
Bitwise XOR together two BitSets. Called when the '^' operator is used
between two bit sets. |
public static Number xor(Number left,
Number right) {
return NumberMath.xor(left, right);
}
Bitwise XOR together two Numbers. Called when the '|' operator is used. |
public static Boolean xor(Boolean left,
Boolean right) {
return left ^ right;
}
Exclusive disjunction of two boolean operators |