Java Code Examples for org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation

The following examples show how to use org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: groovy   Author: apache   File: ArrayCachedClass.java    License: Apache License 2.0 6 votes vote down vote up
public Object coerceArgument(Object argument) {
    Class argumentClass = argument.getClass();
    if (argumentClass.getName().charAt(0) != '[') return argument;
    Class argumentComponent = argumentClass.getComponentType();

    Class paramComponent = getTheClass().getComponentType();
    if (paramComponent.isPrimitive()) {
        argument = DefaultTypeTransformation.convertToPrimitiveArray(argument, paramComponent);
    } else if (paramComponent == String.class && argument instanceof GString[]) {
        GString[] strings = (GString[]) argument;
        String[] ret = new String[strings.length];
        for (int i = 0; i < strings.length; i++) {
            ret[i] = strings[i].toString();
        }
        argument = ret;
    } else if (paramComponent==Object.class && argumentComponent.isPrimitive()){
        argument = DefaultTypeTransformation.primitiveArrayBox(argument);
    }
    return argument;
}
 
Example #2
Source Project: groovy   Author: apache   File: DefaultGroovyStaticMethods.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * This method is used by both sleep() methods to implement sleeping
 * for the given time even if interrupted
 *
 * @param millis  the number of milliseconds to sleep
 * @param closure optional closure called when interrupted
 *                as long as the closure returns false the sleep continues
 */
private static void sleepImpl(long millis, Closure closure) {
    long start = System.currentTimeMillis();
    long rest = millis;
    long current;
    while (rest > 0) {
        try {
            Thread.sleep(rest);
            rest = 0;
        } catch (InterruptedException e) {
            if (closure != null) {
                if (DefaultTypeTransformation.castToBoolean(closure.call(e))) {
                    return;
                }
            }
            current = System.currentTimeMillis(); // compensate for closure's time
            rest = millis + start - current;
        }
    }
}
 
Example #3
Source Project: groovy   Author: apache   File: DefaultGroovyMethodsSupport.java    License: Apache License 2.0 6 votes vote down vote up
protected static RangeInfo subListBorders(int size, Range range) {
    if (range instanceof IntRange) {
        return ((IntRange) range).subListBorders(size);
    }
    if (range instanceof NumberRange) {
        return ((NumberRange) range).subListBorders(size);
    }
    int from = normaliseIndex(DefaultTypeTransformation.intUnbox(range.getFrom()), size);
    int to = normaliseIndex(DefaultTypeTransformation.intUnbox(range.getTo()), size);
    boolean reverse = range.isReverse();
    if (from > to) {
        // support list[1..-1]
        int tmp = to;
        to = from;
        from = tmp;
        reverse = !reverse;
    }
    return new RangeInfo(from, to + 1, reverse);
}
 
Example #4
Source Project: groovy   Author: apache   File: ObjectArrayPutAtMetaMethod.java    License: Apache License 2.0 6 votes vote down vote up
private static Object adjustNewValue(Object[] objects, Object newValue) {
    Class arrayComponentClass = objects.getClass().getComponentType();
    Object adjustedNewVal = newValue;
    if (newValue instanceof Number) {
        if (!arrayComponentClass.equals(newValue.getClass())) {
            adjustedNewVal = DefaultTypeTransformation.castToType(newValue, arrayComponentClass);
        }
    } else if (Character.class.isAssignableFrom(arrayComponentClass)) {
        adjustedNewVal = DefaultTypeTransformation.getCharFromSizeOneString(newValue);
    } else if (Number.class.isAssignableFrom(arrayComponentClass)) {
        if (newValue instanceof Character || newValue instanceof String || newValue instanceof GString) {
            Character ch = DefaultTypeTransformation.getCharFromSizeOneString(newValue);
            adjustedNewVal = DefaultTypeTransformation.castToType(ch, arrayComponentClass);
        }
    } else if (arrayComponentClass.isArray()) {
        adjustedNewVal = DefaultTypeTransformation.castToType(newValue, arrayComponentClass);
    }
    return adjustedNewVal;
}
 
