org.codehaus.groovy.runtime.DefaultGroovyMethods Java Examples

The following examples show how to use org.codehaus.groovy.runtime.DefaultGroovyMethods. 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: AtlasConfigurationHelper.java    From atlas with Apache License 2.0 6 votes vote down vote up
public void createBuilderAfterEvaluate() throws Exception {

        AndroidBuilder androidBuilder = appPluginHook.getAndroidBuilder();

        if (null == androidBuilder) {
            return;
        }

        AndroidBuilder atlasBuilder = new AtlasBuilder(project.equals(project.getRootProject()) ? project
                .getName() : project.getPath(),
                creator,
                new GradleProcessExecutor(project),
                new GradleJavaProcessExecutor(project),
                DefaultGroovyMethods.asType(ReflectUtils.getField(
                        androidBuilder,
                        "mErrorReporter"),
                        ErrorReporter.class),
                LoggerWrapper.getLogger(AtlasBuilder.class),
                DefaultGroovyMethods.asType(ReflectUtils.getField(
                        androidBuilder,
                        "mVerboseExec"), Boolean.class));

        ((AtlasBuilder) atlasBuilder).setDefaultBuilder(androidBuilder);
        ((AtlasBuilder) atlasBuilder).setAtlasExtension(atlasExtension);
        AtlasBuildContext.androidBuilderMap.put(project, (AtlasBuilder) (atlasBuilder));
    }
 
Example #2
Source File: VMPluginFactory.java    From groovy with Apache License 2.0 6 votes vote down vote up
private static VMPlugin createPlugin(final String classNameCheck, final String pluginName) {
    return AccessController.doPrivileged((PrivilegedAction<VMPlugin>) () -> {
        try {
            ClassLoader loader = VMPluginFactory.class.getClassLoader();
            loader.loadClass(classNameCheck);
            return (VMPlugin) loader.loadClass(pluginName).getDeclaredConstructor().newInstance();
        } catch (Throwable t) {
            if (LOGGER.isLoggable(Level.FINE)) {
                LOGGER.fine("Trying to create VM plugin `" + pluginName + "` by checking `" + classNameCheck
                        + "`, but failed:\n" + DefaultGroovyMethods.asString(t)
                );
            }

            return null;
        }
    });
}
 
Example #3
Source File: SimpleGroovyClassDoc.java    From groovy with Apache License 2.0 6 votes vote down vote up
public Set<GroovyClassDoc> getParentInterfaces() {
    Set<GroovyClassDoc> result = new LinkedHashSet<GroovyClassDoc>();
    result.add(this);
    Set<GroovyClassDoc> next = new LinkedHashSet<GroovyClassDoc>(Arrays.asList(this.interfaces()));
    while (!next.isEmpty()) {
        Set<GroovyClassDoc> temp = next;
        next = new LinkedHashSet<GroovyClassDoc>();
        for (GroovyClassDoc t : temp) {
            if (t instanceof SimpleGroovyClassDoc) {
                next.addAll(((SimpleGroovyClassDoc)t).getParentInterfaces());
            } else if (t instanceof ExternalGroovyClassDoc) {
                ExternalGroovyClassDoc d = (ExternalGroovyClassDoc) t;
                next.addAll(getJavaInterfaces(d));
            }
        }
        next = DefaultGroovyMethods.minus(next, result);
        result.addAll(next);
    }
    return result;
}
 
Example #4
Source File: XStreamUtils.java    From groovy with Apache License 2.0 6 votes vote down vote up
public static void serialize(final String name, final Object ast) {
    if (name == null || name.length() == 0) return;

    XStream xstream = new XStream(new StaxDriver());
    FileWriter astFileWriter = null;
    try {
        File astFile = astFile(name);
        if (astFile == null) {
            System.out.println("File-name for writing " + name + " AST could not be determined!");
            return;
        }
        astFileWriter = new FileWriter(astFile, false);
        xstream.toXML(ast, astFileWriter);
        System.out.println("Written AST to " + name + ".xml");

    } catch (Exception e) {
        System.out.println("Couldn't write to " + name + ".xml");
        e.printStackTrace();
    } finally {
        DefaultGroovyMethods.closeQuietly(astFileWriter);
    }
}
 
