Search in sources :

Example 6 with ResourceAnalyzer

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;
}
Also used : ResourceAnalyzer(org.osgi.service.indexer.ResourceAnalyzer) Capability(org.osgi.service.indexer.Capability) Formatter(java.util.Formatter) URL(java.net.URL) InvalidSyntaxException(org.osgi.framework.InvalidSyntaxException) Requirement(org.osgi.service.indexer.Requirement) AddOnlyList(org.osgi.service.indexer.impl.util.AddOnlyList) StringWriter(java.io.StringWriter) Filter(org.osgi.framework.Filter) FrameworkUtil.createFilter(org.osgi.framework.FrameworkUtil.createFilter) Tag(org.osgi.service.indexer.impl.util.Tag) File(java.io.File) PrintWriter(java.io.PrintWriter)

Example 7 with ResourceAnalyzer

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();
}
Also used : WibbleAnalyzer(org.example.tests.utils.WibbleAnalyzer) ResourceAnalyzer(org.osgi.service.indexer.ResourceAnalyzer) LinkedHashSet(java.util.LinkedHashSet) HashMap(java.util.HashMap) Hashtable(java.util.Hashtable) Matchers.anyString(org.mockito.Matchers.anyString) ResourceIndexer(org.osgi.service.indexer.ResourceIndexer) StringWriter(java.io.StringWriter) Utils.copyToTempFile(org.example.tests.utils.Utils.copyToTempFile) File(java.io.File)

Example 8 with ResourceAnalyzer

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());
}
Also used : ResourceAnalyzer(org.osgi.service.indexer.ResourceAnalyzer) Capability(org.osgi.service.indexer.Capability) HashMap(java.util.HashMap) Resource(org.osgi.service.indexer.Resource) Matchers.anyString(org.mockito.Matchers.anyString) IOException(java.io.IOException) Requirement(org.osgi.service.indexer.Requirement) StringWriter(java.io.StringWriter) List(java.util.List) File(java.io.File) LogService(org.osgi.service.log.LogService)

Example 9 with ResourceAnalyzer

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);
    }
}
Also used : ResourceAnalyzer(org.osgi.service.indexer.ResourceAnalyzer) IFile(org.eclipse.core.resources.IFile) HashMap(java.util.HashMap) Builder(org.osgi.service.indexer.Builder) OutputStream(java.io.OutputStream) URI(java.net.URI) WorkspaceR5Repository(bndtools.central.WorkspaceR5Repository) HashSet(java.util.HashSet) IPath(org.eclipse.core.runtime.IPath) Capability(org.osgi.service.indexer.Capability) InputStream(java.io.InputStream) Resource(org.osgi.service.indexer.Resource) IResource(org.eclipse.core.resources.IResource) IProject(org.eclipse.core.resources.IProject) Project(aQute.bnd.build.Project) Requirement(org.osgi.service.indexer.Requirement) IWorkspaceRoot(org.eclipse.core.resources.IWorkspaceRoot) IFile(org.eclipse.core.resources.IFile) File(java.io.File) RepoIndex(org.osgi.service.indexer.impl.RepoIndex)

Aggregations

ResourceAnalyzer (org.osgi.service.indexer.ResourceAnalyzer)9 File (java.io.File)6 HashMap (java.util.HashMap)6 StringWriter (java.io.StringWriter)5 Matchers.anyString (org.mockito.Matchers.anyString)4 Filter (org.osgi.framework.Filter)3 Capability (org.osgi.service.indexer.Capability)3 Requirement (org.osgi.service.indexer.Requirement)3 Resource (org.osgi.service.indexer.Resource)3 ResourceIndexer (org.osgi.service.indexer.ResourceIndexer)3 List (java.util.List)2 Utils.copyToTempFile (org.example.tests.utils.Utils.copyToTempFile)2 WibbleAnalyzer (org.example.tests.utils.WibbleAnalyzer)2 FrameworkUtil.createFilter (org.osgi.framework.FrameworkUtil.createFilter)2 InvalidSyntaxException (org.osgi.framework.InvalidSyntaxException)2 RepoIndex (org.osgi.service.indexer.impl.RepoIndex)2 LogService (org.osgi.service.log.LogService)2 Project (aQute.bnd.build.Project)1 WorkspaceR5Repository (bndtools.central.WorkspaceR5Repository)1 IOException (java.io.IOException)1