Java Code Examples for org.gradle.api.Action

The following examples show how to use org.gradle.api.Action. 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: pushfish-android   Author: PushFish   File: DefaultCachePolicy.java    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
private void cacheMissingModulesAndArtifactsFor(final int value, final TimeUnit units) {
    eachModule(new Action<ModuleResolutionControl>() {
        public void execute(ModuleResolutionControl moduleResolutionControl) {
            if (moduleResolutionControl.getCachedResult() == null) {
                moduleResolutionControl.cacheFor(value, units);
            }
        }
    });
    eachArtifact(new Action<ArtifactResolutionControl>() {
        public void execute(ArtifactResolutionControl artifactResolutionControl) {
            if (artifactResolutionControl.getCachedResult() == null) {
                artifactResolutionControl.cacheFor(value, units);
            }
        }
    });
}
 
Example #2
Source Project: Pushjet-Android   Author: Pushjet   File: Binary2JUnitXmlReportGenerator.java    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
public void generate() {
    Clock clock = new Clock();
    testResultsProvider.visitClasses(new Action<TestClassResult>() {
        public void execute(TestClassResult result) {
            File file = new File(testResultsDir, getReportFileName(result));
            OutputStream output = null;
            try {
                output = new BufferedOutputStream(new FileOutputStream(file));
                saxWriter.write(result, output);
                output.close();
            } catch (Exception e) {
                throw new GradleException(String.format("Could not write XML test results for %s to file %s.", result.getClassName(), file), e);
            } finally {
                IOUtils.closeQuietly(output);
            }
        }
    });
    LOG.info("Finished generating test XML results ({}) into: {}", clock.getTime(), testResultsDir);
}
 
Example #3
Source Project: native-samples   Author: gradle   File: SourceCopyTask.java    License: Apache License 2.0 6 votes vote down vote up
public void doCopyDir(String templateDirName, String srcName, String targetDir, Action<TemplateDirectory> dirAction) {
    String srcFileName = templateDirName + "/" + srcName;
    File srcDir = getTemplatesDir().dir(srcFileName).get().getAsFile();
    if (!srcDir.isDirectory() || srcDir.list().length == 0) {
        return;

    }

    final TemplateDirectory dirDetails = new TemplateDirectory(srcName);
    dirAction.execute(dirDetails);
    File destDir = getSampleDir().dir(targetDir + "/" + dirDetails.getTargetDirName()).get().getAsFile();
    copy(srcDir, destDir, dirDetails.getLineFilter(), dirDetails.getRecursive());
    if (dirDetails.getRecursive()) {
        return;

    }

    Arrays.stream(srcDir.listFiles()).forEach(f -> {
        if (f.isDirectory() && !f.getName().equals(".gradle")) {
            doCopyDir(templateDirName, StringGroovyMethods.asBoolean(srcName) ? srcName + "/" + f.getName() : f.getName(), targetDir, dirAction);
        }
    });
}
 
Example #4
Source Project: pushfish-android   Author: PushFish   File: CollectionUtils.java    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
public static <T, I> T inject(T target, Iterable<? extends I> items, Action<InjectionStep<T, I>> action) {
    if (target == null) {
        throw new NullPointerException("The 'target' cannot be null");
    }
    if (items == null) {
        throw new NullPointerException("The 'items' cannot be null");
    }
    if (action == null) {
        throw new NullPointerException("The 'action' cannot be null");
    }

    for (I item : items) {
        action.execute(new InjectionStep<T, I>(target, item));
    }
    return target;
}
 
Example #5
Source Project: Pushjet-Android   Author: Pushjet   File: TestResultSerializer.java    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
public void read(Action<? super TestClassResult> visitor) {
    if (!isHasResults()) {
        return;
    }
    try {
        InputStream inputStream = new FileInputStream(resultsFile);
        try {
            Decoder decoder = new KryoBackedDecoder(inputStream);
            int version = decoder.readSmallInt();
            if (version != RESULT_VERSION) {
                throw new IllegalArgumentException(String.format("Unexpected result file version %d found in %s.", version, resultsFile));
            }
            readResults(decoder, visitor);
        } finally {
            inputStream.close();
        }
    } catch (Exception e) {
        throw UncheckedException.throwAsUncheckedException(e);
    }
}
 
