Java Code Examples for org.gradle.tooling.GradleConnector#connect()

The following examples show how to use org.gradle.tooling.GradleConnector#connect() . 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: 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 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: 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 4
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 5
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 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: 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: 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 9
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 10
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 11
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 12
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 13
Source File: AbstractModelBuilderTest.java    From intellij-quarkus with Eclipse Public License 2.0 4 votes vote down vote up
@Before
public void setUp() throws Exception {
  assumeThat(gradleVersion, versionMatcherRule.getMatcher());

  ensureTempDirCreated();

  String methodName = name.getMethodName();
  Matcher m = TEST_METHOD_NAME_PATTERN.matcher(methodName);
  if (m.matches()) {
    methodName = m.group(1);
  }

  testDir = new File(ourTempDir, methodName);
  FileUtil.ensureExists(testDir);

  final InputStream buildScriptStream = getClass().getResourceAsStream("/" + methodName + "/" + GradleConstants.DEFAULT_SCRIPT_NAME);
  try {
    FileUtil.writeToFile(
      new File(testDir, GradleConstants.DEFAULT_SCRIPT_NAME),
      FileUtil.loadTextAndClose(buildScriptStream)
    );
  }
  finally {
    StreamUtil.closeStream(buildScriptStream);
  }

  final InputStream settingsStream = getClass().getResourceAsStream("/" + methodName + "/" + GradleConstants.SETTINGS_FILE_NAME);
  try {
    if(settingsStream != null) {
      FileUtil.writeToFile(
        new File(testDir, GradleConstants.SETTINGS_FILE_NAME),
        FileUtil.loadTextAndClose(settingsStream)
      );
    }
  } finally {
    StreamUtil.closeStream(settingsStream);
  }

  GradleConnector connector = GradleConnector.newConnector();

  GradleVersion _gradleVersion = GradleVersion.version(gradleVersion);
  final URI distributionUri = new DistributionLocator().getDistributionFor(_gradleVersion);
  connector.useDistribution(distributionUri);
  connector.forProjectDirectory(testDir);
  int daemonMaxIdleTime = 10;
  try {
    daemonMaxIdleTime = Integer.parseInt(System.getProperty("gradleDaemonMaxIdleTime", "10"));
  }
  catch (NumberFormatException ignore) {}

  ((DefaultGradleConnector)connector).daemonMaxIdleTime(daemonMaxIdleTime, TimeUnit.SECONDS);
  ProjectConnection connection = connector.connect();

  try {
    boolean isGradleProjectDirSupported = _gradleVersion.compareTo(GradleVersion.version("2.4")) >= 0;
    boolean isCompositeBuildsSupported = isGradleProjectDirSupported && _gradleVersion.compareTo(GradleVersion.version("3.1")) >= 0;
    final ProjectImportAction projectImportAction = new ProjectImportAction(false, isGradleProjectDirSupported,
                                                                            isCompositeBuildsSupported);
    projectImportAction.addProjectImportExtraModelProvider(new ClassSetProjectImportExtraModelProvider(getModels()));
    BuildActionExecuter<ProjectImportAction.AllModels> buildActionExecutor = connection.action(projectImportAction);
    File initScript = GradleExecutionHelper.generateInitScript(false, getToolingExtensionClasses());
    assertNotNull(initScript);
    String jdkHome = IdeaTestUtil.requireRealJdkHome();
    buildActionExecutor.setJavaHome(new File(jdkHome));
    buildActionExecutor.setJvmArguments("-Xmx128m", "-XX:MaxPermSize=64m");
    buildActionExecutor.withArguments("--info", GradleConstants.INIT_SCRIPT_CMD_OPTION, initScript.getAbsolutePath());
    allModels = buildActionExecutor.run();
    assertNotNull(allModels);
  } finally {
    connection.close();
  }
}
 
