Java Code Examples for org.gradle.api.specs.Spec

The following examples show how to use org.gradle.api.specs.Spec. 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
public static ModelRuleDescriptor of(Class<?> clazz, final String methodName) {
    List<Method> methodsOfName = CollectionUtils.filter(clazz.getDeclaredMethods(), new Spec<Method>() {
        public boolean isSatisfiedBy(Method element) {
            return element.getName().equals(methodName);
        }
    });

    if (methodsOfName.isEmpty()) {
        throw new IllegalStateException("Class " + clazz.getName() + " has no method named '" + methodName + "'");
    }

    if (methodsOfName.size() > 1) {
        throw new IllegalStateException("Class " + clazz.getName() + " has more than one method named '" + methodName + "'");
    }

    return new MethodModelRuleDescriptor(methodsOfName.get(0));
}
 
Example 2
private void configureSourceSetDefaults(final JavaBasePlugin javaBasePlugin) {
    project.getConvention().getPlugin(JavaPluginConvention.class).getSourceSets().all(new Action<SourceSet>() {
        public void execute(SourceSet sourceSet) {
            final DefaultGroovySourceSet groovySourceSet = new DefaultGroovySourceSet(((DefaultSourceSet) sourceSet).getDisplayName(), fileResolver);
            new DslObject(sourceSet).getConvention().getPlugins().put("groovy", groovySourceSet);

            groovySourceSet.getGroovy().srcDir(String.format("src/%s/groovy", sourceSet.getName()));
            sourceSet.getResources().getFilter().exclude(new Spec<FileTreeElement>() {
                public boolean isSatisfiedBy(FileTreeElement element) {
                    return groovySourceSet.getGroovy().contains(element.getFile());
                }
            });
            sourceSet.getAllJava().source(groovySourceSet.getGroovy());
            sourceSet.getAllSource().source(groovySourceSet.getGroovy());

            String compileTaskName = sourceSet.getCompileTaskName("groovy");
            GroovyCompile compile = project.getTasks().create(compileTaskName, GroovyCompile.class);
            javaBasePlugin.configureForSourceSet(sourceSet, compile);
            compile.dependsOn(sourceSet.getCompileJavaTaskName());
            compile.setDescription(String.format("Compiles the %s Groovy source.", sourceSet.getName()));
            compile.setSource(groovySourceSet.getGroovy());

            project.getTasks().getByName(sourceSet.getClassesTaskName()).dependsOn(compileTaskName);
        }
    });
}
 
Example 3
private Map<String, List<String>> getModelledInstructions() {
    Map<String, List<String>> modelledInstructions = new HashMap<String, List<String>>();
    modelledInstructions.put(Analyzer.BUNDLE_SYMBOLICNAME, createListFromPropertyString(symbolicName));
    modelledInstructions.put(Analyzer.BUNDLE_NAME, createListFromPropertyString(name));
    modelledInstructions.put(Analyzer.BUNDLE_VERSION, createListFromPropertyString(version));
    modelledInstructions.put(Analyzer.BUNDLE_DESCRIPTION, createListFromPropertyString(description));
    modelledInstructions.put(Analyzer.BUNDLE_LICENSE, createListFromPropertyString(description));
    modelledInstructions.put(Analyzer.BUNDLE_VENDOR, createListFromPropertyString(vendor));
    modelledInstructions.put(Analyzer.BUNDLE_DOCURL, createListFromPropertyString(docURL));

    return CollectionUtils.filter(modelledInstructions, new Spec<Map.Entry<String, List<String>>>() {
        public boolean isSatisfiedBy(Map.Entry<String, List<String>> element) {
            return element.getValue() != null;
        }
    });
}
 
Example 4
/**
 * Recursive, includes unsuccessfully resolved artifacts
 *
 * @param dependencySpec dependency spec
 */
public Set<ResolvedArtifact> getAllArtifacts(Spec<? super Dependency> dependencySpec) {
    //this is not very nice might be good enough until we get rid of ResolvedConfiguration and friends
    //avoid traversing the graph causing the full ResolvedDependency graph to be loaded for the most typical scenario
    if (dependencySpec == Specs.SATISFIES_ALL) {
        return results.getArtifacts();
    }

    CachingDirectedGraphWalker<ResolvedDependency, ResolvedArtifact> walker
            = new CachingDirectedGraphWalker<ResolvedDependency, ResolvedArtifact>(new ResolvedDependencyArtifactsGraph());

    Set<ResolvedDependency> firstLevelModuleDependencies = getFirstLevelModuleDependencies(dependencySpec);

    Set<ResolvedArtifact> artifacts = new LinkedHashSet<ResolvedArtifact>();

    for (ResolvedDependency resolvedDependency : firstLevelModuleDependencies) {
        artifacts.addAll(resolvedDependency.getParentArtifacts(results.more().getRoot()));
        walker.add(resolvedDependency);
    }

    artifacts.addAll(walker.findValues());
    return artifacts;
}
 
