use of org.osgi.service.indexer.ResourceAnalyzer in project bnd by bndtools.
the class RepoIndex method generateResource.
private Tag generateResource(File file, Map<String, String> config) throws Exception {
JarResource resource = new JarResource(file);
List<Capability> caps = new AddOnlyList<Capability>(new LinkedList<Capability>());
List<Requirement> reqs = new AddOnlyList<Requirement>(new LinkedList<Requirement>());
Tag resourceTag = new Tag(Schema.ELEM_RESOURCE);
try {
// Read config settings and save in thread local state
if (config != null) {
URL rootURL;
String rootURLStr = config.get(ResourceIndexer.ROOT_URL);
if (rootURLStr != null) {
File rootDir = new File(rootURLStr);
if (rootDir.isDirectory())
rootURL = rootDir.toURI().toURL();
else
rootURL = new URL(rootURLStr);
} else
rootURL = new File(System.getProperty("user.dir")).toURI().toURL();
String urlTemplate = config.get(ResourceIndexer.URL_TEMPLATE);
bundleAnalyzer.setStateLocal(new GeneratorState(rootURL.toURI().normalize(), urlTemplate, resolvers));
} else {
bundleAnalyzer.setStateLocal(null);
}
// Iterate over the analyzers
try {
synchronized (analyzers) {
for (Pair<ResourceAnalyzer, Filter> entry : analyzers) {
ResourceAnalyzer analyzer = entry.getFirst();
Filter filter = entry.getSecond();
if (filter == null || filter.match(resource.getProperties())) {
try {
analyzer.analyzeResource(resource, caps, reqs);
} catch (Exception e) {
log(LogService.LOG_ERROR, MessageFormat.format("Error calling analyzer \"{0}\" on resource {1}.", analyzer.getClass().getName(), resource.getLocation()), e);
StringWriter writer = new StringWriter();
Formatter comment = new Formatter(writer);
comment.format("Error calling analyzer \"%s\" on resource %s with message %s and stack: ", analyzer.getClass().getName(), resource.getLocation(), e);
comment.close();
e.printStackTrace(new PrintWriter(writer));
resourceTag.addComment(writer.toString());
}
}
}
}
} finally {
bundleAnalyzer.setStateLocal(null);
}
} finally {
resource.close();
}
for (Capability cap : caps) {
Tag capTag = new Tag(Schema.ELEM_CAPABILITY);
capTag.addAttribute(Schema.ATTR_NAMESPACE, cap.getNamespace());
appendAttributeAndDirectiveTags(capTag, cap.getAttributes(), cap.getDirectives());
resourceTag.addContent(capTag);
}
for (Requirement req : reqs) {
Tag reqTag = new Tag(Schema.ELEM_REQUIREMENT);
reqTag.addAttribute(Schema.ATTR_NAMESPACE, req.getNamespace());
appendAttributeAndDirectiveTags(reqTag, req.getAttributes(), req.getDirectives());
resourceTag.addContent(reqTag);
}
return resourceTag;
}
use of org.osgi.service.indexer.ResourceAnalyzer in project bnd by bndtools.
the class TestOSGiServices method testWhiteboardAnalyzerWithFilter.
// Test whiteboard registration of Resource Analyzers, with resource filter
// property.
public void testWhiteboardAnalyzerWithFilter() throws Exception {
Dictionary<String, Object> analyzerProps = new Hashtable<String, Object>();
analyzerProps.put(ResourceAnalyzer.FILTER, "(location=*sion.jar)");
ServiceRegistration<ResourceAnalyzer> reg = context.registerService(ResourceAnalyzer.class, new WibbleAnalyzer(), analyzerProps);
ServiceReference<ResourceIndexer> ref = context.getServiceReference(ResourceIndexer.class);
ResourceIndexer indexer = context.getService(ref);
StringWriter writer = new StringWriter();
Set<File> files = new LinkedHashSet<File>();
files.add(copyToTempFile(tempDir, "testdata/01-bsn+version.jar"));
files.add(copyToTempFile(tempDir, "testdata/02-localization.jar"));
Map<String, String> config = new HashMap<String, String>();
config.put(ResourceIndexer.ROOT_URL, tempDir.getAbsoluteFile().toURI().toString());
indexer.indexFragment(files, writer, config);
assertEquals(readStream(TestOSGiServices.class.getResourceAsStream("/testdata/fragment-wibble-filtered.txt")), writer.toString().trim());
context.ungetService(ref);
reg.unregister();
}
use of org.osgi.service.indexer.ResourceAnalyzer in project bnd by bndtools.
the class TestIndexer method testLogErrorsFromAnalyzer.
public void testLogErrorsFromAnalyzer() throws Exception {
ResourceAnalyzer badAnalyzer = new ResourceAnalyzer() {
public void analyzeResource(Resource resource, List<Capability> capabilities, List<Requirement> requirements) throws Exception {
throw new Exception("Bang!");
}
};
ResourceAnalyzer goodAnalyzer = mock(ResourceAnalyzer.class);
LogService log = mock(LogService.class);
RepoIndex indexer = new RepoIndex(log);
indexer.addAnalyzer(badAnalyzer, null);
indexer.addAnalyzer(goodAnalyzer, null);
// Run the indexer
Map<String, String> props = new HashMap<String, String>();
props.put(ResourceIndexer.ROOT_URL, new File("testdata").getAbsoluteFile().toURI().toURL().toString());
StringWriter writer = new StringWriter();
indexer.indexFragment(Collections.singleton(new File("testdata/subdir/01-bsn+version.jar")), writer, props);
// The "good" analyzer should have been called
verify(goodAnalyzer).analyzeResource(any(Resource.class), anyListOf(Capability.class), anyListOf(Requirement.class));
// The log service should have been notified about the exception
ArgumentCaptor<Exception> exceptionCaptor = ArgumentCaptor.forClass(Exception.class);
verify(log).log(eq(LogService.LOG_ERROR), any(String.class), exceptionCaptor.capture());
assertEquals("Bang!", exceptionCaptor.getValue().getMessage());
}
use of org.osgi.service.indexer.ResourceAnalyzer in project bndtools by bndtools.
the class BuiltBundleIndexer method builtBundles.
@Override
public void builtBundles(final IProject project, IPath[] paths) {
IWorkspaceRoot wsroot = ResourcesPlugin.getWorkspace().getRoot();
final URI workspaceRootUri = wsroot.getLocationURI();
Set<File> files = new HashSet<File>();
for (IPath path : paths) {
try {
IFile ifile = wsroot.getFile(path);
IPath location = ifile.getLocation();
if (location != null)
files.add(location.toFile());
} catch (IllegalArgumentException e) {
System.err.println("### Error processing path: " + path);
e.printStackTrace();
}
}
// Generate the index file
File indexFile;
try {
Project model = Central.getProject(project);
File target = model.getTarget();
indexFile = new File(target, INDEX_FILENAME);
IFile indexPath = wsroot.getFile(Central.toPath(indexFile));
// Create the indexer and add ResourceAnalyzers from plugins
RepoIndex indexer = new RepoIndex(logAdapter);
List<ResourceAnalyzer> analyzers = Central.getWorkspace().getPlugins(ResourceAnalyzer.class);
for (ResourceAnalyzer analyzer : analyzers) {
indexer.addAnalyzer(analyzer, null);
}
// Use an analyzer to add a marker capability to workspace resources
indexer.addAnalyzer(new ResourceAnalyzer() {
@Override
public void analyzeResource(Resource resource, List<Capability> capabilities, List<Requirement> requirements) throws Exception {
Capability cap = new Builder().setNamespace("bndtools.workspace").addAttribute("bndtools.workspace", workspaceRootUri.toString()).addAttribute("project.path", project.getFullPath().toString()).buildCapability();
capabilities.add(cap);
}
}, null);
Map<String, String> config = new HashMap<String, String>();
config.put(ResourceIndexer.REPOSITORY_NAME, project.getName());
config.put(ResourceIndexer.ROOT_URL, project.getLocation().toFile().toURI().toString());
config.put(ResourceIndexer.PRETTY, "true");
try (OutputStream output = IO.outputStream(indexFile)) {
indexer.index(files, output, config);
}
indexPath.refreshLocal(IResource.DEPTH_ZERO, null);
if (indexPath.exists())
indexPath.setDerived(true, null);
} catch (Exception e) {
logger.logError(MessageFormat.format("Failed to generate index file for bundles in project {0}.", project.getName()), e);
return;
}
// Parse the index and add to the workspace repository
try (InputStream input = IO.stream(indexFile)) {
WorkspaceR5Repository workspaceRepo = Central.getWorkspaceR5Repository();
workspaceRepo.loadProjectIndex(project, input, project.getLocation().toFile().toURI());
} catch (Exception e) {
logger.logError("Failed to update workspace index.", e);
}
}
Aggregations