Example #5
Source Project: groovy   Author: apache   File: NumberAwareComparator.java    License: Apache License 2.0 6 votes vote down vote up
public int compare(T o1, T o2) {
    try {
        return DefaultTypeTransformation.compareTo(o1, o2);
    } catch (ClassCastException | IllegalArgumentException | GroovyRuntimeException cce) {
        /* ignore */
    }
    // since the object does not have a valid compareTo method
    // we compare using the hashcodes. null cases are handled by
    // DefaultTypeTransformation.compareTo
    // This is not exactly a mathematical valid approach, since we compare object
    // that cannot be compared. To avoid strange side effects we do a pseudo order
    // using hashcodes, but without equality. Since then an x and y with the same
    // hashcodes will behave different depending on if we compare x with y or
    // x with y, the result might be unstable as well. Setting x and y to equal
    // may mean the removal of x or y in a sorting operation, which we don't want.
    int x1 = o1.hashCode();
    int x2 = o2.hashCode();
    if (x1 == x2 && o1.equals(o2)) return 0;
    if (x1 > x2) return 1;
    return -1;
}
 
Example #6
Source Project: groovy   Author: apache   File: StringGroovyMethods.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Selects a List of values from a Matcher using a Collection
 * to identify the indices to be selected.
 *
 * @param self    a Matcher
 * @param indices a Collection of indices
 * @return a String of the values at the given indices
 *
 * @since 1.6.0
 */
public static List getAt(final Matcher self, Collection indices) {
    List result = new ArrayList();
    if (indices instanceof IntRange) {
        int size = (int) size(self);
        RangeInfo info = subListBorders(size, (Range) indices);
        indices = new IntRange(((IntRange)indices).getInclusive(), info.from, info.to - 1);
    }
    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;
}
 
Example #7
Source Project: groovy   Author: apache   File: NioExtensions.java    License: Apache License 2.0 5 votes vote down vote up
private static boolean notFiltered(Path path, Object filter, Object nameFilter, Object excludeFilter, Object excludeNameFilter) {
    if (filter == null && nameFilter == null && excludeFilter == null && excludeNameFilter == null) return true;
    if (filter != null && nameFilter != null)
        throw new IllegalArgumentException("Can't set both 'filter' and 'nameFilter'");
    if (excludeFilter != null && excludeNameFilter != null)
        throw new IllegalArgumentException("Can't set both 'excludeFilter' and 'excludeNameFilter'");
    Object filterToUse = null;
    Object filterParam = null;
    if (filter != null) {
        filterToUse = filter;
        filterParam = path;
    } else if (nameFilter != null) {
        filterToUse = nameFilter;
        filterParam = path.getFileName().toString();
    }
    Object excludeFilterToUse = null;
    Object excludeParam = null;
    if (excludeFilter != null) {
        excludeFilterToUse = excludeFilter;
        excludeParam = path;
    } else if (excludeNameFilter != null) {
        excludeFilterToUse = excludeNameFilter;
        excludeParam = path.getFileName().toString();
    }
    final MetaClass filterMC = filterToUse == null ? null : InvokerHelper.getMetaClass(filterToUse);
    final MetaClass excludeMC = excludeFilterToUse == null ? null : InvokerHelper.getMetaClass(excludeFilterToUse);
    boolean included = filterToUse == null || DefaultTypeTransformation.castToBoolean(filterMC.invokeMethod(filterToUse, "isCase", filterParam));
    boolean excluded = excludeFilterToUse != null && DefaultTypeTransformation.castToBoolean(excludeMC.invokeMethod(excludeFilterToUse, "isCase", excludeParam));
    return included && !excluded;
}
 
Example #8
Source Project: groovy   Author: apache   File: GroovyTestCase.java    License: Apache License 2.0 5 votes vote down vote up
public static void assertEquals(String message, Object expected, Object actual) {
    if (expected == null && actual == null)
        return;
    if (expected != null && DefaultTypeTransformation.compareEqual(expected, actual))
        return;
    TestCase.assertEquals(message, expected, actual);
}
 
Example #9
Source Project: groovy   Author: apache   File: Attribute.java    License: Apache License 2.0 5 votes vote down vote up
public GPathResult find(final Closure closure) {
    if (DefaultTypeTransformation.castToBoolean(closure.call(new Object[]{this}))) {
        return this;
    } else {
        return new NoChildren(this, "", this.namespaceTagHints);
    }
}
 
Example #10
Source Project: groovy   Author: apache   File: FilteredAttributes.java    License: Apache License 2.0 5 votes vote down vote up
public Iterator nodeIterator() {
    return new NodeIterator(this.parent.iterator())
    {
        protected Object getNextNode(final Iterator iter) {
            while (iter.hasNext()) {
                final Object node = iter.next();
                if (DefaultTypeTransformation.castToBoolean(FilteredAttributes.this.closure.call(new Object[]{node}))) {
                    return node;
                }
            }
            return null;
        }
    };
}
 
