org.gradle.tooling.GradleConnector Java Examples

The following examples show how to use org.gradle.tooling.GradleConnector. 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: GradleBuildFileFromConnector.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@Override
public List<Dependency> getDependencies() throws IOException {
    if (dependencies == null) {
        EclipseProject eclipseProject = null;
        if (getBuildContent() != null) {
            try {
                ProjectConnection connection = GradleConnector.newConnector()
                        .forProjectDirectory(getProjectDirPath().toFile())
                        .connect();
                eclipseProject = connection.getModel(EclipseProject.class);
            } catch (BuildException e) {
                // ignore this error.
                e.printStackTrace();
            }
        }
        if (eclipseProject != null) {
            dependencies = eclipseProject.getClasspath().stream().map(this::gradleModuleVersionToDependency)
                    .filter(Objects::nonNull)
                    .collect(Collectors.toList());
        } else {
            dependencies = Collections.emptyList();
        }
        dependencies = Collections.unmodifiableList(dependencies);
    }
    return dependencies;
}
 
Example #2
Source File: GradleBuildComparison.java    From pushfish-android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private ProjectConnection createProjectConnection(ComparableGradleBuildExecuter executer) {
    GradleConnector connector = GradleConnector.newConnector();
    connector.forProjectDirectory(executer.getSpec().getProjectDir());
    File gradleUserHomeDir = gradle.getStartParameter().getGradleUserHomeDir();
    if (gradleUserHomeDir != null) {
        connector.useGradleUserHomeDir(gradleUserHomeDir);
    }

    GradleVersion gradleVersion = executer.getGradleVersion();
    if (gradleVersion.equals(GradleVersion.current())) {
        connector.useInstallation(gradle.getGradleHomeDir());
    } else {
        connector.useGradleVersion(gradleVersion.getVersion());
    }

    return connector.connect();
}
 
Example #3
Source File: GradleDaemon.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static void doLoadDaemon() {
    GradleConnector gconn = GradleConnector.newConnector();
    ProjectConnection pconn = gconn.forProjectDirectory(LOADER_PROJECT_DIR).connect();
    BuildActionExecuter<String> action = pconn.action(DUMMY_ACTION);
    GradleCommandLine cmd = new GradleCommandLine();
    cmd.addSystemProperty(PROP_TOOLING_JAR, TOOLING_JAR);
    cmd.setFlag(GradleCommandLine.Flag.OFFLINE, true);
    cmd.addParameter(GradleCommandLine.Parameter.INIT_SCRIPT, INIT_SCRIPT);
    cmd.configure(action);
    try {
        action.run();
    } catch (GradleConnectionException | IllegalStateException ex) {
        // Well for some reason we were  not able to load Gradle.
        // Ignoring that for now
    } finally {
        pconn.close();
    }
}
 
Example #4
Source File: GradleBuildComparison.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private ProjectConnection createProjectConnection(ComparableGradleBuildExecuter executer) {
    GradleConnector connector = GradleConnector.newConnector();
    connector.forProjectDirectory(executer.getSpec().getProjectDir());
    File gradleUserHomeDir = gradle.getStartParameter().getGradleUserHomeDir();
    if (gradleUserHomeDir != null) {
        connector.useGradleUserHomeDir(gradleUserHomeDir);
    }

    GradleVersion gradleVersion = executer.getGradleVersion();
    if (gradleVersion.equals(GradleVersion.current())) {
        connector.useInstallation(gradle.getGradleHomeDir());
    } else {
        connector.useGradleVersion(gradleVersion.getVersion());
    }

    return connector.connect();
}
 
Example #5
Source File: GradleProjectCache.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Messages({
    "# {0} - The project name",
    "LBL_Loading=Loading {0}"
})
@Override
public GradleProject call() throws Exception {
    tokenSource = GradleConnector.newCancellationTokenSource();
    final ProgressHandle handle = ProgressHandle.createHandle(Bundle.LBL_Loading(ctx.previous.getBaseProject().getName()), this);
    ProgressListener pl = (ProgressEvent pe) -> {
        handle.progress(pe.getDescription());
    };
    handle.start();
    try {
        return loadGradleProject(ctx, tokenSource.token(), pl);
    } catch (Throwable ex) {
        LOG.log(WARNING, ex.getMessage(), ex);
        throw ex;
    } finally {
        handle.finish();
    }
}
 
