Java Code Examples for org.gradle.util.GFileUtils

The following examples show how to use org.gradle.util.GFileUtils. 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 DefaultGroovyJavaJointCompileSpec createSpec() {
    DefaultGroovyJavaJointCompileSpec spec = new DefaultGroovyJavaJointCompileSpec();
    spec.setSource(getSource());
    spec.setDestinationDir(getDestinationDir());
    spec.setWorkingDir(getProject().getProjectDir());
    spec.setTempDir(getTemporaryDir());
    spec.setClasspath(getClasspath());
    spec.setSourceCompatibility(getSourceCompatibility());
    spec.setTargetCompatibility(getTargetCompatibility());
    spec.setGroovyClasspath(getGroovyClasspath());
    spec.setCompileOptions(compileOptions);
    spec.setGroovyCompileOptions(groovyCompileOptions);
    if (spec.getGroovyCompileOptions().getStubDir() == null) {
        File dir = new File(getTemporaryDir(), "groovy-java-stubs");
        GFileUtils.mkdirs(dir);
        spec.getGroovyCompileOptions().setStubDir(dir);
    }
    return spec;
}
 
Example 2
private void locateKitsInRegistry(String baseKey) {
    String[] versions = {
            VERSION_KIT_8,
            VERSION_KIT_81
    };
    String[] keys = {
            REGISTRY_KIT_8,
            REGISTRY_KIT_81
    };

    for (int i = 0; i != keys.length; ++i) {
        try {
            File kitDir = GFileUtils.canonicalise(new File(windowsRegistry.getStringValue(WindowsRegistry.Key.HKEY_LOCAL_MACHINE, baseKey + REGISTRY_ROOTPATH_KIT, keys[i])));
            if (isWindowsSdk(kitDir)) {
                LOGGER.debug("Found Windows Kit {} at {}", versions[i], kitDir);
                addSdk(kitDir, versions[i], NAME_KIT + " " + versions[i]);
            } else {
                LOGGER.debug("Ignoring candidate Windows Kit directory {} as it does not look like a Windows Kit installation.", kitDir);
            }
        } catch (MissingRegistryEntryException e) {
            // Ignore the version if the string cannot be read
        }
    }
}
 
Example 3
public FileLock lock(File target, LockOptions options, String targetDisplayName, String operationDisplayName) {
    if (options.getMode() == LockMode.None) {
        throw new UnsupportedOperationException(String.format("No %s mode lock implementation available.", options));
    }
    File canonicalTarget = GFileUtils.canonicalise(target);
    if (!lockedFiles.add(canonicalTarget)) {
        throw new IllegalStateException(String.format("Cannot lock %s as it has already been locked by this process.", targetDisplayName));
    }
    try {
        int port = fileLockContentionHandler.reservePort();
        return new DefaultFileLock(canonicalTarget, options, targetDisplayName, operationDisplayName, port);
    } catch (Throwable t) {
        lockedFiles.remove(canonicalTarget);
        throw throwAsUncheckedException(t);
    }
}
 
Example 4
protected LocallyAvailableResource saveIntoFileStore(final File source, final File destination, final boolean isMove) {
    String verb = isMove ? "move" : "copy";

    if (!source.exists()) {
        throw new GradleException(String.format("Cannot %s '%s' into filestore @ '%s' as it does not exist", verb, source, destination));
    }

    String error = String.format("Failed to %s file '%s' into filestore at '%s' ", verb, source, destination);

    return doAdd(destination, error, new Action<File>() {
        public void execute(File file) {
            if (isMove) {
                GFileUtils.moveFile(source, destination);
            } else {
                GFileUtils.copyFile(source, destination);
            }
        }
    });
}
 
