Java Code Examples for org.gradle.api.tasks.compile.JavaCompile

The following examples show how to use org.gradle.api.tasks.compile.JavaCompile. These examples are extracted from open source projects. 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 Project: gradle-modules-plugin   Source File: CompileJavaTaskMutator.java    License: MIT License 6 votes vote down vote up
private List<String> buildCompilerArgs(JavaCompile javaCompile) {
    var patchModuleContainer = PatchModuleContainer.copyOf(
            helper().modularityExtension().optionContainer().getPatchModuleContainer());
    String moduleName = helper().moduleName();
    new MergeClassesHelper(project).otherCompileTaskStream()
            .map(AbstractCompile::getDestinationDir)
            .forEach(dir -> patchModuleContainer.addDir(moduleName, dir.getAbsolutePath()));

    var compilerArgs = new ArrayList<>(javaCompile.getOptions().getCompilerArgs());
    patchModuleContainer.buildModulePathOption(compileJavaClasspath)
            .ifPresent(option -> option.mutateArgs(compilerArgs));
    patchModuleContainer.mutator(compileJavaClasspath).mutateArgs(compilerArgs);

    moduleOptions.mutateArgs(compilerArgs);
    MutatorHelper.configureModuleVersion(helper(), compilerArgs);

    return compilerArgs;
}
 
Example 2
Source Project: gradle-modules-plugin   Source File: CompileModuleInfoTask.java    License: MIT License 6 votes vote down vote up
/**
 * @see CompileTask#configureModularityForCompileJava
 */
void configureModularityForCompileModuleInfoJava(
        JavaCompile compileJava, CompileModuleOptions moduleOptions) {
    JavaCompile compileModuleInfoJava = preconfigureCompileModuleInfoJava(compileJava);
    CompileModuleInfoHelper.dependOnOtherCompileModuleInfoJavaTasks(compileModuleInfoJava);

    CompileJavaTaskMutator mutator = createCompileJavaTaskMutator(compileJava, moduleOptions);

    // don't convert to lambda: https://github.com/java9-modularity/gradle-modules-plugin/issues/54
    compileModuleInfoJava.doFirst(new Action<Task>() {
        @Override
        public void execute(Task task) {
            mutator.modularizeJavaCompileTask(compileModuleInfoJava);
        }
    });

    project.getTasks().withType(Jar.class).configureEach(jar -> jar.from(helper().getModuleInfoDir()));
}
 
Example 3
Source Project: gradle-modules-plugin   Source File: CompileModuleInfoTask.java    License: MIT License 6 votes vote down vote up
/**
 * Preconfigures a separate task that is meant to compile {@code module-info.java} separately.
 * Final (modular) configuration is performed later by {@link CompileJavaTaskMutator}.
 */
private JavaCompile preconfigureCompileModuleInfoJava(JavaCompile compileJava) {
    var compileModuleInfoJava = helper().compileJavaTask(CompileModuleOptions.COMPILE_MODULE_INFO_TASK_NAME);

    compileModuleInfoJava.setClasspath(project.files()); // empty
    compileModuleInfoJava.setSource(pathToModuleInfoJava());
    compileModuleInfoJava.getOptions().setSourcepath(project.files(pathToModuleInfoJava().getParent()));

    compileModuleInfoJava.setDestinationDir(helper().getModuleInfoDir());

    // we need all the compiled classes before compiling module-info.java
    compileModuleInfoJava.dependsOn(compileJava);

    // make "classes" trigger module-info.java compilation
    helper().task(JavaPlugin.CLASSES_TASK_NAME).dependsOn(compileModuleInfoJava);

    return compileModuleInfoJava;
}
 
Example 4
Source Project: gradle-modules-plugin   Source File: CompileTestTask.java    License: MIT License 6 votes vote down vote up
private void configureCompileTestJava(JavaCompile compileTestJava) {
    var moduleOptions = compileTestJava.getExtensions()
            .create("moduleOptions", CompileTestModuleOptions.class, project);

    // don't convert to lambda: https://github.com/java9-modularity/gradle-modules-plugin/issues/54
    compileTestJava.doFirst(new Action<Task>() {
        @Override
        public void execute(Task task) {
            var compilerArgs = buildCompilerArgs(compileTestJava, moduleOptions);
            compileTestJava.getOptions().setCompilerArgs(compilerArgs);
            LOGGER.info("compiler args for task {}: {}", compileTestJava.getName(),
                    compileTestJava.getOptions().getAllCompilerArgs());
            compileTestJava.setClasspath(project.files());
        }
    });
}
 