Example #5
Source File: ExtensionMethodCache.java    From groovy with Apache License 2.0 6 votes vote down vote up
@Override
protected void addAdditionalClassesToScan(Set<Class> instanceExtClasses, Set<Class> staticExtClasses) {
    Collections.addAll(instanceExtClasses, DefaultGroovyMethods.DGM_LIKE_CLASSES);
    Collections.addAll(instanceExtClasses, DefaultGroovyMethods.ADDITIONAL_CLASSES);
    staticExtClasses.add(DefaultGroovyStaticMethods.class);

    instanceExtClasses.add(StaticTypeCheckingSupport.ObjectArrayStaticTypesHelper.class);
    instanceExtClasses.add(StaticTypeCheckingSupport.BooleanArrayStaticTypesHelper.class);
    instanceExtClasses.add(StaticTypeCheckingSupport.CharArrayStaticTypesHelper.class);
    instanceExtClasses.add(StaticTypeCheckingSupport.ByteArrayStaticTypesHelper.class);
    instanceExtClasses.add(StaticTypeCheckingSupport.ShortArrayStaticTypesHelper.class);
    instanceExtClasses.add(StaticTypeCheckingSupport.IntArrayStaticTypesHelper.class);
    instanceExtClasses.add(StaticTypeCheckingSupport.LongArrayStaticTypesHelper.class);
    instanceExtClasses.add(StaticTypeCheckingSupport.FloatArrayStaticTypesHelper.class);
    instanceExtClasses.add(StaticTypeCheckingSupport.DoubleArrayStaticTypesHelper.class);

    Collections.addAll(instanceExtClasses, VMPluginFactory.getPlugin().getPluginDefaultGroovyMethods());
    Collections.addAll(staticExtClasses, VMPluginFactory.getPlugin().getPluginStaticGroovyMethods());
}
 
Example #6
Source File: BaseDuration.java    From groovy with Apache License 2.0 6 votes vote down vote up
public String toString() {
    List buffer = new ArrayList();

    if (this.years != 0) buffer.add(this.years + " years");
    if (this.months != 0) buffer.add(this.months + " months");
    if (this.days != 0) buffer.add(this.days + " days");
    if (this.hours != 0) buffer.add(this.hours + " hours");
    if (this.minutes != 0) buffer.add(this.minutes + " minutes");

    if (this.seconds != 0 || this.millis != 0) {
        int norm_millis = this.millis % 1000;
        int norm_seconds = this.seconds + DefaultGroovyMethods.intdiv(this.millis - norm_millis, 1000).intValue();
        CharSequence millisToPad = "" + Math.abs(norm_millis);
        buffer.add((norm_seconds == 0 ? (norm_millis < 0 ? "-0" : "0") : norm_seconds) + "." + StringGroovyMethods.padLeft(millisToPad, 3, "0") + " seconds");
    }

    if (!buffer.isEmpty()) {
        return DefaultGroovyMethods.join(buffer.iterator(), ", ");
    } else {
        return "0";
    }
}
 
Example #7
Source File: MetaClassImpl.java    From groovy with Apache License 2.0 6 votes vote down vote up
private void connectMultimethods(List<CachedClass> superClasses, CachedClass firstGroovyClass) {
    superClasses = DefaultGroovyMethods.reverse(superClasses);
    MetaMethodIndex.Header last = null;
    for (final CachedClass c : superClasses) {
        MetaMethodIndex.Header methodIndex = metaMethodIndex.getHeader(c.getTheClass());
        // We don't copy DGM methods to superclasses' indexes
        // The reason we can do that is particular set of DGM methods in use,
        // if at some point we will define DGM method for some Groovy class or
        // for a class derived from such, we will need to revise this condition.
        // It saves us a lot of space and some noticeable time
        if (last != null) metaMethodIndex.copyNonPrivateNonNewMetaMethods(last, methodIndex);
        last = methodIndex;

        if (c == firstGroovyClass)
            break;
    }
}
 
