Java Code Examples for org.gradle.api.Transformer

The following examples show how to use org.gradle.api.Transformer. 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
private void listModuleVersionsFromCache(DependencyMetaData dependency, BuildableModuleComponentVersionSelectionResolveResult result) {
    ModuleVersionSelector requested = dependency.getRequested();
    final ModuleIdentifier moduleId = getCacheKey(requested);
    ModuleVersionsCache.CachedModuleVersionList cachedModuleVersionList = moduleVersionsCache.getCachedModuleResolution(delegate, moduleId);
    if (cachedModuleVersionList != null) {
        ModuleVersionListing versionList = cachedModuleVersionList.getModuleVersions();
        Set<ModuleVersionIdentifier> versions = CollectionUtils.collect(versionList.getVersions(), new Transformer<ModuleVersionIdentifier, Versioned>() {
            public ModuleVersionIdentifier transform(Versioned original) {
                return new DefaultModuleVersionIdentifier(moduleId, original.getVersion());
            }
        });
        if (cachePolicy.mustRefreshVersionList(moduleId, versions, cachedModuleVersionList.getAgeMillis())) {
            LOGGER.debug("Version listing in dynamic revision cache is expired: will perform fresh resolve of '{}' in '{}'", requested, delegate.getName());
        } else {
            result.listed(versionList);
            // When age == 0, verified since the start of this build, assume listing hasn't changed
            result.setAuthoritative(cachedModuleVersionList.getAgeMillis() == 0);
        }
    }
}
 
Example #2
Source Project: Pushjet-Android   Author: Pushjet   File: PomReader.java    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
public PomReader(final LocallyAvailableExternalResource resource) throws IOException, SAXException {
    final String systemId = resource.getLocalResource().getFile().toURI().toASCIIString();
    Document pomDomDoc = resource.withContent(new Transformer<Document, InputStream>() {
        public Document transform(InputStream inputStream) {
            try {
                return parseToDom(inputStream, systemId);
            } catch (Exception e) {
                throw new MetaDataParseException("POM", resource, e);
            }
        }
    });
    projectElement = pomDomDoc.getDocumentElement();
    if (!PROJECT.equals(projectElement.getNodeName()) && !MODEL.equals(projectElement.getNodeName())) {
        throw new SAXParseException("project must be the root tag", systemId, systemId, 0, 0);
    }
    parentElement = getFirstChildElement(projectElement, PARENT);

    setDefaultParentGavProperties();
    setPomProperties();
    setActiveProfileProperties();
}
 
Example #3
Source Project: Pushjet-Android   Author: Pushjet   File: ClassLoaderCache.java    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
public ClassLoaderDetails getDetails(ClassLoader classLoader, Transformer<ClassLoaderDetails, ClassLoader> factory) {
    lock.lock();
    try {
        ClassLoaderDetails details = classLoaderDetails.getIfPresent(classLoader);
        if (details != null) {
            return details;
        }

        details = factory.transform(classLoader);
        classLoaderDetails.put(classLoader, details);
        classLoaderIds.put(details.uuid, classLoader);
        return details;
    } finally {
        lock.unlock();
    }
}
 
Example #4
Source Project: Pushjet-Android   Author: Pushjet   File: TestReport.java    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
private TestResultsProvider createAggregateProvider() {
    List<TestResultsProvider> resultsProviders = new LinkedList<TestResultsProvider>();
    try {
        FileCollection resultDirs = getTestResultDirs();
        if (resultDirs.getFiles().size() == 1) {
            return new BinaryResultBackedTestResultsProvider(resultDirs.getSingleFile());
        } else {
            return new AggregateTestResultsProvider(collect(resultDirs, resultsProviders, new Transformer<TestResultsProvider, File>() {
                public TestResultsProvider transform(File dir) {
                    return new BinaryResultBackedTestResultsProvider(dir);
                }
            }));
        }
    } catch (RuntimeException e) {
        stoppable(resultsProviders).stop();
        throw e;
    }
}
 
Example #5
Source Project: pushfish-android   Author: PushFish   File: Suppliers.java    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
public static <I extends Closeable> Supplier<I> ofQuietlyClosed(final Factory<I> factory) {
    return new Supplier<I>() {
        public <R> R supplyTo(Transformer<R, ? super I> transformer) {
            I thing = factory.create();
            try {
                return transformer.transform(thing);
            } finally {
                try {
                    thing.close();
                } catch (Exception ignore) {
                    // ignore
                }
            }
        }
    };
}
 