Example 5
Source Project: gradle-modules-plugin   Source File: DefaultModularityExtension.java    License: MIT License 6 votes vote down vote up
private void setJavaRelease(JavaCompile javaCompile, int javaRelease) {
    String currentJavaVersion = JavaVersion.current().toString();
    if (!javaCompile.getSourceCompatibility().equals(currentJavaVersion)) {
        throw new IllegalStateException("sourceCompatibility should not be set together with --release option");
    }
    if (!javaCompile.getTargetCompatibility().equals(currentJavaVersion)) {
        throw new IllegalStateException("targetCompatibility should not be set together with --release option");
    }

    List<String> compilerArgs = javaCompile.getOptions().getCompilerArgs();
    if (compilerArgs.contains("--release")) {
        throw new IllegalStateException("--release option is already set in compiler args");
    }

    compilerArgs.add("--release");
    compilerArgs.add(String.valueOf(javaRelease));
}
 
Example 6
Source Project: gradle-java-modules   Source File: JigsawPlugin.java    License: Apache License 2.0 6 votes vote down vote up
private void configureCompileTestJavaTask(final Project project) {
    final JavaCompile compileTestJava = (JavaCompile) project.getTasks()
            .findByName(JavaPlugin.COMPILE_TEST_JAVA_TASK_NAME);
    final SourceSet test = ((SourceSetContainer) project.getProperties().get("sourceSets")).getByName("test");
    final JavaModule module = (JavaModule) project.getExtensions().getByName(EXTENSION_NAME);
    compileTestJava.getInputs().property("moduleName", module.geName());
    compileTestJava.doFirst(new Action<Task>() {
        @Override
        public void execute(Task task) {
            List<String> args = new ArrayList<>();
            args.add("--module-path");
            args.add(compileTestJava.getClasspath().getAsPath());
            args.add("--add-modules");
            args.add("junit");
            args.add("--add-reads");
            args.add(module.geName() + "=junit");
            args.add("--patch-module");
            args.add(module.geName() + "=" + test.getJava().getSourceDirectories().getAsPath());
            compileTestJava.getOptions().setCompilerArgs(args);
            compileTestJava.setClasspath(project.files());
        }
    });
}
 
Example 7
Source Project: javaide   Source File: JavaBasePlugin.java    License: GNU General Public License v3.0 6 votes vote down vote up
private void createCompileJavaTaskForBinary(final SourceSet sourceSet, SourceDirectorySet javaSourceSet, Project target) {
    JavaCompile compileTask = target.getTasks().create(sourceSet.getCompileJavaTaskName(), JavaCompile.class);
    compileTask.setDescription("Compiles " + javaSourceSet + ".");
    compileTask.setSource(javaSourceSet);
    ConventionMapping conventionMapping = compileTask.getConventionMapping();
    conventionMapping.map("classpath", new Callable<Object>() {
        public Object call() throws Exception {
            return sourceSet.getCompileClasspath();
        }
    });
    conventionMapping.map("destinationDir", new Callable<Object>() {
        public Object call() throws Exception {
            return sourceSet.getOutput().getClassesDir();
        }
    });
}
 
Example 8
Source Project: javaccPlugin   Source File: CompileJjtreeTask.java    License: MIT License 6 votes vote down vote up
@TaskAction
public void run() {
    TaskCollection<JavaCompile> javaCompileTasks = this.getProject().getTasks().withType(JavaCompile.class);
    CompilerInputOutputConfiguration inputOutputDirectories
        = new JavaccCompilerInputOutputConfiguration(getInputDirectory(), getOutputDirectory(), getSource(), javaCompileTasks);
    JjtreeProgramInvoker jjtreeInvoker = new JjtreeProgramInvoker(getProject(), getClasspath(), inputOutputDirectories.getTempOutputDirectory());
    ProgramArguments arguments = new ProgramArguments();
    arguments.addAll(getArguments());
    SourceFileCompiler compiler = new JavaccSourceFileCompiler(jjtreeInvoker, arguments, inputOutputDirectories, getLogger());

    compiler.createTempOutputDirectory();
    compiler.compileSourceFilesToTempOutputDirectory();
    compiler.copyCompiledFilesFromTempOutputDirectoryToOutputDirectory();
    compiler.copyNonJavaccFilesToOutputDirectory();
    compiler.cleanTempOutputDirectory();
}
 
