org.gradle.tooling.ProjectConnection Java Examples

The following examples show how to use org.gradle.tooling.ProjectConnection. 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
void prepareCompileAndroidJava() {
  try (ProjectConnection connection = this.project.getProjectConnection()) {
    BuildLauncher buildLauncher = connection.newBuild();
    String genTask = this.project.getName() + this.genSourceTaskName;
    buildLauncher.forTasks(genTask).run();

    int size = this.project.getDependencies().size();

    String aar =
        Joiner.on(File.separator)
            .join(this.project.getProjectRoot(), BUILD_DIR, INTERMEDIATE_DIR, EXPLODED_DIR);
    List<File> jars = FileUtils.collectFiles(new File(aar), EXT_JAR);
    for (File jar : jars) {
      addAAR(jar);
    }

    int after = this.project.getDependencies().size();
    if (size != after) {
      CachedASMReflector.getInstance().createClassIndexes(jars);
      this.project.resetCachedClasspath();
    }
  }
}
 
Example #2
Source File: ComparableGradleBuildExecuter.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public ProjectOutcomes executeWith(ProjectConnection connection) {
    List<String> tasksList = getSpec().getTasks();
    String[] tasks = tasksList.toArray(new String[tasksList.size()]);
    List<String> argumentsList = getImpliedArguments();
    String[] arguments = argumentsList.toArray(new String[argumentsList.size()]);

    if (isCanObtainProjectOutcomesModel()) {
        // Run the build and get the build outcomes model
        ModelBuilder<ProjectOutcomes> modelBuilder = connection.model(ProjectOutcomes.class);
        return modelBuilder.
                withArguments(arguments).
                forTasks(tasks).
                get();
    } else {
        BuildLauncher buildLauncher = connection.newBuild();
        buildLauncher.
                withArguments(arguments).
                forTasks(tasks).
                run();

        return null;
    }
}
 
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: 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 #5
Source File: GradleConnector.java    From MSPaintIDE with MIT License 6 votes vote down vote up
public void runTask(OutputStream out, OutputStream err, String... tasks) {
    LOGGER.info("Running task(s) {}", String.join(" ", tasks));
    try (ProjectConnection connection = connector.connect()) {
        connection.newBuild().setStandardOutput(out).setStandardError(err).forTasks(tasks).run(new ResultHandler<>() {
            @Override
            public void onComplete(Void result) {
                LOGGER.info("Finished {}", String.join(" ", tasks));
            }

            @Override
            public void onFailure(GradleConnectionException failure) {
                LOGGER.error("Failed to execute " + String.join(" ", tasks), failure.fillInStackTrace());
            }
        });
    }
}
 
Example #6
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 #7
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 #8
Source File: ComparableGradleBuildExecuter.java    From pushfish-android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public ProjectOutcomes executeWith(ProjectConnection connection) {
    List<String> tasksList = getSpec().getTasks();
    String[] tasks = tasksList.toArray(new String[tasksList.size()]);
    List<String> argumentsList = getImpliedArguments();
    String[] arguments = argumentsList.toArray(new String[argumentsList.size()]);

    if (isCanObtainProjectOutcomesModel()) {
        // Run the build and get the build outcomes model
        ModelBuilder<ProjectOutcomes> modelBuilder = connection.model(ProjectOutcomes.class);
        return modelBuilder.
                withArguments(arguments).
                forTasks(tasks).
                get();
    } else {
        BuildLauncher buildLauncher = connection.newBuild();
        buildLauncher.
                withArguments(arguments).
                forTasks(tasks).
                run();

        return null;
    }
}
 
Example #9
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 #10
Source File: AndroidSupport.java    From meghanada-server with GNU General Public License v3.0 6 votes vote down vote up
private void prepareCompileAndroidTestJavaV2() {
  try (ProjectConnection connection = this.project.getProjectConnection()) {
    BuildLauncher buildLauncher = connection.newBuild();
    String genTestTask = this.project.getName() + genUnitTestTaskName;
    String genAndroidTestTask = this.project.getName() + genAndroidTestTaskName;

    buildLauncher.forTasks(genTestTask, genAndroidTestTask).run();

    int size = this.project.getDependencies().size();

    String aar =
        Joiner.on(File.separator)
            .join(this.project.getProjectRoot(), BUILD_DIR, INTERMEDIATE_DIR, EXPLODED_DIR);
    List<File> jars = FileUtils.collectFiles(new File(aar), EXT_JAR);
    for (File jar : jars) {
      addAAR(jar);
    }

    int after = this.project.getDependencies().size();
    if (size != after) {
      CachedASMReflector.getInstance().createClassIndexes(jars);
      this.project.resetCachedClasspath();
    }
  }
}
 
Example #11
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 #12
Source File: ComparableGradleBuildExecuter.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public ProjectOutcomes executeWith(ProjectConnection connection) {
    List<String> tasksList = getSpec().getTasks();
    String[] tasks = tasksList.toArray(new String[tasksList.size()]);
    List<String> argumentsList = getImpliedArguments();
    String[] arguments = argumentsList.toArray(new String[argumentsList.size()]);

    if (isCanObtainProjectOutcomesModel()) {
        // Run the build and get the build outcomes model
        ModelBuilder<ProjectOutcomes> modelBuilder = connection.model(ProjectOutcomes.class);
        return modelBuilder.
                withArguments(arguments).
                forTasks(tasks).
                get();
    } else {
        BuildLauncher buildLauncher = connection.newBuild();
        buildLauncher.
                withArguments(arguments).
                forTasks(tasks).
                run();

        return null;
    }
}
 
