package org.eclipse.osgi.internal.loader.buddy;
import java.io.IOException;
import java.net.URL;
import java.util.*;
import org.eclipse.osgi.container.ModuleWire;
import org.eclipse.osgi.container.ModuleWiring;
import org.eclipse.osgi.internal.loader.BundleLoader;
import org.osgi.framework.namespace.BundleNamespace;
import org.osgi.framework.namespace.PackageNamespace;
public class DependentPolicy implements IBuddyPolicy {
BundleLoader buddyRequester;
int lastDependentOfAdded = -1;
List<ModuleWiring> allDependents = null;
public DependentPolicy(BundleLoader requester) {
buddyRequester = requester;
allDependents = new ArrayList<>();
basicAddImmediateDependents(requester.getWiring());
if (allDependents.size() == 0)
allDependents = null;
}
@Override
public Class<?> loadClass(String name) {
if (allDependents == null)
return null;
Class<?> result = null;
for (int i = 0; i < allDependents.size() && result == null; i++) {
ModuleWiring searchWiring = allDependents.get(i);
BundleLoader searchLoader = (BundleLoader) searchWiring.getModuleLoader();
if (searchLoader != null) {
try {
result = searchLoader.findClass(name);
} catch (ClassNotFoundException e) {
if (result == null)
addDependent(i, searchWiring);
}
}
}
return result;
}
private synchronized void addDependent(int i, ModuleWiring searchedWiring) {
if (i > lastDependentOfAdded) {
lastDependentOfAdded = i;
basicAddImmediateDependents(searchedWiring);
}
}
@Override
public URL loadResource(String name) {
if (allDependents == null)
return null;
URL result = null;
for (int i = 0; i < allDependents.size() && result == null; i++) {
ModuleWiring searchWiring = allDependents.get(i);
BundleLoader searchLoader = (BundleLoader) searchWiring.getModuleLoader();
if (searchLoader != null) {
result = searchLoader.findResource(name);
if (result == null) {
addDependent(i, searchWiring);
}
}
}
return result;
}
@Override
public Enumeration<URL> loadResources(String name) {
if (allDependents == null)
return null;
Enumeration<URL> results = null;
for (int i = 0; i < allDependents.size(); i++) {
ModuleWiring searchWiring = allDependents.get(i);
BundleLoader searchLoader = (BundleLoader) searchWiring.getModuleLoader();
if (searchLoader != null) {
try {
results = BundleLoader.compoundEnumerations(results, searchLoader.findResources(name));
addDependent(i, searchWiring);
} catch (IOException e) {
}
}
}
return results;
}
private void basicAddImmediateDependents(ModuleWiring wiring) {
List<ModuleWire> providedWires = wiring.getProvidedModuleWires(null);
if (providedWires != null) {
for (ModuleWire wire : providedWires) {
String namespace = wire.getRequirement().getNamespace();
if (PackageNamespace.PACKAGE_NAMESPACE.equals(namespace) || BundleNamespace.BUNDLE_NAMESPACE.equals(namespace)) {
ModuleWiring dependent = wire.getRequirerWiring();
if (!allDependents.contains(dependent)) {
allDependents.add(dependent);
}
}
}
}
}
}