com.android.builder.model.AndroidProject Java Examples

The following examples show how to use com.android.builder.model.AndroidProject. 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: AndroidSupport.java    From meghanada-server with GNU General Public License v3.0 6 votes vote down vote up
static AndroidProject getAndroidProject(
    final File root, final org.gradle.tooling.model.GradleProject gradleProject) {
  String path = gradleProject.getPath();
  String name = path.substring(1);
  File childDir = new File(root, name);
  GradleConnector childConnector = GradleConnector.newConnector().forProjectDirectory(childDir);
  try (ProjectConnection childConnection = childConnector.connect()) {
    ModelBuilder<AndroidProject> modelBuilder =
        childConnection
            .model(AndroidProject.class)
            .withArguments("-Pandroid.injected.build.model.only.versioned=3");
    if (nonNull(modelBuilder)) {
      return modelBuilder.get();
    }
    return null;
  } catch (Exception e) {
    log.debug("not android project", e);
    return null;
  }
}
 
Example #2
Source File: LintUtils.java    From javaide with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Returns true if the given Gradle model is older than the given version number
 */
public static boolean isModelOlderThan(@Nullable AndroidProject project,
        int major, int minor, int micro) {
    if (project != null) {
        String modelVersion = project.getModelVersion();
        try {
            FullRevision version = FullRevision.parseRevision(modelVersion);
            if (version.getMajor() != major) {
                return version.getMajor() < major;
            }
            if (version.getMinor() != minor) {
                return version.getMinor() < minor;
            }
            return version.getMicro() < micro;
        } catch (NumberFormatException e) {
            // ignore
        }
    }

    return false;
}
 
Example #3
Source File: LintUtils.java    From javaide with GNU General Public License v3.0 6 votes vote down vote up
/** Looks up the resource prefix for the given Gradle project, if possible */
@Nullable
public static String computeResourcePrefix(@Nullable AndroidProject project) {
    try {
        if (sTryPrefixLookup && project != null) {
            return project.getResourcePrefix();
        }
    } catch (Exception e) {
        // This happens if we're talking to an older model than 0.10
        // Ignore; fall through to normal handling and never try again.
        //noinspection AssignmentToStaticFieldFromInstanceMethod
        sTryPrefixLookup = false;
    }

    return null;
}
 
Example #4
Source File: LayoutMultiViewEditorElement.java    From NBANDROID-V2 with Apache License 2.0 6 votes vote down vote up
private void start() {
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            project = FileOwnerQuery.getOwner(dataObject.getPrimaryFile());
            lookupResultAndroidProject = project.getLookup().lookupResult(AndroidProject.class);
            lookupResulClassPathProvider = project.getLookup().lookupResult(AndroidClassPathProvider.class);
            lookupResulBuildVariant = project.getLookup().lookupResult(BuildVariant.class);
            lookupResultAndroidProject.addLookupListener(WeakListeners.create(LookupListener.class, LayoutMultiViewEditorElement.this, lookupResultAndroidProject));
            lookupResulClassPathProvider.addLookupListener(WeakListeners.create(LookupListener.class, LayoutMultiViewEditorElement.this, lookupResulClassPathProvider));
            lookupResulBuildVariant.addLookupListener(WeakListeners.create(LookupListener.class, LayoutMultiViewEditorElement.this, lookupResulBuildVariant));
            resultChanged(null);
        }
    };
    ProjectManager.mutex().postWriteRequest(runnable);
}
 
Example #5
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 #6
Source File: LayoutMultiViewEditorElement.java    From NBANDROID-V2 with Apache License 2.0 6 votes vote down vote up
@Override
public void resultChanged(LookupEvent ev) {
    Collection<? extends AndroidClassPathProvider> allInstances = lookupResulClassPathProvider.allInstances();
    Collection<? extends BuildVariant> allInstances1 = lookupResulBuildVariant.allInstances();
    Collection<? extends AndroidProject> allInstances2 = lookupResultAndroidProject.allInstances();
    if (!allInstances2.isEmpty() && !allInstances.isEmpty() && androidClassPathProvider == null && !allInstances1.isEmpty()) {
        AndroidProject androidProject = allInstances2.iterator().next();
        Collection<File> resDirectories = androidProject.getDefaultConfig().getSourceProvider().getResDirectories();
        resFolderFile = resDirectories.iterator().next();
        androidClassPathProvider = allInstances.iterator().next();
        classPath = androidClassPathProvider.getCompilePath();
        classPath.addPropertyChangeListener(WeakListeners.create(PropertyChangeListener.class, this, classPath));
        roots = classPath.getRoots();
        buildVariant = allInstances1.iterator().next();
        loader = new Loader();
        buildVariant.addChangeListener(WeakListeners.change(loader, buildVariant));
        loader.stateChanged(null);
    }
}
 
