com.android.utils.Pair Java Examples

The following examples show how to use com.android.utils.Pair. 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: LayoutlibVersionMixin.java    From javaide with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Parses an XML node to process the {@code <layoutlib>} element.
 *
 * The layoutlib element is new in the XSD rev 4, so we need to cope with it missing
 * in earlier XMLs.
 */
public LayoutlibVersionMixin(Node pkgNode) {

    int api = LAYOUTLIB_API_NOT_SPECIFIED;
    int rev = LAYOUTLIB_REV_NOT_SPECIFIED;

    Node layoutlibNode =
        PackageParserUtils.findChildElement(pkgNode, RepoConstants.NODE_LAYOUT_LIB);

    if (layoutlibNode != null) {
        api = PackageParserUtils.getXmlInt(layoutlibNode, RepoConstants.NODE_API, 0);
        rev = PackageParserUtils.getXmlInt(layoutlibNode, RepoConstants.NODE_REVISION, 0);
    }

    mLayoutlibVersion = Pair.of(api, rev);
}
 
Example #2
Source File: LintGradleProject.java    From javaide with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Creates a {@link LintGradleProject} from
 * the given {@link com.android.builder.model.AndroidProject} definition for
 * a given {@link com.android.builder.model.Variant}, and returns it along with
 * a set of lint custom rule jars applicable for the given model project.
 *
 * @param client        the client
 * @param project       the model project
 * @param variant       the variant
 * @param gradleProject the gradle project
 * @return a pair of new project and list of custom rule jars
 */
@NonNull
public static Pair<LintGradleProject, List<File>> create(
        @NonNull LintGradleClient client,
        @NonNull AndroidProject project,
        @NonNull Variant variant,
        @NonNull org.gradle.api.Project gradleProject) {
    File dir = gradleProject.getProjectDir();
    AppGradleProject lintProject = new AppGradleProject(client, dir,
            dir, project, variant);

    List<File> customRules = Lists.newArrayList();
    File appLintJar = new File(gradleProject.getBuildDir(),
            "lint" + separatorChar + "lint.jar");
    if (appLintJar.exists()) {
        customRules.add(appLintJar);
    }

    Set<AndroidLibrary> libraries = Sets.newHashSet();
    Dependencies dependencies = variant.getMainArtifact().getDependencies();
    for (AndroidLibrary library : dependencies.getLibraries()) {
        lintProject.addDirectLibrary(createLibrary(client, library, libraries, customRules));
    }

    return Pair.<LintGradleProject, List<File>>of(lintProject, customRules);
}
 
Example #3
Source File: LintGradleRequest.java    From javaide with GNU General Public License v3.0 6 votes vote down vote up
@Nullable
@Override
public Collection<Project> getProjects() {
    if (mProjects == null) {
        Variant variant = findVariant(mModelProject, mVariantName);
        if (variant == null) {
            mProjects = Collections.emptyList();
            return mProjects;
        }
        Pair<LintGradleProject, List<File>> result = LintGradleProject.create(
                mLintClient, mModelProject, variant, mGradleProject);
        mProjects = Collections.<Project>singletonList(result.getFirst());
        mLintClient.setCustomRules(result.getSecond());
    }

    return mProjects;
}
 
Example #4
Source File: ManifestMerger2.java    From javaide with GNU General Public License v3.0 6 votes vote down vote up
private ManifestMerger2(
        @NonNull ILogger logger,
        @NonNull File mainManifestFile,
        @NonNull ImmutableList<Pair<String, File>> libraryFiles,
        @NonNull ImmutableList<File> flavorsAndBuildTypeFiles,
        @NonNull ImmutableList<Invoker.Feature> optionalFeatures,
        @NonNull Map<String, Object> placeHolderValues,
        @NonNull KeyBasedValueResolver<SystemProperty> systemPropertiesResolver,
        @NonNull MergeType mergeType,
        @NonNull Optional<File> reportFile) {
    this.mSystemPropertyResolver = systemPropertiesResolver;
    this.mPlaceHolderValues = placeHolderValues;
    this.mManifestFile = mainManifestFile;
    this.mLogger = logger;
    this.mLibraryFiles = libraryFiles;
    this.mFlavorsAndBuildTypeFiles = flavorsAndBuildTypeFiles;
    this.mOptionalFeatures = optionalFeatures;
    this.mMergeType = mergeType;
    this.mReportFile = reportFile;
}
 
