This is an automated email from the ASF dual-hosted git repository. mbenson pushed a commit to branch master in repository https://gitbox.apache.org/repos/asf/commons-weaver.git
commit 901ba1ae923352168dc5857c3b3d462a915f7e0f Author: Gary D. Gregory <ggreg...@apache.org> AuthorDate: Sun Jan 7 20:53:24 2018 +0000 Java 8; assorted minor refactorings --- BUILDING.txt | 2 +- ant/pom.xml | 1 - .../commons/weaver/ant/AbstractWeaverTask.java | 1 - .../org/apache/commons/weaver/ant/CleanTask.java | 4 +- .../org/apache/commons/weaver/ant/WeaveTask.java | 4 +- .../apache/commons/weaver/ant/WeaverSettings.java | 2 - maven-plugin/pom.xml | 2 +- .../commons/weaver/maven/AbstractCWMojo.java | 12 +- .../commons/weaver/maven/AbstractPrepareMojo.java | 4 +- .../commons/weaver/maven/AbstractWeaveMojo.java | 4 +- .../maven/JavaLoggingToMojoLoggingRedirector.java | 21 +- .../apache/commons/weaver/maven/PrepareMojo.java | 1 - .../commons/weaver/maven/TestPrepareMojo.java | 1 - .../apache/commons/weaver/maven/TestWeaveMojo.java | 1 - .../org/apache/commons/weaver/maven/WeaveMojo.java | 1 - modules/normalizer/pom.xml | 2 - .../commons/weaver/normalizer/Normalizer.java | 65 ++--- .../weaver/normalizer/NormalizerWeaver.java | 1 - .../apache/commons/weaver/normalizer/Utils.java | 9 +- modules/privilizer/weaver/pom.xml | 3 - .../commons/weaver/privilizer/ActionGenerator.java | 8 +- .../weaver/privilizer/BlueprintingVisitor.java | 52 ++-- .../apache/commons/weaver/privilizer/Field.java | 12 +- .../commons/weaver/privilizer/FieldAccess.java | 1 - .../apache/commons/weaver/privilizer/Policy.java | 1 - .../commons/weaver/privilizer/Privilizer.java | 23 +- .../weaver/privilizer/PrivilizerCleaner.java | 11 +- .../weaver/privilizer/PrivilizerWeaver.java | 2 +- .../weaver/privilizer/PrivilizingVisitor.java | 5 +- pom.xml | 9 +- .../org/apache/commons/weaver/CleanProcessor.java | 2 +- .../java/org/apache/commons/weaver/Finder.java | 281 +++++++-------------- .../java/org/apache/commons/weaver/Inflater.java | 88 +++---- .../org/apache/commons/weaver/ProcessorBase.java | 4 +- .../org/apache/commons/weaver/WeaveProcessor.java | 2 +- .../apache/commons/weaver/model/ScanRequest.java | 4 +- .../apache/commons/weaver/model/ScanResult.java | 9 +- .../org/apache/commons/weaver/model/Weavable.java | 2 +- .../apache/commons/weaver/model/WeavableClass.java | 39 +-- .../commons/weaver/model/WeavableConstructor.java | 1 - .../weaver/model/WeavableConstructorParameter.java | 1 - .../commons/weaver/model/WeavableExecutable.java | 3 +- .../commons/weaver/model/WeavableMethod.java | 2 +- .../weaver/model/WeavableMethodParameter.java | 1 - .../commons/weaver/model/WeavablePackage.java | 6 +- .../commons/weaver/model/WeavableParameter.java | 1 - .../commons/weaver/model/WeaveEnvironment.java | 37 +-- .../apache/commons/weaver/model/WeaveInterest.java | 20 +- .../java/org/apache/commons/weaver/utils/Args.java | 1 - .../org/apache/commons/weaver/utils/Providers.java | 33 +-- .../org/apache/commons/weaver/utils/URLArray.java | 60 ++--- 51 files changed, 300 insertions(+), 562 deletions(-) diff --git a/BUILDING.txt b/BUILDING.txt deleted file mode 120000 index 5af3810..0000000 --- a/BUILDING.txt +++ /dev/null @@ -1 +0,0 @@ -src/site/markdown/building.md \ No newline at end of file diff --git a/BUILDING.txt b/BUILDING.txt new file mode 100644 index 0000000..0fcdf1e --- /dev/null +++ b/BUILDING.txt @@ -0,0 +1 @@ +link src/site/markdown/building.md \ No newline at end of file diff --git a/ant/pom.xml b/ant/pom.xml index dd472ae..0db620b 100644 --- a/ant/pom.xml +++ b/ant/pom.xml @@ -111,7 +111,6 @@ under the License. <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-shade-plugin</artifactId> - <version>2.1</version> <executions> <execution> <id>shade</id> diff --git a/ant/src/main/java/org/apache/commons/weaver/ant/AbstractWeaverTask.java b/ant/src/main/java/org/apache/commons/weaver/ant/AbstractWeaverTask.java index fde4f9e..50c66c9 100644 --- a/ant/src/main/java/org/apache/commons/weaver/ant/AbstractWeaverTask.java +++ b/ant/src/main/java/org/apache/commons/weaver/ant/AbstractWeaverTask.java @@ -66,5 +66,4 @@ public abstract class AbstractWeaverTask extends Task { settings.setRefid(new Reference(getProject(), refid)); add(settings); } - } \ No newline at end of file diff --git a/ant/src/main/java/org/apache/commons/weaver/ant/CleanTask.java b/ant/src/main/java/org/apache/commons/weaver/ant/CleanTask.java index a91f9da..1756958 100644 --- a/ant/src/main/java/org/apache/commons/weaver/ant/CleanTask.java +++ b/ant/src/main/java/org/apache/commons/weaver/ant/CleanTask.java @@ -42,9 +42,7 @@ public class CleanTask extends AbstractWeaverTask { public void execute() { try { final WeaverSettings settings = Validate.notNull(getSettings(), "settings"); - final CleanProcessor cleanProcessor = - new CleanProcessor(settings.getClasspathEntries(), settings.getTarget(), settings.getProperties()); - cleanProcessor.clean(); + new CleanProcessor(settings.getClasspathEntries(), settings.getTarget(), settings.getProperties()).clean(); } catch (final Exception e) { throw new BuildException(e); } diff --git a/ant/src/main/java/org/apache/commons/weaver/ant/WeaveTask.java b/ant/src/main/java/org/apache/commons/weaver/ant/WeaveTask.java index 414bfb7..31ab7f4 100644 --- a/ant/src/main/java/org/apache/commons/weaver/ant/WeaveTask.java +++ b/ant/src/main/java/org/apache/commons/weaver/ant/WeaveTask.java @@ -42,9 +42,7 @@ public class WeaveTask extends AbstractWeaverTask { public void execute() { try { final WeaverSettings settings = Validate.notNull(getSettings(), "settings"); - final WeaveProcessor weaveProcessor = - new WeaveProcessor(settings.getClasspathEntries(), settings.getTarget(), settings.getProperties()); - weaveProcessor.weave(); + new WeaveProcessor(settings.getClasspathEntries(), settings.getTarget(), settings.getProperties()).weave(); } catch (final Exception e) { throw new BuildException(e); } diff --git a/ant/src/main/java/org/apache/commons/weaver/ant/WeaverSettings.java b/ant/src/main/java/org/apache/commons/weaver/ant/WeaverSettings.java index 5533f5f..0686e2f 100644 --- a/ant/src/main/java/org/apache/commons/weaver/ant/WeaverSettings.java +++ b/ant/src/main/java/org/apache/commons/weaver/ant/WeaverSettings.java @@ -121,7 +121,6 @@ public class WeaverSettings extends DataType { if (includeSystemClasspath) { path.add(Path.systemClasspath); } - return Arrays.asList(path.list()); } @@ -227,5 +226,4 @@ public class WeaverSettings extends DataType { private WeaverSettings getRef() { return getCheckedRef(WeaverSettings.class, "settings"); } - } \ No newline at end of file diff --git a/maven-plugin/pom.xml b/maven-plugin/pom.xml index 465bc0c..d7ebb30 100644 --- a/maven-plugin/pom.xml +++ b/maven-plugin/pom.xml @@ -35,7 +35,7 @@ under the License. <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.version>3.1.0</maven.version> - <maven.plugin.version>3.1</maven.plugin.version> + <maven.plugin.version>3.5.1</maven.plugin.version> <aether.version>1.1.0</aether.version> </properties> diff --git a/maven-plugin/src/main/java/org/apache/commons/weaver/maven/AbstractCWMojo.java b/maven-plugin/src/main/java/org/apache/commons/weaver/maven/AbstractCWMojo.java index 46f6500..0387719 100755 --- a/maven-plugin/src/main/java/org/apache/commons/weaver/maven/AbstractCWMojo.java +++ b/maven-plugin/src/main/java/org/apache/commons/weaver/maven/AbstractCWMojo.java @@ -23,11 +23,9 @@ import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -import java.util.ArrayList; -import java.util.LinkedHashSet; import java.util.List; import java.util.Properties; -import java.util.Set; +import java.util.stream.Collectors; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.StringUtils; @@ -42,7 +40,6 @@ import org.apache.maven.project.MavenProject; import org.eclipse.aether.RepositorySystem; import org.eclipse.aether.RepositorySystemSession; import org.eclipse.aether.collection.CollectRequest; -import org.eclipse.aether.resolution.ArtifactResult; import org.eclipse.aether.resolution.DependencyRequest; import org.eclipse.aether.resolution.DependencyResolutionException; import org.eclipse.aether.resolution.DependencyResult; @@ -139,11 +136,8 @@ abstract class AbstractCWMojo extends AbstractMojo { repositorySystem.resolveDependencies(repositorySystemSession, new DependencyRequest() .setFilter(new ScopeDependencyFilter(getExcludeScopes())).setCollectRequest(collect)); - final Set<String> result = new LinkedHashSet<String>(); - for (final ArtifactResult artifactResult : dependencyResult.getArtifactResults()) { - result.add(artifactResult.getArtifact().getFile().getAbsolutePath()); - } - return new ArrayList<String>(result); + return dependencyResult.getArtifactResults().stream().map(ar -> ar.getArtifact().getFile().getAbsolutePath()) + .distinct().collect(Collectors.toList()); } private String[] getExcludeScopes() { diff --git a/maven-plugin/src/main/java/org/apache/commons/weaver/maven/AbstractPrepareMojo.java b/maven-plugin/src/main/java/org/apache/commons/weaver/maven/AbstractPrepareMojo.java index 4160648..8555626 100644 --- a/maven-plugin/src/main/java/org/apache/commons/weaver/maven/AbstractPrepareMojo.java +++ b/maven-plugin/src/main/java/org/apache/commons/weaver/maven/AbstractPrepareMojo.java @@ -37,11 +37,9 @@ public abstract class AbstractPrepareMojo extends AbstractCWMojo { return; } try { - final CleanProcessor cleanProcessor = new CleanProcessor(classpath, target, config); - cleanProcessor.clean(); + new CleanProcessor(classpath, target, config).clean(); } catch (Exception e) { throw new MojoExecutionException("cleaning failed due to " + e.getMessage(), e); } } - } diff --git a/maven-plugin/src/main/java/org/apache/commons/weaver/maven/AbstractWeaveMojo.java b/maven-plugin/src/main/java/org/apache/commons/weaver/maven/AbstractWeaveMojo.java index 8af0ab1..6638a2e 100644 --- a/maven-plugin/src/main/java/org/apache/commons/weaver/maven/AbstractWeaveMojo.java +++ b/maven-plugin/src/main/java/org/apache/commons/weaver/maven/AbstractWeaveMojo.java @@ -34,11 +34,9 @@ public abstract class AbstractWeaveMojo extends AbstractCWMojo { protected void doExecute(final File target, final List<String> classpath, final Properties config) throws MojoExecutionException { try { - final WeaveProcessor weaveProcessor = new WeaveProcessor(classpath, target, config); - weaveProcessor.weave(); + new WeaveProcessor(classpath, target, config).weave(); } catch (Exception e) { throw new MojoExecutionException("weaving failed due to " + e.getMessage(), e); } } - } diff --git a/maven-plugin/src/main/java/org/apache/commons/weaver/maven/JavaLoggingToMojoLoggingRedirector.java b/maven-plugin/src/main/java/org/apache/commons/weaver/maven/JavaLoggingToMojoLoggingRedirector.java index 69f5313..4534cec 100644 --- a/maven-plugin/src/main/java/org/apache/commons/weaver/maven/JavaLoggingToMojoLoggingRedirector.java +++ b/maven-plugin/src/main/java/org/apache/commons/weaver/maven/JavaLoggingToMojoLoggingRedirector.java @@ -27,6 +27,7 @@ import java.util.logging.Level; import java.util.logging.LogManager; import java.util.logging.LogRecord; import java.util.logging.Logger; +import java.util.stream.Stream; import org.apache.commons.lang3.ArrayUtils; import org.apache.maven.plugin.MojoExecutionException; @@ -36,7 +37,7 @@ import org.apache.maven.plugin.logging.Log; * This class redirects calls to java.util Logging to Mojo logging. */ public class JavaLoggingToMojoLoggingRedirector { - private final List<Handler> removedHandlers = new ArrayList<Handler>(); + private final List<Handler> removedHandlers = new ArrayList<>(); /** * The Maven mojo logger to delegate messages to. @@ -68,12 +69,10 @@ public class JavaLoggingToMojoLoggingRedirector { if (removedHandlers.isEmpty()) { throw new MojoExecutionException("could not remove any handler. aborting."); } - // add our own activeHandler = new JDKLogHandler(); activeHandler.setLevel(Level.ALL); rootLogger.setLevel(Level.ALL); - rootLogger.addHandler(activeHandler); } catch (Exception exc) { throw new MojoExecutionException("failed to activate the jul logging redirector", exc); @@ -87,15 +86,11 @@ public class JavaLoggingToMojoLoggingRedirector { public void deactivate() { final Logger rootLogger = LogManager.getLogManager().getLogger(""); // remove old handlers - for (final Handler handler : rootLogger.getHandlers()) { - if (handler == activeHandler) { - rootLogger.removeHandler(handler); - } - } - - for (final Handler oldHandler : removedHandlers) { - rootLogger.addHandler(oldHandler); + + if (Stream.of(rootLogger.getHandlers()).anyMatch(h -> h == activeHandler)) { + rootLogger.removeHandler(activeHandler); } + removedHandlers.forEach(rootLogger::addHandler); } private class JDKLogHandler extends Handler { @@ -133,7 +128,6 @@ public class JavaLoggingToMojoLoggingRedirector { private String getMessage(final LogRecord record) { final ResourceBundle bundle = record.getResourceBundle(); - final Object[] params = record.getParameters(); final String message; if (bundle != null && bundle.containsKey(record.getMessage())) { // todo: cannot enforce Locale.ENGLISH here @@ -141,6 +135,7 @@ public class JavaLoggingToMojoLoggingRedirector { } else { message = record.getMessage(); } + final Object[] params = record.getParameters(); if (ArrayUtils.isNotEmpty(params)) { return new MessageFormat(message).format(params); } @@ -156,7 +151,5 @@ public class JavaLoggingToMojoLoggingRedirector { public void close() { // nothing to do } - } - } diff --git a/maven-plugin/src/main/java/org/apache/commons/weaver/maven/PrepareMojo.java b/maven-plugin/src/main/java/org/apache/commons/weaver/maven/PrepareMojo.java index eda7622..810c9f8 100644 --- a/maven-plugin/src/main/java/org/apache/commons/weaver/maven/PrepareMojo.java +++ b/maven-plugin/src/main/java/org/apache/commons/weaver/maven/PrepareMojo.java @@ -49,5 +49,4 @@ public class PrepareMojo extends AbstractPrepareMojo { protected File getTarget() { return target; } - } diff --git a/maven-plugin/src/main/java/org/apache/commons/weaver/maven/TestPrepareMojo.java b/maven-plugin/src/main/java/org/apache/commons/weaver/maven/TestPrepareMojo.java index 849d5e9..79ce5eb 100644 --- a/maven-plugin/src/main/java/org/apache/commons/weaver/maven/TestPrepareMojo.java +++ b/maven-plugin/src/main/java/org/apache/commons/weaver/maven/TestPrepareMojo.java @@ -51,5 +51,4 @@ public class TestPrepareMojo extends AbstractPrepareMojo { protected File getTarget() { return target; } - } diff --git a/maven-plugin/src/main/java/org/apache/commons/weaver/maven/TestWeaveMojo.java b/maven-plugin/src/main/java/org/apache/commons/weaver/maven/TestWeaveMojo.java index db714f6..af5c77d 100644 --- a/maven-plugin/src/main/java/org/apache/commons/weaver/maven/TestWeaveMojo.java +++ b/maven-plugin/src/main/java/org/apache/commons/weaver/maven/TestWeaveMojo.java @@ -60,5 +60,4 @@ public class TestWeaveMojo extends AbstractWeaveMojo { protected File getTarget() { return target; } - } diff --git a/maven-plugin/src/main/java/org/apache/commons/weaver/maven/WeaveMojo.java b/maven-plugin/src/main/java/org/apache/commons/weaver/maven/WeaveMojo.java index a5d37af..ecdc025 100644 --- a/maven-plugin/src/main/java/org/apache/commons/weaver/maven/WeaveMojo.java +++ b/maven-plugin/src/main/java/org/apache/commons/weaver/maven/WeaveMojo.java @@ -50,5 +50,4 @@ public class WeaveMojo extends AbstractWeaveMojo { protected File getTarget() { return target; } - } diff --git a/modules/normalizer/pom.xml b/modules/normalizer/pom.xml index 53a9e77..d27fcd8 100644 --- a/modules/normalizer/pom.xml +++ b/modules/normalizer/pom.xml @@ -120,7 +120,6 @@ under the License. <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-shade-plugin</artifactId> - <version>2.1</version> <executions> <execution> <id>shade</id> @@ -233,7 +232,6 @@ under the License. <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-dependency-plugin</artifactId> - <version>2.10</version> <executions> <execution> <id>it-compile-deps</id> diff --git a/modules/normalizer/src/main/java/org/apache/commons/weaver/normalizer/Normalizer.java b/modules/normalizer/src/main/java/org/apache/commons/weaver/normalizer/Normalizer.java index 0ead390..b469c88 100644 --- a/modules/normalizer/src/main/java/org/apache/commons/weaver/normalizer/Normalizer.java +++ b/modules/normalizer/src/main/java/org/apache/commons/weaver/normalizer/Normalizer.java @@ -30,6 +30,7 @@ import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; +import java.util.stream.Stream; import javax.activation.DataSource; @@ -96,7 +97,7 @@ public class Normalizer { } } - private final MutablePair<String, String> key = new MutablePair<String, String>(); + private final MutablePair<String, String> key = new MutablePair<>(); private final MutableBoolean ignore = new MutableBoolean(false); private final MutableBoolean valid = new MutableBoolean(true); private final MutableBoolean mustRewriteConstructor = new MutableBoolean(false); @@ -262,14 +263,10 @@ public class Normalizer { final DataSource classfile = env.getClassfile(className); env.debug("Writing class %s to %s", className, classfile.getName()); - OutputStream outputStream = null; - try { - outputStream = classfile.getOutputStream(); + try (OutputStream outputStream = classfile.getOutputStream()) { IOUtils.write(bytecode, outputStream); } catch (final IOException e) { throw new RuntimeException(e); - } finally { - IOUtils.closeQuietly(outputStream); } } } @@ -350,15 +347,10 @@ public class Normalizer { * @return {@link Map} of enclosing classname to {@link Map} of internal name to {@link ClassWrapper} */ private Map<String, Map<String, ClassWrapper>> byEnclosingClass(final Set<ClassWrapper> sort) { - final Map<String, Map<String, ClassWrapper>> result = new HashMap<String, Map<String, ClassWrapper>>(); + final Map<String, Map<String, ClassWrapper>> result = new HashMap<>(); for (final ClassWrapper wrapper : sort) { - final String outer = wrapper.wrapped.getEnclosingClass().getName(); - Map<String, ClassWrapper> map = result.get(outer); - if (map == null) { - map = new LinkedHashMap<String, Normalizer.ClassWrapper>(); - result.put(outer, map); - } - map.put(wrapper.wrapped.getName().replace('.', '/'), wrapper); + result.computeIfAbsent(wrapper.wrapped.getEnclosingClass().getName(), k -> new LinkedHashMap<>()) + .put(wrapper.wrapped.getName().replace('.', '/'), wrapper); } return result; } @@ -380,19 +372,15 @@ public class Normalizer { for (final Map.Entry<String, Map<String, ClassWrapper>> entry : byEnclosingClass.entrySet()) { final String outer = entry.getKey(); env.debug("Normalizing %s inner classes of %s", entry.getValue().size(), outer); - final Map<String, String> classMap = new HashMap<String, String>(); + final Map<String, String> classMap = new HashMap<>(); for (final String merged : entry.getValue().keySet()) { classMap.put(merged, target); } final Remapper remapper = new SimpleRemapper(classMap); - InputStream enclosingBytecode = null; - try { - enclosingBytecode = env.getClassfile(outer).getInputStream(); + try (InputStream enclosingBytecode = env.getClassfile(outer).getInputStream()) { final ClassReader reader = new ClassReader(enclosingBytecode); reader.accept(new Remap(new WriteClass(reader), remapper, classMap, entry.getValue()), 0); - } finally { - IOUtils.closeQuietly(enclosingBytecode); } for (final String merged : entry.getValue().keySet()) { if (env.deleteClassfile(merged)) { @@ -422,7 +410,7 @@ public class Normalizer { */ private Set<Class<?>> getBroadlyEligibleSubclasses(final Class<?> supertype, final Scanner scanner) { final ScanResult scanResult = scanner.scan(new ScanRequest().addSupertypes(supertype)); - final Set<Class<?>> result = new LinkedHashSet<Class<?>>(); + final Set<Class<?>> result = new LinkedHashSet<>(); for (final WeavableClass<?> cls : scanResult.getClasses()) { final Class<?> subtype = cls.getTarget(); final IneligibilityReason reason; @@ -464,28 +452,18 @@ public class Normalizer { */ private Map<Pair<String, String>, Set<ClassWrapper>> segregate(final Iterable<Class<?>> subtypes) throws IOException { - final Map<Pair<String, String>, Set<ClassWrapper>> classMap = - new LinkedHashMap<Pair<String, String>, Set<ClassWrapper>>(); + final Map<Pair<String, String>, Set<ClassWrapper>> classMap = new LinkedHashMap<>(); for (final Class<?> subtype : subtypes) { final Inspector inspector = new Inspector(); - InputStream bytecode = null; - try { - bytecode = env.getClassfile(subtype).getInputStream(); + try (InputStream bytecode = env.getClassfile(subtype).getInputStream()) { new ClassReader(bytecode).accept(inspector, 0); - } finally { - IOUtils.closeQuietly(bytecode); } if (inspector.ignore()) { continue; } if (inspector.valid()) { - final Pair<String, String> key = inspector.key(); - Set<ClassWrapper> set = classMap.get(key); - if (set == null) { - set = new LinkedHashSet<ClassWrapper>(); - classMap.put(key, set); - } - set.add(new ClassWrapper(subtype, inspector.mustRewriteConstructor())); + classMap.computeIfAbsent(inspector.key(), k -> new LinkedHashSet<>()) + .add(new ClassWrapper(subtype, inspector.mustRewriteConstructor())); } else { env.debug("%s is ineligible for normalization due to %s", subtype, IneligibilityReason.TOO_BUSY_CONSTRUCTOR); @@ -522,10 +500,7 @@ public class Normalizer { env.debug("Copying class %s to %s", classWrapper.wrapped.getName(), result); - InputStream bytecode = null; - - try { - bytecode = env.getClassfile(classWrapper.wrapped).getInputStream(); + try (InputStream bytecode = env.getClassfile(classWrapper.wrapped).getInputStream()) { final ClassReader reader = new ClassReader(bytecode); final ClassVisitor writeClass = new WriteClass(); @@ -542,7 +517,6 @@ public class Normalizer { final String superName, final String[] interfaces) { supertype = Type.getObjectType(superName); writeClass.visit(version, Opcodes.ACC_PUBLIC, result, signature, superName, interfaces); - visitAnnotation(Type.getType(Marker.class).getDescriptor(), false); } @@ -600,8 +574,6 @@ public class Normalizer { writeClass.visitEnd(); } }, 0); - } finally { - IOUtils.closeQuietly(bytecode); } return result; } @@ -614,13 +586,6 @@ public class Normalizer { */ @SuppressWarnings("PMD.UseVarargs") //varargs not needed here private static Type[] toObjectTypes(final String[] types) { - if (types == null) { - return null; - } - final Type[] result = new Type[types.length]; - for (int i = 0; i < types.length; i++) { - result[i] = Type.getObjectType(types[i]); - } - return result; + return types == null ? null : Stream.of(types).map(Type::getObjectType).toArray(Type[]::new); } } diff --git a/modules/normalizer/src/main/java/org/apache/commons/weaver/normalizer/NormalizerWeaver.java b/modules/normalizer/src/main/java/org/apache/commons/weaver/normalizer/NormalizerWeaver.java index 0b8693a..aa769ac 100644 --- a/modules/normalizer/src/main/java/org/apache/commons/weaver/normalizer/NormalizerWeaver.java +++ b/modules/normalizer/src/main/java/org/apache/commons/weaver/normalizer/NormalizerWeaver.java @@ -35,5 +35,4 @@ public class NormalizerWeaver implements Weaver { public boolean process(final WeaveEnvironment environment, final Scanner scanner) { return new Normalizer(environment).normalize(scanner); } - } diff --git a/modules/normalizer/src/main/java/org/apache/commons/weaver/normalizer/Utils.java b/modules/normalizer/src/main/java/org/apache/commons/weaver/normalizer/Utils.java index 93d1bea..1192694 100644 --- a/modules/normalizer/src/main/java/org/apache/commons/weaver/normalizer/Utils.java +++ b/modules/normalizer/src/main/java/org/apache/commons/weaver/normalizer/Utils.java @@ -27,9 +27,6 @@ import org.apache.commons.lang3.Validate; * Normalization utilities. */ final class Utils { - private Utils() { - } - /** * Validate a package name. * @param pkg to validate @@ -59,7 +56,6 @@ final class Utils { } Validate.isTrue(Character.isJavaIdentifierPart(chr), unexpected, chr, pos, result); } - result = result.replace('.', '/'); final int last = result.length() - 1; if (result.charAt(last) == '/') { @@ -77,7 +73,7 @@ final class Utils { * @return {@link Set} of {@link Class} */ static Set<Class<?>> parseTypes(final String types, final ClassLoader classLoader) { - final Set<Class<?>> result = new LinkedHashSet<Class<?>>(); + final Set<Class<?>> result = new LinkedHashSet<>(); for (final String token : StringUtils.splitByWholeSeparatorPreserveAllTokens(types, ",")) { try { result.add(ClassUtils.getClass(classLoader, token.trim().replace('/', '.'))); @@ -87,4 +83,7 @@ final class Utils { } return result; } + + private Utils() { + } } diff --git a/modules/privilizer/weaver/pom.xml b/modules/privilizer/weaver/pom.xml index 09eeb42..bef4e15 100644 --- a/modules/privilizer/weaver/pom.xml +++ b/modules/privilizer/weaver/pom.xml @@ -41,7 +41,6 @@ under the License. <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-weaver-privilizer-api</artifactId> - <version>${project.version}</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> @@ -90,7 +89,6 @@ under the License. <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-shade-plugin</artifactId> - <version>2.1</version> <executions> <execution> <id>shade</id> @@ -163,7 +161,6 @@ under the License. <plugins> <plugin> <artifactId>maven-invoker-plugin</artifactId> - <version>2.0.0</version> <configuration> <cloneProjectsTo>${project.build.directory}/it</cloneProjectsTo> <settingsFile>src/it/settings.xml</settingsFile> diff --git a/modules/privilizer/weaver/src/main/java/org/apache/commons/weaver/privilizer/ActionGenerator.java b/modules/privilizer/weaver/src/main/java/org/apache/commons/weaver/privilizer/ActionGenerator.java index a30fae8..20f2121 100644 --- a/modules/privilizer/weaver/src/main/java/org/apache/commons/weaver/privilizer/ActionGenerator.java +++ b/modules/privilizer/weaver/src/main/java/org/apache/commons/weaver/privilizer/ActionGenerator.java @@ -157,8 +157,7 @@ class ActionGenerator extends Privilizer.WriteClass implements Builder<Type> { final SignatureVisitor actionImplemented = type.visitInterface(); actionImplemented.visitClassType(actionInterface.getInternalName()); final SignatureVisitor visitTypeArgument = actionImplemented.visitTypeArgument('='); - final SignatureReader result = new SignatureReader(privilizer().wrap(methd.getReturnType()).getDescriptor()); - result.accept(visitTypeArgument); + new SignatureReader(privilizer().wrap(methd.getReturnType()).getDescriptor()).accept(visitTypeArgument); actionImplemented.visitEnd(); final String signature = type.toString(); @@ -194,7 +193,6 @@ class ActionGenerator extends Privilizer.WriteClass implements Builder<Type> { mgen.loadArg(arg++); mgen.putField(action, field.name, field.type); } - mgen.returnValue(); final Label end = mgen.mark(); @@ -219,16 +217,12 @@ class ActionGenerator extends Privilizer.WriteClass implements Builder<Type> { mgen.loadThis(); mgen.getField(action, field.name, field.type); } - mgen.invokeStatic(owner.target, helper); if (methd.getReturnType().getSort() < Type.ARRAY) { mgen.valueOf(methd.getReturnType()); } - mgen.returnValue(); - mgen.endMethod(); } - } diff --git a/modules/privilizer/weaver/src/main/java/org/apache/commons/weaver/privilizer/BlueprintingVisitor.java b/modules/privilizer/weaver/src/main/java/org/apache/commons/weaver/privilizer/BlueprintingVisitor.java index ba2108a..00a7049 100644 --- a/modules/privilizer/weaver/src/main/java/org/apache/commons/weaver/privilizer/BlueprintingVisitor.java +++ b/modules/privilizer/weaver/src/main/java/org/apache/commons/weaver/privilizer/BlueprintingVisitor.java @@ -31,7 +31,6 @@ import java.util.List; import java.util.Map; import java.util.Set; -import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.Validate; import org.apache.commons.lang3.mutable.MutableObject; @@ -54,27 +53,27 @@ import org.objectweb.asm.tree.MethodNode; */ class BlueprintingVisitor extends Privilizer.PrivilizerClassVisitor { - private final Set<Type> blueprintTypes = new HashSet<Type>(); - private final Map<Pair<Type, Method>, MethodNode> blueprintRegistry = new HashMap<Pair<Type, Method>, MethodNode>(); + private final Set<Type> blueprintTypes = new HashSet<>(); + private final Map<Pair<Type, Method>, MethodNode> blueprintRegistry = new HashMap<>(); - private final Map<Pair<Type, Method>, String> importedMethods = new HashMap<Pair<Type, Method>, String>(); + private final Map<Pair<Type, Method>, String> importedMethods = new HashMap<>(); - private final Map<Type, Map<Method, MethodNode>> methodCache = new HashMap<Type, Map<Method, MethodNode>>(); - private final Map<Pair<Type, String>, FieldAccess> fieldAccessMap = new HashMap<Pair<Type, String>, FieldAccess>(); + private final Map<Type, Map<Method, MethodNode>> methodCache = new HashMap<>(); + private final Map<Pair<Type, String>, FieldAccess> fieldAccessMap = new HashMap<>(); - private final ClassVisitor next; + private final ClassVisitor nextVisitor; /** * Create a new {@link BlueprintingVisitor}. * @param privilizer owner - * @param next wrapped + * @param nextVisitor wrapped * @param config annotation */ BlueprintingVisitor(@SuppressWarnings("PMD.UnusedFormalParameter") final Privilizer privilizer, //false positive - final ClassVisitor next, + final ClassVisitor nextVisitor, final Privilizing config) { privilizer.super(new ClassNode(Opcodes.ASM5)); - this.next = next; + this.nextVisitor = nextVisitor; // load up blueprint methods: for (final Privilizing.CallTo callTo : config.value()) { @@ -104,9 +103,8 @@ class BlueprintingVisitor extends Privilizer.PrivilizerClassVisitor { return methodCache.get(type); } final ClassNode classNode = read(type.getClassName()); - final Map<Method, MethodNode> result = new HashMap<Method, MethodNode>(); + final Map<Method, MethodNode> result = new HashMap<>(); - @SuppressWarnings("unchecked") final List<MethodNode> methods = classNode.methods; for (final MethodNode methodNode : methods) { @@ -120,14 +118,10 @@ class BlueprintingVisitor extends Privilizer.PrivilizerClassVisitor { private ClassNode read(final String className) { final ClassNode result = new ClassNode(Opcodes.ASM5); - InputStream bytecode = null; - try { - bytecode = privilizer().env.getClassfile(className).getInputStream(); + try (InputStream bytecode = privilizer().env.getClassfile(className).getInputStream();) { new ClassReader(bytecode).accept(result, ClassReader.SKIP_DEBUG | ClassReader.EXPAND_FRAMES); } catch (final Exception e) { throw new RuntimeException(e); - } finally { - IOUtils.closeQuietly(bytecode); } return result; } @@ -168,10 +162,10 @@ class BlueprintingVisitor extends Privilizer.PrivilizerClassVisitor { final MethodNode source = getMethods(key.getLeft()).get(key.getRight()); @SuppressWarnings("unchecked") - final String[] exceptions = (String[]) source.exceptions.toArray(ArrayUtils.EMPTY_STRING_ARRAY); + final String[] exceptions = ((List<String>) source.exceptions).toArray(ArrayUtils.EMPTY_STRING_ARRAY); // non-public fields accessed - final Set<FieldAccess> fieldAccesses = new LinkedHashSet<FieldAccess>(); + final Set<FieldAccess> fieldAccesses = new LinkedHashSet<>(); source.accept(new MethodVisitor(Opcodes.ASM5) { @Override @@ -192,17 +186,14 @@ class BlueprintingVisitor extends Privilizer.PrivilizerClassVisitor { MethodVisitor mv = new NestedMethodInvocationHandler(withAccessibleAdvice, key.getLeft()); //NOPMD if (!fieldAccesses.isEmpty()) { - // accessesNonPublicFields = true; - mv = new AccessibleAdvisor(mv, access, result, source.desc, new ArrayList<FieldAccess>(fieldAccesses)); + mv = new AccessibleAdvisor(mv, access, result, source.desc, new ArrayList<>(fieldAccesses)); } - source.accept(mv); // private can only be called by other privileged methods, so no need to mark as privileged if (!Modifier.isPrivate(source.access)) { withAccessibleAdvice.visitAnnotation(Type.getType(Privileged.class).getDescriptor(), false).visitEnd(); } - withAccessibleAdvice.accept(this.cv); return result; @@ -212,16 +203,15 @@ class BlueprintingVisitor extends Privilizer.PrivilizerClassVisitor { final Pair<Type, String> key = Pair.of(owner, name); if (!fieldAccessMap.containsKey(key)) { try { - final MutableObject<Type> next = new MutableObject<Type>(owner); - final Deque<Type> stk = new ArrayDeque<Type>(); + final MutableObject<Type> next = new MutableObject<>(owner); + final Deque<Type> stk = new ArrayDeque<>(); while (next.getValue() != null) { stk.push(next.getValue()); - InputStream bytecode = null; - try { - bytecode = privilizer().env.getClassfile(next.getValue().getInternalName()).getInputStream(); + try (InputStream bytecode = + privilizer().env.getClassfile(next.getValue().getInternalName()).getInputStream()) { new ClassReader(bytecode).accept(privilizer().new PrivilizerClassVisitor() { @Override - @SuppressWarnings("PMD.UseVarargs") //overridden method + @SuppressWarnings("PMD.UseVarargs") // overridden method public void visit(final int version, final int access, final String name, final String signature, final String superName, final String[] interfaces) { super.visit(version, access, name, signature, superName, interfaces); @@ -242,8 +232,6 @@ class BlueprintingVisitor extends Privilizer.PrivilizerClassVisitor { return null; } }, ClassReader.SKIP_CODE); - } finally { - IOUtils.closeQuietly(bytecode); } if (fieldAccessMap.containsKey(key)) { break; @@ -260,7 +248,7 @@ class BlueprintingVisitor extends Privilizer.PrivilizerClassVisitor { @Override public void visitEnd() { super.visitEnd(); - ((ClassNode) cv).accept(next); + ((ClassNode) cv).accept(nextVisitor); } private abstract class MethodInvocationHandler extends MethodVisitor { diff --git a/modules/privilizer/weaver/src/main/java/org/apache/commons/weaver/privilizer/Field.java b/modules/privilizer/weaver/src/main/java/org/apache/commons/weaver/privilizer/Field.java index afa5915..8f9965e 100644 --- a/modules/privilizer/weaver/src/main/java/org/apache/commons/weaver/privilizer/Field.java +++ b/modules/privilizer/weaver/src/main/java/org/apache/commons/weaver/privilizer/Field.java @@ -18,7 +18,8 @@ */ package org.apache.commons.weaver.privilizer; -import org.apache.commons.lang3.ObjectUtils; +import java.util.Objects; + import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.Validate; import org.objectweb.asm.Type; @@ -60,7 +61,6 @@ public class Field { * @param obj to check for equality * @return whether equal */ - @SuppressWarnings("deprecation") @Override public boolean equals(final Object obj) { if (obj == this) { @@ -70,7 +70,7 @@ public class Field { return false; } final Field other = (Field) obj; - return StringUtils.equals(other.name, name) && ObjectUtils.equals(other.type, type); + return StringUtils.equals(other.name, name) && Objects.equals(other.type, type); } /** @@ -79,10 +79,6 @@ public class Field { */ @Override public int hashCode() { - int result = 57 << 2; - result |= name.hashCode(); - result <<= 4; - result |= type.hashCode(); - return result; + return Objects.hash(name, type); } } diff --git a/modules/privilizer/weaver/src/main/java/org/apache/commons/weaver/privilizer/FieldAccess.java b/modules/privilizer/weaver/src/main/java/org/apache/commons/weaver/privilizer/FieldAccess.java index ba5554c..cc1542e 100644 --- a/modules/privilizer/weaver/src/main/java/org/apache/commons/weaver/privilizer/FieldAccess.java +++ b/modules/privilizer/weaver/src/main/java/org/apache/commons/weaver/privilizer/FieldAccess.java @@ -67,5 +67,4 @@ public class FieldAccess extends Field { final int result = super.hashCode() << 4; return result | owner.hashCode(); } - } diff --git a/modules/privilizer/weaver/src/main/java/org/apache/commons/weaver/privilizer/Policy.java b/modules/privilizer/weaver/src/main/java/org/apache/commons/weaver/privilizer/Policy.java index cef9344..762e1d9 100644 --- a/modules/privilizer/weaver/src/main/java/org/apache/commons/weaver/privilizer/Policy.java +++ b/modules/privilizer/weaver/src/main/java/org/apache/commons/weaver/privilizer/Policy.java @@ -75,5 +75,4 @@ public enum Policy { public boolean isConditional() { return this == ON_INIT || this == DYNAMIC; } - } \ No newline at end of file diff --git a/modules/privilizer/weaver/src/main/java/org/apache/commons/weaver/privilizer/Privilizer.java b/modules/privilizer/weaver/src/main/java/org/apache/commons/weaver/privilizer/Privilizer.java index ffa839b..d1e7ab4 100644 --- a/modules/privilizer/weaver/src/main/java/org/apache/commons/weaver/privilizer/Privilizer.java +++ b/modules/privilizer/weaver/src/main/java/org/apache/commons/weaver/privilizer/Privilizer.java @@ -110,17 +110,12 @@ public class Privilizer { if (verify) { verify(className, bytecode); } - final DataSource classfile = env.getClassfile(className); env.debug("Writing class %s to resource %s", className, classfile.getName()); - OutputStream outputStream = null; - try { - outputStream = classfile.getOutputStream(); + try (OutputStream outputStream = classfile.getOutputStream()) { IOUtils.write(bytecode, outputStream); } catch (final IOException e) { throw new RuntimeException(e); - } finally { - IOUtils.closeQuietly(outputStream); } } } @@ -201,9 +196,7 @@ public class Privilizer { void blueprint(final Class<?> type, final Privilizing privilizing) { final Object[] args = { type.getName(), privilizing }; env.debug("blueprinting class %s %s", args); - InputStream bytecode = null; - try { - bytecode = env.getClassfile(type).getInputStream(); + try (InputStream bytecode = env.getClassfile(type).getInputStream()) { final ClassReader classReader = new ClassReader(bytecode); ClassVisitor cvr; @@ -214,27 +207,21 @@ public class Privilizer { classReader.accept(cvr, ClassReader.EXPAND_FRAMES); } catch (final Exception e) { throw new RuntimeException(e); - } finally { - IOUtils.closeQuietly(bytecode); } } void privilize(final Class<?> type) { final Object[] args = { type.getName() }; env.debug("privilizing class %s", args); - InputStream bytecode = null; - try { - bytecode = env.getClassfile(type).getInputStream(); + try (InputStream bytecode = env.getClassfile(type).getInputStream()) { final ClassReader classReader = new ClassReader(bytecode); - ClassVisitor cv; //NOPMD + ClassVisitor cv; // NOPMD cv = new WriteClass(classReader, ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS); cv = new PrivilizingVisitor(this, cv); classReader.accept(cv, ClassReader.EXPAND_FRAMES); } catch (final Exception e) { throw new RuntimeException(e); - } finally { - IOUtils.closeQuietly(bytecode); } } @@ -255,7 +242,7 @@ public class Privilizer { Validate.validState(StringUtils.isBlank(error), error); final ClassVisitor checkInnerClasses = new ClassVisitor(Opcodes.ASM5, null) { - final Set<String> innerNames = new HashSet<String>(); + final Set<String> innerNames = new HashSet<>(); @Override public void visitInnerClass(final String name, final String outerName, final String innerName, diff --git a/modules/privilizer/weaver/src/main/java/org/apache/commons/weaver/privilizer/PrivilizerCleaner.java b/modules/privilizer/weaver/src/main/java/org/apache/commons/weaver/privilizer/PrivilizerCleaner.java index 1f6c799..4c45ffa 100644 --- a/modules/privilizer/weaver/src/main/java/org/apache/commons/weaver/privilizer/PrivilizerCleaner.java +++ b/modules/privilizer/weaver/src/main/java/org/apache/commons/weaver/privilizer/PrivilizerCleaner.java @@ -23,7 +23,6 @@ import java.lang.annotation.ElementType; import java.util.ArrayList; import java.util.List; -import org.apache.commons.io.IOUtils; import org.apache.commons.weaver.model.ScanRequest; import org.apache.commons.weaver.model.Scanner; import org.apache.commons.weaver.model.WeavableClass; @@ -43,7 +42,7 @@ public class PrivilizerCleaner implements Cleaner { public boolean clean(final WeaveEnvironment environment, final Scanner scanner) { final Privilizer privilizer = new Privilizer(environment); - final List<String> toDelete = new ArrayList<String>(); + final List<String> toDelete = new ArrayList<>(); final ScanRequest scanRequest = new ScanRequest().add(WeaveInterest.of(Privilized.class, ElementType.TYPE)); @@ -56,13 +55,11 @@ public class PrivilizerCleaner implements Cleaner { final String className = weavableClass.getTarget().getName(); environment.debug("Class %s privilized with %s; deleting.", className, privilizedPolicy); - InputStream bytecode = null; - try { - bytecode = privilizer.env.getClassfile(className).getInputStream(); + try (InputStream bytecode = privilizer.env.getClassfile(className).getInputStream()) { final ClassReader classReader = new ClassReader(bytecode); classReader.accept(new ClassVisitor(Opcodes.ASM5) { @Override - @SuppressWarnings("PMD.UseVarargs") //overridden method + @SuppressWarnings("PMD.UseVarargs") // overridden method public void visit(final int version, final int access, final String name, final String signature, final String superName, final String[] interfaces) { toDelete.add(name); @@ -78,8 +75,6 @@ public class PrivilizerCleaner implements Cleaner { }, ClassReader.SKIP_CODE + ClassReader.SKIP_DEBUG + ClassReader.SKIP_FRAMES); } catch (final Exception e) { throw new RuntimeException(e); - } finally { - IOUtils.closeQuietly(bytecode); } } boolean result = false; diff --git a/modules/privilizer/weaver/src/main/java/org/apache/commons/weaver/privilizer/PrivilizerWeaver.java b/modules/privilizer/weaver/src/main/java/org/apache/commons/weaver/privilizer/PrivilizerWeaver.java index e7e7149..44e53bb 100644 --- a/modules/privilizer/weaver/src/main/java/org/apache/commons/weaver/privilizer/PrivilizerWeaver.java +++ b/modules/privilizer/weaver/src/main/java/org/apache/commons/weaver/privilizer/PrivilizerWeaver.java @@ -38,7 +38,7 @@ public class PrivilizerWeaver implements Weaver { public boolean process(final WeaveEnvironment weaveEnvironment, final Scanner scanner) { final Privilizer privilizer = new Privilizer(weaveEnvironment); - final Set<Class<?>> privilizedTypes = new LinkedHashSet<Class<?>>(); + final Set<Class<?>> privilizedTypes = new LinkedHashSet<>(); // handle blueprints: for (final WeavableClass<?> type : scanner.scan( diff --git a/modules/privilizer/weaver/src/main/java/org/apache/commons/weaver/privilizer/PrivilizingVisitor.java b/modules/privilizer/weaver/src/main/java/org/apache/commons/weaver/privilizer/PrivilizingVisitor.java index ec4374c..8d4c1a5 100644 --- a/modules/privilizer/weaver/src/main/java/org/apache/commons/weaver/privilizer/PrivilizingVisitor.java +++ b/modules/privilizer/weaver/src/main/java/org/apache/commons/weaver/privilizer/PrivilizingVisitor.java @@ -42,7 +42,7 @@ import org.objectweb.asm.commons.StaticInitMerger; * ASM {@link ClassVisitor} to privilize {@link Privileged} methods. */ class PrivilizingVisitor extends Privilizer.PrivilizerClassVisitor { - final Map<Method, String> privilegedMethods = new LinkedHashMap<Method, String>(); + final Map<Method, String> privilegedMethods = new LinkedHashMap<>(); boolean annotated; final Policy policy; final AccessLevel accessLevel; @@ -148,7 +148,6 @@ class PrivilizingVisitor extends Privilizer.PrivilizerClassVisitor { } else { privilizer().env.debug("setting up unconditional privileged execution due to policy %s", policy); } - // generate action: final Type[] ctorArgs; if (instanceMethod) { @@ -190,7 +189,6 @@ class PrivilizingVisitor extends Privilizer.PrivilizerClassVisitor { // throw throwException(); } - // end original method endMethod(); @@ -199,7 +197,6 @@ class PrivilizingVisitor extends Privilizer.PrivilizerClassVisitor { mv.visitCode(); } }; - } @Override diff --git a/pom.xml b/pom.xml index 0503308..c3bf4cc 100644 --- a/pom.xml +++ b/pom.xml @@ -61,8 +61,8 @@ under the License. <!-- most Java-related items are defined in parent/pom.xml; define these here for the animal-sniffer config of commons-parent: --> - <maven.compiler.source>1.6</maven.compiler.source> - <maven.compiler.target>1.6</maven.compiler.target> + <maven.compiler.source>1.8</maven.compiler.source> + <maven.compiler.target>1.8</maven.compiler.target> <ant.version>1.9.4</ant.version> <asm.version>5.1</asm.version> @@ -119,6 +119,11 @@ under the License. </configuration> </plugin> <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-shade-plugin</artifactId> + <version>3.1.1</version> + </plugin> + <plugin> <groupId>org.apache.rat</groupId> <artifactId>apache-rat-plugin</artifactId> <configuration> diff --git a/processor/src/main/java/org/apache/commons/weaver/CleanProcessor.java b/processor/src/main/java/org/apache/commons/weaver/CleanProcessor.java index af4004d..0f9ad99 100644 --- a/processor/src/main/java/org/apache/commons/weaver/CleanProcessor.java +++ b/processor/src/main/java/org/apache/commons/weaver/CleanProcessor.java @@ -62,7 +62,7 @@ public class CleanProcessor extends ProcessorBase<Cleaner> { */ public void clean() { if (!target.exists()) { - log.warning("Target directory " + target + " does not exist; nothing to do!"); + log.warning(() -> String.format("Target directory %s does not exist; nothing to do!", target)); } for (final Cleaner cleaner : providers) { final WeaveEnvironment env = new LocalWeaveEnvironment(target, classLoader, configuration, diff --git a/processor/src/main/java/org/apache/commons/weaver/Finder.java b/processor/src/main/java/org/apache/commons/weaver/Finder.java index f86d60a..548998e 100644 --- a/processor/src/main/java/org/apache/commons/weaver/Finder.java +++ b/processor/src/main/java/org/apache/commons/weaver/Finder.java @@ -33,9 +33,13 @@ import java.util.IdentityHashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.Objects; +import java.util.function.Function; +import java.util.function.Predicate; +import java.util.function.Supplier; +import java.util.stream.Collectors; +import java.util.stream.Stream; -import org.apache.commons.collections4.CollectionUtils; -import org.apache.commons.collections4.Predicate; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.Validate; @@ -63,7 +67,7 @@ class Finder extends AnnotationFinder implements Scanner { private abstract class AnnotationInflater extends AnnotationCapturer { final Class<? extends Annotation> annotationType; - final Map<String, Object> elements = new LinkedHashMap<String, Object>(); + final Map<String, Object> elements = new LinkedHashMap<>(); AnnotationInflater(final String desc, final AnnotationVisitor wrapped) { super(wrapped); @@ -136,7 +140,7 @@ class Finder extends AnnotationFinder implements Scanner { @Override public AnnotationVisitor visitArray(final String name) { final AnnotationCapturer owner = this; - final List<Object> values = new ArrayList<Object>(); + final List<Object> values = new ArrayList<>(); return new AnnotationCapturer(super.visitArray(name)) { @Override @@ -180,18 +184,7 @@ class Finder extends AnnotationFinder implements Scanner { @Override public void visitEnd() { super.visitEnd(); - classfileAnnotationsFor(info).add(inflate()); - } - - private List<Annotation> classfileAnnotationsFor(final Info info) { - synchronized (CLASSFILE_ANNOTATIONS) { - if (!CLASSFILE_ANNOTATIONS.get().containsKey(info)) { - final List<Annotation> result = new ArrayList<Annotation>(); - CLASSFILE_ANNOTATIONS.get().put(info, result); - return result; - } - } - return CLASSFILE_ANNOTATIONS.get().get(info); + CLASSFILE_ANNOTATIONS.get().computeIfAbsent(info, k -> new ArrayList<>()).add(inflate()); } } @@ -361,36 +354,25 @@ class Finder extends AnnotationFinder implements Scanner { public T get() { return target; } - } /** * Helper class for finding elements with annotations (including those with classfile-level retention). */ public final class WithAnnotations { - private static final String INIT = "<init>"; - private WithAnnotations() { } public List<Annotated<Package>> findAnnotatedPackages(final Class<? extends Annotation> annotation) { Finder.this.findAnnotatedPackages(annotation); - final List<Annotated<Package>> result = new ArrayList<Annotated<Package>>(); - for (final Info info : getAnnotationInfos(annotation.getName())) { - if (info instanceof PackageInfo) { - final PackageInfo packageInfo = (PackageInfo) info; - try { - final IncludesClassfile<Package> annotated = - new IncludesClassfile<Package>(packageInfo.get(), classfileAnnotationsFor(packageInfo)); - if (annotated.isAnnotationPresent(annotation)) { - result.add(annotated); - } - } catch (final ClassNotFoundException e) { - continue; - } + + return typed(PackageInfo.class, getAnnotationInfos(annotation.getName())::stream).map(packageInfo -> { + try { + return new IncludesClassfile<>(packageInfo.get(), classfileAnnotationsFor(packageInfo)); + } catch (ClassNotFoundException e) { + return null; } - } - return result; + }).filter(hasAnnotation(annotation)).collect(Collectors.toList()); } /** @@ -405,212 +387,138 @@ class Finder extends AnnotationFinder implements Scanner { public List<Annotated<Class<?>>> findAnnotatedClasses(final Class<? extends Annotation> annotation) { Finder.this.findAnnotatedClasses(annotation); - final List<Annotated<Class<?>>> annotatedClasses = annotate(getAnnotationInfos(annotation.getName())); - CollectionUtils.filter(annotatedClasses, new Predicate<Annotated<Class<?>>>() { - - @Override - public boolean evaluate(final Annotated<Class<?>> annotatedClass) { - return annotatedClass.isAnnotationPresent(annotation); - } - }); - return annotatedClasses; + return annotate(getAnnotationInfos(annotation.getName())).stream().filter(hasAnnotation(annotation)) + .collect(Collectors.toList()); } private List<Annotated<Class<?>>> annotate(final Collection<? extends Info> infos) { - final List<Annotated<Class<?>>> result = new ArrayList<Annotated<Class<?>>>(); - for (final Info info : infos) { - if (info instanceof ClassInfo) { - final ClassInfo classInfo = (ClassInfo) info; - - try { - result - .add(new IncludesClassfile<Class<?>>(classInfo.get(), classfileAnnotationsFor(classInfo))); - } catch (final ClassNotFoundException e) { - continue; - } + return typed(ClassInfo.class, infos::stream).map(classInfo -> { + try { + return new IncludesClassfile<Class<?>>(classInfo.get(), classfileAnnotationsFor(classInfo)); + } catch (ClassNotFoundException e1) { + return null; } - } - return result; + }).filter(Objects::nonNull).collect(Collectors.toList()); } public List<Annotated<Class<?>>> findAssignableTypes(final Class<?> supertype) { - final List<Annotated<Class<?>>> result = new ArrayList<Annotated<Class<?>>>(); - final List<?> assignableTypes; - if (supertype.isInterface()) { - assignableTypes = Finder.this.findImplementations(supertype); - } else { - assignableTypes = Finder.this.findSubclasses(supertype); - } + @SuppressWarnings({ "unchecked", "rawtypes" }) + final List<Class<?>> assignableTypes = (List) (supertype.isInterface() + ? Finder.this.findImplementations(supertype) : Finder.this.findSubclasses(supertype)); - for (final Object object : assignableTypes) { - final ClassInfo classInfo = classInfos.get(((Class<?>) object).getName()); - final IncludesClassfile<Class<?>> annotated; - try { - annotated = new IncludesClassfile<Class<?>>(classInfo.get(), classfileAnnotationsFor(classInfo)); - } catch (final ClassNotFoundException e) { - continue; - } - result.add(annotated); - } - return result; + return assignableTypes.stream().map(Class::getName).map(classInfos::get) + .<IncludesClassfile<Class<?>>> map(classInfo -> { + try { + return new IncludesClassfile<>(classInfo.get(), classfileAnnotationsFor(classInfo)); + } catch (final ClassNotFoundException e) { + return null; + } + }).filter(Objects::nonNull).collect(Collectors.toList()); } public List<Annotated<Method>> findAnnotatedMethods(final Class<? extends Annotation> annotation) { Finder.this.findAnnotatedMethods(annotation); - final List<Annotated<Method>> result = new ArrayList<Annotated<Method>>(); - for (final Info info : getAnnotationInfos(annotation.getName())) { - if (info instanceof MethodInfo) { - final MethodInfo methodInfo = (MethodInfo) info; - if (INIT.equals(methodInfo.getName())) { - continue; - } - IncludesClassfile<Method> annotated; + + return typed(MethodInfo.class, getAnnotationInfos(annotation.getName())::stream).filter(CTOR.negate()) + .map(methodInfo -> { try { - annotated = - new IncludesClassfile<Method>((Method) methodInfo.get(), - classfileAnnotationsFor(methodInfo)); + return new IncludesClassfile<>((Method) methodInfo.get(), + classfileAnnotationsFor(methodInfo)); } catch (final ClassNotFoundException e) { - continue; + return null; } - if (annotated.isAnnotationPresent(annotation)) { - result.add(annotated); - } - } - } - return result; - + }).filter(hasAnnotation(annotation)).collect(Collectors.toList()); } public List<Annotated<Parameter<Method>>> findAnnotatedMethodParameters( final Class<? extends Annotation> annotationType) { Finder.this.findAnnotatedMethodParameters(annotationType); - final List<Annotated<Parameter<Method>>> result = new ArrayList<Annotated<Parameter<Method>>>(); - for (final Info info : getAnnotationInfos(annotationType.getName())) { - if (info instanceof ParameterInfo) { - final ParameterInfo parameterInfo = (ParameterInfo) info; - if (INIT.equals(parameterInfo.getDeclaringMethod().getName())) { - continue; - } - Parameter<Method> parameter; + + return typed(ParameterInfo.class, getAnnotationInfos(annotationType.getName())::stream) + .filter(isCtor(ParameterInfo::getDeclaringMethod).negate()).map(parameterInfo -> { try { @SuppressWarnings("unchecked") - final Parameter<Method> unchecked = (Parameter<Method>) parameterInfo.get(); - parameter = unchecked; + final Parameter<Method> parameter = (Parameter<Method>) parameterInfo.get(); + return new IncludesClassfile<>(parameter, classfileAnnotationsFor(parameterInfo)); } catch (final ClassNotFoundException e) { - continue; - } - final IncludesClassfile<Parameter<Method>> annotated = - new IncludesClassfile<Parameter<Method>>(parameter, classfileAnnotationsFor(parameterInfo)); - if (annotated.isAnnotationPresent(annotationType)) { - result.add(annotated); + return null; } - } - } - return result; + }).filter(hasAnnotation(annotationType)).collect(Collectors.toList()); } public List<Annotated<Constructor<?>>> findAnnotatedConstructors(final Class<? extends Annotation> annotation) { Finder.this.findAnnotatedConstructors(annotation); - final List<Annotated<Constructor<?>>> result = new ArrayList<Annotated<Constructor<?>>>(); - for (final Info info : getAnnotationInfos(annotation.getName())) { - if (info instanceof MethodInfo) { - final MethodInfo methodInfo = (MethodInfo) info; - if (!INIT.equals(methodInfo.getName())) { - continue; - } - final IncludesClassfile<Constructor<?>> annotated; + + return typed(MethodInfo.class, getAnnotationInfos(annotation.getName())::stream).filter(CTOR) + .map(methodInfo -> { try { - annotated = - new IncludesClassfile<Constructor<?>>((Constructor<?>) methodInfo.get(), - classfileAnnotationsFor(methodInfo)); + final IncludesClassfile<Constructor<?>> annotated = new IncludesClassfile<>( + (Constructor<?>) methodInfo.get(), classfileAnnotationsFor(methodInfo)); + return annotated; } catch (final ClassNotFoundException e) { - continue; - } - if (annotated.isAnnotationPresent(annotation)) { - result.add(annotated); + return null; } - } - } - return result; + }).filter(hasAnnotation(annotation)).collect(Collectors.toList()); } public List<Annotated<Parameter<Constructor<?>>>> findAnnotatedConstructorParameters( final Class<? extends Annotation> annotation) { Finder.this.findAnnotatedConstructorParameters(annotation); - final List<Annotated<Parameter<Constructor<?>>>> result = - new ArrayList<Annotated<Parameter<Constructor<?>>>>(); - for (final Info info : getAnnotationInfos(annotation.getName())) { - if (info instanceof ParameterInfo) { - final ParameterInfo parameterInfo = (ParameterInfo) info; - if (!INIT.equals(parameterInfo.getDeclaringMethod().getName())) { - continue; - } - Parameter<Constructor<?>> parameter; + + return typed(ParameterInfo.class, getAnnotationInfos(annotation.getName())::stream) + .filter(isCtor(ParameterInfo::getDeclaringMethod)).map(parameterInfo -> { try { @SuppressWarnings("unchecked") - final Parameter<Constructor<?>> unchecked = (Parameter<Constructor<?>>) parameterInfo.get(); - parameter = unchecked; + final Parameter<Constructor<?>> parameter = (Parameter<Constructor<?>>) parameterInfo.get(); + return new IncludesClassfile<>(parameter, classfileAnnotationsFor(parameterInfo)); } catch (final ClassNotFoundException e) { - continue; + return null; } - final IncludesClassfile<Parameter<Constructor<?>>> annotated = - new IncludesClassfile<Parameter<Constructor<?>>>(parameter, - classfileAnnotationsFor(parameterInfo)); - if (annotated.isAnnotationPresent(annotation)) { - result.add(annotated); - } - } - } - return result; + }).filter(hasAnnotation(annotation)).collect(Collectors.toList()); } public List<Annotated<Field>> findAnnotatedFields(final Class<? extends Annotation> annotation) { Finder.this.findAnnotatedFields(annotation); - final List<Annotated<Field>> result = new ArrayList<Annotated<Field>>(); - for (final Info info : getAnnotationInfos(annotation.getName())) { - if (info instanceof FieldInfo) { - final FieldInfo fieldInfo = (FieldInfo) info; - try { - final IncludesClassfile<Field> annotated = - new IncludesClassfile<Field>((Field) fieldInfo.get(), classfileAnnotationsFor(fieldInfo)); - if (annotated.isAnnotationPresent(annotation)) { - result.add(annotated); - } - } catch (final ClassNotFoundException e) { - continue; - } + + return typed(FieldInfo.class, getAnnotationInfos(annotation.getName())::stream).map(fieldInfo -> { + try { + return new IncludesClassfile<>((Field) fieldInfo.get(), classfileAnnotationsFor(fieldInfo)); + } catch (final ClassNotFoundException e) { + return null; } - } - return result; + }).filter(hasAnnotation(annotation)).collect(Collectors.toList()); } private List<Annotation> classfileAnnotationsFor(final Info info) { - synchronized (classfileAnnotations) { - if (!classfileAnnotations.containsKey(info)) { - final List<Annotation> result = new ArrayList<Annotation>(); - classfileAnnotations.put(info, result); - return result; - } - } - return classfileAnnotations.get(info); + return classfileAnnotations.computeIfAbsent(info, k -> new ArrayList<>()); } - } private static final int ASM_FLAGS = ClassReader.SKIP_CODE + ClassReader.SKIP_DEBUG + ClassReader.SKIP_FRAMES; + private static final String INIT = "<init>"; + + private static final Predicate<MethodInfo> CTOR = methodInfo -> INIT.equals(methodInfo.getName()); + /** * The {@link #classfileAnnotations} member stores these; however the scanning takes place in the scope of the super * constructor call, thus there is no opportunity to set the reference beforehand. To work around this, we use a * static ThreadLocal with an initializer and pull/clear its value when we return from the super constructor. :P */ private static final ThreadLocal<Map<Info, List<Annotation>>> CLASSFILE_ANNOTATIONS = - new ThreadLocal<Map<Info, List<Annotation>>>() { - @Override - protected Map<Info, List<Annotation>> initialValue() { - return new IdentityHashMap<AnnotationFinder.Info, List<Annotation>>(); - } - }; + ThreadLocal.withInitial(IdentityHashMap::new); + + private static <T, U> Stream<U> typed(Class<U> type, Supplier<Stream<T>> stream) { + return stream.get().filter(type::isInstance).map(type::cast); + } + + private static Predicate<Annotated<?>> hasAnnotation(Class<? extends Annotation> annotation) { + return annotated -> annotated != null && annotated.isAnnotationPresent(annotation); + } + + private static <T> Predicate<T> isCtor(Function<? super T, MethodInfo> xform) { + return t -> CTOR.test(xform.apply(t)); + } private final WithAnnotations withAnnotations = new WithAnnotations(); private final Map<Info, List<Annotation>> classfileAnnotations; @@ -643,8 +551,7 @@ class Finder extends AnnotationFinder implements Scanner { @Override protected void readClassDef(final InputStream bytecode) throws IOException { try { - final ClassReader classReader = new ClassReader(bytecode); - classReader.accept(new Visitor(new InfoBuildingVisitor()), ASM_FLAGS); + new ClassReader(bytecode).accept(new Visitor(new InfoBuildingVisitor()), ASM_FLAGS); } finally { bytecode.close(); } @@ -737,11 +644,9 @@ class Finder extends AnnotationFinder implements Scanner { break; } } - for (final Class<?> supertype : request.getSupertypes()) { - for (final Annotated<Class<?>> type : this.withAnnotations().findAssignableTypes(supertype)) { - result.getWeavable(type.get()).addAnnotations(type.getAnnotations()); - } - } + request.getSupertypes().stream().map(this.withAnnotations()::findAssignableTypes) + .flatMap(Collection::stream) + .forEach(type -> result.getWeavable(type.get()).addAnnotations(type.getAnnotations())); } return inflater.inflate(result); } diff --git a/processor/src/main/java/org/apache/commons/weaver/Inflater.java b/processor/src/main/java/org/apache/commons/weaver/Inflater.java index 0b1dae4..c5b6137 100644 --- a/processor/src/main/java/org/apache/commons/weaver/Inflater.java +++ b/processor/src/main/java/org/apache/commons/weaver/Inflater.java @@ -19,9 +19,10 @@ package org.apache.commons.weaver; import java.lang.annotation.Annotation; -import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.function.Predicate; +import java.util.stream.Collectors; import org.apache.commons.weaver.model.ScanResult; import org.apache.commons.weaver.model.WeavableClass; @@ -43,7 +44,7 @@ import org.apache.xbean.finder.Parameter; * Adds all classfile annotations to a ScanResult. */ class Inflater { - private class InfoMatcher { + private class InfoMatcher implements Predicate<Info> { final Class<? extends Info> type; InfoMatcher(final Class<? extends Info> type) { @@ -51,10 +52,9 @@ class Inflater { this.type = type; } - boolean test(final Info info) { + public boolean test(final Info info) { return type.isInstance(info); } - } private class MethodMatcher extends InfoMatcher { @@ -66,7 +66,7 @@ class Inflater { } @Override - boolean test(final Info info) { + public boolean test(final Info info) { return super.test(info) && ((MethodInfo) info).isConstructor() == isCtor; } } @@ -80,7 +80,7 @@ class Inflater { } @Override - boolean test(final Info info) { + public boolean test(final Info info) { return super.test(info) && ((ParameterInfo) info).getDeclaringMethod().isConstructor() == isCtor; } } @@ -107,94 +107,82 @@ class Inflater { static <I extends Info> Map<I, List<Annotation>> subMap(final Map<Info, List<Annotation>> source, final InfoMatcher matcher) { - final HashMap<I, List<Annotation>> result = new HashMap<I, List<Annotation>>(); - for (final Map.Entry<Info, List<Annotation>> entry : source.entrySet()) { - if (matcher.test(entry.getKey())) { - @SuppressWarnings("unchecked") - final I key = (I) entry.getKey(); - result.put(key, entry.getValue()); - } - } + @SuppressWarnings("unchecked") + final Map<I, List<Annotation>> result = source.entrySet().stream().filter(e -> matcher.test(e.getKey())) + .collect(Collectors.toMap(t -> (I) t.getKey(), Map.Entry::getValue)); + return result; } ScanResult inflate(final ScanResult scanResult) { for (final WeavablePackage pkg : scanResult.getPackages()) { - for (final Map.Entry<PackageInfo, List<Annotation>> entry : packageAnnotations.entrySet()) { - if (entry.getKey().getName().equals(pkg.getTarget().getName())) { - pkg.addAnnotations(entry.getValue()); + packageAnnotations.forEach((k, v) -> { + if (k.getName().equals(pkg.getTarget().getName())) { + pkg.addAnnotations(v); } - } + }); for (final WeavableClass<?> cls : pkg.getClasses()) { - for (final Map.Entry<ClassInfo, List<Annotation>> entry : classAnnotations.entrySet()) { - if (entry.getKey().getName().equals(cls.getTarget().getName())) { - cls.addAnnotations(entry.getValue()); + classAnnotations.forEach((k, v) -> { + if (k.getName().equals(cls.getTarget().getName())) { + cls.addAnnotations(v); } - } + }); for (final WeavableField<?> fld : cls.getFields()) { - for (final Map.Entry<FieldInfo, List<Annotation>> entry : fieldAnnotations.entrySet()) { + fieldAnnotations.forEach((k, v) -> { try { - if (entry.getKey().get().equals(fld.getTarget())) { - fld.addAnnotations(entry.getValue()); + if (k.get().equals(fld.getTarget())) { + fld.addAnnotations(v); } } catch (final ClassNotFoundException cnfe) { - continue; } - } + }); } for (final WeavableConstructor<?> ctor : cls.getConstructors()) { - for (final Map.Entry<MethodInfo, List<Annotation>> entry : ctorAnnotations.entrySet()) { + ctorAnnotations.forEach((k, v) -> { try { - if (entry.getKey().get().equals(ctor.getTarget())) { - ctor.addAnnotations(entry.getValue()); + if (k.get().equals(ctor.getTarget())) { + ctor.addAnnotations(v); } } catch (final ClassNotFoundException cnfe) { - continue; } - } + }); for (final WeavableConstructorParameter<?> param : ctor.getParameters()) { - for (final Map.Entry<ParameterInfo, List<Annotation>> entry : ctorParameterAnnotations - .entrySet()) { + ctorParameterAnnotations.forEach((k, v) -> { try { - final Parameter<?> parameter = entry.getKey().get(); + final Parameter<?> parameter = k.get(); if (parameter.getDeclaringExecutable().equals(ctor.getTarget()) && param.getTarget().intValue() == parameter.getIndex()) { - param.addAnnotations(entry.getValue()); + param.addAnnotations(v); } } catch (final ClassNotFoundException cnfe) { - continue; } - } + }); } } for (final WeavableMethod<?> methd : cls.getMethods()) { - for (final Map.Entry<MethodInfo, List<Annotation>> entry : methodAnnotations.entrySet()) { + methodAnnotations.forEach((k, v) -> { try { - if (entry.getKey().get().equals(methd.getTarget())) { - methd.addAnnotations(entry.getValue()); + if (k.get().equals(methd.getTarget())) { + methd.addAnnotations(v); } } catch (final ClassNotFoundException cnfe) { - continue; } - } + }); for (final WeavableMethodParameter<?> param : methd.getParameters()) { - for (final Map.Entry<ParameterInfo, List<Annotation>> entry : methodParameterAnnotations - .entrySet()) { + methodParameterAnnotations.forEach((k, v) -> { try { - final Parameter<?> parameter = entry.getKey().get(); + final Parameter<?> parameter = k.get(); if (parameter.getDeclaringExecutable().equals(methd.getTarget()) && param.getTarget().intValue() == parameter.getIndex()) { - param.addAnnotations(entry.getValue()); + param.addAnnotations(v); } } catch (final ClassNotFoundException cnfe) { - continue; } - } + }); } } } } return scanResult; } - } diff --git a/processor/src/main/java/org/apache/commons/weaver/ProcessorBase.java b/processor/src/main/java/org/apache/commons/weaver/ProcessorBase.java index 1248821..ee449ac 100755 --- a/processor/src/main/java/org/apache/commons/weaver/ProcessorBase.java +++ b/processor/src/main/java/org/apache/commons/weaver/ProcessorBase.java @@ -52,7 +52,7 @@ class ProcessorBase<P extends WeaveLifecycleProvider<?>> { */ static <T> Iterable<T> getServiceInstances(final Class<T> type) { Validate.notNull(type); - final List<T> result = new ArrayList<T>(); + final List<T> result = new ArrayList<>(); final ClassLoader typeLoader = type.getClassLoader(); if (!Thread.currentThread().getContextClassLoader().equals(typeLoader)) { for (final T t : ServiceLoader.load(type, typeLoader)) { @@ -120,7 +120,7 @@ class ProcessorBase<P extends WeaveLifecycleProvider<?>> { } private ClassLoader createClassLoader() { - final Set<String> finderClasspath = new LinkedHashSet<String>(); + final Set<String> finderClasspath = new LinkedHashSet<>(); finderClasspath.add(target.getAbsolutePath()); finderClasspath.addAll(classpath); return new URLClassLoader(URLArray.fromPaths(finderClasspath)); diff --git a/processor/src/main/java/org/apache/commons/weaver/WeaveProcessor.java b/processor/src/main/java/org/apache/commons/weaver/WeaveProcessor.java index d77dd93..5624c4e 100644 --- a/processor/src/main/java/org/apache/commons/weaver/WeaveProcessor.java +++ b/processor/src/main/java/org/apache/commons/weaver/WeaveProcessor.java @@ -62,7 +62,7 @@ public class WeaveProcessor extends ProcessorBase<Weaver> { */ public void weave() { if (!target.exists()) { - log.warning("Target directory " + target + " does not exist; nothing to do!"); + log.warning(() -> String.format("Target directory %s does not exist; nothing to do!", target)); } for (final Weaver weaver : providers) { final WeaveEnvironment env = new LocalWeaveEnvironment(target, classLoader, configuration, diff --git a/processor/src/main/java/org/apache/commons/weaver/model/ScanRequest.java b/processor/src/main/java/org/apache/commons/weaver/model/ScanRequest.java index 06638b4..1c4cb17 100644 --- a/processor/src/main/java/org/apache/commons/weaver/model/ScanRequest.java +++ b/processor/src/main/java/org/apache/commons/weaver/model/ScanRequest.java @@ -35,8 +35,8 @@ import org.apache.commons.weaver.spi.Weaver; */ public class ScanRequest { - private final List<WeaveInterest> interests = new ArrayList<WeaveInterest>(); - private final Set<Class<?>> supertypes = new LinkedHashSet<Class<?>>(); + private final List<WeaveInterest> interests = new ArrayList<>(); + private final Set<Class<?>> supertypes = new LinkedHashSet<>(); /** * Register a {@link WeaveInterest}. diff --git a/processor/src/main/java/org/apache/commons/weaver/model/ScanResult.java b/processor/src/main/java/org/apache/commons/weaver/model/ScanResult.java index fdaf892..7f3ce0e 100644 --- a/processor/src/main/java/org/apache/commons/weaver/model/ScanResult.java +++ b/processor/src/main/java/org/apache/commons/weaver/model/ScanResult.java @@ -111,7 +111,7 @@ public class ScanResult { @Override public AnnotatedElements<CHILD> with(final Class<? extends Annotation> annotationType) { - return new AnnotatedWith<CHILD>(this, annotationType); + return new AnnotatedWith<>(this, annotationType); } } @@ -167,13 +167,13 @@ public class ScanResult { @Override public AnnotatedElements<W> with(final Class<? extends Annotation> annotationType) { - return new AnnotatedWith<W>(this, annotationType); + return new AnnotatedWith<>(this, annotationType); } } private final ConcurrentNavigableMap<String, WeavablePackage> packages = - new ConcurrentSkipListMap<String, WeavablePackage>(); + new ConcurrentSkipListMap<>(); /** * Public for use by {@link WeaveProcessor}. @@ -242,7 +242,7 @@ public class ScanResult { @Override public AnnotatedElements<WeavablePackage> with(final Class<? extends Annotation> annotationType) { - return new AnnotatedWith<WeavablePackage>(packages.values(), annotationType); + return new AnnotatedWith<>(packages.values(), annotationType); } }; } @@ -400,5 +400,4 @@ public class ScanResult { } }; } - } diff --git a/processor/src/main/java/org/apache/commons/weaver/model/Weavable.java b/processor/src/main/java/org/apache/commons/weaver/model/Weavable.java index fb756ca..37bc4b1 100644 --- a/processor/src/main/java/org/apache/commons/weaver/model/Weavable.java +++ b/processor/src/main/java/org/apache/commons/weaver/model/Weavable.java @@ -74,7 +74,7 @@ public abstract class Weavable<SELF extends Weavable<SELF, TARGET>, TARGET> impl } synchronized (this) { if (annotations == null) { - annotations = new LinkedHashSet<Annotation>(); + annotations = new LinkedHashSet<>(); } boolean result = false; for (final Annotation ann : toAdd) { diff --git a/processor/src/main/java/org/apache/commons/weaver/model/WeavableClass.java b/processor/src/main/java/org/apache/commons/weaver/model/WeavableClass.java index 38f579e..9d78a7a 100644 --- a/processor/src/main/java/org/apache/commons/weaver/model/WeavableClass.java +++ b/processor/src/main/java/org/apache/commons/weaver/model/WeavableClass.java @@ -22,7 +22,6 @@ import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.Collections; -import java.util.Comparator; import java.util.concurrent.ConcurrentNavigableMap; import java.util.concurrent.ConcurrentSkipListMap; @@ -34,26 +33,15 @@ import org.apache.commons.weaver.utils.Args; * @param <T> type */ public class WeavableClass<T> extends NestedWeavable<WeavableClass<T>, Class<T>, WeavablePackage, Package> { - private final ConcurrentNavigableMap<String, WeavableField<T>> fields = - new ConcurrentSkipListMap<String, WeavableField<T>>(); + private final ConcurrentNavigableMap<String, WeavableField<T>> fields = new ConcurrentSkipListMap<>(); - private final ConcurrentNavigableMap<Constructor<T>, WeavableConstructor<T>> ctors = - new ConcurrentSkipListMap<Constructor<T>, WeavableConstructor<T>>(new Comparator<Constructor<?>>() { - - @Override - public int compare(final Constructor<?> ctor1, final Constructor<?> ctor2) { - return Args.compare(ctor1.getParameterTypes(), ctor2.getParameterTypes()); - } - }); + private final ConcurrentNavigableMap<Constructor<T>, WeavableConstructor<T>> ctors = new ConcurrentSkipListMap<>( + (ctor1, ctor2) -> Args.compare(ctor1.getParameterTypes(), ctor2.getParameterTypes())); private final ConcurrentNavigableMap<Method, WeavableMethod<T>> methods = - new ConcurrentSkipListMap<Method, WeavableMethod<T>>(new Comparator<Method>() { - - @Override - public int compare(final Method methd1, final Method methd2) { - final int result = methd1.getName().compareTo(methd2.getName()); - return result == 0 ? Args.compare(methd1.getParameterTypes(), methd2.getParameterTypes()) : result; - } + new ConcurrentSkipListMap<>((methd1, methd2) -> { + final int result = methd1.getName().compareTo(methd2.getName()); + return result == 0 ? Args.compare(methd1.getParameterTypes(), methd2.getParameterTypes()) : result; }); /** @@ -73,10 +61,9 @@ public class WeavableClass<T> extends NestedWeavable<WeavableClass<T>, Class<T>, public WeavableField<T> getWeavable(final Field fld) { final String key = fld.getName(); if (fields.containsKey(key)) { - final WeavableField<T> result = fields.get(key); - return result; + return fields.get(key); } - final WeavableField<T> result = new WeavableField<T>(fld, this); + final WeavableField<T> result = new WeavableField<>(fld, this); final WeavableField<T> faster = fields.putIfAbsent(key, result); return faster == null ? result : faster; } @@ -88,10 +75,9 @@ public class WeavableClass<T> extends NestedWeavable<WeavableClass<T>, Class<T>, */ public WeavableMethod<T> getWeavable(final Method methd) { if (methods.containsKey(methd)) { - final WeavableMethod<T> result = methods.get(methd); - return result; + return methods.get(methd); } - final WeavableMethod<T> result = new WeavableMethod<T>(methd, this); + final WeavableMethod<T> result = new WeavableMethod<>(methd, this); final WeavableMethod<T> faster = methods.putIfAbsent(methd, result); return faster == null ? result : faster; } @@ -103,10 +89,9 @@ public class WeavableClass<T> extends NestedWeavable<WeavableClass<T>, Class<T>, */ public WeavableConstructor<T> getWeavable(final Constructor<T> ctor) { if (ctors.containsKey(ctor)) { - final WeavableConstructor<T> result = ctors.get(ctor); - return result; + return ctors.get(ctor); } - final WeavableConstructor<T> result = new WeavableConstructor<T>(ctor, this); + final WeavableConstructor<T> result = new WeavableConstructor<>(ctor, this); final WeavableConstructor<T> faster = ctors.putIfAbsent(ctor, result); return faster == null ? result : faster; } diff --git a/processor/src/main/java/org/apache/commons/weaver/model/WeavableConstructor.java b/processor/src/main/java/org/apache/commons/weaver/model/WeavableConstructor.java index 79c1cb0..1a75c7b 100644 --- a/processor/src/main/java/org/apache/commons/weaver/model/WeavableConstructor.java +++ b/processor/src/main/java/org/apache/commons/weaver/model/WeavableConstructor.java @@ -52,5 +52,4 @@ public class WeavableConstructor<T> extends protected WeavableConstructorParameter<T> createParameter(final int index) { return new WeavableConstructorParameter<T>(Integer.valueOf(index), this); } - } diff --git a/processor/src/main/java/org/apache/commons/weaver/model/WeavableConstructorParameter.java b/processor/src/main/java/org/apache/commons/weaver/model/WeavableConstructorParameter.java index 5ca5cc9..0b5c3d8 100644 --- a/processor/src/main/java/org/apache/commons/weaver/model/WeavableConstructorParameter.java +++ b/processor/src/main/java/org/apache/commons/weaver/model/WeavableConstructorParameter.java @@ -36,5 +36,4 @@ public class WeavableConstructorParameter<T> extends public WeavableConstructorParameter(final Integer target, final WeavableConstructor<T> parent) { super(target, parent); } - } diff --git a/processor/src/main/java/org/apache/commons/weaver/model/WeavableExecutable.java b/processor/src/main/java/org/apache/commons/weaver/model/WeavableExecutable.java index 4a8b90f..d7df972 100644 --- a/processor/src/main/java/org/apache/commons/weaver/model/WeavableExecutable.java +++ b/processor/src/main/java/org/apache/commons/weaver/model/WeavableExecutable.java @@ -49,7 +49,7 @@ public abstract class WeavableExecutable */ protected WeavableExecutable(final TARGET target, final WeavableClass<T> parent) { super(target, parent); - final List<P> params = new ArrayList<P>(); + final List<P> params = new ArrayList<>(); final int paramCount = getParameterTypes().length; for (int i = 0; i < paramCount; i++) { params.add(createParameter(i)); @@ -94,5 +94,4 @@ public abstract class WeavableExecutable public Iterable<P> getParameters() { return parameters; } - } diff --git a/processor/src/main/java/org/apache/commons/weaver/model/WeavableMethod.java b/processor/src/main/java/org/apache/commons/weaver/model/WeavableMethod.java index eb79dec..1c80853 100644 --- a/processor/src/main/java/org/apache/commons/weaver/model/WeavableMethod.java +++ b/processor/src/main/java/org/apache/commons/weaver/model/WeavableMethod.java @@ -58,6 +58,6 @@ public class WeavableMethod<T> extends WeavableExecutable<WeavableMethod<T>, Met */ @Override protected WeavableMethodParameter<T> createParameter(final int index) { - return new WeavableMethodParameter<T>(Integer.valueOf(index), this); + return new WeavableMethodParameter<>(Integer.valueOf(index), this); } } diff --git a/processor/src/main/java/org/apache/commons/weaver/model/WeavableMethodParameter.java b/processor/src/main/java/org/apache/commons/weaver/model/WeavableMethodParameter.java index 642119a..19bf38e 100644 --- a/processor/src/main/java/org/apache/commons/weaver/model/WeavableMethodParameter.java +++ b/processor/src/main/java/org/apache/commons/weaver/model/WeavableMethodParameter.java @@ -36,5 +36,4 @@ public class WeavableMethodParameter<T> extends public WeavableMethodParameter(final Integer target, final WeavableMethod<T> parent) { super(target, parent); } - } diff --git a/processor/src/main/java/org/apache/commons/weaver/model/WeavablePackage.java b/processor/src/main/java/org/apache/commons/weaver/model/WeavablePackage.java index 993ac26..e1a5c9a 100644 --- a/processor/src/main/java/org/apache/commons/weaver/model/WeavablePackage.java +++ b/processor/src/main/java/org/apache/commons/weaver/model/WeavablePackage.java @@ -27,8 +27,7 @@ import java.util.concurrent.ConcurrentSkipListMap; */ public class WeavablePackage extends Weavable<WeavablePackage, Package> { - private final ConcurrentNavigableMap<String, WeavableClass<?>> clazzes = - new ConcurrentSkipListMap<String, WeavableClass<?>>(); + private final ConcurrentNavigableMap<String, WeavableClass<?>> clazzes = new ConcurrentSkipListMap<>(); /** * Create a new {@link WeavablePackage} instance. @@ -51,7 +50,7 @@ public class WeavablePackage extends Weavable<WeavablePackage, Package> { final WeavableClass<T> result = (WeavableClass<T>) clazzes.get(key); return result; } - final WeavableClass<T> result = new WeavableClass<T>(cls, this); + final WeavableClass<T> result = new WeavableClass<>(cls, this); @SuppressWarnings("unchecked") final WeavableClass<T> faster = (WeavableClass<T>) clazzes.putIfAbsent(key, result); return faster == null ? result : faster; @@ -74,5 +73,4 @@ public class WeavablePackage extends Weavable<WeavablePackage, Package> { public int compareTo(final WeavablePackage arg0) { return getTarget().getName().compareTo(arg0.getTarget().getName()); } - } diff --git a/processor/src/main/java/org/apache/commons/weaver/model/WeavableParameter.java b/processor/src/main/java/org/apache/commons/weaver/model/WeavableParameter.java index 9ea5659..09d2d42 100644 --- a/processor/src/main/java/org/apache/commons/weaver/model/WeavableParameter.java +++ b/processor/src/main/java/org/apache/commons/weaver/model/WeavableParameter.java @@ -51,5 +51,4 @@ public abstract class WeavableParameter protected int localCompareTo(final SELF obj) { return getTarget().compareTo(getTarget()); } - } diff --git a/processor/src/main/java/org/apache/commons/weaver/model/WeaveEnvironment.java b/processor/src/main/java/org/apache/commons/weaver/model/WeaveEnvironment.java index e851127..565eb4b 100644 --- a/processor/src/main/java/org/apache/commons/weaver/model/WeaveEnvironment.java +++ b/processor/src/main/java/org/apache/commons/weaver/model/WeaveEnvironment.java @@ -22,6 +22,7 @@ import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Properties; +import java.util.function.Supplier; import java.util.logging.Logger; import javax.activation.DataSource; @@ -34,8 +35,6 @@ import org.apache.commons.weaver.spi.Weaver; * Encapsulates the environment in which a {@link Weaver} or {@link Cleaner} must operate. */ public abstract class WeaveEnvironment { - private static final String CONTENT_TYPE = "application/octet-stream"; - private class Resource implements DataSource { private final String name; @@ -79,6 +78,21 @@ public abstract class WeaveEnvironment { } } + private static final String CONTENT_TYPE = "application/octet-stream"; + + /** + * Convert a classname into a resource name. + * @param classname to convert + * @return String + */ + protected static String getResourceName(final String classname) { + return classname.replace('.', '/') + ".class"; + } + + private static Supplier<String> supplier(String format, Object... args) { + return () -> String.format(format, args); + } + /** * ClassLoader containing scannable and weavable classes. */ @@ -112,7 +126,7 @@ public abstract class WeaveEnvironment { * @see String#format(String, Object...) */ public void debug(final String message, final Object... args) { - log.fine(String.format(message, args)); + log.fine(supplier(message, args)); } /** @@ -122,7 +136,7 @@ public abstract class WeaveEnvironment { * @see String#format(String, Object...) */ public void verbose(final String message, final Object... args) { - log.fine(String.format(message, args)); + log.fine(supplier(message, args)); } /** @@ -132,7 +146,7 @@ public abstract class WeaveEnvironment { * @see String#format(String, Object...) */ public void warn(final String message, final Object... args) { - log.warning(String.format(message, args)); + log.warning(supplier(message, args)); } /** @@ -142,7 +156,7 @@ public abstract class WeaveEnvironment { * @see String#format(String, Object...) */ public void info(final String message, final Object... args) { - log.info(String.format(message, args)); + log.info(supplier(message, args)); } /** @@ -152,7 +166,7 @@ public abstract class WeaveEnvironment { * @see String#format(String, Object...) */ public void error(final String message, final Object... args) { - log.severe(String.format(message, args)); + log.severe(supplier(message, args)); } /** @@ -214,13 +228,4 @@ public abstract class WeaveEnvironment { * @throws IOException on error */ protected abstract OutputStream getOutputStream(String resourceName) throws IOException; - - /** - * Convert a classname into a resource name. - * @param classname to convert - * @return String - */ - protected static String getResourceName(final String classname) { - return classname.replace('.', '/') + ".class"; - } } diff --git a/processor/src/main/java/org/apache/commons/weaver/model/WeaveInterest.java b/processor/src/main/java/org/apache/commons/weaver/model/WeaveInterest.java index 6b23fac..3fa7a1e 100644 --- a/processor/src/main/java/org/apache/commons/weaver/model/WeaveInterest.java +++ b/processor/src/main/java/org/apache/commons/weaver/model/WeaveInterest.java @@ -28,6 +28,16 @@ import java.lang.annotation.ElementType; public final class WeaveInterest { /** + * Get a {@link WeaveInterest}. + * @param annotationType observed annotation type + * @param target attached element type + * @return {@link WeaveInterest} + */ + public static WeaveInterest of(final Class<? extends Annotation> annotationType, final ElementType target) { + return new WeaveInterest(annotationType, target); + } + + /** * Observed annotation type. */ public final Class<? extends Annotation> annotationType; @@ -42,14 +52,4 @@ public final class WeaveInterest { this.annotationType = annotationType; this.target = target; } - - /** - * Get a {@link WeaveInterest}. - * @param annotationType observed annotation type - * @param target attached element type - * @return {@link WeaveInterest} - */ - public static WeaveInterest of(final Class<? extends Annotation> annotationType, final ElementType target) { - return new WeaveInterest(annotationType, target); - } } diff --git a/processor/src/main/java/org/apache/commons/weaver/utils/Args.java b/processor/src/main/java/org/apache/commons/weaver/utils/Args.java index 23f18a9..8d31a1e 100644 --- a/processor/src/main/java/org/apache/commons/weaver/utils/Args.java +++ b/processor/src/main/java/org/apache/commons/weaver/utils/Args.java @@ -52,5 +52,4 @@ public final class Args { } return -1; } - } diff --git a/processor/src/main/java/org/apache/commons/weaver/utils/Providers.java b/processor/src/main/java/org/apache/commons/weaver/utils/Providers.java index 8ed4f5d..5c919c8 100755 --- a/processor/src/main/java/org/apache/commons/weaver/utils/Providers.java +++ b/processor/src/main/java/org/apache/commons/weaver/utils/Providers.java @@ -28,8 +28,6 @@ import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; -import org.apache.commons.collections4.Factory; -import org.apache.commons.collections4.map.LazyMap; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.Validate; import org.apache.commons.weaver.Consumes; @@ -56,18 +54,18 @@ public final class Providers { final Map<Class<? extends P>, Set<Class<? extends P>>> dependencyMap = toDependencyMap(providers); - final Collection<Class<? extends P>> order = new LinkedHashSet<Class<? extends P>>(); + final Collection<Class<? extends P>> order = new LinkedHashSet<>(); - final Map<Class<? extends P>, State> stateMap = new HashMap<Class<? extends P>, Providers.State>(); - final Deque<Class<? extends P>> visiting = new ArrayDeque<Class<? extends P>>(); + final Map<Class<? extends P>, State> stateMap = new HashMap<>(); + final Deque<Class<? extends P>> visiting = new ArrayDeque<>(); for (final Class<? extends P> type : dependencyMap.keySet()) { final State state = stateMap.get(type); if (state == null) { tsort(type, dependencyMap, stateMap, visiting, order); - } else if (state == State.VISITING) { - throw new RuntimeException("Unexpected node in visiting state: " + type); + } else { + Validate.validState(state != State.VISITING, "Unexpected node in visiting state: %s", type); } } return imposeOrder(providers, order); @@ -154,22 +152,15 @@ public final class Providers { */ private Map<Class<? extends P>, Set<Class<? extends P>>> toDependencyMap(final Iterable<P> providers) { - final Map<Class<? extends P>, Set<Class<? extends P>>> result = LazyMap.lazyMap( - new HashMap<Class<? extends P>, Set<Class<? extends P>>>(), new Factory<Set<Class<? extends P>>>() { - - @Override - public Set<Class<? extends P>> create() { - return new HashSet<Class<? extends P>>(); - } - }); + final Map<Class<? extends P>, Set<Class<? extends P>>> result = new HashMap<>(); for (final WeaveLifecycleProvider<?> provider : providers) { @SuppressWarnings("unchecked") final Class<? extends P> type = (Class<? extends P>) provider.getClass(); - Collections.addAll(result.get(type), consumedBy(type)); + Collections.addAll(result.computeIfAbsent(type, k -> new HashSet<>()), consumedBy(type)); for (final Class<? extends P> dependent : producedBy(type)) { - result.get(dependent).add(type); + result.computeIfAbsent(dependent, k -> new HashSet<>()).add(type); } } return result; @@ -184,7 +175,7 @@ public final class Providers { */ private Iterable<P> imposeOrder(final Iterable<P> providers, final Iterable<Class<? extends P>> order) { - final Set<P> result = new LinkedHashSet<P>(); + final Set<P> result = new LinkedHashSet<>(); for (final Class<? extends P> type : order) { for (final P provider : providers) { @@ -195,10 +186,6 @@ public final class Providers { } return Collections.unmodifiableSet(result); } - - } - - private Providers() { } /** @@ -212,4 +199,6 @@ public final class Providers { return new SortWorker<P>().sort(providers); } + private Providers() { + } } diff --git a/processor/src/main/java/org/apache/commons/weaver/utils/URLArray.java b/processor/src/main/java/org/apache/commons/weaver/utils/URLArray.java index 5a36acb..855354e 100644 --- a/processor/src/main/java/org/apache/commons/weaver/utils/URLArray.java +++ b/processor/src/main/java/org/apache/commons/weaver/utils/URLArray.java @@ -21,47 +21,20 @@ package org.apache.commons.weaver.utils; import java.io.File; import java.net.MalformedURLException; import java.net.URL; -import java.util.ArrayList; -import java.util.Iterator; +import java.util.Collection; +import java.util.stream.Stream; /** * {@link URL} Array utilities. */ public final class URLArray { - private URLArray() { - } - /** * Convert an {@link Iterable} of filesystem paths. * @param files to convert * @return URL[] */ public static URL[] fromPaths(final Iterable<String> files) { - return fromFiles(new Iterable<File>() { - - @Override - public Iterator<File> iterator() { - final Iterator<String> path = files.iterator(); - return new Iterator<File>() { - - @Override - public boolean hasNext() { - return path.hasNext(); - } - - @Override - public File next() { - final String element = path.next(); - return element == null ? null : new File(element); - } - - @Override - public void remove() { - throw new UnsupportedOperationException(); - } - }; - } - }); + return fromFiles(() -> stream(files).map(e -> e == null ? null : new File(e)).iterator()); } /** @@ -70,19 +43,32 @@ public final class URLArray { * @return URL[] */ public static URL[] fromFiles(final Iterable<File> files) { - final ArrayList<URL> result = new ArrayList<URL>(); - for (final File file : files) { - if (file == null) { - result.add(null); - continue; + return fromFiles(stream(files)); + } + + private static URL[] fromFiles(final Stream<File> files) { + return files.map(f -> { + if (f == null) { + return null; } try { - result.add(file.toURI().toURL()); + return f.toURI().toURL(); } catch (final MalformedURLException e) { // this shouldn't happen throw new RuntimeException(e); } + }).toArray(URL[]::new); + } + + private static <T> Stream<T> stream(Iterable<T> iterable) { + if (iterable instanceof Collection<?>) { + return ((Collection<T>) iterable).stream(); } - return result.toArray(new URL[result.size()]); + final Stream.Builder<T> b = Stream.builder(); + iterable.forEach(b); + return b.build(); + } + + private URLArray() { } } -- To stop receiving notification emails like this one, please contact mben...@apache.org.