Java Code Examples for com.android.utils.FileUtils#deleteIfExists()

The following examples show how to use com.android.utils.FileUtils#deleteIfExists() . 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: CollectHandler.java    From EasyRouter with Apache License 2.0 6 votes vote down vote up
@Override
public boolean onStart(QualifiedContent content) throws IOException {
    if (content instanceof JarInput) {
        JarInput jarInput = (JarInput) content;
        File targetFile = context.getRelativeFile(content);
        switch (jarInput.getStatus()) {
            case REMOVED:
                FileUtils.deleteIfExists(targetFile);
                return false;
            case CHANGED:
                FileUtils.deleteIfExists(targetFile);
            default:
                Files.createParentDirs(targetFile);
                map.put(content, new JarWriter(targetFile));
        }
        return true;
    }
    return false;
}
 
Example 2
Source File: AtlasBundleInstantApp.java    From atlas with Apache License 2.0 5 votes vote down vote up
@TaskAction
public void taskAction() throws IOException {
    FileUtils.mkdirs(bundleDirectory);
    File bundleFile = new File(bundleDirectory, bundleName);
    FileUtils.deleteIfExists(bundleFile);
    File baseFeatureApk = new File(bundleDirectory, "baseFeature.apk");
    if (!apkFile.exists()){
        File[]apkFiles = apkFile.getParentFile().listFiles(new FileFilter() {
            @Override
            public boolean accept(File pathname) {
                return pathname.getName().endsWith(".apk");
            }
        });
        if (apkFiles != null){
            apkFile = apkFiles[0];
        }
    }
    if (apkFile.exists()) {
        try {
            make(baseFeatureApk, apkFile, bundleFile, scope.getVariantConfiguration().getSigningConfig());
        } catch (SigningException e) {
            e.printStackTrace();
        }
    }else {
        getLogger().error(apkFile.getAbsolutePath()+" is not exist!");
    }
}
 
Example 3
Source File: AtlasDexArchiveBuilderTransform.java    From atlas with Apache License 2.0 4 votes vote down vote up
private List<File> convertToDexArchive(
        @NonNull Context context,
        @NonNull QualifiedContent input,
        @NonNull TransformOutputProvider outputProvider,
        boolean isIncremental)
        throws Exception {

    logger.verbose("Dexing {}", input.getFile().getAbsolutePath());
    ImmutableList.Builder<File> dexArchives = ImmutableList.builder();
    for (int bucketId = 0; bucketId < NUMBER_OF_BUCKETS; bucketId++) {
        File preDexOutputFile = getPreDexFile(outputProvider, input, bucketId);
        if (input.getFile().isDirectory()) {
            File cachedVersion = cacheHandler.getCachedVersionIfPresent(input.getFile());
            dexArchives.add(preDexOutputFile);
            if (cachedVersion != null) {
                FileUtils.copyDirectoryContentToDirectory(cachedVersion, preDexOutputFile);
                return dexArchives.build();

            }
        }
        if (preDexOutputFile.isDirectory() && preDexOutputFile.exists()) {
            FileUtils.cleanOutputDir(preDexOutputFile);
        }else {
            FileUtils.deleteIfExists(preDexOutputFile);
        }
        AtlasDexArchiveBuilderTransform.DexConversionParameters parameters =
                new AtlasDexArchiveBuilderTransform.DexConversionParameters(
                        input,
                        preDexOutputFile,
                        NUMBER_OF_BUCKETS,
                        bucketId,
                        minSdkVersion,
                        dexOptions.getAdditionalParameters(),
                        inBufferSize,
                        outBufferSize,
                        dexer,
                        isDebuggable,
                        isIncremental,
                        false);

        if (useGradleWorkers) {
            context.getWorkerExecutor()
                    .submit(
                            DexArchiveBuilderTransform.DexConversionWorkAction.class,
                            configuration -> {
                                configuration.setIsolationMode(IsolationMode.NONE);
                                configuration.setParams(parameters);
                            });
        } else {
            executor.execute(
                    () -> {
                        ProcessOutputHandler outputHandler =
                                new ParsingProcessOutputHandler(
                                        new ToolOutputParser(
                                                new DexParser(), Message.Kind.ERROR, logger),
                                        new ToolOutputParser(new DexParser(), logger),
                                        errorReporter);
                        ProcessOutput output = null;
                        try (Closeable ignored = output = outputHandler.createOutput()) {
                            launchProcessing(
                                    parameters,
                                    output.getStandardOutput(),
                                    output.getErrorOutput());
                        } finally {
                            if (output != null) {
                                try {
                                    outputHandler.handleOutput(output);
                                } catch (ProcessException e) {
                                    // ignore this one
                                }
                            }
                        }
                        return null;
                    });
        }
    }
    List<File> files = dexArchives.build();
    return files;
}
 