Example #11
Source Project: groovy   Author: apache   File: NodeChildren.java    License: Apache License 2.0 5 votes vote down vote up
public GPathResult find(final Closure closure) {
    for (Object node : this) {
        if (DefaultTypeTransformation.castToBoolean(closure.call(new Object[]{node}))) {
            return (GPathResult) node;
        }
    }
    return new NoChildren(this, this.name, namespaceTagHints);
}
 
Example #12
Source Project: groovy   Author: apache   File: NodeChild.java    License: Apache License 2.0 5 votes vote down vote up
public GPathResult find(final Closure closure) {
    if (DefaultTypeTransformation.castToBoolean(closure.call(new Object[]{this.node}))) {
        return this;
    } else {
        return new NoChildren(this, "", this.namespaceTagHints);
    }
}
 
Example #13
Source Project: groovy   Author: apache   File: ParameterTypes.java    License: Apache License 2.0 5 votes vote down vote up
private static Object makeCommonArray(Object[] arguments, int offset, Class baseClass) {
    Object[] result = (Object[]) Array.newInstance(baseClass, arguments.length - offset);
    for (int i = offset; i < arguments.length; i++) {
        Object v = arguments[i];
        v = DefaultTypeTransformation.castToType(v, baseClass);
        result[i - offset] = v;
    }
    return result;
}
 
Example #14
Source Project: groovy   Author: apache   File: CachedField.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Sets the property on the given object to the new value
 *
 * @param object on which to set the property
 * @param newValue the new value of the property
 * @throws RuntimeException if the property could not be set
 */
public void setProperty(final Object object, Object newValue) {
    makeAccessibleIfNecessary();
    AccessPermissionChecker.checkAccessPermission(cachedField);
    final Object goalValue = DefaultTypeTransformation.castToType(newValue, cachedField.getType());

    if (isFinal()) {
        throw new GroovyRuntimeException("Cannot set the property '" + name + "' because the backing field is final.");
    }
    try {
        cachedField.set(object, goalValue);
    } catch (IllegalAccessException ex) {
        throw new GroovyRuntimeException("Cannot set the property '" + name + "'.", ex);
    }
}
 
Example #15
Source Project: groovy   Author: apache   File: StackTraceUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static boolean isApplicationClass(String className) {
    for (Closure test : tests) {
        Object result = test.call(className);
        if (result != null) {
            return DefaultTypeTransformation.castToBoolean(result);
        }
    }

    for (String groovyPackage : GROOVY_PACKAGES) {
        if (className.startsWith(groovyPackage)) {
            return false;
        }
    }
    return true;
}
 
Example #16
Source Project: groovy   Author: apache   File: ScriptBytecodeAdapter.java    License: Apache License 2.0 5 votes vote down vote up
public static boolean compareEqual(Object left, Object right) {
    if (left==right) return true;
    Class<?> leftClass = left==null?null:left.getClass();
    Class<?> rightClass = right==null?null:right.getClass();
    if (leftClass ==Integer.class && rightClass==Integer.class) {
        return left.equals(right);
    }
    if (leftClass ==Double.class && rightClass==Double.class) {
        return left.equals(right);
    }
    if (leftClass ==Long.class && rightClass==Long.class) {
        return left.equals(right);
    }
    return DefaultTypeTransformation.compareEqual(left, right);
}
 
Example #17
Source Project: groovy   Author: apache   File: ScriptBytecodeAdapter.java    License: Apache License 2.0 5 votes vote down vote up
public static Integer compareTo(Object left, Object right) {
    int answer = DefaultTypeTransformation.compareTo(left, right);
    if (answer == 0) {
        return ZERO;
    } else {
        return answer > 0 ? ONE : MINUS_ONE;
    }
}
 
Example #18
Source Project: groovy   Author: apache   File: ScriptBytecodeAdapter.java    License: Apache License 2.0 5 votes vote down vote up
public static Object[] despreadList(Object[] args, Object[] spreads, int[] positions) {
    List ret = new ArrayList();
    int argsPos = 0;
    int spreadPos = 0;
    for (int position : positions) {
        for (; argsPos < position; argsPos++) {
            ret.add(args[argsPos]);
        }
        Object value = spreads[spreadPos];
        if (value == null) {
            ret.add(null);
        } else if (value instanceof List) {
            ret.addAll((List) value);
        } else if (value.getClass().isArray()) {
            ret.addAll(DefaultTypeTransformation.primitiveArrayToList(value));
        } else {
            String error = "cannot spread the type " + value.getClass().getName() + " with value " + value;
            if (value instanceof Map) {
                error += ", did you mean to use the spread-map operator instead?";
            }
            throw new IllegalArgumentException(error);
        }
        spreadPos++;
    }
    for (; argsPos < args.length; argsPos++) {
        ret.add(args[argsPos]);
    }
    return ret.toArray();
}
 
