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

The following examples show how to use org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation. 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 File: ObjectArrayPutAtMetaMethod.java    From groovy with 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 #2
Source File: DefaultGroovyMethodsSupport.java    From groovy with 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 #3
Source File: NumberAwareComparator.java    From groovy with 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 #4
Source File: ArrayCachedClass.java    From groovy with 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 #5
Source File: StringGroovyMethods.java    From groovy with 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 #6
Source File: DefaultGroovyStaticMethods.java    From groovy with 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 #7
Source File: ObjectRange.java    From groovy with 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 #8
Source File: IntegerArrayPutAtMetaMethod.java    From groovy with 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 #9
Source File: FloatArrayPutAtMetaMethod.java    From groovy with 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 #10
Source File: DoubleArrayPutAtMetaMethod.java    From groovy with 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 #11
Source File: StringGroovyMethods.java    From groovy with 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 #12
Source File: SpreadMap.java    From groovy with 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 #13
Source File: MetaBeanProperty.java    From groovy with 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 #14
Source File: ObjectRange.java    From groovy with 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 #15
Source File: ShortArrayPutAtMetaMethod.java    From groovy with 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 #16
Source File: Sequence.java    From groovy with 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;
}
 
Example #17
Source File: Tuple.java    From groovy with Apache License 2.0 5 votes vote down vote up
@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (!(o instanceof Tuple)) return false;

    Tuple that = (Tuple) o;
    int size = size();
    if (size != that.size()) return false;
    for (int i = 0; i < size; i++) {
        if (!DefaultTypeTransformation.compareEqual(get(i), that.get(i))) {
            return false;
        }
    }
    return true;
}
 
Example #18
Source File: OrderBy.java    From groovy with Apache License 2.0 5 votes vote down vote up
public int compare(T object1, T object2) {
    for (Closure closure : closures) {
        Object value1 = closure.call(object1);
        Object value2 = closure.call(object2);
        int result;
        if (!equalityCheck || (value1 instanceof Comparable && value2 instanceof Comparable)) {
            result = numberAwareComparator.compare(value1, value2);
        } else {
            result = DefaultTypeTransformation.compareEqual(value1, value2) ? 0 : -1;
        }
        if (result == 0) continue;
        return result;
    }
    return 0;
}
 
Example #19
Source File: GroovyCollections.java    From groovy with Apache License 2.0 5 votes vote down vote up
/**
 * Finds all combinations of items from the given Iterable aggregate of collections.
 * So, <code>combinations([[true, false], [true, false]])</code>
 * is <code>[[true, true], [false, true], [true, false], [false, false]]</code>
 * and <code>combinations([['a', 'b'],[1, 2, 3]])</code>
 * is <code>[['a', 1], ['b', 1], ['a', 2], ['b', 2], ['a', 3], ['b', 3]]</code>.
 * If a non-collection item is given, it is treated as a singleton collection,
 * i.e. <code>combinations([[1, 2], 'x'])</code> is <code>[[1, 'x'], [2, 'x']]</code>.
 * If an empty collection is found within the given collections, the result will be an empty list.
 *
 * @param collections the Iterable of given collections
 * @return a List of the combinations found
 * @since 2.2.0
 */
public static List combinations(Iterable collections) {
    List collectedCombos = new ArrayList();
    for (Object collection : collections) {
        Iterable items = DefaultTypeTransformation.asCollection(collection);
        if (collectedCombos.isEmpty()) {
            for (Object item : items) {
                List l = new ArrayList();
                l.add(item);
                collectedCombos.add(l);
            }
        } else {
            List savedCombos = new ArrayList(collectedCombos);
            List newCombos = new ArrayList();
            for (Object value : items) {
                for (Object savedCombo : savedCombos) {
                    List oldList = new ArrayList((List) savedCombo);
                    oldList.add(value);
                    newCombos.add(oldList);
                }
            }
            collectedCombos = newCombos;
        }

        if (collectedCombos.isEmpty()) 
            break;
    }
    return collectedCombos;
}
 
Example #20
Source File: InvokerTest.java    From groovy with Apache License 2.0 5 votes vote down vote up
/**
 * Asserts that the given object can be converted into a collection and iterator
 * of the given size
 */
protected void assertAsCollection(Object collectionObject, int count) {
    Collection collection = DefaultTypeTransformation.asCollection(collectionObject);
    assertTrue("Collection is not null", collection != null);
    assertEquals("Collection size", count, collection.size());

    assertIterator("collections iterator", collection.iterator(), count);
    assertIterator("InvokerHelper.asIterator", InvokerHelper.asIterator(collectionObject), count);
    assertIterator("InvokerHelper.asIterator(InvokerHelper.asCollection)", InvokerHelper.asIterator(collection), count);
    assertIterator("InvokerHelper.asIterator(InvokerHelper.asIterator)", InvokerHelper.asIterator(InvokerHelper.asIterator(collectionObject)), count);
}
 
Example #21
Source File: ClosureJavaIntegrationTest.java    From groovy with Apache License 2.0 5 votes vote down vote up
public void testInject() {
    Collection<Integer> c = Arrays.asList(2, 4, 5, 20);
    Number initial = BigDecimal.ZERO;
    Closure<? extends Number> closure = new Closure<BigDecimal>(c) {
        BigDecimal doCall(BigDecimal total, Integer next) {
            return total.add(BigDecimal.ONE.divide(new BigDecimal(next)));
        }
    };
    assertTrue(DefaultTypeTransformation.compareEqual(BigDecimal.ONE, inject(c, initial, closure)));
}
 
Example #22
Source File: DoWhileBlock.java    From groovy-cps with Apache License 2.0 5 votes vote down vote up
public Next loopCond(Object cond) {
    if (DefaultTypeTransformation.castToBoolean(cond)) {
        // loop
        return top();
    } else {
        // exit loop
        return loopEnd.receive(null);
    }
}
 
Example #23
Source File: ElvisBlock.java    From groovy-cps with Apache License 2.0 5 votes vote down vote up
public Next jump(Object cond) {
    if (DefaultTypeTransformation.castToBoolean(cond)) {
        return k.receive(cond);
    } else {
        return then(falseExp, e, k);
    }
}
 
Example #24
Source File: WhileBlock.java    From groovy-cps with Apache License 2.0 5 votes vote down vote up
public Next loopCond(Object cond) {
    if (DefaultTypeTransformation.castToBoolean(cond)) {
        // loop
        return then(body,e,loopHead);
    } else {
        // exit loop
        return loopEnd.receive(null);
    }
}
 
Example #25
Source File: LogicalOpBlock.java    From groovy-cps with Apache License 2.0 5 votes vote down vote up
public Next decide(Object lhs) {
    boolean v = DefaultTypeTransformation.castToBoolean(lhs);
    if (and) {
        if (!v)     return k.receive(false);    // false && ...
        else        return then(rhs,e,k);
    } else {
        if (v)      return k.receive(true);    // true || ...
        else        return then(rhs,e,k);
    }
}
 
Example #26
Source File: ForLoopBlock.java    From groovy-cps with Apache License 2.0 5 votes vote down vote up
public Next loopCond(Object cond) {
    if (DefaultTypeTransformation.castToBoolean(cond)) {
        // loop
        return then(body,e,increment);
    } else {
        // exit loop
        return loopEnd.receive(null);
    }
}
 
Example #27
Source File: ParameterTypes.java    From groovy with 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 #28
Source File: NioExtensions.java    From groovy with 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 #29
Source File: GroovyTestCase.java    From groovy with 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 #30
Source File: Attribute.java    From groovy with 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);
    }
}