Example #7
Source File: LintGradleRequest.java    From javaide with GNU General Public License v3.0 6 votes vote down vote up
private static Variant findVariant(@NonNull AndroidProject project,
                                   @Nullable String variantName) {
    if (variantName != null) {
        for (Variant variant : project.getVariants()) {
            if (variantName.equals(variant.getName())) {
                return variant;
            }
        }
    }

    if (!project.getVariants().isEmpty()) {
        return project.getVariants().iterator().next();
    }

    return null;
}
 
Example #8
Source File: MainActivityConfigurationPanel.java    From NBANDROID-V2 with Apache License 2.0 6 votes vote down vote up
@Override
public void resultChanged(LookupEvent ev) {
    Collection<? extends AndroidProject> allInstances = lookupResult.allInstances();
    if(!allInstances.isEmpty()){
        AndroidProject androidProject = allInstances.iterator().next();
        File manifestFile = androidProject.getDefaultConfig().getSourceProvider().getManifestFile();
        try {
            ManifestData manifest = AndroidProjects.parseProjectManifest(new FileInputStream(manifestFile));
            ManifestData.Activity[] activities = manifest.getActivities();
            Vector<String> tmp = new Vector<>();
            for (ManifestData.Activity activitie : activities) {
                tmp.add(activitie.getName());
            }
            customMainActivity.setModel(new DefaultComboBoxModel<>(tmp));
            customMainActivity.setSelectedItem(activityConfiguration.getMainActivity());
    } catch (Exception ex) {
            Exceptions.printStackTrace(ex);
            customMainActivity.setModel(new DefaultComboBoxModel<>());
    }
    }
}
 
Example #9
Source File: TranslationDetector.java    From javaide with GNU General Public License v3.0 6 votes vote down vote up
@Nullable
private static List<String> getResConfigLanguages(@NonNull Project project) {
    if (project.isGradleProject() && project.getGradleProjectModel() != null &&
            project.getCurrentVariant() != null) {
        Set<String> relevantDensities = Sets.newHashSet();
        Variant variant = project.getCurrentVariant();
        List<String> variantFlavors = variant.getProductFlavors();
        AndroidProject gradleProjectModel = project.getGradleProjectModel();

        addResConfigsFromFlavor(relevantDensities, null,
                project.getGradleProjectModel().getDefaultConfig());
        for (ProductFlavorContainer container : gradleProjectModel.getProductFlavors()) {
            addResConfigsFromFlavor(relevantDensities, variantFlavors, container);
        }
        if (!relevantDensities.isEmpty()) {
            ArrayList<String> strings = Lists.newArrayList(relevantDensities);
            Collections.sort(strings);
            return strings;
        }
    }

    return null;
}
 
Example #10
Source File: ManifestDetector.java    From javaide with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Returns true iff the given manifest file is in a debug-specific source set,
 * or a test source set
 */
private static boolean isDebugOrTestManifest(
        @NonNull XmlContext context,
        @NonNull File manifestFile) {
    AndroidProject model = context.getProject().getGradleProjectModel();
    if (model != null) {
        // Quickly check if it's the main manifest first; that's the most likely scenario
        if (manifestFile.equals(model.getDefaultConfig().getSourceProvider().getManifestFile())) {
            return false;
        }

        // Debug build type?
        for (BuildTypeContainer container : model.getBuildTypes()) {
            if (container.getBuildType().isDebuggable()) {
                if (manifestFile.equals(container.getSourceProvider().getManifestFile())) {
                    return true;
                }
            }
        }
    }

    return false;
}
 
Example #11
Source File: PropertyFileDetectorTest.java    From javaide with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected TestLintClient createClient() {
    return new TestLintClient() {
        @NonNull
        @Override
        protected Project createProject(@NonNull File dir, @NonNull File referenceDir) {
            return new Project(this, dir, referenceDir) {
                @Override
                public boolean isGradleProject() {
                    return true;
                }

                @Nullable
                @Override
                public AndroidProject getGradleProjectModel() {
                    AndroidProject project = mock(AndroidProject.class);
                    when(project.getResourcePrefix()).thenReturn("unit_test_prefix_");
                    return project;
                }
            };
        }
    };
}
 
