Java Code Examples for org.codehaus.groovy.runtime.DefaultGroovyMethods#asType()

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

        if (PluginTypeUtils.isAppProject(project)) {
            AppExtension appExtension = DefaultGroovyMethods.asType(DefaultGroovyMethods.getAt(
                    project.getExtensions(),
                    "android"), AppExtension.class);
            new AtlasAppTaskManager(AtlasBuildContext.androidBuilderMap.get(project),
                    appExtension,
                    project,
                    atlasExtension).run();
        } else if (PluginTypeUtils.isLibraryProject(project)) {
            LibraryExtension libExtension = DefaultGroovyMethods.asType(DefaultGroovyMethods.getAt(
                    project.getExtensions(),
                    "android"), LibraryExtension.class);
            new AtlasLibTaskManager(AtlasBuildContext.androidBuilderMap.get(project),
                    libExtension,
                    project,
                    atlasExtension).run();
        } else if (PluginTypeUtils.isFeatureProject(project)) {
            LibraryExtension featureExtension = DefaultGroovyMethods.asType(DefaultGroovyMethods.getAt(
                    project.getExtensions(),
                    "android"), FeatureExtension.class);
            new AtlasFeatureTaskManager(AtlasBuildContext.androidBuilderMap.get(project),
                    featureExtension,
                    project,
                    atlasExtension).run();
        }
    }
 
Example 3
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 4
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 5
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 6
Source File: BasePomFilterContainer.java    From pushfish-android with BSD 2-Clause "Simplified" License 4 votes vote down vote up
private PublishFilter toFilter(final Closure filter) {
    return (PublishFilter) DefaultGroovyMethods.asType(filter, PublishFilter.class);
}
 
Example 7
Source File: BasePomFilterContainer.java    From pushfish-android with BSD 2-Clause "Simplified" License 4 votes vote down vote up
private PublishFilter toFilter(final Closure filter) {
    return (PublishFilter) DefaultGroovyMethods.asType(filter, PublishFilter.class);
}
 
Example 8
Source File: GrailsHibernateTemplate.java    From gorm-hibernate5 with Apache License 2.0 4 votes vote down vote up
@Override
public <T> T execute(Closure<T> callable) {
    HibernateCallback<T> hibernateCallback = DefaultGroovyMethods.asType(callable, HibernateCallback.class);
    return execute(hibernateCallback);
}
 
Example 9
Source File: BasePomFilterContainer.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 4 votes vote down vote up
private PublishFilter toFilter(final Closure filter) {
    return (PublishFilter) DefaultGroovyMethods.asType(filter, PublishFilter.class);
}
 
Example 10
Source File: BasePomFilterContainer.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 4 votes vote down vote up
private PublishFilter toFilter(final Closure filter) {
    return (PublishFilter) DefaultGroovyMethods.asType(filter, PublishFilter.class);
}
 