Example #19
Source Project: groovy   Author: apache   File: ResourceGroovyMethods.java    License: Apache License 2.0 5 votes vote down vote up
private static boolean notFiltered(File file, Object filter, Object nameFilter, Object excludeFilter, Object excludeNameFilter) {
    if (filter == null && nameFilter == null && excludeFilter == null && excludeNameFilter == null) return true;
    if (filter != null && nameFilter != null)
        throw new IllegalArgumentException("Can't set both 'filter' and 'nameFilter'");
    if (excludeFilter != null && excludeNameFilter != null)
        throw new IllegalArgumentException("Can't set both 'excludeFilter' and 'excludeNameFilter'");
    Object filterToUse = null;
    Object filterParam = null;
    if (filter != null) {
        filterToUse = filter;
        filterParam = file;
    } else if (nameFilter != null) {
        filterToUse = nameFilter;
        filterParam = file.getName();
    }
    Object excludeFilterToUse = null;
    Object excludeParam = null;
    if (excludeFilter != null) {
        excludeFilterToUse = excludeFilter;
        excludeParam = file;
    } else if (excludeNameFilter != null) {
        excludeFilterToUse = excludeNameFilter;
        excludeParam = file.getName();
    }
    final MetaClass filterMC = filterToUse == null ? null : InvokerHelper.getMetaClass(filterToUse);
    final MetaClass excludeMC = excludeFilterToUse == null ? null : InvokerHelper.getMetaClass(excludeFilterToUse);
    boolean included = filterToUse == null || DefaultTypeTransformation.castToBoolean(filterMC.invokeMethod(filterToUse, "isCase", filterParam));
    boolean excluded = excludeFilterToUse != null && DefaultTypeTransformation.castToBoolean(excludeMC.invokeMethod(excludeFilterToUse, "isCase", excludeParam));
    return included && !excluded;
}
 
Example #20
Source Project: groovy   Author: apache   File: LongArrayPutAtMetaMethod.java    License: Apache License 2.0 5 votes vote down vote up
public Object invoke(Object object, Object[] args) {
    final long[] objects = (long[]) object;
    final int index = normaliseIndex((Integer) args[0], objects.length);
    Object newValue = args[1];
    if (!(newValue instanceof Long)) {
        if (newValue instanceof Character || newValue instanceof String || newValue instanceof GString) {
            Character ch = DefaultTypeTransformation.getCharFromSizeOneString(newValue);
            objects[index] = (Long) DefaultTypeTransformation.castToType(ch, Long.class);
        } else {
            objects[index] = ((Number) newValue).longValue();
        }
    } else
        objects[index] = (Long) args[1];
    return null;
}
 
Example #21
Source Project: groovy   Author: apache   File: IntegerArrayPutAtMetaMethod.java    License: Apache License 2.0 5 votes vote down vote up
public Object invoke(Object object, Object[] args) {
    final int[] objects = (int[]) object;
    final int index = normaliseIndex((Integer) args[0], objects.length);
    Object newValue = args[1];
    if (!(newValue instanceof Integer)) {
        if (newValue instanceof Character || newValue instanceof String || newValue instanceof GString) {
            Character ch = DefaultTypeTransformation.getCharFromSizeOneString(newValue);
            objects[index] = (Integer) DefaultTypeTransformation.castToType(ch, Integer.class);
        } else {
            objects[index] = ((Number) newValue).intValue();
        }
    } else
        objects[index] = (Integer) args[1];
    return null;
}
 
Example #22
Source Project: groovy   Author: apache   File: ShortArrayPutAtMetaMethod.java    License: Apache License 2.0 5 votes vote down vote up
public Object invoke(Object object, Object[] args) {
    final short[] objects = (short[]) object;
    final int index = normaliseIndex((Integer) args[0], objects.length);
    Object newValue = args[1];
    if (!(newValue instanceof Short)) {
        if (newValue instanceof Character || newValue instanceof String || newValue instanceof GString) {
            Character ch = DefaultTypeTransformation.getCharFromSizeOneString(newValue);
            objects[index] = (Short) DefaultTypeTransformation.castToType(ch, Short.class);
        } else {
            objects[index] = ((Number) newValue).shortValue();
        }
    } else
        objects[index] = (Short) args[1];
    return null;
}
 