Example 5
private void locateKitsInRegistry(String baseKey) {
    String[] versions = {
            VERSION_KIT_8,
            VERSION_KIT_81
    };
    String[] keys = {
            REGISTRY_KIT_8,
            REGISTRY_KIT_81
    };

    for (int i = 0; i != keys.length; ++i) {
        try {
            File kitDir = GFileUtils.canonicalise(new File(windowsRegistry.getStringValue(WindowsRegistry.Key.HKEY_LOCAL_MACHINE, baseKey + REGISTRY_ROOTPATH_KIT, keys[i])));
            if (isWindowsSdk(kitDir)) {
                LOGGER.debug("Found Windows Kit {} at {}", versions[i], kitDir);
                addSdk(kitDir, versions[i], NAME_KIT + " " + versions[i]);
            } else {
                LOGGER.debug("Ignoring candidate Windows Kit directory {} as it does not look like a Windows Kit installation.", kitDir);
            }
        } catch (MissingRegistryEntryException e) {
            // Ignore the version if the string cannot be read
        }
    }
}
 
Example 6
protected LocallyAvailableResource saveIntoFileStore(final File source, final File destination, final boolean isMove) {
    String verb = isMove ? "move" : "copy";

    if (!source.exists()) {
        throw new GradleException(String.format("Cannot %s '%s' into filestore @ '%s' as it does not exist", verb, source, destination));
    }

    String error = String.format("Failed to %s file '%s' into filestore at '%s' ", verb, source, destination);

    return doAdd(destination, error, new Action<File>() {
        public void execute(File file) {
            if (isMove) {
                GFileUtils.moveFile(source, destination);
            } else {
                GFileUtils.copyFile(source, destination);
            }
        }
    });
}
 
Example 7
public void upload(Factory<InputStream> source, Long contentLength, String 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 {
            if (IOUtils.copy(sourceInputStream, fileOutputStream) == -1) {
                throw new IOException(String.format("File copy failed from %s to %s", source, target));
            }
        } finally {
            sourceInputStream.close();
        }
    } finally {
        fileOutputStream.close();
    }
}
 
Example 8
protected LocallyAvailableResource saveIntoFileStore(final File source, final File destination, final boolean isMove) {
    String verb = isMove ? "move" : "copy";

    if (!source.exists()) {
        throw new GradleException(String.format("Cannot %s '%s' into filestore @ '%s' as it does not exist", verb, source, destination));
    }

    String error = String.format("Failed to %s file '%s' into filestore at '%s' ", verb, source, destination);

    return doAdd(destination, error, new Action<File>() {
        public void execute(File file) {
            if (isMove) {
                GFileUtils.moveFile(source, destination);
            } else {
                GFileUtils.copyFile(source, destination);
            }
        }
    });
}
 
Example 9
protected void doBuild(DaemonCommandExecution execution, Build build) {
    Properties originalSystemProperties = new Properties();
    originalSystemProperties.putAll(System.getProperties());
    Map<String, String> originalEnv = new HashMap<String, String>(System.getenv());
    File originalProcessDir = GFileUtils.canonicalise(new File("."));

    for (Map.Entry<String, String> entry : build.getParameters().getSystemProperties().entrySet()) {
        if (SystemProperties.getStandardProperties().contains(entry.getKey())) {
            continue;
        }
        if (SystemProperties.getNonStandardImportantProperties().contains(entry.getKey())) {
            continue;
        }
        if (entry.getKey().startsWith("sun.")) {
            continue;
        }
        System.setProperty(entry.getKey(), entry.getValue());
    }

    LOGGER.debug("Configuring env variables: {}", build.getParameters().getEnvVariables());
    processEnvironment.maybeSetEnvironment(build.getParameters().getEnvVariables());
    processEnvironment.maybeSetProcessDir(build.getParameters().getCurrentDir());

    // Capture and restore this in case the build code calls Locale.setDefault()
    Locale locale = Locale.getDefault();

    try {
        execution.proceed();
    } finally {
        System.setProperties(originalSystemProperties);
        processEnvironment.maybeSetEnvironment(originalEnv);
        processEnvironment.maybeSetProcessDir(originalProcessDir);
        Locale.setDefault(locale);
    }
}
 