Example #5
Source File: LayoutConsistencyDetector.java    From javaide with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void visitDocument(@NonNull XmlContext context, @NonNull Document document) {
    Element root = document.getDocumentElement();
    if (root != null) {
        if (context.getPhase() == 1) {
            // Map from ids to types
            Map<String,String> fileMap = Maps.newHashMapWithExpectedSize(10);
            addIds(root, fileMap);

            getFileMapList(context).add(Pair.of(context.file, fileMap));
        } else {
            String name = LintUtils.getLayoutName(context.file);
            Map<String, List<Location>> map = mLocations.get(name);
            if (map != null) {
                lookupLocations(context, root, map);
            }
        }
    }
}
 
Example #6
Source File: ManifestMerger2.java    From java-n-IDE-for-Android with Apache License 2.0 6 votes vote down vote up
private ManifestMerger2(
        @NonNull ILogger logger,
        @NonNull File mainManifestFile,
        @NonNull ImmutableList<Pair<String, File>> libraryFiles,
        @NonNull ImmutableList<File> flavorsAndBuildTypeFiles,
        @NonNull ImmutableList<Invoker.Feature> optionalFeatures,
        @NonNull Map<String, Object> placeHolderValues,
        @NonNull KeyBasedValueResolver<SystemProperty> systemPropertiesResolver,
        @NonNull MergeType mergeType,
        @NonNull Optional<File> reportFile) {
    this.mSystemPropertyResolver = systemPropertiesResolver;
    this.mPlaceHolderValues = placeHolderValues;
    this.mManifestFile = mainManifestFile;
    this.mLogger = logger;
    this.mLibraryFiles = libraryFiles;
    this.mFlavorsAndBuildTypeFiles = flavorsAndBuildTypeFiles;
    this.mOptionalFeatures = optionalFeatures;
    this.mMergeType = mergeType;
    this.mReportFile = reportFile;
}
 
Example #7
Source File: StringFormatDetector.java    From javaide with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void afterCheckProject(@NonNull Context context) {
    if (mFormatStrings != null) {
        boolean checkCount = context.isEnabled(ARG_COUNT);
        boolean checkValid = context.isEnabled(INVALID);
        boolean checkTypes = context.isEnabled(ARG_TYPES);

        // Ensure that all the format strings are consistent with respect to each other;
        // e.g. they all have the same number of arguments, they all use all the
        // arguments, and they all use the same types for all the numbered arguments
        for (Map.Entry<String, List<Pair<Handle, String>>> entry : mFormatStrings.entrySet()) {
            String name = entry.getKey();
            List<Pair<Handle, String>> list = entry.getValue();

            // Check argument counts
            if (checkCount) {
                checkArity(context, name, list);
            }

            // Check argument types (and also make sure that the formatting strings are valid)
            if (checkValid || checkTypes) {
                checkTypes(context, checkValid, checkTypes, name, list);
            }
        }
    }
}
 
Example #8
Source File: ApkUtils.java    From NBANDROID-V2 with Apache License 2.0 6 votes vote down vote up
public static boolean addNewKey(KeyStore ks, File storeFile, char[] storePassword, DN dn) {
    try {
        Pair<PrivateKey, X509Certificate> generated = generateKeyAndCertificate("RSA", "SHA1withRSA", dn.validityYears, encodeDN(dn));
        ks.setKeyEntry(dn.alias, generated.getFirst(), dn.password, new Certificate[]{generated.getSecond()});
        FileOutputStream fos = new FileOutputStream(storeFile);
        boolean threw = true;
        try {
            ks.store(fos, storePassword);
            threw = false;
        } finally {
            Closeables.close(fos, threw);
        }
    } catch (KeyStoreException | IOException | NoSuchAlgorithmException | CertificateException | OperatorCreationException e) {
        return false;
    }
    return true;
}
 
Example #9
Source File: ApkUtils.java    From NBANDROID-V2 with Apache License 2.0 6 votes vote down vote up
public static boolean createNewStore(String storeType, File storeFile, char[] storePassword, DN dn) {
    if (storeType == null) {
        storeType = "jks";
    }
    try {
        KeyStore ks = KeyStore.getInstance(storeType);
        ks.load(null, null);
        Pair<PrivateKey, X509Certificate> generated = generateKeyAndCertificate("RSA", "SHA1withRSA", dn.validityYears, encodeDN(dn));
        ks.setKeyEntry(dn.alias, generated.getFirst(), dn.password, new Certificate[]{generated.getSecond()});
        FileOutputStream fos = new FileOutputStream(storeFile);
        boolean threw = true;
        try {
            ks.store(fos, storePassword);
            threw = false;
        } finally {
            Closeables.close(fos, threw);
        }
    } catch (KeyStoreException | IOException | NoSuchAlgorithmException | CertificateException | OperatorCreationException e) {
        return false;
    }
    return true;
}
 