Example #6
Source Project: Pushjet-Android   Author: Pushjet   File: PatternSetAntBuilderDelegate.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
private static Object logical(Object node, String op, final Action<Object> withNode) {
    GroovyObject groovyObject = (GroovyObject) node;
    groovyObject.invokeMethod(op, new Closure(null, null) {
        void doCall() {
            withNode.execute(getDelegate());
        }
    });
    return node;
}
 
Example #7
Source Project: crate   Author: crate   File: JdkDownloadPlugin.java    License: Apache License 2.0 5 votes vote down vote up
private static TaskProvider<?> createExtractTask(
    String taskName,
    Project rootProject,
    boolean isWindows,
    Provider<Directory> extractPath,
    Supplier<File> jdkBundle) {
    if (isWindows) {
        Action<CopySpec> removeRootDir = copy -> {
            // remove extra unnecessary directory levels
            copy.eachFile(details -> {
                Path newPathSegments = trimArchiveExtractPath(details.getRelativePath().getPathString());
                String[] segments = StreamSupport.stream(newPathSegments.spliterator(), false)
                    .map(Path::toString)
                    .toArray(String[]::new);
                details.setRelativePath(new RelativePath(true, segments));
            });
            copy.setIncludeEmptyDirs(false);
        };

        return rootProject.getTasks().register(taskName, Copy.class, copyTask -> {
            copyTask.doFirst(t -> rootProject.delete(extractPath));
            copyTask.into(extractPath);
            Callable<FileTree> fileGetter = () -> rootProject.zipTree(jdkBundle.get());
            copyTask.from(fileGetter, removeRootDir);
        });
    } else {
        /*
         * Gradle TarFileTree does not resolve symlinks, so we have to manually
         * extract and preserve the symlinks. cf. https://github.com/gradle/gradle/issues/3982
         * and https://discuss.gradle.org/t/tar-and-untar-losing-symbolic-links/2039
         */
        return rootProject.getTasks().register(taskName, SymbolicLinkPreservingUntarTask.class, task -> {
            task.getTarFile().fileProvider(rootProject.provider(jdkBundle::get));
            task.getExtractPath().set(extractPath);
            task.setTransform(JdkDownloadPlugin::trimArchiveExtractPath);
        });
    }
}
 
Example #8
Source Project: Pushjet-Android   Author: Pushjet   File: DefaultMavenPom.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
public DefaultMavenPom writeTo(Object path) {
    IoActions.writeTextFile(fileResolver.resolve(path), POM_FILE_ENCODING, new Action<BufferedWriter>() {
        public void execute(BufferedWriter writer) {
            writeTo(writer);
        }
    });
    return this;
}
 
Example #9
Source Project: Pushjet-Android   Author: Pushjet   File: DefaultCacheFactory.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
public PersistentCache open(File cacheDir, String displayName, CacheUsage usage, CacheValidator cacheValidator, Map<String, ?> properties, LockOptions lockOptions, Action<? super PersistentCache> initializer) throws CacheOpenException {
    lock.lock();
    try {
        return doOpen(cacheDir, displayName, usage, cacheValidator, properties, lockOptions, initializer);
    } finally {
        lock.unlock();
    }
}
 
Example #10
private <T extends ArtifactRepository> T addWithUniqueName(T repository, String defaultName, Action<? super T> insertion) {
    String repositoryName = repository.getName();
    if (!GUtil.isTrue(repositoryName)) {
        repository.setName(uniquifyName(defaultName));
    } else {
        repository.setName(uniquifyName(repositoryName));
    }

    assertCanAdd(repository.getName());
    insertion.execute(repository);
    return repository;
}
 
Example #11
Source Project: gradle-modules-plugin   Author: java9-modularity   File: CompileTask.java    License: MIT License 5 votes vote down vote up
private void enforceJarForCompilation() {
    Configuration config = project.getConfigurations().getByName(JavaPlugin.COMPILE_CLASSPATH_CONFIGURATION_NAME);
    config.attributes(new Action<AttributeContainer>() {
        @Override
        public void execute(AttributeContainer attributeContainer) {
            if(GradleVersion.current().compareTo(GradleVersion.version("5.6")) < 0) {
                LOGGER.warn("Cannot enforce using JARs for compilation. Please upgrade to Gradle 5.6 or newer.");
                return;
            }
            attributeContainer.attribute(
                    LibraryElements.LIBRARY_ELEMENTS_ATTRIBUTE,
                    project.getObjects().named(LibraryElements.class, LibraryElements.JAR));
        }
    });
}
 
