Search in sources :

Example 46 with Wire

use of org.osgi.resource.Wire in project rt.equinox.framework by eclipse.

the class ResolveContext method getSubstitutionWires.

/**
 * Returns the subset of {@link Wiring#getRequiredResourceWires(String)
 * required} wires that provide wires to {@link Capability capabilities}
 * which substitute capabilities of the wiring. For example, when a
 * {@link PackageNamespace package} name is both provided and required by
 * the same resource. If the package requirement is resolved to a capability
 * provided by a different wiring then the package capability is considered
 * to be substituted.
 * <p>
 * The resolver asks the resolve context to return substitution wires for
 * each wiring that {@link Wiring#getResourceCapabilities(String) provides}
 * a {@link BundleNamespace bundle} namespace capability that is used to
 * resolve one or more bundle requirements.
 * <p>
 * Note that this method searches all the {@link PackageNamespace package}
 * capabilities declared as {@link Resource#getCapabilities(String)
 * provided} by the resource associated with the wiring and fragment
 * resources wired to the wiring with the {@link HostNamespace host}
 * namespace. The provided package names are compared against the
 * {@link Wiring#getRequiredResourceWires(String) required} package wires to
 * determine which wires are substitution wires. Subclasses of
 * <code>ResolveContext</code> should provide a more efficient
 * implementation of this method.
 *
 * @param wiring the wiring to get the substitution wires for. Must not be
 *            {@code null}.
 * @return A list containing a snapshot of the substitution {@link Wire}s
 *         for the {@link Requirement requirements} of the wiring, or an
 *         empty list if the wiring has no substitution wires. The list
 *         contains the wires in the order they are found in the
 *         {@link Wiring#getRequiredResourceWires(String) required} wires of
 *         the wiring.
 * @since 1.1
 */
public List<Wire> getSubstitutionWires(Wiring wiring) {
    // Keep track of the declared capability package names
    Set<String> exportNames = new HashSet<String>();
    // Add packages declared as provided by the wiring host
    for (Capability cap : wiring.getResource().getCapabilities(null)) {
        if (PackageNamespace.PACKAGE_NAMESPACE.equals(cap.getNamespace())) {
            exportNames.add((String) cap.getAttributes().get(PackageNamespace.PACKAGE_NAMESPACE));
        }
    }
    // Add packages declared as provided by the attached fragments
    for (Wire wire : wiring.getProvidedResourceWires(null)) {
        if (HostNamespace.HOST_NAMESPACE.equals(wire.getCapability().getNamespace())) {
            Resource fragment = wire.getRequirement().getResource();
            for (Capability cap : fragment.getCapabilities(null)) {
                if (PackageNamespace.PACKAGE_NAMESPACE.equals(cap.getNamespace())) {
                    exportNames.add((String) cap.getAttributes().get(PackageNamespace.PACKAGE_NAMESPACE));
                }
            }
        }
    }
    // collect the package wires that substitute one of the declared
    // export package names
    List<Wire> substitutionWires = new ArrayList<Wire>();
    for (Wire wire : wiring.getRequiredResourceWires(null)) {
        if (PackageNamespace.PACKAGE_NAMESPACE.equals(wire.getCapability().getNamespace())) {
            if (exportNames.contains(wire.getCapability().getAttributes().get(PackageNamespace.PACKAGE_NAMESPACE))) {
                substitutionWires.add(wire);
            }
        }
    }
    return substitutionWires;
}
Also used : Capability(org.osgi.resource.Capability) Resource(org.osgi.resource.Resource) ArrayList(java.util.ArrayList) Wire(org.osgi.resource.Wire) HashSet(java.util.HashSet)

Example 47 with Wire

use of org.osgi.resource.Wire in project intellij-plugins by JetBrains.

the class ResolveAction method actionPerformed.

