org.gradle.api.Transformer Java Examples

The following examples show how to use org.gradle.api.Transformer. 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: DefaultIvyExtraInfo.java    From Pushjet-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 #2
Source File: ClassLoaderCache.java    From Pushjet-Android with 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 #3
Source File: PomReader.java    From Pushjet-Android with 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 #4
Source File: TestReport.java    From Pushjet-Android with 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 File: Suppliers.java    From pushfish-android with 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 File: NativeCompiler.java    From pushfish-android with 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
Source File: LocallyAvailableResourceFinderSearchableFileStoreAdapter.java    From pushfish-android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
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 File: ChainingTransformer.java    From Pushjet-Android with 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 File: DefaultTaskExecutionPlan.java    From pushfish-android with 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 #10
Source File: DaemonGradleExecuter.java    From Pushjet-Android with 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 #11
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 #12
Source File: PomReader.java    From pushfish-android with 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 #13
Source File: HttpResourceLister.java    From Pushjet-Android with 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 #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: ClassLoaderCache.java    From Pushjet-Android with 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 File: CachingModuleComponentRepository.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
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 #17
Source File: Suppliers.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static <I> Supplier<I> of(final Factory<? extends I> factory) {
    return new Supplier<I>() {
        public <R> R supplyTo(Transformer<R, ? super I> transformer) {
            I value = factory.create();
            return transformer.transform(value);
        }
    };
}
 
Example #18
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 #19
Source File: AbstractExternalResource.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public <T> T withContent(Transformer<? extends T, ? super InputStream> readAction) throws IOException {
    InputStream input = openStream();
    try {
        return readAction.transform(input);
    } finally {
        input.close();
    }
}
 
Example #20
Source File: ModelCreators.java    From pushfish-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static ModelCreator resultOf(final Closure creatorClosure, Set<String> modelPaths) {
    Transformer<Object, Map<String, Object>> closureBackedCreator = new Transformer<Object, Map<String, Object>>() {
        public Object transform(Map<String, Object> inputs) {
            return creatorClosure.call(inputs);
        }
    };

    return new ModelCreator(modelPaths, closureBackedCreator);
}
 
Example #21
Source File: PluginDependenciesService.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public List<PluginRequest> getRequests() {
    List<PluginRequest> pluginRequests = collect(specs, new Transformer<PluginRequest, DependencySpecImpl>() {
        public PluginRequest transform(DependencySpecImpl original) {
            return new DefaultPluginRequest(original.id, original.version, original.lineNumber, scriptSource);
        }
    });

    ListMultimap<PluginId, PluginRequest> groupedById = CollectionUtils.groupBy(pluginRequests, new Transformer<PluginId, PluginRequest>() {
        public PluginId transform(PluginRequest pluginRequest) {
            return pluginRequest.getId();
        }
    });

    // Check for duplicates
    for (PluginId key : groupedById.keySet()) {
        List<PluginRequest> pluginRequestsForId = groupedById.get(key);
        if (pluginRequestsForId.size() > 1) {
            PluginRequest first = pluginRequests.get(0);
            PluginRequest second = pluginRequests.get(1);

            InvalidPluginRequestException exception = new InvalidPluginRequestException(second, "Plugin with id '" + key + "' was already requested at line " + first.getLineNumber());
            throw new LocationAwareException(exception, second.getScriptSource(), second.getLineNumber());
        }
    }

    return pluginRequests;
}
 
Example #22
Source File: DefaultModelRegistry.java    From pushfish-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private boolean isDependedOn(ModelPath candidate) {
    Transformer<Iterable<ModelPath>, ModelMutation<?>> extractInputPaths = new Transformer<Iterable<ModelPath>, ModelMutation<?>>() {
        public Iterable<ModelPath> transform(ModelMutation<?> original) {
            return original.getInputPaths();
        }
    };

    Transformer<ImmutableList<ModelPath>, ImmutableList<ModelPath>> passThrough = Transformers.noOpTransformer();

    return hasModelPath(candidate, mutators.values(), extractInputPaths)
            || hasModelPath(candidate, usedMutators.values(), passThrough)
            || hasModelPath(candidate, finalizers.values(), extractInputPaths)
            || hasModelPath(candidate, usedFinalizers.values(), passThrough);
}
 
Example #23
Source File: DefaultIvyContextManager.java    From pushfish-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public <T> T withIvy(Transformer<? extends T, ? super Ivy> action) {
    Integer currentDepth = depth.get();

    if (currentDepth != null) {
        depth.set(currentDepth + 1);
        try {
            return action.transform(IvyContext.getContext().getIvy());
        } finally {
            depth.set(currentDepth);
        }
    }

    IvyContext.pushNewContext();
    try {
        depth.set(1);
        try {
            Ivy ivy = getIvy();
            try {
                IvyContext.getContext().setIvy(ivy);
                return action.transform(ivy);
            } finally {
                releaseIvy(ivy);
            }
        } finally {
            depth.set(null);
        }
    } finally {
        IvyContext.popContext();
    }
}
 
Example #24
Source File: CollectionUtils.java    From pushfish-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
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 #25
Source File: ChainingTransformer.java    From pushfish-android with 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 #26
Source File: VisualCppToolChain.java    From pushfish-android with 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");
}
 
Example #27
Source File: DefaultModelRegistry.java    From pushfish-android with 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 #28
Source File: CollectionUtils.java    From pushfish-android with 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 #29
Source File: ArgWriter.java    From pushfish-android with 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 #30
Source File: ArtifactIdentifierFileStore.java    From pushfish-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private static Transformer<String, ModuleComponentArtifactMetaData> toTransformer(final String pattern) {
    final ResourcePattern resourcePattern = new IvyResourcePattern(pattern);
    return new Transformer<String, ModuleComponentArtifactMetaData>() {
         public String transform(ModuleComponentArtifactMetaData artifact) {
             return resourcePattern.getLocation(artifact).getPath();
         }
     };
}