Java Code Examples for com.android.utils.Pair#getSecond()

The following examples show how to use com.android.utils.Pair#getSecond() . 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: MergeRootFrameLayoutDetector.java    From javaide with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void afterCheckProject(@NonNull Context context) {
    if (mPending != null && mWhitelistedLayouts != null) {
        // Process all the root FrameLayouts that are eligible, and generate
        // suggestions for <merge> replacements for any layouts that are included
        // from other layouts
        for (Pair<String, Handle> pair : mPending) {
            String layout = pair.getFirst();
            if (mWhitelistedLayouts.contains(layout)) {
                Handle handle = pair.getSecond();

                Object clientData = handle.getClientData();
                if (clientData instanceof Node) {
                    if (context.getDriver().isSuppressed(null, ISSUE, (Node) clientData)) {
                        return;
                    }
                }

                Location location = handle.resolve();
                context.report(ISSUE, location,
                        "This `<FrameLayout>` can be replaced with a `<merge>` tag");
            }
        }
    }
}
 
Example 2
Source File: LocalSdkParser.java    From java-n-IDE-for-Android with Apache License 2.0 5 votes vote down vote up
/**
 * The sdk manager only lists valid addons. However here we also want to find "broken"
 * addons, i.e. addons that failed to load for some reason.
 * <p/>
 * Find any other sub-directories under the /add-ons root that hasn't been visited yet
 * and assume they contain broken addons.
 */
private void scanMissingAddons(SdkManager sdkManager,
        HashSet<File> visited,
        ArrayList<Package> packages,
        ILogger log) {
    File addons = new File(new File(sdkManager.getLocation()), SdkConstants.FD_ADDONS);

    for (File dir : listFilesNonNull(addons)) {
        if (dir.isDirectory() && !visited.contains(dir)) {
            Pair<Map<String, String>, String> infos =
                parseAddonProperties(dir, sdkManager.getTargets(), log);
            Properties sourceProps =
                parseProperties(new File(dir, SdkConstants.FN_SOURCE_PROP));

            Map<String, String> addonProps = infos.getFirst();
            String error = infos.getSecond();
            try {
                Package pkg = AddonPackage.createBroken(dir.getAbsolutePath(),
                                                        sourceProps,
                                                        addonProps,
                                                        error);
                packages.add(pkg);
                visited.add(dir);
            } catch (Exception e) {
                log.error(e, null);
            }
        }
    }
}
 
Example 3
Source File: OverdrawDetector.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void afterCheckProject(@NonNull Context context) {
    if (mRootAttributes != null) {
        for (Pair<Location, String> pair : mRootAttributes) {
            Location location = pair.getFirst();

            Object clientData = location.getClientData();
            if (clientData instanceof Node) {
                if (context.getDriver().isSuppressed(null, ISSUE, (Node) clientData)) {
                    return;
                }
            }

            String layoutName = location.getFile().getName();
            if (endsWith(layoutName, DOT_XML)) {
                layoutName = layoutName.substring(0, layoutName.length() - DOT_XML.length());
            }

            String theme = getTheme(context, layoutName);
            if (theme == null || !isBlankTheme(theme)) {
                String drawable = pair.getSecond();
                String message = String.format(
                        "Possible overdraw: Root element paints background `%1$s` with " +
                        "a theme that also paints a background (inferred theme is `%2$s`)",
                        drawable, theme);
                // TODO: Compute applicable scope node
                context.report(ISSUE, location, message);
            }
        }
    }
}
 
Example 4
Source File: ApiDetector.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void afterCheckProject(@NonNull Context context) {
    if (mPendingFields != null) {
        for (List<Pair<String, Location>> list : mPendingFields.values()) {
            for (Pair<String, Location> pair : list) {
                String message = pair.getFirst();
                Location location = pair.getSecond();
                context.report(INLINED, location, message);
            }
        }
    }

    super.afterCheckProject(context);
}
 