Example #6
Source File: GradleBuildComparison.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private ProjectConnection createProjectConnection(ComparableGradleBuildExecuter executer) {
    GradleConnector connector = GradleConnector.newConnector();
    connector.forProjectDirectory(executer.getSpec().getProjectDir());
    File gradleUserHomeDir = gradle.getStartParameter().getGradleUserHomeDir();
    if (gradleUserHomeDir != null) {
        connector.useGradleUserHomeDir(gradleUserHomeDir);
    }

    GradleVersion gradleVersion = executer.getGradleVersion();
    if (gradleVersion.equals(GradleVersion.current())) {
        connector.useInstallation(gradle.getGradleHomeDir());
    } else {
        connector.useGradleVersion(gradleVersion.getVersion());
    }

    return connector.connect();
}
 
Example #7
Source File: GradleProject.java    From meghanada-server with GNU General Public License v3.0 6 votes vote down vote up
ProjectConnection getProjectConnection() {
  final String gradleVersion = Config.load().getGradleVersion();
  GradleConnector connector;
  if (gradleVersion.isEmpty()) {
    connector = GradleConnector.newConnector().forProjectDirectory(this.rootProject);
  } else {
    log.debug("use gradle version:'{}'", gradleVersion);
    connector =
        GradleConnector.newConnector()
            .useGradleVersion(gradleVersion)
            .forProjectDirectory(this.rootProject);
  }

  if (connector instanceof DefaultGradleConnector) {
    final DefaultGradleConnector defaultGradleConnector = (DefaultGradleConnector) connector;
    defaultGradleConnector.daemonMaxIdleTime(1, TimeUnit.HOURS);
  }
  return connector.connect();
}
 
Example #8
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 #9
Source File: GradleBuildComparison.java    From pushfish-android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private ProjectConnection createProjectConnection(ComparableGradleBuildExecuter executer) {
    GradleConnector connector = GradleConnector.newConnector();
    connector.forProjectDirectory(executer.getSpec().getProjectDir());
    File gradleUserHomeDir = gradle.getStartParameter().getGradleUserHomeDir();
    if (gradleUserHomeDir != null) {
        connector.useGradleUserHomeDir(gradleUserHomeDir);
    }

    GradleVersion gradleVersion = executer.getGradleVersion();
    if (gradleVersion.equals(GradleVersion.current())) {
        connector.useInstallation(gradle.getGradleHomeDir());
    } else {
        connector.useGradleVersion(gradleVersion.getVersion());
    }

    return connector.connect();
}
 
Example #10
Source File: ToolingApiProjectGenerator.java    From gradle-initializr with Apache License 2.0 6 votes vote down vote up
@Override
public void generate(File targetDir, ProjectRequest projectRequest) {
    GradleConnector gradleConnector = GradleConnector.newConnector().forProjectDirectory(targetDir);

    if (projectRequest.getGradleVersion() != null) {
        gradleConnector.useGradleVersion(projectRequest.getGradleVersion());
    }

    ProjectConnection connection = gradleConnector.connect();

    try {
        connection.newBuild().forTasks(buildTasks(projectRequest)).run();
    } finally {
        connection.close();
    }
}
 
Example #11
Source File: Main.java    From pushfish-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static void main(String[] args) {
    // Configure the connector and create the connection
    GradleConnector connector = GradleConnector.newConnector();

    if (args.length > 0) {
        connector.useInstallation(new File(args[0]));
        if (args.length > 1) {
            connector.useGradleUserHomeDir(new File(args[1]));
        }
    }

    connector.forProjectDirectory(new File("."));

    ProjectConnection connection = connector.connect();
    try {
        // Configure the build
        BuildLauncher launcher = connection.newBuild();
        launcher.forTasks("help");
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        launcher.setStandardOutput(outputStream);
        launcher.setStandardError(outputStream);

        // Run the build
        launcher.run();
    } finally {
        // Clean up
        connection.close();
    }
}
 
Example #12
Source File: Main.java    From pushfish-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static void main(String[] args) {
    // Configure the connector and create the connection
    GradleConnector connector = GradleConnector.newConnector();

    if (args.length > 0) {
        connector.useInstallation(new File(args[0]));
        if (args.length > 1) {
            connector.useGradleUserHomeDir(new File(args[1]));
        }
    }

    connector.forProjectDirectory(new File("."));

    ProjectConnection connection = connector.connect();
    try {
        // Configure the build
        BuildLauncher launcher = connection.newBuild();
        launcher.forTasks("help");
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        launcher.setStandardOutput(outputStream);
        launcher.setStandardError(outputStream);

        // Run the build
        launcher.run();
    } finally {
        // Clean up
        connection.close();
    }
}
 
Example #13
Source File: TemplateOperation.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public Set<FileObject> execute() {
    GradleConnector gconn = GradleConnector.newConnector();
    ProjectConnection pconn = gconn.forProjectDirectory(projectDir).connect();
    try {
        pconn.newBuild().withArguments("--offline").forTasks("wrapper").run(); //NOI18N
    } catch (GradleConnectionException | IllegalStateException ex) {
        // Well for some reason we were  not able to load Gradle.
        // Ignoring that for now
    } finally {
        pconn.close();
    }
    return null;
}
 