Example 5
public Spec<Task> getFilter(String path) {
    final ResolvedTaskPath taskPath = taskPathResolver.resolvePath(path, gradle.getDefaultProject());
    if (!taskPath.isQualified()) {
        ProjectInternal targetProject = taskPath.getProject();
        configurer.configure(targetProject);
        TaskSelectionResult tasks = taskNameResolver.selectWithName(taskPath.getTaskName(), taskPath.getProject(), true);
        if (tasks != null) {
            // An exact match in the target project - can just filter tasks by path to avoid configuring sub-projects at this point
            return new TaskPathSpec(targetProject, taskPath.getTaskName());
        }
    }

    final Set<Task> selectedTasks = getSelection(path, gradle.getDefaultProject()).getTasks();
    return new Spec<Task>() {
        public boolean isSatisfiedBy(Task element) {
            return !selectedTasks.contains(element);
        }
    };
}
 
Example 6
Source Project: atlas   Source File: BuildAtlasEnvTask.java    License: Apache License 2.0 6 votes vote down vote up
@Nullable
private static Spec<ComponentIdentifier> getComponentFilter(
        @NonNull AndroidArtifacts.ArtifactScope scope) {
    switch (scope) {
        case ALL:
            return null;
        case EXTERNAL:
            // since we want both Module dependencies and file based dependencies in this case
            // the best thing to do is search for non ProjectComponentIdentifier.
            return id -> !(id instanceof ProjectComponentIdentifier);
        case MODULE:
            return id -> id instanceof ProjectComponentIdentifier;
        default:
            throw new RuntimeException("unknown ArtifactScope value");
    }
}
 
Example 7
public List<Spec<FileTreeElement>> getAllExcludeSpecs() {
    List<Spec<FileTreeElement>> result = new ArrayList<Spec<FileTreeElement>>();
    if (parentResolver != null) {
        result.addAll(parentResolver.getAllExcludeSpecs());
    }
    result.addAll(patternSet.getExcludeSpecs());
    return result;
}
 
Example 8
public static Method findBindingMethod(Object object) {
    Class<?> objectClass = object.getClass();
    List<Method> declaredMethods = filter(Arrays.asList(objectClass.getDeclaredMethods()), new Spec<Method>() {
        public boolean isSatisfiedBy(Method element) {
            int modifiers = element.getModifiers();
            return !isPrivate(modifiers) && !isStatic(modifiers) && !element.isSynthetic();
        }
    });
    if (declaredMethods.size() != 1) {
        throw new IllegalArgumentException(objectClass + " rule must have exactly 1 public method, has: " + join(", ", toStringList(declaredMethods)));
    }

    return declaredMethods.get(0);
}
 
Example 9
private Spec<StackTraceElement> createCompositeFilter(TestDescriptor descriptor) {
    List<Spec<StackTraceElement>> filters = Lists.newArrayList();
    for (TestStackTraceFilter type : testLogging.getStackTraceFilters()) {
        filters.add(createFilter(descriptor, type));
    }
    return new AndSpec<StackTraceElement>(filters);
}
 
Example 10
Source Project: javaide   Source File: AbstractReportTask.java    License: GNU General Public License v3.0 5 votes vote down vote up
protected AbstractReportTask() {
    getOutputs().upToDateWhen(new Spec<Task>() {
        public boolean isSatisfiedBy(Task element) {
            return false;
        }
    });
    projects = new HashSet<Project>();
    projects.add(getProject());
}
 
Example 11
private MavenArtifact determineMainArtifact(String publicationName, Set<MavenArtifact> mavenArtifacts) {
    Set<MavenArtifact> candidateMainArtifacts = CollectionUtils.filter(mavenArtifacts, new Spec<MavenArtifact>() {
        public boolean isSatisfiedBy(MavenArtifact element) {
            return element.getClassifier() == null || element.getClassifier().length() == 0;
        }
    });
    if (candidateMainArtifacts.isEmpty()) {
        return null;
    }
    if (candidateMainArtifacts.size() > 1) {
        throw new InvalidMavenPublicationException(publicationName, "Cannot determine main artifact - multiple artifacts found with empty classifier.");
    }
    return candidateMainArtifacts.iterator().next();
}
 
Example 12
public static <E> boolean replace(List<E> list, Spec<? super E> filter, Transformer<? extends E, ? super E> transformer) {
    boolean replaced = false;
    int i = 0;
    for (E it : list) {
        if (filter.isSatisfiedBy(it)) {
            list.set(i, transformer.transform(it));
            replaced = true;
        }
        ++i;
    }
    return replaced;
}
 