Example #12
Source File: ApkUtils.java    From NBANDROID-V2 with Apache License 2.0 6 votes vote down vote up
public static void gradleSignApk(Project project, String displayName, List<String> tasks, KeystoreConfiguration keystoreConfiguration, File out) {

        GradleCommandTemplate.Builder builder = new GradleCommandTemplate.Builder(
                displayName != null ? displayName : "", tasks);
        List<String> arguments = new ArrayList<>();
        arguments.add(createArgument(AndroidProject.PROPERTY_SIGNING_STORE_FILE, keystoreConfiguration.getCurrentKeystoreConfiguration().getKeystorePath()));
        arguments.add(createArgument(AndroidProject.PROPERTY_SIGNING_STORE_PASSWORD, keystoreConfiguration.getCurrentKeystoreConfiguration().getKeystorePassword()));
        arguments.add(createArgument(AndroidProject.PROPERTY_SIGNING_KEY_ALIAS, keystoreConfiguration.getCurrentKeystoreConfiguration().getKeyAlias()));
        arguments.add(createArgument(AndroidProject.PROPERTY_SIGNING_KEY_PASSWORD, keystoreConfiguration.getCurrentKeystoreConfiguration().getKeyPassword()));
        arguments.add(createArgument(AndroidProject.PROPERTY_APK_LOCATION, out.getAbsolutePath()));

        // These were introduced in 2.3, but gradle doesn't care if it doesn't know the properties and so they don't affect older versions.
        arguments.add(createArgument(AndroidProject.PROPERTY_SIGNING_V1_ENABLED, Boolean.toString(keystoreConfiguration.getCurrentKeystoreConfiguration().isApkV1())));
        arguments.add(createArgument(AndroidProject.PROPERTY_SIGNING_V2_ENABLED, Boolean.toString(keystoreConfiguration.getCurrentKeystoreConfiguration().isApkV2())));

        builder.setArguments(arguments);
        builder.setJvmArguments(Collections.EMPTY_LIST);
        executeCommandTemplate(project, builder.create());
    }
 
Example #13
Source File: ResourcePrefixDetectorTest.java    From javaide with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected TestLintClient createClient() {
    return new TestLintClient() {
        @NonNull
        @Override
        protected Project createProject(@NonNull File dir, @NonNull File referenceDir) {
            return new Project(this, dir, referenceDir) {
                @Override
                public boolean isGradleProject() {
                    return true;
                }

                @Nullable
                @Override
                public AndroidProject getGradleProjectModel() {
                    AndroidProject project = mock(AndroidProject.class);
                    when(project.getResourcePrefix()).thenReturn("unit_test_prefix_");
                    return project;
                }
            };
        }
    };
}
 
Example #14
Source File: InjectTransformManager.java    From atlas with Apache License 2.0 6 votes vote down vote up
/**
 * Get the task outputStream
 *
 * @param injectTransform
 * @param scope
 * @param taskName
 * @param <T>
 * @return
 */
@NotNull
private <T extends Transform> IntermediateStream getOutputStream(T injectTransform,
                                                                 @NonNull VariantScope scope,
                                                                 String taskName) {
    File outRootFolder = FileUtils.join(project.getBuildDir(),
                                        StringHelper.toStrings(AndroidProject.FD_INTERMEDIATES,
                                                               FD_TRANSFORMS,
                                                               injectTransform.getName(),
                                                               scope.getDirectorySegments()));

    Set<? super Scope> requestedScopes = injectTransform.getScopes();

    // create the output
    return IntermediateStream.builder(project,injectTransform.getName())
            .addContentTypes(injectTransform.getOutputTypes())
            .addScopes(requestedScopes)
            .setTaskName(taskName)
            .setRootLocation(outRootFolder).build();

}
 
Example #15
Source File: AndroidClassPathProvider.java    From NBANDROID-V2 with Apache License 2.0 6 votes vote down vote up
public AndroidClassPathProvider(BuildVariant buildConfig, Project project) {
    this.buildConfig = Preconditions.checkNotNull(buildConfig);
    this.project = project;
    lookupResultProjectModel = project.getLookup().lookupResult(AndroidProject.class);
    lookupResultProjectModel.addLookupListener(WeakListeners.create(LookupListener.class, this, lookupResultProjectModel));
    buildConfig.addChangeListener(WeakListeners.change(this, buildConfig));
    source = createSource();
    test = createTest();
    compile = createCompile();
    boot = createBoot();
    execute = createExecute(compile);
    testCompile = createTestCompile(execute);
    register();
    resultChanged(null);

}
 