Example 14
Source File: ExecuteGoal.java    From NBANDROID-V2 with Apache License 2.0 4 votes vote down vote up
@Override
public void run() {
    cancellation.set(false);
    cancellationReference.set(new DefaultBuildCancellationToken());
    GradleConnector connector = GradleConnector.newConnector();
    connector.useInstallation(gradleHome);
    connector.forProjectDirectory(FileUtil.toFile(project.getProjectDirectory()));
    try (ProjectConnection connection = connector.connect()) {
        BuildLauncher buildLauncher = connection.newBuild();
        buildLauncher.forTasks(taskInfo.getName());
        buildLauncher.withCancellationToken(this);
        ProjectConfigurationProvider pcp = project.getLookup().lookup(ProjectConfigurationProvider.class);
        if (pcp != null && pcp.getActiveConfiguration() != null) {
            buildLauncher.addArguments("-Pandroid.profile=" + pcp.getActiveConfiguration());
        }
        if (argsConfiguration != null) {
            buildLauncher.addArguments(argsConfiguration.getJvmArguments());
        }
        if (jvmConfiguration == null) {
            buildLauncher.addJvmArguments("-Xms800m", "-Xmx2000m");
        } else {
            buildLauncher.addJvmArguments(jvmConfiguration.getJvmArguments());
        }
        InputOutput io = project.getLookup().lookup(InputOutput.class);
        if (io != null) {
            io.show(ImmutableSet.of(ShowOperation.OPEN, ShowOperation.MAKE_VISIBLE));
            io.getOut().print("\n\r");
            io.getOut().print("\n\r");
            io.getOut().print("\n\r");
            io.getOut().print("\n\r");
            io.getOut().println(BLUE + "Executing task: " + taskInfo.getName() + BLACK);
            io.getOut().print("\n\r");
            io.getOut().print("\n\r");
            CustomWriterOutputStream cwos = new CustomWriterOutputStream(io.getOut(), "UTF-8");
            buildLauncher.setStandardOutput(cwos);
            buildLauncher.setStandardError(cwos);
            buildLauncher.setColorOutput(true);
        }
        final ProgressHandle progressHandle = ProgressHandleFactory.createSystemHandle(project.getProjectDirectory().getName() + " : " + taskInfo.getDescription(), this);
        progressHandle.start();
        buildLauncher.addProgressListener(new ProgressListener() {
            @Override
            public void statusChanged(ProgressEvent event) {
                progressHandle.progress(event.getDisplayName());
            }
        });
        try {
            buildLauncher.run();
        } catch (GradleConnectionException | IllegalStateException gradleConnectionException) {
            if (!(gradleConnectionException instanceof BuildCancelledException)) {
                Exceptions.printStackTrace(gradleConnectionException);
            }
        }
        progressHandle.finish();
        ModelRefresh modelRefresh = project.getLookup().lookup(ModelRefresh.class);
        if (modelRefresh != null) {
            modelRefresh.refreshModels();
        }
    } catch (Exception e) {
        Exceptions.printStackTrace(e);
    }
}
 
Example 15
Source File: GradleHandlerImpl.java    From NBANDROID-V2 with Apache License 2.0 4 votes vote down vote up
private void deserializeModels() {
    cancellation.set(false);
    cancellationReference.set(new DefaultBuildCancellationToken());
    GradleHome gradleHome = lookupResult.allInstances().iterator().next();
    if (gradleHome.getStatus() == GradleDownloader.Status.OK) {
        synchronized (gradleLocations) {
            gradleLocations.put(project, gradleHome);
        }
        //      modelContent.set(Collections.emptyList(), null);
        GradleConnector connector = GradleConnector.newConnector();
        connector.useInstallation(gradleHome.getGradleHome());
        connector.forProjectDirectory(FileUtil.toFile(project.getProjectDirectory()));
        try (ProjectConnection connection = connector.connect()) {
            List<Object> modelList = new ArrayList<>();
            for (Class model : models) {
                ModelBuilder modelBuilder = connection.model(model);
                modelBuilder.withCancellationToken(this);
                //Emulate Android studio
                modelBuilder.addArguments("-Pandroid.injected.build.model.only.versioned=3");
                //Prepare load of plugin to retreive tasks from Gradle
                modelBuilder.addJvmArguments("-DANDROID_TOOLING_JAR=" + TOOLING_JAR);
                modelBuilder.addArguments("-I");
                modelBuilder.addArguments(INIT_SCRIPT);
                if (argsConfiguration != null) {
                    modelBuilder.addArguments(argsConfiguration.getJvmArguments());
                }
                if (jvmConfiguration == null) {
                    modelBuilder.addJvmArguments("-Xms800m", "-Xmx2000m");
                } else {
                    modelBuilder.addJvmArguments(jvmConfiguration.getJvmArguments());
                }
                InputOutput io = project.getLookup().lookup(InputOutput.class);
                if (io != null) {
                    io.show(ImmutableSet.of(ShowOperation.OPEN, ShowOperation.MAKE_VISIBLE));
                    io.getOut().print("\n\r");
                    io.getOut().print("\n\r");
                    io.getOut().print("\n\r");
                    io.getOut().print("\n\r");
                    io.getOut().println(BLUE + "Deserializing model: " + model.getSimpleName() + BLACK);
                    io.getOut().print("\n\r");
                    io.getOut().print("\n\r");
                    CustomWriterOutputStream cwos = new CustomWriterOutputStream(io.getOut(), "UTF-8");
                    modelBuilder.setStandardOutput(cwos);
                    modelBuilder.setStandardError(cwos);
                    modelBuilder.setColorOutput(true);
                }
                final ProgressHandle progressHandle = ProgressHandleFactory.createSystemHandle(project.getProjectDirectory().getName() + ": Loading Gradle model..", this);
                progressHandle.start();
                modelBuilder.addProgressListener(new ProgressListener() {
                    @Override
                    public void statusChanged(ProgressEvent event) {
                        progressHandle.progress(event.getDisplayName());
                    }
                });
                try {
                    modelList.add(modelBuilder.get());
                } catch (GradleConnectionException | IllegalStateException gradleConnectionException) {
                    if (!(gradleConnectionException instanceof BuildCancelledException)) {
                        Exceptions.printStackTrace(gradleConnectionException);
                    }
                }
                progressHandle.finish();
            }
            modelContent.set(modelList, null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}