Example #14
Source File: Main.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static void main(String[] args) {
    // Configure the connector and create the connection
    GradleConnector connector = GradleConnector.newConnector();

    if (args.length > 0) {
        connector.useInstallation(new File(args[0]));
        if (args.length > 1) {
            connector.useGradleUserHomeDir(new File(args[1]));
        }
    }

    connector.forProjectDirectory(new File("."));

    ProjectConnection connection = connector.connect();
    try {
        // Configure the build
        BuildLauncher launcher = connection.newBuild();
        launcher.forTasks("help");
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        launcher.setStandardOutput(outputStream);
        launcher.setStandardError(outputStream);

        // Run the build
        launcher.run();
    } finally {
        // Clean up
        connection.close();
    }
}
 
Example #15
Source File: GradleBuildSupport.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private boolean isRoot(IProject project, GradleBuild gradleBuild, IProgressMonitor monitor) {
	if (gradleBuild instanceof InternalGradleBuild) {
		CancellationTokenSource tokenSource = GradleConnector.newCancellationTokenSource();
		Collection<EclipseProject> eclipseProjects = ((InternalGradleBuild) gradleBuild).getModelProvider().fetchModels(EclipseProject.class, FetchStrategy.LOAD_IF_NOT_CACHED, tokenSource, monitor);
		for (EclipseProject eclipseProject : eclipseProjects) {
			File eclipseProjectDirectory = eclipseProject.getProjectDirectory();
			File projectDirectory = project.getLocation().toFile();
			if (eclipseProjectDirectory.equals(projectDirectory)) {
				return eclipseProject.getParent() == null;
			}
		}
	}
	return false;
}
 
Example #16
Source File: GradleDependencyAdapter.java    From thorntail with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("UnstableApiUsage")
public DeclaredDependencies getProjectDependencies() {
    return PREVIOUSLY_COMPUTED_VALUES.computeIfAbsent(rootPath, __ -> {
        DeclaredDependencies declaredDependencies;

        File projectDir = rootPath.toFile();
        GradleConnector connector = GradleConnector.newConnector().forProjectDirectory(projectDir);
        String gradleVersion = System.getenv(GradleToolingHelper.THORNTAIL_ARQUILLIAN_GRADLE_VERSION);
        if (gradleVersion != null) {
            connector.useGradleVersion(gradleVersion);
        }
        ProjectConnection connection = connector.connect();
        try {
            // 1. Attempt to fetch the dependencies via the Thorntail model.
            declaredDependencies = getDependenciesViaThorntailModel(connection);

            if (declaredDependencies == null) {
                System.err.println("The 'thorntail-arquillian' plugin is missing on your project. " +
                                           "Falling back to IdeaProject model which may not give accurate results.");
                // Fallback and load the dependencies via the Idea project model.
                declaredDependencies = getDependenciesViaIdeaModel(connection);
            }
        } finally {
            connection.close();
        }

        return declaredDependencies;
    });
}
 
Example #17
Source File: CreateNewProject.java    From jacamo with GNU Lesser General Public License v3.0 5 votes vote down vote up
void runGradleWrapper() {
    ProjectConnection connection = GradleConnector
            .newConnector()
            .forProjectDirectory(path)
            .connect();
    connection.newBuild()
        .forTasks("wrapper")
        .run();
    connection.close();
}
 
Example #18
Source File: Main.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static void main(String[] args) {
    // Configure the connector and create the connection
    GradleConnector connector = GradleConnector.newConnector();

    if (args.length > 0) {
        connector.useInstallation(new File(args[0]));
        if (args.length > 1) {
            connector.useGradleUserHomeDir(new File(args[1]));
        }
    }

    connector.forProjectDirectory(new File("."));

    ProjectConnection connection = connector.connect();
    try {
        // Configure the build
        BuildLauncher launcher = connection.newBuild();
        launcher.forTasks("help");
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        launcher.setStandardOutput(outputStream);
        launcher.setStandardError(outputStream);

        // Run the build
        launcher.run();
    } finally {
        // Clean up
        connection.close();
    }
}
 
Example #19
Source File: ToolingApiGradleHandleFactory.java    From paraphrase with Apache License 2.0 5 votes vote down vote up
public GradleHandle start(File directory, List<String> arguments) {
    GradleConnector connector = GradleConnector.newConnector();
    connector.forProjectDirectory(directory);
    ProjectConnection connection = connector.connect();
    BuildLauncher launcher = connection.newBuild();
    String[] argumentArray = new String[arguments.size()];
    arguments.toArray(argumentArray);
    launcher.withArguments(argumentArray);
    return new BuildLauncherBackedGradleHandle(launcher);
}
 
