Java Code Examples for org.gradle.internal.Factory

The following examples show how to use org.gradle.internal.Factory. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
public void upload(Factory<InputStream> sourceFactory, Long contentLength, URI destination) throws IOException {
    LockableSftpClient client = sftpClientFactory.createSftpClient(destination, credentials);

    try {
        ChannelSftp channel = client.getSftpClient();
        ensureParentDirectoryExists(channel, destination);
        InputStream sourceStream = sourceFactory.create();
        try {
            channel.put(sourceStream, destination.getPath());
        } finally {
            sourceStream.close();
        }
    } catch (com.jcraft.jsch.SftpException e) {
        throw new SftpException(String.format("Could not write to resource '%s'.", destination), e);
    } finally {
        sftpClientFactory.releaseSftpClient(client);
    }
}
 
Example 2
public void apply(final Project target) {
    target.getExtensions().create("sources", DefaultProjectSourceSet.class, instantiator);
    final BinaryContainer binaries = target.getExtensions().create("binaries", DefaultBinaryContainer.class, instantiator);

    modelRules.register("binaries", BinaryContainer.class, new Factory<BinaryContainer>() {
        public BinaryContainer create() {
            return binaries;
        }
    });

    binaries.withType(BinaryInternal.class).all(new Action<BinaryInternal>() {
        public void execute(BinaryInternal binary) {
            Task binaryLifecycleTask = target.task(binary.getNamingScheme().getLifecycleTaskName());
            binaryLifecycleTask.setGroup(BUILD_GROUP);
            binaryLifecycleTask.setDescription(String.format("Assembles %s.", binary));
            binary.setLifecycleTask(binaryLifecycleTask);
        }
    });
}
 
Example 3
public void upload(Factory<InputStream> source, Long contentLength, URI destination) throws IOException {
    File target = getFile(destination);
    if (!target.canWrite()) {
        target.delete();
    } // if target is writable, the copy will overwrite it without requiring a delete
    GFileUtils.mkdirs(target.getParentFile());
    FileOutputStream fileOutputStream = new FileOutputStream(target);
    try {
        InputStream sourceInputStream = source.create();
        try {
            IOUtils.copyLarge(sourceInputStream, fileOutputStream);
        } finally {
            sourceInputStream.close();
        }
    } finally {
        fileOutputStream.close();
    }
}
 
Example 4
public LocallyAvailableExternalResource downloadAndCacheArtifactFile(final ModuleVersionArtifactMetaData artifact, ExternalResourceDownloader resourceDownloader, final ExternalResource resource) throws IOException {
    final File tmpFile = temporaryFileProvider.createTemporaryFile("gradle_download", "bin");
    try {
        resourceDownloader.download(resource, tmpFile);
        return cacheLockingManager.useCache(String.format("Store %s", artifact), new Factory<LocallyAvailableExternalResource>() {
            public LocallyAvailableExternalResource create() {
                LocallyAvailableResource cachedResource = fileStore.move(artifact, tmpFile);
                File fileInFileStore = cachedResource.getFile();
                ExternalResourceMetaData metaData = resource.getMetaData();
                artifactUrlCachedResolutionIndex.store(metaData.getLocation(), fileInFileStore, metaData);
                return new DefaultLocallyAvailableExternalResource(resource.getName(), cachedResource, metaData);
            }
        });
    } finally {
        tmpFile.delete();
    }
}
 
Example 5
public <T> T useCache(String operationDisplayName, Factory<? extends T> factory) {
    if (lockOptions != null && lockOptions.getMode() == FileLockManager.LockMode.Shared) {
        throw new UnsupportedOperationException("Not implemented yet.");
    }

    takeOwnership(operationDisplayName);
    boolean wasStarted = false;
    try {
        wasStarted = onStartWork();
        return factory.create();
    } finally {
        lock.lock();
        try {
            try {
                if (wasStarted) {
                    onEndWork();
                }
            } finally {
                releaseOwnership();
            }
        } finally {
            lock.unlock();
        }
    }
}
 