Example 11
Source File: NioExtensions.java    From groovy with Apache License 2.0 3 votes vote down vote up
/**
 * Processes each descendant file in this directory and any sub-directories.
 * Processing consists of potentially calling <code>closure</code> passing it the current
 * file (which may be a normal file or subdirectory) and then if a subdirectory was encountered,
 * recursively processing the subdirectory.
 * <p>
 * The traversal can be adapted by providing various options in the <code>options</code> Map according
 * to the following keys:<dl>
 * <dt>type</dt><dd>A {@link groovy.io.FileType} enum to determine if normal files or directories or both are processed</dd>
 * <dt>preDir</dt><dd>A {@link groovy.lang.Closure} run before each directory is processed and optionally returning a {@link groovy.io.FileVisitResult} value
 * which can be used to control subsequent processing.</dd>
 * <dt>preRoot</dt><dd>A boolean indicating that the 'preDir' closure should be applied at the root level</dd>
 * <dt>postDir</dt><dd>A {@link groovy.lang.Closure} run after each directory is processed and optionally returning a {@link groovy.io.FileVisitResult} value
 * which can be used to control subsequent processing.</dd>
 * <dt>postRoot</dt><dd>A boolean indicating that the 'postDir' closure should be applied at the root level</dd>
 * <dt>visitRoot</dt><dd>A boolean indicating that the given closure should be applied for the root dir
 * (not applicable if the 'type' is set to {@link groovy.io.FileType#FILES})</dd>
 * <dt>maxDepth</dt><dd>The maximum number of directory levels when recursing
 * (default is -1 which means infinite, set to 0 for no recursion)</dd>
 * <dt>filter</dt><dd>A filter to perform on traversed files/directories (using the {@link DefaultGroovyMethods#isCase(Object, Object)} method). If set,
 * only files/dirs which match are candidates for visiting.</dd>
 * <dt>nameFilter</dt><dd>A filter to perform on the name of traversed files/directories (using the {@link DefaultGroovyMethods#isCase(Object, Object)} method). If set,
 * only files/dirs which match are candidates for visiting. (Must not be set if 'filter' is set)</dd>
 * <dt>excludeFilter</dt><dd>A filter to perform on traversed files/directories (using the {@link DefaultGroovyMethods#isCase(Object, Object)} method).
 * If set, any candidates which match won't be visited.</dd>
 * <dt>excludeNameFilter</dt><dd>A filter to perform on the names of traversed files/directories (using the {@link DefaultGroovyMethods#isCase(Object, Object)} method).
 * If set, any candidates which match won't be visited. (Must not be set if 'excludeFilter' is set)</dd>
 * <dt>sort</dt><dd>A {@link groovy.lang.Closure} which if set causes the files and subdirectories for each directory to be processed in sorted order.
 * Note that even when processing only files, the order of visited subdirectories will be affected by this parameter.</dd>
 * </dl>
 * This example prints out file counts and size aggregates for groovy source files within a directory tree:
 * <pre>
 * def totalSize = 0
 * def count = 0
 * def sortByTypeThenName = { a, b {@code ->}
 *     a.isFile() != b.isFile() ? a.isFile() {@code <=>} b.isFile() : a.name {@code <=>} b.name
 * }
 * rootDir.traverse(
 *         type         : FILES,
 *         nameFilter   : ~/.*\.groovy/,
 *         preDir       : { if (it.name == '.svn') return SKIP_SUBTREE },
 *         postDir      : { println "Found $count files in $it.name totalling $totalSize bytes"
 *                         totalSize = 0; count = 0 },
 *         postRoot     : true
 *         sort         : sortByTypeThenName
 * ) {it {@code ->} totalSize += it.size(); count++ }
 * </pre>
 *
 * @param self    a Path (that happens to be a folder/directory)
 * @param options a Map of options to alter the traversal behavior
 * @param closure the Closure to invoke on each file/directory and optionally returning a {@link groovy.io.FileVisitResult} value
 *                which can be used to control subsequent processing
 * @throws java.io.FileNotFoundException if the given directory does not exist
 * @throws IllegalArgumentException      if the provided Path object does not represent a directory or illegal filter combinations are supplied
 * @see DefaultGroovyMethods#sort(java.lang.Iterable, groovy.lang.Closure)
 * @see groovy.io.FileVisitResult
 * @see groovy.io.FileType
 * @since 2.3.0
 */
public static void traverse(final Path self, final Map<String, Object> options, @ClosureParams(value = SimpleType.class, options = "java.nio.file.Path") final Closure closure)
        throws IOException {
    // throws FileNotFoundException, IllegalArgumentException {
    Number maxDepthNumber = DefaultGroovyMethods.asType(options.remove("maxDepth"), Number.class);
    int maxDepth = maxDepthNumber == null ? -1 : maxDepthNumber.intValue();
    Boolean visitRoot = DefaultGroovyMethods.asType(get(options, "visitRoot", false), Boolean.class);
    Boolean preRoot = DefaultGroovyMethods.asType(get(options, "preRoot", false), Boolean.class);
    Boolean postRoot = DefaultGroovyMethods.asType(get(options, "postRoot", false), Boolean.class);
    final Closure pre = (Closure) options.get("preDir");
    final Closure post = (Closure) options.get("postDir");
    final FileType type = (FileType) options.get("type");
    final Object filter = options.get("filter");
    final Object nameFilter = options.get("nameFilter");
    final Object excludeFilter = options.get("excludeFilter");
    final Object excludeNameFilter = options.get("excludeNameFilter");
    Object preResult = null;
    if (preRoot && pre != null) {
        preResult = pre.call(self);
    }
    if (preResult == FileVisitResult.TERMINATE ||
            preResult == FileVisitResult.SKIP_SUBTREE) return;

    FileVisitResult terminated = traverse(self, options, closure, maxDepth);

    if (type != FileType.FILES && visitRoot) {
        if (closure != null && notFiltered(self, filter, nameFilter, excludeFilter, excludeNameFilter)) {
            Object closureResult = closure.call(self);
            if (closureResult == FileVisitResult.TERMINATE) return;
        }
    }

    if (postRoot && post != null && terminated != FileVisitResult.TERMINATE) post.call(self);
}
 
Example 12
Source File: NioExtensions.java    From groovy with Apache License 2.0 3 votes vote down vote up
/**
 * Converts this Path to a {@link groovy.lang.Writable} or delegates to default
 * {@link org.codehaus.groovy.runtime.DefaultGroovyMethods#asType(Object, Class)}.
 *
 * @param path a Path
 * @param c    the desired class
 * @return the converted object
 * @since 2.3.0
 */
@SuppressWarnings("unchecked")
public static <T> T asType(Path path, Class<T> c) {
    if (c == Writable.class) {
        return (T) asWritable(path);
    }
    return DefaultGroovyMethods.asType((Object) path, c);
}