org.gradle.util.CollectionUtils Java Examples

The following examples show how to use org.gradle.util.CollectionUtils. 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: EnumFromCharSequenceNotationParser.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public T parseNotation(CharSequence notation) throws UnsupportedNotationException, TypeConversionException {
    final String enumString = notation.toString();
    List<? extends T> enumConstants = Arrays.asList(type.getEnumConstants());
    T match = CollectionUtils.findFirst(enumConstants, new Spec<T>() {
        public boolean isSatisfiedBy(T enumValue) {
            return enumValue.name().equalsIgnoreCase(enumString);
        }
    });
    if (match == null) {
        throw new TypeConversionException(
                String.format("Cannot coerce string value '%s' to an enum value of type '%s' (valid case insensitive values: %s)",
                        enumString, type.getName(), CollectionUtils.toStringList(Arrays.asList(type.getEnumConstants()))
                )
        );
    } else {
        return match;
    }
}
 
Example #2
Source File: CachingModuleVersionRepository.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private void resolveAndCacheModuleArtifacts(ComponentMetaData component, ArtifactResolveContext context, BuildableArtifactSetResolveResult result) {
    final CachingModuleSource cachedModuleSource = (CachingModuleSource) component.getSource();
    ModuleArtifactsCache.CachedArtifacts cachedModuleArtifacts = moduleArtifactsCache.getCachedArtifacts(delegate, component.getId(), context.getId());
    BigInteger moduleDescriptorHash = cachedModuleSource.getDescriptorHash();

    if (cachedModuleArtifacts != null) {
        if (!cachePolicy.mustRefreshModuleArtifacts(component.getId(), null, cachedModuleArtifacts.getAgeMillis(),
                cachedModuleSource.isChangingModule(), moduleDescriptorHash.equals(cachedModuleArtifacts.getDescriptorHash()))) {
            Set<ModuleVersionArtifactMetaData> artifactMetaDataSet = CollectionUtils.collect(cachedModuleArtifacts.getArtifacts(), new ArtifactIdToMetaData());
            result.resolved(artifactMetaDataSet);
            return;
        }

        LOGGER.debug("Artifact listing has expired: will perform fresh resolve of '{}' for '{}' in '{}'", context.getDescription(), component.getId(), delegate.getName());
    }

    delegate.resolveModuleArtifacts(component.withSource(cachedModuleSource.getDelegate()), context, result);

    if (result.getFailure() == null) {
        Set<ModuleVersionArtifactIdentifier> artifactIdentifierSet = CollectionUtils.collect(result.getArtifacts(), new ArtifactMetaDataToId());
        moduleArtifactsCache.cacheArtifacts(delegate, component.getId(), context.getId(), moduleDescriptorHash, artifactIdentifierSet);
    }
}
 
Example #3
Source File: NamedElementSelector.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Return the matching elements: never returns an empty list (at this stage this class chooses the default).
 */
public List<T> transform(NamedDomainObjectContainer<? super T> ts) { //TODO freekh: consider changing to select
    NamedDomainObjectSet<T> allWithType = ts.withType(type);

    if (names.isEmpty()) {
        return Lists.newArrayList(allWithType);
    }

    List<T> matching = Lists.newArrayList();
    final List<String> notFound = Lists.newArrayList(names);
    CollectionUtils.filter(allWithType, matching, new Spec<T>() {
        public boolean isSatisfiedBy(T element) {
            return notFound.remove(element.getName());
        }
    });

    if (notFound.size() == 1) {
        throw new InvalidUserDataException(String.format("Invalid %s: %s", type.getSimpleName(), notFound.get(0)));
    } else if (notFound.size() > 1) {
        throw new InvalidUserDataException(String.format("Invalid %ss: %s", type.getSimpleName(), notFound));
    }
    return matching;
}
 
Example #4
Source File: MethodModelRuleDescriptor.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
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 #5
Source File: BaseDirFileResolver.java    From pushfish-android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public String resolveAsRelativePath(Object path) {
    List<String> basePath = Arrays.asList(StringUtils.split(baseDir.getAbsolutePath(), "/" + File.separator));
    File targetFile = resolve(path);
    List<String> targetPath = new ArrayList<String>(Arrays.asList(StringUtils.split(targetFile.getAbsolutePath(),
            "/" + File.separator)));

    // Find and remove common prefix
    int maxDepth = Math.min(basePath.size(), targetPath.size());
    int prefixLen = 0;
    while (prefixLen < maxDepth && basePath.get(prefixLen).equals(targetPath.get(prefixLen))) {
        prefixLen++;
    }
    basePath = basePath.subList(prefixLen, basePath.size());
    targetPath = targetPath.subList(prefixLen, targetPath.size());

    for (int i = 0; i < basePath.size(); i++) {
        targetPath.add(0, "..");
    }
    if (targetPath.isEmpty()) {
        return ".";
    }
    return CollectionUtils.join(File.separator, targetPath);
}
 
