Java Code Examples for com.android.utils.Pair

The following examples show how to use com.android.utils.Pair. 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
/**
 * 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 Project: java-n-IDE-for-Android   Source File: ManifestMerger2.java    License: 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 3
Source Project: javaide   Source File: LintGradleProject.java    License: 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 4
Source Project: javaide   Source File: LintGradleRequest.java    License: 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 5
Source Project: javaide   Source File: ManifestMerger2.java    License: 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 6
@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 7
Source Project: javaide   Source File: StringFormatDetector.java    License: 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
@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 9
/**
 * 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 10
Source Project: NBANDROID-V2   Source File: ApkUtils.java    License: 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 11
Source Project: NBANDROID-V2   Source File: ApkUtils.java    License: 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 12
/**
 * 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 13
Source Project: java-n-IDE-for-Android   Source File: SdkUpdaterNoWindow.java    License: Apache License 2.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 14
Source Project: java-n-IDE-for-Android   Source File: DownloadCache.java    License: Apache License 2.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 15
Source Project: java-n-IDE-for-Android   Source File: LocalSdkParser.java    License: 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 16
Source Project: java-n-IDE-for-Android   Source File: XmlDocument.java    License: Apache License 2.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 17
Source Project: java-n-IDE-for-Android   Source File: ManifestMerger2.java    License: Apache License 2.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 18
Source Project: java-n-IDE-for-Android   Source File: ManifestMerger2.java    License: Apache License 2.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 19
Source Project: logviewer   Source File: ClientCellRenderer.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Render the given {@link LogProcess} object
 */
private void renderClient(@NotNull LogProcess c, ColoredTextContainer container) {
    String name = c.getProcessName();
    if (name != null) {
        Pair<String, String> app = splitApplicationName(name);
        container.append(app.getFirst(), SimpleTextAttributes.REGULAR_ATTRIBUTES);
        container.append(app.getSecond(), SimpleTextAttributes.REGULAR_BOLD_ATTRIBUTES);

        if (c.getProcessID() != 0) {
            container.append(String.format(" (%1$d)", c.getProcessID()), SimpleTextAttributes.GRAY_ATTRIBUTES);
        }
    }
}
 
Example 20
Source Project: logviewer   Source File: ClientCellRenderer.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Split the name if possible as package and app name
 */
private Pair<String, String> splitApplicationName(String name) {
    int index = name.lastIndexOf('.');
    if (index != -1) {
        return Pair.of(name.substring(0, index + 1), name.substring(index + 1));
    } else {
        return Pair.of("", name);
    }
}
 
Example 21
Source Project: javaide   Source File: GroovyGradleDetector.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
protected Location createLocation(@NonNull Context context, @NonNull Object cookie) {
    ASTNode node = (ASTNode) cookie;
    Pair<Integer, Integer> offsets = getOffsets(node, context);
    int fromLine = node.getLineNumber() - 1;
    int fromColumn = node.getColumnNumber() - 1;
    int toLine = node.getLastLineNumber() - 1;
    int toColumn = node.getLastColumnNumber() - 1;
    return Location.create(context.file,
            new DefaultPosition(fromLine, fromColumn, offsets.getFirst()),
            new DefaultPosition(toLine, toColumn, offsets.getSecond()));
}
 
Example 22
@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 23
Source Project: javaide   Source File: XmlDocument.java    License: 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 24
Source Project: javaide   Source File: ManifestMerger2.java    License: 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 25
Source Project: javaide   Source File: ManifestMerger2.java    License: 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 26
Source Project: javaide   Source File: OverdrawDetector.java    License: 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 27
Source Project: javaide   Source File: ApiDetector.java    License: 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 28
@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 29
@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 30
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;
}