Example 9
Source Project: javaccPlugin   Source File: CompileJavaccTask.java    License: MIT License 6 votes vote down vote up
@TaskAction
public void run() {
    TaskCollection<JavaCompile> javaCompileTasks = this.getProject().getTasks().withType(JavaCompile.class);
    CompilerInputOutputConfiguration inputOutputDirectories
        = new JavaccCompilerInputOutputConfiguration(getInputDirectory(), getOutputDirectory(), getSource(), javaCompileTasks);
    JavaccProgramInvoker javaccInvoker = new JavaccProgramInvoker(getProject(), getClasspath(), inputOutputDirectories.getTempOutputDirectory());
    ProgramArguments arguments = new ProgramArguments();
    arguments.addAll(getArguments());
    SourceFileCompiler compiler = new JavaccSourceFileCompiler(javaccInvoker, arguments, inputOutputDirectories, getLogger());

    compiler.createTempOutputDirectory();
    compiler.compileSourceFilesToTempOutputDirectory();
    compiler.copyCompiledFilesFromTempOutputDirectoryToOutputDirectory();
    compiler.copyNonJavaccFilesToOutputDirectory();
    compiler.cleanTempOutputDirectory();
}
 
Example 10
Source Project: javaccPlugin   Source File: JavaToJavaccDependencyActionTest.java    License: MIT License 6 votes vote down vote up
@Test
public void generatedJavaFilesFromCompileJavaccAreAddedToMainJavaSourceSet() {
    applyJavaccPluginToProject();
    applyJavaPluginToProject();
    JavaToJavaccDependencyAction action = new JavaToJavaccDependencyAction();
    final File outputDirectory = new File(getClass().getResource("/javacc/testgenerated").getFile());
    CompileJavaccTask compileJavaccTask = (CompileJavaccTask) project.getTasks().findByName(CompileJavaccTask.TASK_NAME_VALUE);
    compileJavaccTask.setOutputDirectory(outputDirectory);

    action.execute(project);

    TaskCollection<JavaCompile> javaCompilationTasks = project.getTasks().withType(JavaCompile.class);
    for (JavaCompile task : javaCompilationTasks) {
        assertTrue(task.getSource().contains(new File(outputDirectory, "someSourceFile.txt")));
    }
}
 
Example 11
@Test
public void getJavaSourceTreeReturnsAggregatedJavaCompileSourceWhenMultipleJavaCompileTasks() throws IOException {
    Project project = ProjectBuilder.builder().withProjectDir(testFolder.getRoot()).build();
    File javaFile = addTaskWithSourceFile(project, "compileJava", "input/TestClass.java", JavaCompile.class);
    testFolder.newFolder("inputTest");
    File testFile = addTaskWithSourceFile(project, "compileTest", "inputTest/AnotherTestClass.java", JavaCompile.class);
    CompilerInputOutputConfiguration configuration = builder
        .withInputDirectory(inputDirectory)
        .withOutputDirectory(outputDirectory)
        .withJavaCompileTasks(project.getTasks().withType(JavaCompile.class))
        .build();

    FileTree javaSourceTree = configuration.getJavaSourceTree();

    assertThat(javaSourceTree, containsInAnyOrder(javaFile.getCanonicalFile(), testFile.getCanonicalFile()));
}
 
Example 12
@Test
public void getJavaSourceTreeExcludesOutputFolder() throws IOException {
    Project project = ProjectBuilder.builder().withProjectDir(testFolder.getRoot()).build();
    File javaFile = addTaskWithSourceFile(project, "compileJava", "input/TestClass.java", JavaCompile.class);
    File outputFile = addTaskWithSourceFile(project, "compileJavaccGenerated", "output/Generated.java", JavaCompile.class);
    CompilerInputOutputConfiguration configuration = builder
        .withInputDirectory(inputDirectory)
        .withOutputDirectory(outputDirectory)
        .withJavaCompileTasks(project.getTasks().withType(JavaCompile.class))
        .build();

    FileTree javaSourceTree = configuration.getJavaSourceTree();

    assertThat(javaSourceTree, contains(javaFile.getCanonicalFile()));
    assertThat(javaSourceTree, not(contains(outputFile.getCanonicalFile())));
}
 