Example #6
Source Project: pushfish-android   Author: PushFish   File: NativeCompiler.java    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
public WorkResult execute(T spec) {
    MutableCommandLineToolInvocation invocation = baseInvocation.copy();
    invocation.addPostArgsAction(new VisualCppOptionsFileArgTransformer(spec.getTempDir()));

    Transformer<List<String>, File> outputFileArgTransformer = new Transformer<List<String>, File>(){
        public List<String> transform(File outputFile) {
            return Arrays.asList("/Fo"+ outputFile.getAbsolutePath());
        }
    };
    for (File sourceFile : spec.getSourceFiles()) {
        String objectFileNameSuffix = ".obj";
        SingleSourceCompileArgTransformer<T> argTransformer = new SingleSourceCompileArgTransformer<T>(sourceFile,
                objectFileNameSuffix,
                new ShortCircuitArgsTransformer<T>(argsTransFormer),
                true,
                outputFileArgTransformer);
        invocation.setArgs(argTransformer.transform(specTransformer.transform(spec)));
        invocation.setWorkDirectory(spec.getObjectFileDir());
        commandLineTool.execute(invocation);
    }
    return new SimpleWorkResult(!spec.getSourceFiles().isEmpty());
}
 
Example #7
public LocallyAvailableResourceFinderSearchableFileStoreAdapter(final FileStoreSearcher<C> fileStore) {
    super(new Transformer<Factory<List<File>>, C>() {
        public Factory<List<File>> transform(final C criterion) {
            return new Factory<List<File>>() {
                public List<File> create() {
                    Set<? extends LocallyAvailableResource> entries = fileStore.search(criterion);
                    return CollectionUtils.collect(entries, new ArrayList<File>(entries.size()), new Transformer<File, LocallyAvailableResource>() {
                        public File transform(LocallyAvailableResource original) {
                            return original.getFile();
                        }
                    });
                }
            };
        }
    });
}
 
Example #8
Source Project: Pushjet-Android   Author: Pushjet   File: ChainingTransformer.java    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
public void add(final Closure transformer) {
    transformers.add(new Transformer<T, T>() {
        public T transform(T original) {
            transformer.setDelegate(original);
            transformer.setResolveStrategy(Closure.DELEGATE_FIRST);
            Object value = transformer.call(original);
            if (type.isInstance(value)) {
                return type.cast(value);
            }
            if (type == String.class && value instanceof GString) {
                return type.cast(value.toString());
            }
            return original;
        }
    });
}
 
Example #9
Source Project: Pushjet-Android   Author: Pushjet   File: HttpResourceLister.java    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
public List<String> list(final URI parent) throws IOException {
    final HttpResponseResource resource = accessor.getResource(parent);
    if (resource == null) {
        return null;
    }
    try {
        return resource.withContent(new Transformer<List<String>, InputStream>() {
            public List<String> transform(InputStream inputStream) {
                String contentType = resource.getContentType();
                ApacheDirectoryListingParser directoryListingParser = new ApacheDirectoryListingParser();
                try {
                    return directoryListingParser.parse(parent, inputStream, contentType);
                } catch (Exception e) {
                    throw new ResourceException("Unable to parse HTTP directory listing.", e);
                }
            }
        });
    } finally {
        resource.close();
    }
}
 
Example #10
Source Project: pushfish-android   Author: PushFish   File: DefaultTaskExecutionPlan.java    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
private int finalizerTaskPosition(TaskInfo finalizer, final List<TaskInfo> nodeQueue) {
    if (nodeQueue.size() == 0) {
        return 0;
    }

    ArrayList<TaskInfo> dependsOnTasks = new ArrayList<TaskInfo>();
    dependsOnTasks.addAll(finalizer.getDependencySuccessors());
    dependsOnTasks.addAll(finalizer.getMustSuccessors());
    dependsOnTasks.addAll(finalizer.getShouldSuccessors());
    List<Integer> dependsOnTaskIndexes = CollectionUtils.collect(dependsOnTasks, new Transformer<Integer, TaskInfo>() {
        public Integer transform(TaskInfo dependsOnTask) {
            return nodeQueue.indexOf(dependsOnTask);
        }
    });
    return Collections.max(dependsOnTaskIndexes) + 1;
}
 