Example 13
public static <T> T findFirst(T[] source, Spec<? super T> filter) {
    for (T thing : source) {
        if (filter.isSatisfiedBy(thing)) {
            return thing;
        }
    }

    return null;
}
 
Example 14
public void configure(BuildExecutionContext context) {
    GradleInternal gradle = context.getGradle();
    Set<String> excludedTaskNames = gradle.getStartParameter().getExcludedTaskNames();
    if (!excludedTaskNames.isEmpty()) {
        final Set<Spec<Task>> filters = new HashSet<Spec<Task>>();
        for (String taskName : excludedTaskNames) {
            filters.add(taskSelector.getFilter(taskName));
        }
        gradle.getTaskGraph().useFilter(Specs.and(filters));
    }

    context.proceed();
}
 
Example 15
private void closeChild(Object parent, ModelPath childPath) {
    try {
        String fieldName = childPath.getName();
        final String setterName = String.format("set%s%s", fieldName.substring(0, 1).toUpperCase(), fieldName.substring(1));
        Method setter = CollectionUtils.findFirst(parent.getClass().getDeclaredMethods(), new Spec<Method>() {
            public boolean isSatisfiedBy(Method method) {
                return method.getName().equals(setterName);
            }
        });
        setter.invoke(parent, get(childPath));
    } catch (Exception e) {
        throw new GradleException("Could not close model element children", e);
    }
}
 
Example 16
private <K, V extends Response<?>> V maybeFetch(String operationName, final PersistentIndexedCache<K, V> cache, final K key, Factory<V> factory, Spec<? super V> shouldFetch) {
    V cachedValue = cacheAccess.useCache(operationName + " - read", new Factory<V>() {
        public V create() {
            return cache.get(key);
        }
    });

    boolean fetch = cachedValue == null || shouldFetch.isSatisfiedBy(cachedValue);
    if (fetch) {
        return fetch(operationName, cache, key, factory);
    } else {
        return cachedValue;
    }
}
 
Example 17
public Set<File> getFiles(Spec<? super Dependency> dependencySpec) throws ResolveException {
    try {
        return resolvedConfiguration.getFiles(dependencySpec);
    } catch (Throwable e) {
        throw wrapException(e, configuration);
    }
}
 
Example 18
public SingleIncludePatternFileTree(File baseDir, String includePattern, Spec<FileTreeElement> excludeSpec) {
    this.baseDir = baseDir;
    if (includePattern.endsWith("/") || includePattern.endsWith("\\")) {
        includePattern += "**";
    }
    this.includePattern = includePattern;
    this.patternSegments = Arrays.asList(includePattern.split("[/\\\\]"));
    this.excludeSpec = excludeSpec;
}
 
Example 19
private SpecRuleAction<? super ComponentSelection> createSpecRuleActionFromId(Object id, RuleAction<? super ComponentSelection> ruleAction) {
    final ModuleIdentifier moduleIdentifier;

    try {
        moduleIdentifier = moduleIdentifierNotationParser.parseNotation(id);
    } catch (UnsupportedNotationException e) {
        throw new InvalidUserCodeException(String.format(INVALID_SPEC_ERROR, id == null ? "null" : id.toString()), e);
    }

    Spec<ComponentSelection> spec = new ComponentSelectionMatchingSpec(moduleIdentifier);
    return new SpecRuleAction<ComponentSelection>(ruleAction, spec);
}
 
Example 20
Set<File> getFiles(Spec<? super Dependency> dependencySpec) {
    Set<Dependency> selectedDependencies = CollectionUtils.filter(dependencies, dependencySpec);
    for (Dependency dependency : selectedDependencies) {
        resolveContext.add(dependency);
    }
    return resolveContext.resolve().getFiles();
}
 
Example 21
public boolean isBuildsAreIdentical() {
    //noinspection SimplifiableIfStatement
    if (!getUncomparedSourceOutcomes().isEmpty() || !getUncomparedTargetOutcomes().isEmpty()) {
        return false;
    } else {
        return CollectionUtils.every(comparisons, new Spec<BuildOutcomeComparisonResult<?>>() {
            public boolean isSatisfiedBy(BuildOutcomeComparisonResult<?> comparisonResult) {
                return comparisonResult.isOutcomesAreIdentical();
            }
        });
    }
}
 
Example 22
public void setOnlyIf(final Spec<? super Task> spec) {
    taskMutator.mutate("Task.setOnlyIf(Spec)", new Runnable() {
        public void run() {
            onlyIfSpec = createNewOnlyIfSpec().and(spec);
        }
    });
}
 