Example #16
Source File: ResourceVisibilityLookup.java    From javaide with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Looks up a (possibly cached) {@link ResourceVisibilityLookup} for the given {@link
 * AndroidArtifact}
 *
 * @param project the project
 * @return the corresponding {@link ResourceVisibilityLookup}
 */
@NonNull
public ResourceVisibilityLookup get(
        @NonNull AndroidProject project,
        @NonNull Variant variant) {
    ResourceVisibilityLookup visibility = mInstances.get(variant);
    if (visibility == null) {
        if (isVisibilityAwareModel(project)) {
            AndroidArtifact artifact = variant.getMainArtifact();
            visibility = get(artifact);
        } else {
            visibility = NONE;
        }
        mInstances.put(variant, visibility);
    }
    return visibility;
}
 
Example #17
Source File: ReleaseUnsignedApkAction.java    From NBANDROID-V2 with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean enable(Node[] activatedNodes) {
    if (activatedNodes.length != 1) {
        return false;
    }
    Project owner = activatedNodes[0].getLookup().lookup(Project.class);
    return owner != null && owner.getLookup().lookup(AndroidProject.class) != null;
}
 
Example #18
Source File: GradleProject.java    From meghanada-server with GNU General Public License v3.0 5 votes vote down vote up
private void parseIdeaModule(final IdeaModule ideaModule) throws IOException {
  final org.gradle.tooling.model.GradleProject gradleProject = ideaModule.getGradleProject();
  String name = convertName(gradleProject.getPath());
  if (nonNull(name) && !name.isEmpty()) {
    this.name = name;
  }
  final AndroidProject androidProject =
      AndroidSupport.getAndroidProject(this.rootProject, gradleProject);
  if (nonNull(androidProject)) {
    Set<ProjectDependency> projectDependencies = analyzeDependencies(ideaModule);
    this.dependencies.addAll(projectDependencies);
    // parse android
    this.isAndroidProject = true;
    this.androidApiVersion = androidProject.getApiVersion();
    this.androidModelVersion = androidProject.getModelVersion();
    log.info(
        "detect android project {}. api {} model {}",
        name,
        androidApiVersion,
        androidModelVersion);
    System.setProperty("meghanada.android.project", "true");
    System.setProperty("meghanada.android.project.name", name);
    final AndroidSupport androidSupport = new AndroidSupport(this);
    androidSupport.parseAndroidProject(androidProject);
  } else {
    // normal
    this.parseIdeaModule(gradleProject, ideaModule);
  }
}
 
Example #19
Source File: AndroidSources.java    From NBANDROID-V2 with Apache License 2.0 5 votes vote down vote up
public AndroidSources(Project project, BuildVariant buildConfig) {
    this.project = project;
    this.buildConfig = buildConfig;
    buildConfig.addChangeListener(WeakListeners.change(this, buildConfig));
    lookupResult = project.getLookup().lookupResult(AndroidProject.class);
    lookupResult.addLookupListener(WeakListeners.create(LookupListener.class, this, lookupResult));
    resultChanged(null);
}
 
Example #20
Source File: SourceLevelQueryImpl.java    From NBANDROID-V2 with Apache License 2.0 5 votes vote down vote up
@Override
public void resultChanged(LookupEvent ev) {
    Collection<? extends AndroidProject> allInstances = lookupResult.allInstances();
    if (!allInstances.isEmpty()) {
        androidProject.set(allInstances.iterator().next());
    }
    changeSupport.fireChange();
}
 
Example #21
Source File: AndroidSources.java    From NBANDROID-V2 with Apache License 2.0 5 votes vote down vote up
@Override
public void resultChanged(LookupEvent ev) {
    Collection<? extends AndroidProject> allInstances = lookupResult.allInstances();
    if (!allInstances.isEmpty()) {
        androidProjectModel = allInstances.iterator().next();
    } else {
        androidProjectModel = null;
    }
    cs.fireChange();
}
 
Example #22
Source File: BuildVariant.java    From NBANDROID-V2 with Apache License 2.0 5 votes vote down vote up
@Override
public void resultChanged(LookupEvent ev) {
    Collection<? extends AndroidProject> allInstances = lookupResult.allInstances();
    if (!allInstances.isEmpty()) {
        androidProjectModel = allInstances.iterator().next();
        cs.fireChange();
    }
}
 