Example #8
Source File: Node.java    From groovy with Apache License 2.0 6 votes vote down vote up
private List breadthFirstRest(boolean preorder) {
    List answer = new NodeList();
    Stack stack = new Stack();
    List nextLevelChildren = preorder ? getDirectChildren() : DefaultGroovyMethods.reverse(getDirectChildren());
    while (!nextLevelChildren.isEmpty()) {
        List working = new NodeList(nextLevelChildren);
        nextLevelChildren = new NodeList();
        for (Object child : working) {
            if (preorder) {
                answer.add(child);
            } else {
                stack.push(child);
            }
            if (child instanceof Node) {
                Node childNode = (Node) child;
                List children = childNode.getDirectChildren();
                if (children.size() > 1 || (children.size() == 1 && !(children.get(0) instanceof String))) nextLevelChildren.addAll(preorder ? children : DefaultGroovyMethods.reverse(children));
            }
        }
    }
    while (!stack.isEmpty()) {
        answer.add(stack.pop());
    }
    return answer;
}
 
Example #9
Source File: Node.java    From groovy with Apache License 2.0 6 votes vote down vote up
private void breadthFirstRest(boolean preorder, int level, Closure c) {
    Stack<Tuple2<Object, Integer>> stack = new Stack<Tuple2<Object, Integer>>();
    List nextLevelChildren = preorder ? getDirectChildren() : DefaultGroovyMethods.reverse(getDirectChildren());
    while (!nextLevelChildren.isEmpty()) {
        List working = new NodeList(nextLevelChildren);
        nextLevelChildren = new NodeList();
        for (Object child : working) {
            if (preorder) {
                callClosureForNode(c, child, level);
            } else {
                stack.push(new Tuple2<Object, Integer>(child, level));
            }
            if (child instanceof Node) {
                Node childNode = (Node) child;
                List children = childNode.getDirectChildren();
                if (children.size() > 1 || (children.size() == 1 && !(children.get(0) instanceof String))) nextLevelChildren.addAll(preorder ? children : DefaultGroovyMethods.reverse(children));
            }
        }
        level++;
    }
    while (!stack.isEmpty()) {
        Tuple2<Object, Integer> next = stack.pop();
        callClosureForNode(c, next.getV1(), next.getV2());
    }
}
 
Example #10
Source File: FinalVariableAnalyzer.java    From groovy with Apache License 2.0 6 votes vote down vote up
/**
 * @return true if the block's last statement is a return or throw
 */
private boolean returningBlock(Statement block) {
    if (block instanceof ReturnStatement || block instanceof  ThrowStatement) {
        return true;
    }
    if (!(block instanceof BlockStatement)) {
        return false;
    }
    BlockStatement bs = (BlockStatement) block;
    if (bs.getStatements().size() == 0) {
        return false;
    }
    Statement last = DefaultGroovyMethods.last(bs.getStatements());
    if (last instanceof ReturnStatement || last instanceof ThrowStatement) {
        return true;
    }
    return false;
}
 
Example #11
Source File: FinalVariableAnalyzer.java    From groovy with Apache License 2.0 6 votes vote down vote up
/**
 * @return true if the block falls through, i.e. no break/return
 */
private boolean fallsThrough(Statement statement) {
    if (statement instanceof EmptyStatement) {
        return true;
    }
    if (statement instanceof ReturnStatement) { // from ReturnAdder
        return false;
    }
    BlockStatement block = (BlockStatement) statement; // currently only possibility
    if (block.getStatements().size() == 0) {
        return true;
    }
    Statement last = DefaultGroovyMethods.last(block.getStatements());
    boolean completesAbruptly = last instanceof ReturnStatement || last instanceof BreakStatement || last instanceof ThrowStatement || last instanceof ContinueStatement;
    return !completesAbruptly;
}
 
Example #12
Source File: Script.java    From groovy with Apache License 2.0 5 votes vote down vote up
/**
 * Prints the value and a newline to the current 'out' variable which should be a PrintWriter
 * or at least have a println() method defined on it.
 * If there is no 'out' property then print to standard out.
 */
public void println(Object value) {
    Object object;

    try {
        object = getProperty("out");
    } catch (MissingPropertyException e) {
        DefaultGroovyMethods.println(System.out,value);
        return;
    }

    InvokerHelper.invokeMethod(object, "println", new Object[]{value});
}
 