Example #20
Source File: GradleTestCase.java    From intellij-quarkus with Eclipse Public License 2.0 5 votes vote down vote up
static File getDependency(String path, String groupId, String artifactId, String version) {
    try (ProjectConnection connection = GradleConnector.newConnector().forProjectDirectory(new File(path)).connect()) {
        Optional<IdeaSingleEntryLibraryDependency> dependency = (Optional<IdeaSingleEntryLibraryDependency>) connection.getModel(IdeaProject.class).getModules().stream().flatMap(module -> module.getDependencies().stream()).
                filter(dep -> dep instanceof IdeaSingleEntryLibraryDependency).
                map(dep -> (IdeaSingleEntryLibraryDependency)dep).
                filter(library -> isCoordinateSame((IdeaSingleEntryLibraryDependency) library, groupId, artifactId, version)).findFirst();
        if (dependency.isPresent()) {
            return dependency.get().getFile();
        } else {
            return GradleToolDelegate.getDeploymentFile(groupId + ":" + artifactId + ":" + version);
        }
    }
}
 
Example #21
Source File: DefaultGradleConnector.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public GradleConnector useClasspathDistribution() {
    distribution = distributionFactory.getClasspathDistribution();
    return this;
}
 
Example #22
Source File: DefaultGradleConnector.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public GradleConnector useDistribution(URI gradleDistribution) {
    distribution = distributionFactory.getDistribution(gradleDistribution);
    return this;
}
 
Example #23
Source File: DefaultGradleConnector.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public GradleConnector useGradleVersion(String gradleVersion) {
    distribution = distributionFactory.getDistribution(gradleVersion);
    return this;
}
 
Example #24
Source File: GradleBuildAutomaticDeployment.java    From arquillian-container-chameleon with Apache License 2.0 4 votes vote down vote up
private Archive<?> runBuild(GradleBuild conf) {
  	
  	ProjectConnection projectConnector = GradleConnector
  		.newConnector()
  		.forProjectDirectory(new File(conf.path()))
  		.connect();
  	
  	BuildLauncher launcher = projectConnector
  		.newBuild()
  		.forTasks(conf.tasks())
  		.withArguments("-x", "test");
  	
  	if (!conf.quiet()) {
   	launcher.withArguments("--info", "--stacktrace");
   	launcher.setStandardOutput(System.out);
       launcher.setStandardError(System.err);
  	}
  	launcher.run();
  	
  	GradleProject projectModel = projectConnector.getModel(GradleProject.class);
final Path artifactDir = projectModel.getBuildDirectory().toPath().resolve("libs");

Path artifactPath = null;
try (DirectoryStream<Path> filesInArtifactDir = Files.newDirectoryStream(artifactDir)) {
	for (Path file : filesInArtifactDir) {
              if (file.toString().endsWith(".war")) {
              	artifactPath = file;
              	break;
              }
          }
} catch (Exception e) {
	throw new RuntimeException(e);
}
	
if (artifactPath == null) {
	throw new RuntimeException("No .war-file found in " + artifactDir.toString() + ".");
}

return ShrinkWrap
		  .create(ZipImporter.class, artifactPath.getFileName().toString())
		  .importFrom(artifactPath.toFile())
		  .as(WebArchive.class);

  }
 
Example #25
Source File: DefaultGradleConnector.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public GradleConnector useDefaultDistribution() {
    distribution = null;
    return this;
}
 
Example #26
Source File: DefaultGradleConnector.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public GradleConnector forProjectDirectory(File projectDir) {
    connectionParamsBuilder.setProjectDir(projectDir);
    return this;
}
 
Example #27
Source File: DefaultGradleConnector.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public GradleConnector useGradleUserHomeDir(File gradleUserHomeDir) {
    connectionParamsBuilder.setGradleUserHomeDir(gradleUserHomeDir);
    return this;
}
 
Example #28
Source File: DefaultGradleConnector.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public GradleConnector daemonMaxIdleTime(int timeoutValue, TimeUnit timeoutUnits) {
    connectionParamsBuilder.setDaemonMaxIdleTimeValue(timeoutValue);
    connectionParamsBuilder.setDaemonMaxIdleTimeUnits(timeoutUnits);
    return this;
}
 
Example #29
Source File: DefaultGradleConnector.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public GradleConnector useInstallation(File gradleHome) {
    distribution = distributionFactory.getDistribution(gradleHome);
    return this;
}
 
Example #30
Source File: DefaultGradleConnector.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public GradleConnector useGradleVersion(String gradleVersion) {
    distribution = distributionFactory.getDistribution(gradleVersion);
    return this;
}