Example #6
Source File: MethodModelRuleDescriptor.java    From pushfish-android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
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 #7
Source File: DefaultOsgiManifest.java    From pushfish-android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
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 #8
Source File: OptionReader.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private static JavaMethod<Object, Collection> getOptionValueMethodForOption(List<JavaMethod<Object, Collection>> optionValueMethods, OptionElement optionElement) {
    JavaMethod<Object, Collection> valueMethod = null;
    for (JavaMethod<Object, Collection> optionValueMethod : optionValueMethods) {
        OptionValues optionValues = optionValueMethod.getMethod().getAnnotation(OptionValues.class);
        if (CollectionUtils.toList(optionValues.value()).contains(optionElement.getOptionName())) {
                        if (valueMethod == null) {
                            valueMethod = optionValueMethod;
                        } else {
                            throw new OptionValidationException(
                                    String.format("@OptionValues for '%s' cannot be attached to multiple methods in class '%s'.",
                                            optionElement.getOptionName(),
                                            optionValueMethod.getMethod().getDeclaringClass().getName()));
                        }
                    }
    }
    return valueMethod;
}
 
Example #9
Source File: DefaultLenientConfiguration.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Recursive but excludes unsuccessfully resolved artifacts.
 *
 * @param dependencySpec dependency spec
 */
public Set<ResolvedArtifact> getArtifacts(Spec<? super Dependency> dependencySpec) {
    final Set<ResolvedArtifact> allArtifacts = getAllArtifacts(dependencySpec);
    return cacheLockingManager.useCache("retrieve artifacts from " + configuration, new Factory<Set<ResolvedArtifact>>() {
        public Set<ResolvedArtifact> create() {
            return CollectionUtils.filter(allArtifacts, new Spec<ResolvedArtifact>() {
                public boolean isSatisfiedBy(ResolvedArtifact element) {
                    try {
                        File file = element.getFile();
                        return file != null;
                    } catch (ArtifactResolveException e) {
                        return false;
                    }
                }
            });
        }
    });
}
 
Example #10
Source File: ReflectiveRule.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private static void registerMutator(ModelRegistry modelRegistry, ModelRule modelRule, final Method bindingMethod, final List<BindableParameter<?>> bindings) {
    BindableParameter<?> first = bindings.get(0);
    List<BindableParameter<?>> tail = bindings.subList(1, bindings.size());
    ModelMutator<?> modelMutator = toMutator(modelRule, bindingMethod, first, tail);

    String path = first.getPath().toString();
    List<String> bindingPaths = CollectionUtils.collect(tail, new Transformer<String, BindableParameter<?>>() {
        public String transform(BindableParameter<?> bindableParameter) {
            return bindableParameter.getPath().toString();
        }
    });

    if (modelRule instanceof ModelFinalizer) {
        modelRegistry.finalize(path, bindingPaths, modelMutator);
    } else {
        modelRegistry.mutate(path, bindingPaths, modelMutator);
    }
}
 
Example #11
Source File: GroupsJavadocOptionFileOption.java    From pushfish-android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public void write(JavadocOptionFileWriterContext writerContext) throws IOException {
    if (value != null && !value.isEmpty()) {
        for (final String group : value.keySet()) {
            final List<String> groupPackages = value.get(group);

            writerContext
                .writeOptionHeader(option)
                .write(
                    new StringBuffer()
                        .append("\"")
                        .append(group)
                        .append("\"")
                        .toString())
                .write(" ")
                .write(
                    new StringBuffer()
                        .append("\"")
                        .append(CollectionUtils.join(":", groupPackages))
                        .append("\"")
                        .toString())
                .newLine();
        }
    }
}
 
Example #12
Source File: UnboundRulesProcessor.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private UnboundRuleInput.Builder toInputBuilder(ModelBinding<?> binding, ModelReference<?> reference) {
    UnboundRuleInput.Builder builder = UnboundRuleInput.type(reference.getType());
    ModelPath path;
    if (binding != null) {
        builder.bound();
        path = binding.getPath();
    } else {
        path = reference.getPath();
        if (path != null) {
            builder.suggestions(CollectionUtils.stringize(suggestionsProvider.transform(path)));
        }
    }
    if (path != null) {
        builder.path(path);
    }
    builder.description(reference.getDescription());
    return builder;
}
 
