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
The following commit(s) were added to refs/heads/master by this push: new 125e3a4 code quality 125e3a4 is described below commit 125e3a468fe1816d5c789ee11617858ca5f68a25 Author: Matt Benson <mben...@apache.org> AuthorDate: Tue Aug 28 14:59:55 2018 -0500 code quality --- .../org/apache/commons/weaver/checkstyle.xml | 1 - .../resources/org/apache/commons/weaver/pmd.xml | 14 ++ maven-plugin/pom.xml | 4 + .../maven/JavaLoggingToMojoLoggingRedirector.java | 4 +- .../commons/weaver/normalizer/Normalizer.java | 56 ++++-- .../commons/weaver/privilizer/AccessLevel.java | 2 +- .../weaver/privilizer/BlueprintingVisitor.java | 188 +++++++++++++-------- .../privilizer/InlineNestedPrivilegedCalls.java | 14 +- .../commons/weaver/privilizer/Privilized.java | 1 + .../weaver/privilizer/PrivilizingVisitor.java | 2 +- parent/pom.xml | 6 +- .../java/org/apache/commons/weaver/Consumes.java | 1 + .../java/org/apache/commons/weaver/Finder.java | 76 ++++++--- .../java/org/apache/commons/weaver/Inflater.java | 10 +- .../java/org/apache/commons/weaver/Produces.java | 1 + .../weaver/lifecycle/WeaveLifecycleToken.java | 1 + .../apache/commons/weaver/model/ScanResult.java | 6 +- .../org/apache/commons/weaver/model/Weavable.java | 2 +- .../commons/weaver/model/WeaveEnvironment.java | 7 +- .../org/apache/commons/weaver/utils/URLArray.java | 8 +- 20 files changed, 278 insertions(+), 126 deletions(-) diff --git a/build-tools/src/main/resources/org/apache/commons/weaver/checkstyle.xml b/build-tools/src/main/resources/org/apache/commons/weaver/checkstyle.xml index cb72326..9e63863 100644 --- a/build-tools/src/main/resources/org/apache/commons/weaver/checkstyle.xml +++ b/build-tools/src/main/resources/org/apache/commons/weaver/checkstyle.xml @@ -153,7 +153,6 @@ <module name="MissingSwitchDefault" /> <module name="ModifiedControlVariable" /> <module name="ParameterAssignment" /> - <module name="RedundantThrows" /> <module name="SimplifyBooleanExpression" /> <module name="SimplifyBooleanReturn" /> <module name="StringLiteralEquality" /> diff --git a/build-tools/src/main/resources/org/apache/commons/weaver/pmd.xml b/build-tools/src/main/resources/org/apache/commons/weaver/pmd.xml index 4009047..3a79213 100644 --- a/build-tools/src/main/resources/org/apache/commons/weaver/pmd.xml +++ b/build-tools/src/main/resources/org/apache/commons/weaver/pmd.xml @@ -27,9 +27,11 @@ limitations under the License. <rule ref="rulesets/java/design.xml"> <exclude name="AccessorClassGeneration" /> + <exclude name="AvoidDeeplyNestedIfStmts" /> <exclude name="CompareObjectsWithEquals" /> <exclude name="NonStaticInitializer" /> <exclude name="ConfusingTernary" /> + <exclude name="DataClass" /> <exclude name="AvoidSynchronizedAtMethodLevel" /> <exclude name="UnnecessaryLocalBeforeReturn" /> <exclude name="PreserveStackTrace" /> @@ -38,6 +40,12 @@ limitations under the License. <exclude name="GodClass" /> </rule> + <rule ref="category/java/design.xml/AvoidDeeplyNestedIfStmts"> + <properties> + <property name="problemDepth" value="4" /> + </properties> + </rule> + <rule ref="rulesets/java/empty.xml" /> <rule ref="rulesets/java/imports.xml" /> <rule ref="rulesets/java/migrating.xml"> @@ -46,11 +54,17 @@ limitations under the License. <rule ref="rulesets/java/naming.xml"> <exclude name="AbstractNaming" /> <exclude name="AvoidFieldNameMatchingMethodName" /> + <exclude name="ClassNamingConventions" /> <exclude name="GenericsNaming" /> <exclude name="LongVariable" /> <exclude name="ShortClassName" /> <exclude name="ShortMethodName" /> </rule> + <rule ref="category/java/codestyle.xml/ClassNamingConventions"> + <properties> + <property name="utilityClassPattern" value="[A-Z][a-zA-Z0-9]+(Utils?|Helper|s$)" /> + </properties> + </rule> <rule ref="rulesets/java/optimizations.xml"> <exclude name="AvoidInstantiatingObjectsInLoops" /> <exclude name="PrematureDeclaration" /> diff --git a/maven-plugin/pom.xml b/maven-plugin/pom.xml index 558e851..2548342 100644 --- a/maven-plugin/pom.xml +++ b/maven-plugin/pom.xml @@ -177,6 +177,9 @@ under the License. <ruleset>/org/apache/commons/weaver/pmd.xml</ruleset> </rulesets> <skipEmptyReport>false</skipEmptyReport> + <excludeRoots> + <excludeRoot>target/generated-sources/plugin</excludeRoot> + </excludeRoots> </configuration> </plugin> <plugin> @@ -185,6 +188,7 @@ under the License. <version>${checkstyle.version}</version> <configuration> <configLocation>org/apache/commons/weaver/checkstyle.xml</configLocation> + <excludes>org/apache/commons/weaver/maven/HelpMojo.java</excludes> </configuration> </plugin> <plugin> 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 4534cec..a4866a7 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 @@ -42,7 +42,7 @@ public class JavaLoggingToMojoLoggingRedirector { /** * The Maven mojo logger to delegate messages to. */ - private final Log mojoLogger; + final Log mojoLogger; private JDKLogHandler activeHandler; @@ -86,7 +86,7 @@ public class JavaLoggingToMojoLoggingRedirector { public void deactivate() { final Logger rootLogger = LogManager.getLogManager().getLogger(""); // remove old handlers - + if (Stream.of(rootLogger.getHandlers()).anyMatch(h -> h == activeHandler)) { rootLogger.removeHandler(activeHandler); } 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 890b3b8..6d12d42 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 @@ -64,9 +64,6 @@ import org.objectweb.asm.commons.SimpleRemapper; * Handles the work of "normalizing" anonymous class definitions. */ public class Normalizer { - private static final String INIT = "<init>"; - - private static final Type OBJECT_TYPE = Type.getType(Object.class); private static final class Inspector extends ClassVisitor { private final class InspectConstructor extends MethodVisitor { @@ -95,12 +92,27 @@ public class Normalizer { } } - 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); + /** + * Supername of visited class. + */ + String superName; + + /** + * Key to identify "like" subclasses: abstract class or implemented interface + super ctor signature. + */ + final MutablePair<String, String> key = new MutablePair<>(); - private String superName; + /** + * Whether the constructor must be rewritten (true for non-{@code static} classes). + */ + final MutableBoolean mustRewriteConstructor = new MutableBoolean(false); + + /** + * Whether the inspected class is eligible to be normalized. + */ + final MutableBoolean valid = new MutableBoolean(true); + + private final MutableBoolean ignore = new MutableBoolean(false); private Inspector() { super(ASM_VERSION); @@ -176,8 +188,12 @@ public class Normalizer { } } + /** + * Map of original class to normalized class wrapper. + */ + final Map<String, ClassWrapper> wrappers; + private final Map<String, String> classMap; - private final Map<String, ClassWrapper> wrappers; private Remap(final ClassVisitor wrapped, final Remapper remapper, final Map<String, String> classMap, final Map<String, ClassWrapper> wrappers) { @@ -289,9 +305,25 @@ public class Normalizer { */ public static final String CONFIG_TARGET_PACKAGE = CONFIG_WEAVER + "targetPackage"; - private static final int ASM_VERSION = Opcodes.ASM6; + /** + * ASM version in use. + */ + static final int ASM_VERSION = Opcodes.ASM6; - private final WeaveEnvironment env; + /** + * Method name of a constructor. + */ + static final String INIT = "<init>"; + + /** + * {@link Type} instance representing {@link Object}. + */ + static final Type OBJECT_TYPE = Type.getType(Object.class); + + /** + * {@link WeaveEnvironment} used by this {@link Normalizer} instance. + */ + final WeaveEnvironment env; private final Set<Class<?>> normalizeTypes; private final String targetPackage; @@ -577,7 +609,7 @@ public class Normalizer { * @see Type#getObjectType(String) */ @SuppressWarnings("PMD.UseVarargs") //varargs not needed here - private static Type[] toObjectTypes(final String[] types) { + static Type[] toObjectTypes(final String[] types) { return types == null ? null : Stream.of(types).map(Type::getObjectType).toArray(Type[]::new); } } diff --git a/modules/privilizer/weaver/src/main/java/org/apache/commons/weaver/privilizer/AccessLevel.java b/modules/privilizer/weaver/src/main/java/org/apache/commons/weaver/privilizer/AccessLevel.java index 28e01af..25596ef 100644 --- a/modules/privilizer/weaver/src/main/java/org/apache/commons/weaver/privilizer/AccessLevel.java +++ b/modules/privilizer/weaver/src/main/java/org/apache/commons/weaver/privilizer/AccessLevel.java @@ -52,7 +52,7 @@ public enum AccessLevel { private final int flag; - private AccessLevel(final int flag) { + AccessLevel(final int flag) { this.flag = flag; } 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 ef88a7f..33239ce 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 @@ -30,6 +30,7 @@ import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.OptionalInt; import java.util.Set; import java.util.function.Function; import java.util.stream.Collectors; @@ -63,7 +64,8 @@ class BlueprintingVisitor extends Privilizer.PrivilizerClassVisitor { final Map<String, FieldNode> fields; final Map<Method, MethodNode> methods; - TypeInfo(int access, String superName, Map<String, FieldNode> fields, Map<Method, MethodNode> methods) { + TypeInfo(final int access, final String superName, final Map<String, FieldNode> fields, + final Map<Method, MethodNode> methods) { super(); this.access = access; this.superName = superName; @@ -72,19 +74,37 @@ class BlueprintingVisitor extends Privilizer.PrivilizerClassVisitor { } } - private static final Type LAMBDA_METAFACTORY = Type.getType(LambdaMetafactory.class); + /** + * ASM {@link Type} for {@link LambdaMetafactory}. + */ + static final Type LAMBDA_METAFACTORY = Type.getType(LambdaMetafactory.class); - private static Pair<Type, Method> methodKey(String owner, String name, String desc) { + /** + * Compute a method key from the specified parameters. + * @param owner + * @param name + * @param desc + * @return {@link Pair} of {@link Type} and {@link Method} + */ + static Pair<Type, Method> methodKey(final String owner, final String name, final String desc) { return Pair.of(Type.getObjectType(owner), new Method(name, desc)); } + /** + * Blueprint registry {@link Map}. + */ + final Map<Pair<Type, Method>, MethodNode> blueprintRegistry = new HashMap<>(); + + /** + * Field access map. + */ + final Map<Pair<Type, String>, FieldAccess> fieldAccessMap = new HashMap<>(); + 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<>(); private final Map<Type, TypeInfo> typeInfoCache = new HashMap<>(); - private final Map<Pair<Type, String>, FieldAccess> fieldAccessMap = new HashMap<>(); private final ClassVisitor nextVisitor; @@ -113,13 +133,18 @@ class BlueprintingVisitor extends Privilizer.PrivilizerClassVisitor { } } - private TypeInfo typeInfo(Type type) { + /** + * Compute {@link TypeInfo} for the specified {@link Type}. + * @param type + * @return {@link TypeInfo} + */ + TypeInfo typeInfo(final Type type) { return typeInfoCache.computeIfAbsent(type, k -> { - final ClassNode cn = read(k.getClassName()); + final ClassNode classNode = read(k.getClassName()); - return new TypeInfo(cn.access, cn.superName, - cn.fields.stream().collect(Collectors.toMap(f -> f.name, Function.identity())), - cn.methods.stream().collect(Collectors.toMap(m -> new Method(m.name, m.desc), Function.identity()))); + return new TypeInfo(classNode.access, classNode.superName, + classNode.fields.stream().collect(Collectors.toMap(f -> f.name, Function.identity())), classNode.methods + .stream().collect(Collectors.toMap(m -> new Method(m.name, m.desc), Function.identity()))); }); } @@ -155,7 +180,12 @@ class BlueprintingVisitor extends Privilizer.PrivilizerClassVisitor { }; } - private String importMethod(final Pair<Type, Method> key) { + /** + * Import the method specified by {@code key}. + * @param key + * @return {@link String} method name + */ + String importMethod(final Pair<Type, Method> key) { if (importedMethods.containsKey(key)) { return importedMethods.get(key); } @@ -205,7 +235,13 @@ class BlueprintingVisitor extends Privilizer.PrivilizerClassVisitor { return result; } - private FieldAccess fieldAccess(final Type owner, final String name) { + /** + * Compute a {@link FieldAccess} object for the specified parameters. + * @param owner + * @param name + * @return {@link FieldAccess} + */ + FieldAccess fieldAccess(final Type owner, final String name) { return fieldAccessMap.computeIfAbsent(Pair.of(owner, name), k -> { final FieldNode fieldNode = typeInfo(k.getLeft()).fields.get(k.getRight()); Validate.validState(fieldNode != null, "Could not locate %s.%s", k.getLeft().getClassName(), k.getRight()); @@ -244,57 +280,70 @@ class BlueprintingVisitor extends Privilizer.PrivilizerClassVisitor { } @Override - public void visitInvokeDynamicInsn(String name, String descriptor, Handle bootstrapMethodHandle, - Object... bootstrapMethodArguments) { - - if (isLambda(bootstrapMethodHandle)) { - Object[] args = bootstrapMethodArguments; - - Handle handle = null; - - for (int i = 0; i < args.length; i++) { - if (bootstrapMethodArguments[i] instanceof Handle) { - if (handle != null) { - // we don't know what to do with multiple handles; skip the whole thing: - args = bootstrapMethodArguments; - break; - } - handle = (Handle) args[i]; - - if (handle.getTag() == Opcodes.H_INVOKESTATIC) { - final Pair<Type, Method> methodKey = - methodKey(handle.getOwner(), handle.getName(), handle.getDesc()); - - if (shouldImport(methodKey)) { - final String importedName = importMethod(methodKey); - args = bootstrapMethodArguments.clone(); - args[i] = new Handle(handle.getTag(), className, importedName, handle.getDesc(), false); - } - } - } - } - if (handle != null) { - if (args == bootstrapMethodArguments) { - validateLambda(handle); - } else { - super.visitInvokeDynamicInsn(name, descriptor, bootstrapMethodHandle, args); - return; - } - } + public void visitInvokeDynamicInsn(final String name, final String descriptor, + final Handle bootstrapMethodHandle, final Object... bootstrapMethodArguments) { + + if (!(isLambda(bootstrapMethodHandle) + && invokeDynamicImportedMethod(name, descriptor, bootstrapMethodHandle, bootstrapMethodArguments))) { + super.visitInvokeDynamicInsn(name, descriptor, bootstrapMethodHandle, bootstrapMethodArguments); } - super.visitInvokeDynamicInsn(name, descriptor, bootstrapMethodHandle, bootstrapMethodArguments); } - protected void validateLambda(Handle handle) { + /** + * May be overridden by subclasses. + * @param handle + */ + protected void validateLambda(final Handle handle) { + // base implementation does nothing } + /** + * Learn whether the method specified by {@code methodKey} should be imported. + * @param methodKey + * @return {@code boolean} + */ abstract boolean shouldImport(Pair<Type, Method> methodKey); - private boolean isLambda(Handle handle) { + private boolean isLambda(final Handle handle) { return handle.getTag() == Opcodes.H_INVOKESTATIC && LAMBDA_METAFACTORY.getInternalName().equals(handle.getOwner()) && "metafactory".equals(handle.getName()); } + + private boolean invokeDynamicImportedMethod(final String name, final String descriptor, + final Handle bootstrapMethodHandle, final Object... bootstrapMethodArguments) { + + OptionalInt handleIndex = OptionalInt.empty(); + + for (int i = 0; i < bootstrapMethodArguments.length; i++) { + if (bootstrapMethodArguments[i] instanceof Handle) { + if (handleIndex.isPresent()) { + return false; + } + handleIndex = OptionalInt.of(i); + } + } + if (handleIndex.isPresent()) { + final Handle handle = (Handle) bootstrapMethodArguments[handleIndex.getAsInt()]; + if (handle.getTag() == Opcodes.H_INVOKESTATIC) { + final Pair<Type, Method> methodKey = + methodKey(handle.getOwner(), handle.getName(), handle.getDesc()); + + if (shouldImport(methodKey)) { + final String importedName = importMethod(methodKey); + final Object[] args = bootstrapMethodArguments.clone(); + + args[handleIndex.getAsInt()] = + new Handle(handle.getTag(), className, importedName, handle.getDesc(), false); + + super.visitInvokeDynamicInsn(name, descriptor, bootstrapMethodHandle, args); + return true; + } + validateLambda(handle); + } + } + return false; + } } class NestedMethodInvocationHandler extends MethodInvocationHandler { @@ -308,28 +357,29 @@ class BlueprintingVisitor extends Privilizer.PrivilizerClassVisitor { } @Override - protected void visitNonImportedMethodInsn(int opcode, String owner, String name, String desc, boolean itf) { + protected void visitNonImportedMethodInsn(final int opcode, final String owner, final String name, + final String desc, final boolean itf) { final Type ownerType = Type.getObjectType(owner); - final Method m = new Method(name, desc); + final Method method = new Method(name, desc); - if (isAccessible(ownerType) && isAccessible(ownerType, m)) { + if (isAccessible(ownerType) && isAccessible(ownerType, method)) { super.visitNonImportedMethodInsn(opcode, owner, name, desc, itf); } else { throw new IllegalStateException(String.format("Blueprint method %s.%s calls inaccessible method %s.%s", - this.owner, methodKey.getRight(), owner, m)); + this.owner, methodKey.getRight(), owner, method)); } } @Override - protected void validateLambda(Handle handle) { + protected void validateLambda(final Handle handle) { super.validateLambda(handle); final Type ownerType = Type.getObjectType(handle.getOwner()); - final Method m = new Method(handle.getName(), handle.getDesc()); + final Method method = new Method(handle.getName(), handle.getDesc()); - if (!(isAccessible(ownerType) && isAccessible(ownerType, m))) { + if (!(isAccessible(ownerType) && isAccessible(ownerType, method))) { throw new IllegalStateException( String.format("Blueprint method %s.%s utilizes inaccessible method reference %s::%s", owner, - methodKey.getRight(), handle.getOwner(), m)); + methodKey.getRight(), handle.getOwner(), method)); } } @@ -354,26 +404,26 @@ class BlueprintingVisitor extends Privilizer.PrivilizerClassVisitor { return privilizer().env.classLoader.loadClass(type.getClassName()); } - private boolean isAccessible(Type type) { + private boolean isAccessible(final Type type) { final TypeInfo typeInfo = typeInfo(type); return isAccessible(type, typeInfo.access); } - private boolean isAccessible(Type type, Method m) { - Type t = type; - while (t != null) { - final TypeInfo typeInfo = typeInfo(t); - final MethodNode methodNode = typeInfo.methods.get(m); + private boolean isAccessible(final Type type, final Method method) { + Type currentType = type; + while (currentType != null) { + final TypeInfo typeInfo = typeInfo(currentType); + final MethodNode methodNode = typeInfo.methods.get(method); if (methodNode == null) { - t = Optional.ofNullable(typeInfo.superName).map(Type::getObjectType).orElse(null); + currentType = Optional.ofNullable(typeInfo.superName).map(Type::getObjectType).orElse(null); continue; } return isAccessible(type, methodNode.access); } - throw new IllegalStateException(String.format("Cannot find method %s.%s", type, m)); + throw new IllegalStateException(String.format("Cannot find method %s.%s", type, method)); } - private boolean isAccessible(Type type, int access) { + private boolean isAccessible(final Type type, final int access) { if (Modifier.isPublic(access)) { return true; } diff --git a/modules/privilizer/weaver/src/main/java/org/apache/commons/weaver/privilizer/InlineNestedPrivilegedCalls.java b/modules/privilizer/weaver/src/main/java/org/apache/commons/weaver/privilizer/InlineNestedPrivilegedCalls.java index 2795a22..85146d0 100644 --- a/modules/privilizer/weaver/src/main/java/org/apache/commons/weaver/privilizer/InlineNestedPrivilegedCalls.java +++ b/modules/privilizer/weaver/src/main/java/org/apache/commons/weaver/privilizer/InlineNestedPrivilegedCalls.java @@ -74,14 +74,20 @@ class InlineNestedPrivilegedCalls extends ClassNode { } } - private final Privilizer privilizer; - - private final ClassVisitor next; + /** + * Owning {@link Privilizer}. + */ + final Privilizer privilizer; /** * Map of original method to name of internal implementation method. */ - private final Map<Method, String> privilegedMethods; + final Map<Method, String> privilegedMethods; + + /** + * Next {@link ClassVisitor}. + */ + final ClassVisitor next; /** * Create a new {@link InlineNestedPrivilegedCalls} object. diff --git a/modules/privilizer/weaver/src/main/java/org/apache/commons/weaver/privilizer/Privilized.java b/modules/privilizer/weaver/src/main/java/org/apache/commons/weaver/privilizer/Privilized.java index 6e1e5cb..adb56fa 100644 --- a/modules/privilizer/weaver/src/main/java/org/apache/commons/weaver/privilizer/Privilized.java +++ b/modules/privilizer/weaver/src/main/java/org/apache/commons/weaver/privilizer/Privilized.java @@ -28,6 +28,7 @@ import java.lang.annotation.Target; public @interface Privilized { /** * Name of {@link Policy} with which privilized weaving was performed. + * @return {@link String} */ String value(); } \ No newline at end of file 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 bda171e..387dbd6 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 @@ -220,7 +220,7 @@ class PrivilizingVisitor extends Privilizer.PrivilizerClassVisitor { * security manager available. * @param mgen to control */ - private static void checkSecurityManager(final GeneratorAdapter mgen) { + static void checkSecurityManager(final GeneratorAdapter mgen) { final Label setFalse = new Label(); final Label done = new Label(); mgen.invokeStatic(Type.getType(System.class), diff --git a/parent/pom.xml b/parent/pom.xml index 00194c8..6acbe0d 100755 --- a/parent/pom.xml +++ b/parent/pom.xml @@ -35,7 +35,7 @@ under the License. <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> - <checkstyle.version>2.15</checkstyle.version> + <checkstyle.version>3.0.0</checkstyle.version> <hamcrest.version>1.3</hamcrest.version> </properties> @@ -215,12 +215,12 @@ under the License. <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-pmd-plugin</artifactId> - <version>3.5</version> + <version>3.10.0</version> </plugin> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>findbugs-maven-plugin</artifactId> - <version>3.0.3</version> + <version>3.0.5</version> </plugin> <plugin> <groupId>com.github.siom79.japicmp</groupId> diff --git a/processor/src/main/java/org/apache/commons/weaver/Consumes.java b/processor/src/main/java/org/apache/commons/weaver/Consumes.java index c133860..02948ee 100755 --- a/processor/src/main/java/org/apache/commons/weaver/Consumes.java +++ b/processor/src/main/java/org/apache/commons/weaver/Consumes.java @@ -38,6 +38,7 @@ import org.apache.commons.weaver.spi.WeaveLifecycleProvider; public @interface Consumes { /** * The consumed types. + * @return array of {@link WeaveLifecycleProvider} subclasses */ Class<? extends WeaveLifecycleProvider<?>>[] value(); } 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 b08bc1b..7833822 100644 --- a/processor/src/main/java/org/apache/commons/weaver/Finder.java +++ b/processor/src/main/java/org/apache/commons/weaver/Finder.java @@ -21,6 +21,7 @@ package org.apache.commons.weaver; import java.io.IOException; import java.io.InputStream; import java.lang.annotation.Annotation; +import java.lang.annotation.ElementType; import java.lang.reflect.AnnotatedElement; import java.lang.reflect.Array; import java.lang.reflect.Constructor; @@ -109,7 +110,7 @@ class Finder extends AnnotationFinder implements Scanner { } private abstract class AnnotationCapturer extends AnnotationVisitor { - public AnnotationCapturer(final AnnotationVisitor wrapped) { + AnnotationCapturer(final AnnotationVisitor wrapped) { super(ASM_VERSION, wrapped); } @@ -195,7 +196,7 @@ class Finder extends AnnotationFinder implements Scanner { public class Visitor extends ClassVisitor { private final InfoBuildingVisitor wrapped; - public Visitor(final InfoBuildingVisitor wrapped) { + Visitor(final InfoBuildingVisitor wrapped) { super(ASM_VERSION, wrapped); this.wrapped = wrapped; } @@ -307,18 +308,18 @@ class Finder extends AnnotationFinder implements Scanner { } private static class IncludesClassfile<T extends AnnotatedElement> implements Annotated<T> { - private final T target; + private final T annotatedElement; private final Annotation[] annotations; - IncludesClassfile(final T target, final List<Annotation> classfileAnnotations) { - this(target, classfileAnnotations.toArray(new Annotation[classfileAnnotations.size()])); + IncludesClassfile(final T annotatedElement, final List<Annotation> classfileAnnotations) { + this(annotatedElement, classfileAnnotations.toArray(new Annotation[0])); } @SuppressWarnings("PMD.UseVarargs") // varargs not necessary here - IncludesClassfile(final T target, final Annotation[] classfileAnnotations) { + IncludesClassfile(final T annotatedElement, final Annotation[] classfileAnnotations) { super(); - this.target = target; - this.annotations = ArrayUtils.addAll(target.getAnnotations(), classfileAnnotations); + this.annotatedElement = annotatedElement; + this.annotations = ArrayUtils.addAll(annotatedElement.getAnnotations(), classfileAnnotations); } @Override @@ -352,7 +353,7 @@ class Finder extends AnnotationFinder implements Scanner { @Override public T get() { - return target; + return annotatedElement; } } @@ -494,42 +495,73 @@ class Finder extends AnnotationFinder implements Scanner { } } - private static final int ASM_VERSION = Opcodes.ASM6; 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()); + /** + * ASM version in use. + */ + static final int ASM_VERSION = Opcodes.ASM6; + + /** + * Ctor {@link Predicate}. + */ + 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 = + static final ThreadLocal<Map<Info, List<Annotation>>> CLASSFILE_ANNOTATIONS = ThreadLocal.withInitial(IdentityHashMap::new); - private static <T, U> Stream<U> typed(Class<U> type, Supplier<Stream<T>> stream) { + /** + * Filter and cast {@code stream}. + * @param type + * @param stream + * @return {@link Stream} + */ + static <T, U> Stream<U> typed(final Class<U> type, final Supplier<Stream<T>> stream) { return stream.get().filter(type::isInstance).map(type::cast); } - private static Predicate<Annotated<?>> hasAnnotation(Class<? extends Annotation> annotation) { + /** + * Obtain a {@link Predicate} to test whether an {@link Annotated} instance + * hosts annotations of the specified type. + * + * @param annotation + * @return {@link Predicate} + */ + static Predicate<Annotated<?>> hasAnnotation(final Class<? extends Annotation> annotation) { return annotated -> annotated != null && annotated.isAnnotationPresent(annotation); } - private static <T> Predicate<T> isCtor(Function<? super T, MethodInfo> xform) { + /** + * Obtain a {@link Predicate} to test whether an argument, once transformed + * by the specified {@link Function}, represents a Java constructor. + * + * @param xform + * @return {@link Predicate} + */ + static <T> Predicate<T> isCtor(final Function<? super T, MethodInfo> xform) { return t -> CTOR.test(xform.apply(t)); } + /** + * Map of {@link Info} to {@link List} of classfile {@link Annotation}s. + */ + final Map<Info, List<Annotation>> classfileAnnotations; + private final WithAnnotations withAnnotations = new WithAnnotations(); - private final Map<Info, List<Annotation>> classfileAnnotations; private final Inflater inflater; /** * Create a new {@link Finder} instance. * @param archive */ - public Finder(final Archive archive) { + Finder(final Archive archive) { super(archive, false); classfileAnnotations = CLASSFILE_ANNOTATIONS.get(); CLASSFILE_ANNOTATIONS.remove(); @@ -595,7 +627,8 @@ class Finder extends AnnotationFinder implements Scanner { } } else { for (final WeaveInterest interest : request.getInterests()) { - switch (interest.target) { + final ElementType target = interest.target; + switch (target) { case PACKAGE: for (final Annotated<Package> pkg : this.withAnnotations().findAnnotatedPackages( interest.annotationType)) { @@ -652,7 +685,12 @@ class Finder extends AnnotationFinder implements Scanner { return inflater.inflate(result); } - private Class<?> toClass(final Type type) { + /** + * Transform a {@link java.lang.reflect.Type} instance to a {@link Class}. + * @param type + * @return {@link Class} + */ + Class<?> toClass(final Type type) { final String className; if (type.getSort() == Type.ARRAY) { className = type.getElementType().getClassName(); 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 c5b6137..7671d5a 100644 --- a/processor/src/main/java/org/apache/commons/weaver/Inflater.java +++ b/processor/src/main/java/org/apache/commons/weaver/Inflater.java @@ -133,7 +133,7 @@ class Inflater { if (k.get().equals(fld.getTarget())) { fld.addAnnotations(v); } - } catch (final ClassNotFoundException cnfe) { + } catch (final ClassNotFoundException ignored) { } }); } @@ -143,7 +143,7 @@ class Inflater { if (k.get().equals(ctor.getTarget())) { ctor.addAnnotations(v); } - } catch (final ClassNotFoundException cnfe) { + } catch (final ClassNotFoundException ignored) { } }); for (final WeavableConstructorParameter<?> param : ctor.getParameters()) { @@ -154,7 +154,7 @@ class Inflater { && param.getTarget().intValue() == parameter.getIndex()) { param.addAnnotations(v); } - } catch (final ClassNotFoundException cnfe) { + } catch (final ClassNotFoundException ignored) { } }); } @@ -165,7 +165,7 @@ class Inflater { if (k.get().equals(methd.getTarget())) { methd.addAnnotations(v); } - } catch (final ClassNotFoundException cnfe) { + } catch (final ClassNotFoundException ignored) { } }); for (final WeavableMethodParameter<?> param : methd.getParameters()) { @@ -176,7 +176,7 @@ class Inflater { && param.getTarget().intValue() == parameter.getIndex()) { param.addAnnotations(v); } - } catch (final ClassNotFoundException cnfe) { + } catch (final ClassNotFoundException ignored) { } }); } diff --git a/processor/src/main/java/org/apache/commons/weaver/Produces.java b/processor/src/main/java/org/apache/commons/weaver/Produces.java index 153fd5b..e945a32 100755 --- a/processor/src/main/java/org/apache/commons/weaver/Produces.java +++ b/processor/src/main/java/org/apache/commons/weaver/Produces.java @@ -38,6 +38,7 @@ import org.apache.commons.weaver.spi.WeaveLifecycleProvider; public @interface Produces { /** * The consuming types. + * @return array of {@link WeaveLifecycleProvider} subclasses */ Class<? extends WeaveLifecycleProvider<?>>[] value(); } diff --git a/processor/src/main/java/org/apache/commons/weaver/lifecycle/WeaveLifecycleToken.java b/processor/src/main/java/org/apache/commons/weaver/lifecycle/WeaveLifecycleToken.java index a091b14..f81a350 100755 --- a/processor/src/main/java/org/apache/commons/weaver/lifecycle/WeaveLifecycleToken.java +++ b/processor/src/main/java/org/apache/commons/weaver/lifecycle/WeaveLifecycleToken.java @@ -39,6 +39,7 @@ public class WeaveLifecycleToken { public @interface Represents { /** * The {@link WeaveLifecycle} stage represented by the annotated {@link WeaveLifecycleToken} type. + * @return {@link WeaveLifecycle} */ WeaveLifecycle value(); } 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 71bcf10..b8b8a0b 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 @@ -173,8 +173,10 @@ public class ScanResult { } - private final ConcurrentNavigableMap<String, WeavablePackage> packages = - new ConcurrentSkipListMap<>(); + /** + * Weavable packages by name. + */ + final ConcurrentNavigableMap<String, WeavablePackage> packages = new ConcurrentSkipListMap<>(); /** * Public for use by {@link WeaveProcessor}. 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 37bc4b1..8e06ebc 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 @@ -104,7 +104,7 @@ public abstract class Weavable<SELF extends Weavable<SELF, TARGET>, TARGET> impl if (annotations == null) { return EMPTY_ANNOTATION_ARRAY; //NOPMD - no problem sharing zero-length array } - return annotations.toArray(new Annotation[annotations.size()]); + return annotations.toArray(new Annotation[0]); } /** 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 565eb4b..955f2d4 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 @@ -78,7 +78,10 @@ public abstract class WeaveEnvironment { } } - private static final String CONTENT_TYPE = "application/octet-stream"; + /** + * Content type for environment resource. + */ + static final String CONTENT_TYPE = "application/octet-stream"; /** * Convert a classname into a resource name. @@ -89,7 +92,7 @@ public abstract class WeaveEnvironment { return classname.replace('.', '/') + ".class"; } - private static Supplier<String> supplier(String format, Object... args) { + private static Supplier<String> supplier(final String format, final Object... args) { return () -> String.format(format, args); } 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 855354e..ba1964f 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 @@ -60,13 +60,13 @@ public final class URLArray { }).toArray(URL[]::new); } - private static <T> Stream<T> stream(Iterable<T> iterable) { + private static <T> Stream<T> stream(final Iterable<T> iterable) { if (iterable instanceof Collection<?>) { return ((Collection<T>) iterable).stream(); } - final Stream.Builder<T> b = Stream.builder(); - iterable.forEach(b); - return b.build(); + final Stream.Builder<T> builder = Stream.builder(); + iterable.forEach(builder); + return builder.build(); } private URLArray() {