Example #10
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 #11
Source File: LayoutlibVersionMixin.java    From java-n-IDE-for-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Parses an XML node to process the {@code <layoutlib>} element.
 *
 * The layoutlib element is new in the XSD rev 4, so we need to cope with it missing
 * in earlier XMLs.
 */
public LayoutlibVersionMixin(Node pkgNode) {

    int api = LAYOUTLIB_API_NOT_SPECIFIED;
    int rev = LAYOUTLIB_REV_NOT_SPECIFIED;

    Node layoutlibNode =
        PackageParserUtils.findChildElement(pkgNode, RepoConstants.NODE_LAYOUT_LIB);

    if (layoutlibNode != null) {
        api = PackageParserUtils.getXmlInt(layoutlibNode, RepoConstants.NODE_API, 0);
        rev = PackageParserUtils.getXmlInt(layoutlibNode, RepoConstants.NODE_REVISION, 0);
    }

    mLayoutlibVersion = Pair.of(api, rev);
}
 
Example #12
Source File: AndroidBuilder.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Collect the list of libraries' manifest files.
 *
 * @param libraries declared dependencies
 * @return a list of files and names for the libraries' manifest files.
 */
private static ImmutableList<Pair<String, File>> collectLibraries(
        List<? extends ManifestDependency> libraries) {

    ImmutableList.Builder<Pair<String, File>> manifestFiles = ImmutableList.builder();
    if (libraries != null) {
        collectLibraries(libraries, manifestFiles);
    }
    return manifestFiles.build();
}
 
Example #13
Source File: AndroidBuilder.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
/**
 * recursively calculate the list of libraries to merge the manifests files from.
 *
 * @param libraries     the dependencies
 * @param manifestFiles list of files and names identifiers for the libraries' manifest files.
 */
private static void collectLibraries(List<? extends ManifestDependency> libraries,
                                     ImmutableList.Builder<Pair<String, File>> manifestFiles) {

    for (ManifestDependency library : libraries) {
        manifestFiles.add(Pair.of(library.getName(), library.getManifest()));
        List<? extends ManifestDependency> manifestDependencies = library
                .getManifestDependencies();
        if (!manifestDependencies.isEmpty()) {
            collectLibraries(manifestDependencies, manifestFiles);
        }
    }
}
 
Example #14
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 #15
Source File: ExtractAnnotationsDriver.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
@NonNull
private static Pair<Collection<CompilationUnitDeclaration>, INameEnvironment> parseSources(
        @NonNull List<File> sourcePaths,
        @NonNull List<String> classpath,
        @NonNull String encoding,
        long languageLevel)
        throws IOException {
    List<ICompilationUnit> sourceUnits = Lists.newArrayListWithExpectedSize(100);

    for (File source : gatherJavaSources(sourcePaths)) {
        char[] contents = Util.getFileCharContent(source, encoding);
        ICompilationUnit unit = new CompilationUnit(contents, source.getPath(), encoding);
        sourceUnits.add(unit);
    }

    Map<ICompilationUnit, CompilationUnitDeclaration> outputMap = Maps.newHashMapWithExpectedSize(
            sourceUnits.size());

    CompilerOptions options = EcjParser.createCompilerOptions();
    options.docCommentSupport = true; // So I can find @hide

    // Note: We can *not* set options.ignoreMethodBodies=true because it disables
    // type attribution!

    options.sourceLevel = languageLevel;
    options.complianceLevel = options.sourceLevel;
    // We don't generate code, but just in case the parser consults this flag
    // and makes sure that it's not greater than the source level:
    options.targetJDK = options.sourceLevel;
    options.originalComplianceLevel = options.sourceLevel;
    options.originalSourceLevel = options.sourceLevel;
    options.inlineJsrBytecode = true; // >= 1.5

    INameEnvironment environment = EcjParser.parse(options, sourceUnits, classpath,
            outputMap, null);
    Collection<CompilationUnitDeclaration> parsedUnits = outputMap.values();
    return Pair.of(parsedUnits, environment);
}
 