Example #13
Source File: DefaultJsonGenerator.java    From groovy with Apache License 2.0 5 votes vote down vote up
protected Map<?, ?> getObjectProperties(Object object) {
    Map<?, ?> properties = DefaultGroovyMethods.getProperties(object);
    properties.remove("class");
    properties.remove("declaringClass");
    properties.remove("metaClass");
    return properties;
}
 
Example #14
Source File: AbstractInterruptibleASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
protected static boolean getBooleanAnnotationParameter(AnnotationNode node, String parameterName, boolean defaultValue) {
    Expression member = node.getMember(parameterName);
    if (member != null) {
        if (member instanceof ConstantExpression) {
            try {
                return DefaultGroovyMethods.asType(((ConstantExpression) member).getValue(), Boolean.class);
            } catch (Exception e) {
                internalError("Expecting boolean value for " + parameterName + " annotation parameter. Found " + member + "member");
            }
        } else {
            internalError("Expecting boolean value for " + parameterName + " annotation parameter. Found " + member + "member");
        }
    }
    return defaultValue;
}
 
Example #15
Source File: Script.java    From groovy with Apache License 2.0 5 votes vote down vote up
/**
 * Prints a formatted string using the specified format string and arguments.
 *
 * @param format the format to follow
 * @param values an array of values to be formatted
 */
public void printf(String format, Object[] values) {
    Object object;

    try {
        object = getProperty("out");
    } catch (MissingPropertyException e) {
        DefaultGroovyMethods.printf(System.out, format, values);
        return;
    }

    InvokerHelper.invokeMethod(object, "printf", new Object[] { format, values });
}
 
Example #16
Source File: SwingExtensions.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static Object[] buildRowData(DefaultTableModel delegate, Object row) {
    int cols = delegate.getColumnCount();
    Object[] rowData = new Object[cols];
    int i = 0;
    for (Iterator<?> it = DefaultGroovyMethods.iterator(row); it.hasNext() && i < cols;) {
        rowData[i++] = it.next();
    }
    return rowData;
}
 
Example #17
Source File: Inspector.java    From groovy with Apache License 2.0 5 votes vote down vote up
/**
 * Get info about Properties (Java and Groovy alike).
 *
 * @return Array of StringArrays that can be indexed with the MEMBER_xxx_IDX constants
 */
public Object[] getPropertyInfo() {
    List props = DefaultGroovyMethods.getMetaPropertyValues(objectUnderInspection);
    Object[] result = new Object[props.size()];
    int i = 0;
    for (Iterator iter = props.iterator(); iter.hasNext(); i++) {
        PropertyValue pv = (PropertyValue) iter.next();
        result[i] = fieldInfo(pv);
    }
    return result;
}
 
Example #18
Source File: Script.java    From groovy with Apache License 2.0 5 votes vote down vote up
/**
 * Prints a formatted string using the specified format string and argument.
 *
 * @param format the format to follow
 * @param value the value to be formatted
 */
public void printf(String format, Object value) {
    Object object;

    try {
        object = getProperty("out");
    } catch (MissingPropertyException e) {
        DefaultGroovyMethods.printf(System.out, format, value);
        return;
    }

    InvokerHelper.invokeMethod(object, "printf", new Object[] { format, value });
}
 
Example #19
Source File: GroovyCollections.java    From groovy with Apache License 2.0 5 votes vote down vote up
public static <T> List<List<T>> tails(Iterable<T> collections) {
    List<T> copy = DefaultGroovyMethods.toList(collections);
    List<List<T>> result = new ArrayList<List<T>>();
    for (int i = 0; i <= copy.size(); i++) {
        List<T> next = copy.subList(i, copy.size());
        result.add(next);
    }
    return result;
}
 