Example 6
public TransientConfigurationResults load(final ResolvedContentsMapping mapping) {
    synchronized (lock) {
        return cache.load(new Factory<TransientConfigurationResults>() {
            public TransientConfigurationResults create() {
                try {
                    return binaryData.read(new BinaryStore.ReadAction<TransientConfigurationResults>() {
                        public TransientConfigurationResults read(Decoder decoder) throws IOException {
                            return deserialize(decoder, mapping);
                        }
                    });
                } finally {
                    try {
                        binaryData.close();
                    } catch (IOException e) {
                        throw throwAsUncheckedException(e);
                    }
                }
            }
        });
    }
}
 
Example 7
@Override
public FileCollectionSnapshot getOutputFilesSnapshot() {
    if (outputFilesSnapshot == null) {
        outputFilesSnapshot = cacheAccess.useCache("fetch output files", new Factory<FileCollectionSnapshot>() {
            public FileCollectionSnapshot create() {
                return snapshotRepository.get(outputFilesSnapshotId);
            }
        });
    }
    return outputFilesSnapshot;
}
 
Example 8
public ConsumerConnection create(Distribution distribution, ProgressLoggerFactory progressLoggerFactory, ConnectionParameters connectionParameters) {
    LOGGER.debug("Using tooling provider from {}", distribution.getDisplayName());
    ClassLoader classLoader = createImplementationClassLoader(distribution, progressLoggerFactory, connectionParameters.getGradleUserHomeDir());
    ServiceLocator serviceLocator = new ServiceLocator(classLoader);
    try {
        Factory<ConnectionVersion4> factory = serviceLocator.findFactory(ConnectionVersion4.class);
        if (factory == null) {
            return new NoToolingApiConnection(distribution);
        }
        // ConnectionVersion4 is a part of the protocol and cannot be easily changed.
        ConnectionVersion4 connection = factory.create();

        ProtocolToModelAdapter adapter = new ProtocolToModelAdapter(new ConsumerTargetTypeProvider());
        ModelMapping modelMapping = new ModelMapping();

        // Adopting the connection to a refactoring friendly type that the consumer owns
        AbstractConsumerConnection adaptedConnection;
        if (connection instanceof ModelBuilder && connection instanceof InternalBuildActionExecutor) {
            adaptedConnection = new ActionAwareConsumerConnection(connection, modelMapping, adapter);
        } else if (connection instanceof ModelBuilder) {
            adaptedConnection = new ModelBuilderBackedConsumerConnection(connection, modelMapping, adapter);
        } else if (connection instanceof BuildActionRunner) {
            adaptedConnection = new BuildActionRunnerBackedConsumerConnection(connection, modelMapping, adapter);
        } else if (connection instanceof InternalConnection) {
            adaptedConnection = new InternalConnectionBackedConsumerConnection(connection, modelMapping, adapter);
        } else {
            adaptedConnection = new ConnectionVersion4BackedConsumerConnection(connection, modelMapping, adapter);
        }
        adaptedConnection.configure(connectionParameters);
        return adaptedConnection;
    } catch (UnsupportedVersionException e) {
        throw e;
    } catch (Throwable t) {
        throw new GradleConnectionException(String.format("Could not create an instance of Tooling API implementation using the specified %s.", distribution.getDisplayName()), t);
    }
}
 
Example 9
public PluginRegistry createChild(final ClassLoaderScope lookupScope, Instantiator instantiator) {
    Factory<ClassLoader> classLoaderFactory = new Factory<ClassLoader>() {
        public ClassLoader create() {
            return lookupScope.getScopeClassLoader();
        }
    };
    return new DefaultPluginRegistry(this, classLoaderFactory, instantiator);
}
 
Example 10
public static <T> T whileDisabled(Factory<T> factory) {
    ENABLED.set(false);
    try {
        return factory.create();
    } finally {
        ENABLED.set(true);
    }
}
 
Example 11
private Factory<Action<Task>> createActionFactory(final Method method, final Class<?>[] parameterTypes) {
    return new Factory<Action<Task>>() {
        public Action<Task> create() {
            if (parameterTypes.length == 1) {
                return new IncrementalTaskAction(method);
            } else {
                return new StandardTaskAction(method);
            }
        }
    };
}
 
Example 12
protected TemporaryFileProvider createTemporaryFileProvider() {
    return new DefaultTemporaryFileProvider(new Factory<File>() {
        public File create() {
            return new File(project.getBuildDir(), "tmp");
        }
    });
}
 