Example #11
Source Project: Pushjet-Android   Author: Pushjet   File: DaemonGradleExecuter.java    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
protected List<String> getGradleOpts() {
    if (isNoDefaultJvmArgs()) {
        return super.getGradleOpts();
    } else {
        // Workaround for https://issues.gradle.org/browse/GRADLE-2629
        // Instead of just adding these as standalone opts, we need to add to
        // -Dorg.gradle.jvmArgs in order for them to be effectual
        List<String> jvmArgs = new ArrayList<String>(4);
        jvmArgs.add("-XX:MaxPermSize=320m");
        jvmArgs.add("-XX:+HeapDumpOnOutOfMemoryError");
        jvmArgs.add("-XX:HeapDumpPath=" + buildContext.getGradleUserHomeDir().getAbsolutePath());

        String quotedArgs = join(" ", collect(jvmArgs, new Transformer<String, String>() {
            public String transform(String input) {
                return String.format("'%s'", input);
            }
        }));

        List<String> gradleOpts = new ArrayList<String>(super.getGradleOpts());
        gradleOpts.add("-Dorg.gradle.jvmArgs=" +  quotedArgs);
        return gradleOpts;
    }
}
 
Example #12
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 #13
Source Project: pushfish-android   Author: PushFish   File: PomReader.java    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
public PomReader(final LocallyAvailableExternalResource resource) throws IOException, SAXException {
    final String systemId = resource.getLocalResource().getFile().toURI().toASCIIString();
    Document pomDomDoc = resource.withContent(new Transformer<Document, InputStream>() {
        public Document transform(InputStream inputStream) {
            try {
                return parseToDom(inputStream, systemId);
            } catch (Exception e) {
                throw new MetaDataParseException("POM", resource, e);
            }
        }
    });
    projectElement = pomDomDoc.getDocumentElement();
    if (!PROJECT.equals(projectElement.getNodeName()) && !MODEL.equals(projectElement.getNodeName())) {
        throw new SAXParseException("project must be the root tag", systemId, systemId, 0, 0);
    }
    parentElement = getFirstChildElement(projectElement, PARENT);

    setDefaultParentGavProperties();
    setPomProperties();
    setActiveProfileProperties();
}
 
Example #14
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 #15
Source Project: Pushjet-Android   Author: Pushjet   File: ClassLoaderCache.java    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
public ClassLoader getClassLoader(ClassLoaderDetails details, Transformer<ClassLoader, ClassLoaderDetails> factory) {
    lock.lock();
    try {
        ClassLoader classLoader = classLoaderIds.getIfPresent(details.uuid);
        if (classLoader != null) {
            return classLoader;
        }

        classLoader = factory.transform(details);
        classLoaderIds.put(details.uuid, classLoader);
        classLoaderDetails.put(classLoader, details);
        return classLoader;
    } finally {
        lock.unlock();
    }
}
 
Example #16
Source Project: Pushjet-Android   Author: Pushjet   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 #17
Source Project: pushfish-android   Author: PushFish   File: ArgWriter.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static Transformer<ArgWriter, PrintWriter> windowsStyleFactory() {
    return new Transformer<ArgWriter, PrintWriter>() {
        public ArgWriter transform(PrintWriter original) {
            return windowsStyle(original);
        }
    };
}
 
Example #18
Source Project: pushfish-android   Author: PushFish   File: JCenterPluginMapper.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
public Dependency map(final PluginRequest request, DependencyHandler dependencyHandler) {
    final String pluginId = request.getId();

    String systemId = cacheSupplier.supplyTo(new Transformer<String, PersistentIndexedCache<PluginRequest, String>>() {
        public String transform(PersistentIndexedCache<PluginRequest, String> cache) {
            return doCacheAwareSearch(request, pluginId, cache);
        }
    });

    if (systemId.equals(NOT_FOUND)) {
        return null;
    } else {
        return dependencyHandler.create(systemId + ":" + request.getVersion());
    }
}
 
Example #19
Source Project: pushfish-android   Author: PushFish   File: DefaultModelRegistry.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
private <T> boolean hasModelPath(ModelPath candidate, Iterable<T> things, Transformer<? extends Iterable<ModelPath>, T> transformer) {
    for (T thing : things) {
        for (ModelPath path : transformer.transform(thing)) {
            if (path.equals(candidate)) {
                return true;
            }
        }
    }

    return false;
}
 
Example #20
Source Project: pushfish-android   Author: PushFish   File: Transformers.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Converts an {@link Action} to a {@link Transformer} that runs the action against the input value and returns {@code null}.
 */
public static <R, I> Transformer<R, I> toTransformer(final Action<? super I> action) {
    return new Transformer<R, I>() {
        public R transform(I original) {
            action.execute(original);
            return null;
        }
    };
}
 