Example 13
@Test
public void getCompleteSourceTreeReturnsSourceAndJavaSourceWhenProjectHasJavaCompileTasks() throws IOException {
    Project project = ProjectBuilder.builder().withProjectDir(testFolder.getRoot()).build();
    File javaccFile = addTaskWithSourceFile(project, "compileJavacc", "input/TestClass.jj", CompileJavaccTask.class);
    testFolder.newFolder("inputJava");
    File javaFile = addTaskWithSourceFile(project, "compileJava", "inputJava/MyClass.java", JavaCompile.class);
    CompilerInputOutputConfiguration configuration = builder
        .withInputDirectory(inputDirectory)
        .withOutputDirectory(outputDirectory)
        .withSource(((SourceTask) project.getTasks().getByName("compileJavacc")).getSource())
        .withJavaCompileTasks(project.getTasks().withType(JavaCompile.class))
        .build();

    FileTree completeSourceTree = configuration.getCompleteSourceTree();

    assertThat(completeSourceTree, containsInAnyOrder(javaccFile.getCanonicalFile(), javaFile.getCanonicalFile()));
}
 
Example 14
@Test
public void getCompleteSourceTreeExcludesOutputFolder() throws IOException {
    Project project = ProjectBuilder.builder().withProjectDir(testFolder.getRoot()).build();
    File javaccFile = addTaskWithSourceFile(project, "compileJavacc", "input/TestClass.jj", CompileJavaccTask.class);
    File outputFile = addTaskWithSourceFile(project, "compileJavaccGenerated", "output/Generated.java", JavaCompile.class);
    CompilerInputOutputConfiguration configuration = builder
        .withInputDirectory(inputDirectory)
        .withOutputDirectory(outputDirectory)
        .withSource(((SourceTask) project.getTasks().getByName("compileJavacc")).getSource())
        .withJavaCompileTasks(project.getTasks().withType(JavaCompile.class))
        .build();

    FileTree completeSourceTree = configuration.getCompleteSourceTree();

    assertThat(completeSourceTree, contains(javaccFile.getCanonicalFile()));
    assertThat(completeSourceTree, not(contains(outputFile.getCanonicalFile())));
}
 
Example 15
@Override
public void apply(final Project project) {
  project.getPluginManager().apply(ErrorProneBasePlugin.class);

  final ErrorProneToolChain toolChain = ErrorProneToolChain.create(project);
  Action<JavaCompile> action =
      task -> {
        task.setToolChain(toolChain);
        taskGetInputsFiles(task, toolChain.getConfiguration());
      };
  if (GradleVersion.current().compareTo(GradleVersion.version("4.9")) >= 0) {
    project.getTasks().withType(JavaCompile.class).configureEach(action);
  } else {
    project.getTasks().withType(JavaCompile.class, action);
  }
}
 
Example 16
Source Project: gradle-avro-plugin   Source File: AvroPlugin.java    License: Apache License 2.0 6 votes vote down vote up
private static TaskProvider<GenerateAvroJavaTask> configureJavaGenerationTask(final Project project, final SourceSet sourceSet,
                                                                TaskProvider<GenerateAvroProtocolTask> protoTaskProvider) {
    String taskName = sourceSet.getTaskName("generate", "avroJava");
    TaskProvider<GenerateAvroJavaTask> javaTaskProvider = project.getTasks().register(taskName, GenerateAvroJavaTask.class, task -> {
        task.setDescription(String.format("Generates %s Avro Java source files from schema/protocol definition files.",
            sourceSet.getName()));
        task.setGroup(GROUP_SOURCE_GENERATION);
        task.source(getAvroSourceDir(project, sourceSet));
        task.source(protoTaskProvider);
        task.include("**/*." + SCHEMA_EXTENSION, "**/*." + PROTOCOL_EXTENSION);
        task.getOutputDir().convention(getGeneratedOutputDir(project, sourceSet, JAVA_EXTENSION));

        sourceSet.getJava().srcDir(task.getOutputDir());

        JavaCompile compileJavaTask = project.getTasks().named(sourceSet.getCompileJavaTaskName(), JavaCompile.class).get();
        task.getOutputCharacterEncoding().convention(project.provider(() ->
            Optional.ofNullable(compileJavaTask.getOptions().getEncoding()).orElse(Charset.defaultCharset().name())));
    });
    project.getTasks().named(sourceSet.getCompileJavaTaskName(), JavaCompile.class, compileJavaTask -> {
        compileJavaTask.source(javaTaskProvider);
    });
    return javaTaskProvider;
}
 
