Skip to content

Commit

Permalink
refactor: Replace Plexus AbstractLogEnabled with SLF4J (#343)
Browse files Browse the repository at this point in the history
* refactor: Replace Plexus AbstractLogEnabled with SLF4J

Use this link to re-run the recipe: https://app.moderne.io/builder/P4zH7djn6?organizationId=QXBhY2hlIE1hdmVu

Co-authored-by: Moderne <team@moderne.io>

* Remove calls to `enableLogging` and retain original logger name for scanner

* Apply formatter and fix checkstyle violations

* Fix more checkstyle violations

---------

Co-authored-by: Moderne <team@moderne.io>
timtebeek and TeamModerne authored Dec 12, 2024

Verified

This commit was created on GitHub.com and signed with GitHub’s verified signature.
1 parent bbe34dc commit 301bc33
Showing 7 changed files with 49 additions and 62 deletions.
Original file line number Diff line number Diff line change
@@ -79,14 +79,15 @@
import org.codehaus.plexus.archiver.UnArchiver;
import org.codehaus.plexus.archiver.manager.ArchiverManager;
import org.codehaus.plexus.archiver.manager.NoSuchArchiverException;
import org.codehaus.plexus.logging.AbstractLogEnabled;
import org.codehaus.plexus.util.StringUtils;
import org.eclipse.aether.RepositorySystem;
import org.eclipse.aether.artifact.DefaultArtifact;
import org.eclipse.aether.resolution.ArtifactRequest;
import org.eclipse.aether.resolution.ArtifactResolutionException;
import org.eclipse.aether.resolution.ArtifactResult;
import org.objectweb.asm.Opcodes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
* JavaMojoDescriptorExtractor, a MojoDescriptor extractor to read descriptors from java classes with annotations.
@@ -97,7 +98,8 @@
*/
@Named(JavaAnnotationsMojoDescriptorExtractor.NAME)
@Singleton
public class JavaAnnotationsMojoDescriptorExtractor extends AbstractLogEnabled implements MojoDescriptorExtractor {
public class JavaAnnotationsMojoDescriptorExtractor implements MojoDescriptorExtractor {
private static final Logger LOGGER = LoggerFactory.getLogger(JavaAnnotationsMojoDescriptorExtractor.class);
public static final String NAME = "java-annotations";

private static final GroupKey GROUP_KEY = new GroupKey(GroupKey.JAVA_GROUP, 100);
@@ -448,7 +450,7 @@ private DocletTag findInClassHierarchy(JavaClass javaClass, String tagName) {
} catch (Throwable t) {
str = javaClass.getValue();
}
getLogger().warn("Failed extracting tag '" + tagName + "' from class " + str);
LOGGER.warn("Failed extracting tag '" + tagName + "' from class " + str);
throw (NoClassDefFoundError) new NoClassDefFoundError(e.getMessage()).initCause(e);
}
}
@@ -488,7 +490,7 @@ private Map<String, JavaAnnotatedElement> extractFieldsAnnotations(

return rawParams;
} catch (NoClassDefFoundError e) {
getLogger().warn("Failed extracting parameters from " + javaClass);
LOGGER.warn("Failed extracting parameters from " + javaClass);
throw e;
}
}
@@ -540,7 +542,7 @@ private Map<String, JavaAnnotatedElement> extractMethodsAnnotations(
} catch (Throwable t) {
str = javaClass.getValue();
}
getLogger().warn("Failed extracting methods from " + str);
LOGGER.warn("Failed extracting methods from " + str);
throw (NoClassDefFoundError) new NoClassDefFoundError(e.getMessage()).initCause(e);
}
}
@@ -589,10 +591,10 @@ protected void extendJavaProjectBuilderWithSourcesJar(
} catch (ArtifactResolutionException e) {
String message = "Unable to get sources artifact for " + artifact.getId()
+ ". Some javadoc tags (@since, @deprecated and comments) won't be used";
if (getLogger().isDebugEnabled()) {
getLogger().warn(message, e);
if (LOGGER.isDebugEnabled()) {
LOGGER.warn(message, e);
} else {
getLogger().warn(message);
LOGGER.warn(message);
}
return;
}
Original file line number Diff line number Diff line change
@@ -50,13 +50,14 @@
import org.apache.maven.tools.plugin.extractor.annotations.scanner.visitors.MojoClassVisitor;
import org.apache.maven.tools.plugin.extractor.annotations.scanner.visitors.MojoFieldVisitor;
import org.apache.maven.tools.plugin.extractor.annotations.scanner.visitors.MojoParameterVisitor;
import org.codehaus.plexus.logging.AbstractLogEnabled;
import org.codehaus.plexus.util.DirectoryScanner;
import org.codehaus.plexus.util.StringUtils;
import org.codehaus.plexus.util.reflection.Reflector;
import org.codehaus.plexus.util.reflection.ReflectorException;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.Type;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
* Mojo scanner with java annotations.
@@ -66,7 +67,8 @@
*/
@Named
@Singleton
public class DefaultMojoAnnotationsScanner extends AbstractLogEnabled implements MojoAnnotationsScanner {
public class DefaultMojoAnnotationsScanner implements MojoAnnotationsScanner {
private static final Logger LOGGER = LoggerFactory.getLogger(DefaultMojoAnnotationsScanner.class);
public static final String MVN4_API = "org.apache.maven.api.plugin.annotations.";
public static final String MOJO_V4 = MVN4_API + "Mojo";
public static final String EXECUTE_V4 = MVN4_API + "Execute";
@@ -174,7 +176,7 @@ protected Map<String, MojoAnnotatedClass> scanArchive(File archiveFile, Artifact
}
} catch (IllegalArgumentException e) {
// In case of a class with newer specs an IllegalArgumentException can be thrown
getLogger().error("Failed to analyze " + archiveFile.getAbsolutePath() + "!/" + zipEntryName);
LOGGER.error("Failed to analyze " + archiveFile.getAbsolutePath() + "!/" + zipEntryName);

throw e;
}
@@ -232,17 +234,15 @@ private void analyzeClassStream(
ClassReader rdr = new ClassReader(is);
rdr.accept(mojoClassVisitor, ClassReader.SKIP_FRAMES | ClassReader.SKIP_CODE | ClassReader.SKIP_DEBUG);
} catch (ArrayIndexOutOfBoundsException aiooe) {
getLogger()
.warn(
"Error analyzing class " + file + " in " + source + ": ignoring class",
getLogger().isDebugEnabled() ? aiooe : null);
LOGGER.warn(
"Error analyzing class " + file + " in " + source + ": ignoring class",
LOGGER.isDebugEnabled() ? aiooe : null);
return;
} catch (IllegalArgumentException iae) {
if (iae.getMessage() == null) {
getLogger()
.warn(
"Error analyzing class " + file + " in " + source + ": ignoring class",
getLogger().isDebugEnabled() ? iae : null);
LOGGER.warn(
"Error analyzing class " + file + " in " + source + ": ignoring class",
LOGGER.isDebugEnabled() ? iae : null);
return;
} else {
throw iae;
@@ -259,10 +259,9 @@ private void analyzeClassStream(

if (mojoAnnotatedClass != null) // see MPLUGIN-206 we can have intermediate classes without annotations
{
if (getLogger().isDebugEnabled() && mojoAnnotatedClass.hasAnnotations()) {
getLogger()
.debug("found MojoAnnotatedClass:" + mojoAnnotatedClass.getClassName() + ":"
+ mojoAnnotatedClass);
if (LOGGER.isDebugEnabled() && mojoAnnotatedClass.hasAnnotations()) {
LOGGER.debug(
"found MojoAnnotatedClass:" + mojoAnnotatedClass.getClassName() + ":" + mojoAnnotatedClass);
}
mojoAnnotatedClass.setArtifact(artifact);
mojoAnnotatedClasses.put(mojoAnnotatedClass.getClassName(), mojoAnnotatedClass);
Original file line number Diff line number Diff line change
@@ -35,13 +35,11 @@
import org.apache.maven.tools.plugin.DefaultPluginToolsRequest;
import org.apache.maven.tools.plugin.extractor.ExtractionException;
import org.apache.maven.tools.plugin.extractor.annotations.scanner.DefaultMojoAnnotationsScanner;
import org.codehaus.plexus.logging.Logger;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.mock;

class JavaAnnotationsMojoDescriptorExtractorTest {
@TempDir
@@ -55,7 +53,6 @@ MojoDescriptor extractDescriptorFromMojoClass(Class<? extends AbstractMojo> mojo
Files.copy(sourceClass, targetDir.resolve(sourceClass.getFileName()));
JavaAnnotationsMojoDescriptorExtractor mojoDescriptorExtractor = new JavaAnnotationsMojoDescriptorExtractor();
DefaultMojoAnnotationsScanner scanner = new DefaultMojoAnnotationsScanner();
scanner.enableLogging(mock(Logger.class));
mojoDescriptorExtractor.mojoAnnotationsScanner = scanner;
PluginDescriptor pluginDescriptor = new PluginDescriptor();
MavenProject mavenProject = new MavenProject();
Original file line number Diff line number Diff line change
@@ -37,7 +37,6 @@
import org.apache.maven.tools.plugin.extractor.annotations.ParametersWithGenericsMojo;
import org.apache.maven.tools.plugin.extractor.annotations.datamodel.ComponentAnnotationContent;
import org.apache.maven.tools.plugin.extractor.annotations.datamodel.ParameterAnnotationContent;
import org.codehaus.plexus.logging.Logger;
import org.junit.jupiter.api.Test;

import static org.assertj.core.api.Assertions.assertThat;
@@ -46,7 +45,6 @@
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;

class DefaultMojoAnnotationsScannerTest {
private DefaultMojoAnnotationsScanner scanner = new DefaultMojoAnnotationsScanner();
@@ -58,15 +56,13 @@ void testSkipModuleInfoClassInArchive() throws Exception {

@Test
void testJava8Annotations() throws Exception {
scanner.enableLogging(mock(Logger.class));
scanner.scanArchive(new File("target/test-classes/java8-annotations.jar"), null, false);
}

@Test
void scanDeprecatedMojoAnnotatins() throws ExtractionException, IOException {
File directoryToScan = new File(DeprecatedMojo.class.getResource("").getFile());

scanner.enableLogging(mock(Logger.class));
Map<String, MojoAnnotatedClass> result =
scanner.scanDirectory(directoryToScan, Collections.singletonList("DeprecatedMojo.class"), null, false);

@@ -94,7 +90,6 @@ void scanParametersWithGenerics() throws ExtractionException, IOException {
File directoryToScan =
new File(ParametersWithGenericsMojo.class.getResource("").getFile());

scanner.enableLogging(mock(Logger.class));
Map<String, MojoAnnotatedClass> result = scanner.scanDirectory(
directoryToScan, Collections.singletonList("ParametersWithGenericsMojo**.class"), null, false);

@@ -147,7 +142,6 @@ void scanFooMojoClass() throws Exception {
request.setIncludePatterns(Arrays.asList("**/FooMojo.class"));
request.setProject(new MavenProject());

scanner.enableLogging(mock(Logger.class));
Map<String, MojoAnnotatedClass> mojoAnnotatedClasses = scanner.scan(request);

System.out.println("mojoAnnotatedClasses:" + mojoAnnotatedClasses);
Original file line number Diff line number Diff line change
@@ -30,17 +30,19 @@
import org.apache.maven.plugin.descriptor.MojoDescriptor;
import org.apache.maven.project.MavenProject;
import org.apache.maven.tools.plugin.PluginToolsRequest;
import org.codehaus.plexus.logging.AbstractLogEnabled;
import org.codehaus.plexus.util.DirectoryScanner;
import org.codehaus.plexus.util.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
* @deprecated Scripting support for Mojos is deprecated and is planned to be removed in Maven 4.0
* @author jdcasey
*/
@Deprecated
public abstract class AbstractScriptedMojoDescriptorExtractor extends AbstractLogEnabled
implements MojoDescriptorExtractor {
public abstract class AbstractScriptedMojoDescriptorExtractor implements MojoDescriptorExtractor {
private static final Logger LOGGER = LoggerFactory.getLogger(AbstractScriptedMojoDescriptorExtractor.class);

@Override
public boolean isDeprecated() {
return true;
@@ -50,7 +52,7 @@ public boolean isDeprecated() {
@Override
public List<MojoDescriptor> execute(PluginToolsRequest request)
throws ExtractionException, InvalidPluginDescriptorException {
getLogger().debug("Running: " + getClass().getName());
LOGGER.debug("Running: " + getClass().getName());
String metadataExtension = getMetadataFileExtension(request);
String scriptExtension = getScriptFileExtension(request);

@@ -75,8 +77,8 @@ public List<MojoDescriptor> execute(PluginToolsRequest request)
scriptFilesKeyedByBasedir, project.getBuild().getOutputDirectory(), request);

if (!mojoDescriptors.isEmpty()) {
getLogger().warn("Scripting support for mojos is deprecated and is planned to be removed in Maven 4.");
getLogger().warn("Found " + mojoDescriptors.size() + " scripted mojos.");
LOGGER.warn("Scripting support for mojos is deprecated and is planned to be removed in Maven 4.");
LOGGER.warn("Found " + mojoDescriptors.size() + " scripted mojos.");
}

return mojoDescriptors;
@@ -140,9 +142,8 @@ protected Map<String, Set<File>> gatherFilesByBasedir(
for (String resourceDir : directories) {
Set<File> sources = new HashSet<>();

getLogger()
.debug("Scanning script dir: " + resourceDir + " with extractor: "
+ getClass().getName());
LOGGER.debug("Scanning script dir: " + resourceDir + " with extractor: "
+ getClass().getName());
File dir = new File(resourceDir);
if (!dir.isAbsolute()) {
dir = new File(basedir, resourceDir).getAbsoluteFile();
Original file line number Diff line number Diff line change
@@ -36,15 +36,15 @@
import org.apache.maven.tools.plugin.extractor.GroupKey;
import org.apache.maven.tools.plugin.extractor.MojoDescriptorExtractor;
import org.apache.maven.tools.plugin.extractor.MojoDescriptorExtractorComparator;
import org.codehaus.plexus.logging.AbstractLogEnabled;
import org.codehaus.plexus.logging.Logger;
import org.codehaus.plexus.logging.console.ConsoleLogger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
* @author jdcasey
*/
@Named
public class DefaultMojoScanner extends AbstractLogEnabled implements MojoScanner {
public class DefaultMojoScanner implements MojoScanner {
private static final Logger LOGGER = LoggerFactory.getLogger("standalone-scanner-logger");

private Map<String, MojoDescriptorExtractor> mojoDescriptorExtractors;

@@ -61,8 +61,6 @@ public class DefaultMojoScanner extends AbstractLogEnabled implements MojoScanne
@Inject
public DefaultMojoScanner(Map<String, MojoDescriptorExtractor> extractors) {
this.mojoDescriptorExtractors = extractors;

this.enableLogging(new ConsoleLogger(Logger.LEVEL_INFO, "standalone-scanner-logger"));
}

/**
@@ -78,40 +76,39 @@ public DefaultMojoScanner() {
@Override
public void populatePluginDescriptor(PluginToolsRequest request)
throws ExtractionException, InvalidPluginDescriptorException {
Logger logger = getLogger();

int numMojoDescriptors = 0;

List<MojoDescriptorExtractor> orderedExtractors = getOrderedExtractors();

logger.debug("Using " + orderedExtractors.size() + " mojo extractors.");
LOGGER.debug("Using " + orderedExtractors.size() + " mojo extractors.");

HashMap<String, Integer> groupStats = new HashMap<>();

for (MojoDescriptorExtractor extractor : orderedExtractors) {
GroupKey groupKey = extractor.getGroupKey();
String extractorId = extractor.getName();

logger.debug("Applying " + extractorId + " mojo extractor");
LOGGER.debug("Applying " + extractorId + " mojo extractor");

List<MojoDescriptor> extractorDescriptors = extractor.execute(request);

int extractorDescriptorsCount = extractorDescriptors.size();

logger.info(extractorId + " mojo extractor found " + extractorDescriptorsCount + " mojo descriptor"
LOGGER.info(extractorId + " mojo extractor found " + extractorDescriptorsCount + " mojo descriptor"
+ (extractorDescriptorsCount > 1 ? "s" : "") + ".");
numMojoDescriptors += extractorDescriptorsCount;

if (extractor.isDeprecated() && extractorDescriptorsCount > 0) {
logger.warn("");
logger.warn("Deprecated extractor " + extractorId
LOGGER.warn("");
LOGGER.warn("Deprecated extractor " + extractorId
+ " extracted " + extractorDescriptorsCount
+ " descriptor" + (extractorDescriptorsCount > 1 ? "s" : "")
+ ". Upgrade your Mojo definitions.");
if (GroupKey.JAVA_GROUP.equals(groupKey.getGroup())) {
logger.warn("You should use Mojo Annotations instead of Javadoc tags.");
LOGGER.warn("You should use Mojo Annotations instead of Javadoc tags.");
}
logger.warn("");
LOGGER.warn("");
}

if (groupStats.containsKey(groupKey.getGroup())) {
@@ -121,15 +118,15 @@ public void populatePluginDescriptor(PluginToolsRequest request)
}

for (MojoDescriptor descriptor : extractorDescriptors) {
logger.debug("Adding mojo: " + descriptor + " to plugin descriptor.");
LOGGER.debug("Adding mojo: " + descriptor + " to plugin descriptor.");

descriptor.setPluginDescriptor(request.getPluginDescriptor());

request.getPluginDescriptor().addMojo(descriptor);
}
}

logger.debug("Discovered descriptors by groups: " + groupStats);
LOGGER.debug("Discovered descriptors by groups: " + groupStats);

if (numMojoDescriptors == 0 && !request.isSkipErrorNoDescriptorsFound()) {
throw new InvalidPluginDescriptorException("No mojo definitions were found for plugin: "
Original file line number Diff line number Diff line change
@@ -28,9 +28,6 @@

import org.apache.maven.project.MavenProject;
import org.apache.velocity.VelocityContext;
import org.codehaus.plexus.logging.AbstractLogEnabled;
import org.codehaus.plexus.logging.Logger;
import org.codehaus.plexus.logging.console.ConsoleLogger;
import org.codehaus.plexus.util.io.CachingOutputStream;
import org.codehaus.plexus.velocity.VelocityComponent;

@@ -44,7 +41,7 @@
* @author <a href="mailto:vincent.siveton@gmail.com">Vincent Siveton</a>
* @since 2.4
*/
public class PluginHelpGenerator extends AbstractLogEnabled {
public class PluginHelpGenerator {
/**
* Default generated class name
*/
@@ -60,7 +57,7 @@ public class PluginHelpGenerator extends AbstractLogEnabled {
* Default constructor
*/
public PluginHelpGenerator() {
this.enableLogging(new ConsoleLogger(Logger.LEVEL_INFO, "PluginHelpGenerator"));
// nop
}

// ----------------------------------------------------------------------

0 comments on commit 301bc33

Please sign in to comment.