@Override
public void actionPerformed(@NotNull AnActionEvent event) {
    VirtualFile virtualFile = event.getData(CommonDataKeys.VIRTUAL_FILE);
    Project project = event.getProject();
    if (virtualFile == null || project == null)
        return;
    Document document = FileDocumentManager.getInstance().getDocument(virtualFile);
    if (document == null)
        return;
    FileDocumentManager.getInstance().saveAllDocuments();
    new Task.Backgroundable(project, message("bnd.resolve.requirements.title"), true) {

        private Map<Resource, List<Wire>> resolveResult;

        private String updatedText;

        @Override
        public void run(@NotNull ProgressIndicator indicator) {
            indicator.setIndeterminate(true);
            File file = new File(virtualFile.getPath());
            try (Workspace workspace = Workspace.findWorkspace(file);
                Run run = Run.createRun(workspace, file);
                ProjectResolver projectResolver = new ProjectResolver(run)) {
                resolveResult = projectResolver.resolve();
                List<VersionedClause> versionedClauses = projectResolver.getRunBundles().stream().map(c -> {
                    Attrs attrs = new Attrs();
                    attrs.put(Constants.VERSION_ATTRIBUTE, c.getVersion());
                    return new VersionedClause(c.getBundleSymbolicName(), attrs);
                }).sorted(Comparator.comparing(VersionedClause::getName)).collect(Collectors.toList());
                BndEditModel editModel = new BndEditModel();
                IDocument bndDocument = new aQute.bnd.properties.Document(document.getImmutableCharSequence().toString());
                editModel.loadFrom(bndDocument);
                editModel.setRunBundles(versionedClauses);
                editModel.saveChangesTo(bndDocument);
                updatedText = bndDocument.get();
            } catch (ProcessCanceledException e) {
                throw e;
            } catch (Exception e) {
                throw new WrappingException(e);
            }
            indicator.checkCanceled();
        }

        @Override
        public void onSuccess() {
            if (new ResolutionSucceedDialog(project, resolveResult).showAndGet() && FileModificationService.getInstance().prepareVirtualFilesForWrite(project, Collections.singleton(virtualFile))) {
                writeCommandAction(project).withName("Bndrun Resolve").run(() -> document.setText(updatedText));
            }
        }

        @Override
        public void onThrowable(@NotNull Throwable t) {
            Throwable cause = t instanceof WrappingException ? t.getCause() : t;
            LOG.warn("Resolution failed", cause);
            if (cause instanceof ResolutionException) {
                new ResolutionFailedDialog(project, (ResolutionException) cause).show();
            } else {
                OsmorcBundle.notification(message("bnd.resolve.failed.title"), cause.getMessage(), NotificationType.ERROR).notify(project);
            }
        }
    }.queue();
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) WriteCommandAction.writeCommandAction(com.intellij.openapi.command.WriteCommandAction.writeCommandAction) Constants(aQute.bnd.osgi.Constants) VirtualFile(com.intellij.openapi.vfs.VirtualFile) Document(com.intellij.openapi.editor.Document) ProcessCanceledException(com.intellij.openapi.progress.ProcessCanceledException) Task(com.intellij.openapi.progress.Task) Workspace(aQute.bnd.build.Workspace) DialogWrapper(com.intellij.openapi.ui.DialogWrapper) Map(java.util.Map) Project(com.intellij.openapi.project.Project) CommonDataKeys(com.intellij.openapi.actionSystem.CommonDataKeys) Logger(com.intellij.openapi.diagnostic.Logger) OsmorcBundle.message(org.osmorc.i18n.OsmorcBundle.message) BndEditModel(aQute.bnd.build.model.BndEditModel) OsmorcBundle(org.osmorc.i18n.OsmorcBundle) ProjectResolver(biz.aQute.resolve.ProjectResolver) FileModificationService(com.intellij.codeInsight.FileModificationService) Resource(org.osgi.resource.Resource) AnAction(com.intellij.openapi.actionSystem.AnAction) FileDocumentManager(com.intellij.openapi.fileEditor.FileDocumentManager) Run(aQute.bnd.build.Run) Collectors(java.util.stream.Collectors) File(java.io.File) NotificationType(com.intellij.notification.NotificationType) BndFileType(org.jetbrains.osgi.bnd.BndFileType) Nullable(org.jetbrains.annotations.Nullable) ProgressIndicator(com.intellij.openapi.progress.ProgressIndicator) List(java.util.List) IDocument(aQute.bnd.properties.IDocument) VersionedClause(aQute.bnd.build.model.clauses.VersionedClause) Attrs(aQute.bnd.header.Attrs) Wire(org.osgi.resource.Wire) AnActionEvent(com.intellij.openapi.actionSystem.AnActionEvent) ResolutionException(org.osgi.service.resolver.ResolutionException) NotNull(org.jetbrains.annotations.NotNull) Comparator(java.util.Comparator) Collections(java.util.Collections) javax.swing(javax.swing) Task(com.intellij.openapi.progress.Task) VersionedClause(aQute.bnd.build.model.clauses.VersionedClause) ProjectResolver(biz.aQute.resolve.ProjectResolver) Attrs(aQute.bnd.header.Attrs) Document(com.intellij.openapi.editor.Document) IDocument(aQute.bnd.properties.IDocument) ProgressIndicator(com.intellij.openapi.progress.ProgressIndicator) List(java.util.List) BndEditModel(aQute.bnd.build.model.BndEditModel) ProcessCanceledException(com.intellij.openapi.progress.ProcessCanceledException) Resource(org.osgi.resource.Resource) Run(aQute.bnd.build.Run) ProcessCanceledException(com.intellij.openapi.progress.ProcessCanceledException) ResolutionException(org.osgi.service.resolver.ResolutionException) ResolutionException(org.osgi.service.resolver.ResolutionException) Project(com.intellij.openapi.project.Project) VirtualFile(com.intellij.openapi.vfs.VirtualFile) File(java.io.File) IDocument(aQute.bnd.properties.IDocument) Workspace(aQute.bnd.build.Workspace)