Example 23
public CompareGradleBuilds() {
    FileResolver fileResolver = getFileResolver();
    Instantiator instantiator = getInstantiator();
    sourceBuild = instantiator.newInstance(DefaultGradleBuildInvocationSpec.class, fileResolver, getProject().getRootDir());
    sourceBuild.setTasks(DEFAULT_TASKS);
    targetBuild = instantiator.newInstance(DefaultGradleBuildInvocationSpec.class, fileResolver, getProject().getRootDir());
    targetBuild.setTasks(DEFAULT_TASKS);

    // Never up to date
    getOutputs().upToDateWhen(new Spec<Task>() {
        public boolean isSatisfiedBy(Task element) {
            return false;
        }
    });
}
 
Example 24
public HtmlDependencyReportTask() {
    reports = getServices().get(Instantiator.class).newInstance(DefaultDependencyReportContainer.class, this);
    reports.getHtml().setEnabled(true);
    getOutputs().upToDateWhen(new Spec<Task>() {
        public boolean isSatisfiedBy(Task element) {
            return false;
        }
    });
}
 
Example 25
public Spec<DependencyResult> parseNotation(final Object notation) throws UnsupportedNotationException {
    if (notation instanceof CharSequence) {
        final String stringNotation = notation.toString().trim();
        if (stringNotation.length() > 0) {
            return new DependencyResultSpec(stringNotation);
        }
    }
    throw new UnsupportedNotationException(notation);
}
 
Example 26
public static NotationParser<Object, Spec<DependencyResult>> create() {
    return NotationParserBuilder
            .toType(new TypeInfo<Spec<DependencyResult>>(Spec.class))
            .invalidNotationMessage("Please check the input for the DependencyInsight.dependency element.")
            .fromType(Closure.class, new ClosureToSpecNotationParser<DependencyResult>(DependencyResult.class))
            .fromCharSequence(new DependencyResultSpecNotationParser())
            .toComposite();
}
 
Example 27
public List<Spec<FileTreeElement>> getAllIncludeSpecs() {
    List<Spec<FileTreeElement>> result = new ArrayList<Spec<FileTreeElement>>();
    if (parentResolver != null) {
        result.addAll(parentResolver.getAllIncludeSpecs());
    }
    result.addAll(patternSet.getIncludeSpecs());
    return result;
}
 
Example 28
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 29
public FindBugsSpec build() {
    ArrayList<String> args = new ArrayList<String>();
    args.add("-pluginList");
    args.add(pluginsList==null ? "" : pluginsList.getAsPath());
    args.add("-sortByClass");
    args.add("-timestampNow");
    args.add("-progress");

    if (reports != null && !reports.getEnabled().isEmpty()) {
        if (reports.getEnabled().size() == 1) {
            FindBugsReportsImpl reportsImpl = (FindBugsReportsImpl) reports;
            String outputArg = "-" + reportsImpl.getFirstEnabled().getName();
            if (reportsImpl.getFirstEnabled() instanceof FindBugsXmlReportImpl) {
                FindBugsXmlReportImpl r = (FindBugsXmlReportImpl)reportsImpl.getFirstEnabled();
                if (r.isWithMessages()) {
                    outputArg += ":withMessages";
                }
            }
            args.add(outputArg);
            args.add("-outputFile");
            args.add(reportsImpl.getFirstEnabled().getDestination().getAbsolutePath());
        } else {
            throw new InvalidUserDataException("FindBugs tasks can only have one report enabled, however more than one report was enabled. You need to disable all but one of them.");
        }
    }

    if (has(sources)) {
        args.add("-sourcepath");
        args.add(sources.getAsPath());
    }

    if (has(classpath)) {
        args.add("-auxclasspath");

        // Filter unexisting files as FindBugs can't handle them.
        args.add(classpath.filter(new Spec<File>() {
            public boolean isSatisfiedBy(File element) {
                return element.exists();
            }
        }).getAsPath());
    }

    if (has(effort)) {
        args.add(String.format("-effort:%s", effort));
    }

    if (has(reportLevel)) {
        args.add(String.format("-%s", reportLevel));
    }

    if (has(visitors)) {
        args.add("-visitors");
        args.add(CollectionUtils.join(",", visitors));
    }

    if (has(omitVisitors)) {
        args.add("-omitVisitors");
        args.add(CollectionUtils.join(",", omitVisitors));
    }

    if (has(excludeFilter)) {
        args.add("-exclude");
        args.add(excludeFilter.getPath());
    }

    if (has(includeFilter)) {
        args.add("-include");
        args.add(includeFilter.getPath());
    }

    for (File classFile : classes.getFiles()) {
        args.add(classFile.getAbsolutePath());
    }
    
    return new FindBugsSpec(args, maxHeapSize, debugEnabled);
}
 
Example 30
public void upToDateWhen(Spec<? super Task> upToDateSpec) {
    taskStatusNagger.nagIfTaskNotInConfigurableState("TaskOutputs.upToDateWhen(Spec)");
    this.upToDateSpec = this.upToDateSpec.and(upToDateSpec);
}