All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.sealights.onpremise.agents.plugin.ProjectDataCollector Maven / Gradle / Ivy

There is a newer version: 4.0.954
Show newest version
package io.sealights.onpremise.agents.plugin;

import io.sealights.onpremise.agents.infra.utils.StringUtils;
import io.sealights.plugins.engine.api.DependencyInfo;
import io.sealights.plugins.engine.api.ProjectDescriptor;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.artifacts.Configuration;
import org.gradle.api.artifacts.ConfigurationContainer;
import org.gradle.api.artifacts.ModuleVersionIdentifier;
import org.gradle.api.artifacts.ResolvedArtifact;
import org.gradle.api.plugins.JavaPlugin;
import org.gradle.api.plugins.JavaPluginConvention;
import org.gradle.api.tasks.SourceSet;

import java.util.*;

public class ProjectDataCollector {

    private final static String SEALIGHTS_GRADLE_PLUGIN = "sealights-gradle-plugin";
    private final static String COMPILE_CONFIG = "compile";

    private SealightsPluginExtension sealightsExtension;
    private Project rootProject;
    private Project project;

    public static ProjectDescriptor execute(SealightsPluginExtension sealightsExtension) {
    		ProjectDataCollector instance = new ProjectDataCollector(sealightsExtension);
    		return instance.collectProjectData();
    }

    public static String resolvePluginVersion() {
        String packageVersion = ProjectDataCollector.class.getPackage().getImplementationVersion();
        return packageVersion != null ? packageVersion : "[-]";
    }

    private ProjectDataCollector(SealightsPluginExtension sealightsExtension) {
        this.sealightsExtension = sealightsExtension;
        this.rootProject = sealightsExtension.getProject().getRootProject();
        this.project = sealightsExtension.getProject();
    }

    private ProjectDescriptor collectProjectData() {
    	try {
	        return new ProjectDescriptor(
	                SEALIGHTS_GRADLE_PLUGIN,
	                resolvePluginVersion(),
	                project.getName(),
	                rootProject.getVersion().toString(),
	                collectProperties(),
	                resolveBaseSourceDir(),
	                project.getProjectDir().getAbsolutePath(),
	                project.getBuildDir().getAbsolutePath(),
	                collectDependenciesData(),
	                collectPluginsData());
    	}
    	catch(Exception e) {
    		// Catch any null pointer exception instead of checking each getMethod 
    		return new ProjectDescriptor();
    	}
    }
    
    private Properties collectProperties() {
        Properties destProps = new Properties();
        // This is too much ...
//        Map projectProps = project.getProperties();
//        for (String key : projectProps.keySet()) {
//            Object value = projectProps.get(key);
//            if (value != null) {
//                destProps.setProperty(key, value.toString());
//            }
//        }
        return destProps;
    }

    private List collectDependenciesData(){
        Set dependencies = new HashSet<>();
        for (Project subproject : rootProject.getAllprojects()){
            dependencies.addAll(collectProjectDependencies(subproject));
        }
        List dependenciesAsList = new ArrayList<>();
        dependenciesAsList.addAll(dependencies);
        return dependenciesAsList;
    }

    private Set collectProjectDependencies(Project project) {
        Set projectDependencies = new HashSet<>();
        List collectedConfigs = new ArrayList<>();
        try {
            ConfigurationContainer allConfigs = project.getConfigurations();
            for (String configName : allConfigs.getNames()) {
                if (isRelevantConfiguration(configName)) {
                    Configuration config = allConfigs.getByName(configName);
                    if (config != null && config.getResolvedConfiguration() != null) {
                        collectedConfigs.add(configName);
                        artifactsToDependencies(config.getResolvedConfiguration().getResolvedArtifacts(), projectDependencies);
                    }
                }
            }
        }
        catch(Throwable e) {
            // Exception is thrown if a configuration is not found
            sealightsExtension.getLogger().error("Failed to collect dependencies info, error:{}", e.getMessage());
        }
        if (!projectDependencies.isEmpty()) {
            sealightsExtension.getLogger().info("Project '{}': {} dependencies collected from configurations :{}",
                    project.getName(), projectDependencies.size(), collectedConfigs);
        }
        return projectDependencies;
    }

    private boolean isRelevantConfiguration(String configName) {
        String lowerCaseName = configName.toLowerCase();
        return lowerCaseName.contains(COMPILE_CONFIG);
    }

    private void artifactsToDependencies(Set artifacts, Set dependenciesData) {
        if (artifacts != null) {
            for (ResolvedArtifact a : artifacts) {
                DependencyInfo dependencyInfo = artifactAsDependecyInfo(a);
                if (dependencyInfo != null) {
                    dependenciesData.add(dependencyInfo);
                }
            }
        }
    }

    private DependencyInfo artifactAsDependecyInfo(ResolvedArtifact artifact) {
        if (artifact.getModuleVersion() != null && artifact.getModuleVersion().getId() != null ) {
            // Artifact may have either module version or module version id 'null'
            // Put dependencies of "good" artifacts only
            ModuleVersionIdentifier moduleVersion =  artifact.getModuleVersion().getId();

            return new DependencyInfo(
                            notNullValue(moduleVersion.getGroup()),
                            notNullValue(moduleVersion.getName()),
                            notNullValue(moduleVersion.getVersion()));
        }
        else {
        	return null;
        }
    }

    private String notNullValue(String value) {
        return value != null ? value : StringUtils.EMPTY_STRING;
    }

    private List collectPluginsData() {
        List pluginsData = new ArrayList<>();
        for (Plugin p: rootProject.getPlugins()) {
            pluginsData.add(new DependencyInfo("[-]", p.getClass().getSimpleName(), "[-]"));
        }
        return pluginsData;
    }

    private String resolveBaseSourceDir() {
    	String defaultSrcDir = rootProject.getPath();
    	try {
    		boolean javaPlugin = rootProject.getPlugins().hasPlugin(JavaPlugin.class); 
    		if (javaPlugin ) {
    			   JavaPluginConvention javaPluginConvention = rootProject.getConvention().getPlugin(JavaPluginConvention.class); 
    			   SourceSet main = javaPluginConvention.getSourceSets().getByName(SourceSet.MAIN_SOURCE_SET_NAME); 
    			   return main.getOutput().getAsPath();
    		} 
    	}
    	catch(Exception e) {
    		// Catch any null pointer exception instead of checking each getMethod
    	}
    	return defaultSrcDir;
    }	

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy