Skip to content
Draft
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Stream;

import org.apache.maven.api.JavaToolchain;
import org.apache.maven.api.Project;
import org.apache.maven.api.Session;
import org.apache.maven.api.SessionData;
Expand All @@ -35,6 +36,8 @@
import org.apache.maven.api.di.Inject;
import org.apache.maven.api.di.Named;
import org.apache.maven.api.di.Singleton;
import org.apache.maven.api.model.Build;
import org.apache.maven.api.model.Source;
import org.apache.maven.api.services.Lookup;
import org.apache.maven.api.services.ToolchainFactory;
import org.apache.maven.api.services.ToolchainFactoryException;
Expand Down Expand Up @@ -89,7 +92,21 @@ public Optional<Toolchain> getToolchainFromBuildContext(@Nonnull Session session
throws ToolchainManagerException {
Map<String, Object> context = retrieveContext(session);
ToolchainModel model = (ToolchainModel) context.get("toolchain-" + type);
return Optional.ofNullable(model).flatMap(this::createToolchain);
if (model != null) {
return createToolchain(model);
}

// For JDK type, try auto-selection based on project's target version
if ("jdk".equals(type)) {
Optional<Toolchain> autoSelected = autoSelectJdkToolchain(session);
if (autoSelected.isPresent()) {
// Cache the selection so subsequent calls for this project return the same toolchain
context.put("toolchain-" + type, autoSelected.get().getModel());
}
return autoSelected;
}

return Optional.empty();
}

@Override
Expand All @@ -98,6 +115,130 @@ public void storeToolchainToBuildContext(@Nonnull Session session, @Nonnull Tool
context.put("toolchain-" + toolchain.getType(), toolchain.getModel());
}

/**
* Attempts to automatically select a JDK toolchain when the running JDK
* does not support the project's required {@code --source}/{@code --release} level.
* <p>
* Searches configured toolchains for the newest JDK that supports the required
* source level. If found, emits a warning and returns it.
*/
Optional<Toolchain> autoSelectJdkToolchain(Session session) {
int requiredSourceLevel = getProjectRequiredSourceLevel(session);
logger.debug("Auto-select JDK toolchain: requiredSourceLevel={}", requiredSourceLevel);
if (requiredSourceLevel <= 0) {
return Optional.empty();
}

int runningJdkMajor = getRunningJdkMajor();
logger.debug(
"Auto-select JDK toolchain: runningJdkMajor={}, supportsLevel={}",
runningJdkMajor,
JdkSourceLevelSupport.supportsSourceLevel(runningJdkMajor, requiredSourceLevel));
if (JdkSourceLevelSupport.supportsSourceLevel(runningJdkMajor, requiredSourceLevel)) {
return Optional.empty();
}

// Search available toolchains for a compatible JDK, preferring the newest
List<Toolchain> allToolchains = getToolchains(session, "jdk", null);
Toolchain bestMatch = null;
int bestVersion = 0;

for (Toolchain tc : allToolchains) {
if (tc instanceof JavaToolchain jtc && jtc.getJavaVersion() != null) {
int tcMajor = JdkSourceLevelSupport.normalizeSourceLevel(
jtc.getJavaVersion().toString());
if (tcMajor > 0 && JdkSourceLevelSupport.supportsSourceLevel(tcMajor, requiredSourceLevel)) {
if (tcMajor > bestVersion) {
bestVersion = tcMajor;
bestMatch = tc;
}
}
}
}

if (bestMatch != null) {
JavaToolchain jtc = (JavaToolchain) bestMatch;
logger.warn(
"Project requires --source {} which is not supported by JDK {}.",
requiredSourceLevel,
runningJdkMajor);
logger.warn(
"Automatically selected JDK {} (discovered at {}) for compilation.",
jtc.getJavaVersion(),
jtc.getJavaHome());
logger.warn("To suppress this warning, configure the maven-toolchains-plugin explicitly");
logger.warn("or set <targetVersion> to a value supported by your JDK.");
return Optional.of(bestMatch);
}

return Optional.empty();
}

/**
* Reads the project's required source level from either Model 4.1.0
* {@code <source><targetVersion>} elements or legacy properties
* ({@code maven.compiler.release}, {@code maven.compiler.source}).
*
* @return the required source level as a major version, or {@code -1} if none is specified
*/
int getProjectRequiredSourceLevel(Session session) {
Optional<Project> current = session.getService(Lookup.class).lookupOptional(Project.class);
if (current.isEmpty()) {
return -1;
}

Project project = current.get();

// Check Model 4.1.0 <source><targetVersion> elements
Build build = project.getModel().getBuild();
if (build != null) {
List<Source> sources = build.getSources();
if (sources != null) {
for (Source source : sources) {
String targetVersion = source.getTargetVersion();
if (targetVersion != null && !targetVersion.isEmpty()) {
int level = JdkSourceLevelSupport.normalizeSourceLevel(targetVersion);
if (level > 0) {
return level;
}
}
}
}
}

// Fall back to legacy properties
Map<String, String> properties = project.getModel().getProperties();
if (properties != null) {
// maven.compiler.release takes precedence
String release = properties.get("maven.compiler.release");
if (release != null && !release.isEmpty()) {
int level = JdkSourceLevelSupport.normalizeSourceLevel(release);
if (level > 0) {
return level;
}
}

// Then maven.compiler.source
String source = properties.get("maven.compiler.source");
if (source != null && !source.isEmpty()) {
int level = JdkSourceLevelSupport.normalizeSourceLevel(source);
if (level > 0) {
return level;
}
}
}

return -1;
}

/**
* Returns the major version of the running JDK.
* Extracted as a method so tests can override it.
*/
int getRunningJdkMajor() {
return JdkSourceLevelSupport.getRunningJdkMajor();
}

private Optional<Toolchain> createToolchain(ToolchainModel model) {
String type = Objects.requireNonNull(model.getType(), "model.getType()");
ToolchainFactory factory = factories.get(type);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.maven.impl;

/**
* Utility class for JDK source level compatibility checks.
* <p>
* Maps JDK major versions to their supported {@code --source}/{@code --release} levels,
* based on the javac retirement schedule defined in
* <a href="https://openjdk.org/jeps/182">JEP 182</a> and subsequent JDK releases.
* <p>
* The retirement schedule follows these milestones:
* <ul>
* <li>JDK 9: removed {@code --source 1} through {@code 5}, minimum is {@code 6}</li>
* <li>JDK 12: removed {@code --source 6}, minimum is {@code 7}</li>
* <li>JDK 21: removed {@code --source 7}, minimum is {@code 8}</li>
* </ul>
*/
final class JdkSourceLevelSupport {

private JdkSourceLevelSupport() {}

/**
* Returns the minimum {@code --source} level supported by a given JDK major version.
*
* @param jdkMajor the JDK major version (e.g., {@code 17}, {@code 21})
* @return the minimum supported source level
*/
static int minimumSupportedSourceLevel(int jdkMajor) {
if (jdkMajor <= 8) {
return 1;
}
if (jdkMajor <= 11) {
return 6;
}
if (jdkMajor <= 20) {
return 7;
}
return 8;
}

/**
* Returns whether a given JDK version supports the specified {@code --source} level.
*
* @param jdkMajor the JDK major version
* @param sourceLevel the desired source level
* @return {@code true} if the JDK supports the source level
*/
static boolean supportsSourceLevel(int jdkMajor, int sourceLevel) {
return sourceLevel >= minimumSupportedSourceLevel(jdkMajor) && sourceLevel <= jdkMajor;
}

/**
* Normalizes a source level string to a major version number.
* <p>
* Handles legacy formats:
* <ul>
* <li>{@code "1.5"} → {@code 5}</li>
* <li>{@code "1.8"} → {@code 8}</li>
* <li>{@code "11"} → {@code 11}</li>
* <li>{@code "21.0.1"} → {@code 21}</li>
* </ul>
*
* @param version the source level string
* @return the normalized major version, or {@code -1} if the string cannot be parsed
*/
static int normalizeSourceLevel(String version) {
if (version == null || version.isEmpty()) {
return -1;
}
version = version.trim();
// Handle "1.x" legacy format (e.g., "1.5", "1.8")
if (version.startsWith("1.") && version.length() > 2) {
try {
return Integer.parseInt(version.substring(2));
} catch (NumberFormatException e) {
return -1;
}
}
// Handle dotted versions like "21.0.1" — take the first segment
int dotIndex = version.indexOf('.');
if (dotIndex > 0) {
version = version.substring(0, dotIndex);
}
try {
return Integer.parseInt(version);
} catch (NumberFormatException e) {
return -1;
}
}

/**
* Returns the major version of the currently running JDK.
*
* @return the running JDK major version
*/
static int getRunningJdkMajor() {
return Runtime.version().feature();
}
}
Loading
Loading