Example #21
Source Project: Pushjet-Android   Author: Pushjet   File: ModelRuleInspector.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
private String describeHandlers() {
    String desc = Joiner.on(", ").join(CollectionUtils.collect(handlers, new Transformer<String, MethodRuleDefinitionHandler>() {
        public String transform(MethodRuleDefinitionHandler original) {
            return original.getDescription();
        }
    }));

    return "[" + desc + "]";
}
 
Example #22
Source Project: pushfish-android   Author: PushFish   File: VisualCppToolChain.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
private <T extends NativeCompileSpec> Transformer<T, T> addIncludePathAndDefinitions(Class<T> type) {
    return new Transformer<T, T>() {
        public T transform(T original) {
            original.include(visualCpp.getIncludePath(targetPlatform));
            original.include(sdk.getIncludeDirs());
            for (Entry<String, String> definition : visualCpp.getDefinitions(targetPlatform).entrySet()) {
                original.define(definition.getKey(), definition.getValue());
            }
            return original;
        }
    };
}
 
Example #23
Source Project: pushfish-android   Author: PushFish   File: ChainingTransformer.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
public T transform(T original) {
    T value = original;
    for (Transformer<T, T> transformer : transformers) {
        value = type.cast(transformer.transform(value));
    }
    return value;
}
 
Example #24
Source Project: pushfish-android   Author: PushFish   File: Transformers.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * A getClass() transformer.
 *
 * @param <T> The type of the object
 * @return A getClass() transformer.
 */
public static <T> Transformer<Class<T>, T> type() {
    return new Transformer<Class<T>, T>() {
        public Class<T> transform(T original) {
            @SuppressWarnings("unchecked")
            Class<T> aClass = (Class<T>) original.getClass();
            return aClass;
        }
    };
}
 
Example #25
Source Project: Pushjet-Android   Author: Pushjet   File: JavaReflectionUtil.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Search methods in an inheritance aware fashion, stopping when stopIndicator returns true.
 */
public static void searchMethods(Class<?> target, final Transformer<Boolean, Method> stopIndicator) {
    Spec<Method> stopIndicatorAsSpec = new Spec<Method>() {
        public boolean isSatisfiedBy(Method element) {
            return stopIndicator.transform(element);
        }
    };

    findAllMethodsInternal(target, stopIndicatorAsSpec, new MultiMap<String, Method>(), new ArrayList<Method>(1), true);
}
 
Example #26
Source Project: Pushjet-Android   Author: Pushjet   File: GradleBuildOutcomeSetInferrer.java    License: 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 #27
Source Project: Pushjet-Android   Author: Pushjet   File: VisualCppToolChain.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
private Transformer<LinkerSpec, LinkerSpec> addLibraryPath() {
    return new Transformer<LinkerSpec, LinkerSpec>() {
        public LinkerSpec transform(LinkerSpec original) {
            original.libraryPath(visualCpp.getLibraryPath(targetPlatform), sdk.getLibDir(targetPlatform));
            return original;
        }
    };
}
 
Example #28
Source Project: Pushjet-Android   Author: Pushjet   File: CollectionUtils.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static <K, V> ImmutableListMultimap<K, V> groupBy(Iterable<? extends V> iterable, Transformer<? extends K, V> grouper) {
    ImmutableListMultimap.Builder<K, V> builder = ImmutableListMultimap.builder();

    for (V element : iterable) {
        K key = grouper.transform(element);
        builder.put(key, element);
    }

    return builder.build();
}
 
Example #29
Source Project: pushfish-android   Author: PushFish   File: CollectionUtils.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static <R, I> R[] collectArray(I[] list, R[] destination, Transformer<? extends R, ? super I> transformer) {
    assert list.length <= destination.length;
    for (int i = 0; i < list.length; ++i) {
        destination[i] = transformer.transform(list[i]);
    }
    return destination;
}
 
Example #30
Source Project: pushfish-android   Author: PushFish   File: VisualCppToolChain.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
public <T extends BinaryToolSpec> Compiler<T> createWindowsResourceCompiler() {
    CommandLineTool<WindowsResourceCompileSpec> commandLineTool = commandLineTool("Windows resource compiler", sdk.getResourceCompiler(targetPlatform));
    Transformer<WindowsResourceCompileSpec, WindowsResourceCompileSpec> specTransformer = addIncludePathAndDefinitions();
    commandLineTool.withSpecTransformer(specTransformer);
    WindowsResourceCompiler windowsResourceCompiler = new WindowsResourceCompiler(commandLineTool);
    return (Compiler<T>) new OutputCleaningCompiler<WindowsResourceCompileSpec>(windowsResourceCompiler, ".res");
}