Example 10
public File prepareProjectDir(File projectDir) {
    if (projectDir == null) {
        TemporaryFileProvider temporaryFileProvider = new TmpDirTemporaryFileProvider();
        projectDir = temporaryFileProvider.createTemporaryDirectory("gradle", "projectDir");
        // TODO deleteOnExit won't clean up non-empty directories (and it leaks memory for long-running processes).
        projectDir.deleteOnExit();
    } else {
        projectDir = GFileUtils.canonicalise(projectDir);
    }
    return projectDir;
}
 
Example 11
Source Project: pushfish-android   Source File: JarCache.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
private FileInfo copyIntoCache(Factory<File> baseDirFactory, File source, long lastModified, long length, HashValue hashValue) {
    File baseDir = baseDirFactory.create();
    File cachedFile = new File(baseDir, hashValue.asCompactString() + '/' + source.getName());
    if (!cachedFile.isFile()) {
        // Has previously been added to the cache directory
        GFileUtils.copyFile(source, cachedFile);
    }
    FileInfo fileInfo = new FileInfo(lastModified, length, hashValue, cachedFile);
    cachedFiles.put(source, fileInfo);
    return fileInfo;
}
 
Example 12
public InputStream open() {
    if (read && file != null) {
        return GFileUtils.openInputStream(file);
    }
    if (read || tar.getCurrent() != entry) {
        throw new UnsupportedOperationException(String.format("The contents of %s has already been read.", this));
    }
    read = true;
    return tar;
}
 
Example 13
public DefaultProjectDescriptor(DefaultProjectDescriptor parent, String name, File dir,
                                ProjectDescriptorRegistry projectDescriptorRegistry, FileResolver fileResolver) {
    this.parent = parent;
    this.name = name;
    this.fileResolver = fileResolver;
    this.dir = GFileUtils.canonicalise(dir);
    this.projectDescriptorRegistry = projectDescriptorRegistry;
    this.path = path(name);
    projectDescriptorRegistry.addProject(this);
    if (parent != null) {
        parent.getChildren().add(this);
    }
}
 
Example 14
public void initialize(FileLock fileLock) {
    for (File file : getBaseDir().listFiles()) {
        if (fileLock.isLockFile(file) || file.equals(propertiesFile)) {
            continue;
        }
        GFileUtils.forceDelete(file);
    }
    if (initAction != null) {
        initAction.execute(DefaultPersistentDirectoryCache.this);
    }
    GUtil.saveProperties(properties, propertiesFile);
    didRebuild = true;
}
 
Example 15
private BuildComparisonResultRenderer<Writer> createResultRenderer(Charset encoding, final File reportDir, final Map<String, String> hostAttributes) {
    return new GradleBuildComparisonResultHtmlRenderer(
            comparisonResultRenderers,
            outcomeRenderers,
            encoding,
            sourceBuildExecuter,
            targetBuildExecuter,
            hostAttributes,
            new Transformer<String, File>() {
                public String transform(File original) {
                    return GFileUtils.relativePath(reportDir, original);
                }
            }
    );
}
 
Example 16
private void locateInstallsInRegistry(String baseKey) {
    List<String> visualCppVersions;
    try {
        visualCppVersions = windowsRegistry.getValueNames(WindowsRegistry.Key.HKEY_LOCAL_MACHINE, baseKey + REGISTRY_ROOTPATH_VC);
    } catch (MissingRegistryEntryException e) {
        // No Visual Studio information available in the registry
        return;
    }

    for (String valueName : visualCppVersions) {
        if (!valueName.matches("\\d+\\.\\d+")) {
            // Ignore the other values
            continue;
        }
        File visualCppDir = new File(windowsRegistry.getStringValue(WindowsRegistry.Key.HKEY_LOCAL_MACHINE, baseKey + REGISTRY_ROOTPATH_VC, valueName));
        visualCppDir = GFileUtils.canonicalise(visualCppDir);
        File visualStudioDir = visualCppDir.getParentFile();

        if (isVisualCpp(visualCppDir) && isVisualStudio(visualStudioDir)) {
            LOGGER.debug("Found Visual C++ {} at {}", valueName, visualCppDir);
            VersionNumber version = VersionNumber.parse(valueName);
            VisualCppInstall visualCpp = buildVisualCppInstall("Visual C++ " + valueName, visualStudioDir, visualCppDir, version);
            VisualStudioInstall visualStudio = new VisualStudioInstall(visualStudioDir, visualCpp);
            foundInstalls.put(visualStudioDir, visualStudio);
        } else {
            LOGGER.debug("Ignoring candidate Visual C++ directory {} as it does not look like a Visual C++ installation.", visualCppDir);
        }
    }
}
 