Example 17
Source Project: gradle-modules-plugin   Source File: CompileJavaTaskMutator.java    License: MIT License 5 votes vote down vote up
/**
 * The argument is a {@link JavaCompile} task whose modularity is to be configured.
 *
 * @param javaCompile {@code compileJava} if {@link CompileModuleOptions#getCompileModuleInfoSeparately()}
 *                    is {@code false}, {@code compileModuleInfoJava} if it is {@code true}
 */
void modularizeJavaCompileTask(JavaCompile javaCompile) {
    List<String> compilerArgs = buildCompilerArgs(javaCompile);
    javaCompile.getOptions().setCompilerArgs(compilerArgs);
    LOGGER.info("compiler args for task {}: {}", javaCompile.getName(), javaCompile.getOptions().getAllCompilerArgs());

    javaCompile.setClasspath(project.files());
    configureSourcepath(javaCompile);
}
 
Example 18
Source Project: gradle-modules-plugin   Source File: CompileModuleInfoTask.java    License: MIT License 5 votes vote down vote up
private void configureCompileModuleInfoJava(JavaCompile compileJava) {
    var moduleOptions = compileJava.getExtensions().getByType(CompileModuleOptions.class);
    project.afterEvaluate(p -> {
        if (moduleOptions.getCompileModuleInfoSeparately()) {
            configureModularityForCompileModuleInfoJava(compileJava, moduleOptions);
        }
    });
}
 
Example 19
Source Project: gradle-modules-plugin   Source File: CompileTestTask.java    License: MIT License 5 votes vote down vote up
private List<String> buildCompilerArgs(
        JavaCompile compileTestJava, CompileTestModuleOptions moduleOptions) {
    var compilerArgs = new ArrayList<>(compileTestJava.getOptions().getCompilerArgs());

    String moduleName = helper().moduleName();
    FileCollection classpath = mergeClassesHelper().getMergeAdjustedClasspath(compileTestJava.getClasspath());

    var patchModuleContainer = PatchModuleContainer.copyOf(
            helper().modularityExtension().optionContainer().getPatchModuleContainer());
    FileCollection testSourceDirs = helper().testSourceSet().getJava().getSourceDirectories();
    testSourceDirs.forEach(dir -> patchModuleContainer.addDir(moduleName, dir.getAbsolutePath()));
    patchModuleContainer.buildModulePathOption(classpath).ifPresent(option -> option.mutateArgs(compilerArgs));

    TestEngine.selectMultiple(project).forEach(testEngine -> {
        new TaskOption("--add-modules", testEngine.moduleName).mutateArgs(compilerArgs);
        new TaskOption("--add-reads", moduleName + "=" + testEngine.moduleName).mutateArgs(compilerArgs);
        testEngine.additionalTaskOptions.forEach(option -> option.mutateArgs(compilerArgs));
    });

    moduleOptions.mutateArgs(compilerArgs);

    patchModuleContainer.mutator(classpath).mutateArgs(compilerArgs);

    ModuleInfoTestHelper.mutateArgs(project, compilerArgs::add);

    return compilerArgs;
}
 