Example #12
Source Project: putnami-gradle-plugin   Author: Putnami   File: PwtPlugin.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
private void createCheckTask(final Project project) {
	project.getTasks().create(GwtCheckTask.NAME, GwtCheckTask.class);
	final PutnamiExtension extension = project.getExtensions().getByType(PutnamiExtension.class);
	final Task checkTask = project.getTasks().getByName(JavaBasePlugin.CHECK_TASK_NAME);
	checkTask.dependsOn(GwtCheckTask.NAME);
	project.getTasks().withType(GwtCheckTask.class, new Action<GwtCheckTask>() {
		@Override
		public void execute(final GwtCheckTask task) {
			task.configure(project, extension);
		}
	});
}
 
Example #13
Source Project: Pushjet-Android   Author: Pushjet   File: DefaultCopySpec.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
public CopySpec expand(final Map<String, ?> properties) {
    copyActions.add(new Action<FileCopyDetails>() {
        public void execute(FileCopyDetails fileCopyDetails) {
            fileCopyDetails.expand(properties);
        }
    });
    return this;
}
 
Example #14
Source Project: Pushjet-Android   Author: Pushjet   File: TaskFactory.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
public TaskInternal createTask(Map<String, ?> args) {
    Map<String, Object> actualArgs = new HashMap<String, Object>(args);
    checkTaskArgsAndCreateDefaultValues(actualArgs);

    String name = actualArgs.get(Task.TASK_NAME).toString();
    if (!GUtil.isTrue(name)) {
        throw new InvalidUserDataException("The task name must be provided.");
    }

    Class<? extends TaskInternal> type = (Class) actualArgs.get(Task.TASK_TYPE);
    Boolean generateSubclass = Boolean.valueOf(actualArgs.get(GENERATE_SUBCLASS).toString());
    TaskInternal task = createTaskObject(project, type, name, generateSubclass);

    Object dependsOnTasks = actualArgs.get(Task.TASK_DEPENDS_ON);
    if (dependsOnTasks != null) {
        task.dependsOn(dependsOnTasks);
    }
    Object description = actualArgs.get(Task.TASK_DESCRIPTION);
    if (description != null) {
        task.setDescription(description.toString());
    }
    Object group = actualArgs.get(Task.TASK_GROUP);
    if (group != null) {
        task.setGroup(group.toString());
    }
    Object action = actualArgs.get(Task.TASK_ACTION);
    if (action instanceof Action) {
        Action<? super Task> taskAction = (Action<? super Task>) action;
        task.doFirst(taskAction);
    } else if (action != null) {
        Closure closure = (Closure) action;
        task.doFirst(closure);
    }

    return task;
}
 
Example #15
Source Project: pushfish-android   Author: PushFish   File: LanguageSourceSetContainer.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Temporarily, we need to have a 'live' connection between a component's 'main' FunctionalSourceSet and the set of LanguageSourceSets for the component.
 * We should be able to do away with this, once sourceSets are part of the model proper.
 */
public void addMainSources(FunctionalSourceSet mainSources) {
    mainSources.all(new Action<LanguageSourceSet>() {
        public void execute(LanguageSourceSet languageSourceSet) {
            add(languageSourceSet);
        }
    });
}
 
Example #16
Source Project: pushfish-android   Author: PushFish   File: StdinSwapper.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
public StdinSwapper() {
    super(
        new Callable<InputStream>() {
            public InputStream call() {
                return System.in;
            }
        },
        new Action<InputStream>() {
            public void execute(InputStream newValue) {
                System.setIn(newValue);
            }
        }
    );
}
 
Example #17
Source Project: Pushjet-Android   Author: Pushjet   File: StatefulIncrementalTaskInputs.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void removed(Action<? super InputFileDetails> removedAction) {
    if (!outOfDateProcessed) {
        throw new IllegalStateException("Must first process outOfDate files before processing removed files");
    }
    if (removedProcessed) {
        throw new IllegalStateException("Cannot process removed files multiple times");
    }
    doRemoved(removedAction);
    removedProcessed = true;
}
 
Example #18
Source Project: Pushjet-Android   Author: Pushjet   File: PatternSet.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
public Object addToAntBuilder(Object node, String childNodeName) {
    return PatternSetAntBuilderDelegate.and(node, new Action<Object>() {
        public void execute(Object andNode) {
            IntersectionPatternSet.super.addToAntBuilder(andNode, null);
            other.addToAntBuilder(andNode, null);
        }
    });
}
 
