the first commit
This commit is contained in:
@@ -0,0 +1,9 @@
|
||||
# EditorConfig is awesome: https://EditorConfig.org
|
||||
|
||||
# top-most EditorConfig file
|
||||
root = true
|
||||
|
||||
# Unix-style newlines with a newline ending every file
|
||||
[*]
|
||||
indent_style = tab
|
||||
indent_size = 4
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
## OS Generated
|
||||
|
||||
.DS_Store
|
||||
.DS_Store?
|
||||
._*
|
||||
.Spotlight-V100
|
||||
.Trashes
|
||||
ehthumbs.db
|
||||
Thumbs.db
|
||||
Desktop.ini
|
||||
|
||||
## Eclipse IDE
|
||||
|
||||
.project
|
||||
.classpath
|
||||
.settings/
|
||||
.metadata
|
||||
bin/
|
||||
*.tmp
|
||||
*.bak
|
||||
*.swp
|
||||
local.properties
|
||||
.externalToolBuilders/
|
||||
*.launch
|
||||
.pmd
|
||||
.eclipse-pmd
|
||||
|
||||
# Intellij Idea
|
||||
.idea
|
||||
*.iml
|
||||
|
||||
# Maven
|
||||
target/
|
||||
|
||||
# Gradle
|
||||
.gradle/
|
||||
build/
|
||||
out/
|
||||
|
||||
## Project specific
|
||||
deploy
|
||||
|
||||
# Default by github for Java projects
|
||||
|
||||
*.class
|
||||
|
||||
# Mobile Tools for Java (J2ME)
|
||||
.mtj.tmp/
|
||||
|
||||
# Package Files #
|
||||
*.jar
|
||||
*.war
|
||||
*.ear
|
||||
|
||||
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
|
||||
hs_err_pid*
|
||||
|
||||
# Maven versionsBackup
|
||||
|
||||
*.versionsBackup
|
||||
@@ -1,9 +1,9 @@
|
||||
Dux Technica Source Code License Agreement
|
||||
DuxTechnica Limited Use Source Code License Agreement (DT-LUSCL)
|
||||
|
||||
1. Introduction
|
||||
|
||||
This is a Limited Use Source Code License Agreement ("Agreement") that is made and entered into by
|
||||
and between the Licensor, Dux Technica, and the Licensee. By accessing, downloading, or using the
|
||||
and between the Licensor, DuxTechnica, and the Licensee. By accessing, downloading, or using the
|
||||
source code provided by the Licensor (the "Source Code"), the Licensee agrees to be bound by the
|
||||
terms and conditions of this Agreement.
|
||||
|
||||
@@ -11,8 +11,8 @@ terms and conditions of this Agreement.
|
||||
|
||||
Subject to the terms and conditions of this Agreement, the Licensor hereby grants to the Licensee a
|
||||
non-exclusive, non-transferable, limited license to use the Source Code solely for internal
|
||||
purposes. The Licensee may use the Source Code for evaluation, development, and testing purposes
|
||||
within their organisation.
|
||||
purposes only. The Licensee may use the Source Code for evaluation, development, and testing
|
||||
purposes within their organisation.
|
||||
|
||||
3. Restrictions
|
||||
|
||||
@@ -31,6 +31,7 @@ reasonable steps to prevent unauthorised access or disclosure.
|
||||
Source Code.
|
||||
|
||||
4. Payment
|
||||
|
||||
Access to the Source Code may be subject to payment. The terms of payment will be specified
|
||||
separately by the Licensor. The Licensee agrees to pay any applicable fees as stipulated by the
|
||||
Licensor before accessing the Source Code.
|
||||
@@ -78,5 +79,5 @@ amendments or modifications to this Agreement must be in writing and signed by b
|
||||
|
||||
For any questions regarding this Agreement, please contact the Licensor at:
|
||||
|
||||
Dux Technica, Bangalore, India
|
||||
DuxTechnica, Bangalore, India
|
||||
email: [email protected]
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!--
|
||||
~ Copyright (c) DuxTechnica
|
||||
~
|
||||
~ Licensed under the DuxTechnica Limited Use Source Code License Agreement (DT-LUSCL); you may not
|
||||
~ use this file except in compliance with the License. You may obtain a copy of the License by
|
||||
~ contacting:
|
||||
~
|
||||
~ Dux Technica, [email protected]
|
||||
~
|
||||
~ This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
|
||||
~ either express or implied. See the License for the specific language governing permissions and
|
||||
~ limitations under the License.
|
||||
-->
|
||||
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>dux.scanpath</groupId>
|
||||
<artifactId>dux.scanpath</artifactId>
|
||||
<version>v2-SNAPSHOT</version>
|
||||
<name>scanpath</name>
|
||||
<description>Scans the Java classpath for specific entities</description>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<properties>
|
||||
<plugin.compiler.version>3.12.1</plugin.compiler.version>
|
||||
<plugin.javadoc.version>3.6.3</plugin.javadoc.version>
|
||||
<plugin.source.version>3.3.0</plugin.source.version>
|
||||
<plugin.release.version>3.1.1</plugin.release.version>
|
||||
<plugin.deploy.version>3.1.1</plugin.deploy.version>
|
||||
<target.java.version>25</target.java.version>
|
||||
</properties>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${plugin.compiler.version}</version>
|
||||
<configuration>
|
||||
<release>${target.java.version}</release>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-javadoc-plugin</artifactId>
|
||||
<version>${plugin.javadoc.version}</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>javadoc</id>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>jar</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
<configuration>
|
||||
<javadocExecutable>${java.home}/bin/javadoc</javadocExecutable>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-source-plugin</artifactId>
|
||||
<version>${plugin.source.version}</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>attach-sources</id>
|
||||
<phase>verify</phase>
|
||||
<goals>
|
||||
<goal>jar-no-fork</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<artifactId>maven-release-plugin</artifactId>
|
||||
<version>${plugin.release.version}</version>
|
||||
<configuration>
|
||||
<useReleaseProfile>false</useReleaseProfile>
|
||||
<releaseProfiles>release</releaseProfiles>
|
||||
<autoVersionSubmodules>true</autoVersionSubmodules>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-deploy-plugin</artifactId>
|
||||
<version>${plugin.deploy.version}</version>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,144 @@
|
||||
/*
|
||||
* Copyright (c) DuxTechnica
|
||||
*
|
||||
* Licensed under the DuxTechnica Limited Use Source Code License Agreement (DT-LUSCL); you may not
|
||||
* use this file except in compliance with the License. You may obtain a copy of the License by
|
||||
* contacting:
|
||||
*
|
||||
* Dux Technica, [email protected]
|
||||
*
|
||||
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
|
||||
* either express or implied. See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package dux.scanpath.v2;
|
||||
|
||||
import dux.scanpath.v2.mstore.ClassNameFilter;
|
||||
import dux.scanpath.v2.mstore.MetaStore;
|
||||
import dux.scanpath.v2.mstore.MetaStoreBuilder;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
/**
|
||||
* Scans one or more Java classpaths and indexes the discovered types so callers can query
|
||||
* inheritance, annotation, field, and method metadata without having to load every class manually.
|
||||
*
|
||||
* @author indroneel
|
||||
*/
|
||||
|
||||
public class ClasspathScanner {
|
||||
|
||||
private static final Logger L = Logger.getLogger(ClasspathScanner.class.getName());
|
||||
|
||||
private MetaStore mstor;
|
||||
|
||||
/**
|
||||
* Creates a new classpath scanner to search for specific items on the classpath.
|
||||
*/
|
||||
|
||||
public ClasspathScanner() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepare the list of Java types that would be further looked up for types with specific
|
||||
* characteristics and/or constructs.
|
||||
*
|
||||
* @param sscope provides the configuration, in terms of classpaths and name matching criteria,
|
||||
* that is used to arrive at the list of Java types for further lookup.
|
||||
*/
|
||||
|
||||
public void load(ScanScope sscope) {
|
||||
if(sscope == null) {
|
||||
return;
|
||||
}
|
||||
ClassNameFilter clsFilter = sscope.createFilter();
|
||||
List<String> cpaths = sscope.classPaths();
|
||||
mstor = new MetaStoreBuilder().build(cpaths, clsFilter);
|
||||
}
|
||||
|
||||
/**
|
||||
* Dumps the internal state of the classpath scanner, in terms of the list of Java types that were
|
||||
* discovered and indexed, along with their inheritance, annotation, field, and method metadata.
|
||||
*
|
||||
* @param identStr a string that is used to indent the output for better readability.
|
||||
* @return a list of strings, each string being a line of the dumped state.
|
||||
*/
|
||||
|
||||
public List<String> dumpState(String identStr) {
|
||||
return mstor.dumpState(identStr);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets a custom classloader that is subsequently used to load classes from the scanned class path.
|
||||
*
|
||||
* @param cl a custom classloader that is used to load the classes. A null value will default
|
||||
* to the system classloader.
|
||||
*/
|
||||
|
||||
public void setClassLoader(ClassLoader cl) {
|
||||
if(mstor == null) {
|
||||
if (L.isLoggable(Level.WARNING)) {
|
||||
L.warning("MetaStore not initialized. Call load() before setting classloader.");
|
||||
}
|
||||
return;
|
||||
}
|
||||
//else
|
||||
mstor.setClassLoader(cl);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves a list of Java types that derives/implements, either directly or indirectly, the given
|
||||
* type.
|
||||
*
|
||||
* @param type a Java type that is present on the type hierarchy for each entry in the returned
|
||||
* list of Java types.
|
||||
* @return the corresponding list of Java types.
|
||||
*/
|
||||
|
||||
public List<Class<?>> listInheritingClasses(Class<?> type) {
|
||||
return mstor.listInheritingClasses(type.getName());
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves a list of Java types, that are qualified with the given annotation. The list also
|
||||
* includes types that derive from or inherit at least one Java type that is qualified with the
|
||||
* given annotation.
|
||||
*
|
||||
* @param ann the annotation, the target type being a Java class.
|
||||
* @return the corresponding list of Java types that have the annotation, or derive/inherit from
|
||||
* one or more Java types that bear the annotation.
|
||||
*/
|
||||
|
||||
public List<Class<?>> listAnnotatedClasses(Class<?> ann) {
|
||||
return mstor.listAnnotatedClasses(ann.getName());
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves a list of Java types, that encapsulates at least one field, that is qualified with the
|
||||
* given annotation. The list also includes types that derive/inherit from at least one Java type
|
||||
* that encapsulates at least one field that is qualified with the given annotation.
|
||||
*
|
||||
* @param ann the annotation, the target type being a field within a Java class.
|
||||
* @return the corresponding list of Java types.
|
||||
*/
|
||||
|
||||
public List<Class<?>> listClassesWithAnnotatedFields(Class<?> ann) {
|
||||
return mstor.listClassesWithAnnotatedFields(ann.getName());
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves a list of Java types, that encapsulates at least one method, that is qualified with the
|
||||
* given annotation. The list also includes types that derive/inherit from at least one Java type
|
||||
* that encapsulates at least one method that is qualified with the given annotation.
|
||||
*
|
||||
* @param ann the annotation, the target type being a method within a Java class.
|
||||
* @return the corresponding list of Java types.
|
||||
*/
|
||||
|
||||
public List<Class<?>> listClassesWithAnnotatedMethods(Class<?> ann) {
|
||||
return mstor.listClassesWithAnnotatedMethods(ann.getName());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,235 @@
|
||||
/*
|
||||
* Copyright (c) DuxTechnica
|
||||
*
|
||||
* Licensed under the DuxTechnica Limited Use Source Code License Agreement (DT-LUSCL); you may not
|
||||
* use this file except in compliance with the License. You may obtain a copy of the License by
|
||||
* contacting:
|
||||
*
|
||||
* Dux Technica, [email protected]
|
||||
*
|
||||
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
|
||||
* either express or implied. See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package dux.scanpath.v2;
|
||||
|
||||
import dux.scanpath.v2.mstore.ClassNameFilter;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* This class is used to specify the classpath entries and library files to be scanned for specific
|
||||
* Java types. It also defines the name patterns to be used to filter out and arrive at the final
|
||||
* list of Java types to be used by the classpath browser for lookup operations.
|
||||
*
|
||||
* @author indroneel
|
||||
*/
|
||||
|
||||
public class ScanScope {
|
||||
|
||||
private final List<String> classPaths;
|
||||
private final List<String> includePkgs;
|
||||
private final List<String> excludePkgs;
|
||||
private final List<String> includeClasses;
|
||||
private final List<String> excludeClasses;
|
||||
private final List<String> includePats;
|
||||
private final List<String> excludePats;
|
||||
private boolean appClsPth;
|
||||
|
||||
/**
|
||||
* Creates a new scan scope with no classpath or libpath entries, and no package or type name
|
||||
* filters. By default, the system classpath is included in the scan scope.
|
||||
*/
|
||||
|
||||
public ScanScope() {
|
||||
appClsPth = true;
|
||||
classPaths = new LinkedList<>();
|
||||
includePkgs = new LinkedList<>();
|
||||
excludePkgs = new LinkedList<>();
|
||||
includeClasses = new LinkedList<>();
|
||||
excludeClasses = new LinkedList<>();
|
||||
includePats = new LinkedList<>();
|
||||
excludePats = new LinkedList<>();
|
||||
}
|
||||
|
||||
List<String> classPaths() {
|
||||
List<String> result = new LinkedList<>();
|
||||
if(appClsPth) {
|
||||
//Prepare the java class path for subsequent scanning.
|
||||
String javaClassPath = System.getProperty("java.class.path");
|
||||
if (javaClassPath != null) {
|
||||
Collections.addAll(result, javaClassPath.split(File.pathSeparator));
|
||||
}
|
||||
}
|
||||
result.addAll(classPaths);
|
||||
return result;
|
||||
}
|
||||
|
||||
ClassNameFilter createFilter() {
|
||||
ClassNameFilter filter = new ClassNameFilter();
|
||||
|
||||
for(String name : includePkgs) {
|
||||
filter.includePackage(name);
|
||||
}
|
||||
|
||||
for(String name : excludePkgs) {
|
||||
filter.excludePackage(name);
|
||||
}
|
||||
|
||||
for(String pattern : includePats) {
|
||||
filter.includeClassesByPattern(pattern);
|
||||
}
|
||||
|
||||
for(String pattern : excludePats) {
|
||||
filter.excludeClassesByPattern(pattern);
|
||||
}
|
||||
|
||||
for(String name : includeClasses) {
|
||||
filter.includeClass(name);
|
||||
}
|
||||
|
||||
for(String name : excludeClasses) {
|
||||
filter.excludeClass(name);
|
||||
}
|
||||
|
||||
return filter;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
// Public methods
|
||||
|
||||
/**
|
||||
* Adds an entry to the list of classpaths that should be scanned by the classpath browser for
|
||||
* lookup of specific Java types. A classpath denotes an absolute or relative path to a folder, or a
|
||||
* ZIP/JAR archive containing a set of Java class files.
|
||||
*
|
||||
* @param path a classpath entry
|
||||
* @return this object for fluent style invocation of methods.
|
||||
*/
|
||||
|
||||
public ScanScope addClassPath(String path) {
|
||||
classPaths.add(path);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Excludes the system classpath from the scan scope. By default, the system classpath is included
|
||||
* in the scan scope. This method can be used to exclude it if desired.
|
||||
*
|
||||
* @return this object for fluent style invocation of methods.
|
||||
*/
|
||||
|
||||
public ScanScope excludeApplicationClassPath() {
|
||||
appClsPth = false;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds an entry to the list of package names to narrow down the set of Java types for lookup
|
||||
* operations by the classpath browser. Use of wildcard or any other form of pattern-matching
|
||||
* expressions are not allowed. All Java types under these packages and sub-packages are included in
|
||||
* the lookup scope.
|
||||
*
|
||||
* @param name a Java package name for inclusion.
|
||||
* @return this object for fluent style invocation of methods.
|
||||
*/
|
||||
|
||||
public ScanScope includePackage(String name) {
|
||||
includePkgs.add(name);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds an entry to the list of package names to narrow down the set of Java types for lookup
|
||||
* operations by the classpath browser. Use of wildcard or any other form of pattern-matching
|
||||
* expressions are not allowed. All Java types under this packages and sub-packages are excluded
|
||||
* from the lookup scope.
|
||||
*
|
||||
* @param name a Java package name for exclusion.
|
||||
* @return this object for fluent style invocation of methods.
|
||||
*/
|
||||
|
||||
public ScanScope excludePackage(String name) {
|
||||
excludePkgs.add(name);
|
||||
return this;
|
||||
}
|
||||
|
||||
/** Adds an entry to the list of inclusion patterns to narrow down the set of Java types for lookup
|
||||
* operations by the classpath browser. These patterns follow the semantics of Java regular
|
||||
* expressions. Each fully qualified type name on the classpaths and libpaths is matched against
|
||||
* these patterns for inclusion in the lookup scope.
|
||||
*
|
||||
* @param pattern a regular expression that can match a Java type name.
|
||||
* @return this object for fluent style invocation of methods.
|
||||
*/
|
||||
|
||||
public ScanScope includeClassesByPattern(String pattern) {
|
||||
includePats.add(pattern);
|
||||
return this;
|
||||
}
|
||||
|
||||
/** Adds an entry to the list of exclusion patterns to narrow down the set of Java types for lookup
|
||||
* operations by the classpath browser. These patterns follow the semantics of Java regular
|
||||
* expressions. Each fully qualified type name on the classpaths and libpaths is matched against
|
||||
* these patterns for exclusion from the lookup scope.
|
||||
*
|
||||
* @param pattern a regular expression that can match a Java type name.
|
||||
* @return this object for fluent style invocation of methods.
|
||||
*/
|
||||
|
||||
public ScanScope excludeClassesByPattern(String pattern) {
|
||||
excludePats.add(pattern);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds an entry to the list of type names to narrow down the set of Java types for lookup
|
||||
* operations by the classpath browser. Use of wildcard or any other form of pattern-matching
|
||||
* expressions are not allowed.
|
||||
*
|
||||
* @param name a fully qualified type name for inclusion in the lookup scope.
|
||||
* @return this object for fluent style invocation of methods.
|
||||
*/
|
||||
|
||||
public ScanScope includeClass(String name) {
|
||||
includeClasses.add(name);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds an entry to the list of type names to narrow down the set of Java types for lookup
|
||||
* operations by the classpath browser. Use of wildcard or any other form of pattern-matching
|
||||
* expressions are not allowed.
|
||||
*
|
||||
* @param name a fully qualified type name for exclusion from the lookup scope.
|
||||
* @return this object for fluent style invocation of methods.
|
||||
*/
|
||||
|
||||
public ScanScope excludeClass(String name) {
|
||||
excludeClasses.add(name);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new scanning scope using the data contained within this scope.
|
||||
*
|
||||
* @return the new scan scope
|
||||
*/
|
||||
|
||||
public ScanScope duplicate() {
|
||||
ScanScope scope = new ScanScope();
|
||||
scope.classPaths.addAll(classPaths);
|
||||
scope.includePkgs.addAll(includePkgs);
|
||||
scope.excludePkgs.addAll(excludePkgs);
|
||||
scope.includeClasses.addAll(includeClasses);
|
||||
scope.excludeClasses.addAll(excludeClasses);
|
||||
scope.includePats.addAll(includePats);
|
||||
scope.excludePats.addAll(excludePats);
|
||||
scope.appClsPth = appClsPth;
|
||||
return scope;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
/*
|
||||
* Copyright (c) DuxTechnica
|
||||
*
|
||||
* Licensed under the DuxTechnica Limited Use Source Code License Agreement (DT-LUSCL); you may not
|
||||
* use this file except in compliance with the License. You may obtain a copy of the License by
|
||||
* contacting:
|
||||
*
|
||||
* Dux Technica, [email protected]
|
||||
*
|
||||
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
|
||||
* either express or implied. See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package dux.scanpath.v2.bc;
|
||||
|
||||
import java.lang.classfile.Annotation;
|
||||
import java.lang.classfile.ClassFile;
|
||||
import java.lang.classfile.ClassModel;
|
||||
import java.lang.classfile.FieldModel;
|
||||
import java.lang.classfile.MethodModel;
|
||||
import java.lang.classfile.attribute.RuntimeVisibleAnnotationsAttribute;
|
||||
import java.lang.classfile.constantpool.ClassEntry;
|
||||
import java.lang.constant.ClassDesc;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Encapsulates metadata for a class read directly from a class file.
|
||||
*
|
||||
* <p>The metadata includes the class name, availability of class-file data, superclass, implemented
|
||||
* interfaces, runtime-visible annotations, fields, and methods.
|
||||
*
|
||||
* @author indroneel
|
||||
*/
|
||||
|
||||
public class ZClass {
|
||||
|
||||
private final String clsName;
|
||||
private final boolean available;
|
||||
|
||||
private ZClass supType;
|
||||
private List<ZClass> ifTypes;
|
||||
private List<ZClass> annTypes;
|
||||
private List<ZField> fields;
|
||||
private List<ZMethod> methods;
|
||||
|
||||
/**
|
||||
* Creates a placeholder for a class whose classfile data is unavailable.
|
||||
*
|
||||
* @param fqcn the fully qualified class name
|
||||
*/
|
||||
|
||||
ZClass(String fqcn) {
|
||||
clsName = fqcn;
|
||||
available = false;
|
||||
ifTypes = new ArrayList<>(); // avoid null pointer
|
||||
annTypes = new ArrayList<>(); // avoid null pointer
|
||||
fields = new ArrayList<>(); // avoid null pointer
|
||||
methods = new ArrayList<>(); // avoid null pointer
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses class metadata from the bytes in a class file.
|
||||
*
|
||||
* @param ctxt the class context used to resolve related classes
|
||||
* @param clsData the class-file contents
|
||||
*/
|
||||
|
||||
ZClass(ZClassContext ctxt, byte[] clsData) {
|
||||
ClassModel clsMod = ClassFile.of().parse(clsData);
|
||||
available = true;
|
||||
ClassEntry ce = clsMod.thisClass();
|
||||
clsName = ce.asInternalName().replace('/', '.');
|
||||
|
||||
prepareSuperClass(ctxt, clsMod);
|
||||
prepareInterfaces(ctxt, clsMod);
|
||||
prepareAnnotations(ctxt, clsMod);
|
||||
prepareFields(ctxt, clsMod);
|
||||
prepareMethods(ctxt, clsMod);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the fully qualified class name.
|
||||
*
|
||||
* @return the class name
|
||||
*/
|
||||
|
||||
public String getName() {
|
||||
return clsName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Indicates whether classfile data was available when this object was created.
|
||||
*
|
||||
* @return {@code true} if the class was parsed from class-file data; otherwise, {@code false}
|
||||
*/
|
||||
|
||||
public boolean isAvailable() {
|
||||
return available;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the interfaces implemented by this class.
|
||||
*
|
||||
* @return the implemented interface metadata
|
||||
*/
|
||||
|
||||
public List<ZClass> getInterfaces() {
|
||||
return ifTypes;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the superclass metadata.
|
||||
*
|
||||
* @return the superclass, or {@code null} if no superclass is present
|
||||
*/
|
||||
|
||||
public ZClass getSuperClass() {
|
||||
return supType;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the types of the class's runtime-visible annotations.
|
||||
*
|
||||
* @return the class's annotation types
|
||||
*/
|
||||
|
||||
public List<ZClass> getAnnotations() {
|
||||
return annTypes;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the fields declared by this class.
|
||||
*
|
||||
* @return all field metadata as a list
|
||||
*/
|
||||
|
||||
public List<ZField> getFields() {
|
||||
return fields;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the methods declared by this class.
|
||||
*
|
||||
* @return all method metadata as a list
|
||||
*/
|
||||
|
||||
public List<ZMethod> getMethods() {
|
||||
return methods;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
// Helper methods
|
||||
|
||||
private void prepareSuperClass(ZClassContext clsCtxt, ClassModel clsMod) {
|
||||
supType = null;
|
||||
Optional<ClassEntry> optSup = clsMod.superclass();
|
||||
if(optSup.isPresent()) {
|
||||
ClassEntry ce = optSup.get();
|
||||
String pclsName = ce.asInternalName().replace('/', '.');
|
||||
supType = clsCtxt.getZClass(pclsName);
|
||||
}
|
||||
}
|
||||
|
||||
private void prepareInterfaces(ZClassContext clsCtxt, ClassModel clsMod) {
|
||||
ifTypes = new ArrayList<>();
|
||||
List<ClassEntry> ifentries = clsMod.interfaces();
|
||||
if(ifentries == null) {
|
||||
return;
|
||||
}
|
||||
for (ClassEntry ce : ifentries) {
|
||||
String iclsName = ce.asInternalName().replace('/', '.');
|
||||
ZClass iftype = clsCtxt.getZClass(iclsName);
|
||||
if (iftype != null) {
|
||||
ifTypes.add(iftype);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void prepareAnnotations(ZClassContext clsCtxt, ClassModel clsMod) {
|
||||
annTypes = new ArrayList<>();
|
||||
clsMod.forEach(ce -> {
|
||||
if(ce instanceof RuntimeVisibleAnnotationsAttribute annAtr) {
|
||||
List<Annotation> annotations = annAtr.annotations();
|
||||
for (Annotation ann : annotations) {
|
||||
ClassDesc desc = ann.classSymbol();
|
||||
String annType = desc.packageName().isEmpty() ?
|
||||
desc.displayName() : desc.packageName() + "." + desc.displayName();
|
||||
annType = annType.replace('/', '.');
|
||||
ZClass annCls = clsCtxt.getZClass(annType);
|
||||
if(annCls != null) {
|
||||
annTypes.add(annCls);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void prepareFields(ZClassContext clsCtxt, ClassModel clsMod) {
|
||||
fields = new ArrayList<>();
|
||||
clsMod.forEach(ce -> {
|
||||
if(ce instanceof FieldModel) {
|
||||
ZField zfld = new ZField(clsCtxt, (FieldModel) ce);
|
||||
fields.add(zfld);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void prepareMethods(ZClassContext clsCtxt, ClassModel clsMod) {
|
||||
methods = new ArrayList<>();
|
||||
clsMod.forEach(ce -> {
|
||||
if(ce instanceof MethodModel) {
|
||||
ZMethod zmthd = new ZMethod(clsCtxt, (MethodModel) ce);
|
||||
methods.add(zmthd);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
/*
|
||||
* Copyright (c) DuxTechnica
|
||||
*
|
||||
* Licensed under the DuxTechnica Limited Use Source Code License Agreement (DT-LUSCL); you may not
|
||||
* use this file except in compliance with the License. You may obtain a copy of the License by
|
||||
* contacting:
|
||||
*
|
||||
* Dux Technica, [email protected]
|
||||
*
|
||||
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
|
||||
* either express or implied. See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package dux.scanpath.v2.bc;
|
||||
|
||||
import dux.scanpath.v2.io.BinFile;
|
||||
import dux.scanpath.v2.io.BinSource;
|
||||
import dux.scanpath.v2.io.DiskBinSource;
|
||||
import dux.scanpath.v2.io.JarBinSource;
|
||||
import dux.scanpath.v2.io.ZipBinSource;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.jar.JarFile;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
import java.util.zip.ZipFile;
|
||||
|
||||
/**
|
||||
* Provides access to class metadata discovered from configured classpath locations.
|
||||
*
|
||||
* <p>A context maintains the configured {@link BinSource} instances, an index of their
|
||||
* {@link BinFile} entries, and the {@link ZClass} instances created from those entries. Call
|
||||
* {@link #prepareIndex()} after adding class paths and before querying class names or metadata.
|
||||
*
|
||||
* @author indroneel
|
||||
*/
|
||||
|
||||
public class ZClassContext {
|
||||
|
||||
private static final Logger L = Logger.getLogger(ZClassContext.class.getName());
|
||||
|
||||
private final List<BinSource> binSrcList;
|
||||
private final Map<String, BinFile> binFileMap;
|
||||
private final Map<String, ZClass> clsMap;
|
||||
|
||||
/**
|
||||
* Creates an empty class context with no configured class-path locations.
|
||||
*/
|
||||
|
||||
public ZClassContext() {
|
||||
binSrcList = new LinkedList<>();
|
||||
binFileMap = new HashMap<>();
|
||||
clsMap = new HashMap<>();
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a class-path location to this context.
|
||||
*
|
||||
* <p>Paths ending in {@code .zip} or {@code .jar} are treated as archive files. Other paths are
|
||||
* treated as directories. The location is not indexed until {@link #prepareIndex()} is called.
|
||||
* Invalid or unreadable locations are ignored after a warning is logged.
|
||||
*
|
||||
* @param path the path to a class-file directory, ZIP archive, or JAR archive
|
||||
*/
|
||||
|
||||
public void appendClassPath(String path) {
|
||||
String lpath = path.toLowerCase(Locale.getDefault()).trim();
|
||||
if(lpath.endsWith(".zip")) {
|
||||
File sf = new File(path).getAbsoluteFile();
|
||||
if(sf.isFile()) {
|
||||
try {
|
||||
ZipFile zipFile = new ZipFile(sf);
|
||||
ZipBinSource bsrc = new ZipBinSource(zipFile);
|
||||
binSrcList.add(bsrc);
|
||||
}
|
||||
catch (Exception exep) {
|
||||
if (L.isLoggable(Level.WARNING)) {
|
||||
L.log(Level.WARNING, "Could not open ZIP source: " + path, exep);
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
if(L.isLoggable(Level.WARNING)) {
|
||||
L.log(Level.WARNING, "Not a file: " + path);
|
||||
}
|
||||
}
|
||||
}
|
||||
else if(lpath.endsWith(".jar")) {
|
||||
File sf = new File(path).getAbsoluteFile();
|
||||
if(sf.isFile()) {
|
||||
try {
|
||||
JarFile jarFile = new JarFile(sf);
|
||||
JarBinSource bsrc = new JarBinSource(jarFile);
|
||||
binSrcList.add(bsrc);
|
||||
}
|
||||
catch (Exception exep) {
|
||||
if (L.isLoggable(Level.WARNING)) {
|
||||
L.log(Level.WARNING, "Could not open JAR source: " + path, exep);
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
if(L.isLoggable(Level.WARNING)) {
|
||||
L.log(Level.WARNING, "Not a file: " + path);
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
File sd = new File(path).getAbsoluteFile();
|
||||
if(sd.isDirectory()) {
|
||||
try {
|
||||
DiskBinSource bsrc = new DiskBinSource(sd);
|
||||
binSrcList.add(bsrc);
|
||||
}
|
||||
catch (Exception exep) {
|
||||
if (L.isLoggable(Level.WARNING)) {
|
||||
L.log(Level.WARNING, "Could not open directory source: " + path, exep);
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
if(L.isLoggable(Level.WARNING)) {
|
||||
L.log(Level.WARNING, "Not a directory: " + path);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Rebuilds the class-file index from all classpath locations currently configured. Rebuilding also
|
||||
* discards all previously created {@link ZClass} instances.
|
||||
*/
|
||||
|
||||
public void prepareIndex() {
|
||||
binFileMap.clear();
|
||||
clsMap.clear();
|
||||
for(BinSource bsrc : binSrcList) {
|
||||
for(BinFile bfile : bsrc.getFiles()) {
|
||||
binFileMap.put(bfile.getClassName(), bfile);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Clears the indexed class files and cached class metadata.
|
||||
*
|
||||
* <p>Configured classpath locations remain available and can be indexed again by calling
|
||||
* {@link #prepareIndex()}.
|
||||
*/
|
||||
|
||||
public void close() {
|
||||
binFileMap.clear();
|
||||
clsMap.clear();
|
||||
}
|
||||
|
||||
/**
|
||||
* Lists the fully qualified names of the class files in the current index.
|
||||
*
|
||||
* @return an immutable snapshot of the indexed class names
|
||||
*/
|
||||
|
||||
public List<String> listClassNames() {
|
||||
return List.copyOf(binFileMap.keySet());
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves metadata for a class by fully qualified name.
|
||||
*
|
||||
* <p>If the class is present in the current index, its bytecode is parsed and the resulting
|
||||
* metadata is cached. If it is not indexed, a placeholder {@link ZClass} is created and cached.
|
||||
*
|
||||
* @param clsName the fully qualified class name
|
||||
* @return the cached or newly created class metadata
|
||||
*/
|
||||
|
||||
public ZClass getZClass(String clsName) {
|
||||
ZClass zcls = null;
|
||||
if(clsMap.containsKey(clsName)) {
|
||||
zcls = clsMap.get(clsName);
|
||||
}
|
||||
else if(binFileMap.containsKey(clsName)) {
|
||||
BinFile bfile = binFileMap.get(clsName);
|
||||
try {
|
||||
zcls = new ZClass(this, bfile.getContent());
|
||||
clsMap.put(clsName, zcls);
|
||||
}
|
||||
catch(Exception exep) {
|
||||
if(L.isLoggable(Level.WARNING)) {
|
||||
L.log(Level.WARNING, "Could not parse class file: " + clsName, exep);
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
zcls = new ZClass(clsName);
|
||||
clsMap.put(clsName, zcls);
|
||||
}
|
||||
return zcls;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
/*
|
||||
* Copyright (c) DuxTechnica
|
||||
*
|
||||
* Licensed under the DuxTechnica Limited Use Source Code License Agreement (DT-LUSCL); you may not
|
||||
* use this file except in compliance with the License. You may obtain a copy of the License by
|
||||
* contacting:
|
||||
*
|
||||
* Dux Technica, [email protected]
|
||||
*
|
||||
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
|
||||
* either express or implied. See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package dux.scanpath.v2.bc;
|
||||
|
||||
import java.lang.classfile.AccessFlags;
|
||||
import java.lang.classfile.Annotation;
|
||||
import java.lang.classfile.FieldModel;
|
||||
import java.lang.classfile.attribute.RuntimeVisibleAnnotationsAttribute;
|
||||
import java.lang.constant.ClassDesc;
|
||||
import java.lang.reflect.AccessFlag;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Encapsulates metadata for a field read directly from a class file.
|
||||
*
|
||||
* <p>The metadata includes the field name, whether it is static, and the types of its annotations
|
||||
* that are visible at runtime.
|
||||
*
|
||||
* @author indroneel
|
||||
*/
|
||||
|
||||
public class ZField {
|
||||
|
||||
private final String fldName;
|
||||
private Set<AccessFlag> accessFlags;
|
||||
private final List<ZClass> annTypes;
|
||||
|
||||
/**
|
||||
* Creates field metadata from a classfile field model.
|
||||
*
|
||||
* @param ctxt the class context used to resolve annotation types
|
||||
* @param fldMod the class-file model of the field
|
||||
*/
|
||||
|
||||
public ZField(ZClassContext ctxt, FieldModel fldMod) {
|
||||
annTypes = new ArrayList<>();
|
||||
fldName = fldMod.fieldName().stringValue();
|
||||
|
||||
fldMod.forEach(ce -> {
|
||||
if(ce instanceof AccessFlags aflgs) {
|
||||
accessFlags = aflgs.flags();
|
||||
}
|
||||
else if(ce instanceof RuntimeVisibleAnnotationsAttribute annAtr) {
|
||||
List<Annotation> annotations = annAtr.annotations();
|
||||
for (Annotation ann : annotations) {
|
||||
ClassDesc desc = ann.classSymbol();
|
||||
String annType = desc.packageName().isEmpty() ?
|
||||
desc.displayName() : desc.packageName() + "." + desc.displayName();
|
||||
annType = annType.replace('/', '.');
|
||||
ZClass annCls = ctxt.getZClass(annType);
|
||||
if(annCls != null) {
|
||||
annTypes.add(annCls);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
ClassDesc desc = fldMod.fieldTypeSymbol();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the field name.
|
||||
*
|
||||
* @return the field name
|
||||
*/
|
||||
|
||||
public String getName() {
|
||||
return fldName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Indicates whether the field has the {@code static} modifier.
|
||||
*
|
||||
* @return {@code true} if the field is static; otherwise, {@code false}
|
||||
*/
|
||||
|
||||
public boolean isStatic() {
|
||||
return accessFlags.contains(AccessFlag.STATIC);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the types of the field's runtime-visible annotations.
|
||||
*
|
||||
* @return the field's annotation types
|
||||
*/
|
||||
|
||||
public List<ZClass> getAnnotations() {
|
||||
return annTypes;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
/*
|
||||
* Copyright (c) DuxTechnica
|
||||
*
|
||||
* Licensed under the DuxTechnica Limited Use Source Code License Agreement (DT-LUSCL); you may not
|
||||
* use this file except in compliance with the License. You may obtain a copy of the License by
|
||||
* contacting:
|
||||
*
|
||||
* Dux Technica, [email protected]
|
||||
*
|
||||
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
|
||||
* either express or implied. See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package dux.scanpath.v2.bc;
|
||||
|
||||
import java.lang.classfile.AccessFlags;
|
||||
import java.lang.classfile.Annotation;
|
||||
import java.lang.classfile.MethodModel;
|
||||
import java.lang.classfile.attribute.RuntimeVisibleAnnotationsAttribute;
|
||||
import java.lang.constant.ClassDesc;
|
||||
import java.lang.constant.MethodTypeDesc;
|
||||
import java.lang.reflect.AccessFlag;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Encapsulates metadata for a method read directly from a class file.
|
||||
*
|
||||
* <p>The metadata includes the method name, access modifiers, and the types of its annotations that
|
||||
* are visible at runtime.
|
||||
*
|
||||
* @author indroneel
|
||||
*/
|
||||
|
||||
public class ZMethod {
|
||||
|
||||
private final String mthdName;
|
||||
private Set<AccessFlag> accessFlags;
|
||||
private final List<ZClass> annTypes;
|
||||
|
||||
/**
|
||||
* Creates method metadata from a class-file method model.
|
||||
*
|
||||
* @param ctxt the class context used to resolve annotation types
|
||||
* @param mthdMod the class-file model of the method
|
||||
*/
|
||||
|
||||
public ZMethod(ZClassContext ctxt, MethodModel mthdMod) {
|
||||
annTypes = new ArrayList<>();
|
||||
mthdName = mthdMod.methodName().stringValue();
|
||||
|
||||
mthdMod.forEach(ce -> {
|
||||
if(ce instanceof AccessFlags aflgs) {
|
||||
accessFlags = aflgs.flags();
|
||||
}
|
||||
else if(ce instanceof RuntimeVisibleAnnotationsAttribute annAtr) {
|
||||
List<Annotation> annotations = annAtr.annotations();
|
||||
for (Annotation ann : annotations) {
|
||||
ClassDesc desc = ann.classSymbol();
|
||||
String annType = desc.packageName().isEmpty() ?
|
||||
desc.displayName() : desc.packageName() + "." + desc.displayName();
|
||||
annType = annType.replace('/', '.');
|
||||
ZClass annCls = ctxt.getZClass(annType);
|
||||
if(annCls != null) {
|
||||
annTypes.add(annCls);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
MethodTypeDesc desc = mthdMod.methodTypeSymbol();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the method name.
|
||||
*
|
||||
* @return the method name
|
||||
*/
|
||||
|
||||
public String getName() {
|
||||
return mthdName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Indicates whether the method has the {@code static} modifier.
|
||||
*
|
||||
* @return {@code true} if the method is static; otherwise, {@code false}
|
||||
*/
|
||||
|
||||
public boolean isStatic() {
|
||||
return accessFlags.contains(AccessFlag.STATIC);
|
||||
}
|
||||
|
||||
/**
|
||||
* Indicates whether the method has the {@code abstract} modifier.
|
||||
*
|
||||
* @return {@code true} if the method is abstract; otherwise, {@code false}
|
||||
*/
|
||||
|
||||
public boolean isAbstract() {
|
||||
return accessFlags.contains(AccessFlag.ABSTRACT);
|
||||
}
|
||||
|
||||
/**
|
||||
* Indicates whether the method has the {@code native} modifier.
|
||||
*
|
||||
* @return {@code true} if the method is native; otherwise, {@code false}
|
||||
*/
|
||||
|
||||
public boolean isNative() {
|
||||
return accessFlags.contains(AccessFlag.NATIVE);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the types of the method's runtime-visible annotations.
|
||||
*
|
||||
* @return the method's annotation types
|
||||
*/
|
||||
|
||||
public List<ZClass> getAnnotations() {
|
||||
return annTypes;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
/*
|
||||
* Copyright (c) DuxTechnica
|
||||
*
|
||||
* Licensed under the DuxTechnica Limited Use Source Code License Agreement (DT-LUSCL); you may not
|
||||
* use this file except in compliance with the License. You may obtain a copy of the License by
|
||||
* contacting:
|
||||
*
|
||||
* Dux Technica, [email protected]
|
||||
*
|
||||
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
|
||||
* either express or implied. See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package dux.scanpath.v2.io;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* Represents a file or archive entry containing the bytecode of a Java class.
|
||||
*
|
||||
* @author indroneel
|
||||
*/
|
||||
|
||||
public interface BinFile {
|
||||
|
||||
/**
|
||||
* Returns the fully qualified name of the class whose bytecode is contained in this file.
|
||||
*
|
||||
* @return the fully qualified class name
|
||||
*/
|
||||
|
||||
String getClassName();
|
||||
|
||||
/**
|
||||
* Returns the class name without package information.
|
||||
*
|
||||
* @return the simple class name
|
||||
*/
|
||||
|
||||
String getSimpleClassName();
|
||||
|
||||
/**
|
||||
* Reads the binary contents of the class file.
|
||||
*
|
||||
* @return the class-file contents
|
||||
* @throws IOException if the contents cannot be read
|
||||
*/
|
||||
|
||||
byte[] getContent() throws IOException;
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
/*
|
||||
* Copyright (c) DuxTechnica
|
||||
*
|
||||
* Licensed under the DuxTechnica Limited Use Source Code License Agreement (DT-LUSCL); you may not
|
||||
* use this file except in compliance with the License. You may obtain a copy of the License by
|
||||
* contacting:
|
||||
*
|
||||
* Dux Technica, [email protected]
|
||||
*
|
||||
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
|
||||
* either express or implied. See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package dux.scanpath.v2.io;
|
||||
|
||||
/**
|
||||
* Provides access to class files discovered in a specific location, such as a directory, ZIP
|
||||
* archive, or JAR archive.
|
||||
*
|
||||
* @author indroneel
|
||||
*/
|
||||
|
||||
public interface BinSource {
|
||||
|
||||
/**
|
||||
* Returns the class files available from this source.
|
||||
*
|
||||
* @return an iterable of class-file representations
|
||||
*/
|
||||
Iterable<BinFile> getFiles();
|
||||
|
||||
/**
|
||||
* Releases resources held by this source.
|
||||
*/
|
||||
void close();
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
/*
|
||||
* Copyright (c) DuxTechnica
|
||||
*
|
||||
* Licensed under the DuxTechnica Limited Use Source Code License Agreement (DT-LUSCL); you may not
|
||||
* use this file except in compliance with the License. You may obtain a copy of the License by
|
||||
* contacting:
|
||||
*
|
||||
* Dux Technica, [email protected]
|
||||
*
|
||||
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
|
||||
* either express or implied. See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package dux.scanpath.v2.io;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* Represents a local filesystem class file.
|
||||
*
|
||||
* @author indroneel
|
||||
*
|
||||
*/
|
||||
|
||||
public class DiskBinFile implements BinFile {
|
||||
|
||||
private final File root;
|
||||
private final File file;
|
||||
|
||||
/**
|
||||
* Creates a representation of a class file relative to a filesystem root.
|
||||
*
|
||||
* @param root the root directory containing the class file
|
||||
* @param file the class file
|
||||
*/
|
||||
public DiskBinFile(File root, File file) {
|
||||
this.root = root;
|
||||
this.file = file;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
// Methods of interface BinFile
|
||||
|
||||
/**
|
||||
* Returns the class name derived from the file's path relative to the root directory.
|
||||
*
|
||||
* @return the fully qualified class name
|
||||
*/
|
||||
|
||||
@Override
|
||||
public String getClassName() {
|
||||
String filepath = file.getPath();
|
||||
if (filepath.startsWith(root.getPath())) {
|
||||
filepath = filepath.substring(root.getPath().length() + 1);
|
||||
}
|
||||
int endpos = filepath.lastIndexOf('.');
|
||||
return filepath.substring(0, endpos).replace(File.separatorChar, '.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the class name without package information.
|
||||
*
|
||||
* @return the simple class name
|
||||
*/
|
||||
|
||||
@Override
|
||||
public String getSimpleClassName() {
|
||||
String filepath = file.getName();
|
||||
int endpos = filepath.lastIndexOf('.');
|
||||
return filepath.substring(0, endpos);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the class-file contents from the local filesystem.
|
||||
*
|
||||
* @return the class-file contents
|
||||
* @throws IOException if the file cannot be read
|
||||
*/
|
||||
|
||||
@Override
|
||||
public byte[] getContent() throws IOException {
|
||||
FileInputStream fis = new FileInputStream(file);
|
||||
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
|
||||
byte[] chunk = new byte[1024];
|
||||
int amt = 0;
|
||||
while(amt >=0) {
|
||||
amt = fis.read(chunk);
|
||||
buffer.write(chunk, 0, Math.max(amt, 0));
|
||||
}
|
||||
fis.close();
|
||||
buffer.flush();
|
||||
buffer.close();
|
||||
return buffer.toByteArray();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
/*
|
||||
* Copyright (c) DuxTechnica
|
||||
*
|
||||
* Licensed under the DuxTechnica Limited Use Source Code License Agreement (DT-LUSCL); you may not
|
||||
* use this file except in compliance with the License. You may obtain a copy of the License by
|
||||
* contacting:
|
||||
*
|
||||
* Dux Technica, [email protected]
|
||||
*
|
||||
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
|
||||
* either express or implied. See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package dux.scanpath.v2.io;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileFilter;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Stack;
|
||||
|
||||
/**
|
||||
* Discovers class files recursively within a local filesystem directory.
|
||||
*
|
||||
* @author indroneel
|
||||
*/
|
||||
|
||||
public class DiskBinSource implements BinSource {
|
||||
|
||||
private final File root;
|
||||
|
||||
/**
|
||||
* Creates a source rooted at the supplied directory.
|
||||
*
|
||||
* @param dir the directory to scan, or {@code null} for an empty source
|
||||
* @throws RuntimeException if {@code dir} is not a readable directory
|
||||
*/
|
||||
|
||||
public DiskBinSource(File dir) {
|
||||
if (dir != null && (!dir.isDirectory() || !dir.canRead())) {
|
||||
throw new RuntimeException("cannot use dir " + dir);
|
||||
}
|
||||
root = dir;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
// Methods of interface BinSource
|
||||
|
||||
/**
|
||||
* Recursively finds files with the {@code .class} extension below the root directory.
|
||||
*
|
||||
* @return the discovered class files, or an empty collection when no root is available
|
||||
*/
|
||||
|
||||
@Override
|
||||
public Iterable<BinFile> getFiles() {
|
||||
List<BinFile> resList = Collections.emptyList();
|
||||
if (root != null && root.exists()) {
|
||||
Stack<File> stack = new Stack<File>();
|
||||
stack.addAll(listFiles(root));
|
||||
|
||||
resList = new LinkedList<>();
|
||||
while (!stack.isEmpty()) {
|
||||
final File file = stack.pop();
|
||||
if (file.isDirectory()) {
|
||||
stack.addAll(listFiles(file));
|
||||
}
|
||||
else {
|
||||
resList.add(new DiskBinFile(root, file));
|
||||
}
|
||||
}
|
||||
}
|
||||
return resList;
|
||||
}
|
||||
|
||||
/**
|
||||
* Releases resources held by this filesystem source.
|
||||
*
|
||||
* <p>This implementation does not hold resources and therefore performs no action.
|
||||
*/
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
// NOOP
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
// Helper methods
|
||||
|
||||
private List<File> listFiles(final File file) {
|
||||
FileFilter filter = new FileFilter() {
|
||||
@Override
|
||||
public boolean accept(File pathname) {
|
||||
if(pathname.isDirectory()) {
|
||||
return true;
|
||||
}
|
||||
return pathname.getName().toLowerCase().endsWith(".class");
|
||||
}
|
||||
};
|
||||
File[] files = file.listFiles(filter);
|
||||
|
||||
if (files != null)
|
||||
return Arrays.asList(files);
|
||||
else
|
||||
return Collections.emptyList();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
/*
|
||||
* Copyright (c) DuxTechnica
|
||||
*
|
||||
* Licensed under the DuxTechnica Limited Use Source Code License Agreement (DT-LUSCL); you may not
|
||||
* use this file except in compliance with the License. You may obtain a copy of the License by
|
||||
* contacting:
|
||||
*
|
||||
* Dux Technica, [email protected]
|
||||
*
|
||||
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
|
||||
* either express or implied. See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package dux.scanpath.v2.io;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.jar.JarEntry;
|
||||
import java.util.jar.JarFile;
|
||||
|
||||
/**
|
||||
* Represents a class-file entry within a JAR archive.
|
||||
*
|
||||
* @author indroneel
|
||||
*/
|
||||
|
||||
public class JarBinFile implements BinFile {
|
||||
|
||||
private final JarFile root;
|
||||
private final JarEntry entry;
|
||||
|
||||
/**
|
||||
* Creates a representation of a JAR class-file entry.
|
||||
*
|
||||
* @param root the containing JAR file
|
||||
* @param entry the class-file entry
|
||||
*/
|
||||
public JarBinFile(JarFile root, JarEntry entry) {
|
||||
this.root = root;
|
||||
this.entry = entry;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
// Methods of interface BinFile
|
||||
|
||||
/**
|
||||
* Returns the fully qualified class name derived from the archive entry name.
|
||||
*
|
||||
* @return the fully qualified class name
|
||||
*/
|
||||
|
||||
@Override
|
||||
public String getClassName() {
|
||||
String name = entry.getName();
|
||||
if(name.startsWith("/")) {
|
||||
name = name.substring(1, name.lastIndexOf('.')).replace('/', '.');
|
||||
}
|
||||
else {
|
||||
name = name.substring(0, name.lastIndexOf('.')).replace('/', '.');
|
||||
}
|
||||
return name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the class name without package information.
|
||||
*
|
||||
* @return the simple class name
|
||||
*/
|
||||
|
||||
@Override
|
||||
public String getSimpleClassName() {
|
||||
String fqcn = getClassName();
|
||||
return fqcn.substring(fqcn.lastIndexOf('.') + 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the class-file contents from the JAR archive.
|
||||
*
|
||||
* @return the class-file contents
|
||||
* @throws IOException if the entry cannot be read
|
||||
*/
|
||||
|
||||
@Override
|
||||
public byte[] getContent() throws IOException {
|
||||
InputStream istrm = root.getInputStream(entry);
|
||||
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
|
||||
byte[] chunk = new byte[1024];
|
||||
int amt = 0;
|
||||
while(amt >=0) {
|
||||
amt = istrm.read(chunk);
|
||||
buffer.write(chunk, 0, Math.max(amt, 0));
|
||||
}
|
||||
istrm.close();
|
||||
buffer.flush();
|
||||
buffer.close();
|
||||
return buffer.toByteArray();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the archive path and entry path identifying this class file.
|
||||
*
|
||||
* @return the JAR entry location
|
||||
*/
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return root.getName() + "!" + java.io.File.separatorChar + entry.toString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
/*
|
||||
* Copyright (c) DuxTechnica
|
||||
*
|
||||
* Licensed under the DuxTechnica Limited Use Source Code License Agreement (DT-LUSCL); you may not
|
||||
* use this file except in compliance with the License. You may obtain a copy of the License by
|
||||
* contacting:
|
||||
*
|
||||
* Dux Technica, [email protected]
|
||||
*
|
||||
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
|
||||
* either express or implied. See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package dux.scanpath.v2.io;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Enumeration;
|
||||
import java.util.LinkedList;
|
||||
import java.util.jar.JarEntry;
|
||||
import java.util.jar.JarFile;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
/**
|
||||
* Discovers class-file entries within a JAR archive.
|
||||
*
|
||||
* @author indroneel
|
||||
*/
|
||||
|
||||
public class JarBinSource implements BinSource {
|
||||
|
||||
private static final Logger _L = Logger.getLogger(JarBinSource.class.getName());
|
||||
|
||||
private final JarFile jarFile;
|
||||
|
||||
/**
|
||||
* Creates a source backed by the supplied JAR file.
|
||||
*
|
||||
* @param file the JAR file to scan
|
||||
*/
|
||||
public JarBinSource(JarFile file) {
|
||||
jarFile = file;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
// Methods of interface ClassArchive
|
||||
|
||||
/**
|
||||
* Returns all non-directory entries whose names end with {@code .class}.
|
||||
*
|
||||
* @return the discovered JAR class-file entries
|
||||
*/
|
||||
|
||||
@Override
|
||||
public Iterable<BinFile> getFiles() {
|
||||
LinkedList<BinFile> ll = new LinkedList<>();
|
||||
Enumeration<? extends JarEntry> entries = jarFile.entries();
|
||||
while (entries.hasMoreElements()) {
|
||||
JarEntry entry = entries.nextElement();
|
||||
if (!entry.isDirectory()) {
|
||||
String entryName = entry.getName().toLowerCase();
|
||||
if(entryName.endsWith(".class")) {
|
||||
ll.add(new JarBinFile(jarFile, entry));
|
||||
}
|
||||
}
|
||||
}
|
||||
return ll;
|
||||
}
|
||||
|
||||
/**
|
||||
* Closes the underlying JAR file.
|
||||
*/
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
try {
|
||||
jarFile.close();
|
||||
}
|
||||
catch (IOException exep) {
|
||||
if(_L.isLoggable(Level.WARNING)) {
|
||||
_L.log(Level.WARNING, "unable to release jar file: " + jarFile.getName(), exep);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the path of the underlying JAR file.
|
||||
*
|
||||
* @return the JAR file path
|
||||
*/
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return jarFile.getName();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
/*
|
||||
* Copyright (c) DuxTechnica
|
||||
*
|
||||
* Licensed under the DuxTechnica Limited Use Source Code License Agreement (DT-LUSCL); you may not
|
||||
* use this file except in compliance with the License. You may obtain a copy of the License by
|
||||
* contacting:
|
||||
*
|
||||
* Dux Technica, [email protected]
|
||||
*
|
||||
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
|
||||
* either express or implied. See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package dux.scanpath.v2.io;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipFile;
|
||||
|
||||
/**
|
||||
* Represents a class-file entry within a ZIP archive.
|
||||
*
|
||||
* @author indroneel
|
||||
*/
|
||||
|
||||
public class ZipBinFile implements BinFile {
|
||||
|
||||
private final ZipFile root;
|
||||
private final ZipEntry entry;
|
||||
|
||||
/**
|
||||
* Creates a representation of a ZIP class-file entry.
|
||||
*
|
||||
* @param root the containing ZIP file
|
||||
* @param entry the class-file entry
|
||||
*/
|
||||
public ZipBinFile(ZipFile root, ZipEntry entry) {
|
||||
this.root = root;
|
||||
this.entry = entry;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
// Methods of interface BinFile
|
||||
|
||||
/**
|
||||
* Returns the fully qualified class name derived from the archive entry name.
|
||||
*
|
||||
* @return the fully qualified class name
|
||||
*/
|
||||
|
||||
@Override
|
||||
public String getClassName() {
|
||||
String name = entry.getName();
|
||||
if(name.startsWith("/")) {
|
||||
name = name.substring(1, name.lastIndexOf('.')).replace('/', '.');
|
||||
}
|
||||
else {
|
||||
name = name.substring(0, name.lastIndexOf('.')).replace('/', '.');
|
||||
}
|
||||
return name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the class name without package information.
|
||||
*
|
||||
* @return the simple class name
|
||||
*/
|
||||
|
||||
@Override
|
||||
public String getSimpleClassName() {
|
||||
String fqcn = getClassName();
|
||||
return fqcn.substring(fqcn.lastIndexOf('.') + 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the class-file contents from the ZIP archive.
|
||||
*
|
||||
* @return the class-file contents
|
||||
* @throws IOException if the entry cannot be read
|
||||
*/
|
||||
|
||||
@Override
|
||||
public byte[] getContent() throws IOException {
|
||||
InputStream istrm = root.getInputStream(entry);
|
||||
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
|
||||
byte[] chunk = new byte[1024];
|
||||
int amt = 0;
|
||||
while(amt >=0) {
|
||||
amt = istrm.read(chunk);
|
||||
buffer.write(chunk, 0, Math.max(amt, 0));
|
||||
}
|
||||
istrm.close();
|
||||
buffer.flush();
|
||||
buffer.close();
|
||||
return buffer.toByteArray();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the archive path and entry path identifying this class file.
|
||||
*
|
||||
* @return the ZIP entry location
|
||||
*/
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return root.getName() + "!" + java.io.File.separatorChar + entry.toString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
/*
|
||||
* Copyright (c) DuxTechnica
|
||||
*
|
||||
* Licensed under the DuxTechnica Limited Use Source Code License Agreement (DT-LUSCL); you may not
|
||||
* use this file except in compliance with the License. You may obtain a copy of the License by
|
||||
* contacting:
|
||||
*
|
||||
* Dux Technica, [email protected]
|
||||
*
|
||||
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
|
||||
* either express or implied. See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package dux.scanpath.v2.io;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Enumeration;
|
||||
import java.util.LinkedList;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipFile;
|
||||
|
||||
/**
|
||||
* Discovers class-file entries within a ZIP archive.
|
||||
*
|
||||
* @author indroneel
|
||||
*/
|
||||
|
||||
public class ZipBinSource implements BinSource {
|
||||
|
||||
private static final Logger _L = Logger.getLogger(ZipBinSource.class.getName());
|
||||
|
||||
private final ZipFile zipFile;
|
||||
|
||||
/**
|
||||
* Creates a source backed by the supplied ZIP file.
|
||||
*
|
||||
* @param file the ZIP file to scan
|
||||
*/
|
||||
public ZipBinSource(ZipFile file) {
|
||||
zipFile = file;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
// Methods of interface BinSource
|
||||
|
||||
/**
|
||||
* Returns all non-directory entries whose names end with {@code .class}.
|
||||
*
|
||||
* @return the discovered ZIP class-file entries
|
||||
*/
|
||||
|
||||
@Override
|
||||
public Iterable<BinFile> getFiles() {
|
||||
LinkedList<BinFile> ll = new LinkedList<>();
|
||||
Enumeration<? extends ZipEntry> entries = zipFile.entries();
|
||||
while (entries.hasMoreElements()) {
|
||||
ZipEntry entry = entries.nextElement();
|
||||
if (!entry.isDirectory()) {
|
||||
String entryName = entry.getName().toLowerCase();
|
||||
if(entryName.endsWith(".class")) {
|
||||
ll.add(new ZipBinFile(zipFile, entry));
|
||||
}
|
||||
}
|
||||
}
|
||||
return ll;
|
||||
}
|
||||
|
||||
/**
|
||||
* Closes the underlying ZIP file.
|
||||
*/
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
try {
|
||||
zipFile.close();
|
||||
}
|
||||
catch (IOException exep) {
|
||||
if(_L.isLoggable(Level.WARNING)) {
|
||||
_L.log(Level.WARNING, "unable to release zip file: " + zipFile.getName(), exep);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the path of the underlying ZIP file.
|
||||
*
|
||||
* @return the ZIP file path
|
||||
*/
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return zipFile.getName();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
/*
|
||||
* Copyright (c) DuxTechnica
|
||||
*
|
||||
* Licensed under the DuxTechnica Limited Use Source Code License Agreement (DT-LUSCL); you may not
|
||||
* use this file except in compliance with the License. You may obtain a copy of the License by
|
||||
* contacting:
|
||||
*
|
||||
* Dux Technica, [email protected]
|
||||
*
|
||||
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
|
||||
* either express or implied. See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package dux.scanpath.v2.mstore;
|
||||
|
||||
import dux.scanpath.v2.bc.ZClass;
|
||||
import dux.scanpath.v2.bc.ZClassContext;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
/**
|
||||
* Visits classes and records class-level annotation associations in a {@link MetaStore}.
|
||||
*
|
||||
* @author indroneel
|
||||
*/
|
||||
|
||||
public class ClassAnnotationVisitor extends ClassVisitor {
|
||||
|
||||
private static final Logger L = Logger.getLogger(ClassAnnotationVisitor.class.getName());
|
||||
|
||||
/**
|
||||
* Creates a visitor backed by the supplied metadata store and class context.
|
||||
*
|
||||
* @param store the store to populate
|
||||
* @param ctxt the context used to resolve class metadata
|
||||
*/
|
||||
|
||||
public ClassAnnotationVisitor(MetaStore store, ZClassContext ctxt) {
|
||||
super(store, ctxt);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
// Methods of base class ClassVisitor
|
||||
|
||||
/**
|
||||
* Visits the named class and its superclasses and interfaces.
|
||||
*
|
||||
* @param fqcn the fully qualified class name to visit
|
||||
*/
|
||||
|
||||
@Override
|
||||
public void visit(String fqcn) {
|
||||
ZClass zcls = clsCtxt.getZClass(fqcn);
|
||||
if(zcls == null) {
|
||||
if(L.isLoggable(Level.WARNING)) {
|
||||
L.warning(String.format("unable to visit annotations - class %s", fqcn));
|
||||
}
|
||||
return;
|
||||
}
|
||||
visitImpl(fqcn, zcls);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
// Helper methods
|
||||
|
||||
private void visitImpl(String startClsName, ZClass cls) {
|
||||
|
||||
List<ZClass> clscol = collateClasses(cls);
|
||||
for(ZClass scls : clscol) {
|
||||
List<ZClass> annotations = scls.getAnnotations();
|
||||
for(ZClass ann : annotations) {
|
||||
metaStore.addClassWithAnnotation(ann.getName(), cls.getName());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private List<ZClass> collateClasses(ZClass cls) {
|
||||
List<ZClass> retCol = new ArrayList<>();
|
||||
retCol.add(cls);
|
||||
|
||||
List<ZClass> ifaces = cls.getInterfaces();
|
||||
for(ZClass iface: ifaces) {
|
||||
List<ZClass> ifcol = collateClasses(iface);
|
||||
retCol.addAll(ifcol);
|
||||
}
|
||||
|
||||
ZClass supcls = cls.getSuperClass();
|
||||
if(supcls != null && !supcls.getName().equals("java.lang.Object")) {
|
||||
List<ZClass> supcol = collateClasses(supcls);
|
||||
retCol.addAll(supcol);
|
||||
}
|
||||
return retCol;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
/*
|
||||
* Copyright (c) DuxTechnica
|
||||
*
|
||||
* Licensed under the DuxTechnica Limited Use Source Code License Agreement (DT-LUSCL); you may not
|
||||
* use this file except in compliance with the License. You may obtain a copy of the License by
|
||||
* contacting:
|
||||
*
|
||||
* Dux Technica, [email protected]
|
||||
*
|
||||
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
|
||||
* either express or implied. See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package dux.scanpath.v2.mstore;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.regex.PatternSyntaxException;
|
||||
|
||||
/**
|
||||
* Selects classes for scanning by package names, exact class names, and regular expressions.
|
||||
*
|
||||
* <p>A class must match at least one inclusion rule and must not match any exclusion rule.
|
||||
*
|
||||
* @author indroneel
|
||||
*/
|
||||
|
||||
public class ClassNameFilter {
|
||||
|
||||
private static final Logger L = Logger.getLogger(ClassNameFilter.class.getName());
|
||||
|
||||
private final List<String> includePkgs;
|
||||
private final List<String> excludePkgs;
|
||||
private final List<Pattern> includeClsPatterns;
|
||||
private final List<Pattern> excludeClsPatterns;
|
||||
private final List<String> includeClsNames;
|
||||
private final List<String> excludeClsNames;
|
||||
|
||||
/**
|
||||
* Creates an empty filter with no inclusion or exclusion rules.
|
||||
*/
|
||||
|
||||
public ClassNameFilter() {
|
||||
includePkgs = new ArrayList<>();
|
||||
excludePkgs = new ArrayList<>();
|
||||
includeClsPatterns = new ArrayList<>();
|
||||
excludeClsPatterns = new ArrayList<>();
|
||||
includeClsNames = new ArrayList<>();
|
||||
excludeClsNames = new ArrayList<>();
|
||||
}
|
||||
|
||||
/**
|
||||
* Includes classes in the named package or one of its subpackages.
|
||||
*
|
||||
* @param name the package name
|
||||
*/
|
||||
|
||||
public void includePackage(String name) {
|
||||
includePkgs.add(name);
|
||||
if(L.isLoggable(Level.FINE)) {
|
||||
L.fine("package_to_scan = %s (included)".formatted(name));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Excludes classes in the named package or one of its subpackages.
|
||||
*
|
||||
* @param name the package name
|
||||
*/
|
||||
|
||||
public void excludePackage(String name) {
|
||||
excludePkgs.add(name);
|
||||
if(L.isLoggable(Level.FINE)) {
|
||||
L.fine("package_to_scan = %s (excluded)".formatted(name));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Includes classes whose fully qualified names match a regular expression.
|
||||
*
|
||||
* @param pattern the regular expression
|
||||
*/
|
||||
|
||||
public void includeClassesByPattern(String pattern) {
|
||||
try {
|
||||
includeClsPatterns.add(Pattern.compile(pattern));
|
||||
if(L.isLoggable(Level.FINE)) {
|
||||
L.fine(String.format("class_to_scan pattern = %s (included)", pattern));
|
||||
}
|
||||
}
|
||||
catch(PatternSyntaxException exep) {
|
||||
if(L.isLoggable(Level.WARNING)) {
|
||||
L.log(Level.WARNING, "include_class_pattern error compiling", exep);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Excludes classes whose fully qualified names match a regular expression.
|
||||
*
|
||||
* @param pattern the regular expression
|
||||
*/
|
||||
|
||||
public void excludeClassesByPattern(String pattern) {
|
||||
try {
|
||||
excludeClsPatterns.add(Pattern.compile(pattern));
|
||||
if(L.isLoggable(Level.FINE)) {
|
||||
L.fine(String.format("class_to_scan pattern = %s (excluded)", pattern));
|
||||
}
|
||||
}
|
||||
catch(PatternSyntaxException exep) {
|
||||
if(L.isLoggable(Level.WARNING)) {
|
||||
L.log(Level.WARNING, "exclude_class_pattern error compiling", exep);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Includes a class by its exact fully qualified name.
|
||||
*
|
||||
* @param name the fully qualified class name
|
||||
*/
|
||||
|
||||
public void includeClass(String name) {
|
||||
includeClsNames.add(name);
|
||||
if(L.isLoggable(Level.FINE)) {
|
||||
L.fine(String.format("class_to_scan = %s (included)", name));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Excludes a class by its exact fully qualified name.
|
||||
*
|
||||
* @param name the fully qualified class name
|
||||
*/
|
||||
|
||||
public void excludeClass(String name) {
|
||||
excludeClsNames.add(name);
|
||||
if(L.isLoggable(Level.FINE)) {
|
||||
L.fine(String.format("class_to_scan = %s (excluded)", name));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines whether a fully qualified class name passes the configured rules.
|
||||
*
|
||||
* @param className the fully qualified class name
|
||||
* @return {@code true} if the name matches an inclusion rule and no exclusion rule; otherwise,
|
||||
* {@code false}
|
||||
*/
|
||||
|
||||
public boolean accepts(String className) {
|
||||
|
||||
boolean exChecks = !excludePkgs.isEmpty() || !excludeClsNames.isEmpty()
|
||||
|| !excludeClsPatterns.isEmpty();
|
||||
boolean inChecks = !includePkgs.isEmpty() || !includeClsNames.isEmpty()
|
||||
|| !includeClsPatterns.isEmpty();
|
||||
|
||||
// if the scope does not define any includes, then reject
|
||||
if(!inChecks) {
|
||||
return false;
|
||||
}
|
||||
|
||||
for(Pattern pattern : excludeClsPatterns) {
|
||||
if(pattern.matcher(className).matches()) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
for(String clsStr : excludeClsNames) {
|
||||
if(className.equals(clsStr)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
for(String pkgStr : excludePkgs) {
|
||||
if(className.startsWith(pkgStr + '.')) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
for (Pattern pattern : includeClsPatterns) {
|
||||
if (pattern.matcher(className).matches()) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
for (String clsStr : includeClsNames) {
|
||||
if (className.equals(clsStr)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
for (String pkgStr : includePkgs) {
|
||||
if (className.startsWith(pkgStr + '.')) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
/*
|
||||
* Copyright (c) DuxTechnica
|
||||
*
|
||||
* Licensed under the DuxTechnica Limited Use Source Code License Agreement (DT-LUSCL); you may not
|
||||
* use this file except in compliance with the License. You may obtain a copy of the License by
|
||||
* contacting:
|
||||
*
|
||||
* Dux Technica, [email protected]
|
||||
*
|
||||
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
|
||||
* either express or implied. See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package dux.scanpath.v2.mstore;
|
||||
|
||||
import dux.scanpath.v2.bc.ZClassContext;
|
||||
|
||||
/**
|
||||
* Base class for visitors that inspect class metadata and populate a {@link MetaStore}.
|
||||
*
|
||||
* @author indroneel
|
||||
*/
|
||||
|
||||
public abstract class ClassVisitor {
|
||||
|
||||
/**
|
||||
* The metadata store populated by this visitor.
|
||||
*/
|
||||
|
||||
protected final MetaStore metaStore;
|
||||
|
||||
/**
|
||||
* The context used to obtain class metadata by fully qualified name.
|
||||
*/
|
||||
|
||||
protected final ZClassContext clsCtxt;
|
||||
|
||||
/**
|
||||
* Creates a visitor with a shared metadata store and class context.
|
||||
*
|
||||
* @param store the store populated by this visitor
|
||||
* @param ctxt the context used to obtain class metadata by fully qualified name
|
||||
*/
|
||||
|
||||
protected ClassVisitor(MetaStore store, ZClassContext ctxt) {
|
||||
metaStore = store;
|
||||
clsCtxt = ctxt;
|
||||
}
|
||||
|
||||
/**
|
||||
* Visits a class identified by its fully qualified name.
|
||||
*
|
||||
* <p>Subclasses define the metadata associations recorded during the visit.
|
||||
*
|
||||
* @param fqcn the fully qualified name of the class to visit
|
||||
*/
|
||||
|
||||
public abstract void visit(String fqcn);
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
/*
|
||||
* Copyright (c) DuxTechnica
|
||||
*
|
||||
* Licensed under the DuxTechnica Limited Use Source Code License Agreement (DT-LUSCL); you may not
|
||||
* use this file except in compliance with the License. You may obtain a copy of the License by
|
||||
* contacting:
|
||||
*
|
||||
* Dux Technica, [email protected]
|
||||
*
|
||||
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
|
||||
* either express or implied. See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package dux.scanpath.v2.mstore;
|
||||
|
||||
import dux.scanpath.v2.bc.ZClass;
|
||||
import dux.scanpath.v2.bc.ZClassContext;
|
||||
import dux.scanpath.v2.bc.ZField;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
/**
|
||||
* Visits classes and records associations for annotations present on instance fields.
|
||||
*
|
||||
* @author indroneel
|
||||
*/
|
||||
|
||||
public class FieldAnnotationVisitor extends ClassVisitor {
|
||||
|
||||
private static final Logger L = Logger.getLogger(FieldAnnotationVisitor.class.getName());
|
||||
|
||||
/**
|
||||
* Creates a visitor backed by the supplied metadata store and class context.
|
||||
*
|
||||
* @param store the store to populate
|
||||
* @param ctxt the context used to resolve class metadata
|
||||
*/
|
||||
|
||||
public FieldAnnotationVisitor(MetaStore store, ZClassContext ctxt) {
|
||||
super(store, ctxt);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
// Methods of base class ClassVisitor
|
||||
|
||||
/**
|
||||
* Visits the named class and its inherited fields.
|
||||
*
|
||||
* @param fqcn the fully qualified class name to visit
|
||||
*/
|
||||
|
||||
@Override
|
||||
public void visit(String fqcn) {
|
||||
ZClass zcls = clsCtxt.getZClass(fqcn);
|
||||
if (zcls == null) {
|
||||
if (L.isLoggable(Level.WARNING)) {
|
||||
L.warning(String.format("unable to visit class %s", fqcn));
|
||||
}
|
||||
return;
|
||||
}
|
||||
visitImpl(zcls);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
// Helper methods
|
||||
|
||||
private void visitImpl(ZClass zcls) {
|
||||
List<ZField> fields = collateFields(zcls);
|
||||
for(ZField field : fields) {
|
||||
if(field.isStatic()) {
|
||||
continue;
|
||||
}
|
||||
List<ZClass> annotations = field.getAnnotations();
|
||||
for (ZClass ann : annotations) {
|
||||
metaStore.addClassWithFieldAnnotation(ann.getName(), zcls.getName());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private List<ZField> collateFields(ZClass zcls) {
|
||||
List<ZField> fields = zcls.getFields();
|
||||
|
||||
ZClass supcls = zcls.getSuperClass();
|
||||
if(supcls != null) {
|
||||
List<ZField> supFields = collateFields(supcls);
|
||||
fields.addAll(supFields);
|
||||
}
|
||||
return fields;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
/*
|
||||
* Copyright (c) DuxTechnica
|
||||
*
|
||||
* Licensed under the DuxTechnica Limited Use Source Code License Agreement (DT-LUSCL); you may not
|
||||
* use this file except in compliance with the License. You may obtain a copy of the License by
|
||||
* contacting:
|
||||
*
|
||||
* Dux Technica, [email protected]
|
||||
*
|
||||
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
|
||||
* either express or implied. See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package dux.scanpath.v2.mstore;
|
||||
|
||||
import dux.scanpath.v2.bc.ZClass;
|
||||
import dux.scanpath.v2.bc.ZClassContext;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
/**
|
||||
* Visits classes and records superclass and interface inheritance relationships.
|
||||
*
|
||||
* @author indroneel
|
||||
*/
|
||||
|
||||
public class HierarchyVisitor extends ClassVisitor {
|
||||
|
||||
private static final Logger L = Logger.getLogger(HierarchyVisitor.class.getName());
|
||||
|
||||
/**
|
||||
* Creates a visitor backed by the supplied metadata store and class context.
|
||||
*
|
||||
* @param store the store to populate
|
||||
* @param ctxt the context used to resolve class metadata
|
||||
*/
|
||||
|
||||
public HierarchyVisitor(MetaStore store, ZClassContext ctxt) {
|
||||
super(store, ctxt);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
// Methods of base class ClassVisitor
|
||||
|
||||
/**
|
||||
* Visits the named class and records its inherited types.
|
||||
*
|
||||
* @param fqcn the fully qualified class name to visit
|
||||
*/
|
||||
|
||||
@Override
|
||||
public void visit(String fqcn) {
|
||||
ZClass zcls = clsCtxt.getZClass(fqcn);
|
||||
if(zcls == null) {
|
||||
if(L.isLoggable(Level.WARNING)) {
|
||||
L.warning(String.format("unable to visit class %s", fqcn));
|
||||
}
|
||||
return;
|
||||
}
|
||||
visitImpl(fqcn, zcls);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
// Helper methods
|
||||
|
||||
private void visitImpl(String startClsName, ZClass zcls) {
|
||||
if(L.isLoggable(Level.FINE)) {
|
||||
L.fine("visiting class " + startClsName);
|
||||
}
|
||||
ZClass supCls = zcls.getSuperClass();
|
||||
if (supCls != null && !supCls.getName().equals("java.lang.Object")) {
|
||||
metaStore.addInheritance(supCls.getName(), startClsName);
|
||||
visitImpl(startClsName, supCls);
|
||||
}
|
||||
|
||||
List<ZClass> ifaces = zcls.getInterfaces();
|
||||
for (ZClass iface : ifaces) {
|
||||
visitInterfaces(startClsName, iface);
|
||||
}
|
||||
}
|
||||
|
||||
private void visitInterfaces(String startClsName, ZClass iface) {
|
||||
metaStore.addInheritance(iface.getName(), startClsName);
|
||||
List<ZClass> ifaces = iface.getInterfaces();
|
||||
for (ZClass niface : ifaces) {
|
||||
visitInterfaces(startClsName, niface);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,340 @@
|
||||
/*
|
||||
* Copyright (c) DuxTechnica
|
||||
*
|
||||
* Licensed under the DuxTechnica Limited Use Source Code License Agreement (DT-LUSCL); you may not
|
||||
* use this file except in compliance with the License. You may obtain a copy of the License by
|
||||
* contacting:
|
||||
*
|
||||
* Dux Technica, [email protected]
|
||||
*
|
||||
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
|
||||
* either express or implied. See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package dux.scanpath.v2.mstore;
|
||||
|
||||
import java.io.PrintWriter;
|
||||
import java.io.StringWriter;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
/**
|
||||
* Stores relationships discovered while scanning class metadata.
|
||||
*
|
||||
* <p>The store tracks inheritance, class annotations, field annotations, and method annotations,
|
||||
* and can resolve the recorded class names through its configured class loader.
|
||||
*
|
||||
* @author indroneel
|
||||
*/
|
||||
|
||||
public class MetaStore {
|
||||
|
||||
private static final Logger _L = Logger.getLogger(MetaStore.class.getName());
|
||||
|
||||
private ClassLoader cload;
|
||||
private final Map<String, Set<String>> inheritList;
|
||||
private final Map<String, Set<String>> annList;
|
||||
private final Map<String, Set<String>> fldAnnList;
|
||||
private final Map<String, Set<String>> mthdAnnList;
|
||||
|
||||
/**
|
||||
* Creates an empty metadata store using the current thread's context class loader when available.
|
||||
*/
|
||||
|
||||
public MetaStore() {
|
||||
cload = Thread.currentThread().getContextClassLoader();
|
||||
if(cload == null) {
|
||||
cload = getClass().getClassLoader();
|
||||
}
|
||||
|
||||
inheritList = new HashMap<>();
|
||||
annList = new HashMap<>();
|
||||
fldAnnList = new HashMap<>();
|
||||
mthdAnnList = new HashMap<>();
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the class loader used when resolving recorded class names.
|
||||
*
|
||||
* <p>If {@code cl} is {@code null}, the thread context loader and then this class's loader are used
|
||||
* as fallbacks.
|
||||
*
|
||||
* @param cl the class loader to use, or {@code null} to select a fallback loader
|
||||
*/
|
||||
|
||||
public void setClassLoader(ClassLoader cl) {
|
||||
cload = cl;
|
||||
if(cload == null) {
|
||||
cload = Thread.currentThread().getContextClassLoader();
|
||||
}
|
||||
if(cload == null) {
|
||||
cload = getClass().getClassLoader();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Records that a class inherits from a base class or interface.
|
||||
*
|
||||
* @param baseName the fully qualified base type name
|
||||
* @param clsName the fully qualified inheriting class name
|
||||
*/
|
||||
|
||||
public void addInheritance(String baseName, String clsName) {
|
||||
if(inheritList.containsKey(baseName)) {
|
||||
inheritList.get(baseName).add(clsName);
|
||||
}
|
||||
else {
|
||||
HashSet<String> set = new HashSet<>();
|
||||
set.add(clsName);
|
||||
inheritList.put(baseName, set);
|
||||
}
|
||||
if(_L.isLoggable(Level.FINE)) {
|
||||
_L.fine("parent = %s, inherited_by = %s".formatted(baseName, clsName));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Records a class that has the specified class-level annotation.
|
||||
*
|
||||
* @param ann the fully qualified annotation type name
|
||||
* @param clsName the fully qualified annotated class name
|
||||
*/
|
||||
|
||||
public void addClassWithAnnotation(String ann, String clsName) {
|
||||
if(annList.containsKey(ann)) {
|
||||
annList.get(ann).add(clsName);
|
||||
}
|
||||
else {
|
||||
HashSet<String> set = new HashSet<>();
|
||||
set.add(clsName);
|
||||
annList.put(ann, set);
|
||||
}
|
||||
if(_L.isLoggable(Level.FINE)) {
|
||||
_L.fine(String.format("annotation = %s, present_in = %s", ann, clsName));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Records a class that has a field with the specified annotation.
|
||||
*
|
||||
* @param ann the fully qualified annotation type name
|
||||
* @param clsName the fully qualified class name
|
||||
*/
|
||||
|
||||
public void addClassWithFieldAnnotation(String ann, String clsName) {
|
||||
if(fldAnnList.containsKey(ann)) {
|
||||
fldAnnList.get(ann).add(clsName);
|
||||
}
|
||||
else {
|
||||
HashSet<String> set = new HashSet<>();
|
||||
set.add(clsName);
|
||||
fldAnnList.put(ann, set);
|
||||
}
|
||||
if(_L.isLoggable(Level.FINE)) {
|
||||
_L.fine(String.format("field_annotation = %s, present_in = %s", ann, clsName));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Records a class that has a method with the specified annotation.
|
||||
*
|
||||
* @param ann the fully qualified annotation type name
|
||||
* @param clsName the fully qualified class name
|
||||
*/
|
||||
|
||||
public void addClassWithMethodAnnotation(String ann, String clsName) {
|
||||
if(mthdAnnList.containsKey(ann)) {
|
||||
mthdAnnList.get(ann).add(clsName);
|
||||
}
|
||||
else {
|
||||
HashSet<String> set = new HashSet<>();
|
||||
set.add(clsName);
|
||||
mthdAnnList.put(ann, set);
|
||||
}
|
||||
if(_L.isLoggable(Level.FINE)) {
|
||||
_L.fine(String.format("method_annotation = %s, present_in = %s", ann, clsName));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves and returns classes recorded as inheriting from the supplied base type.
|
||||
*
|
||||
* @param baseName the fully qualified base type name
|
||||
* @return the resolved inheriting classes
|
||||
*/
|
||||
|
||||
public List<Class<?>> listInheritingClasses(String baseName) {
|
||||
List<Class<?>> result = new ArrayList<>();
|
||||
Set<String> clsNames = inheritList.get(baseName);
|
||||
if(clsNames == null) {
|
||||
return result;
|
||||
}
|
||||
for(String name : clsNames) {
|
||||
try {
|
||||
result.add(cload.loadClass(name));
|
||||
}
|
||||
catch (ClassNotFoundException exep) {
|
||||
if(_L.isLoggable(Level.WARNING)) {
|
||||
_L.log(Level.WARNING, String.format("unable to load class %s", name), exep);
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves and returns classes recorded with the supplied class-level annotation.
|
||||
*
|
||||
* @param ann the fully qualified annotation type name
|
||||
* @return the resolved annotated classes
|
||||
*/
|
||||
|
||||
public List<Class<?>> listAnnotatedClasses(String ann) {
|
||||
List<Class<?>> result = new ArrayList<>();
|
||||
Set<String> clsNames = annList.get(ann);
|
||||
if(clsNames == null) {
|
||||
return result;
|
||||
}
|
||||
for(String name : clsNames) {
|
||||
try {
|
||||
result.add(cload.loadClass(name));
|
||||
}
|
||||
catch (ClassNotFoundException exep) {
|
||||
if(_L.isLoggable(Level.WARNING)) {
|
||||
_L.log(Level.WARNING, String.format("unable to load class %s", name), exep);
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves and returns classes recorded with fields carrying the supplied annotation.
|
||||
*
|
||||
* @param ann the fully qualified annotation type name
|
||||
* @return the resolved classes
|
||||
*/
|
||||
|
||||
public List<Class<?>> listClassesWithAnnotatedFields(String ann) {
|
||||
List<Class<?>> result = new ArrayList<>();
|
||||
Set<String> clsNames = fldAnnList.get(ann);
|
||||
if(clsNames == null) {
|
||||
return result;
|
||||
}
|
||||
for(String name : clsNames) {
|
||||
try {
|
||||
result.add(cload.loadClass(name));
|
||||
}
|
||||
catch (ClassNotFoundException exep) {
|
||||
if(_L.isLoggable(Level.WARNING)) {
|
||||
_L.log(Level.WARNING, String.format("unable to load class %s", name), exep);
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves and returns classes recorded with methods carrying the supplied annotation.
|
||||
*
|
||||
* @param ann the fully qualified annotation type name
|
||||
* @return the resolved classes
|
||||
*/
|
||||
|
||||
public List<Class<?>> listClassesWithAnnotatedMethods(String ann) {
|
||||
List<Class<?>> result = new ArrayList<>();
|
||||
Set<String> clsNames = mthdAnnList.get(ann);
|
||||
if(clsNames == null) {
|
||||
return result;
|
||||
}
|
||||
for(String name : clsNames) {
|
||||
try {
|
||||
result.add(cload.loadClass(name));
|
||||
}
|
||||
catch (ClassNotFoundException exep) {
|
||||
if(_L.isLoggable(Level.WARNING)) {
|
||||
_L.log(Level.WARNING, String.format("unable to load class %s", name), exep);
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Produces a human-readable representation of all recorded relationships.
|
||||
*
|
||||
* @param identStr an identifier included in the dump header and footer
|
||||
* @return the dump split into individual lines
|
||||
*/
|
||||
|
||||
public List<String> dumpState(String identStr) {
|
||||
StringWriter buffer = new StringWriter();
|
||||
PrintWriter out = new PrintWriter(buffer);
|
||||
|
||||
out.println(" ");
|
||||
String hdr = "SCANPATH (%s) DUMP STATE - BEGIN".formatted(identStr);
|
||||
out.println(hdr);
|
||||
String hdrDiv = "-".repeat(hdr.length());
|
||||
out.println(hdrDiv);
|
||||
|
||||
if(!inheritList.isEmpty()) {
|
||||
out.println("=== Inheritance List ===");
|
||||
for (Map.Entry<String, Set<String>> entry : inheritList.entrySet()) {
|
||||
out.println(" " + entry.getKey());
|
||||
Set<String> valSet = entry.getValue();
|
||||
for (String val : valSet) {
|
||||
out.println(" -> " + val);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if(!annList.isEmpty()) {
|
||||
out.println("=== Class Annotations ===");
|
||||
for (Map.Entry<String, Set<String>> entry : annList.entrySet()) {
|
||||
out.println(" " + entry.getKey());
|
||||
Set<String> valSet = entry.getValue();
|
||||
for (String val : valSet) {
|
||||
out.println(" -> " + val);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if(!fldAnnList.isEmpty()) {
|
||||
out.println("=== Field Annotations ===");
|
||||
for (Map.Entry<String, Set<String>> entry : fldAnnList.entrySet()) {
|
||||
out.println(" " + entry.getKey());
|
||||
Set<String> valSet = entry.getValue();
|
||||
for (String val : valSet) {
|
||||
out.println(" -> " + val);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if(!mthdAnnList.isEmpty()) {
|
||||
out.println("=== Method Annotations ===");
|
||||
for (Map.Entry<String, Set<String>> entry : mthdAnnList.entrySet()) {
|
||||
out.println(" " + entry.getKey());
|
||||
Set<String> valSet = entry.getValue();
|
||||
for (String val : valSet) {
|
||||
out.println(" -> " + val);
|
||||
}
|
||||
}
|
||||
}
|
||||
String ftr = "SCANPATH (%s) DUMP STATE - END".formatted(identStr);
|
||||
String ftrDiv = "-".repeat(ftr.length());
|
||||
out.println(ftrDiv);
|
||||
out.println(ftr);
|
||||
out.println(" ");
|
||||
|
||||
out.flush();
|
||||
String[] lines = buffer.toString().split("\n");
|
||||
return List.of(lines);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
/*
|
||||
* Copyright (c) DuxTechnica
|
||||
*
|
||||
* Licensed under the DuxTechnica Limited Use Source Code License Agreement (DT-LUSCL); you may not
|
||||
* use this file except in compliance with the License. You may obtain a copy of the License by
|
||||
* contacting:
|
||||
*
|
||||
* Dux Technica, [email protected]
|
||||
*
|
||||
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
|
||||
* either express or implied. See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package dux.scanpath.v2.mstore;
|
||||
|
||||
import dux.scanpath.v2.bc.ZClassContext;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
/**
|
||||
* Builds a {@link MetaStore} from class files on configured class paths. Only classes accepted by
|
||||
* the supplied name filter are visited.
|
||||
*
|
||||
* @author indroneel
|
||||
*/
|
||||
|
||||
public class MetaStoreBuilder {
|
||||
|
||||
private static final Logger L = Logger.getLogger(MetaStoreBuilder.class.getName());
|
||||
|
||||
/**
|
||||
* Creates a metadata-store builder.
|
||||
*/
|
||||
public MetaStoreBuilder() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Scans the supplied class paths and records metadata for accepted classes.
|
||||
*
|
||||
* @param classPaths class-file directories, ZIP archives, or JAR archives
|
||||
* @param filter the class-name filter, or {@code null} to visit no classes
|
||||
* @return the populated metadata store
|
||||
*/
|
||||
|
||||
public MetaStore build(List<String> classPaths, ClassNameFilter filter) {
|
||||
MetaStore mstor = new MetaStore();
|
||||
ZClassContext clsCtxt = new ZClassContext();
|
||||
for(String path : classPaths) {
|
||||
clsCtxt.appendClassPath(path);
|
||||
if(L.isLoggable(Level.FINE)) {
|
||||
L.fine("append_class_path = %s".formatted(path));
|
||||
}
|
||||
}
|
||||
clsCtxt.prepareIndex();
|
||||
List<ClassVisitor> visitors = List.of(
|
||||
new HierarchyVisitor(mstor, clsCtxt),
|
||||
new ClassAnnotationVisitor(mstor, clsCtxt),
|
||||
new FieldAnnotationVisitor(mstor, clsCtxt),
|
||||
new MethodAnnotationVisitor(mstor, clsCtxt)
|
||||
);
|
||||
|
||||
for(String clsName : clsCtxt.listClassNames()) {
|
||||
if(filter != null && filter.accepts(clsName)) {
|
||||
if(L.isLoggable(Level.FINE)) {
|
||||
L.fine("visiting class %s".formatted(clsName));
|
||||
}
|
||||
for (ClassVisitor cv : visitors) {
|
||||
cv.visit(clsName);
|
||||
}
|
||||
}
|
||||
}
|
||||
//cleaning up
|
||||
clsCtxt.close();
|
||||
|
||||
return mstor;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
/*
|
||||
* Copyright (c) DuxTechnica
|
||||
*
|
||||
* Licensed under the DuxTechnica Limited Use Source Code License Agreement (DT-LUSCL); you may not
|
||||
* use this file except in compliance with the License. You may obtain a copy of the License by
|
||||
* contacting:
|
||||
*
|
||||
* Dux Technica, [email protected]
|
||||
*
|
||||
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
|
||||
* either express or implied. See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package dux.scanpath.v2.mstore;
|
||||
|
||||
import dux.scanpath.v2.bc.ZClass;
|
||||
import dux.scanpath.v2.bc.ZClassContext;
|
||||
import dux.scanpath.v2.bc.ZMethod;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
/**
|
||||
* Visits classes and records associations for annotations present on eligible instance methods.
|
||||
*
|
||||
* @author indroneel
|
||||
*/
|
||||
|
||||
public class MethodAnnotationVisitor extends ClassVisitor {
|
||||
|
||||
private static final Logger L = Logger.getLogger(MethodAnnotationVisitor.class.getName());
|
||||
|
||||
/**
|
||||
* Creates a visitor backed by the supplied metadata store and class context.
|
||||
*
|
||||
* @param store the store to populate
|
||||
* @param ctxt the context used to resolve class metadata
|
||||
*/
|
||||
|
||||
public MethodAnnotationVisitor(MetaStore store, ZClassContext ctxt) {
|
||||
super(store, ctxt);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
// Methods of base class ClassVisitor
|
||||
|
||||
/**
|
||||
* Visits the named class and its inherited methods.
|
||||
*
|
||||
* @param fqcn the fully qualified class name to visit
|
||||
*/
|
||||
|
||||
@Override
|
||||
public void visit(String fqcn) {
|
||||
ZClass zcls = clsCtxt.getZClass(fqcn);
|
||||
if (zcls == null) {
|
||||
if (L.isLoggable(Level.WARNING)) {
|
||||
L.warning(String.format("unable to visit class %s", fqcn));
|
||||
}
|
||||
return;
|
||||
}
|
||||
visitImpl(zcls);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
// Helper methods
|
||||
|
||||
private void visitImpl(ZClass zcls) {
|
||||
List<ZMethod> methods = collateMethods(zcls);
|
||||
for(ZMethod mthd : methods) {
|
||||
if(mthd.isStatic() || mthd.isAbstract() || mthd.isNative()) {
|
||||
continue;
|
||||
}
|
||||
List<ZClass> annotations = mthd.getAnnotations();
|
||||
for (ZClass ann : annotations) {
|
||||
metaStore.addClassWithMethodAnnotation(ann.getName(), zcls.getName());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private List<ZMethod> collateMethods(ZClass zcls) {
|
||||
List<ZMethod> methods = zcls.getMethods();
|
||||
|
||||
ZClass supcls = zcls.getSuperClass();
|
||||
if(supcls != null) {
|
||||
List<ZMethod> supMthds = collateMethods(supcls);
|
||||
methods.addAll(supMthds);
|
||||
}
|
||||
return methods;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user