Example 4
Source File: AtlasDexArchiveBuilderTransform.java    From atlas with Apache License 2.0 4 votes vote down vote up
private List<File> convertAwbToDexArchive(
        @NonNull Context context,
        @NonNull QualifiedContent input,
        @NonNull File outputProvider,
        boolean isIncremental,
        boolean awb)
        throws Exception {

    int count = 0;
    if (input.getFile().isFile()) {
         count = computerClassCount(input.getFile());
       
    }else if (input.getFile().isDirectory()){
        count = 1;
    }
    logger.verbose("Dexing {}", input.getFile().getAbsolutePath());

    ImmutableList.Builder<File> dexArchives = ImmutableList.builder();

    for (int bucketId = 0; bucketId < count; bucketId++) {
        File preDexOutputFile = getAwbPreDexFile(outputProvider, input, bucketId);
        if (input.getFile().isDirectory()) {
            File cachedVersion = cacheHandler.getCachedVersionIfPresent(input.getFile());
            dexArchives.add(preDexOutputFile);
            if (cachedVersion != null) {
                FileUtils.copyDirectoryContentToDirectory(cachedVersion, preDexOutputFile);
                return dexArchives.build();
            }
        }
        if (preDexOutputFile.isDirectory() && preDexOutputFile.exists()) {
            FileUtils.cleanOutputDir(preDexOutputFile);
        }else {
            FileUtils.deleteIfExists(preDexOutputFile);
        }
        AtlasDexArchiveBuilderTransform.DexConversionParameters parameters =
                new AtlasDexArchiveBuilderTransform.DexConversionParameters(
                        input,
                        preDexOutputFile,
                        NUMBER_OF_BUCKETS,
                        bucketId,
                        minSdkVersion,
                        dexOptions.getAdditionalParameters(),
                        inBufferSize,
                        outBufferSize,
                        dexer,
                        isDebuggable,
                        false,
                        awb);

        if (useGradleWorkers) {
            context.getWorkerExecutor()
                    .submit(
                            DexArchiveBuilderTransform.DexConversionWorkAction.class,
                            configuration -> {
                                configuration.setIsolationMode(IsolationMode.NONE);
                                configuration.setParams(parameters);
                            });
        } else {
            executor.execute(
                    () -> {
                        ProcessOutputHandler outputHandler =
                                new ParsingProcessOutputHandler(
                                        new ToolOutputParser(
                                                new DexParser(), Message.Kind.ERROR, logger),
                                        new ToolOutputParser(new DexParser(), logger),
                                        errorReporter);
                        ProcessOutput output = null;
                        try (Closeable ignored = output = outputHandler.createOutput()) {
                            launchProcessing(
                                    parameters,
                                    output.getStandardOutput(),
                                    output.getErrorOutput());
                        } finally {
                            if (output != null) {
                                try {
                                    outputHandler.handleOutput(output);
                                } catch (ProcessException e) {
                                    // ignore this one
                                }
                            }
                        }
                        return null;
                    });
        }
    }

   List<File>files =  dexArchives.build();
    return files;
}
 