Example 17
private void maybeDelete(FileVisitDetails fileDetails, boolean isDir) {
    RelativePath path = fileDetails.getRelativePath();
    if (!visited.contains(path)) {
        if (isDir) {
            GFileUtils.deleteDirectory(fileDetails.getFile());
        } else {
            GFileUtils.deleteQuietly(fileDetails.getFile());
        }
        didWork = true;
    }
}
 
Example 18
private SearchResult locateUserSpecifiedInstall(File candidate) {
    File visualStudioDir = GFileUtils.canonicalise(candidate);
    File visualCppDir = new File(visualStudioDir, "VC");
    if (!isVisualStudio(visualStudioDir) || !isVisualCpp(visualCppDir)) {
        LOGGER.debug("Ignoring candidate Visual C++ install for {} as it does not look like a Visual C++ installation.", candidate);
        return new InstallNotFound(String.format("The specified installation directory '%s' does not appear to contain a Visual Studio installation.", candidate));
    }

    if (!foundInstalls.containsKey(visualStudioDir)) {
        VisualCppInstall visualCpp = buildVisualCppInstall("Visual C++ from user provided path", visualStudioDir, visualCppDir, VersionNumber.UNKNOWN);
        VisualStudioInstall visualStudio = new VisualStudioInstall(visualStudioDir, visualCpp);
        foundInstalls.put(visualStudioDir, visualStudio);
    }
    return new InstallFound(foundInstalls.get(visualStudioDir));
}
 
Example 19
@Override
public LocallyAvailableResource move(String path, File source) {
    LocallyAvailableResource entry = super.move(path, source);
    if (source.exists()) {
        GFileUtils.deleteQuietly(source);
    }
    return entry;
}
 
Example 20
private void searchForDependency(Set<ResolvedInclude> dependencies, List<File> searchPath, String include) {
    for (File searchDir : searchPath) {
        File candidate = new File(searchDir, include);
        // TODO:DAZ This means that we'll never detect changed files if they are not on the defined include path
        if (candidate.isFile()) {
            dependencies.add(new ResolvedInclude(include, GFileUtils.canonicalise(candidate)));
            return;
        }
    }
}
 
Example 21
public ClassAnalysis getClassAnalysis(String className, File classFile) {
    FileInputStream input = GFileUtils.openInputStream(classFile);
    try {
        return getClassAnalysis(className, input);
    } catch (IOException e) {
        throw new RuntimeException("Problems loading class analysis for '" + className + "' from file: " + classFile);
    } finally {
        GFileUtils.closeInputStream(input);
    }
}
 
Example 22
private void searchForDependency(Set<ResolvedInclude> dependencies, List<File> searchPath, String include) {
    for (File searchDir : searchPath) {
        File candidate = new File(searchDir, include);
        if (candidate.isFile()) {
            dependencies.add(new ResolvedInclude(include, GFileUtils.canonicalise(candidate)));
            return;
        }
    }
}
 
Example 23
public DefaultPersistentDirectoryStore open() {
    GFileUtils.mkdirs(dir);
    cacheAccess = createCacheAccess();
    try {
        cacheAccess.open(lockOptions);
    } catch (Throwable e) {
        throw new CacheOpenException(String.format("Could not open %s.", this), e);
    }

    return this;
}
 