Example #13
Source File: ComparableGradleBuildExecuter.java    From pushfish-android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public ProjectOutcomes executeWith(ProjectConnection connection) {
    List<String> tasksList = getSpec().getTasks();
    String[] tasks = tasksList.toArray(new String[tasksList.size()]);
    List<String> argumentsList = getImpliedArguments();
    String[] arguments = argumentsList.toArray(new String[argumentsList.size()]);

    if (isCanObtainProjectOutcomesModel()) {
        // Run the build and get the build outcomes model
        ModelBuilder<ProjectOutcomes> modelBuilder = connection.model(ProjectOutcomes.class);
        return modelBuilder.
                withArguments(arguments).
                forTasks(tasks).
                get();
    } else {
        BuildLauncher buildLauncher = connection.newBuild();
        buildLauncher.
                withArguments(arguments).
                forTasks(tasks).
                run();

        return null;
    }
}
 
Example #14
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 #15
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 #16
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 #17
Source File: GradleDependencyAdapter.java    From thorntail with Apache License 2.0 5 votes vote down vote up
/**
 * Attempt to load the {@link ThorntailConfiguration} and retrieve the dependencies.
 *
 * @param connection the Gradle project connection.
 * @return the declared dependencies for the current project.
 */
private DeclaredDependencies getDependenciesViaThorntailModel(ProjectConnection connection) {
    DeclaredDependencies declaredDependencies = null;
    try {
        ThorntailConfiguration config = connection.getModel(ThorntailConfiguration.class);
        if (config != null) {
            declaredDependencies = GradleToolingHelper.toDeclaredDependencies(config.getTestDependencies());
        }

    } catch (GradleConnectionException | IllegalStateException e) {
        e.printStackTrace();
    }
    return declaredDependencies;
}
 
Example #18
Source File: GradleProject.java    From meghanada-server with GNU General Public License v3.0 5 votes vote down vote up
private void runPrepareTestCompileTask() throws IOException {
  if (!this.prepareTestCompileTask.isEmpty()) {
    try (ProjectConnection connection = this.getProjectConnection()) {
      final String[] tasks = prepareTestCompileTask.toArray(STRINGS);
      final BuildLauncher buildLauncher = connection.newBuild();
      log.info("project {} run tasks:{}", this.name, tasks);
      GradleProject.setBuildJVMArgs(buildLauncher);
      buildLauncher.forTasks(tasks).run();
    }
  }
}
 
Example #19
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 #20
Source File: GradleProject.java    From meghanada-server with GNU General Public License v3.0 5 votes vote down vote up
VoidResultHandler(
    final PipedOutputStream outputStream,
    final PipedInputStream inputStream,
    final ProjectConnection projectConnection) {
  this.outputStream = outputStream;
  this.inputStream = inputStream;
  this.projectConnection = projectConnection;
}
 
Example #21
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 #22
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 #23
Source File: DefaultGradleConnector.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public ProjectConnection connect() throws GradleConnectionException {
    LOGGER.debug("Connecting from tooling API consumer version {}", GradleVersion.current().getVersion());

    ConnectionParameters connectionParameters = connectionParamsBuilder.build();
    if (connectionParameters.getProjectDir() == null) {
        throw new IllegalStateException("A project directory must be specified before creating a connection.");
    }
    if (distribution == null) {
        distribution = distributionFactory.getDefaultDistribution(connectionParameters.getProjectDir(), connectionParameters.isSearchUpwards() != null ? connectionParameters.isSearchUpwards() : true);
    }
    return connectionFactory.create(distribution, connectionParameters);
}
 
Example #24
Source File: GradleBuildComparison.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private ProjectOutcomes executeBuild(ComparableGradleBuildExecuter executer) {
    ProjectConnection connection = createProjectConnection(executer);
    try {
        return executer.executeWith(connection);
    } finally {
        connection.close();
    }
}
 
Example #25
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 #26
Source File: DefaultGradleConnector.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public ProjectConnection connect() throws GradleConnectionException {
    LOGGER.debug("Connecting from tooling API consumer version {}", GradleVersion.current().getVersion());

    ConnectionParameters connectionParameters = connectionParamsBuilder.build();
    if (connectionParameters.getProjectDir() == null) {
        throw new IllegalStateException("A project directory must be specified before creating a connection.");
    }
    if (distribution == null) {
        distribution = distributionFactory.getDefaultDistribution(connectionParameters.getProjectDir(), connectionParameters.isSearchUpwards() != null ? connectionParameters.isSearchUpwards() : true);
    }
    return connectionFactory.create(distribution, connectionParameters);
}
 
Example #27
Source File: ConnectionFactory.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public ProjectConnection create(Distribution distribution, ConnectionParameters parameters) {
    SynchronizedLogging synchronizedLogging = new SynchronizedLogging();
    ConsumerActionExecutor lazyConnection = new LazyConsumerActionExecutor(distribution, toolingImplementationLoader, synchronizedLogging, parameters);
    ConsumerActionExecutor progressLoggingConnection = new ProgressLoggingConsumerActionExecutor(lazyConnection, synchronizedLogging);
    ConsumerActionExecutor initializingConnection = new LoggingInitializerConsumerActionExecutor(progressLoggingConnection, synchronizedLogging);
    AsyncConsumerActionExecutor asyncConnection = new DefaultAsyncConsumerActionExecutor(initializingConnection, executorFactory);
    return new DefaultProjectConnection(asyncConnection, parameters);
}
 
Example #28
Source File: GradleBuildComparison.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private ProjectOutcomes executeBuild(ComparableGradleBuildExecuter executer) {
    ProjectConnection connection = createProjectConnection(executer);
    try {
        return executer.executeWith(connection);
    } finally {
        connection.close();
    }
}
 
Example #29
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 #30
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);
}