Example #20
Source File: Java9.java    From groovy with Apache License 2.0 5 votes vote down vote up
@Override
public Map<String, Set<String>> getDefaultImportClasses(String[] packageNames) {
    List<String> javaPns = new ArrayList<>(4);
    List<String> groovyPns = new ArrayList<>(4);
    for (String prefix : packageNames) {
        String pn = prefix.substring(0, prefix.length() - 1).replace('.', '/');

        if (pn.startsWith("java/")) {
            javaPns.add(pn);
        } else if (pn.startsWith("groovy/")) {
            groovyPns.add(pn);
        } else {
            throw new GroovyBugError("unexpected package: " + pn);
        }
    }

    Map<String, Set<String>> result = new LinkedHashMap<>(2048);
    try (GroovyClassLoader gcl = new GroovyClassLoader(this.getClass().getClassLoader())) {
        try {
            URI gsLocation = DefaultGroovyMethods.getLocation(gcl.loadClass("groovy.lang.GroovySystem")).toURI();
            result.putAll(doFindClasses(gsLocation, "groovy", groovyPns));

            // in production environment, groovy-core classes, e.g. `GroovySystem`(java class) and `GrapeIvy`(groovy class) are all packaged in the groovy-core jar file,
            // but in Groovy development environment, groovy-core classes are distributed in different directories
            URI giLocation = DefaultGroovyMethods.getLocation(gcl.loadClass("groovy.grape.GrapeIvy")).toURI();
            if (!gsLocation.equals(giLocation)) {
                result.putAll(doFindClasses(giLocation, "groovy", groovyPns));
            }
        } finally {
            result.putAll(doFindClasses(URI.create("jrt:/modules/java.base/"), "java", javaPns));
        }
    } catch (Exception ignore) {
        if (LOGGER.isLoggable(Level.FINEST)) {
            LOGGER.finest("[WARNING] Failed to find default imported classes:\n" + DefaultGroovyMethods.asString(ignore));
        }
    }

    return result;
}
 
Example #21
Source File: TestFile.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public TestFile leftShift(Object content) {
    getParentFile().mkdirs();
    try {
        DefaultGroovyMethods.leftShift(this, content);
        return this;
    } catch (IOException e) {
        throw new RuntimeException(String.format("Could not append to test file '%s'", this), e);
    }
}
 
Example #22
Source File: ExpandoMetaClass.java    From groovy with Apache License 2.0 5 votes vote down vote up
public Object leftShift(Closure c) {
    if (c != null) {
        final List<MetaMethod> list = ClosureMetaMethod.createMethodList(GROOVY_CONSTRUCTOR, theClass, c);
        for (MetaMethod method : list) {
            Class[] paramTypes = method.getNativeParameterTypes();
            Constructor ctor = retrieveConstructor(paramTypes);
            if (ctor != null)
                throw new GroovyRuntimeException("Cannot add new constructor for arguments [" + DefaultGroovyMethods.inspect(paramTypes) + "]. It already exists!");

            registerInstanceMethod(method);
        }
    }

    return this;
}
 
Example #23
Source File: ToStringASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
public void visit(ASTNode[] nodes, SourceUnit source) {
    init(nodes, source);
    AnnotatedNode parent = (AnnotatedNode) nodes[1];
    AnnotationNode anno = (AnnotationNode) nodes[0];
    if (!MY_TYPE.equals(anno.getClassNode())) return;

    if (parent instanceof ClassNode) {
        ClassNode cNode = (ClassNode) parent;
        if (!checkNotInterface(cNode, MY_TYPE_NAME)) return;
        boolean includeSuper = memberHasValue(anno, "includeSuper", true);
        boolean includeSuperProperties = memberHasValue(anno, "includeSuperProperties", true);
        boolean includeSuperFields = memberHasValue(anno, "includeSuperFields", true);
        boolean cacheToString = memberHasValue(anno, "cache", true);
        List<String> excludes = getMemberStringList(anno, "excludes");
        List<String> includes = getMemberStringList(anno, "includes");
        if (includes != null && includes.contains("super")) {
            includeSuper = true;
        }
        if (includeSuper && cNode.getSuperClass().getName().equals("java.lang.Object")) {
            addError("Error during " + MY_TYPE_NAME + " processing: includeSuper=true but '" + cNode.getName() + "' has no super class.", anno);
        }
        boolean includeNames = memberHasValue(anno, "includeNames", true);
        boolean includeFields = memberHasValue(anno, "includeFields", true);
        boolean ignoreNulls = memberHasValue(anno, "ignoreNulls", true);
        boolean includePackage = !memberHasValue(anno, "includePackage", false);
        boolean allProperties = !memberHasValue(anno, "allProperties", false);
        boolean allNames = memberHasValue(anno, "allNames", true);

        if (!checkIncludeExcludeUndefinedAware(anno, excludes, includes, MY_TYPE_NAME)) return;
        if (!checkPropertyList(cNode, includes != null ? DefaultGroovyMethods.minus(includes, "super") : null, "includes", anno, MY_TYPE_NAME, includeFields, includeSuperProperties, allProperties)) return;
        if (!checkPropertyList(cNode, excludes, "excludes", anno, MY_TYPE_NAME, includeFields, includeSuperProperties, allProperties)) return;
        createToString(cNode, includeSuper, includeFields, excludes, includes, includeNames, ignoreNulls, includePackage, cacheToString, includeSuperProperties, allProperties, allNames, includeSuperFields);
    }
}
 