Example 48 with Wire

use of org.osgi.resource.Wire in project intellij-plugins by JetBrains.

the class ResolveConfirm method addRequirer.

private static void addRequirer(DefaultMutableTreeNode root, Resource resource, Map<Resource, List<Wire>> resolve) {
    List<Wire> wires = resolve.get(resource);
    if (wires == null)
        return;
    Map<Capability, DefaultMutableTreeNode> map = new HashMap<>();
    wires.forEach(wire -> {
        DefaultMutableTreeNode requirement = map.computeIfAbsent(wire.getCapability(), DefaultMutableTreeNode::new);
        DefaultMutableTreeNode child = new DefaultMutableTreeNode(wire.getRequirer());
        requirement.add(child);
        addRequirer(child, wire.getRequirer(), resolve);
    });
    map.values().forEach(root::add);
}
Also used : Capability(org.osgi.resource.Capability) DefaultMutableTreeNode(javax.swing.tree.DefaultMutableTreeNode) HashMap(java.util.HashMap) Wire(org.osgi.resource.Wire)

Example 49 with Wire

use of org.osgi.resource.Wire in project fabric8 by jboss-fuse.

the class SubsystemResolver method resolve.

public Map<Resource, List<Wire>> resolve(MetadataBuilder builder, Set<String> overrides, String featureResolutionRange, final org.osgi.service.repository.Repository globalRepository) throws Exception {
    if (root == null) {
        return Collections.emptyMap();
    }
    // Download bundles
    root.downloadBundles(manager, builder, overrides, featureResolutionRange);
    // Populate digraph and resolve
    digraph = new StandardRegionDigraph(null, null);
    populateDigraph(digraph, root);
    Resolver resolver = new ResolverImpl(new Slf4jResolverLog(LOGGER));
    Downloader downloader = manager.createDownloader();
    wiring = resolver.resolve(new SubsystemResolveContext(root, digraph, globalRepository, downloader));
    downloader.await();
    // Remove wiring to the fake environment resource
    if (environmentResource != null) {
        for (List<Wire> wires : wiring.values()) {
            for (Iterator<Wire> iterator = wires.iterator(); iterator.hasNext(); ) {
                Wire wire = iterator.next();
                if (wire.getProvider() == environmentResource) {
                    iterator.remove();
                }
            }
        }
    }
    // Fragments are always wired to their host only, so create fake wiring to
    // the subsystem the host is wired to
    associateFragments();
    return wiring;
}
Also used : Resolver(org.osgi.service.resolver.Resolver) Slf4jResolverLog(io.fabric8.agent.resolver.Slf4jResolverLog) Downloader(io.fabric8.agent.download.Downloader) ResolverImpl(org.apache.felix.resolver.ResolverImpl) Wire(org.osgi.resource.Wire) StandardRegionDigraph(org.eclipse.equinox.internal.region.StandardRegionDigraph)