Example 13
@Inject
public MavenPlugin(Factory<LoggingManagerInternal> loggingManagerFactory, FileResolver fileResolver,
                   ProjectPublicationRegistry publicationRegistry, ProjectConfigurationActionContainer configurationActionContainer) {
    this.loggingManagerFactory = loggingManagerFactory;
    this.fileResolver = fileResolver;
    this.publicationRegistry = publicationRegistry;
    this.configurationActionContainer = configurationActionContainer;
}
 
Example 14
@Inject
public MavenPlugin(Factory<LoggingManagerInternal> loggingManagerFactory, FileResolver fileResolver,
                   ProjectPublicationRegistry publicationRegistry, ProjectConfigurationActionContainer configurationActionContainer) {
    this.loggingManagerFactory = loggingManagerFactory;
    this.fileResolver = fileResolver;
    this.publicationRegistry = publicationRegistry;
    this.configurationActionContainer = configurationActionContainer;
}
 
Example 15
public <T> Factory<T> getFactory(Class<T> type) {
    synchronized (lock) {
        if (closed) {
            throw new IllegalStateException(String.format("Cannot locate factory for objects of type %s, as %s has been closed.", format(type), displayName));
        }

        DefaultLookupContext context = new DefaultLookupContext();
        ServiceProvider factory = allServices.getFactory(context, type);
        if (factory != null) {
            return (Factory<T>) factory.get();
        }

        throw new UnknownServiceException(type, String.format("No factory for objects of type %s available in %s.", format(type), displayName));
    }
}
 
Example 16
protected Factory<LoggingManagerInternal> createLoggingManagerFactory() {
    OutputEventRenderer renderer = get(OutputEventRenderer.class);
    // Don't configure anything
    return new DefaultLoggingManagerFactory(renderer,
            renderer,
            new NoOpLoggingSystem(),
            new NoOpLoggingSystem());
}
 
Example 17
public ServiceProvider find(Type serviceType, Provider provider) {
    if (!visiting.add(serviceType)) {
        throw new ServiceValidationException(String.format("Cycle in dependencies of service of type %s.", format(serviceType)));
    }
    try {
        if (serviceType instanceof ParameterizedType) {
            ParameterizedType parameterizedType = (ParameterizedType) serviceType;
            if (parameterizedType.getRawType().equals(Factory.class)) {
                Type typeArg = parameterizedType.getActualTypeArguments()[0];
                if (typeArg instanceof Class) {
                    return provider.getFactory(this, (Class) typeArg);
                }
                if (typeArg instanceof WildcardType) {
                    WildcardType wildcardType = (WildcardType) typeArg;
                    if (wildcardType.getLowerBounds().length == 1 && wildcardType.getUpperBounds().length == 1) {
                        if (wildcardType.getLowerBounds()[0] instanceof Class && wildcardType.getUpperBounds()[0].equals(Object.class)) {
                            return provider.getFactory(this, (Class<Object>) wildcardType.getLowerBounds()[0]);
                        }
                    }
                    if (wildcardType.getLowerBounds().length == 0 && wildcardType.getUpperBounds().length == 1) {
                        if (wildcardType.getUpperBounds()[0] instanceof Class) {
                            return provider.getFactory(this, (Class<Object>) wildcardType.getUpperBounds()[0]);
                        }
                    }
                }
            }
        }

        return provider.getService(this, toSpec(serviceType));
    } finally {
        visiting.remove(serviceType);
    }
}
 
Example 18
protected Factory<LoggingManagerInternal> createLoggingManagerFactory() {
    OutputEventRenderer renderer = get(OutputEventRenderer.class);
    // Configure logback only
    return new DefaultLoggingManagerFactory(
            new DefaultLoggingConfigurer(renderer,
                    new LogbackLoggingConfigurer(renderer)),
            renderer,
            new NoOpLoggingSystem(),
            new NoOpLoggingSystem());
}
 
Example 19
@Override
public GradleHandle doStart() {
    return createGradleHandle(getResultAssertion(), getDefaultCharacterEncoding(), new Factory<ExecHandleBuilder>() {
        public ExecHandleBuilder create() {
            return createExecHandleBuilder();
        }
    }).start();
}
 
Example 20
public <T extends K> V get(final T key, final Factory<? extends V> factory) {
    return synchronizer.synchronize(new Factory<V>() {
        public V create() {
            return cache.get(key, factory);
        }
    });
}
 