Example #19
Source Project: Pushjet-Android   Author: Pushjet   File: BuildActionsFactory.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
private Action<? super ExecutionListener> runBuildInProcess(StartParameter startParameter, DaemonParameters daemonParameters, ServiceRegistry loggingServices) {
    ServiceRegistry globalServices = ServiceRegistryBuilder.builder()
            .displayName("Global services")
            .parent(loggingServices)
            .parent(NativeServices.getInstance())
            .provider(new GlobalScopeServices(false))
            .build();
    InProcessBuildActionExecuter executer = new InProcessBuildActionExecuter(globalServices.get(GradleLauncherFactory.class));
    return daemonBuildAction(startParameter, daemonParameters, executer);
}
 
Example #20
Source Project: Pushjet-Android   Author: Pushjet   File: BuildActionsFactory.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
public Action<? super ExecutionListener> createAction(CommandLineParser parser, ParsedCommandLine commandLine) {
    BuildLayoutParameters layout = new BuildLayoutParameters();
    layoutConverter.convert(commandLine, layout);

    Map<String, String> properties = new HashMap<String, String>();
    layoutToPropertiesConverter.convert(layout, properties);
    propertiesConverter.convert(commandLine, properties);

    StartParameter startParameter = new StartParameter();
    propertiesToStartParameterConverter.convert(properties, startParameter);
    commandLineConverter.convert(commandLine, startParameter);

    DaemonParameters daemonParameters = new DaemonParameters(layout);
    propertiesToDaemonParametersConverter.convert(properties, daemonParameters);
    daemonConverter.convert(commandLine, daemonParameters);

    if (commandLine.hasOption(STOP)) {
        return stopAllDaemons(daemonParameters, loggingServices);
    }
    if (commandLine.hasOption(FOREGROUND)) {
        ForegroundDaemonConfiguration conf = new ForegroundDaemonConfiguration(
                daemonParameters.getUid(), daemonParameters.getBaseDir(), daemonParameters.getIdleTimeout());
        return Actions.toAction(new ForegroundDaemonMain(conf));
    }
    if (daemonParameters.isEnabled()) {
        return runBuildWithDaemon(startParameter, daemonParameters, loggingServices);
    }
    if (canUseCurrentProcess(daemonParameters)) {
        return runBuildInProcess(startParameter, daemonParameters, loggingServices);
    }
    return runBuildInSingleUseDaemon(startParameter, daemonParameters, loggingServices);
}
 
Example #21
Source Project: shipkit   Author: mockito   File: GitBranchPlugin.java    License: MIT License 5 votes vote down vote up
@Override
public void apply(Project project) {
    TaskMaker.task(project, IDENTIFY_GIT_BRANCH, IdentifyGitBranchTask.class, new Action<IdentifyGitBranchTask>() {
        public void execute(final IdentifyGitBranchTask t) {
            t.setDescription("Identifies current git branch.");
        }
    });
}
 
Example #22
Source Project: native-samples   Author: gradle   File: CppPublicMacrosPlugin.java    License: Apache License 2.0 5 votes vote down vote up
private static TaskProvider<GeneratePublicMacrosManifest> createTask(TaskContainer tasks) {
    return tasks.register("generatePublicMacros", GeneratePublicMacrosManifest.class, new Action<GeneratePublicMacrosManifest>() {
        @Override
        public void execute(GeneratePublicMacrosManifest task) {
            task.getOutputFile().set(new File(task.getTemporaryDir(), "public-macros.txt"));
        }
    });
}
 
Example #23
Source Project: Pushjet-Android   Author: Pushjet   File: DefaultCachePolicy.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
public boolean mustRefreshVersionList(final ModuleIdentifier moduleIdentifier, Set<ModuleVersionIdentifier> matchingVersions, long ageMillis) {
    CachedDependencyResolutionControl dependencyResolutionControl = new CachedDependencyResolutionControl(moduleIdentifier, matchingVersions, ageMillis);

    for (Action<? super DependencyResolutionControl> rule : dependencyCacheRules) {
        rule.execute(dependencyResolutionControl);
        if (dependencyResolutionControl.ruleMatch()) {
            return dependencyResolutionControl.mustCheck();
        }
    }

    return false;
}
 
Example #24
Source Project: pushfish-android   Author: PushFish   File: BufferingStyledTextOutput.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
protected void doAppend(final String text) {
    if (text.length() == 0) {
        return;
    }
    hasContent = true;
    events.add(new Action<StyledTextOutput>() {
        public void execute(StyledTextOutput styledTextOutput) {
            styledTextOutput.text(text);
        }
    });
}
 