Example 5
Source File: LayoutConsistencyDetector.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
private Map<File, Set<String>> getIdMap(List<Pair<File, Map<String, String>>> files,
        int layoutCount) {
    Map<File, Set<String>> idMap = new HashMap<File, Set<String>>(layoutCount);
    for (Pair<File, Map<String, String>> pair : files) {
        File file = pair.getFirst();
        Map<String, String> typeMap = pair.getSecond();
        Set<String> ids = typeMap.keySet();
        idMap.put(file, stripIrrelevantIds(ids));
    }
    return idMap;
}
 
Example 6
Source File: LayoutInflationDetector.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void afterCheckProject(@NonNull Context context) {
    if (mPendingErrors != null) {
        for (Pair<String,Location> pair : mPendingErrors) {
            String inflatedLayout = pair.getFirst();
            if (mLayoutsWithRootLayoutParams == null ||
                    !mLayoutsWithRootLayoutParams.contains(inflatedLayout)) {
                // No root layout parameters on the inflated layout: no need to complain
                continue;
            }
            Location location = pair.getSecond();
            context.report(ISSUE, location, ERROR_MESSAGE);
        }
    }
}
 
Example 7
Source File: LocalSdkParser.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
/**
 * The sdk manager only lists valid addons. However here we also want to find "broken"
 * addons, i.e. addons that failed to load for some reason.
 * <p/>
 * Find any other sub-directories under the /add-ons root that hasn't been visited yet
 * and assume they contain broken addons.
 */
private void scanMissingAddons(SdkManager sdkManager,
        HashSet<File> visited,
        ArrayList<Package> packages,
        ILogger log) {
    File addons = new File(new File(sdkManager.getLocation()), SdkConstants.FD_ADDONS);

    for (File dir : listFilesNonNull(addons)) {
        if (dir.isDirectory() && !visited.contains(dir)) {
            Pair<Map<String, String>, String> infos =
                parseAddonProperties(dir, sdkManager.getTargets(), log);
            Properties sourceProps =
                parseProperties(new File(dir, SdkConstants.FN_SOURCE_PROP));

            Map<String, String> addonProps = infos.getFirst();
            String error = infos.getSecond();
            try {
                Package pkg = AddonPackage.createBroken(dir.getAbsolutePath(),
                                                        sourceProps,
                                                        addonProps,
                                                        error);
                packages.add(pkg);
                visited.add(dir);
            } catch (Exception e) {
                log.error(e, null);
            }
        }
    }
}
 
Example 8
Source File: ResourceUsageAnalyzer.java    From bazel with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
@Nullable
Resource getResourceFromCode(@NonNull String owner, @NonNull String name) {
  Pair<ResourceType, Map<String, String>> pair = resourceObfuscation.get(owner);
  if (pair != null) {
    ResourceType type = pair.getFirst();
    Map<String, String> nameMap = pair.getSecond();
    String renamedField = nameMap.get(name);
    if (renamedField != null) {
      name = renamedField;
    }
    return model.getResource(type, name);
  }
  return null;
}
 
Example 9
Source File: ArchiveInstaller.java    From java-n-IDE-for-Android with Apache License 2.0 4 votes vote down vote up
/**
 * Install this {@link ArchiveReplacement}s.
 * A "replacement" is composed of the actual new archive to install
 * (c.f. {@link ArchiveReplacement#getNewArchive()} and an <em>optional</em>
 * archive being replaced (c.f. {@link ArchiveReplacement#getReplaced()}.
 * In the case of a new install, the later should be null.
 * <p/>
 * The new archive to install will be skipped if it is incompatible.
 *
 * @return True if the archive was installed, false otherwise.
 */