Example 21
@Override
public GradleHandle doStart() {
    return createGradleHandle(getResultAssertion(), getDefaultCharacterEncoding(), new Factory<ExecHandleBuilder>() {
        public ExecHandleBuilder create() {
            return createExecHandleBuilder();
        }
    }).start();
}
 
Example 22
protected Factory<LoggingManagerInternal> createLoggingManagerFactory() {
    return new Factory<LoggingManagerInternal>() {
        public LoggingManagerInternal create() {
            return new NoOpLoggingManager();
        }
    };
}
 
Example 23
@Override
protected GradleHandle doStart() {
    return new ForkingGradleHandle(getResultAssertion(), getDefaultCharacterEncoding(), new Factory<JavaExecHandleBuilder>() {
        public JavaExecHandleBuilder create() {
            JavaExecHandleBuilder builder = new JavaExecHandleBuilder(TestFiles.resolver());
            builder.workingDir(getWorkingDir());
            Set<File> classpath = new DefaultModuleRegistry().getFullClasspath();
            builder.classpath(classpath);
            builder.setMain(Main.class.getName());
            builder.args(getAllArgs());
            return builder;
        }
    }).start();
}
 
Example 24
public Map<File, JarSnapshot> getJarSnapshots(final Map<File, byte[]> jarHashes) {
    return cache.getCacheAccess().useCache("loading jar snapshots", new Factory<Map<File, JarSnapshot>>() {
        public Map<File, JarSnapshot> create() {
            final Map<File, JarSnapshot> out = new HashMap<File, JarSnapshot>();
            for (Map.Entry<File, byte[]> entry : jarHashes.entrySet()) {
                JarSnapshot snapshot = new JarSnapshot(cache.getCache().get(entry.getValue()));
                out.put(entry.getKey(), snapshot);
            }
            return out;
        }
    });
}
 
Example 25
private TaskHistory loadHistory(final TaskInternal task) {
    return cacheAccess.useCache("Load task history", new Factory<TaskHistory>() {
        public TaskHistory create() {
            ClassLoader original = serializer.getClassLoader();
            serializer.setClassLoader(task.getClass().getClassLoader());
            try {
                TaskHistory history = taskHistoryCache.get(task.getPath());
                return history == null ? new TaskHistory() : history;
            } finally {
                serializer.setClassLoader(original);
            }
        }
    });
}
 
Example 26
public <T> T useCache(String operationDisplayName, Factory<? extends T> action) {
    assertNotClosed();
    // The contract of useCache() means we have to provide some basic synchronization.
    synchronized (this) {
        return action.create();
    }
}
 
Example 27
public DefaultDeployerFactory(MavenFactory mavenFactory, Factory<LoggingManagerInternal> loggingManagerFactory, FileResolver fileResolver, MavenPomMetaInfoProvider pomMetaInfoProvider,
                              ConfigurationContainer configurationContainer, Conf2ScopeMappingContainer scopeMapping) {
    this.mavenFactory = mavenFactory;
    this.loggingManagerFactory = loggingManagerFactory;
    this.fileResolver = fileResolver;
    this.pomMetaInfoProvider = pomMetaInfoProvider;
    this.configurationContainer = configurationContainer;
    this.scopeMapping = scopeMapping;
}
 
Example 28
public JarSnapshot get(byte[] key, final Factory<JarSnapshot> factory) {
    return new JarSnapshot(cache.get(key, new Factory<JarSnapshotData>() {
        public JarSnapshotData create() {
            return factory.create().getData();
        }
    }));
}
 
Example 29
private Factory<Action<Task>> createActionFactory(final Method method, final Class<?>[] parameterTypes) {
    return new Factory<Action<Task>>() {
        public Action<Task> create() {
            if (parameterTypes.length == 1) {
                return new IncrementalTaskAction(method);
            } else {
                return new StandardTaskAction(method);
            }
        }
    };
}
 
Example 30
public <T> T longRunningOperation(String operationDisplayName, Factory<? extends T> action) {
    boolean wasEnded = startLongRunningOperation(operationDisplayName);
    try {
        return action.create();
    } finally {
        finishLongRunningOperation(wasEnded);
    }
}