Example #25
public DeprecationListeningPluginResolutionServiceClient(PluginResolutionServiceClient delegate) {
    this(delegate, new Action<String>() {
        public void execute(String s) {
            DeprecationLogger.nagUserWith(s);
        }
    });
}
 
Example #26
public <R extends Serializable, P extends Serializable> RhinoWorkerHandle<R, P> create(Iterable<File> rhinoClasspath, RhinoWorkerSpec<R, P> workerSpec, LogLevel logLevel, Action<JavaExecSpec> javaExecSpecAction) {
    WorkerProcessBuilder builder = workerProcessBuilderFactory.create();
    builder.setBaseName("Gradle Rhino Worker");
    builder.setLogLevel(logLevel);
    builder.applicationClasspath(rhinoClasspath);
    builder.sharedPackages("org.mozilla.javascript");

    JavaExecHandleBuilder javaCommand = builder.getJavaCommand();
    if (javaExecSpecAction != null) {
        javaExecSpecAction.execute(javaCommand);
    }

    WorkerProcess workerProcess = builder.worker(new RhinoServer<R, P>(workerSpec)).build();
    return new DefaultRhinoWorkerHandle<R, P>(workerSpec.getResultType(), workerProcess);
}
 
Example #27
Source Project: Pushjet-Android   Author: Pushjet   File: ModelRegistryBackedModelRules.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
private <T> Class<T> getActionObjectType(Action<T> action) {
    Class<? extends Action> aClass = action.getClass();
    Type[] genericInterfaces = aClass.getGenericInterfaces();
    Type actionType = findFirst(genericInterfaces, new Spec<Type>() {
        public boolean isSatisfiedBy(Type element) {
            return element instanceof ParameterizedType && ((ParameterizedType) element).getRawType().equals(Action.class);
        }
    });

    final Class<?> modelType;

    if (actionType == null) {
        modelType = Object.class;
    } else {
        ParameterizedType actionParamaterizedType = (ParameterizedType) actionType;
        Type tType = actionParamaterizedType.getActualTypeArguments()[0];

        if (tType instanceof Class) {
            modelType = (Class) tType;
        } else if (tType instanceof ParameterizedType) {
            modelType = (Class) ((ParameterizedType) tType).getRawType();
        } else if (tType instanceof TypeVariable) {
            TypeVariable  typeVariable = (TypeVariable) tType;
            Type[] bounds = typeVariable.getBounds();
            return (Class<T>) bounds[0];
        } else {
            throw new RuntimeException("Don't know how to handle type: " + tType.getClass());
        }
    }

    @SuppressWarnings("unchecked") Class<T> castModelType = (Class<T>) modelType;
    return castModelType;
}
 
Example #28
Source Project: Pushjet-Android   Author: Pushjet   File: XmlTransformer.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void transform(File destination, final Action<? super Writer> generator) {
    IoActions.writeTextFile(destination, new Action<Writer>() {
        public void execute(Writer writer) {
            transform(writer, generator);
        }
    });
}
 
Example #29
Source Project: Pushjet-Android   Author: Pushjet   File: DefaultCacheFactory.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
private PersistentCache doOpenStore(File storeDir, String displayName, LockOptions lockOptions, Action<? super PersistentCache> initializer) throws CacheOpenException {
    if (initializer != null) {
        throw new UnsupportedOperationException("Initializer actions are not currently supported by the directory store implementation.");
    }
    File canonicalDir = GFileUtils.canonicalise(storeDir);
    DirCacheReference dirCacheReference = dirCaches.get(canonicalDir);
    if (dirCacheReference == null) {
        ReferencablePersistentCache cache = new DefaultPersistentDirectoryStore(canonicalDir, displayName, lockOptions, lockManager);
        cache.open();
        dirCacheReference = new DirCacheReference(cache, Collections.<String, Object>emptyMap(), lockOptions);
        dirCaches.put(canonicalDir, dirCacheReference);
    }
    return new ReferenceTrackingCache(dirCacheReference);
}
 
Example #30
Source Project: Pushjet-Android   Author: Pushjet   File: ProtocolToModelAdapter.java    License: BSD 2-Clause "Simplified" License 4 votes vote down vote up
private AdaptingMethodInvoker(Action<? super SourceObjectMapping> mapping, MethodInvoker next) {
    this.mapping = mapping;
    this.next = next;
}