Example #13
Source File: DefaultIvyExtraInfo.java    From pushfish-android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public String get(String name) {
    List<Map.Entry<NamespaceId, String>> foundEntries = new ArrayList<Map.Entry<NamespaceId, String>>();
    for (Map.Entry<NamespaceId, String> entry : extraInfo.entrySet()) {
        if (entry.getKey().getName().equals(name)) {
            foundEntries.add(entry);
        }
    }
    if (foundEntries.size() > 1) {
        String allNamespaces = Joiner.on(", ").join(CollectionUtils.collect(foundEntries, new Transformer<String, Map.Entry<NamespaceId, String>>() {
            public String transform(Map.Entry<NamespaceId, String> original) {
                return original.getKey().getNamespace();
            }
        }));
        throw new InvalidUserDataException(String.format("Cannot get extra info element named '%s' by name since elements with this name were found from multiple namespaces (%s).  Use get(String namespace, String name) instead.", name, allNamespaces));
    }
    return foundEntries.size() == 0 ? null : foundEntries.get(0).getValue();
}
 
Example #14
Source File: IvyXmlModuleDescriptorParser.java    From pushfish-android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private Map<String, String> populateProperties() {
    HashMap<String, String> properties = new HashMap<String, String>();
    String baseDir = new File(".").getAbsolutePath();
    properties.put("ivy.default.settings.dir", baseDir);
    properties.put("ivy.basedir", baseDir);

    Set<String> propertyNames = CollectionUtils.collect(System.getProperties().entrySet(), new Transformer<String, Map.Entry<Object, Object>>() {
        public String transform(Map.Entry<Object, Object> entry) {
            return entry.getKey().toString();
        }
    });

    for (String property : propertyNames) {
        properties.put(property, System.getProperty(property));
    }
    return properties;
}
 
Example #15
Source File: ExternalResourceResolver.java    From pushfish-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public List<String> getArtifactPatterns() {
    return CollectionUtils.collect(artifactPatterns, new Transformer<String, ResourcePattern>() {
        public String transform(ResourcePattern original) {
            return original.getPattern();
        }
    });
}
 
Example #16
Source File: DefaultModuleVersionListing.java    From pushfish-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public String toString() {
    return CollectionUtils.collect(versions, new Transformer<String, Versioned>() {
        public String transform(Versioned original) {
            return original.getVersion();
        }
    }).toString();
}
 
Example #17
Source File: ModelRegistry.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
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 #18
Source File: GenerateBuildDashboard.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private Set<Report> getEnabledInputReports() {
    Set<NamedDomainObjectSet<? extends Report>> enabledReportSets = CollectionUtils.collect(aggregated, new Transformer<NamedDomainObjectSet<? extends Report>, Reporting<? extends ReportContainer<?>>>() {
        public NamedDomainObjectSet<? extends Report> transform(Reporting<? extends ReportContainer<?>> reporting) {
            return reporting.getReports().getEnabled();
        }
    });
    return new LinkedHashSet<Report>(CollectionUtils.flattenCollections(Report.class, enabledReportSets));
}
 
Example #19
Source File: GenerateBuildDashboard.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private Set<Report> getEnabledInputReports() {
    Set<NamedDomainObjectSet<? extends Report>> enabledReportSets = CollectionUtils.collect(aggregated, new Transformer<NamedDomainObjectSet<? extends Report>, Reporting<? extends ReportContainer<?>>>() {
        public NamedDomainObjectSet<? extends Report> transform(Reporting<? extends ReportContainer<?>> reporting) {
            return reporting.getReports().getEnabled();
        }
    });
    return new LinkedHashSet<Report>(CollectionUtils.flattenCollections(Report.class, enabledReportSets));
}
 
Example #20
Source File: TaskReportRenderer.java    From pushfish-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Writes the default task names for the current project.
 *
 * @param defaultTaskNames The default task names (must not be null)
 */
public void addDefaultTasks(List<String> defaultTaskNames) {
    if (defaultTaskNames.size() > 0) {
        getTextOutput().formatln("Default tasks: %s", CollectionUtils.join(", ", defaultTaskNames));
        hasContent = true;
    }
}
 
Example #21
Source File: ReleasedVersionDistributions.java    From pushfish-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public List<GradleDistribution> getAll() {
    if (distributions == null) {
        distributions = CollectionUtils.collect(getProperties().getProperty("versions").split("\\s+"), new Transformer<GradleDistribution, String>() {
            public GradleDistribution transform(String version) {
                return buildContext.distribution(version);
            }
        });
    }
    return distributions;
}
 