Example 20
Source Project: gradle-modules-plugin   Source File: CompileTask.java    License: MIT License 5 votes vote down vote up
private void configureCompileJava(JavaCompile compileJava) {
    project.getConfigurations().stream()
            .flatMap(configuration -> configuration.getDependencies().stream())
            .filter(dependency -> dependency instanceof ProjectDependency)
            .map(dependency -> ((ProjectDependency) dependency).getDependencyProject().getTasks())
            .map(tasks -> tasks.findByName(CompileModuleOptions.COMPILE_MODULE_INFO_TASK_NAME))
            .filter(Objects::nonNull);



    var moduleOptions = compileJava.getExtensions().create("moduleOptions", CompileModuleOptions.class, project);
    project.afterEvaluate(p -> {
        adjustMainClass(compileJava);

        MergeClassesHelper.POST_JAVA_COMPILE_TASK_NAMES.stream()
                .map(name -> helper().findTask(name, AbstractCompile.class))
                .flatMap(Optional::stream)
                .filter(task -> !task.getSource().isEmpty())
                .findAny()
                .ifPresent(task -> moduleOptions.setCompileModuleInfoSeparately(true));

        if (moduleOptions.getCompileModuleInfoSeparately()) {
            compileJava.exclude("module-info.java");
        } else {
            configureModularityForCompileJava(compileJava, moduleOptions);
        }
    });
}
 
Example 21
Source Project: gradle-modules-plugin   Source File: CompileTask.java    License: MIT License 5 votes vote down vote up
private void adjustMainClass(JavaCompile compileJava) {
    if(GradleVersion.current().compareTo(GradleVersion.version("6.4")) >= 0) {
        Property<String> mainClassProp = compileJava.getOptions().getJavaModuleMainClass();
        String mainClass = mainClassProp.getOrNull();
        if(mainClass != null) {
            int idx = mainClass.indexOf('/');
            if(idx >= 0) {
                mainClassProp.set(mainClass.substring(idx + 1));
            }
        }
    }
}
 
Example 22
Source Project: gradle-modules-plugin   Source File: CompileTask.java    License: MIT License 5 votes vote down vote up
/**
 * @see CompileModuleInfoTask#configureModularityForCompileModuleInfoJava
 */
void configureModularityForCompileJava(JavaCompile compileJava, CompileModuleOptions moduleOptions) {
    CompileModuleInfoHelper.dependOnOtherCompileModuleInfoJavaTasks(compileJava);

    CompileJavaTaskMutator mutator = createCompileJavaTaskMutator(compileJava, moduleOptions);
    // don't convert to lambda: https://github.com/java9-modularity/gradle-modules-plugin/issues/54
    compileJava.doFirst(new Action<Task>() {
        @Override
        public void execute(Task task) {
            mutator.modularizeJavaCompileTask(compileJava);
        }
    });
}
 
Example 23
Source Project: gradle-modules-plugin   Source File: CompileModuleOptions.java    License: MIT License 5 votes vote down vote up
public void setCompileModuleInfoSeparately(boolean compileModuleInfoSeparately) {
    if (compileModuleInfoSeparately) {
        // we need to create "compileModuleInfoJava" task eagerly so that the user can configure it immediately
        project.getTasks().maybeCreate(COMPILE_MODULE_INFO_TASK_NAME, JavaCompile.class);
    }
    this.compileModuleInfoSeparately = compileModuleInfoSeparately;
}
 
Example 24
Source Project: gradle-modules-plugin   Source File: CompileJavaTaskMutatorTest.java    License: MIT License 5 votes vote down vote up
@Test
void modularizeJavaCompileTask() {
    // given
    Project project = ProjectBuilder.builder().withProjectDir(new File("test-project/")).build();
    project.getPlugins().apply("java");
    JavaCompile compileJava = (JavaCompile) project.getTasks().getByName(JavaPlugin.COMPILE_JAVA_TASK_NAME);

    FileCollection classpath = project.files("dummy dir"); // we need anything on classpath
    compileJava.setClasspath(classpath);

    CompileModuleOptions moduleOptions = compileJava.getExtensions()
            .create("moduleOptions", CompileModuleOptions.class, project);
    project.getExtensions().add("moduleName", getClass().getName());
    project.getExtensions().create("patchModules", PatchModuleExtension.class);
    project.getExtensions().create("modularity", DefaultModularityExtension.class, project);

    CompileJavaTaskMutator mutator = new CompileJavaTaskMutator(project, compileJava.getClasspath(), moduleOptions);

    // when
    mutator.modularizeJavaCompileTask(compileJava);

    // then
    List<String> twoLastArguments = twoLastCompilerArgs(compileJava);
    assertEquals(
            Arrays.asList("--module-path", classpath.getAsPath()),
            twoLastArguments,
            "Two last arguments should be setting module path to the current compileJava task classpath");
}
 
