You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@felix.apache.org by ri...@apache.org on 2008/12/23 21:07:49 UTC
svn commit: r729083 [2/3] - in
/felix/trunk/framework/src/main/java/org/apache/felix/framework: ./
searchpolicy/
Modified: felix/trunk/framework/src/main/java/org/apache/felix/framework/searchpolicy/R4SearchPolicyCore.java
URL: http://svn.apache.org/viewvc/felix/trunk/framework/src/main/java/org/apache/felix/framework/searchpolicy/R4SearchPolicyCore.java?rev=729083&r1=729082&r2=729083&view=diff
==============================================================================
--- felix/trunk/framework/src/main/java/org/apache/felix/framework/searchpolicy/R4SearchPolicyCore.java (original)
+++ felix/trunk/framework/src/main/java/org/apache/felix/framework/searchpolicy/R4SearchPolicyCore.java Tue Dec 23 12:07:49 2008
@@ -22,72 +22,49 @@
import java.lang.reflect.Proxy;
import java.net.URL;
import java.util.ArrayList;
-import java.util.Arrays;
import java.util.Enumeration;
-import java.util.HashMap;
-import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
-import org.apache.felix.framework.BundleProtectionDomain;
+import org.apache.felix.framework.Felix.FelixResolver;
import org.apache.felix.framework.Logger;
import org.apache.felix.framework.util.CompoundEnumeration;
import org.apache.felix.framework.util.SecurityManagerEx;
import org.apache.felix.framework.util.Util;
-import org.apache.felix.framework.util.manifestparser.Capability;
-import org.apache.felix.framework.util.manifestparser.R4Attribute;
-import org.apache.felix.framework.util.manifestparser.R4Directive;
import org.apache.felix.framework.util.manifestparser.R4Library;
import org.apache.felix.framework.util.manifestparser.Requirement;
import org.apache.felix.moduleloader.ICapability;
import org.apache.felix.moduleloader.IModule;
-import org.apache.felix.moduleloader.IModuleFactory;
import org.apache.felix.moduleloader.IRequirement;
import org.apache.felix.moduleloader.IWire;
-import org.apache.felix.moduleloader.ModuleEvent;
-import org.apache.felix.moduleloader.ModuleImpl;
-import org.apache.felix.moduleloader.ModuleListener;
import org.apache.felix.moduleloader.ResourceNotFoundException;
import org.osgi.framework.Constants;
import org.osgi.framework.InvalidSyntaxException;
-import org.osgi.framework.PackagePermission;
-import org.osgi.framework.Version;
import org.osgi.framework.Bundle;
-public class R4SearchPolicyCore implements ModuleListener
+public class R4SearchPolicyCore
{
- private Logger m_logger = null;
- private Map m_configMap = null;
- private IModuleFactory m_factory = null;
- // Maps a package name to an array of modules.
- private Map m_unresolvedPkgIndexMap = new HashMap();
- // Maps a package name to an array of modules.
- private Map m_resolvedPkgIndexMap = new HashMap();
- // Maps a module to an array of capabilities.
- private Map m_resolvedCapMap = new HashMap();
- private Map m_moduleDataMap = new HashMap();
+ private final Logger m_logger;
+ private final Map m_configMap;
+ private final FelixResolver m_resolver;
// Boot delegation packages.
private String[] m_bootPkgs = null;
private boolean[] m_bootPkgWildcards = null;
- // Listener-related instance variables.
- private static final ResolveListener[] m_emptyListeners = new ResolveListener[0];
- private ResolveListener[] m_listeners = m_emptyListeners;
-
// Reusable empty array.
- public static final IModule[] m_emptyModules = new IModule[0];
public static final ICapability[] m_emptyCapabilities = new ICapability[0];
- public static final PackageSource[] m_emptySources = new PackageSource[0];
// Re-usable security manager for accessing class context.
private static SecurityManagerEx m_sm = new SecurityManagerEx();
- public R4SearchPolicyCore(Logger logger, Map configMap)
+ public R4SearchPolicyCore(
+ Logger logger, Map configMap, FelixResolver resolver)
{
m_logger = logger;
m_configMap = configMap;
+ m_resolver = resolver;
// Read the boot delegation property and parse it.
String s = (String) m_configMap.get(Constants.FRAMEWORK_BOOTDELEGATION);
@@ -107,53 +84,6 @@
}
}
- public IModuleFactory getModuleFactory()
- {
- return m_factory;
- }
-
- public void setModuleFactory(IModuleFactory factory)
- throws IllegalStateException
- {
- if (m_factory == null)
- {
- m_factory = factory;
- m_factory.addModuleListener(this);
- }
- else
- {
- throw new IllegalStateException(
- "Module manager is already initialized");
- }
- }
-
- /**
- * Private utility method to check module resolved state.
- * CONCURRENCY NOTE: This method must be called while holding
- * a lock on m_factory.
- **/
- private boolean isResolved(IModule module)
- {
- ModuleData data = (ModuleData) m_moduleDataMap.get(module);
- return (data == null) ? false : data.m_resolved;
- }
-
- /**
- * Private utility method to set module resolved state.
- * CONCURRENCY NOTE: This method must be called while holding
- * a lock on m_factory.
- **/
- private void setResolved(IModule module, boolean resolved)
- {
- ModuleData data = (ModuleData) m_moduleDataMap.get(module);
- if (data == null)
- {
- data = new ModuleData(module);
- m_moduleDataMap.put(module, data);
- }
- data.m_resolved = resolved;
- }
-
public Object[] definePackage(IModule module, String pkgName)
{
Map headerMap = ((ModuleDefinition) module.getDefinition()).getHeaders();
@@ -233,7 +163,7 @@
// for each class load.
try
{
- resolve(module);
+ m_resolver.resolve(module);
}
catch (ResolveException ex)
{
@@ -350,7 +280,15 @@
// At this point, the module's imports were searched and so was the
// the module's content. Now we make an attempt to load the
// class/resource via a dynamic import, if possible.
- IWire wire = attemptDynamicImport(module, pkgName);
+ IWire wire = null;
+ try
+ {
+ wire = m_resolver.resolveDynamicImport(module, pkgName);
+ }
+ catch (ResolveException ex)
+ {
+ // Ignore this since it is likely normal.
+ }
if (wire != null)
{
urls = wire.getResources(name);
@@ -374,7 +312,7 @@
// for each class load.
try
{
- resolve(module);
+ m_resolver.resolve(module);
}
catch (ResolveException ex)
{
@@ -521,7 +459,15 @@
// At this point, the module's imports were searched and so was the
// the module's content. Now we make an attempt to load the
// class/resource via a dynamic import, if possible.
- IWire wire = attemptDynamicImport(module, pkgName);
+ IWire wire = null;
+ try
+ {
+ wire = m_resolver.resolveDynamicImport(module, pkgName);
+ }
+ catch (ResolveException ex)
+ {
+ // Ignore this since it is likely normal.
+ }
// If the dynamic import was successful, then this initial
// time we must directly return the result from dynamically
@@ -622,259 +568,6 @@
return null;
}
- private IWire attemptDynamicImport(IModule importer, String pkgName)
- {
- R4Wire wire = null;
- PackageSource candidate = null;
-
- // We can only search dynamic imports if the bundle
- // doesn't import, export, nor require the package in
- // question. Check these conditions first.
- if (isDynamicImportAllowed(importer, pkgName))
- {
- // Loop through the importer's dynamic requirements to determine if
- // there is a matching one for the package from which we want to
- // load a class.
- IRequirement[] dynamics = importer.getDefinition().getDynamicRequirements();
- for (int dynIdx = 0; (dynamics != null) && (dynIdx < dynamics.length); dynIdx++)
- {
- IRequirement target =
- createDynamicRequirement(dynamics[dynIdx], pkgName);
- if (target != null)
- {
- // See if there is a candidate exporter that satisfies the
- // constrained dynamic requirement.
- try
- {
- // Lock module manager instance to ensure that nothing changes.
- synchronized (m_factory)
- {
- // Get "resolved" and "unresolved" candidates and put
- // the "resolved" candidates first.
- PackageSource[] resolved = getResolvedCandidates(target);
- PackageSource[] unresolved = getUnresolvedCandidates(target);
- PackageSource[] candidates = new PackageSource[resolved.length + unresolved.length];
- System.arraycopy(resolved, 0, candidates, 0, resolved.length);
- System.arraycopy(unresolved, 0, candidates, resolved.length, unresolved.length);
-
- // Take the first candidate that can resolve.
- for (int candIdx = 0;
- (candidate == null) && (candIdx < candidates.length);
- candIdx++)
- {
- try
- {
- if (resolveDynamicImportCandidate(
- candidates[candIdx].m_module, importer))
- {
- candidate = candidates[candIdx];
- }
- }
- catch (ResolveException ex)
- {
- // Ignore candidates that cannot resolve.
- }
- }
-
- if (candidate != null)
- {
- IWire[] wires = importer.getWires();
- IWire[] newWires = null;
- if (wires == null)
- {
- newWires = new IWire[1];
- }
- else
- {
- newWires = new IWire[wires.length + 1];
- System.arraycopy(wires, 0, newWires, 0, wires.length);
- }
-
- // Create the wire and add it to the module.
- wire = new R4Wire(
- importer, dynamics[dynIdx], candidate.m_module, candidate.m_capability);
- newWires[newWires.length - 1] = wire;
- ((ModuleImpl) importer).setWires(newWires);
-m_logger.log(Logger.LOG_DEBUG, "WIRE: " + newWires[newWires.length - 1]);
- return wire;
- }
- }
- }
- catch (Exception ex)
- {
- m_logger.log(Logger.LOG_ERROR, "Unable to dynamically import package.", ex);
- }
- }
- }
- }
-
- return null;
- }
-
- private boolean isDynamicImportAllowed(IModule importer, String pkgName)
- {
- // If any of the module exports this package, then we cannot
- // attempt to dynamically import it.
- ICapability[] caps = importer.getDefinition().getCapabilities();
- for (int i = 0; (caps != null) && (i < caps.length); i++)
- {
- if (caps[i].getNamespace().equals(ICapability.PACKAGE_NAMESPACE)
- && caps[i].getProperties().get(ICapability.PACKAGE_PROPERTY).equals(pkgName))
- {
- return false;
- }
- }
- // If any of our wires have this package, then we cannot
- // attempt to dynamically import it.
- IWire[] wires = importer.getWires();
- for (int i = 0; (wires != null) && (i < wires.length); i++)
- {
- if (wires[i].hasPackage(pkgName))
- {
- return false;
- }
- }
- // Ok to attempt to dynamically import the package.
- return true;
- }
-
- private IRequirement createDynamicRequirement(IRequirement dynReq, String pkgName)
- {
- IRequirement req = null;
-
- // First check to see if the dynamic requirement matches the
- // package name; this means we have to do wildcard matching.
- String dynPkgName = ((Requirement) dynReq).getPackageName();
- boolean wildcard = (dynPkgName.lastIndexOf(".*") >= 0);
- dynPkgName = (wildcard)
- ? dynPkgName.substring(0, dynPkgName.length() - 2) : dynPkgName;
- // If the dynamic requirement matches the package name, then
- // create a new requirement for the specific package.
- if (dynPkgName.equals("*") ||
- pkgName.equals(dynPkgName) ||
- (wildcard && pkgName.startsWith(dynPkgName + ".")))
- {
- // Create a new requirement based on the dynamic requirement,
- // but substitute the precise package name for which we are
- // looking, because it is not possible to use the potentially
- // wildcarded version in the dynamic requirement.
- R4Directive[] dirs = ((Requirement) dynReq).getDirectives();
- R4Attribute[] attrs = ((Requirement) dynReq).getAttributes();
- R4Attribute[] newAttrs = new R4Attribute[attrs.length];
- System.arraycopy(attrs, 0, newAttrs, 0, attrs.length);
- for (int attrIdx = 0; attrIdx < newAttrs.length; attrIdx++)
- {
- if (newAttrs[attrIdx].getName().equals(ICapability.PACKAGE_PROPERTY))
- {
- newAttrs[attrIdx] = new R4Attribute(
- ICapability.PACKAGE_PROPERTY, pkgName, false);
- break;
- }
- }
- req = new Requirement(ICapability.PACKAGE_NAMESPACE, dirs, newAttrs);
- }
-
- return req;
- }
-
- private boolean resolveDynamicImportCandidate(IModule provider, IModule importer)
- throws ResolveException
- {
- // If the provider of the dynamically imported package is not
- // resolved, then we need to calculate the candidates to resolve
- // it and see if there is a consistent class space for the
- // provider. If there is no consistent class space, then a resolve
- // exception is thrown.
- Map candidatesMap = new HashMap();
- if (!isResolved(provider))
- {
- populateCandidatesMap(candidatesMap, provider);
- findConsistentClassSpace(candidatesMap, provider);
- }
-
- // If the provider can be successfully resolved, then verify that
- // its class space is consistent with the existing class space of the
- // module that instigated the dynamic import.
- Map moduleMap = new HashMap();
- Map importerPkgMap = getModulePackages(moduleMap, importer, candidatesMap);
-
- // Now we need to calculate the "uses" constraints of every package
- // accessible to the provider module based on its current candidates.
- Map usesMap = calculateUsesConstraints(provider, moduleMap, candidatesMap);
-
- // Verify that none of the provider's implied "uses" constraints
- // in the uses map conflict with anything in the importing module's
- // package map.
- for (Iterator iter = usesMap.entrySet().iterator(); iter.hasNext(); )
- {
- Map.Entry entry = (Map.Entry) iter.next();
-
- // For the given "used" package, get that package from the
- // importing module's package map, if present.
- ResolvedPackage rp = (ResolvedPackage) importerPkgMap.get(entry.getKey());
-
- // If the "used" package is also visible to the importing
- // module, make sure there is no conflicts in the implied
- // "uses" constraints.
- if (rp != null)
- {
- // Clone the resolve package so we can modify it.
- rp = (ResolvedPackage) rp.clone();
-
- // Loop through all implied "uses" constraints for the current
- // "used" package and verify that all package sources are
- // compatible with the package source of the importing module's
- // package map.
- List constraintList = (List) entry.getValue();
- for (int constIdx = 0; constIdx < constraintList.size(); constIdx++)
- {
- // Get a specific "uses" constraint for the current "used"
- // package.
- ResolvedPackage rpUses = (ResolvedPackage) constraintList.get(constIdx);
- // Determine if the implied "uses" constraint is compatible with
- // the improting module's package sources for the given "used"
- // package. They are compatible if one is the subset of the other.
- // Retain the union of the two sets if they are compatible.
- if (rpUses.isSubset(rp))
- {
- // Do nothing because we already have the superset.
- }
- else if (rp.isSubset(rpUses))
- {
- // Keep the superset, i.e., the union.
- rp.m_sourceList.clear();
- rp.m_sourceList.addAll(rpUses.m_sourceList);
- }
- else
- {
- m_logger.log(
- Logger.LOG_DEBUG,
- "Constraint violation for " + importer
- + " detected; module can see "
- + rp + " and " + rpUses);
- return false;
- }
- }
- }
- }
-
- Map resolvedModuleWireMap = createWires(candidatesMap, provider);
-
- // Fire resolved events for all resolved modules;
- // the resolved modules array will only be set if the resolve
- // was successful.
- if (resolvedModuleWireMap != null)
- {
- Iterator iter = resolvedModuleWireMap.entrySet().iterator();
- while (iter.hasNext())
- {
- fireModuleResolved((IModule) ((Map.Entry) iter.next()).getKey());
- }
- }
-
- return true;
- }
-
public String findLibrary(IModule module, String name)
{
// Remove leading slash, if present.
@@ -896,2449 +589,127 @@
return null;
}
- public PackageSource[] getResolvedCandidates(IRequirement req)
- {
- // Synchronized on the module manager to make sure that no
- // modules are added, removed, or resolved.
- synchronized (m_factory)
- {
- PackageSource[] candidates = m_emptySources;
- if (req.getNamespace().equals(ICapability.PACKAGE_NAMESPACE)
- && (((Requirement) req).getPackageName() != null))
- {
- String pkgName = ((Requirement) req).getPackageName();
- IModule[] modules = (IModule[]) m_resolvedPkgIndexMap.get(pkgName);
-
- for (int modIdx = 0; (modules != null) && (modIdx < modules.length); modIdx++)
- {
- ICapability resolvedCap = Util.getSatisfyingCapability(modules[modIdx], req);
- if (resolvedCap != null)
- {
-// TODO: RB - Is this permission check correct.
- if ((System.getSecurityManager() != null) &&
- !((BundleProtectionDomain) modules[modIdx].getContentLoader().getSecurityContext()).impliesDirect(
- new PackagePermission(pkgName,
- PackagePermission.EXPORT)))
- {
- m_logger.log(Logger.LOG_DEBUG,
- "PackagePermission.EXPORT denied for "
- + pkgName
- + "from " + modules[modIdx].getId());
- }
- else
- {
- PackageSource[] tmp = new PackageSource[candidates.length + 1];
- System.arraycopy(candidates, 0, tmp, 0, candidates.length);
- tmp[candidates.length] =
- new PackageSource(modules[modIdx], resolvedCap);
- candidates = tmp;
- }
- }
- }
- }
- else
- {
- Iterator i = m_resolvedCapMap.entrySet().iterator();
- while (i.hasNext())
- {
- Map.Entry entry = (Map.Entry) i.next();
- IModule module = (IModule) entry.getKey();
- ICapability[] resolvedCaps = (ICapability[]) entry.getValue();
- for (int capIdx = 0; capIdx < resolvedCaps.length; capIdx++)
- {
- if (req.isSatisfied(resolvedCaps[capIdx]))
- {
-// TODO: RB - Is this permission check correct.
- if (resolvedCaps[capIdx].getNamespace().equals(ICapability.PACKAGE_NAMESPACE) &&
- (System.getSecurityManager() != null) &&
- !((BundleProtectionDomain) module.getContentLoader().getSecurityContext()).impliesDirect(
- new PackagePermission(
- (String) resolvedCaps[capIdx].getProperties().get(ICapability.PACKAGE_PROPERTY),
- PackagePermission.EXPORT)))
- {
- m_logger.log(Logger.LOG_DEBUG,
- "PackagePermission.EXPORT denied for "
- + resolvedCaps[capIdx].getProperties().get(ICapability.PACKAGE_PROPERTY)
- + "from " + module.getId());
- }
- else
- {
- PackageSource[] tmp = new PackageSource[candidates.length + 1];
- System.arraycopy(candidates, 0, tmp, 0, candidates.length);
- tmp[candidates.length] = new PackageSource(module, resolvedCaps[capIdx]);
- candidates = tmp;
- }
- }
- }
- }
- }
- Arrays.sort(candidates);
- return candidates;
- }
- }
-
- public PackageSource[] getUnresolvedCandidates(IRequirement req)
+ /**
+ * This is an experimental method that is likely to change or go
+ * away - so don't use it for now.
+ *
+ * Note to self, we need to think about what the implications of
+ * this are and whether we are fine with them.
+ */
+ /*
+ * This method is used by the framework to let us know that we need to re-read
+ * the system bundle capabilities which have been extended by an extension bundle.
+ *
+ * For now we assume that capabilities have been added only. We might need to
+ * enforce that at one point of time.
+ */
+/* TODO: RESOLVER - We need to figure out what to do with this.
+ public void moduleRefreshed(ModuleEvent event)
{
- // Synchronized on the module manager to make sure that no
- // modules are added, removed, or resolved.
synchronized (m_factory)
{
- // Get all modules.
- IModule[] modules = null;
- if (req.getNamespace().equals(ICapability.PACKAGE_NAMESPACE) &&
- (((Requirement) req).getPackageName() != null))
- {
- modules = (IModule[]) m_unresolvedPkgIndexMap.get(((Requirement) req).getPackageName());
- }
- else
+ IModule module = event.getModule();
+ // Remove exports from package maps.
+ ICapability[] caps = event.getModule().getDefinition().getCapabilities();
+ // Add exports to unresolved package map.
+ for (int i = 0; (caps != null) && (i < caps.length); i++)
{
- modules = m_factory.getModules();
- }
+ ICapability[] resolvedCaps = (ICapability[]) m_resolvedCapMap.get(module);
+ resolvedCaps = addCapabilityToArray(resolvedCaps, caps[i]);
+ m_resolvedCapMap.put(module, resolvedCaps);
- // Create list of compatible providers.
- PackageSource[] candidates = m_emptySources;
- for (int modIdx = 0; (modules != null) && (modIdx < modules.length); modIdx++)
- {
- // Get the module's export package for the target package.
- ICapability cap = Util.getSatisfyingCapability(modules[modIdx], req);
- // If compatible and it is not currently resolved, then add
- // the unresolved candidate to the list.
- if ((cap != null) && !isResolved(modules[modIdx]))
+ // If the capability is a package, then add the exporter module
+ // of the wire to the "resolved" package index and remove it
+ // from the "unresolved" package index.
+ if (caps[i].getNamespace().equals(ICapability.PACKAGE_NAMESPACE))
{
- PackageSource[] tmp = new PackageSource[candidates.length + 1];
- System.arraycopy(candidates, 0, tmp, 0, candidates.length);
- tmp[candidates.length] = new PackageSource(modules[modIdx], cap);
- candidates = tmp;
+ // Get package name.
+ String pkgName = (String)
+ caps[i].getProperties().get(ICapability.PACKAGE_PROPERTY);
+ // Add to "resolved" package index.
+ indexPackageCapability(
+ m_resolvedPkgIndexMap,
+ module,
+ caps[i]);
}
}
- Arrays.sort(candidates);
- return candidates;
}
}
+*/
+ //
+ // Diagnostics.
+ //
- public void resolve(IModule rootModule)
- throws ResolveException
+ private String diagnoseClassLoadError(IModule module, String name)
{
- // This map will be used to hold the final wires for all
- // resolved modules, which can then be used to fire resolved
- // events outside of the synchronized block.
- Map resolvedModuleWireMap = null;
- Map fragmentMap = null;
-
- // Synchronize on the module manager, because we don't want
- // any modules being added or removed while we are in the
- // middle of this operation.
- synchronized (m_factory)
- {
- // If the module is already resolved, then we can just return.
- if (isResolved(rootModule))
- {
- return;
- }
+ // We will try to do some diagnostics here to help the developer
+ // deal with this exception.
- // The root module is either a host or a fragment. If it is a host,
- // then we want to go ahead and resolve it. If it is a fragment, then
- // we want to select a host and resolve the host instead.
- IModule targetFragment = null;
-// TODO: FRAGMENT - Currently we just make a single selection of the available
-// fragments or hosts and try to resolve. In case of failure, we do not
-// backtrack. We will likely want to add backtracking.
- if (Util.isFragment(rootModule))
- {
- targetFragment = rootModule;
- List hostList = getPotentialHosts(targetFragment);
- rootModule = (IModule) hostList.get(0);
- }
-
- // Get the available fragments for the host.
- fragmentMap = getPotentialFragments(rootModule);
-
- // If the resolve was for a specific fragment, then
- // eliminate all other potential candidate fragments
- // of the same symbolic name.
- if (targetFragment != null)
- {
- fragmentMap.put(
- getBundleSymbolicName(targetFragment),
- new IModule[] { targetFragment });
- }
-
- // This variable maps an unresolved module to a list of candidate
- // sets, where there is one candidate set for each requirement that
- // must be resolved. A candidate set contains the potential canidates
- // available to resolve the requirement and the currently selected
- // candidate index.
- Map candidatesMap = new HashMap();
-
- // The first step is to populate the candidates map. This
- // will use the target module to populate the candidates map
- // with all potential modules that need to be resolved as a
- // result of resolving the target module. The key of the
- // map is a potential module to be resolved and the value is
- // a list of candidate sets, one for each of the module's
- // requirements, where each candidate set contains the potential
- // candidates for resolving the requirement. Not all modules in
- // this map will be resolved, only the target module and
- // any candidates selected to resolve its requirements and the
- // transitive requirements this implies.
- populateCandidatesMap(candidatesMap, rootModule);
-
- // The next step is to use the candidates map to determine if
- // the class space for the root module is consistent. This
- // is an iterative process that transitively walks the "uses"
- // relationships of all packages visible from the root module
- // checking for conflicts. If a conflict is found, it "increments"
- // the configuration of currently selected potential candidates
- // and tests them again. If this method returns, then it has found
- // a consistent set of candidates; otherwise, a resolve exception
- // is thrown if it exhausts all possible combinations and could
- // not find a consistent class space.
- findConsistentClassSpace(candidatesMap, rootModule);
-
- // The final step is to create the wires for the root module and
- // transitively all modules that are to be resolved from the
- // selected candidates for resolving the root module's imports.
- // When this call returns, each module's wiring and resolved
- // attributes are set. The resulting wiring map is used below
- // to fire resolved events outside of the synchronized block.
- // The resolved module wire map maps a module to its array of
- // wires.
- resolvedModuleWireMap = createWires(candidatesMap, rootModule);
+ // Get package name.
+ String pkgName = Util.getClassPackage(name);
- // Attach fragments to root module.
- if ((fragmentMap != null) && (fragmentMap.size() > 0))
- {
- List list = new ArrayList();
- for (Iterator iter = fragmentMap.entrySet().iterator(); iter.hasNext(); )
- {
- Map.Entry entry = (Map.Entry) iter.next();
- String symName = (String) entry.getKey();
- IModule[] fragments = (IModule[]) entry.getValue();
-// TODO: FRAGMENT - For now, just attach first candidate.
- list.add(fragments[0]);
- setResolved(fragments[0], true);
-m_logger.log(Logger.LOG_DEBUG, "(FRAGMENT) WIRE: "
- + rootModule + " -> " + symName + " -> " + fragments[0]);
- }
- try
- {
- ((ModuleImpl) rootModule).attachFragments(
- (IModule[]) list.toArray(new IModule[list.size()]));
- }
- catch (Exception ex)
- {
- m_logger.log(Logger.LOG_ERROR, "Unable to attach fragments", ex);
- }
- }
- } // End of synchronized block on module manager.
+ // First, get the bundle ID of the module doing the class loader.
+ long impId = Util.getBundleIdFromModuleId(module.getId());
- // Fire resolved events for all resolved modules;
- // the resolved modules array will only be set if the resolve
- // was successful after the root module was resolved.
- if (resolvedModuleWireMap != null)
+ // Next, check to see if the module imports the package.
+ IWire[] wires = module.getWires();
+ for (int i = 0; (wires != null) && (i < wires.length); i++)
{
- Iterator iter = resolvedModuleWireMap.entrySet().iterator();
- while (iter.hasNext())
- {
- fireModuleResolved((IModule) ((Map.Entry) iter.next()).getKey());
- }
- iter = fragmentMap.entrySet().iterator();
- while (iter.hasNext())
+ if (wires[i].getCapability().getNamespace().equals(ICapability.PACKAGE_NAMESPACE) &&
+ wires[i].getCapability().getProperties().get(ICapability.PACKAGE_PROPERTY).equals(pkgName))
{
- fireModuleResolved(((IModule[]) ((Map.Entry) iter.next()).getValue())[0]);
- }
- }
- }
+ long expId = Util.getBundleIdFromModuleId(
+ wires[i].getExporter().getId());
- // TODO: FRAGMENT - Not very efficient.
- private List getPotentialHosts(IModule fragment)
- throws ResolveException
- {
- List hostList = new ArrayList();
+ StringBuffer sb = new StringBuffer("*** Package '");
+ sb.append(pkgName);
+ sb.append("' is imported by bundle ");
+ sb.append(impId);
+ sb.append(" from bundle ");
+ sb.append(expId);
+ sb.append(", but the exported package from bundle ");
+ sb.append(expId);
+ sb.append(" does not contain the requested class '");
+ sb.append(name);
+ sb.append("'. Please verify that the class name is correct in the importing bundle ");
+ sb.append(impId);
+ sb.append(" and/or that the exported package is correctly bundled in ");
+ sb.append(expId);
+ sb.append(". ***");
- IRequirement[] reqs = fragment.getDefinition().getRequirements();
- IRequirement hostReq = null;
- for (int reqIdx = 0; reqIdx < reqs.length; reqIdx++)
- {
- if (reqs[reqIdx].getNamespace().equals(ICapability.HOST_NAMESPACE))
- {
- hostReq = reqs[reqIdx];
- break;
+ return sb.toString();
}
}
- IModule[] modules = m_factory.getModules();
- for (int modIdx = 0; (hostReq != null) && (modIdx < modules.length); modIdx++)
+ // Next, check to see if the package was optionally imported and
+ // whether or not there is an exporter available.
+ IRequirement[] reqs = module.getDefinition().getRequirements();
+/*
+ * TODO: RB - Fix diagnostic message for optional imports.
+ for (int i = 0; (reqs != null) && (i < reqs.length); i++)
{
- if (!fragment.equals(modules[modIdx]) && !isResolved(modules[modIdx]))
+ if (reqs[i].getName().equals(pkgName) && reqs[i].isOptional())
{
- ICapability[] caps = modules[modIdx].getDefinition().getCapabilities();
- for (int capIdx = 0; (caps != null) && (capIdx < caps.length); capIdx++)
+ // Try to see if there is an exporter available.
+ IModule[] exporters = getResolvedExporters(reqs[i], true);
+ exporters = (exporters.length == 0)
+ ? getUnresolvedExporters(reqs[i], true) : exporters;
+
+ // An exporter might be available, but it may have attributes
+ // that do not match the importer's required attributes, so
+ // check that case by simply looking for an exporter of the
+ // desired package without any attributes.
+ if (exporters.length == 0)
{
- if (caps[capIdx].getNamespace().equals(ICapability.HOST_NAMESPACE)
- && hostReq.isSatisfied(caps[capIdx])
- && !modules[modIdx].isStale())
- {
- hostList.add(modules[modIdx]);
- break;
- }
+ IRequirement pkgReq = new Requirement(
+ ICapability.PACKAGE_NAMESPACE, "(package=" + pkgName + ")");
+ exporters = getResolvedExporters(pkgReq, true);
+ exporters = (exporters.length == 0)
+ ? getUnresolvedExporters(pkgReq, true) : exporters;
}
- }
- }
-
- if (hostList.size() == 0)
- {
- throw new ResolveException("Unable to resolve.", fragment, hostReq);
- }
-
- return hostList;
- }
-
-// TODO: FRAGMENT - Not very efficient.
- private Map getPotentialFragments(IModule host)
- {
-// TODO: FRAGMENT - This should check to make sure that the host allows fragments.
- Map fragmentMap = new HashMap();
- ICapability[] caps = host.getDefinition().getCapabilities();
- ICapability bundleCap = null;
- for (int capIdx = 0; capIdx < caps.length; capIdx++)
- {
- if (caps[capIdx].getNamespace().equals(ICapability.HOST_NAMESPACE))
- {
- bundleCap = caps[capIdx];
- break;
- }
- }
-
- IModule[] modules = m_factory.getModules();
- for (int modIdx = 0; (bundleCap != null) && (modIdx < modules.length); modIdx++)
- {
- if (!host.equals(modules[modIdx]))
- {
- IRequirement[] reqs = modules[modIdx].getDefinition().getRequirements();
- for (int reqIdx = 0; (reqs != null) && (reqIdx < reqs.length); reqIdx++)
- {
- if (reqs[reqIdx].getNamespace().equals(ICapability.HOST_NAMESPACE)
- && reqs[reqIdx].isSatisfied(bundleCap)
- && !modules[modIdx].isStale())
- {
- indexFragment(fragmentMap, modules[modIdx]);
- break;
- }
- }
- }
- }
-
- return fragmentMap;
- }
-
-// TODO: FRAGMENT - Not very efficient.
- private static String getBundleSymbolicName(IModule module)
- {
- ICapability[] caps = module.getDefinition().getCapabilities();
- for (int capIdx = 0; (caps != null) && (capIdx < caps.length); capIdx++)
- {
- if (caps[capIdx].getNamespace().equals(ICapability.MODULE_NAMESPACE))
- {
- return (String)
- caps[capIdx].getProperties().get(Constants.BUNDLE_SYMBOLICNAME_ATTRIBUTE);
- }
- }
- return null;
- }
-
-// TODO: FRAGMENT - Not very efficient.
- private static Version getBundleVersion(IModule module)
- {
- ICapability[] caps = module.getDefinition().getCapabilities();
- for (int capIdx = 0; (caps != null) && (capIdx < caps.length); capIdx++)
- {
- if (caps[capIdx].getNamespace().equals(ICapability.MODULE_NAMESPACE))
- {
- return (Version)
- caps[capIdx].getProperties().get(Constants.BUNDLE_VERSION_ATTRIBUTE);
- }
- }
- return Version.emptyVersion;
- }
-
- private void indexFragment(Map map, IModule module)
- {
- String symName = getBundleSymbolicName(module);
- IModule[] modules = (IModule[]) map.get(symName);
-
- // We want to add the fragment into the list of matching
- // fragments in sorted order (descending version and
- // ascending bundle identifier). Insert using a simple
- // binary search algorithm.
- if (modules == null)
- {
- modules = new IModule[] { module };
- }
- else
- {
- Version version = getBundleVersion(module);
- Version middleVersion = null;
- int top = 0, bottom = modules.length - 1, middle = 0;
- while (top <= bottom)
- {
- middle = (bottom - top) / 2 + top;
- middleVersion = getBundleVersion(modules[middle]);
- // Sort in reverse version order.
- int cmp = middleVersion.compareTo(version);
- if (cmp < 0)
- {
- bottom = middle - 1;
- }
- else if (cmp == 0)
- {
- // Sort further by ascending bundle ID.
- long middleId = Util.getBundleIdFromModuleId(modules[middle].getId());
- long exportId = Util.getBundleIdFromModuleId(module.getId());
- if (middleId < exportId)
- {
- top = middle + 1;
- }
- else
- {
- bottom = middle - 1;
- }
- }
- else
- {
- top = middle + 1;
- }
- }
-
- // Ignore duplicates.
- if ((top >= modules.length) || (modules[top] != module))
- {
- IModule[] newMods = new IModule[modules.length + 1];
- System.arraycopy(modules, 0, newMods, 0, top);
- System.arraycopy(modules, top, newMods, top + 1, modules.length - top);
- newMods[top] = module;
- modules = newMods;
- }
- }
-
- map.put(symName, modules);
- }
-
- private void populateCandidatesMap(Map candidatesMap, IModule module)
- throws ResolveException
- {
- // Detect cycles.
- if (candidatesMap.get(module) != null)
- {
- return;
- }
-
- // List to hold the resolving candidate sets for the module's
- // requirements.
- List candSetList = new ArrayList();
-
- // Even though the candidate set list is currently empty, we
- // record it in the candidates map early so we can use it to
- // detect cycles.
- candidatesMap.put(module, candSetList);
-
- // Loop through each requirement and calculate its resolving
- // set of candidates.
- IRequirement[] reqs = module.getDefinition().getRequirements();
- for (int reqIdx = 0; (reqs != null) && (reqIdx < reqs.length); reqIdx++)
- {
- // Get the candidates from the "resolved" and "unresolved"
- // package maps. The "resolved" candidates have higher priority
- // than "unresolved" ones, so put the "resolved" candidates
- // at the front of the list of candidates.
- PackageSource[] resolved = getResolvedCandidates(reqs[reqIdx]);
- PackageSource[] unresolved = getUnresolvedCandidates(reqs[reqIdx]);
- PackageSource[] candidates = new PackageSource[resolved.length + unresolved.length];
- System.arraycopy(resolved, 0, candidates, 0, resolved.length);
- System.arraycopy(unresolved, 0, candidates, resolved.length, unresolved.length);
-
- // If we have candidates, then we need to recursively populate
- // the resolver map with each of them.
- ResolveException rethrow = null;
- if (candidates.length > 0)
- {
- for (int candIdx = 0; candIdx < candidates.length; candIdx++)
- {
- try
- {
- // Only populate the resolver map with modules that
- // are not already resolved.
- if (!isResolved(candidates[candIdx].m_module))
- {
- populateCandidatesMap(candidatesMap, candidates[candIdx].m_module);
- }
- }
- catch (ResolveException ex)
- {
- // If we received a resolve exception, then the
- // current candidate is not resolvable for some
- // reason and should be removed from the list of
- // candidates. For now, just null it.
- candidates[candIdx] = null;
- rethrow = ex;
- }
- }
-
- // Remove any nulled candidates to create the final list
- // of available candidates.
- candidates = shrinkCandidateArray(candidates);
- }
-
- // If no candidates exist at this point, then throw a
- // resolve exception unless the import is optional.
- if ((candidates.length == 0) && !reqs[reqIdx].isOptional())
- {
- // If we have received an exception while trying to populate
- // the resolver map, rethrow that exception since it might
- // be useful. NOTE: This is not necessarily the "only"
- // correct exception, since it is possible that multiple
- // candidates were not resolvable, but it is better than
- // nothing.
- if (rethrow != null)
- {
- throw rethrow;
- }
- else
- {
- throw new ResolveException(
- "Unable to resolve.", module, reqs[reqIdx]);
- }
- }
- else if (candidates.length > 0)
- {
- candSetList.add(
- new CandidateSet(module, reqs[reqIdx], candidates));
- }
- }
- }
-
- private void dumpPackageIndexMap(Map pkgIndexMap)
- {
- synchronized (this)
- {
- for (Iterator i = pkgIndexMap.entrySet().iterator(); i.hasNext(); )
- {
- Map.Entry entry = (Map.Entry) i.next();
- IModule[] modules = (IModule[]) entry.getValue();
- if ((modules != null) && (modules.length > 0))
- {
- if (!((modules.length == 1) && modules[0].getId().equals("0")))
- {
- System.out.println(" " + entry.getKey());
- for (int j = 0; j < modules.length; j++)
- {
- System.out.println(" " + modules[j]);
- }
- }
- }
- }
- }
- }
-
- private void dumpPackageSources(Map pkgMap)
- {
- for (Iterator i = pkgMap.entrySet().iterator(); i.hasNext(); )
- {
- Map.Entry entry = (Map.Entry) i.next();
- ResolvedPackage rp = (ResolvedPackage) entry.getValue();
- System.out.println(rp);
- }
- }
-
- private void findConsistentClassSpace(Map candidatesMap, IModule rootModule)
- throws ResolveException
- {
- List candidatesList = null;
-
- // The reusable module map maps a module to a map of
- // resolved packages that are accessible by the given
- // module. The set of resolved packages is calculated
- // from the current candidates of the candidates map
- // and the module's metadata.
- Map moduleMap = new HashMap();
-
- // Reusable map used to test for cycles.
- Map cycleMap = new HashMap();
-
- // Test the current potential candidates to determine if they
- // are consistent. Keep looping until we find a consistent
- // set or an exception is thrown.
- while (!isSingletonConsistent(rootModule, moduleMap, candidatesMap) ||
- !isClassSpaceConsistent(rootModule, moduleMap, cycleMap, candidatesMap))
- {
- // The incrementCandidateConfiguration() method requires
- // ordered access to the candidates map, so we will create
- // a reusable list once right here.
- if (candidatesList == null)
- {
- candidatesList = new ArrayList();
- for (Iterator iter = candidatesMap.entrySet().iterator();
- iter.hasNext(); )
- {
- candidatesList.add(((Map.Entry) iter.next()).getValue());
- }
- }
-
- // Increment the candidate configuration so we can test again.
- incrementCandidateConfiguration(candidatesList);
-
- // Clear the module map.
- moduleMap.clear();
-
- // Clear the cycle map.
- cycleMap.clear();
- }
- }
-
- /**
- * This methd checks to see if the target module and any of the candidate
- * modules to resolve its dependencies violate any singleton constraints.
- * Actually, it just creates a map of resolved singleton modules and then
- * delegates all checking to another recursive method.
- *
- * @param targetModule the module that is the root of the tree of modules to check.
- * @param moduleMap a map to cache the package space of each module.
- * @param candidatesMap a map containing the all candidates to resolve all
- * dependencies for all modules.
- * @return <tt>true</tt> if all candidates are consistent with respect to singletons,
- * <tt>false</tt> otherwise.
- **/
- private boolean isSingletonConsistent(IModule targetModule, Map moduleMap, Map candidatesMap)
- {
- // Create a map of all resolved singleton modules.
- Map singletonMap = new HashMap();
- IModule[] modules = m_factory.getModules();
- for (int i = 0; (modules != null) && (i < modules.length); i++)
- {
- if (isResolved(modules[i]) && isSingleton(modules[i]))
- {
- String symName = getBundleSymbolicName(modules[i]);
- singletonMap.put(symName, symName);
- }
- }
-
- return areCandidatesSingletonConsistent(
- targetModule, singletonMap, moduleMap, new HashMap(), candidatesMap);
- }
-
- /**
- * This method recursive checks the target module and all of its transitive
- * dependency modules to verify that they do not violate a singleton constraint.
- * If the target module is a singleton, then it checks that againts existing
- * singletons. Then it checks all current unresolved candidates recursively.
- *
- * @param targetModule the module that is the root of the tree of modules to check.
- * @param singletonMap the current map of singleton symbolic names.
- * @param moduleMap a map to cache the package space of each module.
- * @param cycleMap a map to detect cycles.
- * @param candidatesMap a map containing the all candidates to resolve all
- * dependencies for all modules.
- * @return <tt>true</tt> if all candidates are consistent with respect to singletons,
- * <tt>false</tt> otherwise.
- **/
- private boolean areCandidatesSingletonConsistent(
- IModule targetModule, Map singletonMap, Map moduleMap, Map cycleMap, Map candidatesMap)
- {
- // If we are in a cycle, then assume true for now.
- if (cycleMap.get(targetModule) != null)
- {
- return true;
- }
-
- // Record the target module in the cycle map.
- cycleMap.put(targetModule, targetModule);
-
- // Check to see if the targetModule violates a singleton.
- // If not and it is a singleton, then add it to the singleton
- // map since it will constrain other singletons.
- String symName = getBundleSymbolicName(targetModule);
- boolean isSingleton = isSingleton(targetModule);
- if (isSingleton && singletonMap.containsKey(symName))
- {
- return false;
- }
- else if (isSingleton)
- {
- singletonMap.put(symName, symName);
- }
-
- // Get the package space of the target module.
- Map pkgMap = null;
- try
- {
- pkgMap = getModulePackages(moduleMap, targetModule, candidatesMap);
- }
- catch (ResolveException ex)
- {
- m_logger.log(
- Logger.LOG_DEBUG,
- "Constraint violation for " + targetModule + " detected.",
- ex);
- return false;
- }
-
- // Loop through all of the target module's accessible packages and
- // verify that all package sources are consistent.
- for (Iterator iter = pkgMap.entrySet().iterator(); iter.hasNext(); )
- {
- Map.Entry entry = (Map.Entry) iter.next();
- // Get the resolved package, which contains the set of all
- // package sources for the given package.
- ResolvedPackage rp = (ResolvedPackage) entry.getValue();
- // Loop through each package source and test if it is consistent.
- for (int srcIdx = 0; srcIdx < rp.m_sourceList.size(); srcIdx++)
- {
- // If the module for this package source is not resolved, then
- // we have to see if resolving it would violate a singleton
- // constraint.
- PackageSource ps = (PackageSource) rp.m_sourceList.get(srcIdx);
- if (!isResolved(ps.m_module))
- {
- return areCandidatesSingletonConsistent(ps.m_module, singletonMap, moduleMap, cycleMap, candidatesMap);
- }
- }
- }
-
- return true;
- }
-
- /**
- * Returns true if the specified module is a singleton
- * (i.e., directive singleton:=true in Bundle-SymbolicName).
- *
- * @param module the module to check for singleton status.
- * @return true if the module is a singleton, false otherwise.
- **/
- private boolean isSingleton(IModule module)
- {
- final ICapability[] modCaps = Util.getCapabilityByNamespace(
- module, Capability.MODULE_NAMESPACE);
- if (modCaps == null || modCaps.length == 0)
- {
- // this should never happen?
- return false;
- }
- final R4Directive[] dirs = ((Capability) modCaps[0]).getDirectives();
- for (int dirIdx = 0; (dirs != null) && (dirIdx < dirs.length); dirIdx++)
- {
- if (dirs[dirIdx].getName().equalsIgnoreCase(Constants.SINGLETON_DIRECTIVE)
- && Boolean.valueOf(dirs[dirIdx].getValue()).booleanValue())
- {
- return true;
- }
- }
- return false;
- }
-
- private boolean isClassSpaceConsistent(
- IModule targetModule, Map moduleMap, Map cycleMap, Map candidatesMap)
- {
-//System.out.println("isClassSpaceConsistent("+targetModule+")");
- // If we are in a cycle, then assume true for now.
- if (cycleMap.get(targetModule) != null)
- {
- return true;
- }
-
- // Record the target module in the cycle map.
- cycleMap.put(targetModule, targetModule);
-
- // Get the package map for the target module, which is a
- // map of all packages accessible to the module and their
- // associated package sources.
- Map pkgMap = null;
- try
- {
- pkgMap = getModulePackages(moduleMap, targetModule, candidatesMap);
- }
- catch (ResolveException ex)
- {
- m_logger.log(
- Logger.LOG_DEBUG,
- "Constraint violation for " + targetModule + " detected.",
- ex);
- return false;
- }
-
- // Loop through all of the target module's accessible packages and
- // verify that all package sources are consistent.
- for (Iterator iter = pkgMap.entrySet().iterator(); iter.hasNext(); )
- {
- Map.Entry entry = (Map.Entry) iter.next();
- // Get the resolved package, which contains the set of all
- // package sources for the given package.
- ResolvedPackage rp = (ResolvedPackage) entry.getValue();
- // Loop through each package source and test if it is consistent.
- for (int srcIdx = 0; srcIdx < rp.m_sourceList.size(); srcIdx++)
- {
- PackageSource ps = (PackageSource) rp.m_sourceList.get(srcIdx);
- if (!isClassSpaceConsistent(ps.m_module, moduleMap, cycleMap, candidatesMap))
- {
- return false;
- }
- }
- }
-
- // Now we need to calculate the "uses" constraints of every package
- // accessible to the target module based on the current candidates.
- Map usesMap = null;
- try
- {
- usesMap = calculateUsesConstraints(targetModule, moduleMap, candidatesMap);
- }
- catch (ResolveException ex)
- {
- m_logger.log(
- Logger.LOG_DEBUG,
- "Constraint violation for " + targetModule + " detected.",
- ex);
- return false;
- }
-
- // Verify that none of the implied "uses" constraints in the uses map
- // conflict with anything in the target module's package map.
- for (Iterator iter = usesMap.entrySet().iterator(); iter.hasNext(); )
- {
- Map.Entry entry = (Map.Entry) iter.next();
-
- // For the given "used" package, get that package from the
- // target module's package map, if present.
- ResolvedPackage rp = (ResolvedPackage) pkgMap.get(entry.getKey());
-
- // If the "used" package is also visible to the target module,
- // make sure there is no conflicts in the implied "uses"
- // constraints.
- if (rp != null)
- {
- // Clone the resolve package so we can modify it.
- rp = (ResolvedPackage) rp.clone();
-
- // Loop through all implied "uses" constraints for the current
- // "used" package and verify that all package sources are
- // compatible with the package source of the root module's
- // package map.
- List constraintList = (List) entry.getValue();
- for (int constIdx = 0; constIdx < constraintList.size(); constIdx++)
- {
- // Get a specific "uses" constraint for the current "used"
- // package.
- ResolvedPackage rpUses = (ResolvedPackage) constraintList.get(constIdx);
- // Determine if the implied "uses" constraint is compatible with
- // the target module's package sources for the given "used"
- // package. They are compatible if one is the subset of the other.
- // Retain the union of the two sets if they are compatible.
- if (rpUses.isSubset(rp))
- {
- // Do nothing because we already have the superset.
- }
- else if (rp.isSubset(rpUses))
- {
- // Keep the superset, i.e., the union.
- rp.m_sourceList.clear();
- rp.m_sourceList.addAll(rpUses.m_sourceList);
- }
- else
- {
- m_logger.log(
- Logger.LOG_DEBUG,
- "Constraint violation for " + targetModule
- + " detected; module can see "
- + rp + " and " + rpUses);
- return false;
- }
- }
- }
- }
-
- return true;
- }
-
- private Map calculateUsesConstraints(
- IModule targetModule, Map moduleMap, Map candidatesMap)
- throws ResolveException
- {
-//System.out.println("calculateUsesConstraints("+targetModule+")");
- // Map to store calculated uses constraints. This maps a
- // package name to a list of resolved packages, where each
- // resolved package represents a constraint on anyone
- // importing the given package name. This map is returned
- // by this method.
- Map usesMap = new HashMap();
-
- // Re-usable map to detect cycles.
- Map cycleMap = new HashMap();
-
- // Get all packages accessible by the target module.
- Map pkgMap = getModulePackages(moduleMap, targetModule, candidatesMap);
-
- // Each package accessible from the target module is potentially
- // comprised of one or more modules, called package sources. The
- // "uses" constraints implied by all package sources must be
- // calculated and combined to determine the complete set of implied
- // "uses" constraints for each package accessible by the target module.
- for (Iterator iter = pkgMap.entrySet().iterator(); iter.hasNext(); )
- {
- Map.Entry entry = (Map.Entry) iter.next();
- ResolvedPackage rp = (ResolvedPackage) entry.getValue();
- for (int srcIdx = 0; srcIdx < rp.m_sourceList.size(); srcIdx++)
- {
- usesMap = calculateUsesConstraints(
- (PackageSource) rp.m_sourceList.get(srcIdx),
- moduleMap, usesMap, cycleMap, candidatesMap);
- }
- }
- return usesMap;
- }
-
- private Map calculateUsesConstraints(
- PackageSource psTarget, Map moduleMap, Map usesMap,
- Map cycleMap, Map candidatesMap)
- throws ResolveException
- {
-//System.out.println("calculateUsesConstraints2("+psTarget.m_module+")");
- // If we are in a cycle, then return for now.
- if (cycleMap.get(psTarget) != null)
- {
- return usesMap;
- }
-
- // Record the target package source in the cycle map.
- cycleMap.put(psTarget, psTarget);
-
- // Get all packages accessible from the module of the
- // target package source.
- Map pkgMap = getModulePackages(moduleMap, psTarget.m_module, candidatesMap);
-
- // Get capability (i.e., package) of the target package source.
- Capability cap = (Capability) psTarget.m_capability;
-
- // Loop through all "used" packages of the capability.
- for (int i = 0; i < cap.getUses().length; i++)
- {
- // The target package source module should have a resolved package
- // for the "used" package in its set of accessible packages,
- // since it claims to use it, so get the associated resolved
- // package.
- ResolvedPackage rp = (ResolvedPackage) pkgMap.get(cap.getUses()[i]);
-
- // In general, the resolved package should not be null,
- // but check for safety.
- if (rp != null)
- {
- // First, iterate through all package sources for the resolved
- // package associated with the current "used" package and calculate
- // and combine the "uses" constraints for each package source.
- for (int srcIdx = 0; srcIdx < rp.m_sourceList.size(); srcIdx++)
- {
- usesMap = calculateUsesConstraints(
- (PackageSource) rp.m_sourceList.get(srcIdx),
- moduleMap, usesMap, cycleMap, candidatesMap);
- }
-
- // Then, add the resolved package for the current "used" package
- // as a "uses" constraint too; add it to an existing constraint
- // list if the current "used" package is already in the uses map.
- List constraintList = (List) usesMap.get(cap.getUses()[i]);
- if (constraintList == null)
- {
- constraintList = new ArrayList();
- }
- constraintList.add(rp);
- usesMap.put(cap.getUses()[i], constraintList);
- }
- }
-
- return usesMap;
- }
-
- private Map getModulePackages(Map moduleMap, IModule module, Map candidatesMap)
- throws ResolveException
- {
- Map map = (Map) moduleMap.get(module);
-
- if (map == null)
- {
- map = calculateModulePackages(module, candidatesMap);
- moduleMap.put(module, map);
- }
- return map;
- }
-
- /**
- * <p>
- * Calculates the module's set of accessible packages and their
- * assocaited package sources. This method uses the current candidates
- * for resolving the module's requirements from the candidate map
- * to calculate the module's accessible packages.
- * </p>
- * @param module the module whose package map is to be calculated.
- * @param candidatesMap the map of potential candidates for resolving
- * the module's requirements.
- * @return a map of the packages accessible to the specified module where
- * the key of the map is the package name and the value of the map
- * is a ResolvedPackage.
- **/
- private Map calculateModulePackages(IModule module, Map candidatesMap)
- throws ResolveException
- {
-//System.out.println("calculateModulePackages("+module+")");
- Map importedPackages = calculateImportedPackages(module, candidatesMap);
- Map exportedPackages = calculateExportedPackages(module);
- Map requiredPackages = calculateRequiredPackages(module, candidatesMap);
-
- // Merge exported packages into required packages. If a package is both
- // exported and required, then append the exported source to the end of
- // the require package sources; otherwise just add it to the package map.
- for (Iterator i = exportedPackages.entrySet().iterator(); i.hasNext(); )
- {
- Map.Entry entry = (Map.Entry) i.next();
- ResolvedPackage rpReq = (ResolvedPackage) requiredPackages.get(entry.getKey());
- if (rpReq != null)
- {
- // Merge exported and required packages, avoiding duplicate
- // package sources and maintaining ordering.
- ResolvedPackage rpExport = (ResolvedPackage) entry.getValue();
- rpReq.merge(rpExport);
- }
- else
- {
- requiredPackages.put(entry.getKey(), entry.getValue());
- }
- }
-
- // Merge imported packages into required packages. Imports overwrite
- // any required and/or exported package.
- for (Iterator i = importedPackages.entrySet().iterator(); i.hasNext(); )
- {
- Map.Entry entry = (Map.Entry) i.next();
- requiredPackages.put(entry.getKey(), entry.getValue());
- }
-
- return requiredPackages;
- }
-
- private Map calculateImportedPackages(IModule targetModule, Map candidatesMap)
- throws ResolveException
- {
- return (candidatesMap.get(targetModule) == null)
- ? calculateImportedPackagesResolved(targetModule)
- : calculateImportedPackagesUnresolved(targetModule, candidatesMap);
- }
-
- private Map calculateImportedPackagesUnresolved(IModule targetModule, Map candidatesMap)
- throws ResolveException
- {
-//System.out.println("calculateImportedPackagesUnresolved("+targetModule+")");
- Map pkgMap = new HashMap();
-
- // Get the candidate set list to get all candidates for
- // all of the target module's requirements.
- List candSetList = (List) candidatesMap.get(targetModule);
-
- // Loop through all candidate sets that represent import dependencies
- // for the target module and add the current candidate's package source
- // to the imported package map.
- for (int candSetIdx = 0; (candSetList != null) && (candSetIdx < candSetList.size()); candSetIdx++)
- {
- CandidateSet cs = (CandidateSet) candSetList.get(candSetIdx);
- PackageSource ps = cs.m_candidates[cs.m_idx];
-
- if (ps.m_capability.getNamespace().equals(ICapability.PACKAGE_NAMESPACE))
- {
- String pkgName = (String)
- ps.m_capability.getProperties().get(ICapability.PACKAGE_PROPERTY);
-
- ResolvedPackage rp = new ResolvedPackage(pkgName);
- rp.m_sourceList.add(ps);
- pkgMap.put(rp.m_name, rp);
- }
- }
-
- return pkgMap;
- }
-
- private Map calculateImportedPackagesResolved(IModule targetModule)
- throws ResolveException
- {
-//System.out.println("calculateImportedPackagesResolved("+targetModule+")");
- Map pkgMap = new HashMap();
-
- // Loop through the target module's wires for package
- // dependencies and add the resolved package source to the
- // imported package map.
- IWire[] wires = targetModule.getWires();
- for (int wireIdx = 0; (wires != null) && (wireIdx < wires.length); wireIdx++)
- {
- if (wires[wireIdx].getCapability().getNamespace().equals(ICapability.PACKAGE_NAMESPACE))
- {
- String pkgName = (String)
- wires[wireIdx].getCapability().getProperties().get(ICapability.PACKAGE_PROPERTY);
- ResolvedPackage rp = (ResolvedPackage) pkgMap.get(pkgName);
- rp = (rp == null) ? new ResolvedPackage(pkgName) : rp;
- rp.m_sourceList.add(new PackageSource(wires[wireIdx].getExporter(), wires[wireIdx].getCapability()));
- pkgMap.put(rp.m_name, rp);
- }
- }
-
- return pkgMap;
- }
-
- private Map calculateExportedPackages(IModule targetModule)
- {
-//System.out.println("calculateExportedPackages("+targetModule+")");
- Map pkgMap = new HashMap();
-
- // Loop through the target module's capabilities that represent
- // exported packages and add them to the exported package map.
- ICapability[] caps = targetModule.getDefinition().getCapabilities();
- for (int capIdx = 0; (caps != null) && (capIdx < caps.length); capIdx++)
- {
- if (caps[capIdx].getNamespace().equals(ICapability.PACKAGE_NAMESPACE))
- {
- String pkgName = (String)
- caps[capIdx].getProperties().get(ICapability.PACKAGE_PROPERTY);
- ResolvedPackage rp = (ResolvedPackage) pkgMap.get(pkgName);
- rp = (rp == null) ? new ResolvedPackage(pkgName) : rp;
- rp.m_sourceList.add(new PackageSource(targetModule, caps[capIdx]));
- pkgMap.put(rp.m_name, rp);
- }
- }
-
- return pkgMap;
- }
-
- private Map calculateRequiredPackages(IModule targetModule, Map candidatesMap)
- {
- return (candidatesMap.get(targetModule) == null)
- ? calculateRequiredPackagesResolved(targetModule)
- : calculateRequiredPackagesUnresolved(targetModule, candidatesMap);
- }
-
- private Map calculateRequiredPackagesUnresolved(IModule targetModule, Map candidatesMap)
- {
-//System.out.println("calculateRequiredPackagesUnresolved("+targetModule+")");
- Map pkgMap = new HashMap();
-
- // Loop through target module's candidate list for candidates
- // for its module dependencies and merge re-exported packages.
- List candSetList = (List) candidatesMap.get(targetModule);
- for (int candSetIdx = 0; (candSetList != null) && (candSetIdx < candSetList.size()); candSetIdx++)
- {
- CandidateSet cs = (CandidateSet) candSetList.get(candSetIdx);
- PackageSource ps = cs.m_candidates[cs.m_idx];
-
- // If the capabaility is a module dependency, then flatten it to packages.
- if (ps.m_capability.getNamespace().equals(ICapability.MODULE_NAMESPACE))
- {
- // Calculate transitively required packages.
- Map cycleMap = new HashMap();
- cycleMap.put(targetModule, targetModule);
- Map requireMap =
- calculateExportedAndReexportedPackages(
- ps, candidatesMap, cycleMap);
-
- // Take the flattened required package map for the current
- // module dependency and merge it into the existing map
- // of required packages.
- for (Iterator reqIter = requireMap.entrySet().iterator(); reqIter.hasNext(); )
- {
- Map.Entry entry = (Map.Entry) reqIter.next();
- ResolvedPackage rp = (ResolvedPackage) pkgMap.get(entry.getKey());
- if (rp != null)
- {
- // Merge required packages, avoiding duplicate
- // package sources and maintaining ordering.
- ResolvedPackage rpReq = (ResolvedPackage) entry.getValue();
- rp.merge(rpReq);
- }
- else
- {
- pkgMap.put(entry.getKey(), entry.getValue());
- }
- }
- }
- }
-
- return pkgMap;
- }
-
- private Map calculateRequiredPackagesResolved(IModule targetModule)
- {
-//System.out.println("calculateRequiredPackagesResolved("+targetModule+")");
- Map pkgMap = new HashMap();
-
- // Loop through target module's wires for module dependencies
- // and merge re-exported packages.
- IWire[] wires = targetModule.getWires();
- for (int i = 0; (wires != null) && (i < wires.length); i++)
- {
- // If the wire is a module dependency, then flatten it to packages.
- if (wires[i].getCapability().getNamespace().equals(ICapability.MODULE_NAMESPACE))
- {
- // Calculate transitively required packages.
- // We can call calculateExportedAndReexportedPackagesResolved()
- // directly, since we know all dependencies have to be resolved
- // because this module itself is resolved.
- Map cycleMap = new HashMap();
- cycleMap.put(targetModule, targetModule);
- Map requireMap =
- calculateExportedAndReexportedPackagesResolved(
- wires[i].getExporter(), cycleMap);
-
- // Take the flattened required package map for the current
- // module dependency and merge it into the existing map
- // of required packages.
- for (Iterator reqIter = requireMap.entrySet().iterator(); reqIter.hasNext(); )
- {
- Map.Entry entry = (Map.Entry) reqIter.next();
- ResolvedPackage rp = (ResolvedPackage) pkgMap.get(entry.getKey());
- if (rp != null)
- {
- // Merge required packages, avoiding duplicate
- // package sources and maintaining ordering.
- ResolvedPackage rpReq = (ResolvedPackage) entry.getValue();
- rp.merge(rpReq);
- }
- else
- {
- pkgMap.put(entry.getKey(), entry.getValue());
- }
- }
- }
- }
-
- return pkgMap;
- }
-
- private Map calculateExportedAndReexportedPackages(
- PackageSource psTarget, Map candidatesMap, Map cycleMap)
- {
- return (candidatesMap.get(psTarget.m_module) == null)
- ? calculateExportedAndReexportedPackagesResolved(psTarget.m_module, cycleMap)
- : calculateExportedAndReexportedPackagesUnresolved(psTarget, candidatesMap, cycleMap);
- }
-
- private Map calculateExportedAndReexportedPackagesUnresolved(
- PackageSource psTarget, Map candidatesMap, Map cycleMap)
- {
-//System.out.println("calculateExportedAndReexportedPackagesUnresolved("+psTarget.m_module+")");
- Map pkgMap = new HashMap();
-
- if (cycleMap.get(psTarget.m_module) != null)
- {
- return pkgMap;
- }
-
- cycleMap.put(psTarget.m_module, psTarget.m_module);
-
- // Loop through all current candidates for target module's dependencies
- // and calculate the module's complete set of required packages (and
- // their associated package sources) and the complete set of required
- // packages to be re-exported.
- Map allRequiredMap = new HashMap();
- Map reexportedPkgMap = new HashMap();
- List candSetList = (List) candidatesMap.get(psTarget.m_module);
- for (int candSetIdx = 0; candSetIdx < candSetList.size(); candSetIdx++)
- {
- CandidateSet cs = (CandidateSet) candSetList.get(candSetIdx);
- PackageSource ps = cs.m_candidates[cs.m_idx];
-
- // If the candidate is resolving a module dependency, then
- // flatten the required packages if they are re-exported.
- if (ps.m_capability.getNamespace().equals(ICapability.MODULE_NAMESPACE))
- {
- // Determine if required packages are re-exported.
- boolean reexport = false;
- R4Directive[] dirs = ((Requirement) cs.m_requirement).getDirectives();
- for (int dirIdx = 0;
- !reexport && (dirs != null) && (dirIdx < dirs.length); dirIdx++)
- {
- if (dirs[dirIdx].getName().equals(Constants.VISIBILITY_DIRECTIVE)
- && dirs[dirIdx].getValue().equals(Constants.VISIBILITY_REEXPORT))
- {
- reexport = true;
- }
- }
-
- // Recursively calculate the required packages for the
- // current candidate.
- Map requiredMap = calculateExportedAndReexportedPackages(ps, candidatesMap, cycleMap);
-
- // Merge the candidate's exported and required packages
- // into the complete set of required packages.
- for (Iterator reqIter = requiredMap.entrySet().iterator(); reqIter.hasNext(); )
- {
- Map.Entry entry = (Map.Entry) reqIter.next();
- String pkgName = (String) entry.getKey();
-
- // Merge the current set of required packages into
- // the overall complete set of required packages.
- // We calculate all the required packages, because
- // despite the fact that some packages will be required
- // "privately" and some will be required "reexport", any
- // re-exported package sources will ultimately need to
- // be combined with privately required package sources,
- // if the required packages overlap. This is one of the
- // bad things about require-bundle behavior, it does not
- // necessarily obey the visibility rules declared in the
- // dependency.
- ResolvedPackage rp = (ResolvedPackage) allRequiredMap.get(pkgName);
- if (rp != null)
- {
- // Create the union of all package sources.
- ResolvedPackage rpReq = (ResolvedPackage) entry.getValue();
- rp.merge(rpReq);
- }
- else
- {
- // Add package to required map.
- allRequiredMap.put(pkgName, entry.getValue());
- }
-
- // Keep track of all required packages to be re-exported.
- // All re-exported packages will need to be merged into the
- // target module's package map and become part of its overall
- // export signature.
- if (reexport)
- {
- reexportedPkgMap.put(pkgName, pkgName);
- }
- }
- }
- }
-
- // For the target module we have now calculated its entire set
- // of required packages and their associated package sources in
- // allRequiredMap and have calculated all packages to be re-exported
- // in reexportedPkgMap. Add all re-exported required packages to the
- // target module's package map since they will be part of its export
- // signature.
- for (Iterator iter = reexportedPkgMap.entrySet().iterator(); iter.hasNext(); )
- {
- String pkgName = (String) ((Map.Entry) iter.next()).getKey();
- pkgMap.put(pkgName, allRequiredMap.get(pkgName));
- }
-
- // Now loop through the target module's export package capabilities and
- // add the target module as a package source for any exported packages.
- ICapability[] candCaps = psTarget.m_module.getDefinition().getCapabilities();
- for (int capIdx = 0; (candCaps != null) && (capIdx < candCaps.length); capIdx++)
- {
- if (candCaps[capIdx].getNamespace().equals(ICapability.PACKAGE_NAMESPACE))
- {
- String pkgName = (String)
- candCaps[capIdx].getProperties().get(ICapability.PACKAGE_PROPERTY);
- ResolvedPackage rp = (ResolvedPackage) pkgMap.get(pkgName);
- rp = (rp == null) ? new ResolvedPackage(pkgName) : rp;
- rp.m_sourceList.add(new PackageSource(psTarget.m_module, candCaps[capIdx]));
- pkgMap.put(rp.m_name, rp);
- }
- }
-
- return pkgMap;
- }
-
- private Map calculateExportedAndReexportedPackagesResolved(
- IModule targetModule, Map cycleMap)
- {
-//System.out.println("calculateExportedAndRequiredPackagesResolved("+targetModule+")");
- Map pkgMap = new HashMap();
-
- if (cycleMap.get(targetModule) != null)
- {
- return pkgMap;
- }
-
- cycleMap.put(targetModule, targetModule);
-
- // Loop through all wires for the target module's module dependencies
- // and calculate the module's complete set of required packages (and
- // their associated package sources) and the complete set of required
- // packages to be re-exported.
- Map allRequiredMap = new HashMap();
- Map reexportedPkgMap = new HashMap();
- IWire[] wires = targetModule.getWires();
- for (int i = 0; (wires != null) && (i < wires.length); i++)
- {
- // If the wire is a module dependency, then flatten it to packages.
- if (wires[i].getCapability().getNamespace().equals(ICapability.MODULE_NAMESPACE))
- {
- // Determine if required packages are re-exported.
- boolean reexport = false;
- R4Directive[] dirs = ((Requirement) wires[i].getRequirement()).getDirectives();
- for (int dirIdx = 0;
- !reexport && (dirs != null) && (dirIdx < dirs.length); dirIdx++)
- {
- if (dirs[dirIdx].getName().equals(Constants.VISIBILITY_DIRECTIVE)
- && dirs[dirIdx].getValue().equals(Constants.VISIBILITY_REEXPORT))
- {
- reexport = true;
- }
- }
-
- // Recursively calculate the required packages for the
- // wire's exporting module.
- Map requiredMap = calculateExportedAndReexportedPackagesResolved(wires[i].getExporter(), cycleMap);
-
- // Merge the wires exported and re-exported packages
- // into the complete set of required packages.
- for (Iterator reqIter = requiredMap.entrySet().iterator(); reqIter.hasNext(); )
- {
- Map.Entry entry = (Map.Entry) reqIter.next();
- String pkgName = (String) entry.getKey();
-
- // Merge the current set of required packages into
- // the overall complete set of required packages.
- // We calculate all the required packages, because
- // despite the fact that some packages will be required
- // "privately" and some will be required "reexport", any
- // re-exported package sources will ultimately need to
- // be combined with privately required package sources,
- // if the required packages overlap. This is one of the
- // bad things about require-bundle behavior, it does not
- // necessarily obey the visibility rules declared in the
- // dependency.
- ResolvedPackage rp = (ResolvedPackage) allRequiredMap.get(pkgName);
- if (rp != null)
- {
- // Create the union of all package sources.
- ResolvedPackage rpReq = (ResolvedPackage) entry.getValue();
- rp.merge(rpReq);
- }
- else
- {
- // Add package to required map.
- allRequiredMap.put(pkgName, entry.getValue());
- }
-
- // Keep track of all required packages to be re-exported.
- // All re-exported packages will need to be merged into the
- // target module's package map and become part of its overall
- // export signature.
- if (reexport)
- {
- reexportedPkgMap.put(pkgName, pkgName);
- }
- }
- }
- }
-
- // For the target module we have now calculated its entire set
- // of required packages and their associated package sources in
- // allRequiredMap and have calculated all packages to be re-exported
- // in reexportedPkgMap. Add all re-exported required packages to the
- // target module's package map since they will be part of its export
- // signature.
- for (Iterator iter = reexportedPkgMap.entrySet().iterator(); iter.hasNext(); )
- {
- String pkgName = (String) ((Map.Entry) iter.next()).getKey();
- pkgMap.put(pkgName, allRequiredMap.get(pkgName));
- }
-
- // Now loop through the target module's export package capabilities and
- // add the target module as a package source for any exported packages.
- ICapability[] caps = targetModule.getDefinition().getCapabilities();
- for (int i = 0; (caps != null) && (i < caps.length); i++)
- {
- if (caps[i].getNamespace().equals(ICapability.PACKAGE_NAMESPACE))
- {
- String pkgName = (String)
- caps[i].getProperties().get(ICapability.PACKAGE_PROPERTY);
- ResolvedPackage rp = (ResolvedPackage) pkgMap.get(pkgName);
- rp = (rp == null) ? new ResolvedPackage(pkgName) : rp;
- rp.m_sourceList.add(new PackageSource(targetModule, caps[i]));
- pkgMap.put(rp.m_name, rp);
- }
- }
-
- return pkgMap;
- }
-
[... 1019 lines stripped ...]