Example #16
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 #17
Source File: LayoutlibVersionMixin.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Parses the layoutlib version optionally available in the given {@link Properties}.
 */
public LayoutlibVersionMixin(Properties props) {
    int layoutlibApi = Package.getPropertyInt(props, PkgProps.LAYOUTLIB_API,
                                                     LAYOUTLIB_API_NOT_SPECIFIED);
    int layoutlibRev = Package.getPropertyInt(props, PkgProps.LAYOUTLIB_REV,
                                                     LAYOUTLIB_REV_NOT_SPECIFIED);
    mLayoutlibVersion = Pair.of(layoutlibApi, layoutlibRev);
}
 
Example #18
Source File: XmlDocument.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Adds a new element of type nodeType with a specific keyValue if the element is absent in this
 * document. Will also add attributes expressed through key value pairs.
 *
 * @param actionRecorder to records creation actions.
 * @param nodeType the node type to crete
 * @param keyValue the optional key for the element.
 * @param attributes the optional array of key value pairs for extra element attribute.
 * @return the Xml element whether it was created or existed or {@link Optional#absent()} if
 * it does not exist in this document.
 */
private Optional<Element> addIfAbsent(
        @NonNull ActionRecorder actionRecorder,
        @NonNull ManifestModel.NodeTypes nodeType,
        @Nullable String keyValue,
        @Nullable String reason,
        @Nullable Pair<String, String>... attributes) {

    Optional<XmlElement> xmlElementOptional = getByTypeAndKey(nodeType, keyValue);
    if (xmlElementOptional.isPresent()) {
        return Optional.absent();
    }
    Element elementNS = getXml()
            .createElementNS(SdkConstants.ANDROID_URI, "android:" + nodeType.toXmlName());


    ImmutableList<String> keyAttributesNames = nodeType.getNodeKeyResolver()
            .getKeyAttributesNames();
    if (keyAttributesNames.size() == 1) {
        elementNS.setAttributeNS(
                SdkConstants.ANDROID_URI, "android:" + keyAttributesNames.get(0), keyValue);
    }
    if (attributes != null) {
        for (Pair<String, String> attribute : attributes) {
            elementNS.setAttributeNS(
                    SdkConstants.ANDROID_URI, "android:" + attribute.getFirst(),
                    attribute.getSecond());
        }
    }

    // record creation.
    XmlElement xmlElement = new XmlElement(elementNS, this);
    actionRecorder.recordImpliedNodeAction(xmlElement, reason);

    getRootNode().getXml().appendChild(elementNS);
    return Optional.of(elementNS);
}
 
Example #19
Source File: ManifestMerger2.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Add one library file manifest, will be added last in the list of library files which will
 * make the parameter the lowest priority library manifest file.
 * @param file the library manifest file to add.
 * @return itself.
 */
public Invoker addLibraryManifest(File file) {
    if (mMergeType == MergeType.LIBRARY) {
        throw new IllegalStateException(
                "Cannot add library dependencies manifests when creating a library");
    }
    mLibraryFilesBuilder.add(Pair.of(file.getName(), file));
    return thisAsT();
}
 
Example #20
Source File: ManifestMerger2.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
public Invoker addLibraryManifests(List<Pair<String, File>> namesAndFiles) {
    if (mMergeType == MergeType.LIBRARY && !namesAndFiles.isEmpty()) {
        throw new IllegalStateException(
                "Cannot add library dependencies manifests when creating a library");
    }
    mLibraryFilesBuilder.addAll(namesAndFiles);
    return thisAsT();
}
 
Example #21
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 #22
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 #23
Source File: SdkUpdaterNoWindow.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Installs a platform package given its target hash string.
 * <p/>
 * This does not work for add-ons right now, just basic platforms.
 *
 * @param hashString The hash string of the platform to install.
 * @return A boolean indicating whether the installation was successful (meaning the package
 *   was either already present, or got installed or updated properly) and a {@link File}
 *   with the path to the root folder of the package. The file is null when the boolean
 *   is false, otherwise it should point to an existing valid folder.
 */
public Pair<Boolean, File> installPlatformPackage(String hashString) {

    // TODO right now we really need the caller to use a reader-logger to
    // handle license confirmations. This isn't optimal and should be addressed
    // when we provide a proper UI for this.
    assert mSdkLog instanceof IReaderLogger;

    SdkManager sm = mUpdaterData.getSdkManager();
    IAndroidTarget target = sm.getTargetFromHashString(hashString);

    if (target == null) {
        // Otherwise try to install it.
        // This currently only works for platforms since the package's "install id"
        // is an exactly match with the IAndroidTarget hash string.
        ArrayList<String> filter = new ArrayList<String>();
        filter.add(hashString);
        List<Archive> installed = mUpdaterData.updateOrInstallAll_NoGUI(
                filter,
                true,  //includeAll
                false, //dryMode
                null); //acceptLicense

        if (installed != null) {
            sm.reloadSdk(new NullLogger());
            target = sm.getTargetFromHashString(hashString);
        }
    }

    if (target != null) {
        // Return existing target
        return Pair.of(Boolean.TRUE, new File(target.getLocation()));
    }

    return null;
}
 
Example #24
Source File: LayoutConsistencyDetector.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
@NonNull
private List<Pair<File, Map<String, String>>> getFileMapList(
        @NonNull XmlContext context) {
    String name = LintUtils.getLayoutName(context.file);
    List<Pair<File, Map<String, String>>> list = mMap.get(name);
    if (list == null) {
        list = Lists.newArrayListWithCapacity(4);
        mMap.put(name, list);
    }
    return list;
}
 
Example #25
Source File: LayoutConsistencyDetector.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void afterCheckProject(@NonNull Context context) {
    LintDriver driver = context.getDriver();
    if (driver.getPhase() == 1) {
        // First phase: gather all the ids and look for consistency issues.
        // If any are found, request location computation in phase 2 by
        // writing the ids needed for each layout in the {@link #mLocations} map.
        for (Map.Entry<String,List<Pair<File,Map<String,String>>>> entry : mMap.entrySet()) {
            String layout = entry.getKey();
            List<Pair<File, Map<String, String>>> files = entry.getValue();
            if (files.size() < 2) {
                // No consistency problems for files that don't have resource variations
                continue;
            }

            checkConsistentIds(layout, files);
        }

        if (mLocations != null) {
            driver.requestRepeat(this, Scope.ALL_RESOURCES_SCOPE);
        }
    } else {
        // Collect results and print
        if (!mLocations.isEmpty()) {
            reportErrors(context);
        }
    }
}
 
Example #26
Source File: DownloadCache.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Calls {@link UrlOpener#openUrl(String, boolean, ITaskMonitor, Header[])}
 * to actually perform a download.
 * <p/>
 * Isolated so that it can be overridden by unit tests.
 */
@VisibleForTesting(visibility=Visibility.PRIVATE)
@NonNull
protected Pair<InputStream, HttpResponse> openUrl(
        @NonNull String url,
        boolean needsMarkResetSupport,
        @NonNull ITaskMonitor monitor,
        @Nullable Header[] headers) throws IOException, CanceledByUserException {
    return UrlOpener.openUrl(url, needsMarkResetSupport, monitor, headers);
}
 
Example #27
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 #28
Source File: ObsoleteLayoutParamsDetector.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void visitElement(@NonNull XmlContext context, @NonNull Element element) {
    String layout = element.getAttribute(ATTR_LAYOUT);
    if (layout.startsWith(LAYOUT_RESOURCE_PREFIX)) { // Ignore @android:layout/ layouts
        layout = layout.substring(LAYOUT_RESOURCE_PREFIX.length());

        Node parent = element.getParentNode();
        if (parent.getNodeType() == Node.ELEMENT_NODE) {
            String tag = parent.getNodeName();
            if (tag.indexOf('.') == -1 && !tag.equals(VIEW_MERGE)) {
                if (!context.getProject().getReportIssues()) {
                    // If this is a library project not being analyzed, ignore it
                    return;
                }

                if (mIncludes == null) {
                    mIncludes = new HashMap<String, List<Pair<File, String>>>();
                }
                List<Pair<File, String>> includes = mIncludes.get(layout);
                if (includes == null) {
                    includes = new ArrayList<Pair<File, String>>();
                    mIncludes.put(layout, includes);
                }
                includes.add(Pair.of(context.file, tag));
            }
        }
    }
}
 
Example #29
Source File: ApiClass.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
static void addToArray(List<Pair<String, Integer>> list, String name, int value) {
    // check if we already have that name (at a lower level)
    for (Pair<String, Integer> pair : list) {
        if (name.equals(pair.getFirst())) {
            return;
        }
    }

    list.add(Pair.of(name, Integer.valueOf(value)));

}
 
Example #30
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);
        }
    }
}