Example #23
Source Project: groovy   Author: apache   File: FloatArrayPutAtMetaMethod.java    License: Apache License 2.0 5 votes vote down vote up
public Object invoke(Object object, Object[] args) {
    final float[] objects = (float[]) object;
    final int index = normaliseIndex((Integer) args[0], objects.length);
    Object newValue = args[1];
    if (!(newValue instanceof Float)) {
        if (newValue instanceof Character || newValue instanceof String || newValue instanceof GString) {
            Character ch = DefaultTypeTransformation.getCharFromSizeOneString(newValue);
            objects[index] = (Float) DefaultTypeTransformation.castToType(ch, Float.class);
        } else {
            objects[index] = ((Number) newValue).floatValue();
        }
    } else
        objects[index] = (Float) args[1];
    return null;
}
 
Example #24
Source Project: groovy   Author: apache   File: DoubleArrayPutAtMetaMethod.java    License: Apache License 2.0 5 votes vote down vote up
public Object invoke(Object object, Object[] args) {
    final double[] objects = (double[]) object;
    final int index = normaliseIndex((Integer) args[0], objects.length);
    Object newValue = args[1];
    if (!(newValue instanceof Double)) {
        if (newValue instanceof Character || newValue instanceof String || newValue instanceof GString) {
            Character ch = DefaultTypeTransformation.getCharFromSizeOneString(newValue);
            objects[index] = (Double) DefaultTypeTransformation.castToType(ch, Double.class);
        } else {
            objects[index] = ((Number) newValue).doubleValue();
        }
    } else
        objects[index] = (Double) args[1];
    return null;
}
 
Example #25
Source Project: groovy   Author: apache   File: StringGroovyMethods.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Selects a List of characters from a CharSequence using a Collection
 * to identify the indices to be selected.
 *
 * @param self    a CharSequence
 * @param indices a Collection of indices
 * @return a String consisting of the characters at the given indices
 *
 * @since 1.0
 */
public static String getAt(final CharSequence self, final 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();
}
 
Example #26
Source Project: groovy   Author: apache   File: SpreadMap.java    License: Apache License 2.0 5 votes vote down vote up
public boolean equals(SpreadMap that) {
    if (that == null) return false;        

    if (size() == that.size()) {
        for (Object e : entrySet()) {
            Map.Entry entry = (Map.Entry) e;
            Object key = entry.getKey();
            if (!DefaultTypeTransformation.compareEqual(entry.getValue(), that.get(key))) {
                return false;
            }
        }
        return true;
    }
    return false;
}
 
Example #27
Source Project: groovy   Author: apache   File: MetaBeanProperty.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Set the property on the given object to the new value.
 *
 * @param object   on which to set the property
 * @param newValue the new value of the property
 * @throws RuntimeException if the property could not be set
 */
public void setProperty(Object object, Object newValue) {
    MetaMethod setter = getSetter();
    if (setter == null) {
        if (field != null && !Modifier.isFinal(field.getModifiers())) {
            field.setProperty(object, newValue);
            return;
        }
        throw new GroovyRuntimeException("Cannot set read-only property: " + name);
    }
    newValue = DefaultTypeTransformation.castToType(newValue, getType());
    setter.invoke(object, new Object[]{newValue});
}
 
Example #28
Source Project: groovy   Author: apache   File: ObjectRange.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Compares an {@link ObjectRange} to another {@link ObjectRange}.
 *
 * @param that the object to check equality with
 * @return <code>true</code> if the ranges are equal
 */
public boolean equals(ObjectRange that) {
    return that != null
            && reverse == that.reverse
            && DefaultTypeTransformation.compareEqual(from, that.from)
            && DefaultTypeTransformation.compareEqual(to, that.to);
}
 
Example #29
Source Project: groovy   Author: apache   File: ObjectRange.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Iterates over all values and returns true if one value matches.
 *
 * @see #containsWithinBounds(Object)
 */
@Override
public boolean contains(Object value) {
    final Iterator<Comparable> iter = new StepIterator(this, 1);
    if (value == null) {
        return false;
    }
    while (iter.hasNext()) {
        if (DefaultTypeTransformation.compareEqual(value, iter.next())) return true;
    }
    return false;
}
 
Example #30
Source Project: groovy   Author: apache   File: Sequence.java    License: Apache License 2.0 5 votes vote down vote up
public boolean equals(Sequence that) {
    if (size() == that.size()) {
        for (int i = 0; i < size(); i++) {
            if (!DefaultTypeTransformation.compareEqual(this.get(i), that.get(i))) {
                return false;
            }
        }
        return true;
    }
    return false;
}