Example #23
Source File: GradleAndroidManifest.java    From NBANDROID-V2 with Apache License 2.0 5 votes vote down vote up
@Override
public void resultChanged(LookupEvent ev) {
    Collection<? extends AndroidProject> allInstances = lookupResult.allInstances();
    if (!allInstances.isEmpty()) {
        androidProjectModel = allInstances.iterator().next();
        cs.fireChange();
    } else {
        androidProjectModel = null;
    }
}
 
Example #24
Source File: AndroidTestRunConfiguration.java    From NBANDROID-V2 with Apache License 2.0 5 votes vote down vote up
public AndroidTestRunConfiguration(NbAndroidProject project) {
    this.auxProps = project.getAuxiliaryProperties();
    testRunner = auxProps.get(PREFERENCE_TEST_RUNNER, false);
    lookupResult = project.getLookup().lookupResult(AndroidProject.class);
    lookupResult.addLookupListener(WeakListeners.create(LookupListener.class, this, lookupResult));
    resultChanged(null);
    LOG.log(Level.FINE, "loaded test runner {0}", testRunner);
}
 
Example #25
Source File: AndroidTestRunConfiguration.java    From NBANDROID-V2 with Apache License 2.0 5 votes vote down vote up
@Override
public void resultChanged(LookupEvent ev) {
    Collection<? extends AndroidProject> allInstances = lookupResult.allInstances();
    if (!allInstances.isEmpty()) {
        String runner = allInstances.iterator().next().getDefaultConfig().getProductFlavor().getTestInstrumentationRunner();
        if (runner == null) {
            return;
        }
        setDefaultTestRunner(runner);
        fireChange();
    }
}
 
Example #26
Source File: DebugApkAction.java    From NBANDROID-V2 with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean enable(Node[] activatedNodes) {
    if (activatedNodes.length != 1) {
        return false;
    }
    Project owner = activatedNodes[0].getLookup().lookup(Project.class);
    return owner != null && owner.getLookup().lookup(AndroidProject.class) != null;
}
 
Example #27
Source File: AndroidClassPathProvider.java    From NBANDROID-V2 with Apache License 2.0 5 votes vote down vote up
@Override
public void resultChanged(LookupEvent ev) {
    Collection<? extends AndroidProject> allInstances = lookupResultProjectModel.allInstances();
    if (!allInstances.isEmpty()) {
        gradleBuildModel = project.getLookup().lookup(GradleBuild.class);
        androidProjectModel = allInstances.iterator().next();
        if (buildConfig.getCurrentVariant() != null) {
            update();
        }
    }
}
 
Example #28
Source File: GradlePlatformResolver.java    From NBANDROID-V2 with Apache License 2.0 5 votes vote down vote up
@Override
public AndroidPlatformInfo findAndroidPlatform(Project project) {
    AndroidProject aPrj = project.getLookup().lookup(AndroidProject.class);
    AndroidSdk sdk = project.getLookup().lookup(AndroidSdk.class);
    if (aPrj == null || sdk == null) {
        return null;
    }
    LOG.log(Level.FINE, "look for dalvik platform for {0}", aPrj.getCompileTarget());
    return sdk.findPlatformForTarget(aPrj.getCompileTarget());
}
 
Example #29
Source File: GradleSourceForBinaryQuery.java    From NBANDROID-V2 with Apache License 2.0 5 votes vote down vote up
@Override
public void resultChanged(LookupEvent ev) {
    Collection<? extends AndroidProject> allInstances = lookupResult.allInstances();
    if (!allInstances.isEmpty()) {
        androidProjectModel = allInstances.iterator().next();
    } else {
        androidProjectModel = null;
    }
    cs.fireChange();
}
 
Example #30
Source File: BuildVariant.java    From NBANDROID-V2 with Apache License 2.0 5 votes vote down vote up
public BuildVariant(NbAndroidProject androidProject) {
    this.auxProps = androidProject.getAuxiliaryProperties();
    variant = auxProps.get(PREFERENCE_BUILD_VARIANT, false);
    lookupResult = androidProject.getLookup().lookupResult(AndroidProject.class);
    lookupResult.addLookupListener(WeakListeners.create(LookupListener.class, this, androidProject));
    resultChanged(null);
}