public boolean install(ArchiveReplacement archiveInfo,
        String osSdkRoot,
        boolean forceHttp,
        SdkManager sdkManager,
        DownloadCache cache,
        ITaskMonitor monitor) {

    Archive newArchive = archiveInfo.getNewArchive();
    Package pkg = newArchive.getParentPackage();

    String name = pkg.getShortDescription();

    if (newArchive.isLocal()) {
        // This should never happen.
        monitor.log("Skipping already installed archive: %1$s for %2$s",
                name,
                newArchive.getOsDescription());
        return false;
    }

    // In detail mode, give us a way to force install of incompatible archives.
    boolean checkIsCompatible = System.getenv(ENV_VAR_IGNORE_COMPAT) == null;

    if (checkIsCompatible && !newArchive.isCompatible()) {
        monitor.log("Skipping incompatible archive: %1$s for %2$s",
                name,
                newArchive.getOsDescription());
        return false;
    }

    Pair<File, File> files = downloadFile(newArchive, osSdkRoot, cache, monitor, forceHttp);
    File tmpFile   = files == null ? null : files.getFirst();
    File propsFile = files == null ? null : files.getSecond();
    if (tmpFile != null) {
        // Unarchive calls the pre/postInstallHook methods.
        if (unarchive(archiveInfo, osSdkRoot, tmpFile, sdkManager, monitor)) {
            monitor.log("Installed %1$s", name);
            // Delete the temp archive if it exists, only on success
            mFileOp.deleteFileOrFolder(tmpFile);
            mFileOp.deleteFileOrFolder(propsFile);
            return true;
        }
    }

    return false;
}
 
Example 10
Source File: ExtractAnnotations.java    From javaide with GNU General Public License v3.0 4 votes vote down vote up
@Override
@TaskAction
protected void compile() {
    if (!hasAndroidAnnotations()) {
        return;

    }


    if (encoding == null) {
        encoding = "UTF_8";
    }


    Pair<Collection<CompilationUnitDeclaration>, INameEnvironment> result = parseSources();
    Collection<CompilationUnitDeclaration> parsedUnits = result.getFirst();
    INameEnvironment environment = result.getSecond();

    try {
        if (!allowErrors) {
            for (CompilationUnitDeclaration unit : parsedUnits) {
                // so maybe I don't need my map!!
                CategorizedProblem[] problems = unit.compilationResult().getAllProblems();
                for (IProblem problem : problems) {
                    if (problem.isError()) {
                        System.out.println("Not extracting annotations (compilation problems encountered)");
                        System.out.println("Error: " + problem.getOriginatingFileName() + ":" + problem.getSourceLineNumber() + ": " + problem.getMessage());
                        // TODO: Consider whether we abort the build at this point!
                        return;

                    }

                }

            }

        }


        // API definition file
        ApiDatabase database = null;
        if (apiFilter != null && apiFilter.exists()) {
            try {
                database = new ApiDatabase(apiFilter);
            } catch (IOException e) {
                throw new BuildException("Could not open API database " + apiFilter, e);
            }

        }


        boolean displayInfo = getProject().getLogger().isEnabled(LogLevel.INFO);
        Boolean includeClassRetentionAnnotations = false;
        Boolean sortAnnotations = false;

        Extractor extractor = new Extractor(database, classDir, displayInfo, includeClassRetentionAnnotations, sortAnnotations);
        extractor.extractFromProjectSource(parsedUnits);
        if (mergeJars != null) {
            for (File jar : mergeJars) {
                extractor.mergeExisting(jar);
            }

        }

        extractor.export(output, proguard);
        extractor.removeTypedefClasses();
    } finally {
        if (environment != null) {
            environment.cleanup();
        }

    }

}
 