Example 25
private void createCompileJavaTaskForBinary(final ClassDirectoryBinarySpecInternal binary, final Project target) {
    final BinaryNamingScheme namingScheme = binary.getNamingScheme();
    binary.getSource().withType(JavaSourceSet.class).all(new Action<JavaSourceSet>() {
        public void execute(JavaSourceSet javaSourceSet) {
            JavaCompile compileTask = target.getTasks().create(namingScheme.getTaskName("compile", "java"), JavaCompile.class);
            configureCompileTask(compileTask, javaSourceSet, binary);
            binary.getTasks().add(compileTask);
            binary.builtBy(compileTask);
        }
    });
}
 
Example 26
public void apply(final Project target) {
    target.getPlugins().apply(JvmLanguagePlugin.class);

    BinaryContainer jvmBinaryContainer = target.getExtensions().getByType(BinaryContainer.class);
    jvmBinaryContainer.withType(ClassDirectoryBinary.class).all(new Action<ClassDirectoryBinary>() {
        public void execute(final ClassDirectoryBinary binary) {
            final BinaryNamingScheme namingScheme = ((BinaryInternal) binary).getNamingScheme();
            binary.getSource().withType(JavaSourceSet.class).all(new Action<JavaSourceSet>() {
                public void execute(JavaSourceSet javaSourceSet) {
                    // TODO: handle case where binary has multiple JavaSourceSet's
                    JavaCompile compileTask = target.getTasks().create(namingScheme.getTaskName("compile", "java"), JavaCompile.class);
                    configureCompileTask(compileTask, javaSourceSet, binary);
                    binary.builtBy(compileTask);
                }
            });
        }
    });

    ProjectSourceSet projectSourceSet = target.getExtensions().getByType(DefaultProjectSourceSet.class);
    projectSourceSet.all(new Action<FunctionalSourceSet>() {
        public void execute(final FunctionalSourceSet functionalSourceSet) {
            functionalSourceSet.registerFactory(JavaSourceSet.class, new NamedDomainObjectFactory<JavaSourceSet>() {
                public JavaSourceSet create(String name) {
                    return instantiator.newInstance(DefaultJavaSourceSet.class, name,
                            instantiator.newInstance(DefaultSourceDirectorySet.class, name, fileResolver),
                            instantiator.newInstance(DefaultClasspath.class, fileResolver,
                                    target.getTasks()), functionalSourceSet);
                }
            });
        }
    });
}
 
Example 27
Source Project: doov   Source File: GeneratorPlugin.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void apply(Project target) {
    NamedDomainObjectContainer<ModelMapGenerator> container = target.container(ModelMapGenerator.class,
            name -> new ModelMapGenerator(name, target));
    target.getExtensions().add("doovCodeGen", container);

    JavaCompile compileJava = target.getTasks().withType(JavaCompile.class).getByName("compileJava");
    JavaPluginConvention javaPluginConvention = target.getConvention().findPlugin(JavaPluginConvention.class);
    SourceSet main = javaPluginConvention.getSourceSets().maybeCreate("main");

    container.all(modelMap -> {
        ModelMapGenTask task = target.getTasks().create(modelMap.getName(), ModelMapGenTask.class);
        main.getJava().srcDir(modelMap.getOutputDirectory());

        target.afterEvaluate(project -> {
            task.setClasspath(main.getCompileClasspath());
            task.getBaseClassProperty().set(modelMap.getBaseClass());
            task.getOutputDirectory().set(modelMap.getOutputDirectory());
            task.getOutputResourceDirectory().set(modelMap.getOutputResourceDirectory());
            task.getSourceClassProperty().set(modelMap.getSourceClass());
            task.getFieldClassProperty().set(modelMap.getFieldClass());
            task.getPackageFilter().set(modelMap.getPackageFilter());
            task.getEnumFieldInfo().set(modelMap.getEnumFieldInfo());
            task.getFieldPathProviderProperty().set(modelMap.getFieldPathProvider());
            task.getTypeAdaptersProperty().set(modelMap.getTypeAdapters());
            task.getDslModelPackage().set(modelMap.getDslModelPackage());
            task.getWrapperPackage().set(modelMap.getWrapperPackage());
            task.getFieldInfoPackage().set(modelMap.getFieldInfoPackage());
            task.getDslEntrypointMethods().set(modelMap.getDslEntrypointMethods());

            compileJava.dependsOn(task);
        });

    });

}
 
