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
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 Project: Pushjet-Android   Author: Pushjet   File: UnboundRulesProcessor.java    License: 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 #3
Source Project: Pushjet-Android   Author: Pushjet   File: ReflectiveRule.java    License: 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 #4
Source Project: Pushjet-Android   Author: Pushjet   File: OptionReader.java    License: 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 #5
Source Project: pushfish-android   Author: PushFish   File: MethodModelRuleDescriptor.java    License: 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 #6
Source Project: Pushjet-Android   Author: Pushjet   File: MethodModelRuleDescriptor.java    License: 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 Project: Pushjet-Android   Author: Pushjet   File: CachingModuleVersionRepository.java    License: 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 #8
Source Project: pushfish-android   Author: PushFish   File: BaseDirFileResolver.java    License: 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 #9
Source Project: pushfish-android   Author: PushFish   File: DefaultOsgiManifest.java    License: 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 #10
Source Project: pushfish-android   Author: PushFish   File: DefaultIvyExtraInfo.java    License: 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 #11
Source Project: pushfish-android   Author: PushFish   File: IvyXmlModuleDescriptorParser.java    License: 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 #12
Source Project: Pushjet-Android   Author: Pushjet   File: NamedElementSelector.java    License: 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 #13
Source Project: Pushjet-Android   Author: Pushjet   File: DefaultLenientConfiguration.java    License: 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 #14
Source Project: pushfish-android   Author: PushFish   File: GroupsJavadocOptionFileOption.java    License: 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 #15
Source Project: pushfish-android   Author: PushFish   File: BuildProfile.java    License: 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 #16
Source Project: Pushjet-Android   Author: Pushjet   File: DefaultTemporaryFileProvider.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
public File createTemporaryFile(String prefix, @Nullable String suffix, String... path) {
    File dir = new File(baseDirFactory.create(), CollectionUtils.join("/", path));
    GFileUtils.mkdirs(dir);
    try {
        return File.createTempFile(prefix, suffix, dir);
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
 
Example #17
Source Project: pushfish-android   Author: PushFish   File: JUnitTestClassExecuter.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
private void runTestClass(String testClassName) throws ClassNotFoundException {
    final Class<?> testClass = Class.forName(testClassName, true, 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 #18
Source Project: Pushjet-Android   Author: Pushjet   File: OptionReader.java    License: 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 #19
Source Project: pushfish-android   Author: PushFish   File: DefaultTemporaryFileProvider.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
public File createTemporaryFile(String prefix, @Nullable String suffix, String... path) {
    File dir = new File(baseDirFactory.create(), CollectionUtils.join("/", path));
    GFileUtils.mkdirs(dir);
    try {
        return File.createTempFile(prefix, suffix, dir);
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
 
Example #20
Source Project: pushfish-android   Author: PushFish   File: ProjectionBackedModelCreator.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
public <B> boolean asWritable(final ModelType<B> type) {
    return CollectionUtils.any(projections, new Spec<ModelProjection<? super T>>() {
        public boolean isSatisfiedBy(ModelProjection<? super T> projection) {
            return projection.canBeViewedAsWritable(type);
        }
    });
}
 
Example #21
Source Project: Pushjet-Android   Author: Pushjet   File: BuildComparisonResult.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
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
Source Project: pushfish-android   Author: PushFish   File: OptionReader.java    License: 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 #23
Source Project: Pushjet-Android   Author: Pushjet   File: DefaultModuleVersionListing.java    License: 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 #24
Source Project: Pushjet-Android   Author: Pushjet   File: NativeBinaryResolveResult.java    License: 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();
        }
    });
}
 
Example #25
Source Project: pushfish-android   Author: PushFish   File: ReferenceDetectingVisitor.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
private <T extends Expression> void extractReferencePath(T expression, Action<T> action) {
    boolean topLevel = referenceStack.isEmpty();
    action.execute(expression);
    if (topLevel) {
        if (referenceEncountered) {
            String path = CollectionUtils.join(".", referenceStack);
            expression.setNodeMetaData(AST_NODE_REFERENCE_PATH_KEY, path);
            referenceEncountered = false;
        }
        referenceStack.clear();
    }
}
 
Example #26
Source Project: Pushjet-Android   Author: Pushjet   File: TaskSelector.java    License: 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 #27
Source Project: pushfish-android   Author: PushFish   File: DefaultModuleVersionListing.java    License: 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 #28
Source Project: Pushjet-Android   Author: Pushjet   File: OptionReader.java    License: 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 #29
Source Project: Pushjet-Android   Author: Pushjet   File: NativeBinaryResolveResult.java    License: 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();
        }
    });
}
 
Example #30
Source Project: Pushjet-Android   Author: Pushjet   File: DefaultModuleVersionListing.java    License: 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();
}