Example #22
Source File: JUnitTestClassExecuter.java    From pushfish-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private void runTestClass(String testClassName) throws ClassNotFoundException {
    final Class<?> testClass = Class.forName(testClassName, false, applicationClassLoader);
    Request request = Request.aClass(testClass);
    if (options.hasCategoryConfiguration()) {
        Transformer<Class<?>, String> transformer = new Transformer<Class<?>, String>() {
            public Class<?> transform(final String original) {
                try {
                    return applicationClassLoader.loadClass(original);
                } catch (ClassNotFoundException e) {
                    throw new InvalidUserDataException(String.format("Can't load category class [%s].", original), e);
                }
            }
        };
        request = request.filterWith(new CategoryFilter(
                CollectionUtils.collect(options.getIncludeCategories(), transformer),
                CollectionUtils.collect(options.getExcludeCategories(), transformer)
        ));
    }

    if (!options.getIncludedTests().isEmpty()) {
        request = request.filterWith(new MethodNameFilter(options.getIncludedTests()));
    }

    Runner runner = request.getRunner();
    //In case of no matching methods junit will return a ErrorReportingRunner for org.junit.runner.manipulation.Filter.class.
    //Will be fixed with adding class filters
    if (!org.junit.runner.manipulation.Filter.class.getName().equals(runner.getDescription().getDisplayName())) {
        RunNotifier notifier = new RunNotifier();
        notifier.addListener(listener);
        runner.run(notifier);
    }
}
 
Example #23
Source File: NativeBinaryResolveResult.java    From pushfish-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public List<NativeDependencySet> getAllResults() {
    return CollectionUtils.collect(getAllResolutions(), new Transformer<NativeDependencySet, NativeBinaryRequirementResolveResult>() {
        public NativeDependencySet transform(NativeBinaryRequirementResolveResult original) {
            return original.getNativeDependencySet();
        }
    });
}
 
Example #24
Source File: OptionReader.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public List<OptionDescriptor> getOptions(Object target) {
    final Class<?> targetClass = target.getClass();
    Map<String, OptionDescriptor> options = new HashMap<String, OptionDescriptor>();
    if (!cachedOptionElements.containsKey(targetClass)) {
        loadClassDescriptorInCache(target);
    }
    for (OptionElement optionElement : cachedOptionElements.get(targetClass)) {
        JavaMethod<Object, Collection> optionValueMethod = cachedOptionValueMethods.get(optionElement);
        options.put(optionElement.getOptionName(), new InstanceOptionDescriptor(target, optionElement, optionValueMethod));
    }
    return CollectionUtils.sort(options.values());
}
 
Example #25
Source File: TaskSelector.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public Set<Task> getTasks() {
    return CollectionUtils.collect(taskSelectionResult, new LinkedHashSet<Task>(), new Transformer<Task, TaskSelectionResult>() {
        public Task transform(TaskSelectionResult original) {
            return original.getTask();
        }
    });
}
 
Example #26
Source File: BuildProfile.java    From pushfish-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public CompositeOperation<Operation> getProjectConfiguration() {
    List<Operation> operations = new ArrayList<Operation>();
    for (ProjectProfile projectProfile : projects.values()) {
        operations.add(projectProfile.getConfigurationOperation());
    }
    operations = CollectionUtils.sort(operations, Operation.slowestFirst());
    return new CompositeOperation<Operation>(operations);
}
 
Example #27
Source File: GradleBuildOutcomeSetInferrer.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public Set<BuildOutcome> transform(Set<BuildOutcome> sourceOutcomes) {
    return CollectionUtils.collect(sourceOutcomes, new HashSet<BuildOutcome>(sourceOutcomes.size()), new Transformer<BuildOutcome, BuildOutcome>() {
        public BuildOutcome transform(BuildOutcome original) {
            return infer(original);
        }
    });
}
 
Example #28
Source File: DefaultModuleVersionListing.java    From pushfish-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public String toString() {
    return CollectionUtils.collect(versions, new Transformer<String, Versioned>() {
        public String transform(Versioned original) {
            return original.getVersion();
        }
    }).toString();
}
 
Example #29
Source File: DefaultModuleVersionListing.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public String toString() {
    return CollectionUtils.collect(versions, new Transformer<String, Versioned>() {
        public String transform(Versioned original) {
            return original.getVersion();
        }
    }).toString();
}
 
Example #30
Source File: NativeBinaryResolveResult.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public List<NativeBinaryRequirementResolveResult> getPendingResolutions() {
    return CollectionUtils.filter(resolutions, new Spec<NativeBinaryRequirementResolveResult>() {
        public boolean isSatisfiedBy(NativeBinaryRequirementResolveResult element) {
            return !element.isComplete();
        }
    });
}