Example 5
Source File: AwbApkPackageTask.java    From atlas with Apache License 2.0 4 votes vote down vote up
public File splitFullAction(@NonNull ApkData apkData, @Nullable File processedResources)
        throws IOException {

    File incrementalDirForSplit = new File(getIncrementalFolder(awbBundle), apkData.getFullName());

    /*
     * Clear the intermediate build directory. We don't know if anything is in there and
     * since this is a full build, we don't want to get any interference from previous state.
     */
    if (incrementalDirForSplit.exists()) {
        FileUtils.deleteDirectoryContents(incrementalDirForSplit);
    } else {
        FileUtils.mkdirs(incrementalDirForSplit);
    }

    File cacheByPathDir = new File(incrementalDirForSplit, ZIP_DIFF_CACHE_DIR);
    FileUtils.mkdirs(cacheByPathDir);
    FileCacheByPath cacheByPath = new FileCacheByPath(cacheByPathDir);

    /*
     * Clear the cache to make sure we have do not do an incremental build.
     */
    cacheByPath.clear();

    Set<File> androidResources = getAndroidResources(apkData, processedResources);

    appVariantOutputContext.getVariantContext().getProject().getLogger().warn(awbBundle.getName()+" androidResources File:"+androidResources.iterator().next().getAbsolutePath());

    FileUtils.mkdirs(outputDirectory);

    File outputFile = getOutputFile(awbBundle);

    /*
     * Additionally, make sure we have no previous package, if it exists.
     */
    FileUtils.deleteIfExists(outputFile);

    ImmutableMap<RelativeFile, FileStatus> updatedDex =
            IncrementalRelativeFileSets.fromZipsAndDirectories(dexFolders);
    ImmutableMap<RelativeFile, FileStatus> updatedJavaResources = getJavaResourcesChanges();
    ImmutableMap<RelativeFile, FileStatus> updatedAssets =
            IncrementalRelativeFileSets.fromZipsAndDirectories(assets.getFiles());
    ImmutableMap<RelativeFile, FileStatus> updatedAndroidResources =
            IncrementalRelativeFileSets.fromZipsAndDirectories(androidResources);
    ImmutableMap<RelativeFile, FileStatus> updatedJniResources =
            IncrementalRelativeFileSets.fromZipsAndDirectories(jniFolders);

    Collection<BuildOutput> manifestOutputs = BuildOutputs.load(TaskOutputHolder.TaskOutputType.MERGED_MANIFESTS, awbManifestFolder.getSingleFile().getParentFile());

    doTask(
            apkData,
            incrementalDirForSplit,
            outputFile,
            cacheByPath,
            manifestOutputs,
            updatedDex,
            updatedJavaResources,
            updatedAssets,
            updatedAndroidResources,
            updatedJniResources);

    /*
     * Update the known files.
     */
    KnownFilesSaveData saveData = KnownFilesSaveData.make(incrementalDirForSplit);
    saveData.setInputSet(updatedDex.keySet(), KnownFilesSaveData.InputSet.DEX);
    saveData.setInputSet(updatedJavaResources.keySet(), KnownFilesSaveData.InputSet.JAVA_RESOURCE);
    saveData.setInputSet(updatedAssets.keySet(), KnownFilesSaveData.InputSet.ASSET);
    saveData.setInputSet(updatedAndroidResources.keySet(), KnownFilesSaveData.InputSet.ANDROID_RESOURCE);
    saveData.setInputSet(updatedJniResources.keySet(), KnownFilesSaveData.InputSet.NATIVE_RESOURCE);
    saveData.saveCurrentData();
    File file;
    String outputFileName = outputFile.getName();
    file = getAwbPackageOutputFile(appVariantOutputContext.getVariantContext(), outputFileName);
    FileUtils.copyFileToDirectory(outputFile, file.getParentFile());
    return new File(file.getParentFile(), outputFileName);
}
 
Example 6
Source File: PrepareAPTask.java    From atlas with Apache License 2.0 4 votes vote down vote up
/**
 * Directory of so
 */
@TaskAction
void generate() throws IOException, DocumentException {

    Project project = getProject();
    File apBaseFile = null;

    File apFile = getApFile();
    if (null != apFile && apFile.exists()) {
        apBaseFile = apFile;
    } else {
        String apDependency = getApDependency();
        if (StringUtils.isNotBlank(apContext.getApDependency())) {
            Dependency dependency = project.getDependencies().create(apDependency);
            Configuration configuration = project.getConfigurations().detachedConfiguration(dependency);
            configuration.setTransitive(false);
            configuration.getResolutionStrategy().cacheChangingModulesFor(0, TimeUnit.MILLISECONDS);
            configuration.getResolutionStrategy().cacheDynamicVersionsFor(0, TimeUnit.MILLISECONDS);
            for (File file : configuration.getFiles()) {
                if (file.getName().endsWith(".ap")) {
                    apBaseFile = file;
                    break;
                }
            }
        }
    }

    if (null != apBaseFile && apBaseFile.exists()) {

        try {
            explodedDir = getExplodedDir();
            BetterZip.unzipDirectory(apBaseFile, explodedDir);
            apContext.setApExploredFolder(explodedDir);
            Set<String> awbBundles = getAwbBundles();
            if (awbBundles != null) {
                // Unzip the baseline Bundle
                for (String awbBundle : awbBundles) {
                    File awbFile = BetterZip.extractFile(new File(explodedDir, AP_INLINE_APK_FILENAME),
                                                         "lib/armeabi/" + awbBundle,
                                                         new File(explodedDir, AP_INLINE_AWB_EXTRACT_DIRECTORY));
                    File awbExplodedDir = new File(new File(explodedDir, AP_INLINE_AWB_EXPLODED_DIRECTORY),
                                                   FilenameUtils.getBaseName(awbBundle));
                    BetterZip.unzipDirectory(awbFile, awbExplodedDir);
                    FileUtils.renameTo(new File(awbExplodedDir, FN_APK_CLASSES_DEX),
                                       new File(awbExplodedDir, "classes2.dex"));
                }
                // Preprocessing increment androidmanifest.xml
                ManifestFileUtils.updatePreProcessBaseManifestFile(
                    FileUtils.join(explodedDir, "manifest-modify", ANDROID_MANIFEST_XML),
                    new File(explodedDir, ANDROID_MANIFEST_XML));
            }
            if (explodedDir.listFiles().length == 0){
                throw new RuntimeException("unzip ap exception, no files found");
            }
        }catch (Throwable e){
            FileUtils.deleteIfExists(apBaseFile);
            throw new GradleException(e.getMessage(),e);

        }
    }
}