Example 11
Source File: ArchiveInstaller.java    From javaide with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Install this {@link ArchiveReplacement}s.
 * A "replacement" is composed of the actual new archive to install
 * (c.f. {@link ArchiveReplacement#getNewArchive()} and an <em>optional</em>
 * archive being replaced (c.f. {@link ArchiveReplacement#getReplaced()}.
 * In the case of a new install, the later should be null.
 * <p/>
 * The new archive to install will be skipped if it is incompatible.
 *
 * @return True if the archive was installed, false otherwise.
 */
public boolean install(ArchiveReplacement archiveInfo,
        String osSdkRoot,
        boolean forceHttp,
        SdkManager sdkManager,
        DownloadCache cache,
        ITaskMonitor monitor) {

    Archive newArchive = archiveInfo.getNewArchive();
    Package pkg = newArchive.getParentPackage();

    String name = pkg.getShortDescription();

    if (newArchive.isLocal()) {
        // This should never happen.
        monitor.log("Skipping already installed archive: %1$s for %2$s",
                name,
                newArchive.getOsDescription());
        return false;
    }

    // In detail mode, give us a way to force install of incompatible archives.
    boolean checkIsCompatible = System.getenv(ENV_VAR_IGNORE_COMPAT) == null;

    if (checkIsCompatible && !newArchive.isCompatible()) {
        monitor.log("Skipping incompatible archive: %1$s for %2$s",
                name,
                newArchive.getOsDescription());
        return false;
    }

    Pair<File, File> files = downloadFile(newArchive, osSdkRoot, cache, monitor, forceHttp);
    File tmpFile   = files == null ? null : files.getFirst();
    File propsFile = files == null ? null : files.getSecond();
    if (tmpFile != null) {
        // Unarchive calls the pre/postInstallHook methods.
        if (unarchive(archiveInfo, osSdkRoot, tmpFile, sdkManager, monitor)) {
            monitor.log("Installed %1$s", name);
            // Delete the temp archive if it exists, only on success
            mFileOp.deleteFileOrFolder(tmpFile);
            mFileOp.deleteFileOrFolder(propsFile);
            return true;
        }
    }

    return false;
}
 
Example 12
Source File: PreDexCache.java    From javaide with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Pre-dex a given library to a given output with a specific version of the build-tools.
 * @param inputFile the jar to pre-dex
 * @param outFile the output file or folder (if multi-dex is enabled). must exist
 * @param multiDex whether mutli-dex is enabled.
 * @param dexOptions the dex options to run pre-dex
 * @param buildToolInfo the build tools info
 * @param verbose verbose flag
 * @param processExecutor the process executor
 * @throws IOException
 * @throws ProcessException
 * @throws InterruptedException
 */
public void preDexLibrary(
        @NonNull File inputFile,
        @NonNull File outFile,
                 boolean multiDex,
        @NonNull DexOptions dexOptions,
        @NonNull BuildToolInfo buildToolInfo,
        boolean verbose,
        @NonNull JavaProcessExecutor processExecutor,
        @NonNull ProcessOutputHandler processOutputHandler)
        throws IOException, ProcessException, InterruptedException {
    checkState(!multiDex || outFile.isDirectory());

    DexKey itemKey = DexKey.of(
            inputFile,
            buildToolInfo.getRevision());

    Pair<Item, Boolean> pair = getItem(itemKey);
    Item item = pair.getFirst();

    // if this is a new item
    if (pair.getSecond()) {
        try {
            // haven't process this file yet so do it and record it.
            List<File> files = AndroidBuilder.preDexLibrary(
                    inputFile,
                    outFile,
                    multiDex,
                    dexOptions,
                    buildToolInfo,
                    verbose,
                    processExecutor,
                    processOutputHandler);

            item.getOutputFiles().clear();
            item.getOutputFiles().addAll(files);

            incrementMisses();
        } catch (ProcessException exception) {
            // in case of error, delete (now obsolete) output file
            outFile.delete();
            // and rethrow the error
            throw exception;
        } finally {
            // enable other threads to use the output of this pre-dex.
            // if something was thrown they'll handle the missing output file.
            item.getLatch().countDown();
        }
    } else {
        // wait until the file is pre-dexed by the first thread.
        item.getLatch().await();

        // check that the generated file actually exists
        if (item.areOutputFilesPresent()) {
            if (multiDex) {
                // output should be a folder
                for (File sourceFile : item.getOutputFiles()) {
                    File destFile = new File(outFile, sourceFile.getName());
                    checkSame(sourceFile, destFile);
                    Files.copy(sourceFile, destFile);
                }

            } else {
                // file already pre-dex, just copy the output.
                if (item.getOutputFiles().isEmpty()) {
                    throw new RuntimeException(item.toString());
                }
                checkSame(item.getOutputFiles().get(0), outFile);
                Files.copy(item.getOutputFiles().get(0), outFile);
            }
            incrementHits();

        }
    }
}