Example 28
Source Project: gradle-java-modules   Source File: JigsawPlugin.java    License: Apache License 2.0 5 votes vote down vote up
private void configureCompileJavaTask(final Project project) {
    final JavaCompile compileJava = (JavaCompile) project.getTasks().findByName(JavaPlugin.COMPILE_JAVA_TASK_NAME);
    compileJava.doFirst(new Action<Task>() {
        @Override
        public void execute(Task task) {
            List<String> args = new ArrayList<>();
            args.add("--module-path");
            args.add(compileJava.getClasspath().getAsPath());
            compileJava.getOptions().setCompilerArgs(args);
            compileJava.setClasspath(project.files());
        }
    });
}
 
Example 29
@Override
public void execute(final JavaCompile javacTask) {
    scope.getVariantData().javacTask = javacTask;

    javacTask.setSource(scope.getVariantData().getJavaSources());
    ConventionMappingHelper.map(javacTask, "classpath", new Callable<FileCollection>() {
        @Override
        public FileCollection call() {
            FileCollection classpath = scope.getJavaClasspath();
            Project project = scope.getGlobalScope().getProject();

            return classpath;
        }
    });

    javacTask.setDestinationDir(scope.getJavaOutputDir());

    javacTask.setDependencyCacheDir(scope.getJavaDependencyCache());

    CompileOptions compileOptions = scope.getGlobalScope().getExtension().getCompileOptions();

    AbstractCompilesUtil.configureLanguageLevel(
            javacTask,
            compileOptions,
            scope.getGlobalScope().getExtension().getCompileSdkVersion()
    );

    javacTask.getOptions().setEncoding(compileOptions.getEncoding());

    javacTask.getOptions().setBootClasspath(
            Joiner.on(File.pathSeparator).join(
                    scope.getGlobalScope().getAndroidBuilder().getBootClasspathAsStrings()));
}
 
Example 30
Source Project: gradle-plugins   Source File: MavenPluginPlugin.java    License: MIT License 5 votes vote down vote up
@Override
public void apply(Project project) {
    project.getPlugins().apply(JavaPlugin.class);
    MavenPublishJavaPlugin mavenPublishJavaPlugin = project.getPlugins().apply(MavenPublishJavaPlugin.class);

    // https://github.com/gradle/gradle/issues/10555#issue-492150084
    if (project.getGradle().getGradleVersion().matches("5\\.6(\\.[12])?")) {
        mavenPublishJavaPlugin.getPublication().getPom().withXml(xmlProvider ->
                xmlProvider.asNode().appendNode("packaging", "maven-plugin")
        );
    }
    else {
        mavenPublishJavaPlugin.getPublication().getPom().setPackaging("maven-plugin");
    }

    TaskProvider<GenerateMavenPom> generateMavenPom = project.getTasks().named("generatePomFileForMavenJavaPublication", GenerateMavenPom.class);

    TaskProvider<DescriptorGeneratorTask> descriptorGeneratorTaskProvider = project.getTasks().register("generateMavenPluginDescriptor", DescriptorGeneratorTask.class, generateMavenPluginDescriptor -> {

        generateMavenPluginDescriptor.dependsOn(generateMavenPom);
        generateMavenPluginDescriptor.getPomFile().set(generateMavenPom.get().getDestination());

        generateMavenPluginDescriptor.getOutputDirectory().set(
                project.getLayout().getBuildDirectory().dir("maven-plugin")
        );

        SourceSet main = project.getConvention().getPlugin(JavaPluginConvention.class).getSourceSets().getByName("main");
        generateMavenPluginDescriptor.getSourceDirectories().from(main.getAllJava().getSourceDirectories());
        JavaCompile javaCompile = (JavaCompile) project.getTasks().getByName(main.getCompileJavaTaskName());

        generateMavenPluginDescriptor.getClassesDirectories().from(javaCompile);
        generateMavenPluginDescriptor.getEncoding().convention(javaCompile.getOptions().getEncoding());
    });

    project.getTasks().named(JavaPlugin.PROCESS_RESOURCES_TASK_NAME, ProcessResources.class)
            .configure(processResources -> processResources.from(descriptorGeneratorTaskProvider));
}