Skip to content

Commit

Permalink
Reformat using Palantir formatter
Browse files Browse the repository at this point in the history
  • Loading branch information
Spotless authored and ppkarwasz committed Dec 4, 2023
1 parent b3444bd commit a190ba8
Show file tree
Hide file tree
Showing 22 changed files with 268 additions and 240 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import org.apache.logging.log4j.transform.maven.scan.ClassFileInclusionScanner;
import org.apache.logging.log4j.transform.maven.scan.SimpleInclusionScanner;
import org.apache.logging.log4j.weaver.LocationCacheGenerator;
Expand All @@ -52,7 +51,10 @@
/**
* Generates location information for use with Log4j2.
*/
@Mojo(name = "process-classes", defaultPhase = LifecyclePhase.PROCESS_CLASSES, threadSafe = true,
@Mojo(
name = "process-classes",
defaultPhase = LifecyclePhase.PROCESS_CLASSES,
threadSafe = true,
requiresDependencyResolution = ResolutionScope.COMPILE)
public class LocationMojo extends AbstractMojo {

Expand All @@ -64,7 +66,7 @@ public class LocationMojo extends AbstractMojo {
/**
* The Maven project.
*/
@Parameter( defaultValue = "${project}", readonly = true, required = true )
@Parameter(defaultValue = "${project}", readonly = true, required = true)
private MavenProject project;

/**
Expand Down Expand Up @@ -112,8 +114,8 @@ public void execute() throws MojoExecutionException, MojoFailureException {
final LocationClassConverter converter = new LocationClassConverter(getProjectDependencies());

try {
final Set<Path> staleClassFiles = getClassFileInclusionScanner().getIncludedClassFiles(sourceDirectory,
outputDirectory);
final Set<Path> staleClassFiles =
getClassFileInclusionScanner().getIncludedClassFiles(sourceDirectory, outputDirectory);
staleClassFiles.stream()
.collect(Collectors.groupingBy(LocationCacheGenerator::getCacheClassFile))
.values()
Expand All @@ -126,8 +128,8 @@ public void execute() throws MojoExecutionException, MojoFailureException {
}
}

private void convertClassfiles(List<Path> classFiles, LocationClassConverter converter,
LocationCacheGenerator locationCache) {
private void convertClassfiles(
List<Path> classFiles, LocationClassConverter converter, LocationCacheGenerator locationCache) {
final Path sourceDirectory = this.sourceDirectory.toPath();
classFiles.sort(Path::compareTo);
final ByteArrayOutputStream buf = new ByteArrayOutputStream();
Expand Down Expand Up @@ -185,12 +187,10 @@ private static class WrappedIOException extends RuntimeException {
private WrappedIOException(IOException cause) {
super(cause);
}

}

private void validateLog4jVersion() throws MojoExecutionException {
Artifact log4jApi = project.getArtifacts()
.stream()
Artifact log4jApi = project.getArtifacts().stream()
.filter(a -> LOG4J_GROUP_ID.equals(a.getGroupId()) && LOG4J_API_ARTIFACT_ID.equals(a.getArtifactId()))
.findAny()
.orElseThrow(() -> new MojoExecutionException("Missing `log4j-api` dependency."));
Expand Down Expand Up @@ -221,5 +221,4 @@ private ClassLoader getProjectDependencies() throws MojoExecutionException {
}
return new URLClassLoader(urls.toArray(EMPTY_URL_ARRAY));
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@

import java.nio.file.Path;
import java.util.Set;

import org.apache.logging.log4j.weaver.Constants;

public interface ClassFileInclusionScanner {
Expand All @@ -34,5 +33,4 @@ public interface ClassFileInclusionScanner {
* @return a set of relative paths to file in {@code sourceDir}
*/
Set<Path> getIncludedClassFiles(Path sourceDir, Path targetDir);

}
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.apache.logging.log4j.weaver.LocationCacheGenerator;
import org.apache.maven.plugin.logging.Log;
import org.codehaus.plexus.util.DirectoryScanner;
Expand All @@ -40,12 +39,15 @@ public class SimpleInclusionScanner implements ClassFileInclusionScanner {
private final Log log;

public SimpleInclusionScanner(long lastUpdateWithinMsecs, Log log) {
this(lastUpdateWithinMsecs, Collections.singleton(DEFAULT_INCLUSION_PATTERN),
Collections.singleton(DEFAULT_EXCLUSION_PATTERN), log);
this(
lastUpdateWithinMsecs,
Collections.singleton(DEFAULT_INCLUSION_PATTERN),
Collections.singleton(DEFAULT_EXCLUSION_PATTERN),
log);
}

public SimpleInclusionScanner(long lastUpdateWithinMsecs, Set<String> sourceIncludes, Set<String> sourceExcludes,
Log log) {
public SimpleInclusionScanner(
long lastUpdateWithinMsecs, Set<String> sourceIncludes, Set<String> sourceExcludes, Log log) {
this.lastUpdatedWithinMsecs = lastUpdateWithinMsecs;
this.sourceIncludes = new HashSet<>(sourceIncludes);
this.sourceExcludes = new HashSet<>(sourceExcludes);
Expand All @@ -56,7 +58,8 @@ public SimpleInclusionScanner(long lastUpdateWithinMsecs, Set<String> sourceIncl
public Set<Path> getIncludedClassFiles(Path sourceDir, Path targetDir) {
final Set<Path> potentialSources = scanForSources(sourceDir, sourceIncludes, sourceExcludes);

return potentialSources.stream().filter(source -> isLocationCacheStale(sourceDir, targetDir, source))
return potentialSources.stream()
.filter(source -> isLocationCacheStale(sourceDir, targetDir, source))
.collect(Collectors.toSet());
}

Expand All @@ -70,9 +73,7 @@ private static Set<Path> scanForSources(Path sourceDir, Set<String> sourceInclud
scanner.setExcludes(sourceExcludes.toArray(EMPTY_ARRAY));
scanner.scan();

return Stream.of(scanner.getIncludedFiles())
.map(sourceDir::resolve)
.collect(Collectors.toSet());
return Stream.of(scanner.getIncludedFiles()).map(sourceDir::resolve).collect(Collectors.toSet());
}

private boolean isLocationCacheStale(Path sourceDir, Path targetDir, Path source) {
Expand All @@ -90,5 +91,4 @@ private boolean isLocationCacheStale(Path sourceDir, Path targetDir, Path source
}
return false;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,12 @@
*/
package org.apache.logging.log4j.maven.plugins.shade.transformer;

import static org.apache.commons.io.output.ClosedOutputStream.CLOSED_OUTPUT_STREAM;

import java.io.IOException;
import java.io.OutputStream;

import org.apache.commons.io.output.ProxyOutputStream;

import static org.apache.commons.io.output.ClosedOutputStream.CLOSED_OUTPUT_STREAM;

/**
* Suppress the close of underlying output stream.
*/
Expand All @@ -36,7 +34,6 @@ final class CloseShieldOutputStream extends ProxyOutputStream {
super(out);
}


@Override
public void close() throws IOException {
out.flush();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@
*/
package org.apache.logging.log4j.maven.plugins.shade.transformer;

import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;
import static org.apache.logging.log4j.core.config.plugins.processor.PluginProcessor.PLUGIN_CACHE_FILE;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
Expand All @@ -32,21 +35,15 @@
import java.util.Map.Entry;
import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;

import org.apache.logging.log4j.core.config.plugins.processor.PluginCache;
import org.apache.logging.log4j.core.config.plugins.processor.PluginEntry;
import org.apache.maven.plugins.shade.relocation.Relocator;
import org.apache.maven.plugins.shade.resource.ReproducibleResourceTransformer;

import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;

import static org.apache.logging.log4j.core.config.plugins.processor.PluginProcessor.PLUGIN_CACHE_FILE;

/**
* 'log4j-maven-shade-plugin' transformer implementation.
*/
public class Log4j2PluginCacheFileTransformer
implements ReproducibleResourceTransformer {
public class Log4j2PluginCacheFileTransformer implements ReproducibleResourceTransformer {

/**
* Log4j config files to share across the transformation stages.
Expand All @@ -61,7 +58,6 @@ public class Log4j2PluginCacheFileTransformer
*/
private long youngestTime = 0;


/**
* Default constructor, initializing internal state.
*/
Expand Down Expand Up @@ -93,10 +89,9 @@ public void processResource(String resource, InputStream is, List<Relocator> rel
* @throws IOException thrown by file writing errors
*/
@Override
public void processResource(final String resource,
final InputStream resourceInput,
final List<Relocator> relocators,
final long time) throws IOException {
public void processResource(
final String resource, final InputStream resourceInput, final List<Relocator> relocators, final long time)
throws IOException {
final Path tempFile = Files.createTempFile("Log4j2Plugins", "dat");
Files.copy(resourceInput, tempFile, REPLACE_EXISTING);
tempFiles.add(tempFile);
Expand All @@ -115,24 +110,21 @@ public boolean hasTransformedResource() {
return tempFiles.size() > 0;
}


/**
* Stores all previously collected log4j-cache-files to the target jar.
*
* @param jos jar output
* @throws IOException When the IO blows up
*/
@Override
public void modifyOutputStream(final JarOutputStream jos)
throws IOException {
public void modifyOutputStream(final JarOutputStream jos) throws IOException {
try {
final PluginCache aggregator = new PluginCache();
aggregator.loadCacheFiles(getUrls());
relocatePlugin(tempRelocators, aggregator.getAllCategories());
putJarEntry(jos);
// prevent the aggregator to close the jar output
final CloseShieldOutputStream outputStream =
new CloseShieldOutputStream(jos);
final CloseShieldOutputStream outputStream = new CloseShieldOutputStream(jos);
aggregator.writeCache(outputStream);
} finally {
deleteTempFiles();
Expand All @@ -154,29 +146,25 @@ private Enumeration<URL> getUrls() throws MalformedURLException {
* @param relocators relocators.
* @param aggregatorCategories all categories of the aggregator
*/
/* default */ void relocatePlugin(final List<Relocator> relocators,
Map<String, Map<String, PluginEntry>> aggregatorCategories) {
for (final Entry<String, Map<String, PluginEntry>> categoryEntry
: aggregatorCategories.entrySet()) {
for (final Entry<String, PluginEntry> pluginMapEntry
: categoryEntry.getValue().entrySet()) {
/* default */ void relocatePlugin(
final List<Relocator> relocators, Map<String, Map<String, PluginEntry>> aggregatorCategories) {
for (final Entry<String, Map<String, PluginEntry>> categoryEntry : aggregatorCategories.entrySet()) {
for (final Entry<String, PluginEntry> pluginMapEntry :
categoryEntry.getValue().entrySet()) {
final PluginEntry pluginEntry = pluginMapEntry.getValue();
final String originalClassName = pluginEntry.getClassName();

final Relocator matchingRelocator = findFirstMatchingRelocator(
originalClassName, relocators);
final Relocator matchingRelocator = findFirstMatchingRelocator(originalClassName, relocators);

if (matchingRelocator != null) {
final String newClassName = matchingRelocator
.relocateClass(originalClassName);
final String newClassName = matchingRelocator.relocateClass(originalClassName);
pluginEntry.setClassName(newClassName);
}
}
}
}

private Relocator findFirstMatchingRelocator(final String originalClassName,
final List<Relocator> relocators) {
private Relocator findFirstMatchingRelocator(final String originalClassName, final List<Relocator> relocators) {
Relocator result = null;
for (final Relocator relocator : relocators) {
if (relocator.canRelocateClass(originalClassName)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,14 @@
*/
package org.apache.logging.log4j.maven.plugins.shade.transformer;

import static java.util.Collections.enumeration;
import static java.util.Collections.singletonList;
import static org.apache.logging.log4j.core.config.plugins.processor.PluginProcessor.PLUGIN_CACHE_FILE;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
Expand All @@ -26,7 +34,6 @@
import java.util.jar.JarEntry;
import java.util.jar.JarInputStream;
import java.util.jar.JarOutputStream;

import org.apache.commons.io.IOUtils;
import org.apache.logging.log4j.core.config.plugins.processor.PluginCache;
import org.apache.logging.log4j.core.config.plugins.processor.PluginEntry;
Expand All @@ -36,16 +43,6 @@
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;

import static java.util.Collections.enumeration;
import static java.util.Collections.singletonList;

import static org.apache.logging.log4j.core.config.plugins.processor.PluginProcessor.PLUGIN_CACHE_FILE;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;


final class Log4j2PluginCacheFileTransformerTest {

private static URL pluginUrl;
Expand All @@ -55,7 +52,6 @@ public static void setUp() {
pluginUrl = Log4j2PluginCacheFileTransformerTest.class.getClassLoader().getResource(PLUGIN_CACHE_FILE);
}


@Test
public void testCanTransformResource() {
final Log4j2PluginCacheFileTransformer transformer = new Log4j2PluginCacheFileTransformer();
Expand All @@ -74,14 +70,15 @@ public void test() throws Exception {
assertFalse(transformer.hasTransformedResource());

long expectedYoungestResourceTime = 1605922127000L; // Sat Nov 21 2020 01:28:47
try (InputStream log4jCacheFileInputStream = getClass().getClassLoader()
.getResourceAsStream(PLUGIN_CACHE_FILE)) {
transformer.processResource(PLUGIN_CACHE_FILE, log4jCacheFileInputStream, null, expectedYoungestResourceTime);
try (InputStream log4jCacheFileInputStream =
getClass().getClassLoader().getResourceAsStream(PLUGIN_CACHE_FILE)) {
transformer.processResource(
PLUGIN_CACHE_FILE, log4jCacheFileInputStream, null, expectedYoungestResourceTime);
}
assertTrue(transformer.hasTransformedResource());

try (InputStream log4jCacheFileInputStream = getClass().getClassLoader()
.getResourceAsStream(PLUGIN_CACHE_FILE)) {
try (InputStream log4jCacheFileInputStream =
getClass().getClassLoader().getResourceAsStream(PLUGIN_CACHE_FILE)) {
transformer.processResource(PLUGIN_CACHE_FILE, log4jCacheFileInputStream, null, 2000L);
}
assertTrue(transformer.hasTransformedResource());
Expand All @@ -92,18 +89,19 @@ public void test() throws Exception {
private void assertTransformedCacheFile(
@SuppressWarnings("SameParameterValue") Log4j2PluginCacheFileTransformer transformer,
@SuppressWarnings("SameParameterValue") long expectedTime,
@SuppressWarnings("SameParameterValue") long expectedHash) throws IOException {
@SuppressWarnings("SameParameterValue") long expectedHash)
throws IOException {
final ByteArrayOutputStream jarBuff = new ByteArrayOutputStream();
try(final JarOutputStream out = new JarOutputStream(jarBuff)) {
try (final JarOutputStream out = new JarOutputStream(jarBuff)) {
transformer.modifyOutputStream(out);
}

try(JarInputStream in = new JarInputStream(new ByteArrayInputStream(jarBuff.toByteArray()))) {
for (;;) {
try (JarInputStream in = new JarInputStream(new ByteArrayInputStream(jarBuff.toByteArray()))) {
for (; ; ) {
final JarEntry jarEntry = in.getNextJarEntry();
if(jarEntry == null) {
if (jarEntry == null) {
fail("No expected resource in the output jar");
} else if(jarEntry.getName().equals(PLUGIN_CACHE_FILE)) {
} else if (jarEntry.getName().equals(PLUGIN_CACHE_FILE)) {
assertEquals(expectedTime, jarEntry.getTime());
assertEquals(expectedHash, Arrays.hashCode(IOUtils.toByteArray(in)));
break;
Expand All @@ -112,7 +110,6 @@ private void assertTransformedCacheFile(
}
}


@Test
public void testRelocation() throws IOException {
// test with matching relocator
Expand All @@ -130,7 +127,8 @@ private void testRelocation(final String src, final String pattern, final String

transformer.relocatePlugin(singletonList(log4jRelocator), aggregator.getAllCategories());

for (final Map<String, PluginEntry> pluginEntryMap : aggregator.getAllCategories().values()) {
for (final Map<String, PluginEntry> pluginEntryMap :
aggregator.getAllCategories().values()) {
for (final PluginEntry entry : pluginEntryMap.values()) {
assertTrue(entry.getClassName().startsWith(target));
}
Expand Down
Loading

0 comments on commit a190ba8

Please sign in to comment.