Example #24
Source File: BinaryExpressionTransformer.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static Object convertConstant(final Number source, final ClassNode target) {
    if (ClassHelper.Byte_TYPE.equals(target)) {
        return source.byteValue();
    }
    if (ClassHelper.Short_TYPE.equals(target)) {
        return source.shortValue();
    }
    if (ClassHelper.Integer_TYPE.equals(target)) {
        return source.intValue();
    }
    if (ClassHelper.Long_TYPE.equals(target)) {
        return source.longValue();
    }
    if (ClassHelper.Float_TYPE.equals(target)) {
        return source.floatValue();
    }
    if (ClassHelper.Double_TYPE.equals(target)) {
        return source.doubleValue();
    }
    if (ClassHelper.BigInteger_TYPE.equals(target)) {
        return DefaultGroovyMethods.asType(source, BigInteger.class);
    }
    if (ClassHelper.BigDecimal_TYPE.equals(target)) {
        return DefaultGroovyMethods.asType(source, BigDecimal.class);
    }
    throw new IllegalArgumentException("Unsupported conversion");
}
 
Example #25
Source File: Traits.java    From groovy with Apache License 2.0 5 votes vote down vote up
/**
 * Converts a class implementing some trait into a target class. If the trait is a dynamic proxy and
 * that the target class is assignable to the target object of the proxy, then the target object is
 * returned. Otherwise, falls back to {@link org.codehaus.groovy.runtime.DefaultGroovyMethods#asType(java.lang.Object, Class)}
 * @param self an object to be coerced to some class
 * @param clazz the class to be coerced to
 * @return the object coerced to the target class, or the proxy instance if it is compatible with the target class.
 */
@SuppressWarnings("unchecked")
public static <T> T getAsType(Object self, Class<T> clazz) {
    if (self instanceof GeneratedGroovyProxy) {
        Object proxyTarget = ((GeneratedGroovyProxy)self).getProxyTarget();
        if (clazz.isAssignableFrom(proxyTarget.getClass())) {
            return (T) proxyTarget;
        }
    }
    return DefaultGroovyMethods.asType(self, clazz);
}
 
Example #26
Source File: ImmutableASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
/**
 * This method exists to be binary compatible with 1.7 - 1.8.6 compiled code.
 */
@SuppressWarnings("Unchecked")
public static Object checkImmutable(String className, String fieldName, Object field) {
    if (field == null || field instanceof Enum || ImmutablePropertyUtils.isBuiltinImmutable(field.getClass().getName())) return field;
    if (field instanceof Collection) return DefaultGroovyMethods.asImmutable((Collection) field);
    if (getAnnotationByName(field, "groovy.transform.Immutable") != null) return field;

    final String typeName = field.getClass().getName();
    throw new RuntimeException(createErrorMessage(className, fieldName, typeName, "constructing"));
}
 
Example #27
Source File: ImmutableASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
/**
 * For compatibility with pre 2.5 compiled classes
 */