Example 50 with Wire

use of org.osgi.resource.Wire in project fabric8 by jboss-fuse.

the class Deployer method computeBundlesToRefresh.

private void computeBundlesToRefresh(Map<Bundle, String> toRefresh, Collection<Bundle> bundles, Map<Resource, Bundle> resources, Map<Resource, List<Wire>> resolution) {
    // Compute the new list of fragments
    Map<Bundle, Set<Resource>> newFragments = new HashMap<>();
    for (Bundle bundle : bundles) {
        newFragments.put(bundle, new HashSet<Resource>());
    }
    if (resolution != null) {
        for (Resource res : resolution.keySet()) {
            for (Wire wire : resolution.get(res)) {
                if (HOST_NAMESPACE.equals(wire.getCapability().getNamespace())) {
                    Bundle bundle = resources.get(wire.getProvider());
                    if (bundle != null) {
                        Bundle b = resources.get(wire.getRequirer());
                        Resource r = b != null ? b.adapt(BundleRevision.class) : wire.getRequirer();
                        newFragments.get(bundle).add(r);
                    }
                }
            }
        }
    }
    // Main loop
    int size;
    Map<Bundle, Resource> bndToRes = new HashMap<>();
    for (Map.Entry<Resource, Bundle> entry : resources.entrySet()) {
        bndToRes.put(entry.getValue(), entry.getKey());
    }
    do {
        size = toRefresh.size();
        main: for (Bundle bundle : bundles) {
            Resource resource = bndToRes.get(bundle);
            // This bundle is not managed
            if (resource == null) {
                continue;
            }
            // Continue if we already know about this bundle
            if (toRefresh.containsKey(bundle)) {
                continue;
            }
            // Ignore non resolved bundle
            BundleWiring wiring = bundle.adapt(BundleWiring.class);
            if (wiring == null) {
                continue;
            }
            // Ignore bundles that won't be wired
            List<Wire> newWires = resolution.get(resource);
            if (newWires == null) {
                continue;
            }
            // Check if this bundle is a host and its fragments changed
            Set<Resource> oldFragments = new HashSet<>();
            for (BundleWire wire : wiring.getProvidedWires(null)) {
                if (HOST_NAMESPACE.equals(wire.getCapability().getNamespace())) {
                    oldFragments.add(wire.getRequirer());
                }
            }
            if (!oldFragments.equals(newFragments.get(bundle))) {
                toRefresh.put(bundle, "Attached fragments changed: " + new ArrayList<>(newFragments.get(bundle)));
                break;
            }
            // Compare the old and new resolutions
            Set<Resource> wiredBundles = new HashSet<>();
            for (BundleWire wire : wiring.getRequiredWires(null)) {
                BundleRevision rev = wire.getProvider();
                Bundle provider = rev.getBundle();
                if (toRefresh.containsKey(provider)) {
                    // The bundle is wired to a bundle being refreshed,
                    // so we need to refresh it too
                    toRefresh.put(bundle, "Wired to " + provider.getSymbolicName() + "/" + provider.getVersion() + " which is being refreshed");
                    continue main;
                }
                Resource res = bndToRes.get(provider);
                wiredBundles.add(res != null ? res : rev);
            }
            Map<Resource, Requirement> wiredResources = new HashMap<>();
            for (Wire wire : newWires) {
                // Handle only packages, hosts, and required bundles
                String namespace = wire.getRequirement().getNamespace();
                if (!namespace.equals(BundleNamespace.BUNDLE_NAMESPACE) && !namespace.equals(PackageNamespace.PACKAGE_NAMESPACE) && !namespace.equals(HostNamespace.HOST_NAMESPACE)) {
                    continue;
                }
                // Ignore non-resolution time requirements
                String effective = wire.getRequirement().getDirectives().get(Namespace.CAPABILITY_EFFECTIVE_DIRECTIVE);
                if (effective != null && !Namespace.EFFECTIVE_RESOLVE.equals(effective)) {
                    continue;
                }
                // Ignore non bundle resources
                if (!isBundle(wire.getProvider())) {
                    continue;
                }
                if (!wiredResources.containsKey(wire.getProvider())) {
                    wiredResources.put(wire.getProvider(), wire.getRequirement());
                }
            }
            if (!wiredBundles.containsAll(wiredResources.keySet())) {
                Map<Resource, Requirement> newResources = new HashMap<>(wiredResources);
                newResources.keySet().removeAll(wiredBundles);
                StringBuilder sb = new StringBuilder();
                sb.append("Should be wired to: ");
                boolean first = true;
                for (Map.Entry<Resource, Requirement> entry : newResources.entrySet()) {
                    if (!first) {
                        sb.append(", ");
                    } else {
                        first = false;
                    }
                    Resource res = entry.getKey();
                    Requirement req = entry.getValue();
                    sb.append(getSymbolicName(res)).append("/").append(getVersion(res));
                    sb.append(" (through ");
                    sb.append(req);
                    sb.append(")");
                }
                toRefresh.put(bundle, sb.toString());
            }
        }
    } while (toRefresh.size() > size);
}
Also used : MapUtils.addToMapSet(io.fabric8.agent.internal.MapUtils.addToMapSet) MapUtils.removeFromMapSet(io.fabric8.agent.internal.MapUtils.removeFromMapSet) Bundle(org.osgi.framework.Bundle) BundleWiring(org.osgi.framework.wiring.BundleWiring) Resource(org.osgi.resource.Resource) FeatureResource(io.fabric8.agent.resolver.FeatureResource) Wire(org.osgi.resource.Wire) BundleWire(org.osgi.framework.wiring.BundleWire) BundleWire(org.osgi.framework.wiring.BundleWire) Requirement(org.osgi.resource.Requirement) ZipEntry(java.util.zip.ZipEntry) BundleRevision(org.osgi.framework.wiring.BundleRevision)

Aggregations

Wire (org.osgi.resource.Wire)58 Resource (org.osgi.resource.Resource)49 ArrayList (java.util.ArrayList)38 List (java.util.List)36 HashMap (java.util.HashMap)35 Requirement (org.osgi.resource.Requirement)31 Capability (org.osgi.resource.Capability)29 Wiring (org.osgi.resource.Wiring)18 BundleCapability (org.apache.felix.resolver.test.util.BundleCapability)15 BundleRequirement (org.apache.felix.resolver.test.util.BundleRequirement)15 GenericCapability (org.apache.felix.resolver.test.util.GenericCapability)15 GenericRequirement (org.apache.felix.resolver.test.util.GenericRequirement)15 PackageCapability (org.apache.felix.resolver.test.util.PackageCapability)15 PackageRequirement (org.apache.felix.resolver.test.util.PackageRequirement)15 ResolverImpl (org.apache.felix.resolver.ResolverImpl)14 ResolveContextImpl (org.apache.felix.resolver.test.util.ResolveContextImpl)14 Logger (org.apache.felix.resolver.Logger)13 Test (org.junit.Test)13 Resolver (org.osgi.service.resolver.Resolver)12 Map (java.util.Map)11