You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@sling.apache.org by kw...@apache.org on 2023/12/05 20:08:49 UTC
(sling-org-apache-sling-providertype-bnd-plugin) 01/01: SLING-12181 Evaluate provider type from annotations
This is an automated email from the ASF dual-hosted git repository.
kwin pushed a commit to branch feature/collect-provider-info-from-annotation-directly
in repository https://gitbox.apache.org/repos/asf/sling-org-apache-sling-providertype-bnd-plugin.git
commit 1c88a65812e1be2cbd43ddb2cde24842283bc0ae
Author: Konrad Windszus <kw...@apache.org>
AuthorDate: Tue Dec 5 21:08:41 2023 +0100
SLING-12181 Evaluate provider type from annotations
Only in case META-INF/api-info.json is not available in the class path
(no apis-jar)
---
pom.xml | 34 +++++++-
.../bndplugin/ProviderTypeScanner.java | 99 ++++++++++++++++------
.../providertype/bndplugin/MyBinaryDownload.java | 44 ++++++++++
.../bndplugin/ProviderTypeScannerTest.java | 12 +--
4 files changed, 157 insertions(+), 32 deletions(-)
diff --git a/pom.xml b/pom.xml
index 0ae2e95..0a717a6 100644
--- a/pom.xml
+++ b/pom.xml
@@ -44,7 +44,33 @@
<url>https://github.com/apache/sling-org-apache-sling-providertype-bnd-plugin/tree/${project.scm.tag}</url>
<tag>HEAD</tag>
</scm>
-
+
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-dependency-plugin</artifactId>
+ <executions>
+ <execution>
+ <id>copy-dependencies</id>
+ <phase>generate-test-resources</phase>
+ <goals>
+ <goal>copy-dependencies</goal>
+ </goals>
+ <configuration>
+ <outputDirectory>${project.build.directory}/test-classpath</outputDirectory>
+ <overWriteReleases>false</overWriteReleases>
+ <overWriteSnapshots>false</overWriteSnapshots>
+ <overWriteIfNewer>true</overWriteIfNewer>
+ <includeArtifactIds>oak-jackrabbit-api</includeArtifactIds>
+ <stripVersion>true</stripVersion>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+ </plugins>
+ </build>
+
<dependencyManagement>
<dependencies>
<dependency>
@@ -87,5 +113,11 @@
<artifactId>slf4j-simple</artifactId>
<scope>test</scope>
</dependency>
+ <dependency>
+ <groupId>org.apache.jackrabbit</groupId>
+ <artifactId>oak-jackrabbit-api</artifactId>
+ <version>1.58.0</version>
+ <scope>test</scope>
+ </dependency>
</dependencies>
</project>
\ No newline at end of file
diff --git a/src/main/java/org/apache/sling/providertype/bndplugin/ProviderTypeScanner.java b/src/main/java/org/apache/sling/providertype/bndplugin/ProviderTypeScanner.java
index d4c3b0a..2d3c73d 100644
--- a/src/main/java/org/apache/sling/providertype/bndplugin/ProviderTypeScanner.java
+++ b/src/main/java/org/apache/sling/providertype/bndplugin/ProviderTypeScanner.java
@@ -29,9 +29,12 @@ import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
+import aQute.bnd.build.Classpath.ClassVisitor;
import aQute.bnd.osgi.Analyzer;
import aQute.bnd.osgi.Clazz;
+import aQute.bnd.osgi.Descriptors;
import aQute.bnd.osgi.Descriptors.TypeRef;
+import aQute.bnd.osgi.Jar;
import aQute.bnd.osgi.Resource;
import aQute.bnd.service.AnalyzerPlugin;
import aQute.bnd.service.Plugin;
@@ -39,19 +42,18 @@ import aQute.lib.json.Decoder;
import aQute.lib.json.JSONCodec;
import aQute.service.reporter.Reporter;
-/**
- * Enforces that no classes implement or extend a type marked as provider.
- * Provider types are retrieved from the resource "META-INF/api-info.json" which is expected to be provided
- * in the class path.
- */
+/** Enforces that no classes implement or extend a type marked as provider. Provider types are retrieved from the resource
+ * "META-INF/api-info.json" which is expected to be provided in the class path. */
public class ProviderTypeScanner implements AnalyzerPlugin, Plugin {
private static final String API_INFO_JSON_RESOURCE_PATH = "META-INF/api-info.json";
private static final String FIELD_PROVIDER_TYPES = "providerTypes";
private static final String MESSAGE = "Type \"%s\" %s provider type \"%s\". This is not allowed!";
private static final String ATTRIBUTE_IGNORED_PROVIDER_TYPES = "ignored";
+
+ private static final String PROVIDER_TYPE_ANNOTATION_BINARY_NAME = Descriptors.fqnToBinary("org.osgi.annotation.versioning.ProviderType");
- private Map<String,String> parameters = new HashMap<>();
+ private Map<String, String> parameters = new HashMap<>();
@Override
public void setProperties(Map<String, String> map) throws Exception {
@@ -67,36 +69,42 @@ public class ProviderTypeScanner implements AnalyzerPlugin, Plugin {
@Override
public boolean analyzeJar(Analyzer analyzer) throws Exception {
- List<Resource> apiInfoJsonResources = analyzer.findResources(s -> s.equals(API_INFO_JSON_RESOURCE_PATH)).collect(Collectors.toList());
- if(apiInfoJsonResources.isEmpty()) {
- analyzer.warning("Could not find resource \"%s\" in the classpath", API_INFO_JSON_RESOURCE_PATH);
+ List<Resource> apiInfoJsonResources = analyzer.findResources(s -> s.equals(API_INFO_JSON_RESOURCE_PATH))
+ .collect(Collectors.toList());
+ final Set<String> providerTypes = new HashSet<>();
+ if (apiInfoJsonResources.isEmpty()) {
+ analyzer.warning("Could not find resource \"%s\" in the classpath, retrieving info from annotations found in classpath", API_INFO_JSON_RESOURCE_PATH);
+ providerTypes.addAll(collectProviderTypesFromClasspath(analyzer));
} else {
- Set<String> providerTypes = new HashSet<>();
for (Resource apiInfoJsonResource : apiInfoJsonResources) {
try {
- Set<String> resourceProviderTypes = collectProviderTypes(analyzer, apiInfoJsonResource);
- analyzer.trace("Added provider types from resource \"%s\": %s", apiInfoJsonResource, String.join(",", resourceProviderTypes));
+ Set<String> resourceProviderTypes = collectProviderTypesFromApiInfo(analyzer, apiInfoJsonResource);
+ analyzer.trace("Added provider types from resource \"%s\": %s", apiInfoJsonResource,
+ String.join(",", resourceProviderTypes));
providerTypes.addAll(resourceProviderTypes);
} catch (Exception e) {
throw new IllegalStateException("Could not parse JSON from resource " + apiInfoJsonResource, e);
}
}
- // remove ignored provider types
- Arrays.stream(parameters.getOrDefault(ATTRIBUTE_IGNORED_PROVIDER_TYPES, "").split(",")).filter(s -> !s.isBlank()).forEach(ignored -> {
- if (providerTypes.remove(ignored)) {
- analyzer.trace("Ignore extensions of provider type \"%s\" due to plugin configuration", ignored);
- } else {
- analyzer.warning("Ignored class \"%s\" is not defined as provider type at all, you can safely remove the according plugin parameter", ignored);
- }
- });
- checkIfExtendingType(analyzer, analyzer.getClassspace().values(), providerTypes);
}
+ // remove ignored provider types
+ Arrays.stream(parameters.getOrDefault(ATTRIBUTE_IGNORED_PROVIDER_TYPES, "").split(",")).filter(s -> !s.isBlank())
+ .forEach(ignored -> {
+ if (providerTypes.remove(ignored)) {
+ analyzer.trace("Ignore extensions of provider type \"%s\" due to plugin configuration", ignored);
+ } else {
+ analyzer.warning(
+ "Ignored class \"%s\" is not defined as provider type at all, you can safely remove the according plugin parameter",
+ ignored);
+ }
+ });
+ checkIfExtendingType(analyzer, analyzer.getClassspace().values(), providerTypes);
return false;
}
private void checkIfExtendingType(Reporter reporter, Collection<Clazz> clazzes, Set<String> providerTypes) {
for (Clazz clazz : clazzes) {
- if (clazz.getSuper() != null && (providerTypes.contains(clazz.getSuper().getFQN()))) {
+ if (clazz.getSuper() != null && (providerTypes.contains(clazz.getSuper().getFQN()))) {
reporter.error(MESSAGE, clazz.getFQN(), "extends", clazz.getSuper().getFQN()).file(clazz.getSourceFile());
}
for (TypeRef interfaceType : clazz.interfaces()) {
@@ -108,23 +116,62 @@ public class ProviderTypeScanner implements AnalyzerPlugin, Plugin {
}
@SuppressWarnings("unchecked")
- private Set<String> collectProviderTypes(Reporter reporter, Resource apiInfoResource) throws Exception {
+ private Set<String> collectProviderTypesFromApiInfo(Reporter reporter, Resource apiInfoResource) throws Exception {
JSONCodec codec = new JSONCodec();
// read JSON file
try (InputStream input = apiInfoResource.openInputStream();
- Decoder decoder = codec.dec().from(input)) {
+ Decoder decoder = codec.dec().from(input)) {
Map<?, ?> jsonMap = decoder.get(Map.class);
Object providerTypes = jsonMap.get(FIELD_PROVIDER_TYPES);
if (providerTypes == null) {
reporter.error("Resource \"%s\" does not contain a field named \"%s\"", API_INFO_JSON_RESOURCE_PATH, FIELD_PROVIDER_TYPES);
} else if (!(providerTypes instanceof Collection)) {
- reporter.error("Field \"%s\" in JSON resource \"%s\" is not containing a string array but a type converted to %s", FIELD_PROVIDER_TYPES, API_INFO_JSON_RESOURCE_PATH, providerTypes.getClass().getName());
+ reporter.error("Field \"%s\" in JSON resource \"%s\" is not containing a string array but a type converted to %s",
+ FIELD_PROVIDER_TYPES, API_INFO_JSON_RESOURCE_PATH, providerTypes.getClass().getName());
} else {
- return new HashSet<>((Collection<String>)providerTypes);
+ return new HashSet<>((Collection<String>) providerTypes);
}
}
return Collections.emptySet();
}
+ private Set<String> collectProviderTypesFromClasspath(Analyzer analyzer) throws Exception {
+ // unfortunately bnd does not cache this information in an accessible way
+ ProviderTypeCollectorClassVisitor visitor = new ProviderTypeCollectorClassVisitor();
+ visit(visitor, analyzer);
+ return visitor.getProviderTypes();
+ }
+
+ /** Visit each class on the class path (includes package-info.class).
+ *
+ * @param visitor the visitor */
+ private void visit(ClassVisitor visitor, Analyzer analyzer) throws Exception {
+ for (Jar classpathJar : analyzer.getClasspath()) {
+ for (String path : classpathJar.getResources().keySet()) {
+ if (path.endsWith(".class")) {
+ Resource r = classpathJar.getResource(path);
+ Clazz c = new Clazz(analyzer, path, r);
+ c.parseClassFile();
+ visitor.visit(c);
+ }
+ }
+ }
+ }
+ private static final class ProviderTypeCollectorClassVisitor implements ClassVisitor {
+
+ final Set<String> providerTypes = new HashSet<>();
+
+ @Override
+ public boolean visit(Clazz clazz) throws Exception {
+ if (clazz.annotations(PROVIDER_TYPE_ANNOTATION_BINARY_NAME).findAny().isPresent()) {
+ providerTypes.add(clazz.getFQN());
+ }
+ return true;
+ }
+
+ public Set<String> getProviderTypes() {
+ return providerTypes;
+ }
+ }
}
\ No newline at end of file
diff --git a/src/test/java/org/apache/sling/providertype/bndplugin/MyBinaryDownload.java b/src/test/java/org/apache/sling/providertype/bndplugin/MyBinaryDownload.java
new file mode 100644
index 0000000..024f274
--- /dev/null
+++ b/src/test/java/org/apache/sling/providertype/bndplugin/MyBinaryDownload.java
@@ -0,0 +1,44 @@
+package org.apache.sling.providertype.bndplugin;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URI;
+
+import javax.jcr.RepositoryException;
+
+import org.apache.jackrabbit.api.binary.BinaryDownload;
+import org.apache.jackrabbit.api.binary.BinaryDownloadOptions;
+
+public class MyBinaryDownload implements BinaryDownload {
+
+ @Override
+ public InputStream getStream() throws RepositoryException {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public int read(byte[] b, long position) throws IOException, RepositoryException {
+ // TODO Auto-generated method stub
+ return 0;
+ }
+
+ @Override
+ public long getSize() throws RepositoryException {
+ // TODO Auto-generated method stub
+ return 0;
+ }
+
+ @Override
+ public void dispose() {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public URI getURI(BinaryDownloadOptions downloadOptions) throws RepositoryException {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+}
diff --git a/src/test/java/org/apache/sling/providertype/bndplugin/ProviderTypeScannerTest.java b/src/test/java/org/apache/sling/providertype/bndplugin/ProviderTypeScannerTest.java
index bf26f0f..88cfdab 100644
--- a/src/test/java/org/apache/sling/providertype/bndplugin/ProviderTypeScannerTest.java
+++ b/src/test/java/org/apache/sling/providertype/bndplugin/ProviderTypeScannerTest.java
@@ -38,7 +38,7 @@ class ProviderTypeScannerTest {
static BndBuilderExtension bndBuilderExtension = new BndBuilderExtension(new ProviderTypeScanner());
@Test
- void testBuildWithViolations() throws Exception {
+ void testBuildWithViolationsAndApiInfoJson() throws Exception {
Builder builder = bndBuilderExtension.builder;
// add classpath entry with api-info.json
builder.setClasspath(new File[] { new File("src/test/resources") });
@@ -56,12 +56,14 @@ class ProviderTypeScannerTest {
@Test
void testBuildWithoutProviderTypeMetadata() throws Exception {
Builder builder = bndBuilderExtension.builder;
+ // add classpath entry with api-info.json
+ builder.setClasspath(new File[] { new File("target/test-classpath/oak-jackrabbit-api.jar") });
try (Jar jar = builder.build()) {
- if (!builder.getErrors().isEmpty()) {
- fail(String.join("\n", builder.getErrors()));
- }
+ List<String> expectedErrors = Arrays.asList(
+ "Type \"org.apache.sling.providertype.bndplugin.MyBinaryDownload\" implements provider type \"org.apache.jackrabbit.api.binary.BinaryDownload\". This is not allowed!");
+ assertEquals(expectedErrors, builder.getErrors());
List<String> expectedWarnings = Arrays.asList(
- "Could not find resource \"META-INF/api-info.json\" in the classpath");
+ "Could not find resource \"META-INF/api-info.json\" in the classpath, retrieving info from annotations found in classpath");
assertEquals(expectedWarnings, builder.getWarnings());
}
}