Example 24
public File prepareProjectDir(File projectDir) {
    if (projectDir == null) {
        TemporaryFileProvider temporaryFileProvider = new TmpDirTemporaryFileProvider();
        projectDir = temporaryFileProvider.createTemporaryDirectory("gradle", "projectDir");
        // TODO deleteOnExit won't clean up non-empty directories (and it leaks memory for long-running processes).
        projectDir.deleteOnExit();
    } else {
        projectDir = GFileUtils.canonicalise(projectDir);
    }
    return projectDir;
}
 
Example 25
private SearchResult locateUserSpecifiedSdk(File candidate) {
    File sdkDir = GFileUtils.canonicalise(candidate);
    if (!isWindowsSdk(sdkDir)) {
        return new SdkNotFound(String.format("The specified installation directory '%s' does not appear to contain a Windows SDK installation.", candidate));
    }

    if (!foundSdks.containsKey(sdkDir)) {
        addSdk(sdkDir, VERSION_USER, NAME_USER);
    }
    return new SdkFound(foundSdks.get(sdkDir));
}
 
Example 26
private PersistentCache doOpenStore(File storeDir, String displayName, LockOptions lockOptions, Action<? super PersistentCache> initializer) throws CacheOpenException {
    if (initializer != null) {
        throw new UnsupportedOperationException("Initializer actions are not currently supported by the directory store implementation.");
    }
    File canonicalDir = GFileUtils.canonicalise(storeDir);
    DirCacheReference dirCacheReference = dirCaches.get(canonicalDir);
    if (dirCacheReference == null) {
        ReferencablePersistentCache cache = new DefaultPersistentDirectoryStore(canonicalDir, displayName, lockOptions, lockManager);
        cache.open();
        dirCacheReference = new DirCacheReference(cache, Collections.<String, Object>emptyMap(), lockOptions, false);
        dirCaches.put(canonicalDir, dirCacheReference);
    }
    return new ReferenceTrackingCache(dirCacheReference);
}
 
Example 27
public ClassAnalysis getClassAnalysis(String className, File classFile) {
    FileInputStream input = GFileUtils.openInputStream(classFile);
    try {
        return getClassAnalysis(className, input);
    } catch (IOException e) {
        throw new RuntimeException("Problems loading class analysis for '" + className + "' from file: " + classFile);
    } finally {
        GFileUtils.closeInputStream(input);
    }
}
 
Example 28
public File createTemporaryDirectory(@Nullable String prefix, @Nullable String suffix, @Nullable String... path) {
    File dir = new File(baseDirFactory.create(), CollectionUtils.join("/", path));
    GFileUtils.mkdirs(dir);
    try {
        // TODO: This is not a great paradigm for creating a temporary directory.
        // See http://guava-libraries.googlecode.com/svn/tags/release08/javadoc/com/google/common/io/Files.html#createTempDir%28%29 for an alternative.
        File tmpDir = File.createTempFile("gradle", "projectDir", dir);
        tmpDir.delete();
        tmpDir.mkdir();
        return tmpDir;
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
 
Example 29
public InputStream open() {
    if (read && file != null) {
        return GFileUtils.openInputStream(file);
    }
    if (read || tar.getCurrent() != entry) {
        throw new UnsupportedOperationException(String.format("The contents of %s has already been read.", this));
    }
    read = true;
    return tar;
}
 
Example 30
public DefaultProjectDescriptor(DefaultProjectDescriptor parent, String name, File dir,
                                ProjectDescriptorRegistry projectDescriptorRegistry, FileResolver fileResolver) {
    this.parent = parent;
    this.name = name;
    this.fileResolver = fileResolver;
    this.dir = GFileUtils.canonicalise(dir);
    this.projectDescriptorRegistry = projectDescriptorRegistry;
    this.path = path(name);
    projectDescriptorRegistry.addProject(this);
    if (parent != null) {
        parent.getChildren().add(this);
    }
}