@SuppressWarnings("Unchecked")
public static Object checkImmutable(Class<?> clazz, String fieldName, Object field) {
    if (field == null || field instanceof Enum || builtinOrMarkedImmutableClass(field.getClass())) {
        return field;
    }

    boolean isImmutable = false;
    for (Annotation an : field.getClass().getAnnotations()) {
        if (an.getClass().getName().startsWith("groovy.transform.Immutable")) {
            isImmutable = true;
            break;
        }
    }
    if (isImmutable) return field;

    if (field instanceof Collection) {
        Field declaredField;
        try {
            declaredField = clazz.getDeclaredField(fieldName);
            Class<?> fieldType = declaredField.getType();
            if (Collection.class.isAssignableFrom(fieldType)) {
                return DefaultGroovyMethods.asImmutable((Collection) field);
            }
            // potentially allow Collection coercion for a constructor
            if (builtinOrMarkedImmutableClass(fieldType)) {
                return field;
            }
        } catch (NoSuchFieldException ignore) {
            // ignore
        }
    }
    final String typeName = field.getClass().getName();
    throw new RuntimeException(createErrorMessage(clazz.getName(), fieldName, typeName, "constructing"));
}
 
Example #28
Source File: ImmutableASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("Unchecked")
public static Object checkImmutable(Class<?> clazz, String fieldName, Object field, List<String> knownImmutableFieldNames, List<Class> knownImmutableClasses) {
    if (field == null || field instanceof Enum || builtinOrMarkedImmutableClass(field.getClass()) || knownImmutableFieldNames.contains(fieldName) || knownImmutableClasses.contains(field.getClass())) {
        return field;
    }

    boolean isImmutable = false;
    for (Annotation an : field.getClass().getAnnotations()) {
        if (an.getClass().getName().startsWith("groovy.transform.Immutable")) {
            isImmutable = true;
            break;
        }
    }
    if (isImmutable) return field;

    if (field instanceof Collection) {
        Field declaredField;
        try {
            declaredField = clazz.getDeclaredField(fieldName);
            Class<?> fieldType = declaredField.getType();
            if (Collection.class.isAssignableFrom(fieldType)) {
                return DefaultGroovyMethods.asImmutable((Collection) field);
            }
            // potentially allow Collection coercion for a constructor
            if (builtinOrMarkedImmutableClass(fieldType) || knownImmutableClasses.contains(fieldType)) {
                return field;
            }
        } catch (NoSuchFieldException ignore) {
            // ignore
        }
    }
    final String typeName = field.getClass().getName();
    throw new RuntimeException(createErrorMessage(clazz.getName(), fieldName, typeName, "constructing"));
}
 
Example #29
Source File: FromRunnableClosure.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public T doCall() throws Throwable {
    if (DefaultGroovyMethods.isCase(job, Callable.class)) {
        return ((Callable<T>)job).call();
    } else {
        job.run();
        return null;
    }
}
 
Example #30
Source File: DefaultTypeTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
public static boolean compareEqual(Object left, Object right) {
    if (left == right) return true;
    if (left == null) return right instanceof NullObject;
    if (right == null) return left instanceof NullObject;
    if (left instanceof Comparable) {
        return compareToWithEqualityCheck(left, right, true) == 0;
    }
    // handle arrays on both sides as special case for efficiency
    Class leftClass = left.getClass();
    Class rightClass = right.getClass();
    if (leftClass.isArray() && rightClass.isArray()) {
        return compareArrayEqual(left, right);
    }
    if (leftClass.isArray() && leftClass.getComponentType().isPrimitive()) {
        left = primitiveArrayToList(left);
    }
    if (rightClass.isArray() && rightClass.getComponentType().isPrimitive()) {
        right = primitiveArrayToList(right);
    }
    if (left instanceof Object[] && right instanceof List) {
        return DefaultGroovyMethods.equals((Object[]) left, (List) right);
    }
    if (left instanceof List && right instanceof Object[]) {
        return DefaultGroovyMethods.equals((List) left, (Object[]) right);
    }
    if (left instanceof List && right instanceof List) {
        return DefaultGroovyMethods.equals((List) left, (List) right);
    }
    if (left instanceof Map.Entry && right instanceof Map.Entry) {
        Object k1 = ((Map.Entry) left).getKey();
        Object k2 = ((Map.Entry) right).getKey();
        if (Objects.equals(k1, k2)) {
            Object v1 = ((Map.Entry) left).getValue();
            Object v2 = ((Map.Entry) right).getValue();
            return v1 == v2 || (v1 != null && DefaultTypeTransformation.compareEqual(v1, v2));
        }
        return false;
    }
    return (Boolean) InvokerHelper.invokeMethod(left, "equals", right);
}