index
int64
0
0
repo_id
stringlengths
9
205
file_path
stringlengths
31
246
content
stringlengths
1
12.2M
__index_level_0__
int64
0
10k
0
Create_ds/aries/subsystem/subsystem-scope-itests/src/test/java/org/apache/aries/subsystem/scope
Create_ds/aries/subsystem/subsystem-scope-itests/src/test/java/org/apache/aries/subsystem/scope/itests/ScopeProvider.java
package org.apache.aries.subsystem.scope.itests; import org.apache.aries.subsystem.scope.Scope; public interface ScopeProvider { Scope getScope(); }
8,500
0
Create_ds/aries/subsystem/subsystem-scope-itests/src/test/java/org/apache/aries/subsystem/scope
Create_ds/aries/subsystem/subsystem-scope-itests/src/test/java/org/apache/aries/subsystem/scope/itests/UninstallBundleTest.java
package org.apache.aries.subsystem.scope.itests; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.util.Arrays; import org.apache.aries.subsystem.scope.ScopeUpdate; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.osgi.framework.Bundle; /** * Tests whether or not a bundle can be successfully uninstalled from a scope. * The root scope is used for this test. */ public class UninstallBundleTest extends AbstractTest { private Bundle bundle; private String location; @Test public void test() throws Exception { ScopeUpdate scopeUpdate = getScope().newScopeUpdate(); assertTrue("The bundle should have been removed", scopeUpdate.getBundles().remove(bundle)); assertTrue("The commit should have been successful", scopeUpdate.commit()); assertFalse(scopeUpdate.getScope().getBundles().contains(bundle)); assertFalse("The bundle should have been removed from the scope", getScope().getBundles().contains(bundle)); assertFalse(Arrays.asList(bundleContext.getBundles()).contains(bundle)); assertNull("The bundle should have been uninstalled", bundleContext.getBundle(location)); } @Before public void before0() throws Exception { location = getBundleLocation("tb-2.jar"); bundle = bundleContext.getBundle(location); assertNull("The bundle should not exist", bundle); installBundles(getScope(), new String[]{"tb-2.jar"}); bundle = bundleContext.getBundle(location); assertNotNull("The bundle should exist", bundle); assertTrue("The bundle should part of the scope", getScope().getBundles().contains(bundle)); } @After public void after0() throws Exception { uninstallQuietly(bundle); } }
8,501
0
Create_ds/aries/subsystem/subsystem-scope-itests/src/test/bundles/tb3/org/apache/aries/subsystem/scope/itests
Create_ds/aries/subsystem/subsystem-scope-itests/src/test/bundles/tb3/org/apache/aries/subsystem/scope/itests/tb3/Activator.java
package org.apache.aries.subsystem.scope.itests.tb3; import org.apache.aries.subsystem.scope.Scope; import org.apache.aries.subsystem.scope.itests.ScopeProvider; import org.apache.aries.subsystem.scope.itests.Utils; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceReference; import org.osgi.framework.ServiceRegistration; public class Activator implements BundleActivator { private ServiceRegistration<ScopeProvider> scopeProviderReg; private ServiceReference<Scope> scopeRef; public void start(BundleContext bundleContext) throws Exception { scopeRef = bundleContext.getServiceReference(Scope.class); final Scope scope = bundleContext.getService(scopeRef); scopeProviderReg = bundleContext.registerService( ScopeProvider.class, new ScopeProvider() { public Scope getScope() { return scope; } }, null); } public void stop(BundleContext bundleContext) throws Exception { Utils.unregisterQuietly(scopeProviderReg); Utils.ungetQuietly(scopeRef, bundleContext); } }
8,502
0
Create_ds/aries/subsystem/subsystem-scope-itests/src/test/bundles/tb4/org/apache/aries/subsystem/scope/itests
Create_ds/aries/subsystem/subsystem-scope-itests/src/test/bundles/tb4/org/apache/aries/subsystem/scope/itests/tb4/Activator.java
package org.apache.aries.subsystem.scope.itests.tb4; import java.util.Arrays; import java.util.Collection; import org.apache.aries.subsystem.scope.itests.BundleProvider; import org.apache.aries.subsystem.scope.itests.Utils; import org.osgi.framework.Bundle; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceRegistration; public class Activator implements BundleActivator { public void start(final BundleContext bundleContext) throws Exception { bundleContext.registerService( BundleProvider.class, new BundleProvider() { public Bundle getBundle(long id) { return bundleContext.getBundle(id); } public Collection<Bundle> getBundles() { return Arrays.asList(bundleContext.getBundles()); } }, null); } public void stop(BundleContext bundleContext) throws Exception { } }
8,503
0
Create_ds/aries/subsystem/subsystem-scope-itests/src/test/bundles/tb1/org/apache/aries/subsystem/scope/itests
Create_ds/aries/subsystem/subsystem-scope-itests/src/test/bundles/tb1/org/apache/aries/subsystem/scope/itests/tb1/Activator.java
package org.apache.aries.subsystem.scope.itests.tb1; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import org.apache.aries.subsystem.scope.Scope; import org.apache.aries.subsystem.scope.SharePolicy; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceReference; public class Activator implements BundleActivator { public void start(BundleContext bundleContext) throws Exception { ServiceReference<Scope> scopeRef = bundleContext.getServiceReference(Scope.class); assertNotNull(scopeRef); Scope scope = bundleContext.getService(scopeRef); assertNotNull(scope); assertEquals(bundleContext.getBundles().length, scope.getBundles().size()); assertEquals(0, scope.getChildren().size()); assertEquals(0, scope.getId()); assertNull(scope.getLocation()); assertEquals("root", scope.getName()); assertNull(scope.getParent()); assertEquals(0, scope.getSharePolicies(SharePolicy.TYPE_EXPORT).size()); assertEquals(0, scope.getSharePolicies(SharePolicy.TYPE_IMPORT).size()); assertNotNull(scope.newScopeUpdate()); } public void stop(BundleContext arg0) throws Exception { } }
8,504
0
Create_ds/aries/subsystem/subsystem-scope-itests/src/test/bundles/tb7/org/apache/aries/subsystem/scope/itests
Create_ds/aries/subsystem/subsystem-scope-itests/src/test/bundles/tb7/org/apache/aries/subsystem/scope/itests/tb7/Activator.java
package org.apache.aries.subsystem.scope.itests.tb7; import org.apache.aries.subsystem.scope.itests.Service; import org.apache.aries.subsystem.scope.itests.Utils; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceRegistration; public class Activator implements BundleActivator { private ServiceRegistration<Service> serviceReg; public void start(final BundleContext bundleContext) throws Exception { serviceReg = bundleContext.registerService( Service.class, new Service() {}, null); } public void stop(BundleContext bundleContext) throws Exception { Utils.unregisterQuietly(serviceReg); } }
8,505
0
Create_ds/aries/subsystem/subsystem-scope-impl/src/main/java/org/apache/aries/subsystem/scope
Create_ds/aries/subsystem/subsystem-scope-impl/src/main/java/org/apache/aries/subsystem/scope/impl/IdGenerator.java
package org.apache.aries.subsystem.scope.impl; public class IdGenerator { private long lastId; public IdGenerator() { this(0); } public IdGenerator(long firstId) { lastId = firstId; } public synchronized long nextId() { return lastId++; } }
8,506
0
Create_ds/aries/subsystem/subsystem-scope-impl/src/main/java/org/apache/aries/subsystem/scope
Create_ds/aries/subsystem/subsystem-scope-impl/src/main/java/org/apache/aries/subsystem/scope/impl/ScopeUpdateImpl.java
package org.apache.aries.subsystem.scope.impl; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.aries.subsystem.scope.InstallInfo; import org.apache.aries.subsystem.scope.Scope; import org.apache.aries.subsystem.scope.ScopeUpdate; import org.apache.aries.subsystem.scope.SharePolicy; import org.apache.aries.subsystem.scope.internal.Activator; import org.osgi.framework.Bundle; import org.osgi.framework.BundleException; public class ScopeUpdateImpl implements ScopeUpdate { public static ScopeUpdateImpl newInstance(ScopeImpl scope) { ScopeUpdateImpl scopeUpdate = new ScopeUpdateImpl(scope, null); for (Scope child : scopeUpdate.scope.getChildren()) { scopeUpdate.children.add(new ScopeUpdateImpl((ScopeImpl)child, scopeUpdate)); } return scopeUpdate; } private static final IdGenerator idGenerator = new IdGenerator(1); private final Set<Bundle> bundles = Collections.synchronizedSet(new HashSet<Bundle>()); private final List<InstallInfo> bundlesToInstall = Collections.synchronizedList(new ArrayList<InstallInfo>()); private final Set<ScopeUpdate> children = Collections.synchronizedSet(new HashSet<ScopeUpdate>()); private final long id = idGenerator.nextId(); private final ScopeUpdateImpl parent; private final ScopeImpl scope; private final SharePolicies sharePolicies = new SharePolicies(); private ScopeUpdateImpl(String name, String location, ScopeUpdateImpl parent) { this.parent = parent; this.scope = new ScopeImpl( ((ScopeImpl)parent.getScope()).getScopes().nextScopeId(), name, location, parent.getScope().getId(), null, new SharePolicies(), ((ScopeImpl)parent.getScope()).getScopes()); } private ScopeUpdateImpl(ScopeImpl scope, ScopeUpdateImpl parent) { this.scope = scope; this.parent = parent; bundles.addAll(scope.getBundles()); sharePolicies.replaceAll(scope.getSharePolicies()); } public boolean commit() throws BundleException { if (parent != null) throw new IllegalStateException("Only the root ScopeUpdate may be committed"); return commit0(); } public Collection<Bundle> getBundles() { return bundles; } public List<InstallInfo> getBundlesToInstall() { return bundlesToInstall; } public Collection<ScopeUpdate> getChildren() { return children; } public String getName() { return scope.getName(); } public Scope getScope() { return scope; } public Map<String, List<SharePolicy>> getSharePolicies(String type) { return sharePolicies.getSharePolicies(type); } public ScopeUpdate newChild(String name) { return newChild(name, null); } public ScopeUpdate newChild(String name, String location) { return new ScopeUpdateImpl(name, location, this); } private void addBundles() { for (Bundle b : getBundles()) { if (!getScope().getBundles().contains(b)) { if (contains(b, this)) { throw new IllegalStateException("Bundle " + b.getSymbolicName() + " being added to scope " + getName() + " but already exists in another scope"); } scope.getScopes().addBundle(b, scope); } } } private synchronized boolean commit0() throws BundleException { synchronized (scope) { if (scope.getLastUpdate() > id) return false; scope.setUpdating(true); synchronized (bundles) { removeBundles(); } synchronized (children) { for (ScopeUpdate child : children) { if (!((ScopeUpdateImpl)child).commit0()) return false; } uninstallChildren(); } synchronized (bundles) { addBundles(); } synchronized (bundlesToInstall) { installBundles(); } updateSharePolicies(); scope.setLastUpdate(id); scope.getScopes().addScope(scope); scope.setUpdating(false); return true; } } private boolean contains(Bundle bundle, ScopeUpdateImpl scopeUpdate) { // Recurse to the top of the tree and then perform a depth-first search. return parent == null ? contains0(bundle, scopeUpdate) : parent.contains(bundle, scopeUpdate); } private boolean contains0(Bundle bundle, ScopeUpdateImpl scopeUpdate) { if (!equals(scopeUpdate) && bundles.contains(bundle)) return true; // Depth-first search. for (ScopeUpdate child : children) { if (((ScopeUpdateImpl)child).contains0(bundle, scopeUpdate)) return true; } return false; } private void installBundles() throws BundleException { for (InstallInfo installInfo : getBundlesToInstall()) { ScopeManager.installingBundleToScope.put(installInfo.getLocation(), scope); Activator.getBundleContext().installBundle(installInfo.getLocation(), installInfo.getContent()); } } private void removeBundles() throws BundleException { Collection<Bundle> bundles = new HashSet<Bundle>(scope.getBundles()); for (Bundle b : bundles) { if (!getBundles().contains(b)) { if (!contains(b, null)) { b.uninstall(); } else { scope.getScopes().removeBundle(b); } } } } private void uninstall(ScopeImpl scope) throws BundleException { for (Scope child : scope.getChildren()) { uninstall((ScopeImpl)child); } Collection<Bundle> bundles = new HashSet<Bundle>(scope.getBundles()); for (Bundle bundle : bundles) { if (!contains(bundle, null)) { bundle.uninstall(); } } scope.getScopes().removeScope(scope); } private void uninstallChildren() throws BundleException { Collection<Scope> children = new HashSet<Scope>(scope.getChildren()); for (Scope child : children) { // for (Iterator<Scope> i = scope.children.iterator(); i.hasNext();) { // Scope child = i.next(); boolean found = false; for (ScopeUpdate su : getChildren()) { if (child.equals(su.getScope())) { found = true; break; } } if (!found) { uninstall((ScopeImpl)child); } } } private void updateSharePolicies() { scope.getSharePolicies().replaceAll(sharePolicies); } }
8,507
0
Create_ds/aries/subsystem/subsystem-scope-impl/src/main/java/org/apache/aries/subsystem/scope
Create_ds/aries/subsystem/subsystem-scope-impl/src/main/java/org/apache/aries/subsystem/scope/impl/ScopeImpl.java
package org.apache.aries.subsystem.scope.impl; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.aries.subsystem.scope.Scope; import org.apache.aries.subsystem.scope.ScopeUpdate; import org.apache.aries.subsystem.scope.SharePolicy; import org.osgi.framework.Bundle; public class ScopeImpl implements Scope { private volatile boolean updating; private long lastUpdate; private final Collection<Bundle> bundles = Collections.synchronizedSet(new HashSet<Bundle>()); private final Set<Scope> children = Collections.synchronizedSet(new HashSet<Scope>()); private final long id; private final String location; private final String name; private final long parentId; private final Scopes scopes; private final SharePolicies sharePolicies; public ScopeImpl(long id, String name, String location, long parentId, Collection<Bundle> bundles, SharePolicies sharePolicies, Scopes scopes) { this.id = id; this.name = name; this.location = location; this.parentId = parentId; if (bundles != null) { this.bundles.addAll(bundles); } this.sharePolicies = sharePolicies; this.scopes = scopes; } public Collection<Bundle> getBundles() { return Collections.unmodifiableCollection(bundles); } public Collection<Scope> getChildren() { return Collections.unmodifiableCollection(children); } public long getId() { return id; } public String getLocation() { return location; } public String getName() { return name; } public Scope getParent() { return scopes.getScope(parentId); } public Map<String, List<SharePolicy>> getSharePolicies(String type) { return Collections.unmodifiableMap(sharePolicies.getSharePolicies(type)); } public ScopeUpdate newScopeUpdate() { return ScopeUpdateImpl.newInstance(this); } void addBundle(Bundle bundle) { bundles.add(bundle); } void addChild(ScopeImpl child) { children.add(child); } synchronized long getLastUpdate() { return lastUpdate; } Scopes getScopes() { return scopes; } SharePolicies getSharePolicies() { return sharePolicies; } boolean isUpdating() { return updating; } void removeBundle(Bundle bundle) { bundles.remove(bundle); } void removeChild(ScopeImpl scope) { children.remove(scope); } synchronized void setLastUpdate(long value) { lastUpdate = value; } void setUpdating(boolean value) { updating = value; } }
8,508
0
Create_ds/aries/subsystem/subsystem-scope-impl/src/main/java/org/apache/aries/subsystem/scope
Create_ds/aries/subsystem/subsystem-scope-impl/src/main/java/org/apache/aries/subsystem/scope/impl/SharePolicies.java
package org.apache.aries.subsystem.scope.impl; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.aries.subsystem.scope.SharePolicy; public class SharePolicies { private final Map<String, Map<String, List<SharePolicy>>> typeToSharePolicies = Collections.synchronizedMap(new HashMap<String, Map<String, List<SharePolicy>>>()); public SharePolicies() { init(); } public SharePolicies(SharePolicies sharePolicies) { replaceAll(sharePolicies); } public synchronized void addSharePolicy(SharePolicy sharePolicy) { String type = sharePolicy.getType(); Map<String, List<SharePolicy>> namespaceToSharePolicies = typeToSharePolicies.get(type); if (namespaceToSharePolicies == null) { namespaceToSharePolicies = Collections.synchronizedMap(new HashMap<String, List<SharePolicy>>()); typeToSharePolicies.put(type, namespaceToSharePolicies); } String namespace = sharePolicy.getNamespace(); List<SharePolicy> sharePolicies = namespaceToSharePolicies.get(namespace); if (sharePolicies == null) { sharePolicies = Collections.synchronizedList(new ArrayList<SharePolicy>()); namespaceToSharePolicies.put(namespace, sharePolicies); } sharePolicies.add(sharePolicy); } public synchronized Map<String, List<SharePolicy>> getSharePolicies(String type) { if (!(SharePolicy.TYPE_EXPORT.equals(type) || SharePolicy.TYPE_IMPORT.equals(type))) { throw new IllegalArgumentException(type); } return typeToSharePolicies.get(type); } public synchronized void removeSharePolicy(SharePolicy sharePolicy) { String type = sharePolicy.getType(); Map<String, List<SharePolicy>> namespaceToSharePolicies = typeToSharePolicies.get(type); if (namespaceToSharePolicies == null) { return; } String namespace = sharePolicy.getNamespace(); List<SharePolicy> sharePolicies = namespaceToSharePolicies.get(namespace); if (sharePolicies == null) { return; } sharePolicies.remove(sharePolicy); if (sharePolicies.isEmpty()) { namespaceToSharePolicies.remove(namespace); } if (namespaceToSharePolicies.isEmpty()) { typeToSharePolicies.remove(type); } } public synchronized void replaceAll(SharePolicies sharePolicies) { init(); synchronized (sharePolicies) { synchronized (sharePolicies.typeToSharePolicies) { for (String type : sharePolicies.typeToSharePolicies.keySet()) { Map<String, List<SharePolicy>> namespaceToSharePolicies = sharePolicies.typeToSharePolicies.get(type); synchronized (namespaceToSharePolicies) { for (String namespace : namespaceToSharePolicies.keySet()) { List<SharePolicy> policies = namespaceToSharePolicies.get(namespace); synchronized (policies) { for (SharePolicy policy : policies) { addSharePolicy(policy); } } } } } } } } private void init() { typeToSharePolicies.put(SharePolicy.TYPE_EXPORT, Collections.synchronizedMap(new HashMap<String, List<SharePolicy>>())); typeToSharePolicies.put(SharePolicy.TYPE_IMPORT, Collections.synchronizedMap(new HashMap<String, List<SharePolicy>>())); } }
8,509
0
Create_ds/aries/subsystem/subsystem-scope-impl/src/main/java/org/apache/aries/subsystem/scope
Create_ds/aries/subsystem/subsystem-scope-impl/src/main/java/org/apache/aries/subsystem/scope/impl/ScopeManager.java
package org.apache.aries.subsystem.scope.impl; import java.io.IOException; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.aries.subsystem.scope.Scope; import org.apache.aries.subsystem.scope.SharePolicy; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; import org.osgi.framework.BundleEvent; import org.osgi.framework.InvalidSyntaxException; import org.osgi.framework.ServiceEvent; import org.osgi.framework.ServiceReference; import org.osgi.framework.hooks.bundle.EventHook; import org.osgi.framework.hooks.resolver.ResolverHook; import org.osgi.framework.hooks.resolver.ResolverHookFactory; import org.osgi.framework.hooks.service.EventListenerHook; import org.osgi.framework.hooks.service.ListenerHook.ListenerInfo; import org.osgi.framework.wiring.BundleCapability; import org.osgi.framework.wiring.BundleRequirement; import org.osgi.framework.wiring.BundleRevision; public class ScopeManager implements EventHook, EventListenerHook, org.osgi.framework.hooks.bundle.FindHook, org.osgi.framework.hooks.service.FindHook, ResolverHook, ResolverHookFactory { static final Map<String, ScopeImpl> installingBundleToScope = Collections.synchronizedMap(new HashMap<String, ScopeImpl>()); private final BundleContext bundleContext; private final Scopes scopes; public ScopeManager(BundleContext bundleContext) throws InvalidSyntaxException, IOException { this.bundleContext = bundleContext; scopes = new Scopes(bundleContext); } public ResolverHook begin(java.util.Collection<BundleRevision> triggers) { return this; } public void end() { } public void event(BundleEvent event, Collection<BundleContext> contexts) { int type = event.getType(); Bundle source = event.getBundle(); if (type == BundleEvent.INSTALLED) { // For bundle installed events, the origin is the bundle whose context // was used to install the source bundle. In this case, we need to be // sure the origin bundle is assigned to a scope. This is necessary to // ensure the next step will succeed. This condition may occur, for // example, during Scope Admin initialization. Bundle origin = event.getOrigin(); synchronized (scopes) { if (!scopes.contains(origin)) { scopes.addBundle(origin); } // If Scope Admin is not the installer, add the installed bundle to the // origin bundle's scope. This will occur whenever bundles are not // installed via Scope Admin. if (origin.getBundleId() != bundleContext.getBundle().getBundleId()) { scopes.addBundle(source, scopes.getScope(origin)); } // Otherwise, assign the installed bundle to the scope designated by the scope update. else { ScopeImpl scope = installingBundleToScope.remove(source.getLocation()); scopes.addBundle(source, scope); } } } // Now filter the event listeners, if necessary. Only bundles in the same scope as the // bundle undergoing the state change may see the event. The one exception is the // system bundle, which receives all events and sends events to all listeners. if (source.getBundleId() == 0) return; ScopeImpl scope = scopes.getScope(source); Collection<Bundle> bundles = scope.getBundles(); for (Iterator<BundleContext> i = contexts.iterator(); i.hasNext();) { BundleContext bc = i.next(); Bundle b = bc.getBundle(); if (b.getBundleId() != 0 && !bundles.contains(b)) { i.remove(); } } if (type == BundleEvent.UNINSTALLED) { // For bundle uninstalled events, remove the bundle from Scope Admin. // Note this must be done after filtering the event listeners or the // bundle will get added back. scopes.removeBundle(source); } } public void event(ServiceEvent event, Map<BundleContext, Collection<ListenerInfo>> listeners) { Bundle registrar = event.getServiceReference().getBundle(); ScopeImpl scope = scopes.getScope(registrar); for (Iterator<BundleContext> i = listeners.keySet().iterator(); i.hasNext();) { Bundle listener = i.next().getBundle(); if (!scope.getBundles().contains(listener)) i.remove(); } } public void filterMatches(BundleRequirement requirement, Collection<BundleCapability> candidates) { for (Iterator<BundleCapability> i = candidates.iterator(); i.hasNext();) { if (filterMatch(requirement, i.next())) i.remove(); } } public void filterResolvable(Collection<BundleRevision> candidates) { for (Iterator<BundleRevision> i = candidates.iterator(); i.hasNext();) { BundleRevision candidate = i.next(); ScopeImpl scope = scopes.getScope(candidate.getBundle()); if (scope.isUpdating()) i.remove(); } } public void filterSingletonCollisions(BundleCapability singleton, Collection<BundleCapability> collisionCandidates) { ScopeImpl scope = scopes.getScope(singleton.getRevision().getBundle()); for (Iterator<BundleCapability> i = collisionCandidates.iterator(); i.hasNext();) { BundleCapability collisionCandidate = i.next(); if (!scope.getBundles().contains(collisionCandidate.getRevision().getBundle())) { i.remove(); } } } public void find(BundleContext context, Collection<Bundle> bundles) { // The system bundle may see all bundles. if (context.getBundle().getBundleId() == 0) return; Scope scope = scopes.getScope(context.getBundle()); for (Iterator<Bundle> i = bundles.iterator(); i.hasNext();) { Bundle bundle = i.next(); // All bundles may see the system bundle. if (bundle.getBundleId() == 0) continue; // Otherwise, a bundle may only see other bundles within its scope. if (!scope.getBundles().contains(bundle)) i.remove(); } } public void find(BundleContext context, String name, String filter, boolean allServices, Collection<ServiceReference<?>> references) { // System bundle can see all services. if (context.getBundle().getBundleId() == 0) return; for (Iterator<ServiceReference<?>> i = references.iterator(); i.hasNext();) { if (filterMatch(context, i.next())) i.remove(); } } public Scope getRootScope() { return scopes.getRootScope(); } public Scope getScope(Bundle bundle) { return scopes.getScope(bundle); } public void shutdown() { scopes.clear(); } private boolean filterMatch(BundleRequirement requirement, BundleCapability capability) { Scope scope = scopes.getScope(requirement.getRevision().getBundle()); if (scope.getBundles().contains(capability.getRevision().getBundle())) return false; if (scope.getId() < scopes.getScope(capability.getRevision().getBundle()).getId()) { if (matchesDescendants(scope.getChildren(), capability, null)) return false; } return !matchesAncestry(scope, capability); } private boolean filterMatch(BundleContext context, ServiceReference<?> reference) { Scope scope = scopes.getScope(context.getBundle()); if (scope.getBundles().contains(reference.getBundle())) return false; if (scope.getId() < scopes.getScope(reference.getBundle()).getId()) { if (matchesDescendants(scope.getChildren(), reference)) return false; } return !matchesAncestry(scope, reference); } private boolean matchesPolicyAndContainsBundle(Scope scope, BundleCapability capability, String sharePolicyType) { if (matchesPolicy(scope, capability, sharePolicyType)) { if (scope.getBundles().contains(capability.getRevision().getBundle())) { return true; } } return false; } private boolean matchesPolicy(Scope scope, BundleCapability capability, String sharePolicyType) { List<SharePolicy> policies = scope.getSharePolicies(sharePolicyType).get(capability.getNamespace()); if (policies == null) return false; for (SharePolicy policy : policies) { if (policy.getFilter().matches(capability.getAttributes())) { return true; } } return false; } private boolean matchesAncestry(Scope scope, BundleCapability capability) { if (matchesPolicy(scope, capability, SharePolicy.TYPE_IMPORT)) { Scope parent = scope.getParent(); if (parent != null) { if (parent.getBundles().contains(capability.getRevision().getBundle())) return true; if (matchesDescendants(parent.getChildren(), capability, scope)) return true; return matchesAncestry(parent, capability); } } return false; } private boolean matchesAncestry(Scope scope, ServiceReference<?> reference) { if (matchesPolicy(scope, reference, SharePolicy.TYPE_IMPORT)) { Scope parent = scope.getParent(); if (parent != null) { if (parent.getBundles().contains(reference.getBundle())) return true; return matchesAncestry(parent, reference); } } return false; } private boolean matchesDescendant(Scope child, BundleCapability capability) { if (matchesPolicyAndContainsBundle(child, capability, SharePolicy.TYPE_EXPORT)) return true; return matchesDescendants(child.getChildren(), capability, null); } private boolean matchesDescendant(Scope child, ServiceReference<?> reference) { if (matchesPolicyAndContainsBundle(child, reference, SharePolicy.TYPE_EXPORT)) return true; return matchesDescendants(child.getChildren(), reference); } private boolean matchesDescendants(Collection<Scope> children, BundleCapability capability, Scope skip) { for (Scope child : children) { if (child.equals(skip)) continue; if (matchesDescendant(child, capability)) { return true; } } return false; } private boolean matchesDescendants(Collection<Scope> children, ServiceReference<?> reference) { for (Scope child : children) { if (matchesDescendant(child, reference)) { return true; } } return false; } private boolean matchesPolicyAndContainsBundle(Scope scope, ServiceReference<?> reference, String sharePolicyType) { if (matchesPolicy(scope, reference, sharePolicyType)) { if (scope.getBundles().contains(reference.getBundle())) { return true; } } return false; } private boolean matchesPolicy(Scope scope, ServiceReference<?> reference, String sharePolicyType) { List<SharePolicy> policies = scope.getSharePolicies(sharePolicyType).get("scope.share.service"); if (policies == null) return false; for (SharePolicy policy : policies) { if (policy.getFilter().match(reference)) { return true; } } return false; } }
8,510
0
Create_ds/aries/subsystem/subsystem-scope-impl/src/main/java/org/apache/aries/subsystem/scope
Create_ds/aries/subsystem/subsystem-scope-impl/src/main/java/org/apache/aries/subsystem/scope/impl/Scopes.java
package org.apache.aries.subsystem.scope.impl; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.EOFException; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FilenameFilter; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; import org.apache.aries.subsystem.scope.Scope; import org.apache.aries.subsystem.scope.SharePolicy; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; import org.osgi.framework.FrameworkUtil; import org.osgi.framework.InvalidSyntaxException; public class Scopes { private final BundleContext bundleContext; private final Map<Bundle, ScopeImpl> bundleToScope = Collections.synchronizedMap(new HashMap<Bundle, ScopeImpl>()); private final IdGenerator idGenerator; private final SortedMap<Long, ScopeImpl> idToScope = Collections.synchronizedSortedMap(new TreeMap<Long, ScopeImpl>()); public Scopes(BundleContext bundleContext) { this.bundleContext = bundleContext; selectAll(); for (Bundle bundle : bundleContext.getBundles()) { if (contains(bundle)) { continue; } addBundle(bundle); } if (idToScope.isEmpty()) { idGenerator = new IdGenerator(0); } else { idGenerator = new IdGenerator(idToScope.lastKey() + 1); } } public synchronized void addBundle(Bundle bundle) { addBundle(bundle, getRootScope()); } public synchronized void addBundle(Bundle bundle, ScopeImpl scope) { bundleToScope.put(bundle, scope); scope.addBundle(bundle); insert(scope); } public synchronized void addScope(ScopeImpl scope) { idToScope.put(scope.getId(), scope); for (Bundle bundle : scope.getBundles()) { bundleToScope.put(bundle, scope); } ScopeImpl parent = (ScopeImpl)scope.getParent(); if (parent != null) { parent.addChild(scope); } insert(scope); for (Scope child : scope.getChildren()) { addScope((ScopeImpl)child); } } public synchronized void clear() { idToScope.clear(); bundleToScope.clear(); } public synchronized boolean contains(Bundle bundle) { return bundleToScope.containsKey(bundle); } public synchronized ScopeImpl getRootScope() { ScopeImpl scope = idToScope.get(0L); if (scope == null) { scope = new ScopeImpl(0, "root", null, -1, Arrays.asList(bundleContext.getBundles()), new SharePolicies(), this); addScope(scope); } return scope; } public synchronized ScopeImpl getScope(Long id) { return idToScope.get(id); } public synchronized ScopeImpl getScope(Bundle bundle) { ScopeImpl scope = bundleToScope.get(bundle); if (scope == null) { addBundle(bundle); scope = getRootScope(); } return scope; } public long nextScopeId() { return idGenerator.nextId(); } public synchronized void removeBundle(Bundle bundle) { ScopeImpl scope = bundleToScope.remove(bundle); if (scope != null) { synchronized (scope) { scope.removeBundle(bundle); } insert(scope); } } public synchronized void removeScope(ScopeImpl scope) { for (Scope child : scope.getChildren()) { removeScope((ScopeImpl)child); } idToScope.remove(scope.getId()); for (Bundle bundle : scope.getBundles()) { bundleToScope.remove(bundle); } ScopeImpl parent = (ScopeImpl)scope.getParent(); if (parent != null) { parent.removeChild(scope); } delete(scope); } private void delete(ScopeImpl scope) { File file = bundleContext.getDataFile("scope" + scope.getId()); if (file == null) return; file.delete(); } private void insert(ScopeImpl scope) { File file = bundleContext.getDataFile("scope" + scope.getId()); if (file == null) return; DataOutputStream dos = null; try { dos = new DataOutputStream(new FileOutputStream(file)); insertScope(scope, dos); } catch (IOException e) { // TODO Log this. Remove print stack trace. e.printStackTrace(); } finally { if (dos != null) { try { dos.close(); } catch (IOException e) {} } } } private void insertBundles(Collection<Bundle> bundles, DataOutputStream dos) throws IOException { for (Bundle bundle : bundles) { dos.writeLong(bundle.getBundleId()); } dos.writeLong(-1); } private void insertScope(ScopeImpl scope, DataOutputStream dos) throws IOException { dos.writeLong(scope.getId()); dos.writeUTF(scope.getName()); dos.writeUTF(scope.getLocation() == null ? "" : scope.getLocation()); dos.writeLong(scope.getParent() == null ? -1 : scope.getParent().getId()); insertBundles(scope.getBundles(), dos); insertSharePolicies(scope.getSharePolicies(SharePolicy.TYPE_EXPORT), dos); insertSharePolicies(scope.getSharePolicies(SharePolicy.TYPE_IMPORT), dos); } private void insertSharePolicies(Map<String, List<SharePolicy>> sharePolicies, DataOutputStream dos) throws IOException { for (String namespace : sharePolicies.keySet()) { insertSharePolicies(sharePolicies.get(namespace), dos); } } private void insertSharePolicies(List<SharePolicy> sharePolicies, DataOutputStream dos) throws IOException { for (SharePolicy sharePolicy : sharePolicies) { dos.writeUTF(sharePolicy.getType()); dos.writeUTF(sharePolicy.getNamespace()); dos.writeUTF(sharePolicy.getFilter().toString()); } } private void selectAll() { File file = bundleContext.getDataFile(""); if (file == null) { return; } File[] files = file.listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { return name.startsWith("scope"); } }); if (files == null || files.length == 0) { return; } for (File f : files) { DataInputStream dis = null; try { dis = new DataInputStream(new FileInputStream(f)); addScope(selectScope(dis, bundleContext)); } catch (Exception e) { // TODO Log this. Remove print stack trace. e.printStackTrace(); } finally { if (dis != null) { try { dis.close(); } catch (IOException e) {} } } } } private Collection<Bundle> selectBundles(DataInputStream dis, BundleContext bundleContext) throws IOException { Collection<Bundle> bundles = new ArrayList<Bundle>(); long bundleId; while ((bundleId = dis.readLong()) != -1) { Bundle bundle = bundleContext.getBundle(bundleId); if (bundle != null) { bundles.add(bundle); } } return bundles; } private ScopeImpl selectScope(DataInputStream dis, BundleContext bundleContext) throws InvalidSyntaxException, IOException { long id = dis.readLong(); String name = dis.readUTF(); String location = dis.readUTF(); long parentId = dis.readLong(); Collection<Bundle> bundles = selectBundles(dis, bundleContext); SharePolicies sharePolicies = selectSharePolicies(dis); return new ScopeImpl(id, name, location, parentId, bundles, sharePolicies, this); } private SharePolicies selectSharePolicies(DataInputStream dis) throws InvalidSyntaxException, IOException { SharePolicies sharePolicies = new SharePolicies(); while (true) { try { String type = dis.readUTF(); String namespace = dis.readUTF(); String filter = dis.readUTF(); sharePolicies.addSharePolicy(new SharePolicy(type, namespace, FrameworkUtil.createFilter(filter))); } catch (EOFException e) { break; } } return sharePolicies; } }
8,511
0
Create_ds/aries/subsystem/subsystem-scope-impl/src/main/java/org/apache/aries/subsystem/scope
Create_ds/aries/subsystem/subsystem-scope-impl/src/main/java/org/apache/aries/subsystem/scope/internal/Activator.java
package org.apache.aries.subsystem.scope.internal; import org.apache.aries.subsystem.scope.Scope; import org.apache.aries.subsystem.scope.impl.ScopeManager; import org.osgi.framework.Bundle; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceFactory; import org.osgi.framework.ServiceRegistration; import org.osgi.framework.hooks.bundle.EventHook; import org.osgi.framework.hooks.resolver.ResolverHookFactory; import org.osgi.framework.hooks.service.EventListenerHook; public class Activator implements BundleActivator, ServiceFactory<Scope> { private static volatile BundleContext bundleContext; public static BundleContext getBundleContext() { return bundleContext; } private ScopeManager scopeManager; private ServiceRegistration<?> scopeManagerReg; private ServiceRegistration<Scope> scopeFactoryReg; public Scope getService(Bundle b, ServiceRegistration<Scope> sr) { return scopeManager.getScope(b); } @SuppressWarnings("unchecked") public void start(BundleContext bundleContext) throws Exception { Activator.bundleContext = bundleContext; scopeManager = new ScopeManager(bundleContext); scopeManagerReg = bundleContext.registerService( new String[] { EventHook.class.getName(), EventListenerHook.class.getName(), org.osgi.framework.hooks.bundle.FindHook.class.getName(), org.osgi.framework.hooks.service.FindHook.class.getName(), ResolverHookFactory.class.getName(), }, scopeManager, null); scopeFactoryReg = (ServiceRegistration<Scope>)bundleContext.registerService(Scope.class.getName(), this, null); } public void stop(BundleContext bc) throws Exception { unregisterQuietly(); scopeManager.shutdown(); Activator.bundleContext = null; } public void ungetService(Bundle b, ServiceRegistration<Scope> sr, Scope s) { } private void unregisterQuietly() { unregisterQuietly(scopeFactoryReg); unregisterQuietly(scopeManagerReg); } private void unregisterQuietly(ServiceRegistration<?> serviceRegistration) { try { serviceRegistration.unregister(); } catch (Exception e) { // ignore } } }
8,512
0
Create_ds/aries/subsystem/subsystem-scope-api/src/main/java/org/apache/aries/subsystem
Create_ds/aries/subsystem/subsystem-scope-api/src/main/java/org/apache/aries/subsystem/scope/SharePolicy.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.aries.subsystem.scope; import org.osgi.framework.Filter; /** * A share policy is used to control what capabilities * are imported and exported from a scope. */ public class SharePolicy { /** * A type of share policy for importing capabilities * into a scope. */ public static final String TYPE_IMPORT = "IMPORT"; /** * A type of share policy for exporting capabilities * out of a scope. */ public static final String TYPE_EXPORT = "EXPORT"; private final String type; private final String namespace; private final Filter filter; /** * Constructs a new share policy. * @param type the type of share policy. Must be either * {@link #TYPE_IMPORT IMPORT} or {@link #TYPE_EXPORT * EXPORT}. * @param namespace the name space of the capability this policy controls. * @param filter the filter for matching capabilities this policy controls. */ public SharePolicy(String type, String namespace, Filter filter) { if (!(TYPE_EXPORT.equals(type) || TYPE_IMPORT.equals(type))) throw new IllegalArgumentException("Invalid parameter value: type = " + type); this.type = type; if (namespace == null || namespace.length() == 0) throw new IllegalArgumentException("Missing required paramater: namespace"); this.namespace = namespace; if (filter == null) throw new NullPointerException("Missing required parameter: filter"); this.filter = filter; } /** * Returns the type of this policy. * @return the type of this policy. */ public String getType() { return type; } /** * Returns the name space of the capability this policy controls. * @return the name space of the capability this policy controls. */ public String getNamespace() { return namespace; } /** * Returns the filter for matching capabilities this policy controls. * @return the filter for matching capabilities this policy controls. */ public Filter getFilter() { return filter; } }
8,513
0
Create_ds/aries/subsystem/subsystem-scope-api/src/main/java/org/apache/aries/subsystem
Create_ds/aries/subsystem/subsystem-scope-api/src/main/java/org/apache/aries/subsystem/scope/InstallInfo.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.aries.subsystem.scope; import java.io.IOException; import java.io.InputStream; import java.net.URL; /** * Information for installing a bundle into a {@link ScopeUpdate scope * update}. */ public class InstallInfo { private final InputStream content; private final String location; /** * Constructor for a bundle install info. * @param content the content of the bundle. * @param location the location of the bundle. */ public InstallInfo(String location, URL content) throws IOException { this(location == null ? content.toExternalForm() : location, content.openStream()); } /** * Constructor for a bundle install info. * @param content the content of the bundle. * @param location the location of the bundle. */ public InstallInfo(String location, InputStream content) { if (location == null || location.length() == 0) throw new IllegalArgumentException("Missing required parameter: location"); if (content == null) throw new NullPointerException("Missing required parameter: content"); this.location = location; this.content = content; } /** * Returns a url to the content of the bundle to install. * @return a url to the content of the bundle to install. */ public InputStream getContent() { return content; } /** * Returns the location to use for bundle installation. * @return the location to use for bundle installation. */ public String getLocation() { return location; } }
8,514
0
Create_ds/aries/subsystem/subsystem-scope-api/src/main/java/org/apache/aries/subsystem
Create_ds/aries/subsystem/subsystem-scope-api/src/main/java/org/apache/aries/subsystem/scope/ScopeUpdate.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.aries.subsystem.scope; import java.util.Collection; import java.util.List; import java.util.Map; import org.osgi.framework.Bundle; import org.osgi.framework.BundleException; /** * A scope update represents a snapshot of a scope and its children. * The get methods return modifiable collections or maps that represent the * bundles contained in the scope, the sharing policies, the * children scopes, and optionally what bundles to install. * The collections and maps may be modified with changes that will be * committed when the commit method is called. */ public interface ScopeUpdate { /** * Returns the name of the scope represented by this scope update. * @return the name of the scope. * @see Scope#getName() */ String getName(); /** * Returns the collection of bundles contained in this scope. * Bundles may be added or removed from this collection. * <p> * Adding a bundle to the collection will add the bundle * to this scope when commit is called. A bundle * must belong to one and only one scope at a time. * If a bundle is contained in multiple scopes * when commit is called then the commit will fail * with an exception. * <p> * Removing a bundle from the collection will remove the * bundle from this scope when commit is called. * If a bundle is removed from this collection and is * not added to the collection of another scope then the * bundle will be uninstalled when commit is called. * @return the collection of bundles contained in this scope. */ Collection<Bundle> getBundles(); /** * Returns a map containing the sharing policies for this scope. * The key is the name space of the policy and the value is the * list of policies with the same name space. * <p> * Policies may be removed or added to the lists. If adding a * policy then the policy must have the same name space as the * other policies in the list. A new name space list may also be * added to the map. The same rules apply to lists being * added, each policy in an added list must have the same * name space name space key being added. * <p> * The map will be check for validity on commit. If invalid then * the commit will fail with an exception. * @param type the type of policy to return. Must be * of type {@link SharePolicy#TYPE_EXPORT EXPORT} or * {@link SharePolicy#TYPE_IMPORT IMPORT}. Any other type * results in an exception. * @return a map containing the sharing policies of this scope. * @throws IllegalArgumentException if the type is not * {@link SharePolicy#TYPE_EXPORT EXPORT} or * {@link SharePolicy#TYPE_IMPORT IMPORT}. */ Map<String, List<SharePolicy>> getSharePolicies(String type); /** * Returns the collection of children scopes. * The children scope updates can be used to update * children scopes when the root scope is committed. * <p> * Note that only the root scope update (the one * returned by {@link ScopeAdmin#createUpdate() createUpdate} * may be used to commit changes. * <p> * Scope updates may be added or removed from this collection. * Adding a scope to the collection will add the scope * to the list of children of this scope when commit is called. * A scope must be a child to one and only one scope at a time * except the scope with id zero, this scope has no parent. * If a scope is a child of multiple scopes * when commit is called then the commit will fail * with an exception. * <p> * Removing a scope from the list will remove the * scope as a child of this scope when commit is called. * If a scope is removed from this list and is * not added to the children of another scope then the * scope will be uninstalled when commit is called. * This will result in all bundles and children scopes * of the removed scope to be uninstalled. * @return the collection of children scopes. */ Collection<ScopeUpdate> getChildren(); /** * Returns the list of install infos for bundles * that will be installed into this scope when * commit is called. Initially this list is empty * @return the list of install infos. */ List<InstallInfo> getBundlesToInstall(); /** * Creates a new child scope update for this scope. To * add the returned child scope to this scope the child * scope must be added to the collection * of children returned by {@link ScopeUpdate#getChildren() * getChildren} before calling {@link #commit() commit} on * this scope update. * @param name the name to assign the new child scope. * @return a scope update for a child scope. */ ScopeUpdate newChild(String name); /** * Creates a new child scope update for this scope. To * add the returned child scope to this scope the child * scope must be added to the collection * of children returned by {@link ScopeUpdate#getChildren() * getChildren} before calling {@link #commit() commit} on * this scope update. * @param name the name to assign the new child scope. * @return a scope update for a child scope. */ ScopeUpdate newChild(String name, String location); /** * Commit this update. If no changes have been made to the scopes * since this update was created, then this method will * update the scopes for the system. This method may only be * successfully called once on this object. * <p> * The following steps will be done to commit this scope: * <ul> * <li> If this update was not one returned by {@link * ScopeAdmin#newScopeUpdate()} then an {@link * UnsupportedOperationException} is thrown.</li> * <li> If this update is not valid then an * {@link IllegalStateException} is thrown. * //TODO need to fill in the details of illegal state * </li> * <li> All currently unresolved bundles are disabled from * resolving until the end of the commit operation. * </li> * <li> Any bundle installs or uninstalls are performed. * Any bundles installed will be disabled from resolving * until the end of the commit operation. If a * {@link BundleException} is thrown during a bundle install * or uninstall then the commit operation is terminated and * the exception is propagated to the caller. Any bundle operations * that may have succeeded are left in place and not rolled back. * </li> * <li> Scope uninstallation is performed. If a scope is uninstalled * then all of its bundles are uninstalled and all of its children * scopes are uninstalled. If a {@link BundleException} is thrown * during a bundle uninstall operation then the commit operation * is terminated and the exception is propagated to the caller. * </li> * <li> Scope installation is performed. If a {@link BundleException} * is thrown during a bundle install operation then the commit * operation is terminated and the exception is propagated to the * caller. Any bundle operations that may have succeeded are left * in place and not rolled back. * </li> * <li> This scope's sharing policy is updated. * </li> * <li> Bundles enabled for resolution. Not this must happen * even on exception. * </li> * </ul> * <p> * This method returns <code>false</code> if the commit did not occur * because another scope commit has been performed since the * creation of this update. * * @return <code>true</code> if the commit was successful. * <code>false</code> if the commit did not occur because another * update has been committed since the creation of this update. * @throws SecurityException If the caller does not have the necessary * permission to perform the update. For example, if the * update involves installing or uninstalling bundles. * @throws IllegalStateException If this update's state is * not valid or inconsistent. For example, this update tries to * place a bundle in multiple scopes. * @throws UnsupportedOperationException If this update was not one * returned by {@link ScopeAdmin#newScopeUpdate()}. * @throws BundleException if a bundle lifecycle operation failed. */ boolean commit() throws BundleException; /** * Returns the scope it is updating * @return the scope it is updating */ public Scope getScope(); }
8,515
0
Create_ds/aries/subsystem/subsystem-scope-api/src/main/java/org/apache/aries/subsystem
Create_ds/aries/subsystem/subsystem-scope-api/src/main/java/org/apache/aries/subsystem/scope/Scope.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.aries.subsystem.scope; import java.util.Collection; import java.util.List; import java.util.Map; import org.osgi.framework.Bundle; /** * A scope is used to issolate a collection of bundles * with a sharing policy. Scopes can be nested as * children scopes. * */ public interface Scope { /** * The name of this scope. A name has no meaning * at runtime and is only for informational purposes. * @return the name of this scope. */ String getName(); /** * The collection of bundles contained in this scope. * @return an unmodifiable collection of bundles * contained in this scope. */ Collection<Bundle> getBundles(); /** * Returns a map containing the sharing policies for this scope. * The key is the name space of the policy and the value is the * list of policies with the same name space. * @param type the type of policy to return. Must be * of type {@link SharePolicy#TYPE_EXPORT EXPORT} or * {@link SharePolicy#TYPE_IMPORT IMPORT}. Any other type * results in an exception. * @return an unmodifiable map containing the sharing policies of this scope. * each list value in the map is also unmodifiable. * @throws IllegalArgumentException if the type is not * {@link SharePolicy#TYPE_EXPORT EXPORT} or * {@link SharePolicy#TYPE_IMPORT IMPORT}. */ Map<String, List<SharePolicy>> getSharePolicies(String type); /** * Returns the collection of children scopes for this scope. * @return an unmodifiable collection of children scopes. */ Collection<Scope> getChildren(); /** * Returns the id for the scope * @return id for the scope */ long getId(); /** * Returns the install location String of the scope * @return the install location String of the scope */ String getLocation(); Scope getParent(); ScopeUpdate newScopeUpdate(); }
8,516
0
Create_ds/aries/subsystem/subsystem-core/src/test/java/org/apache/aries/subsystem/core
Create_ds/aries/subsystem/subsystem-core/src/test/java/org/apache/aries/subsystem/core/archive/AriesProvisionDependenciesHeaderTest.java
package org.apache.aries.subsystem.core.archive; import static org.junit.Assert.assertTrue; import org.junit.Test; public class AriesProvisionDependenciesHeaderTest { @Test public void testClauseGetValue() { assertTrue("resolve".equals(AriesProvisionDependenciesDirective.RESOLVE.getValue())); assertTrue("install".equals(AriesProvisionDependenciesDirective.INSTALL.getValue())); } @Test public void testClauseGetInstance() { assertTrue(AriesProvisionDependenciesDirective.getInstance("resolve")== AriesProvisionDependenciesDirective.RESOLVE); assertTrue(AriesProvisionDependenciesDirective.getInstance("install")== AriesProvisionDependenciesDirective.INSTALL); } }
8,517
0
Create_ds/aries/subsystem/subsystem-core/src/test/java/org/apache/aries/subsystem/core
Create_ds/aries/subsystem/subsystem-core/src/test/java/org/apache/aries/subsystem/core/archive/GenericHeaderTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.aries.subsystem.core.archive; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import org.junit.Test; public class GenericHeaderTest { @Test public void testEmptyHeader() { try { GenericHeader header = new GenericHeader("Foo-Bar", ""); assertEquals( "Empty headers are treated the same as those with an empty quoted string", "\"\"", header.getValue()); assertEquals("Empty headers should have one clause", 1, header.getClauses().size()); } catch (Exception e) { fail("Empty headers are allowed"); } } }
8,518
0
Create_ds/aries/subsystem/subsystem-core/src/test/java/org/apache/aries/subsystem/core
Create_ds/aries/subsystem/subsystem-core/src/test/java/org/apache/aries/subsystem/core/archive/Aries1453Test.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.aries.subsystem.core.archive; import java.util.Arrays; import java.util.List; import java.util.Set; import org.apache.aries.subsystem.core.capabilityset.CapabilitySet; import org.apache.aries.subsystem.core.capabilityset.SimpleFilter; import org.junit.Assert; import org.junit.Test; import org.osgi.framework.namespace.HostNamespace; import org.osgi.resource.Capability; import org.osgi.resource.Namespace; import org.osgi.resource.Requirement; import org.osgi.resource.Resource; /* * https://issues.apache.org/jira/browse/ARIES-1453 * * Fragment-Host requirements with version range do not match with * FragmentHostCapability */ public class Aries1453Test { @Test public void shouldResolveFragmentHostWithVersionRangeAndMatchWithBundlesInThatRange() { FragmentHostHeader header = new FragmentHostHeader("host-bundle;bundle-version=\"[9.6.0,10)\""); FragmentHostRequirement requirement = new FragmentHostRequirement( header.getClauses().iterator().next(), null); FragmentHostCapability capability = new FragmentHostCapability( new BundleSymbolicNameHeader("host-bundle"), new BundleVersionHeader("9.6.1"), new Resource() { @Override public List<Capability> getCapabilities(String namespace) { return null; } @Override public List<Requirement> getRequirements(String namespace) { return null; } }); String filterDirective = requirement.getDirectives().get(Namespace.REQUIREMENT_FILTER_DIRECTIVE); SimpleFilter simpleFilter = SimpleFilter.parse(filterDirective); CapabilitySet capabilitySet = new CapabilitySet(Arrays.asList(HostNamespace.HOST_NAMESPACE), true); capabilitySet.addCapability(capability); Set<Capability> capabilities = capabilitySet.match(simpleFilter, true); Assert.assertTrue(capabilities.size() == 1); Assert.assertSame(capabilities.iterator().next(), capability); } }
8,519
0
Create_ds/aries/subsystem/subsystem-core/src/test/java/org/apache/aries/subsystem/core
Create_ds/aries/subsystem/subsystem-core/src/test/java/org/apache/aries/subsystem/core/archive/Aries1425Test.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.aries.subsystem.core.archive; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.aries.subsystem.core.internal.OsgiIdentityCapability; import org.apache.aries.subsystem.core.internal.ResourceHelper; import org.junit.Test; import org.osgi.framework.Version; import org.osgi.framework.namespace.IdentityNamespace; import org.osgi.resource.Capability; import org.osgi.resource.Requirement; import org.osgi.resource.Resource; /* * https://issues.apache.org/jira/browse/ARIES-1425 * * Support both osgi.bundle and osgi.fragment resource types when given a * Subsystem-Content header clause with an unspecified type attribute. */ public class Aries1425Test { private static final String BUNDLE_A = "bundle.a"; private static final String BUNDLE_B = "bundle.b;type=osgi.bundle"; private static final String BUNDLE_C = "bundle.c;type=osgi.fragment"; private static final String BUNDLE_D = "bundle.a;type=osgi.bundle"; private static final String BUNDLE_E = "bundle.b"; private static final String HEADER_1 = BUNDLE_A + ',' + BUNDLE_B + ',' + BUNDLE_C; private static final String HEADER_2 = BUNDLE_C + ',' + BUNDLE_D + ',' + BUNDLE_E; @Test public void testGetValue() { SubsystemContentHeader header = new SubsystemContentHeader(HEADER_1); assertEquals("Wrong value", HEADER_1, header.getValue()); } @Test public void testToString() { SubsystemContentHeader header = new SubsystemContentHeader(HEADER_1); assertEquals("Wrong value", HEADER_1, header.toString()); } @Test public void testClauseToString() { Set<String> clauseStrs = new HashSet<String>(Arrays.asList(HEADER_1.split(","))); SubsystemContentHeader header = new SubsystemContentHeader(HEADER_1); Collection<SubsystemContentHeader.Clause> clauses = header.getClauses(); assertEquals("Wrong size", 3, clauses.size()); for (SubsystemContentHeader.Clause clause : clauses) { String clauseStr = clause.toString(); assertTrue("Wrong clause", clauseStrs.remove(clauseStr)); } } @Test public void testGetType() { SubsystemContentHeader header = new SubsystemContentHeader(HEADER_1); Collection<SubsystemContentHeader.Clause> clauses = header.getClauses(); assertEquals("Wrong size", 3, clauses.size()); Map<String, SubsystemContentHeader.Clause> map = new HashMap<String, SubsystemContentHeader.Clause>(3); for (SubsystemContentHeader.Clause clause : clauses) { map.put(clause.toString(), clause); } SubsystemContentHeader.Clause clause = map.get(BUNDLE_A); assertEquals("Wrong type", IdentityNamespace.TYPE_BUNDLE, clause.getType()); clause = map.get(BUNDLE_B); assertEquals("Wrong type", IdentityNamespace.TYPE_BUNDLE, clause.getType()); clause = map.get(BUNDLE_C); assertEquals("Wrong type", IdentityNamespace.TYPE_FRAGMENT, clause.getType()); } @Test public void testIsTypeSpecified() { SubsystemContentHeader header = new SubsystemContentHeader(HEADER_1); Collection<SubsystemContentHeader.Clause> clauses = header.getClauses(); assertEquals("Wrong size", 3, clauses.size()); Map<String, SubsystemContentHeader.Clause> map = new HashMap<String, SubsystemContentHeader.Clause>(3); for (SubsystemContentHeader.Clause clause : clauses) { map.put(clause.toString(), clause); } SubsystemContentHeader.Clause clause = map.get(BUNDLE_A); assertEquals("Should not be specified", Boolean.FALSE, clause.isTypeSpecified()); clause = map.get(BUNDLE_B); assertEquals("Should be specified", Boolean.TRUE, clause.isTypeSpecified()); clause = map.get(BUNDLE_C); assertEquals("Should be specified", Boolean.TRUE, clause.isTypeSpecified()); } @Test public void testToRequirement() { SubsystemContentHeader header = new SubsystemContentHeader(HEADER_1); Collection<SubsystemContentHeader.Clause> clauses = header.getClauses(); assertEquals("Wrong size", 3, clauses.size()); Map<String, SubsystemContentHeader.Clause> map = new HashMap<String, SubsystemContentHeader.Clause>(3); for (SubsystemContentHeader.Clause clause : clauses) { map.put(clause.toString(), clause); } Resource resource = new Resource() { @Override public List<Capability> getCapabilities(String namespace) { return Collections.emptyList(); } @Override public List<Requirement> getRequirements(String namespace) { return Collections.emptyList(); } }; SubsystemContentHeader.Clause clause = map.get(BUNDLE_A); Requirement requirement = clause.toRequirement(resource); assertTrue("Wrong requirement", ResourceHelper.matches( requirement, new OsgiIdentityCapability( resource, BUNDLE_A, Version.emptyVersion, IdentityNamespace.TYPE_FRAGMENT))); assertTrue("Wrong requirement", ResourceHelper.matches( requirement, new OsgiIdentityCapability( resource, BUNDLE_A, Version.emptyVersion, IdentityNamespace.TYPE_BUNDLE))); clause = map.get(BUNDLE_B); requirement = clause.toRequirement(resource); assertFalse("Wrong requirement", ResourceHelper.matches( requirement, new OsgiIdentityCapability( resource, "bundle.b", Version.emptyVersion, IdentityNamespace.TYPE_FRAGMENT))); assertTrue("Wrong requirement", ResourceHelper.matches( requirement, new OsgiIdentityCapability( resource, "bundle.b", Version.emptyVersion, IdentityNamespace.TYPE_BUNDLE))); clause = map.get(BUNDLE_C); requirement = clause.toRequirement(resource); assertTrue("Wrong requirement", ResourceHelper.matches( requirement, new OsgiIdentityCapability( resource, "bundle.c", Version.emptyVersion, IdentityNamespace.TYPE_FRAGMENT))); assertFalse("Wrong requirement", ResourceHelper.matches( requirement, new OsgiIdentityCapability( resource, "bundle.c", Version.emptyVersion, IdentityNamespace.TYPE_BUNDLE))); } @Test public void testEquals() { SubsystemContentHeader header1 = new SubsystemContentHeader(HEADER_1); SubsystemContentHeader header2 = new SubsystemContentHeader(HEADER_2); assertEquals("Headers are equal", header1, header2); } @Test public void testHashcode() { SubsystemContentHeader header1 = new SubsystemContentHeader(HEADER_1); SubsystemContentHeader header2 = new SubsystemContentHeader(HEADER_2); assertEquals("Headers are equal", header1.hashCode(), header2.hashCode()); } }
8,520
0
Create_ds/aries/subsystem/subsystem-core/src/test/java/org/apache/aries/subsystem/core
Create_ds/aries/subsystem/subsystem-core/src/test/java/org/apache/aries/subsystem/core/archive/FragmentHostHeaderTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.aries.subsystem.core.archive; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import org.junit.Test; import org.osgi.framework.Version; import org.osgi.framework.VersionRange; public class FragmentHostHeaderTest { @Test public void testNullClause() { String headerStr = null; try { new FragmentHostHeader(headerStr); fail("Null clause not allowed"); } catch (NullPointerException e) {} catch (Exception e) { fail("Null clause should result in NPE"); } } @Test public void testEmptyClause() { String headerStr = ""; try { new FragmentHostHeader(headerStr); fail("Empty clause not allowed"); } catch (IllegalArgumentException e) {} catch (Exception e) { fail("Empty clause should result in IAE"); } } @Test public void testMultipleClauses() { String headerStr = "foo;bundle-version=1.0,bar"; try { new FragmentHostHeader(headerStr); fail("Multiple clauses not allowed"); } catch (IllegalArgumentException e) {} catch (Exception e) { fail("Multiple cluases should result in IAE"); } } @Test public void testSymbolicName() { String headerStr = "org.foo"; FragmentHostHeader header = new FragmentHostHeader(headerStr); assertClauses(header, 1); assertSymbolicName(header.getClauses().iterator().next(), headerStr); assertBundleVersionAttribute( header.getClauses().iterator().next(), new VersionRange(VersionRange.LEFT_CLOSED, new Version("0"), null, VersionRange.RIGHT_OPEN)); } @Test public void testBundleVersionSingle() { String headerStr = "com.bar.foo;bundle-version=1.0"; FragmentHostHeader header = new FragmentHostHeader(headerStr); assertClauses(header, 1); assertSymbolicName(header.getClauses().iterator().next(), "com.bar.foo"); assertBundleVersionAttribute( header.getClauses().iterator().next(), new VersionRange("1.0")); } @Test public void testBundleVersionRange() { String headerStr = "com.acme.support;bundle-version=\"[2.0,3.0)\""; FragmentHostHeader header = new FragmentHostHeader(headerStr); assertClauses(header, 1); assertSymbolicName(header.getClauses().iterator().next(), "com.acme.support"); assertBundleVersionAttribute( header.getClauses().iterator().next(), new VersionRange(VersionRange.LEFT_CLOSED, new Version("2.0"), new Version("3.0"), VersionRange.RIGHT_OPEN)); } private void assertBundleVersionAttribute(FragmentHostHeader.Clause clause, VersionRange value) { assertEquals("Wrong bundle version", value, ((BundleVersionAttribute)clause.getAttribute(BundleVersionAttribute.NAME)).getVersionRange()); } private void assertClauses(FragmentHostHeader header, int expectedClauses) { assertEquals("Wrong number of clauses", expectedClauses, header.getClauses().size()); } private void assertSymbolicName(FragmentHostHeader.Clause clause, String value) { assertEquals("Wrong symbolic name", value, clause.getSymbolicName()); } }
8,521
0
Create_ds/aries/subsystem/subsystem-core/src/test/java/org/apache/aries/subsystem/core
Create_ds/aries/subsystem/subsystem-core/src/test/java/org/apache/aries/subsystem/core/archive/ImportPackageHeaderTest.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.aries.subsystem.core.archive; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import org.junit.Test; import org.osgi.framework.VersionRange; public class ImportPackageHeaderTest { @Test public void testVersionAttributeWithMultiplePackages() { String headerStr = "org.foo;org.bar;org.foo.bar;version=1.3"; ImportPackageHeader header = new ImportPackageHeader(headerStr); ImportPackageHeader header2 = new ImportPackageHeader(headerStr); assertClauses(header, 1); assertVersionAttribute(header, "org.foo;org.bar;org.foo.bar", "1.3"); assertEquals(header, header2); } @Test public void testVersionAttributeWithoutMultiplePackages() { String headerStr = "org.foo,org.bar,org.foo.bar;version=1.3"; ImportPackageHeader header = new ImportPackageHeader(headerStr); assertClauses(header, 3); assertVersionAttribute(header, "org.foo", "0"); assertVersionAttribute(header, "org.bar", "0.0"); assertVersionAttribute(header, "org.foo.bar", "1.3"); } private void assertClauses(ImportPackageHeader header, int expectedClauses) { assertEquals("Wrong number of clauses", expectedClauses, header.getClauses().size()); } private void assertVersionAttribute(ImportPackageHeader header, String path, String expectedVersion) { for (ImportPackageHeader.Clause clause : header.getClauses()) if (path.equals(clause.getPath())) { assertVersionAttribute(clause, expectedVersion); return; } fail("Path not found: " + path); } private void assertVersionAttribute(ImportPackageHeader.Clause clause, String expectedVersion) { assertVersionAttribute(clause, new VersionRange(expectedVersion)); } private void assertVersionAttribute(ImportPackageHeader.Clause clause, VersionRange expectedVersion) { assertEquals("Wrong version attribute", expectedVersion, clause.getVersionRangeAttribute().getVersionRange()); } }
8,522
0
Create_ds/aries/subsystem/subsystem-core/src/test/java/org/apache/aries/subsystem/core
Create_ds/aries/subsystem/subsystem-core/src/test/java/org/apache/aries/subsystem/core/archive/BundleRequiredExecutionEnvironmentHeaderTest.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.aries.subsystem.core.archive; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.util.List; import org.apache.aries.subsystem.core.archive.BundleRequiredExecutionEnvironmentHeader.Clause.ExecutionEnvironment; import org.apache.aries.subsystem.core.archive.BundleRequiredExecutionEnvironmentHeader.Clause.ExecutionEnvironment.Parser; import org.apache.aries.subsystem.core.internal.BasicRequirement; import org.easymock.EasyMock; import org.junit.Test; import org.osgi.framework.Constants; import org.osgi.framework.Version; import org.osgi.framework.namespace.ExecutionEnvironmentNamespace; import org.osgi.resource.Requirement; import org.osgi.resource.Resource; public class BundleRequiredExecutionEnvironmentHeaderTest { @Test public void testClause() { String clauseStr = "CDC-1.0/Foundation-1.0"; BundleRequiredExecutionEnvironmentHeader.Clause clause = new BundleRequiredExecutionEnvironmentHeader.Clause(clauseStr); assertClause(clause, clauseStr, "CDC/Foundation", "1.0", "(&(osgi.ee=CDC/Foundation)(version=1.0.0))"); } @Test public void testExecutionEnvironment1() { String name = "foo"; ExecutionEnvironment ee = new ExecutionEnvironment(name); assertExecutionEnvironmentName(ee, name); assertExecutionEnvironmentVersion(ee, (Version)null); } @Test public void testExecutionEnvironment2() { String name = "bar"; Version version = Version.parseVersion("2.0.0.qualifier"); ExecutionEnvironment ee = new ExecutionEnvironment(name, version); assertExecutionEnvironmentName(ee, name); assertExecutionEnvironmentVersion(ee, version); } @SuppressWarnings("deprecation") @Test public void testHeaderWithOneClause() { String value = "OSGi/Minimum-1.2"; String filter = "(&(osgi.ee=OSGi/Minimum)(version=1.2.0))"; BundleRequiredExecutionEnvironmentHeader header = new BundleRequiredExecutionEnvironmentHeader(value); assertEquals("Wrong number of clauses", 1, header.getClauses().size()); assertClause(header.getClauses().iterator().next(), value, "OSGi/Minimum", "1.2", filter); assertEquals("Wrong name", Constants.BUNDLE_REQUIREDEXECUTIONENVIRONMENT, header.getName()); assertEquals("Wrong value", value, header.getValue()); Resource resource = EasyMock.createNiceMock(Resource.class); List<? extends Requirement> requirements = header.toRequirements(resource); assertEquals("Wrong number of requirements", 1, requirements.size()); assertRequirement(requirements.get(0), filter, resource); } @Test @SuppressWarnings("deprecation") public void testHeaderWithMultipleClauses() { String value = "CDC-1.0/Foundation-1.0,OSGi/Minimum-1.2,J2SE-1.4,JavaSE-1.6,AA/BB-1.7,V1-1.5/V2-1.6,MyEE-badVersion"; String filter = "(|" + "(&(osgi.ee=CDC/Foundation)(version=1.0.0))" + "(&(osgi.ee=OSGi/Minimum)(version=1.2.0))" + "(&(osgi.ee=JavaSE)(version=1.4.0))" + "(&(osgi.ee=JavaSE)(version=1.6.0))" + "(&(osgi.ee=AA/BB)(version=1.7.0))" + "(osgi.ee=V1-1.5/V2-1.6)" + "(osgi.ee=MyEE-badVersion))"; BundleRequiredExecutionEnvironmentHeader header = new BundleRequiredExecutionEnvironmentHeader(value); assertEquals("Wrong number of clauses", 7, header.getClauses().size()); assertClause(header.getClauses().iterator().next(), "CDC-1.0/Foundation-1.0", "CDC/Foundation", "1.0", "(&(osgi.ee=CDC/Foundation)(version=1.0.0))"); assertEquals("Wrong name", Constants.BUNDLE_REQUIREDEXECUTIONENVIRONMENT, header.getName()); assertEquals("Wrong value", value, header.getValue()); Resource resource = EasyMock.createNiceMock(Resource.class); List<? extends Requirement> requirements = header.toRequirements(resource); assertEquals("Wrong number of requirements", 1, requirements.size()); assertRequirement(requirements.get(0), filter, resource); } @Test public void testParser1() { doTestParser("CDC-1.0/Foundation-1.0", "CDC/Foundation", "1.0"); } @Test public void testParser2() { doTestParser("OSGi/Minimum-1.2", "OSGi/Minimum", "1.2"); } @Test public void testParser3() { doTestParser("J2SE-1.4", "JavaSE", "1.4"); } @Test public void testParser4() { doTestParser("JavaSE-1.6", "JavaSE", "1.6"); } @Test public void testParser5() { doTestParser("AA/BB-1.7", "AA/BB", "1.7"); } @Test public void testParser6() { doTestParser("V1-1.5/V2-1.6", "V1-1.5/V2-1.6", (Version)null); } @Test public void testParser7() { doTestParser("MyEE-badVersion", "MyEE-badVersion", (Version)null); } @Test public void testParser8() { doTestParser("JavaSE-9", "JavaSE", "9"); } @Test public void testParser9() { doTestParser("JavaSE-10", "JavaSE", "10"); } @Test public void testParser10() { doTestParser("JavaSE-17", "JavaSE", "17"); } private void assertClause(BundleRequiredExecutionEnvironmentHeader.Clause clause, String clauseStr, String name, String version, String filter) { assertClause(clause, clauseStr, name, Version.parseVersion(version), filter); } private void assertClause(BundleRequiredExecutionEnvironmentHeader.Clause clause, String clauseStr, String name, Version version, String filter) { assertNull("Attribute should not exist", clause.getAttribute(ExecutionEnvironmentNamespace.CAPABILITY_VERSION_ATTRIBUTE)); assertTrue("Should have no attributes", clause.getAttributes().isEmpty()); assertNull("Directive should not exist", clause.getDirective(ExecutionEnvironmentNamespace.REQUIREMENT_FILTER_DIRECTIVE)); assertExecutionEnvironmentName(clause.getExecutionEnvironment(), name); assertExecutionEnvironmentVersion(clause.getExecutionEnvironment(), version); assertNull("Parameter should not exist", clause.getAttribute(ExecutionEnvironmentNamespace.CAPABILITY_VERSION_ATTRIBUTE)); assertTrue("Should have no parameters", clause.getParameters().isEmpty()); assertEquals("Wrong path", clauseStr, clause.getPath()); assertRequirement(clause, filter); } private void assertExecutionEnvironmentName(ExecutionEnvironment ee, String name) { assertEquals("Wrong name", name, ee.getName()); } private void assertExecutionEnvironmentVersion(ExecutionEnvironment ee, Version version) { assertEquals("Wrong version", version, ee.getVersion()); } private void assertRequirement(BundleRequiredExecutionEnvironmentHeader.Clause clause, String filter) { Resource resource = EasyMock.createNiceMock(Resource.class); assertRequirement(clause.toRequirement(resource), filter, resource); } private void assertRequirement(Requirement requirement, String filter, Resource resource) { Requirement r = new BasicRequirement.Builder() .namespace(ExecutionEnvironmentNamespace.EXECUTION_ENVIRONMENT_NAMESPACE) .directive(ExecutionEnvironmentNamespace.REQUIREMENT_FILTER_DIRECTIVE, filter) .resource(resource) .build(); assertEquals("Wrong requirement", r, requirement); } private void doTestParser(String clause, String name, String version) { doTestParser(clause, name, Version.parseVersion(version)); } private void doTestParser(String clause, String name, Version version) { ExecutionEnvironment ee = null; try { ee = new Parser().parse(clause); } catch (Exception e) { fail("Unable to parse execution environment from clause " + clause); } assertExecutionEnvironmentName(ee, name); assertExecutionEnvironmentVersion(ee, version); } }
8,523
0
Create_ds/aries/subsystem/subsystem-core/src/test/java/org/apache/aries/subsystem/core
Create_ds/aries/subsystem/subsystem-core/src/test/java/org/apache/aries/subsystem/core/archive/Aries1427Test.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.aries.subsystem.core.archive; import static org.junit.Assert.assertEquals; import java.util.Collections; import java.util.List; import org.apache.aries.subsystem.core.internal.BasicRequirement; import org.junit.Test; import org.osgi.framework.VersionRange; import org.osgi.framework.namespace.PackageNamespace; import org.osgi.resource.Capability; import org.osgi.resource.Requirement; import org.osgi.resource.Resource; /* * https://issues.apache.org/jira/browse/ARIES-1427 * * org.osgi.service.subsystem.SubsystemException: * java.lang.IllegalArgumentException: Invalid filter: (version=*) */ public class Aries1427Test { @Test public void testRequirementConversionWithVersionPresence() { VersionRange range = VersionRange.valueOf("(1.0,2.0)"); String filter = new StringBuilder() .append("(&(") .append(PackageNamespace.PACKAGE_NAMESPACE) .append("=com.acme.tnt") .append(')') .append(range.toFilterString(PackageNamespace.CAPABILITY_VERSION_ATTRIBUTE)) .append(')') .toString(); Requirement requirement = new BasicRequirement.Builder() .namespace(PackageNamespace.PACKAGE_NAMESPACE) .directive(PackageNamespace.REQUIREMENT_FILTER_DIRECTIVE, filter) .resource(new Resource() { @Override public List<Capability> getCapabilities(String namespace) { return Collections.emptyList(); } @Override public List<Requirement> getRequirements(String namespace) { return Collections.emptyList(); } }) .build(); ImportPackageHeader.Clause expected = new ImportPackageHeader.Clause( "com.acme.tnt;version=\"(1.0,2.0)\""); ImportPackageHeader.Clause actual = ImportPackageHeader.Clause.valueOf(requirement); assertEquals("Wrong clause", expected, actual); } }
8,524
0
Create_ds/aries/subsystem/subsystem-core/src/test/java/org/apache/aries/subsystem/core
Create_ds/aries/subsystem/subsystem-core/src/test/java/org/apache/aries/subsystem/core/archive/SubsystemManifestEqualityTest.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.aries.subsystem.core.archive; import static org.junit.Assert.assertEquals; import java.io.IOException; import org.junit.Test; public class SubsystemManifestEqualityTest { @Test public void testSubsystemContentEquality() { String headerStr = "org.aries.bundle;start-order:=0;type=osgi.bundle;version=\"1.8.4\";resolution:=mandatory"; SubsystemContentHeader header1 = new SubsystemContentHeader(headerStr); SubsystemContentHeader header2 = new SubsystemContentHeader(headerStr); assertEquals(header1, header2); String headerStr1 = "org.aries.bundle;start-order:=0;type=osgi.bundle;version=\"1.8.4\";resolution:=mandatory"; String headerStr2 = "org.aries.bundle;type=osgi.bundle;resolution:=mandatory;version=\"1.8.4\";start-order:=0"; header1 = new SubsystemContentHeader(headerStr1); header2 = new SubsystemContentHeader(headerStr2); assertEquals(header1, header2); } @Test public void testDynamicImportHeaderEquality() { String headerStr1 = "org.eclipse.jetty.*;version=\"[9.0,10.0)\",*;JavaServlet=contract"; String headerStr2 = "*;JavaServlet=contract,org.eclipse.jetty.*;version=\"[9.0,10.0)\""; DynamicImportPackageHeader header1 = new DynamicImportPackageHeader( headerStr1); DynamicImportPackageHeader header2 = new DynamicImportPackageHeader( headerStr2); assertEquals(header1, header2); } @Test public void testExportPackageHeaderEquality() { String headerStr1 = "javax.servlet;version=\"2.5\",javax.servlet.http; version=\"2.5\""; String headerStr2 = "javax.servlet.http; version=\"2.5\",javax.servlet;version=\"2.5\""; ExportPackageHeader header1 = new ExportPackageHeader(headerStr1); ExportPackageHeader header2 = new ExportPackageHeader(headerStr2); assertEquals(header1, header2); } @Test public void testFragmentHostHeaderEquality() { String headerStr1 = "the.parent.bundle;bundle-version=1.2.3"; String headerStr2 = "the.parent.bundle;bundle-version=1.2.3"; FragmentHostHeader header1 = new FragmentHostHeader(headerStr1); FragmentHostHeader header2 = new FragmentHostHeader(headerStr2); assertEquals(header1, header2); } @Test public void testImportPackageHeaderEquality() { String headerStr1 = "javax.servlet;version=\"2.6.0\", javax.servlet.resources;version=\"2.6.0\""; String headerStr2 = "javax.servlet.resources;version=\"2.6.0\",javax.servlet;version=\"2.6.0\""; ImportPackageHeader header1 = new ImportPackageHeader(headerStr1); ImportPackageHeader header2 = new ImportPackageHeader(headerStr2); assertEquals(header1, header2); } @Test public void testPreferredProviderHeaderEquality() { String headerStr1 = "org.aries.kernel;version=\"1.0.4\";type=osgi.subsystem.composite"; String headerStr2 = "org.aries.kernel;type=osgi.subsystem.composite;version=\"1.0.4\""; PreferredProviderHeader header1 = new PreferredProviderHeader( headerStr1); PreferredProviderHeader header2 = new PreferredProviderHeader( headerStr2); assertEquals(header1, header2); } @Test public void testProvideCapabilityHeaderEquality() { String headerStr1 = "osgi.contract;osgi.contract=JavaServlet;version:Version=2.5;uses:=\"javax.servlet,javax.servlet.http\""; String headerStr2 = "osgi.contract;uses:=\"javax.servlet,javax.servlet.http\";osgi.contract=JavaServlet;version:Version=2.5"; ProvideCapabilityHeader header1 = new ProvideCapabilityHeader( headerStr1); ProvideCapabilityHeader header2 = new ProvideCapabilityHeader( headerStr2); assertEquals(header1, header2); } @Test public void testProvisionResourceHeaderEquality() { String headerStr1 = "com.acme.logging;type=osgi.bundle;deployed-version=1.0.0"; String headerStr2 = "com.acme.logging;deployed-version=1.0.0;type=osgi.bundle"; ProvisionResourceHeader header1 = new ProvisionResourceHeader( headerStr1); ProvisionResourceHeader header2 = new ProvisionResourceHeader( headerStr2); assertEquals(header1, header2); } @Test public void testRequireBundleHeaderEquality() { String headerStr1 = "com.example.acme,com.acme.logging;bundle-version=\"[1.0, 1.1)\""; String headerStr2 = "com.acme.logging;bundle-version=\"[1.0, 1.1)\",com.example.acme"; RequireBundleHeader header1 = new RequireBundleHeader(headerStr1); RequireBundleHeader header2 = new RequireBundleHeader(headerStr2); assertEquals(header1, header2); } @Test public void testRequireCapabilityHeaderEquality() { String headerStr1 = "osgi.ee; filter:=\"(osgi.ee=*)\",screen.size; filter:=\"(&(width>=800)(height>=600))\""; String headerStr2 = "screen.size; filter:=\"(&(width>=800)(height>=600))\",osgi.ee; filter:=\"(osgi.ee=*)\""; RequireCapabilityHeader header1 = new RequireCapabilityHeader( headerStr1); RequireCapabilityHeader header2 = new RequireCapabilityHeader( headerStr2); assertEquals(header1, header2); } @Test public void testSubsystemExportServiceHeaderEquality() { String headerStr1 = "com.acme.service.Logging"; String headerStr2 = "com.acme.service.Logging"; SubsystemExportServiceHeader header1 = new SubsystemExportServiceHeader( headerStr1); SubsystemExportServiceHeader header2 = new SubsystemExportServiceHeader( headerStr2); assertEquals(header1, header2); } @Test public void testSubsystemImportServiceHeaderEquality() { String headerStr1 = "com.acme.service.Logging"; String headerStr2 = "com.acme.service.Logging"; SubsystemImportServiceHeader header1 = new SubsystemImportServiceHeader( headerStr1); SubsystemImportServiceHeader header2 = new SubsystemImportServiceHeader( headerStr2); assertEquals(header1, header2); } @Test public void testSubsystemManifestEquality() throws IOException { SubsystemManifest subsystemManifest1 = new SubsystemManifest(getClass() .getResourceAsStream("/files/SUBSYSTEM.MF.1")); SubsystemManifest subsystemManifest2 = new SubsystemManifest(getClass() .getResourceAsStream("/files/SUBSYSTEM.MF.2")); assertEquals(subsystemManifest1, subsystemManifest2); } @Test public void testSubsystemTypeHeaderEquality() { String headerStr1 = "osgi.subsystem.composite"; String headerStr2 = "osgi.subsystem.composite"; SubsystemTypeHeader header1 = new SubsystemTypeHeader(headerStr1); SubsystemTypeHeader header2 = new SubsystemTypeHeader(headerStr2); assertEquals(header1, header2); } @Test public void testSubsystemVersionHeaderEquality() { String headerStr1 = "1.0.0"; String headerStr2 = "1.0.0"; SubsystemVersionHeader header1 = new SubsystemVersionHeader(headerStr1); SubsystemVersionHeader header2 = new SubsystemVersionHeader(headerStr2); assertEquals(header1, header2); headerStr2 = "1"; header2 = new SubsystemVersionHeader(headerStr2); assertEquals("Equivalent versions should be equal", header1, header2); } @Test public void testBundleSymbolicNameHeaderEquality() { String headerStr1 = "com.example.acme;singleton:=true"; String headerStr2 = "com.example.acme;singleton:=true"; SymbolicNameHeader header1 = new BundleSymbolicNameHeader(headerStr1); SymbolicNameHeader header2 = new BundleSymbolicNameHeader(headerStr2); assertEquals(header1, header2); headerStr1 = "com.example.acme;fragment-attachment:=never;singleton:=true"; headerStr2 = "com.example.acme;singleton:=true;fragment-attachment:=never"; header1 = new BundleSymbolicNameHeader(headerStr1); header2 = new BundleSymbolicNameHeader(headerStr2); assertEquals("Equivalent clauses should be equal", header1, header2); } @Test public void testSubsystemSymbolicNameHeaderEquality() { String headerStr1 = "org.acme.billing;category=banking"; String headerStr2 = "org.acme.billing;category=banking"; SymbolicNameHeader header1 = new SubsystemSymbolicNameHeader( headerStr1); SymbolicNameHeader header2 = new SubsystemSymbolicNameHeader( headerStr2); assertEquals(header1, header2); } @Test public void testDeployedContentHeaderEquality() { String headerStr1 = "com.acme.logging;type=osgi.bundle;deployed-version=1.0.0"; String headerStr2 = "com.acme.logging;type=osgi.bundle;deployed-version=1.0.0"; DeployedContentHeader header1 = new DeployedContentHeader(headerStr1); DeployedContentHeader header2 = new DeployedContentHeader(headerStr2); assertEquals(header1, header2); } }
8,525
0
Create_ds/aries/subsystem/subsystem-core/src/test/java/org/apache/aries/subsystem/core
Create_ds/aries/subsystem/subsystem-core/src/test/java/org/apache/aries/subsystem/core/internal/ResourceHelperTest.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.aries.subsystem.core.internal; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.easymock.EasyMock; import org.junit.Test; import org.osgi.framework.namespace.PackageNamespace; import org.osgi.resource.Capability; import org.osgi.resource.Requirement; import org.osgi.resource.Resource; public class ResourceHelperTest { @Test public void testMandatoryDirectiveAbsent() { Capability cap = new BasicCapability.Builder() .namespace(PackageNamespace.PACKAGE_NAMESPACE) .attribute(PackageNamespace.PACKAGE_NAMESPACE, "com.foo") .attribute("a", "b") .attribute("b", "c") .attribute("c", "d") .resource(EasyMock.createNiceMock(Resource.class)).build(); Requirement req = new BasicRequirement.Builder() .namespace(PackageNamespace.PACKAGE_NAMESPACE) .directive(PackageNamespace.REQUIREMENT_FILTER_DIRECTIVE, "(&(osgi.wiring.package=com.foo)(a=b)(b=c))") .resource(EasyMock.createNiceMock(Resource.class)).build(); assertTrue("Capability should match requirement", ResourceHelper.matches(req, cap)); } @Test public void testMandatoryDirectiveAndNullFilterDirective() { Capability cap = new BasicCapability.Builder() .namespace(PackageNamespace.PACKAGE_NAMESPACE) .attribute(PackageNamespace.PACKAGE_NAMESPACE, "com.foo") .attribute("a", "b") .attribute("b", "c") .attribute("c", "d") .directive(PackageNamespace.CAPABILITY_MANDATORY_DIRECTIVE, "b") .resource(EasyMock.createNiceMock(Resource.class)).build(); Requirement req = new BasicRequirement.Builder() .namespace(PackageNamespace.PACKAGE_NAMESPACE) .resource(EasyMock.createNiceMock(Resource.class)).build(); assertFalse("Capability should not match requirement", ResourceHelper.matches(req, cap)); } @Test public void testMandatoryDirectiveCaseSensitive() { Capability cap = new BasicCapability.Builder() .namespace(PackageNamespace.PACKAGE_NAMESPACE) .attribute(PackageNamespace.PACKAGE_NAMESPACE, "com.foo") .attribute("a", "b") .attribute("bAr", "c") .attribute("c", "d") .directive(PackageNamespace.CAPABILITY_MANDATORY_DIRECTIVE, "bAr") .resource(EasyMock.createNiceMock(Resource.class)).build(); Requirement req = new BasicRequirement.Builder() .namespace(PackageNamespace.PACKAGE_NAMESPACE) .directive(PackageNamespace.REQUIREMENT_FILTER_DIRECTIVE, "(&(osgi.wiring.package=com.foo)(a=b)(baR=c)(c=d))") .resource(EasyMock.createNiceMock(Resource.class)).build(); assertFalse("Capability should not match requirement", ResourceHelper.matches(req, cap)); } @Test public void testMandatoryDirectiveExportPackageFail() { Capability cap = new BasicCapability.Builder() .namespace(PackageNamespace.PACKAGE_NAMESPACE) .attribute(PackageNamespace.PACKAGE_NAMESPACE, "com.foo") .attribute("a", "b") .attribute("b", "c") .attribute("c", "d") .directive(PackageNamespace.CAPABILITY_MANDATORY_DIRECTIVE, "a,c") .resource(EasyMock.createNiceMock(Resource.class)) .build(); Requirement req = new BasicRequirement.Builder() .namespace(PackageNamespace.PACKAGE_NAMESPACE) .directive(PackageNamespace.REQUIREMENT_FILTER_DIRECTIVE, "(&(osgi.wiring.package=com.foo)(a=b)(b=c))") .resource(EasyMock.createNiceMock(Resource.class)).build(); assertFalse("Capability should not match requirement", ResourceHelper.matches(req, cap)); } @Test public void testMandatoryDirectiveExportPackagePass() { Capability cap = new BasicCapability.Builder() .namespace(PackageNamespace.PACKAGE_NAMESPACE) .attribute(PackageNamespace.PACKAGE_NAMESPACE, "com.foo") .attribute("a", "b") .attribute("b", "c") .attribute("c", "d") .directive(PackageNamespace.CAPABILITY_MANDATORY_DIRECTIVE, "a,c") .resource(EasyMock.createNiceMock(Resource.class)) .build(); Requirement req = new BasicRequirement.Builder() .namespace(PackageNamespace.PACKAGE_NAMESPACE) .directive(PackageNamespace.REQUIREMENT_FILTER_DIRECTIVE, "(&(osgi.wiring.package=com.foo)(a=b)(c=d))") .resource(EasyMock.createNiceMock(Resource.class)).build(); assertTrue("Capability should match requirement", ResourceHelper.matches(req, cap)); } @Test public void testMandatoryDirectiveWithWhitespace() { Capability cap = new BasicCapability.Builder() .namespace(PackageNamespace.PACKAGE_NAMESPACE) .attribute(PackageNamespace.PACKAGE_NAMESPACE, "com.foo") .attribute("a", "b") .attribute("b", "c") .attribute("c", "d") .directive(PackageNamespace.CAPABILITY_MANDATORY_DIRECTIVE, "\ra\n, c ") .resource(EasyMock.createNiceMock(Resource.class)) .build(); Requirement req = new BasicRequirement.Builder() .namespace(PackageNamespace.PACKAGE_NAMESPACE) .directive(PackageNamespace.REQUIREMENT_FILTER_DIRECTIVE, "(&(osgi.wiring.package=com.foo)(a=b)(c=d))") .resource(EasyMock.createNiceMock(Resource.class)).build(); assertTrue("Capability should match requirement", ResourceHelper.matches(req, cap)); } }
8,526
0
Create_ds/aries/subsystem/subsystem-core/src/test/java/org/apache/aries/subsystem/core
Create_ds/aries/subsystem/subsystem-core/src/test/java/org/apache/aries/subsystem/core/internal/LocationTest.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.aries.subsystem.core.internal; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.fail; import java.net.MalformedURLException; import org.junit.Test; import org.osgi.framework.Version; public class LocationTest { @Test public void testAnyLocationString() { String locationStr = "anyLocation"; Location location = null; try { location = new Location(locationStr); } catch (Throwable t) { t.printStackTrace(); fail("Any location string must be supported"); } assertNull("Wrong symbolic name", location.getSymbolicName()); assertEquals("Wrong value", locationStr, location.getValue()); assertNull("Wrong version", location.getVersion()); try { location.open(); fail("Opening a location that does not represent a URL should fail"); } catch (MalformedURLException e) { // Okay } catch (Throwable t) { t.printStackTrace(); fail("Wrong exception"); } } @Test public void testAnyURIScheme() throws Exception { Location l = new Location("foo://bar"); assertEquals("foo://bar", l.getValue()); } @Test public void testSubsystemLocation() throws Exception { String locationString = "subsystem://?Subsystem-SymbolicName=org.osgi.service.subsystem.root&Subsystem-Version=1.2.3"; Location location = new Location(locationString); assertEquals(locationString, location.getValue()); assertEquals("org.osgi.service.subsystem.root", location.getSymbolicName()); assertEquals(Version.parseVersion("1.2.3"), location.getVersion()); } @Test public void testSubsystemLocationInvalid() throws Exception { // In some cases the following location string is generated String locationString = "subsystem://?Subsystem-SymbolicName=org.osgi.service.subsystem.root&Subsystem-Version=1.0.0!/my-subsystem@0.5.0"; Location location = new Location(locationString); assertEquals(locationString, location.getValue()); try { String sn = location.getSymbolicName(); fail("Expecting an error: " + sn); } catch (IllegalArgumentException e) { // expected } try { Version v = location.getVersion(); fail("Expecting an error: " + v); } catch (IllegalArgumentException e) { // expected } } }
8,527
0
Create_ds/aries/subsystem/subsystem-core/src/test/java/org/apache/aries/subsystem/core
Create_ds/aries/subsystem/subsystem-core/src/test/java/org/apache/aries/subsystem/core/internal/RepositoryServiceRepositoryTest.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.aries.subsystem.core.internal; import static org.junit.Assert.assertEquals; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.apache.aries.subsystem.core.internal.sub.Creator; import org.easymock.EasyMock; import org.junit.Test; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceReference; import org.osgi.resource.Capability; import org.osgi.resource.Requirement; import org.osgi.resource.Resource; import org.osgi.service.repository.Repository; public class RepositoryServiceRepositoryTest { @Test public void testFindProviders() throws Exception { BundleContext bc = EasyMock.createNiceMock(BundleContext.class); RepositoryServiceRepository rsr = new RepositoryServiceRepository(bc); @SuppressWarnings("unchecked") ServiceReference<Object> sr = EasyMock.createMock(ServiceReference.class); @SuppressWarnings("unchecked") ServiceReference<Object> sr2 = EasyMock.createMock(ServiceReference.class); @SuppressWarnings("unchecked") ServiceReference<Object> sr3 = EasyMock.createMock(ServiceReference.class); EasyMock.expect(bc.getAllServiceReferences("org.osgi.service.repository.Repository", null)). andReturn(new ServiceReference[] {sr, sr2, sr3}).anyTimes(); TestRepository tr = new TestRepository(); EasyMock.expect(bc.getService(sr)).andReturn(tr).anyTimes(); ToastRepository tr2 = new ToastRepository(); EasyMock.expect(bc.getService(sr2)).andReturn(tr2).anyTimes(); Repository tr3 = Creator.create(); EasyMock.expect(bc.getService(sr3)).andReturn(tr3).anyTimes(); EasyMock.replay(bc); Map<String, String> dirs = Collections.singletonMap("filter", "(org.foo=bar)"); Requirement req = new TestRequirement("org.foo", dirs); Collection<Capability> res = rsr.findProviders(req); assertEquals(1, res.size()); Capability cap = res.iterator().next(); assertEquals("org.foo", cap.getNamespace()); assertEquals(1, cap.getAttributes().size()); assertEquals("bar", cap.getAttributes().get("org.foo")); Map<String, String> dirs2 = Collections.singletonMap("filter", "(org.foo=b)"); Requirement req2 = new TestRequirement("poing", dirs2); Collection<Capability> res2 = rsr.findProviders(req2); assertEquals(1, res2.size()); Capability cap2 = res2.iterator().next(); assertEquals("poing", cap2.getNamespace()); assertEquals(1, cap2.getAttributes().size()); assertEquals("b", cap2.getAttributes().get("org.foo")); Map<String, String> dirs3 = Collections.singletonMap("filter", "(x=y)"); Requirement req3 = new TestRequirement("ns1", dirs3); Collection<Capability> res3 = rsr.findProviders(req3); assertEquals(1, res3.size()); Capability cap3 = res3.iterator().next(); assertEquals("ns1", cap3.getNamespace()); assertEquals(1, cap3.getAttributes().size()); assertEquals("y", cap3.getAttributes().get("x")); } private static class TestRequirement implements Requirement { private final String namespace; private final Map<String, String> directives; private TestRequirement(String ns, Map<String, String> dirs) { namespace = ns; directives = dirs; } @Override public String getNamespace() { return namespace; } @Override public Map<String, Object> getAttributes() { return Collections.emptyMap(); } @Override public Map<String, String> getDirectives() { return directives; } @Override public Resource getResource() { return null; } } private static class TestRepository implements Repository { @Override public Map<Requirement, Collection<Capability>> findProviders(Collection<? extends Requirement> requirements) { Map<Requirement, Collection<Capability>> res = new HashMap<Requirement, Collection<Capability>>(); for (Requirement req : requirements) { if (req.getNamespace().equals("org.foo") && req.getDirectives().equals(Collections.singletonMap("filter", "(org.foo=bar)"))) { TestCapability cap = new TestCapability("org.foo", Collections.<String, Object>singletonMap("org.foo", "bar")); Collection<Capability> caps = Collections.<Capability>singleton(cap); res.put(req, caps); } } return res; } } private static class ToastRepository extends TestRepository { @Override public Map<Requirement, Collection<Capability>> findProviders(Collection<? extends Requirement> requirements) { for (Requirement req : requirements) { if (req.getNamespace().equals("poing") && req.getDirectives().equals(Collections.singletonMap("filter", "(org.foo=b)"))) { TestCapability cap = new TestCapability("poing", Collections.<String, Object>singletonMap("org.foo", "b")); Collection<Capability> caps = Collections.<Capability>singleton(cap); return Collections.singletonMap(req, caps); } } return Collections.emptyMap(); } } }
8,528
0
Create_ds/aries/subsystem/subsystem-core/src/test/java/org/apache/aries/subsystem/core
Create_ds/aries/subsystem/subsystem-core/src/test/java/org/apache/aries/subsystem/core/internal/BundleRevisionResourceTest.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.aries.subsystem.core.internal; import static org.junit.Assert.assertEquals; import static org.easymock.EasyMock.*; import java.lang.reflect.Field; import java.util.Collections; import org.easymock.EasyMock; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.osgi.framework.wiring.BundleRevision; import org.osgi.resource.Capability; import org.osgi.resource.Requirement; public class BundleRevisionResourceTest { Activator storedActivator; @Before public void setUp() throws Exception { Field field = Activator.class.getDeclaredField("instance"); field.setAccessible(true); storedActivator = (Activator) field.get(null); field.set(null, new Activator()); } @After public void tearDown() throws Exception { Field field = Activator.class.getDeclaredField("instance"); field.setAccessible(true); field.set(null, storedActivator); storedActivator = null; } @Test public void testNoModellerServiceCapabilities() { BundleRevision br = createNiceMock(BundleRevision.class); expect(br.getCapabilities(anyObject(String.class))).andReturn(Collections.<Capability>emptyList()); expect(br.getRequirements(anyObject(String.class))).andReturn(Collections.<Requirement>emptyList()); replay(br); BundleRevisionResource brr = new BundleRevisionResource(br); assertEquals(0, brr.getCapabilities("osgi.service").size()); } @Test public void testNoModellerServiceRequirements() { BundleRevision br = EasyMock.createNiceMock(BundleRevision.class); expect(br.getRequirements(anyObject(String.class))).andReturn(Collections.<Requirement>emptyList()); expect(br.getCapabilities(anyObject(String.class))).andReturn(Collections.<Capability>emptyList()); replay(br); BundleRevisionResource brr = new BundleRevisionResource(br); assertEquals(0, brr.getRequirements("osgi.service").size()); } }
8,529
0
Create_ds/aries/subsystem/subsystem-core/src/test/java/org/apache/aries/subsystem/core
Create_ds/aries/subsystem/subsystem-core/src/test/java/org/apache/aries/subsystem/core/internal/ResolveContextTest.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.aries.subsystem.core.internal; import java.io.File; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.easymock.EasyMock; import org.junit.Test; import org.osgi.framework.BundleContext; import org.osgi.resource.Capability; import org.osgi.service.resolver.HostedCapability; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; public class ResolveContextTest { @Test public void testInsertHostedCapability() throws Exception { Activator prev = getActivator(); try { Activator activator = createActivator(); setActivator(activator); SubsystemResource res = new SubsystemResource(new File(".")); ResolveContext rc = new ResolveContext(res); HostedCapability hc = EasyMock.createNiceMock(HostedCapability.class); List<Capability> caps = new ArrayList<Capability>() { // Must use add(idx, obj), get the other add() overloads to complain @Override public boolean add(Capability e) { throw new UnsupportedOperationException(); } @Override public boolean addAll(Collection<? extends Capability> c) { throw new UnsupportedOperationException(); } @Override public boolean addAll(int index, Collection<? extends Capability> c) { throw new UnsupportedOperationException(); } }; caps.add(0, EasyMock.createNiceMock(HostedCapability.class)); assertEquals(1, rc.insertHostedCapability(caps, hc)); assertSame(hc, caps.get(1)); } finally { setActivator(prev); } } private Activator createActivator() throws Exception { BundleContext bc = EasyMock.createNiceMock(BundleContext.class); EasyMock.replay(bc); Activator a = new Activator(); Field f = Activator.class.getDeclaredField("subsystems"); f.setAccessible(true); f.set(a, new Subsystems()); Field f2 = Activator.class.getDeclaredField("systemRepositoryManager"); f2.setAccessible(true); f2.set(a, new SystemRepositoryManager(bc)); return a; } private Activator getActivator() throws Exception { Field f = Activator.class.getDeclaredField("instance"); f.setAccessible(true); return (Activator) f.get(null); } private void setActivator(Activator a) throws Exception { Field f = Activator.class.getDeclaredField("instance"); f.setAccessible(true); f.set(null, a); } }
8,530
0
Create_ds/aries/subsystem/subsystem-core/src/test/java/org/apache/aries/subsystem/core
Create_ds/aries/subsystem/subsystem-core/src/test/java/org/apache/aries/subsystem/core/internal/TestCapability.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.aries.subsystem.core.internal; import java.util.Collections; import java.util.Map; import org.osgi.resource.Capability; import org.osgi.resource.Resource; public class TestCapability implements Capability { private final String namespace; private final Map<String, Object> attributes; public TestCapability(String ns, Map<String, Object> attrs) { namespace = ns; attributes = attrs; } @Override public String getNamespace() { return namespace; } @Override public Map<String, String> getDirectives() { return Collections.emptyMap(); } @Override public Map<String, Object> getAttributes() { return attributes; } @Override public Resource getResource() { return null; } }
8,531
0
Create_ds/aries/subsystem/subsystem-core/src/test/java/org/apache/aries/subsystem/core/internal
Create_ds/aries/subsystem/subsystem-core/src/test/java/org/apache/aries/subsystem/core/internal/sub/SubTestRepository.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.aries.subsystem.core.internal.sub; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.apache.aries.subsystem.core.internal.TestCapability; import org.osgi.resource.Capability; import org.osgi.resource.Requirement; import org.osgi.service.repository.Repository; // It is important for the test that this class it non-public class SubTestRepository implements Repository { @Override public Map<Requirement, Collection<Capability>> findProviders(Collection<? extends Requirement> requirements) { Map<Requirement, Collection<Capability>> res = new HashMap<Requirement, Collection<Capability>>(); for (Requirement req : requirements) { if (req.getNamespace().equals("ns1") && req.getDirectives().equals(Collections.singletonMap("filter", "(x=y)"))) { TestCapability cap = new TestCapability("ns1", Collections.<String, Object>singletonMap("x", "y")); Collection<Capability> caps = Collections.<Capability>singleton(cap); res.put(req, caps); } } return res; } }
8,532
0
Create_ds/aries/subsystem/subsystem-core/src/test/java/org/apache/aries/subsystem/core/internal
Create_ds/aries/subsystem/subsystem-core/src/test/java/org/apache/aries/subsystem/core/internal/sub/Creator.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.aries.subsystem.core.internal.sub; import org.osgi.service.repository.Repository; public class Creator { public static Repository create() { return new SubTestRepository(); } }
8,533
0
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/repository/RepositoryContent.java
/* * Copyright (c) OSGi Alliance (2012). All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.aries.subsystem.core.repository; import java.io.InputStream; import org.osgi.resource.Resource; /** * An accessor for the default content of a resource. * * All {@link Resource} objects which represent resources in a * {@link Repository} must implement this interface. A user of the resource can * then cast the {@link Resource} object to this type and then obtain an * {@code InputStream} to the default content of the resource. * * @ThreadSafe * @noimplement * @version $Id$ */ public interface RepositoryContent { /** * Returns a new input stream to the default format of this resource. * * @return A new input stream for associated resource. */ InputStream getContent(); }
8,534
0
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/repository/Repository.java
/* * Copyright (c) OSGi Alliance (2006, 2012). All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // This document is an experimental draft to enable interoperability // between bundle repositories. There is currently no commitment to // turn this draft into an official specification. package org.apache.aries.subsystem.core.repository; import java.util.Collection; import java.util.Map; import org.osgi.resource.Capability; import org.osgi.resource.Requirement; import org.osgi.resource.Resource; /** * A repository service that contains {@link Resource resources}. * * <p> * Repositories may be registered as services and may be used as by a resolve * context during resolver operations. * * <p> * Repositories registered as services may be filtered using standard service * properties. * * @ThreadSafe * @noimplement * @version $Id$ */ public interface Repository { /** * Service property to provide URLs related to this repository. * * <p> * The value of this property must be of type {@code String}, * {@code String[]}, or {@code Collection<String>}. */ String URL = "repository.url"; /** * Find the capabilities that match the specified requirements. * * @param requirements The requirements for which matching capabilities * should be returned. Must not be {@code null}. * @return A map of matching capabilities for the specified requirements. * Each specified requirement must appear as a key in the map. If * there are no matching capabilities for a specified requirement, * then the value in the map for the specified requirement must be * an empty collection. The returned map is the property of the * caller and can be modified by the caller. */ Map<Requirement, Collection<Capability>> findProviders(Collection<? extends Requirement> requirements); }
8,535
0
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/repository/ContentNamespace.java
/* * Copyright (c) OSGi Alliance (2011, 2012). All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.aries.subsystem.core.repository; import org.osgi.resource.Namespace; /** * Content Capability and Requirement Namespace. * * <p> * This class defines the names for the attributes and directives for this * namespace. All unspecified capability attributes are of type {@code String} * and are used as arbitrary matching attributes for the capability. The values * associated with the specified directive and attribute keys are of type * {@code String}, unless otherwise indicated. * * @Immutable * @version $Id$ */ public final class ContentNamespace extends Namespace { /** * Namespace name for content capabilities and requirements. * * <p> * Also, the capability attribute used to specify the unique identifier of * the content. This identifier is the {@code SHA-256} hash of the content. */ public static final String CONTENT_NAMESPACE = "osgi.content"; /** * The capability attribute that contains the URL to the content. */ public static final String CAPABILITY_URL_ATTRIBUTE = "url"; /** * The capability attribute that contains the size, in bytes, of the * content. The value of this attribute must be of type {@code Long}. */ public static final String CAPABILITY_SIZE_ATTRIBUTE = "size"; /** * The capability attribute that defines the IANA MIME Type/Format for this * content. */ public static final String CAPABILITY_MIME_ATTRIBUTE = "mime"; private ContentNamespace() { // empty } }
8,536
0
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/repository/package-info.java
/* * Copyright (c) OSGi Alliance (2010, 2012). All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Repository Service Package Version 1.0. * * <p> * Bundles wishing to use this package must list the package in the * Import-Package header of the bundle's manifest. This package has two types of * users: the consumers that use the API in this package and the providers that * implement the API in this package. * * <p> * Example import for consumers using the API in this package: * <p> * {@code Import-Package: org.osgi.service.repository; version="[1.0,2.0)"} * <p> * Example import for providers implementing the API in this package: * <p> * {@code Import-Package: org.osgi.service.repository; version="[1.0,1.1)"} * * @version $Id$ */ package org.apache.aries.subsystem.core.repository;
8,537
0
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/capabilityset/SimpleFilter.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.aries.subsystem.core.capabilityset; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.apache.aries.subsystem.core.archive.AttributeFactory; import org.apache.aries.subsystem.core.archive.Parameter; import org.apache.aries.subsystem.core.archive.VersionRangeAttribute; import org.osgi.framework.VersionRange; public class SimpleFilter { public static final int MATCH_ALL = 0; public static final int AND = 1; public static final int OR = 2; public static final int NOT = 3; public static final int EQ = 4; public static final int LTE = 5; public static final int GTE = 6; public static final int SUBSTRING = 7; public static final int PRESENT = 8; public static final int APPROX = 9; private final String m_name; private final Object m_value; private final int m_op; public SimpleFilter(String attr, Object value, int op) { m_name = attr; m_value = value; m_op = op; } public String getName() { return m_name; } public Object getValue() { return m_value; } public int getOperation() { return m_op; } public String toString() { String s = null; switch (m_op) { case AND: s = "(&" + toString((List) m_value) + ")"; break; case OR: s = "(|" + toString((List) m_value) + ")"; break; case NOT: s = "(!" + toString((List) m_value) + ")"; break; case EQ: s = "(" + m_name + "=" + toEncodedString(m_value) + ")"; break; case LTE: s = "(" + m_name + "<=" + toEncodedString(m_value) + ")"; break; case GTE: s = "(" + m_name + ">=" + toEncodedString(m_value) + ")"; break; case SUBSTRING: s = "(" + m_name + "=" + unparseSubstring((List<String>) m_value) + ")"; break; case PRESENT: s = "(" + m_name + "=*)"; break; case APPROX: s = "(" + m_name + "~=" + toEncodedString(m_value) + ")"; break; case MATCH_ALL: s = "(*)"; break; } return s; } private static String toString(List list) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < list.size(); i++) { sb.append(list.get(i).toString()); } return sb.toString(); } private static String toDecodedString(String s, int startIdx, int endIdx) { StringBuffer sb = new StringBuffer(endIdx - startIdx); boolean escaped = false; for (int i = 0; i < (endIdx - startIdx); i++) { char c = s.charAt(startIdx + i); if (!escaped && (c == '\\')) { escaped = true; } else { escaped = false; sb.append(c); } } return sb.toString(); } private static String toEncodedString(Object o) { if (o instanceof String) { String s = (String) o; StringBuffer sb = new StringBuffer(); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if ((c == '\\') || (c == '(') || (c == ')') || (c == '*')) { sb.append('\\'); } sb.append(c); } o = sb.toString(); } return o.toString(); } public static SimpleFilter parse(String filter) { int idx = skipWhitespace(filter, 0); if ((filter == null) || (filter.length() == 0) || (idx >= filter.length())) { throw new IllegalArgumentException("Null or empty filter."); } else if (filter.charAt(idx) != '(') { throw new IllegalArgumentException("Missing opening parenthesis: " + filter); } SimpleFilter sf = null; List stack = new ArrayList(); boolean isEscaped = false; while (idx < filter.length()) { if (sf != null) { throw new IllegalArgumentException( "Only one top-level operation allowed: " + filter); } if (!isEscaped && (filter.charAt(idx) == '(')) { // Skip paren and following whitespace. idx = skipWhitespace(filter, idx + 1); if (filter.charAt(idx) == '&') { int peek = skipWhitespace(filter, idx + 1); if (filter.charAt(peek) == '(') { idx = peek - 1; stack.add(0, new SimpleFilter(null, new ArrayList(), SimpleFilter.AND)); } else { stack.add(0, new Integer(idx)); } } else if (filter.charAt(idx) == '|') { int peek = skipWhitespace(filter, idx + 1); if (filter.charAt(peek) == '(') { idx = peek - 1; stack.add(0, new SimpleFilter(null, new ArrayList(), SimpleFilter.OR)); } else { stack.add(0, new Integer(idx)); } } else if (filter.charAt(idx) == '!') { int peek = skipWhitespace(filter, idx + 1); if (filter.charAt(peek) == '(') { idx = peek - 1; stack.add(0, new SimpleFilter(null, new ArrayList(), SimpleFilter.NOT)); } else { stack.add(0, new Integer(idx)); } } else { stack.add(0, new Integer(idx)); } } else if (!isEscaped && (filter.charAt(idx) == ')')) { Object top = stack.remove(0); if (top instanceof SimpleFilter) { if (!stack.isEmpty() && (stack.get(0) instanceof SimpleFilter)) { ((List) ((SimpleFilter) stack.get(0)).m_value).add(top); } else { sf = (SimpleFilter) top; } } else if (!stack.isEmpty() && (stack.get(0) instanceof SimpleFilter)) { ((List) ((SimpleFilter) stack.get(0)).m_value).add( SimpleFilter.subfilter(filter, ((Integer) top).intValue(), idx)); } else { sf = SimpleFilter.subfilter(filter, ((Integer) top).intValue(), idx); } } else if (!isEscaped && (filter.charAt(idx) == '\\')) { isEscaped = true; } else { isEscaped = false; } idx = skipWhitespace(filter, idx + 1); } if (sf == null) { throw new IllegalArgumentException("Missing closing parenthesis: " + filter); } return sf; } private static SimpleFilter subfilter(String filter, int startIdx, int endIdx) { final String opChars = "=<>~"; // Determine the ending index of the attribute name. int attrEndIdx = startIdx; for (int i = 0; i < (endIdx - startIdx); i++) { char c = filter.charAt(startIdx + i); if (opChars.indexOf(c) >= 0) { break; } else if (!Character.isWhitespace(c)) { attrEndIdx = startIdx + i + 1; } } if (attrEndIdx == startIdx) { throw new IllegalArgumentException( "Missing attribute name: " + filter.substring(startIdx, endIdx)); } String attr = filter.substring(startIdx, attrEndIdx); // Skip the attribute name and any following whitespace. startIdx = skipWhitespace(filter, attrEndIdx); // Determine the operator type. int op = -1; switch (filter.charAt(startIdx)) { case '=': op = EQ; startIdx++; break; case '<': if (filter.charAt(startIdx + 1) != '=') { throw new IllegalArgumentException( "Unknown operator: " + filter.substring(startIdx, endIdx)); } op = LTE; startIdx += 2; break; case '>': if (filter.charAt(startIdx + 1) != '=') { throw new IllegalArgumentException( "Unknown operator: " + filter.substring(startIdx, endIdx)); } op = GTE; startIdx += 2; break; case '~': if (filter.charAt(startIdx + 1) != '=') { throw new IllegalArgumentException( "Unknown operator: " + filter.substring(startIdx, endIdx)); } op = APPROX; startIdx += 2; break; default: throw new IllegalArgumentException( "Unknown operator: " + filter.substring(startIdx, endIdx)); } // Parse value. Object value = toDecodedString(filter, startIdx, endIdx); // Check if the equality comparison is actually a substring // or present operation. if (op == EQ) { String valueStr = filter.substring(startIdx, endIdx); List<String> values = parseSubstring(valueStr); if ((values.size() == 2) && (values.get(0).length() == 0) && (values.get(1).length() == 0)) { op = PRESENT; } else if (values.size() > 1) { op = SUBSTRING; value = values; } } return new SimpleFilter(attr, value, op); } public static List<String> parseSubstring(String value) { List<String> pieces = new ArrayList(); StringBuffer ss = new StringBuffer(); // int kind = SIMPLE; // assume until proven otherwise boolean wasStar = false; // indicates last piece was a star boolean leftstar = false; // track if the initial piece is a star boolean rightstar = false; // track if the final piece is a star int idx = 0; // We assume (sub)strings can contain leading and trailing blanks boolean escaped = false; loop: for (;;) { if (idx >= value.length()) { if (wasStar) { // insert last piece as "" to handle trailing star rightstar = true; } else { pieces.add(ss.toString()); // accumulate the last piece // note that in the case of // (cn=); this might be // the string "" (!=null) } ss.setLength(0); break loop; } // Read the next character and account for escapes. char c = value.charAt(idx++); if (!escaped && (c == '*')) { // If we have successive '*' characters, then we can // effectively collapse them by ignoring succeeding ones. if (!wasStar) { if (ss.length() > 0) { pieces.add(ss.toString()); // accumulate the pieces // between '*' occurrences } ss.setLength(0); // if this is a leading star, then track it if (pieces.isEmpty()) { leftstar = true; } wasStar = true; } } else if (!escaped && (c == '\\')) { escaped = true; } else { escaped = false; wasStar = false; ss.append(c); } } if (leftstar || rightstar || pieces.size() > 1) { // insert leading and/or trailing "" to anchor ends if (rightstar) { pieces.add(""); } if (leftstar) { pieces.add(0, ""); } } return pieces; } public static String unparseSubstring(List<String> pieces) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < pieces.size(); i++) { if (i > 0) { sb.append("*"); } sb.append(toEncodedString(pieces.get(i))); } return sb.toString(); } public static boolean compareSubstring(List<String> pieces, String s) { // Walk the pieces to match the string // There are implicit stars between each piece, // and the first and last pieces might be "" to anchor the match. // assert (pieces.length > 1) // minimal case is <string>*<string> boolean result = true; int len = pieces.size(); // Special case, if there is only one piece, then // we must perform an equality test. if (len == 1) { return s.equals(pieces.get(0)); } // Otherwise, check whether the pieces match // the specified string. int index = 0; loop: for (int i = 0; i < len; i++) { String piece = pieces.get(i); // If this is the first piece, then make sure the // string starts with it. if (i == 0) { if (!s.startsWith(piece)) { result = false; break loop; } } // If this is the last piece, then make sure the // string ends with it. if (i == (len - 1)) { if (s.endsWith(piece) && (s.length() >= (index + piece.length()))) { result = true; } else { result = false; } break loop; } // If this is neither the first or last piece, then // make sure the string contains it. if ((i > 0) && (i < (len - 1))) { index = s.indexOf(piece, index); if (index < 0) { result = false; break loop; } } // Move string index beyond the matching piece. index += piece.length(); } return result; } private static int skipWhitespace(String s, int startIdx) { int len = s.length(); while ((startIdx < len) && Character.isWhitespace(s.charAt(startIdx))) { startIdx++; } return startIdx; } /** * Converts a attribute map to a filter. The filter is created by iterating * over the map's entry set. If ordering of attributes is important (e.g., * for hitting attribute indices), then the map's entry set should iterate * in the desired order. Equality testing is assumed for all attribute types * other than version ranges, which are handled appropriated. If the attribute * map is empty, then a filter that matches anything is returned. * @param attrs Map of attributes to convert to a filter. * @return A filter corresponding to the attributes. */ public static SimpleFilter convert(Map<String, Object> attrs) { // Rather than building a filter string to be parsed into a SimpleFilter, // we will just create the parsed SimpleFilter directly. List<SimpleFilter> filters = new ArrayList<SimpleFilter>(); for (Entry<String, Object> entry : attrs.entrySet()) { if (entry.getValue() instanceof VersionRange) { VersionRange vr = (VersionRange) entry.getValue(); if (vr.getLeftType() == VersionRange.RIGHT_OPEN) { filters.add( new SimpleFilter( entry.getKey(), vr.getLeft().toString(), SimpleFilter.GTE)); } else { SimpleFilter not = new SimpleFilter(null, new ArrayList(), SimpleFilter.NOT); ((List) not.getValue()).add( new SimpleFilter( entry.getKey(), vr.getLeft().toString(), SimpleFilter.LTE)); filters.add(not); } if (vr.getRight() != null) { if (vr.getRightType() == VersionRange.RIGHT_OPEN) { filters.add( new SimpleFilter( entry.getKey(), vr.getRight().toString(), SimpleFilter.LTE)); } else { SimpleFilter not = new SimpleFilter(null, new ArrayList(), SimpleFilter.NOT); ((List) not.getValue()).add( new SimpleFilter( entry.getKey(), vr.getRight().toString(), SimpleFilter.GTE)); filters.add(not); } } } else { List<String> values = SimpleFilter.parseSubstring(entry.getValue().toString()); if (values.size() > 1) { filters.add( new SimpleFilter( entry.getKey(), values, SimpleFilter.SUBSTRING)); } else { filters.add( new SimpleFilter( entry.getKey(), values.get(0), SimpleFilter.EQ)); } } } SimpleFilter sf = null; if (filters.size() == 1) { sf = filters.get(0); } else if (attrs.size() > 1) { sf = new SimpleFilter(null, filters, SimpleFilter.AND); } else if (filters.isEmpty()) { sf = new SimpleFilter(null, null, SimpleFilter.MATCH_ALL); } return sf; } @Override public int hashCode() { int result = 17; result = 31 * result + (m_name == null ? 0 : m_name.hashCode()); result = 31 * result + m_op; if (m_value == null) { result = 31 * result + 0; } else if (m_name == null && m_value instanceof Collection) { Iterator iterator = ((Collection)m_value).iterator(); int sum = 0; while (iterator.hasNext()) { sum += iterator.next().hashCode(); } result = 31 * result + sum; } else { result = 31 * result + m_value.hashCode(); } return result; } @Override public boolean equals(Object o) { if (o == this) { return true; } if (!(o instanceof SimpleFilter)) { return false; } SimpleFilter that = (SimpleFilter)o; if (!(that.m_name == null ? this.m_name == null : that.m_name.equals(this.m_name))) { return false; } if (that.m_op != this.m_op) { return false; } if (that.m_value == null) { return this.m_value == null; } if (this.m_value == null) { return false; } if (that.m_name == null && that.m_value instanceof Collection) { if (!(this.m_name == null && this.m_value instanceof Collection)) { return false; } return ((Collection)that.m_value).containsAll((Collection)this.m_value); } return that.m_value.equals(this.m_value); } public static Map<String, List<SimpleFilter>> attributes(String filter) { Map<String, List<SimpleFilter>> attributes = new HashMap<String, List<SimpleFilter>>(); attributes(parse(filter), attributes); return attributes; } private static void attributes(SimpleFilter filter, Map<String, List<SimpleFilter>> attributes) { if (filter.m_op == NOT && ((List<SimpleFilter>)filter.m_value).size() == 1) { SimpleFilter sf = ((List<SimpleFilter>)filter.m_value).get(0); List<SimpleFilter> sfs = attributes.get(sf.m_name); if (sfs == null) { sfs = new ArrayList<SimpleFilter>(); attributes.put(sf.m_name, sfs); } sfs.add(filter); } else if (filter.m_value instanceof Collection) { Collection<SimpleFilter> filters = (Collection<SimpleFilter>)filter.m_value; for (SimpleFilter f : filters) { attributes(f, attributes); } } else { List<SimpleFilter> sfs = attributes.get(filter.m_name); if (sfs == null) { sfs = new ArrayList<SimpleFilter>(); attributes.put(filter.m_name, sfs); } sfs.add(filter); } } }
8,538
0
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/capabilityset/CapabilitySetRepository.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.aries.subsystem.core.capabilityset; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Set; import org.apache.aries.subsystem.core.repository.Repository; import org.osgi.framework.namespace.BundleNamespace; import org.osgi.framework.namespace.ExecutionEnvironmentNamespace; import org.osgi.framework.namespace.HostNamespace; import org.osgi.framework.namespace.IdentityNamespace; import org.osgi.framework.namespace.NativeNamespace; import org.osgi.framework.namespace.PackageNamespace; import org.osgi.namespace.service.ServiceNamespace; import org.osgi.resource.Capability; import org.osgi.resource.Namespace; import org.osgi.resource.Requirement; import org.osgi.resource.Resource; public class CapabilitySetRepository implements Repository { private final Map<String, CapabilitySet> namespace2capabilitySet; public CapabilitySetRepository() { namespace2capabilitySet = Collections.synchronizedMap(new HashMap<String, CapabilitySet>()); namespace2capabilitySet.put( IdentityNamespace.IDENTITY_NAMESPACE, new CapabilitySet(Arrays.asList(IdentityNamespace.IDENTITY_NAMESPACE), true)); namespace2capabilitySet.put( NativeNamespace.NATIVE_NAMESPACE, new CapabilitySet(Arrays.asList(NativeNamespace.NATIVE_NAMESPACE), true)); namespace2capabilitySet.put( ExecutionEnvironmentNamespace.EXECUTION_ENVIRONMENT_NAMESPACE, new CapabilitySet(Arrays.asList(ExecutionEnvironmentNamespace.EXECUTION_ENVIRONMENT_NAMESPACE), true)); namespace2capabilitySet.put( BundleNamespace.BUNDLE_NAMESPACE, new CapabilitySet(Arrays.asList(BundleNamespace.BUNDLE_NAMESPACE), true)); namespace2capabilitySet.put( HostNamespace.HOST_NAMESPACE, new CapabilitySet(Arrays.asList(HostNamespace.HOST_NAMESPACE), true)); namespace2capabilitySet.put( PackageNamespace.PACKAGE_NAMESPACE, new CapabilitySet(Arrays.asList(PackageNamespace.PACKAGE_NAMESPACE), true)); namespace2capabilitySet.put( ServiceNamespace.SERVICE_NAMESPACE, new CapabilitySet(Arrays.asList(ServiceNamespace.CAPABILITY_OBJECTCLASS_ATTRIBUTE), true)); } public void addResource(Resource resource) { for (Capability capability : resource.getCapabilities(null)) { String namespace = capability.getNamespace(); CapabilitySet capabilitySet; synchronized (namespace2capabilitySet) { capabilitySet = namespace2capabilitySet.get(namespace); if (capabilitySet == null) { capabilitySet = new CapabilitySet(Arrays.asList(namespace), true); namespace2capabilitySet.put(namespace, capabilitySet); } } // TODO Examine CapabilitySet for thread safety. capabilitySet.addCapability(capability); } } @Override public Map<Requirement, Collection<Capability>> findProviders(Collection<? extends Requirement> requirements) { Map<Requirement, Collection<Capability>> result = new HashMap<Requirement, Collection<Capability>>(requirements.size()); for (Requirement requirement : requirements) { String filterDirective = requirement.getDirectives().get(Namespace.REQUIREMENT_FILTER_DIRECTIVE); SimpleFilter simpleFilter; if (filterDirective == null) { simpleFilter = new SimpleFilter(null, null, SimpleFilter.MATCH_ALL); } else { simpleFilter = SimpleFilter.parse(filterDirective); } String namespace = requirement.getNamespace(); CapabilitySet capabilitySet = namespace2capabilitySet.get(namespace); if (capabilitySet != null) { Set<Capability> capabilities = capabilitySet.match( simpleFilter, PackageNamespace.PACKAGE_NAMESPACE.equals(namespace) || BundleNamespace.BUNDLE_NAMESPACE.equals(namespace) || HostNamespace.HOST_NAMESPACE.equals(namespace)); result.put(requirement, capabilities); } else { result.put(requirement, Collections.<Capability>emptyList()); } } return result; } public void removeResource(Resource resource) { for (Capability capability : resource.getCapabilities(null)) { CapabilitySet capabilitySet = namespace2capabilitySet.get(capability.getNamespace()); if (capabilitySet == null) { continue; } // TODO Examine CapabilitySet for thread safety. capabilitySet.removeCapability(capability); } } }
8,539
0
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/capabilityset/SecureAction.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.aries.subsystem.core.capabilityset; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.AccessibleObject; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.net.MalformedURLException; import java.net.URI; import java.net.URL; import java.net.URLClassLoader; import java.net.URLConnection; import java.net.URLStreamHandler; import java.security.AccessControlContext; import java.security.AccessController; import java.security.Policy; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import java.util.Collection; import java.util.HashMap; import java.util.Hashtable; import java.util.Map; import java.util.jar.JarFile; import java.util.zip.ZipFile; import org.osgi.framework.Bundle; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; import org.osgi.framework.BundleEvent; import org.osgi.framework.ServiceEvent; import org.osgi.framework.ServiceReference; import org.osgi.framework.hooks.resolver.ResolverHook; import org.osgi.framework.hooks.service.ListenerHook; import org.osgi.framework.wiring.BundleCapability; import org.osgi.framework.wiring.BundleRequirement; import org.osgi.framework.wiring.BundleRevision; /** * <p> * This is a utility class to centralize all action that should be performed * in a <tt>doPrivileged()</tt> block. To perform a secure action, simply * create an instance of this class and use the specific method to perform * the desired action. When an instance is created, this class will capture * the security context and will then use that context when checking for * permission to perform the action. Instances of this class should not be * passed around since they may grant the receiver a capability to perform * privileged actions. * </p> **/ public class SecureAction { private static final ThreadLocal m_actions = new ThreadLocal() { public Object initialValue() { return new Actions(); } }; protected static transient int BUFSIZE = 4096; private AccessControlContext m_acc = null; public SecureAction() { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.INITIALIZE_CONTEXT_ACTION, null); m_acc = (AccessControlContext) AccessController.doPrivileged(actions); } catch (PrivilegedActionException ex) { throw (RuntimeException) ex.getException(); } } else { m_acc = AccessController.getContext(); } } public String getSystemProperty(String name, String def) { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.GET_PROPERTY_ACTION, name, def); return (String) AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException ex) { throw (RuntimeException) ex.getException(); } } else { return System.getProperty(name, def); } } public ClassLoader getParentClassLoader(ClassLoader loader) { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.GET_PARENT_CLASS_LOADER_ACTION, loader); return (ClassLoader) AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException ex) { throw (RuntimeException) ex.getException(); } } else { return loader.getParent(); } } public ClassLoader getSystemClassLoader() { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.GET_SYSTEM_CLASS_LOADER_ACTION); return (ClassLoader) AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException ex) { throw (RuntimeException) ex.getException(); } } else { return ClassLoader.getSystemClassLoader(); } } public ClassLoader getClassLoader(Class clazz) { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.GET_CLASS_LOADER_ACTION, clazz); return (ClassLoader) AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException ex) { throw (RuntimeException) ex.getException(); } } else { return clazz.getClassLoader(); } } public Class forName(String name, ClassLoader classloader) throws ClassNotFoundException { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.FOR_NAME_ACTION, name, classloader); return (Class) AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException ex) { if (ex.getException() instanceof ClassNotFoundException) { throw (ClassNotFoundException) ex.getException(); } throw (RuntimeException) ex.getException(); } } else if (classloader != null) { return Class.forName(name, true, classloader); } else { return Class.forName(name); } } public URL createURL(String protocol, String host, int port, String path, URLStreamHandler handler) throws MalformedURLException { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.CREATE_URL_ACTION, protocol, host, new Integer(port), path, handler); return (URL) AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException ex) { if (ex.getException() instanceof MalformedURLException) { throw (MalformedURLException) ex.getException(); } throw (RuntimeException) ex.getException(); } } else { return new URL(protocol, host, port, path, handler); } } public URL createURL(URL context, String spec, URLStreamHandler handler) throws MalformedURLException { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.CREATE_URL_WITH_CONTEXT_ACTION, context, spec, handler); return (URL) AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException ex) { if (ex.getException() instanceof MalformedURLException) { throw (MalformedURLException) ex.getException(); } throw (RuntimeException) ex.getException(); } } else { return new URL(context, spec, handler); } } public Process exec(String command) throws IOException { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.EXEC_ACTION, command); return (Process) AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException ex) { throw (RuntimeException) ex.getException(); } } else { return Runtime.getRuntime().exec(command); } } public String getAbsolutePath(File file) { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.GET_ABSOLUTE_PATH_ACTION, file); return (String) AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException ex) { throw (RuntimeException) ex.getException(); } } else { return file.getAbsolutePath(); } } public boolean fileExists(File file) { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.FILE_EXISTS_ACTION, file); return ((Boolean) AccessController.doPrivileged(actions, m_acc)) .booleanValue(); } catch (PrivilegedActionException ex) { throw (RuntimeException) ex.getException(); } } else { return file.exists(); } } public boolean isFileDirectory(File file) { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.FILE_IS_DIRECTORY_ACTION, file); return ((Boolean) AccessController.doPrivileged(actions, m_acc)) .booleanValue(); } catch (PrivilegedActionException ex) { throw (RuntimeException) ex.getException(); } } else { return file.isDirectory(); } } public boolean mkdir(File file) { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.MAKE_DIRECTORY_ACTION, file); return ((Boolean) AccessController.doPrivileged(actions, m_acc)) .booleanValue(); } catch (PrivilegedActionException ex) { throw (RuntimeException) ex.getException(); } } else { return file.mkdir(); } } public boolean mkdirs(File file) { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.MAKE_DIRECTORIES_ACTION, file); return ((Boolean) AccessController.doPrivileged(actions, m_acc)) .booleanValue(); } catch (PrivilegedActionException ex) { throw (RuntimeException) ex.getException(); } } else { return file.mkdirs(); } } public File[] listDirectory(File file) { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.LIST_DIRECTORY_ACTION, file); return (File[]) AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException ex) { throw (RuntimeException) ex.getException(); } } else { return file.listFiles(); } } public boolean renameFile(File oldFile, File newFile) { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.RENAME_FILE_ACTION, oldFile, newFile); return ((Boolean) AccessController.doPrivileged(actions, m_acc)) .booleanValue(); } catch (PrivilegedActionException ex) { throw (RuntimeException) ex.getException(); } } else { return oldFile.renameTo(newFile); } } public FileInputStream getFileInputStream(File file) throws IOException { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.GET_FILE_INPUT_ACTION, file); return (FileInputStream) AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException ex) { if (ex.getException() instanceof IOException) { throw (IOException) ex.getException(); } throw (RuntimeException) ex.getException(); } } else { return new FileInputStream(file); } } public FileOutputStream getFileOutputStream(File file) throws IOException { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.GET_FILE_OUTPUT_ACTION, file); return (FileOutputStream) AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException ex) { if (ex.getException() instanceof IOException) { throw (IOException) ex.getException(); } throw (RuntimeException) ex.getException(); } } else { return new FileOutputStream(file); } } public URI toURI(File file) { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.TO_URI_ACTION, file); return (URI) AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException ex) { throw (RuntimeException) ex.getException(); } } else { return file.toURI(); } } public InputStream getURLConnectionInputStream(URLConnection conn) throws IOException { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.GET_URL_INPUT_ACTION, conn); return (InputStream) AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException ex) { if (ex.getException() instanceof IOException) { throw (IOException) ex.getException(); } throw (RuntimeException) ex.getException(); } } else { return conn.getInputStream(); } } public boolean deleteFile(File target) { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.DELETE_FILE_ACTION, target); return ((Boolean) AccessController.doPrivileged(actions, m_acc)) .booleanValue(); } catch (PrivilegedActionException ex) { throw (RuntimeException) ex.getException(); } } else { return target.delete(); } } public File createTempFile(String prefix, String suffix, File dir) throws IOException { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.CREATE_TMPFILE_ACTION, prefix, suffix, dir); return (File) AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException ex) { if (ex.getException() instanceof IOException) { throw (IOException) ex.getException(); } throw (RuntimeException) ex.getException(); } } else { return File.createTempFile(prefix, suffix, dir); } } public void deleteFileOnExit(File file) throws IOException { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.DELETE_FILEONEXIT_ACTION, file); AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException ex) { if (ex.getException() instanceof IOException) { throw (IOException) ex.getException(); } throw (RuntimeException) ex.getException(); } } else { file.deleteOnExit(); } } public URLConnection openURLConnection(URL url) throws IOException { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.OPEN_URLCONNECTION_ACTION, url); return (URLConnection) AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException ex) { if (ex.getException() instanceof IOException) { throw (IOException) ex.getException(); } throw (RuntimeException) ex.getException(); } } else { return url.openConnection(); } } public ZipFile openZipFile(File file) throws IOException { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.OPEN_ZIPFILE_ACTION, file); return (ZipFile) AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException ex) { if (ex.getException() instanceof IOException) { throw (IOException) ex.getException(); } throw (RuntimeException) ex.getException(); } } else { return new ZipFile(file); } } public JarFile openJarFile(File file) throws IOException { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.OPEN_JARFILE_ACTION, file); return (JarFile) AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException ex) { if (ex.getException() instanceof IOException) { throw (IOException) ex.getException(); } throw (RuntimeException) ex.getException(); } } else { return new JarFile(file); } } public void startActivator(BundleActivator activator, BundleContext context) throws Exception { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.START_ACTIVATOR_ACTION, activator, context); AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException ex) { throw ex.getException(); } } else { activator.start(context); } } public void stopActivator(BundleActivator activator, BundleContext context) throws Exception { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.STOP_ACTIVATOR_ACTION, activator, context); AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException ex) { throw ex.getException(); } } else { activator.stop(context); } } public Policy getPolicy() { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.GET_POLICY_ACTION, null); return (Policy) AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException ex) { throw (RuntimeException) ex.getException(); } } else { return Policy.getPolicy(); } } public void addURLToURLClassLoader(URL extension, ClassLoader loader) throws Exception { if (System.getSecurityManager() != null) { Actions actions = (Actions) m_actions.get(); actions.set(Actions.ADD_EXTENSION_URL_ACTION, extension, loader); try { AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException e) { throw e.getException(); } } else { Method addURL = URLClassLoader.class.getDeclaredMethod("addURL", new Class[] {URL.class}); addURL.setAccessible(true); addURL.invoke(loader, new Object[]{extension}); } } public Constructor getConstructor(Class target, Class[] types) throws Exception { if (System.getSecurityManager() != null) { Actions actions = (Actions) m_actions.get(); actions.set(Actions.GET_CONSTRUCTOR_ACTION, target, types); try { return (Constructor) AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException e) { throw e.getException(); } } else { return target.getConstructor(types); } } public Constructor getDeclaredConstructor(Class target, Class[] types) throws Exception { if (System.getSecurityManager() != null) { Actions actions = (Actions) m_actions.get(); actions.set(Actions.GET_DECLARED_CONSTRUCTOR_ACTION, target, types); try { return (Constructor) AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException e) { throw e.getException(); } } else { return target.getDeclaredConstructor(types); } } public Method getMethod(Class target, String method, Class[] types) throws Exception { if (System.getSecurityManager() != null) { Actions actions = (Actions) m_actions.get(); actions.set(Actions.GET_METHOD_ACTION, target, method, types); try { return (Method) AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException e) { throw e.getException(); } } else { return target.getMethod(method, types); } } public Method getDeclaredMethod(Class target, String method, Class[] types) throws Exception { if (System.getSecurityManager() != null) { Actions actions = (Actions) m_actions.get(); actions.set(Actions.GET_DECLARED_METHOD_ACTION, target, method, types); try { return (Method) AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException e) { throw e.getException(); } } else { return target.getDeclaredMethod(method, types); } } public void setAccesssible(AccessibleObject ao) { if (System.getSecurityManager() != null) { Actions actions = (Actions) m_actions.get(); actions.set(Actions.SET_ACCESSIBLE_ACTION, ao); try { AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException e) { throw (RuntimeException) e.getException(); } } else { ao.setAccessible(true); } } public Object invoke(Method method, Object target, Object[] params) throws Exception { if (System.getSecurityManager() != null) { Actions actions = (Actions) m_actions.get(); actions.set(Actions.INVOKE_METHOD_ACTION, method, target, params); try { return AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException e) { throw e.getException(); } } else { method.setAccessible(true); return method.invoke(target, params); } } public Object invokeDirect(Method method, Object target, Object[] params) throws Exception { if (System.getSecurityManager() != null) { Actions actions = (Actions) m_actions.get(); actions.set(Actions.INVOKE_DIRECTMETHOD_ACTION, method, target, params); try { return AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException e) { throw e.getException(); } } else { return method.invoke(target, params); } } public Object invoke(Constructor constructor, Object[] params) throws Exception { if (System.getSecurityManager() != null) { Actions actions = (Actions) m_actions.get(); actions.set(Actions.INVOKE_CONSTRUCTOR_ACTION, constructor, params); try { return AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException e) { throw e.getException(); } } else { return constructor.newInstance(params); } } public Object getDeclaredField(Class targetClass, String name, Object target) throws Exception { if (System.getSecurityManager() != null) { Actions actions = (Actions) m_actions.get(); actions.set(Actions.GET_FIELD_ACTION, targetClass, name, target); try { return AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException e) { throw e.getException(); } } else { Field field = targetClass.getDeclaredField(name); field.setAccessible(true); return field.get(target); } } public Object swapStaticFieldIfNotClass(Class targetClazz, Class targetType, Class condition, String lockName) throws Exception { if (System.getSecurityManager() != null) { Actions actions = (Actions) m_actions.get(); actions.set(Actions.SWAP_FIELD_ACTION, targetClazz, targetType, condition, lockName); try { return AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException e) { throw e.getException(); } } else { return _swapStaticFieldIfNotClass(targetClazz, targetType, condition, lockName); } } private static Object _swapStaticFieldIfNotClass(Class targetClazz, Class targetType, Class condition, String lockName) throws Exception { Object lock = null; if (lockName != null) { try { Field lockField = targetClazz.getDeclaredField(lockName); lockField.setAccessible(true); lock = lockField.get(null); } catch (NoSuchFieldException ex) { } } if (lock == null) { lock = targetClazz; } synchronized (lock) { Field[] fields = targetClazz.getDeclaredFields(); Object result = null; for (int i = 0; (i < fields.length) && (result == null); i++) { if (Modifier.isStatic(fields[i].getModifiers()) && (fields[i].getType() == targetType)) { fields[i].setAccessible(true); result = fields[i].get(null); if (result != null) { if ((condition == null) || !result.getClass().getName().equals(condition.getName())) { fields[i].set(null, null); } } } } if (result != null) { if ((condition == null) || !result.getClass().getName().equals(condition.getName())) { // reset cache for (int i = 0; i < fields.length; i++) { if (Modifier.isStatic(fields[i].getModifiers()) && (fields[i].getType() == Hashtable.class)) { fields[i].setAccessible(true); Hashtable cache = (Hashtable) fields[i].get(null); if (cache != null) { cache.clear(); } } } } return result; } } return null; } public void flush(Class targetClazz, Object lock) throws Exception { if (System.getSecurityManager() != null) { Actions actions = (Actions) m_actions.get(); actions.set(Actions.FLUSH_FIELD_ACTION, targetClazz, lock); try { AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException e) { throw e.getException(); } } else { _flush(targetClazz, lock); } } private static void _flush(Class targetClazz, Object lock) throws Exception { synchronized (lock) { Field[] fields = targetClazz.getDeclaredFields(); // reset cache for (int i = 0; i < fields.length; i++) { if (Modifier.isStatic(fields[i].getModifiers()) && ((fields[i].getType() == Hashtable.class) || (fields[i].getType() == HashMap.class))) { fields[i].setAccessible(true); if (fields[i].getType() == Hashtable.class) { Hashtable cache = (Hashtable) fields[i].get(null); if (cache != null) { cache.clear(); } } else { HashMap cache = (HashMap) fields[i].get(null); if (cache != null) { cache.clear(); } } } } } } public void invokeBundleCollisionHook( org.osgi.framework.hooks.bundle.CollisionHook ch, int operationType, Bundle targetBundle, Collection<Bundle> collisionCandidates) throws Exception { if (System.getSecurityManager() != null) { Actions actions = (Actions) m_actions.get(); actions.set(Actions.INVOKE_BUNDLE_COLLISION_HOOK, ch, operationType, targetBundle, collisionCandidates); try { AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException e) { throw e.getException(); } } else { ch.filterCollisions(operationType, targetBundle, collisionCandidates); } } public void invokeBundleFindHook( org.osgi.framework.hooks.bundle.FindHook fh, BundleContext bc, Collection<Bundle> bundles) throws Exception { if (System.getSecurityManager() != null) { Actions actions = (Actions) m_actions.get(); actions.set(Actions.INVOKE_BUNDLE_FIND_HOOK, fh, bc, bundles); try { AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException e) { throw e.getException(); } } else { fh.find(bc, bundles); } } public void invokeBundleEventHook( org.osgi.framework.hooks.bundle.EventHook eh, BundleEvent event, Collection<BundleContext> contexts) throws Exception { if (System.getSecurityManager() != null) { Actions actions = (Actions) m_actions.get(); actions.set(Actions.INVOKE_BUNDLE_EVENT_HOOK, eh, event, contexts); try { AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException e) { throw e.getException(); } } else { eh.event(event, contexts); } } public void invokeWeavingHook( org.osgi.framework.hooks.weaving.WeavingHook wh, org.osgi.framework.hooks.weaving.WovenClass wc) throws Exception { if (System.getSecurityManager() != null) { Actions actions = (Actions) m_actions.get(); actions.set(Actions.INVOKE_WEAVING_HOOK, wh, wc); try { AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException e) { throw e.getException(); } } else { wh.weave(wc); } } public void invokeServiceEventHook( org.osgi.framework.hooks.service.EventHook eh, ServiceEvent event, Collection<BundleContext> contexts) throws Exception { if (System.getSecurityManager() != null) { Actions actions = (Actions) m_actions.get(); actions.set(Actions.INVOKE_SERVICE_EVENT_HOOK, eh, event, contexts); try { AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException e) { throw e.getException(); } } else { eh.event(event, contexts); } } public void invokeServiceFindHook( org.osgi.framework.hooks.service.FindHook fh, BundleContext context, String name, String filter, boolean allServices, Collection<ServiceReference<?>> references) throws Exception { if (System.getSecurityManager() != null) { Actions actions = (Actions) m_actions.get(); actions.set( Actions.INVOKE_SERVICE_FIND_HOOK, fh, context, name, filter, (allServices) ? Boolean.TRUE : Boolean.FALSE, references); try { AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException e) { throw e.getException(); } } else { fh.find(context, name, filter, allServices, references); } } public void invokeServiceListenerHookAdded( org.osgi.framework.hooks.service.ListenerHook lh, Collection<ListenerHook.ListenerInfo> listeners) throws Exception { if (System.getSecurityManager() != null) { Actions actions = (Actions) m_actions.get(); actions.set(Actions.INVOKE_SERVICE_LISTENER_HOOK_ADDED, lh, listeners); try { AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException e) { throw e.getException(); } } else { lh.added(listeners); } } public void invokeServiceListenerHookRemoved( org.osgi.framework.hooks.service.ListenerHook lh, Collection<ListenerHook.ListenerInfo> listeners) throws Exception { if (System.getSecurityManager() != null) { Actions actions = (Actions) m_actions.get(); actions.set(Actions.INVOKE_SERVICE_LISTENER_HOOK_REMOVED, lh, listeners); try { AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException e) { throw e.getException(); } } else { lh.removed(listeners); } } public void invokeServiceEventListenerHook( org.osgi.framework.hooks.service.EventListenerHook elh, ServiceEvent event, Map<BundleContext, Collection<ListenerHook.ListenerInfo>> listeners) throws Exception { if (System.getSecurityManager() != null) { Actions actions = (Actions) m_actions.get(); actions.set(Actions.INVOKE_SERVICE_EVENT_LISTENER_HOOK, elh, event, listeners); try { AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException e) { throw e.getException(); } } else { elh.event(event, listeners); } } public ResolverHook invokeResolverHookFactory( org.osgi.framework.hooks.resolver.ResolverHookFactory rhf, Collection<BundleRevision> triggers) throws Exception { if (System.getSecurityManager() != null) { Actions actions = (Actions) m_actions.get(); actions.set(Actions.INVOKE_RESOLVER_HOOK_FACTORY, rhf, triggers); try { return (ResolverHook) AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException e) { throw e.getException(); } } else { return rhf.begin(triggers); } } public void invokeResolverHookResolvable( org.osgi.framework.hooks.resolver.ResolverHook rh, Collection<BundleRevision> candidates) throws Exception { if (System.getSecurityManager() != null) { Actions actions = (Actions) m_actions.get(); actions.set(Actions.INVOKE_RESOLVER_HOOK_RESOLVABLE, rh, candidates); try { AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException e) { throw e.getException(); } } else { rh.filterResolvable(candidates); } } public void invokeResolverHookSingleton( org.osgi.framework.hooks.resolver.ResolverHook rh, BundleCapability singleton, Collection<BundleCapability> collisions) throws Exception { if (System.getSecurityManager() != null) { Actions actions = (Actions) m_actions.get(); actions.set(Actions.INVOKE_RESOLVER_HOOK_SINGLETON, rh, singleton, collisions); try { AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException e) { throw e.getException(); } } else { rh.filterSingletonCollisions(singleton, collisions); } } public void invokeResolverHookMatches( org.osgi.framework.hooks.resolver.ResolverHook rh, BundleRequirement req, Collection<BundleCapability> candidates) throws Exception { if (System.getSecurityManager() != null) { Actions actions = (Actions) m_actions.get(); actions.set(Actions.INVOKE_RESOLVER_HOOK_MATCHES, rh, req, candidates); try { AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException e) { throw e.getException(); } } else { rh.filterMatches(req, candidates); } } public void invokeResolverHookEnd( org.osgi.framework.hooks.resolver.ResolverHook rh) throws Exception { if (System.getSecurityManager() != null) { Actions actions = (Actions) m_actions.get(); actions.set(Actions.INVOKE_RESOLVER_HOOK_END, rh); try { AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException e) { throw e.getException(); } } else { rh.end(); } } public void invokeWovenClassListener( org.osgi.framework.hooks.weaving.WovenClassListener wcl, org.osgi.framework.hooks.weaving.WovenClass wc) throws Exception { if (System.getSecurityManager() != null) { Actions actions = (Actions) m_actions.get(); actions.set(Actions.INVOKE_WOVEN_CLASS_LISTENER, wcl, wc); try { AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException e) { throw e.getException(); } } else { wcl.modified(wc); } } private static class Actions implements PrivilegedExceptionAction { public static final int INITIALIZE_CONTEXT_ACTION = 0; public static final int ADD_EXTENSION_URL_ACTION = 1; public static final int CREATE_TMPFILE_ACTION = 2; public static final int CREATE_URL_ACTION = 3; public static final int CREATE_URL_WITH_CONTEXT_ACTION = 4; public static final int DELETE_FILE_ACTION = 5; public static final int EXEC_ACTION = 6; public static final int FILE_EXISTS_ACTION = 7; public static final int FILE_IS_DIRECTORY_ACTION = 8; public static final int FOR_NAME_ACTION = 9; public static final int GET_ABSOLUTE_PATH_ACTION = 10; public static final int GET_CONSTRUCTOR_ACTION = 11; public static final int GET_DECLARED_CONSTRUCTOR_ACTION = 12; public static final int GET_DECLARED_METHOD_ACTION = 13; public static final int GET_FIELD_ACTION = 14; public static final int GET_FILE_INPUT_ACTION = 15; public static final int GET_FILE_OUTPUT_ACTION = 16; public static final int TO_URI_ACTION = 17; public static final int GET_METHOD_ACTION = 18; public static final int GET_POLICY_ACTION = 19; public static final int GET_PROPERTY_ACTION = 20; public static final int GET_PARENT_CLASS_LOADER_ACTION = 21; public static final int GET_SYSTEM_CLASS_LOADER_ACTION = 22; public static final int GET_URL_INPUT_ACTION = 23; public static final int INVOKE_CONSTRUCTOR_ACTION = 24; public static final int INVOKE_DIRECTMETHOD_ACTION = 25; public static final int INVOKE_METHOD_ACTION = 26; public static final int LIST_DIRECTORY_ACTION = 27; public static final int MAKE_DIRECTORIES_ACTION = 28; public static final int MAKE_DIRECTORY_ACTION = 29; public static final int OPEN_ZIPFILE_ACTION = 30; public static final int OPEN_URLCONNECTION_ACTION = 31; public static final int RENAME_FILE_ACTION = 32; public static final int SET_ACCESSIBLE_ACTION = 33; public static final int START_ACTIVATOR_ACTION = 34; public static final int STOP_ACTIVATOR_ACTION = 35; public static final int SWAP_FIELD_ACTION = 36; public static final int SYSTEM_EXIT_ACTION = 37; public static final int FLUSH_FIELD_ACTION = 38; public static final int GET_CLASS_LOADER_ACTION = 39; public static final int INVOKE_BUNDLE_FIND_HOOK = 40; public static final int INVOKE_BUNDLE_EVENT_HOOK = 41; public static final int INVOKE_WEAVING_HOOK = 42; public static final int INVOKE_SERVICE_EVENT_HOOK = 43; public static final int INVOKE_SERVICE_FIND_HOOK = 44; public static final int INVOKE_SERVICE_LISTENER_HOOK_ADDED = 45; public static final int INVOKE_SERVICE_LISTENER_HOOK_REMOVED = 46; public static final int INVOKE_SERVICE_EVENT_LISTENER_HOOK = 47; public static final int INVOKE_RESOLVER_HOOK_FACTORY = 48; public static final int INVOKE_RESOLVER_HOOK_RESOLVABLE = 49; public static final int INVOKE_RESOLVER_HOOK_SINGLETON = 50; public static final int INVOKE_RESOLVER_HOOK_MATCHES = 51; public static final int INVOKE_RESOLVER_HOOK_END = 52; public static final int INVOKE_BUNDLE_COLLISION_HOOK = 53; public static final int OPEN_JARFILE_ACTION = 54; public static final int DELETE_FILEONEXIT_ACTION = 55; public static final int INVOKE_WOVEN_CLASS_LISTENER = 56; private int m_action = -1; private Object m_arg1 = null; private Object m_arg2 = null; private Object m_arg3 = null; private Object m_arg4 = null; private Object m_arg5 = null; private Object m_arg6 = null; public void set(int action) { m_action = action; } public void set(int action, Object arg1) { m_action = action; m_arg1 = arg1; } public void set(int action, Object arg1, Object arg2) { m_action = action; m_arg1 = arg1; m_arg2 = arg2; } public void set(int action, Object arg1, Object arg2, Object arg3) { m_action = action; m_arg1 = arg1; m_arg2 = arg2; m_arg3 = arg3; } public void set(int action, Object arg1, Object arg2, Object arg3, Object arg4) { m_action = action; m_arg1 = arg1; m_arg2 = arg2; m_arg3 = arg3; m_arg4 = arg4; } public void set(int action, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5) { m_action = action; m_arg1 = arg1; m_arg2 = arg2; m_arg3 = arg3; m_arg4 = arg4; m_arg5 = arg5; } public void set(int action, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6) { m_action = action; m_arg1 = arg1; m_arg2 = arg2; m_arg3 = arg3; m_arg4 = arg4; m_arg5 = arg5; m_arg6 = arg6; } private void unset() { m_action = -1; m_arg1 = null; m_arg2 = null; m_arg3 = null; m_arg4 = null; m_arg5 = null; m_arg6 = null; } public Object run() throws Exception { int action = m_action; Object arg1 = m_arg1; Object arg2 = m_arg2; Object arg3 = m_arg3; Object arg4 = m_arg4; Object arg5 = m_arg5; Object arg6 = m_arg6; unset(); switch (action) { case INITIALIZE_CONTEXT_ACTION: return AccessController.getContext(); case ADD_EXTENSION_URL_ACTION: Method addURL = URLClassLoader.class.getDeclaredMethod("addURL", new Class[] {URL.class}); addURL.setAccessible(true); addURL.invoke(arg2, new Object[]{arg1}); return null; case CREATE_TMPFILE_ACTION: return File.createTempFile((String) arg1, (String) arg2, (File) arg3); case CREATE_URL_ACTION: return new URL((String) arg1, (String) arg2, ((Integer) arg3).intValue(), (String) arg4, (URLStreamHandler) arg5); case CREATE_URL_WITH_CONTEXT_ACTION: return new URL((URL) arg1, (String) arg2, (URLStreamHandler) arg3); case DELETE_FILE_ACTION: return ((File) arg1).delete() ? Boolean.TRUE : Boolean.FALSE; case EXEC_ACTION: return Runtime.getRuntime().exec((String) arg1); case FILE_EXISTS_ACTION: return ((File) arg1).exists() ? Boolean.TRUE : Boolean.FALSE; case FILE_IS_DIRECTORY_ACTION: return ((File) arg1).isDirectory() ? Boolean.TRUE : Boolean.FALSE; case FOR_NAME_ACTION: return (arg2 == null) ? Class.forName((String) arg1) : Class.forName((String) arg1, true, (ClassLoader) arg2); case GET_ABSOLUTE_PATH_ACTION: return ((File) arg1).getAbsolutePath(); case GET_CONSTRUCTOR_ACTION: return ((Class) arg1).getConstructor((Class[]) arg2); case GET_DECLARED_CONSTRUCTOR_ACTION: return ((Class) arg1).getDeclaredConstructor((Class[]) arg2); case GET_DECLARED_METHOD_ACTION: return ((Class) arg1).getDeclaredMethod((String) arg2, (Class[]) arg3); case GET_FIELD_ACTION: Field field = ((Class) arg1).getDeclaredField((String) arg2); field.setAccessible(true); return field.get(arg3); case GET_FILE_INPUT_ACTION: return new FileInputStream((File) arg1); case GET_FILE_OUTPUT_ACTION: return new FileOutputStream((File) arg1); case TO_URI_ACTION: return ((File) arg1).toURI(); case GET_METHOD_ACTION: return ((Class) arg1).getMethod((String) arg2, (Class[]) arg3); case GET_POLICY_ACTION: return Policy.getPolicy(); case GET_PROPERTY_ACTION: return System.getProperty((String) arg1, (String) arg2); case GET_PARENT_CLASS_LOADER_ACTION: return ((ClassLoader) arg1).getParent(); case GET_SYSTEM_CLASS_LOADER_ACTION: return ClassLoader.getSystemClassLoader(); case GET_URL_INPUT_ACTION: return ((URLConnection) arg1).getInputStream(); case INVOKE_CONSTRUCTOR_ACTION: return ((Constructor) arg1).newInstance((Object[]) arg2); case INVOKE_DIRECTMETHOD_ACTION: return ((Method) arg1).invoke(arg2, (Object[]) arg3); case INVOKE_METHOD_ACTION: ((Method) arg1).setAccessible(true); return ((Method) arg1).invoke(arg2, (Object[]) arg3); case LIST_DIRECTORY_ACTION: return ((File) arg1).listFiles(); case MAKE_DIRECTORIES_ACTION: return ((File) arg1).mkdirs() ? Boolean.TRUE : Boolean.FALSE; case MAKE_DIRECTORY_ACTION: return ((File) arg1).mkdir() ? Boolean.TRUE : Boolean.FALSE; case OPEN_ZIPFILE_ACTION: return new ZipFile((File) arg1); case OPEN_URLCONNECTION_ACTION: return ((URL) arg1).openConnection(); case RENAME_FILE_ACTION: return ((File) arg1).renameTo((File) arg2) ? Boolean.TRUE : Boolean.FALSE; case SET_ACCESSIBLE_ACTION: ((AccessibleObject) arg1).setAccessible(true); return null; case START_ACTIVATOR_ACTION: ((BundleActivator) arg1).start((BundleContext) arg2); return null; case STOP_ACTIVATOR_ACTION: ((BundleActivator) arg1).stop((BundleContext) arg2); return null; case SWAP_FIELD_ACTION: return _swapStaticFieldIfNotClass((Class) arg1, (Class) arg2, (Class) arg3, (String) arg4); case SYSTEM_EXIT_ACTION: System.exit(((Integer) arg1).intValue()); case FLUSH_FIELD_ACTION: _flush(((Class) arg1), arg2); return null; case GET_CLASS_LOADER_ACTION: return ((Class) arg1).getClassLoader(); case INVOKE_BUNDLE_FIND_HOOK: ((org.osgi.framework.hooks.bundle.FindHook) arg1).find( (BundleContext) arg2, (Collection<Bundle>) arg3); return null; case INVOKE_BUNDLE_EVENT_HOOK: ((org.osgi.framework.hooks.bundle.EventHook) arg1).event( (BundleEvent) arg2, (Collection<BundleContext>) arg3); return null; case INVOKE_WEAVING_HOOK: ((org.osgi.framework.hooks.weaving.WeavingHook) arg1).weave( (org.osgi.framework.hooks.weaving.WovenClass) arg2); return null; case INVOKE_SERVICE_EVENT_HOOK: ((org.osgi.framework.hooks.service.EventHook) arg1).event( (ServiceEvent) arg2, (Collection<BundleContext>) arg3); return null; case INVOKE_SERVICE_FIND_HOOK: ((org.osgi.framework.hooks.service.FindHook) arg1).find( (BundleContext) arg2, (String) arg3, (String) arg4, ((Boolean) arg5).booleanValue(), (Collection<ServiceReference<?>>) arg6); return null; case INVOKE_SERVICE_LISTENER_HOOK_ADDED: ((org.osgi.framework.hooks.service.ListenerHook) arg1).added( (Collection<ListenerHook.ListenerInfo>) arg2); return null; case INVOKE_SERVICE_LISTENER_HOOK_REMOVED: ((org.osgi.framework.hooks.service.ListenerHook) arg1).removed( (Collection<ListenerHook.ListenerInfo>) arg2); return null; case INVOKE_SERVICE_EVENT_LISTENER_HOOK: ((org.osgi.framework.hooks.service.EventListenerHook) arg1).event( (ServiceEvent) arg2, (Map<BundleContext, Collection<ListenerHook.ListenerInfo>>) arg3); return null; case INVOKE_RESOLVER_HOOK_FACTORY: return ((org.osgi.framework.hooks.resolver.ResolverHookFactory) arg1).begin( (Collection<BundleRevision>) arg2); case INVOKE_RESOLVER_HOOK_RESOLVABLE: ((org.osgi.framework.hooks.resolver.ResolverHook) arg1).filterResolvable( (Collection<BundleRevision>) arg2); return null; case INVOKE_RESOLVER_HOOK_SINGLETON: ((org.osgi.framework.hooks.resolver.ResolverHook) arg1) .filterSingletonCollisions( (BundleCapability) arg2, (Collection<BundleCapability>) arg3); return null; case INVOKE_RESOLVER_HOOK_MATCHES: ((org.osgi.framework.hooks.resolver.ResolverHook) arg1).filterMatches( (BundleRequirement) arg2, (Collection<BundleCapability>) arg3); return null; case INVOKE_RESOLVER_HOOK_END: ((org.osgi.framework.hooks.resolver.ResolverHook) arg1).end(); return null; case INVOKE_BUNDLE_COLLISION_HOOK: ((org.osgi.framework.hooks.bundle.CollisionHook) arg1).filterCollisions((Integer) arg2, (Bundle) arg3, (Collection<Bundle>) arg4); return null; case OPEN_JARFILE_ACTION: return new JarFile((File) arg1); case DELETE_FILEONEXIT_ACTION: ((File) arg1).deleteOnExit(); return null; case INVOKE_WOVEN_CLASS_LISTENER: ((org.osgi.framework.hooks.weaving.WovenClassListener) arg1).modified( (org.osgi.framework.hooks.weaving.WovenClass) arg2); return null; } return null; } } }
8,540
0
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/capabilityset/CapabilitySet.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.aries.subsystem.core.capabilityset; import java.lang.reflect.Array; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.SortedMap; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ConcurrentSkipListMap; import org.osgi.framework.Version; import org.osgi.framework.VersionRange; import org.osgi.framework.namespace.AbstractWiringNamespace; import org.osgi.resource.Capability; public class CapabilitySet { private final SortedMap<String, Map<Object, Set<Capability>>> m_indices; // Should also be concurrent! private final Set<Capability> m_capSet = Collections.newSetFromMap(new ConcurrentHashMap<Capability, Boolean>()); private final static SecureAction m_secureAction = new SecureAction(); // public void dump() // { // for (Entry<String, Map<Object, Set<Capability>>> entry : m_indices.entrySet()) // { // boolean header1 = false; // for (Entry<Object, Set<Capability>> entry2 : entry.getValue().entrySet()) // { // boolean header2 = false; // for (Capability cap : entry2.getValue()) // { // if (cap.getRevision().getBundle().getBundleId() != 0) // { // if (!header1) // { // System.out.println(entry.getKey() + ":"); // header1 = true; // } // if (!header2) // { // System.out.println(" " + entry2.getKey()); // header2 = true; // } // System.out.println(" " + cap); // } // } // } // } // } public CapabilitySet(final List<String> indexProps, final boolean caseSensitive) { m_indices = (caseSensitive) ? new ConcurrentSkipListMap<String, Map<Object, Set<Capability>>>() : new ConcurrentSkipListMap<String, Map<Object, Set<Capability>>>( StringComparator.COMPARATOR); for (int i = 0; (indexProps != null) && (i < indexProps.size()); i++) { m_indices.put( indexProps.get(i), new ConcurrentHashMap<Object, Set<Capability>>()); } } public void addCapability(final Capability cap) { m_capSet.add(cap); // Index capability. for (Entry<String, Map<Object, Set<Capability>>> entry : m_indices.entrySet()) { Object value = cap.getAttributes().get(entry.getKey()); if (value != null) { if (value.getClass().isArray()) { value = convertArrayToList(value); } ConcurrentMap<Object, Set<Capability>> index = (ConcurrentMap<Object, Set<Capability>>) entry.getValue(); if (value instanceof Collection) { Collection c = (Collection) value; for (Object o : c) { indexCapability(index, cap, o); } } else { indexCapability(index, cap, value); } } } } private void indexCapability( ConcurrentMap<Object, Set<Capability>> index, Capability cap, Object capValue) { Set<Capability> caps = Collections.newSetFromMap(new ConcurrentHashMap<Capability, Boolean>()); Set<Capability> prevval = index.putIfAbsent(capValue, caps); if (prevval != null) caps = prevval; caps.add(cap); } public void removeCapability(final Capability cap) { if (m_capSet.remove(cap)) { for (Entry<String, Map<Object, Set<Capability>>> entry : m_indices.entrySet()) { Object value = cap.getAttributes().get(entry.getKey()); if (value != null) { if (value.getClass().isArray()) { value = convertArrayToList(value); } Map<Object, Set<Capability>> index = entry.getValue(); if (value instanceof Collection) { Collection c = (Collection) value; for (Object o : c) { deindexCapability(index, cap, o); } } else { deindexCapability(index, cap, value); } } } } } private void deindexCapability( Map<Object, Set<Capability>> index, Capability cap, Object value) { Set<Capability> caps = index.get(value); if (caps != null) { caps.remove(cap); if (caps.isEmpty()) { index.remove(value); } } } public Set<Capability> match(final SimpleFilter sf, final boolean obeyMandatory) { final Set<Capability> matches = match(m_capSet, sf); return (obeyMandatory) ? matchMandatory(matches, sf) : matches; } private Set<Capability> match(Set<Capability> caps, final SimpleFilter sf) { Set<Capability> matches = Collections.newSetFromMap(new ConcurrentHashMap<Capability, Boolean>()); if (sf.getOperation() == SimpleFilter.MATCH_ALL) { matches.addAll(caps); } else if (sf.getOperation() == SimpleFilter.AND) { // Evaluate each subfilter against the remaining capabilities. // For AND we calculate the intersection of each subfilter. // We can short-circuit the AND operation if there are no // remaining capabilities. final List<SimpleFilter> sfs = (List<SimpleFilter>) sf.getValue(); for (int i = 0; (caps.size() > 0) && (i < sfs.size()); i++) { matches = match(caps, sfs.get(i)); caps = matches; } } else if (sf.getOperation() == SimpleFilter.OR) { // Evaluate each subfilter against the remaining capabilities. // For OR we calculate the union of each subfilter. List<SimpleFilter> sfs = (List<SimpleFilter>) sf.getValue(); for (int i = 0; i < sfs.size(); i++) { matches.addAll(match(caps, sfs.get(i))); } } else if (sf.getOperation() == SimpleFilter.NOT) { // Evaluate each subfilter against the remaining capabilities. // For OR we calculate the union of each subfilter. matches.addAll(caps); List<SimpleFilter> sfs = (List<SimpleFilter>) sf.getValue(); for (int i = 0; i < sfs.size(); i++) { matches.removeAll(match(caps, sfs.get(i))); } } else { Map<Object, Set<Capability>> index = m_indices.get(sf.getName()); if ((sf.getOperation() == SimpleFilter.EQ) && (index != null)) { Set<Capability> existingCaps = index.get(sf.getValue()); if (existingCaps != null) { matches.addAll(existingCaps); if (caps != m_capSet) { matches.retainAll(caps); } } } else { for (Iterator<Capability> it = caps.iterator(); it.hasNext(); ) { Capability cap = it.next(); Object lhs = cap.getAttributes().get(sf.getName()); if (lhs != null) { if (compare(lhs, sf.getValue(), sf.getOperation())) { matches.add(cap); } } } } } return matches; } // public static boolean matches(Capability cap, SimpleFilter sf) // { // return matchesInternal(cap, sf) && matchMandatory(cap, sf); // } // private static boolean matchesInternal(Capability cap, SimpleFilter sf) // { // boolean matched = true; // // if (sf.getOperation() == SimpleFilter.MATCH_ALL) // { // matched = true; // } // else if (sf.getOperation() == SimpleFilter.AND) // { // // Evaluate each subfilter against the remaining capabilities. // // For AND we calculate the intersection of each subfilter. // // We can short-circuit the AND operation if there are no // // remaining capabilities. // List<SimpleFilter> sfs = (List<SimpleFilter>) sf.getValue(); // for (int i = 0; matched && (i < sfs.size()); i++) // { // matched = matchesInternal(cap, sfs.get(i)); // } // } // else if (sf.getOperation() == SimpleFilter.OR) // { // // Evaluate each subfilter against the remaining capabilities. // // For OR we calculate the union of each subfilter. // matched = false; // List<SimpleFilter> sfs = (List<SimpleFilter>) sf.getValue(); // for (int i = 0; !matched && (i < sfs.size()); i++) // { // matched = matchesInternal(cap, sfs.get(i)); // } // } // else if (sf.getOperation() == SimpleFilter.NOT) // { // // Evaluate each subfilter against the remaining capabilities. // // For OR we calculate the union of each subfilter. // List<SimpleFilter> sfs = (List<SimpleFilter>) sf.getValue(); // for (int i = 0; i < sfs.size(); i++) // { // matched = !(matchesInternal(cap, sfs.get(i))); // } // } // else // { // matched = false; // Object lhs = cap.getAttributes().get(sf.getName()); // if (lhs != null) // { // matched = compare(lhs, sf.getValue(), sf.getOperation()); // } // } // // return matched; // } private static Set<Capability> matchMandatory( Set<Capability> caps, SimpleFilter sf) { for (Iterator<Capability> it = caps.iterator(); it.hasNext(); ) { Capability cap = it.next(); if (!matchMandatory(cap, sf)) { it.remove(); } } return caps; } private static boolean matchMandatory(Capability cap, SimpleFilter sf) { String mandatoryDirective = cap.getDirectives().get(AbstractWiringNamespace.CAPABILITY_MANDATORY_DIRECTIVE); if (mandatoryDirective == null) { // There are no mandatory attributes to check. return true; } List<String> mandatoryAttributes = Arrays.asList(mandatoryDirective.split(",")); Map<String, Object> attrs = cap.getAttributes(); for (Entry<String, Object> entry : attrs.entrySet()) { if (mandatoryAttributes.contains(entry.getKey()) && !matchMandatoryAttrbute(entry.getKey(), sf)) { return false; } } return true; } private static boolean matchMandatoryAttrbute(String attrName, SimpleFilter sf) { if ((sf.getName() != null) && sf.getName().equals(attrName)) { return true; } else if (sf.getOperation() == SimpleFilter.AND) { List list = (List) sf.getValue(); for (int i = 0; i < list.size(); i++) { SimpleFilter sf2 = (SimpleFilter) list.get(i); if ((sf2.getName() != null) && sf2.getName().equals(attrName)) { return true; } } } return false; } private static final Class<?>[] STRING_CLASS = new Class[] { String.class }; private static final String VALUE_OF_METHOD_NAME = "valueOf"; private static boolean compare(Object lhs, Object rhsUnknown, int op) { if (lhs == null) { return false; } // If this is a PRESENT operation, then just return true immediately // since we wouldn't be here if the attribute wasn't present. if (op == SimpleFilter.PRESENT) { return true; } //Need a special case here when lhs is a Version and rhs is a VersionRange //Version is comparable so we need to check this first if(lhs instanceof Version && op == SimpleFilter.EQ) { Object rhs = null; try { rhs = coerceType(lhs, (String) rhsUnknown); } catch (Exception ex) { //Do nothing will check later if rhs is null } if(rhs != null && rhs instanceof VersionRange) { return ((VersionRange)rhs).includes((Version)lhs); } } // If the type is comparable, then we can just return the // result immediately. if (lhs instanceof Comparable) { // Spec says SUBSTRING is false for all types other than string. if ((op == SimpleFilter.SUBSTRING) && !(lhs instanceof String)) { return false; } Object rhs; if (op == SimpleFilter.SUBSTRING) { rhs = rhsUnknown; } else { try { rhs = coerceType(lhs, (String) rhsUnknown); } catch (Exception ex) { return false; } } switch (op) { case SimpleFilter.EQ : try { return (((Comparable) lhs).compareTo(rhs) == 0); } catch (Exception ex) { return false; } case SimpleFilter.GTE : try { return (((Comparable) lhs).compareTo(rhs) >= 0); } catch (Exception ex) { return false; } case SimpleFilter.LTE : try { return (((Comparable) lhs).compareTo(rhs) <= 0); } catch (Exception ex) { return false; } case SimpleFilter.APPROX : return compareApproximate(lhs, rhs); case SimpleFilter.SUBSTRING : return SimpleFilter.compareSubstring((List<String>) rhs, (String) lhs); default: throw new RuntimeException( "Unknown comparison operator: " + op); } } // Booleans do not implement comparable, so special case them. else if (lhs instanceof Boolean) { Object rhs; try { rhs = coerceType(lhs, (String) rhsUnknown); } catch (Exception ex) { return false; } switch (op) { case SimpleFilter.EQ : case SimpleFilter.GTE : case SimpleFilter.LTE : case SimpleFilter.APPROX : return (lhs.equals(rhs)); default: throw new RuntimeException( "Unknown comparison operator: " + op); } } // If the LHS is not a comparable or boolean, check if it is an // array. If so, convert it to a list so we can treat it as a // collection. if (lhs.getClass().isArray()) { lhs = convertArrayToList(lhs); } // If LHS is a collection, then call compare() on each element // of the collection until a match is found. if (lhs instanceof Collection) { for (Iterator iter = ((Collection) lhs).iterator(); iter.hasNext(); ) { if (compare(iter.next(), rhsUnknown, op)) { return true; } } return false; } // Spec says SUBSTRING is false for all types other than string. if ((op == SimpleFilter.SUBSTRING) && !(lhs instanceof String)) { return false; } // Since we cannot identify the LHS type, then we can only perform // equality comparison. try { return lhs.equals(coerceType(lhs, (String) rhsUnknown)); } catch (Exception ex) { return false; } } private static boolean compareApproximate(Object lhs, Object rhs) { if (rhs instanceof String) { return removeWhitespace((String) lhs) .equalsIgnoreCase(removeWhitespace((String) rhs)); } else if (rhs instanceof Character) { return Character.toLowerCase(((Character) lhs)) == Character.toLowerCase(((Character) rhs)); } return lhs.equals(rhs); } private static String removeWhitespace(String s) { StringBuffer sb = new StringBuffer(s.length()); for (int i = 0; i < s.length(); i++) { if (!Character.isWhitespace(s.charAt(i))) { sb.append(s.charAt(i)); } } return sb.toString(); } private static Object coerceType(Object lhs, String rhsString) throws Exception { // If the LHS expects a string, then we can just return // the RHS since it is a string. if (lhs.getClass() == rhsString.getClass()) { return rhsString; } // Try to convert the RHS type to the LHS type by using // the string constructor of the LHS class, if it has one. Object rhs = null; try { // The Character class is a special case, since its constructor // does not take a string, so handle it separately. if (lhs instanceof Character) { rhs = new Character(rhsString.charAt(0)); } else if(lhs instanceof Version && rhsString.indexOf(',') >= 0) { rhs = VersionRange.valueOf(rhsString); } else { // Spec says we should trim number types. if ((lhs instanceof Number) || (lhs instanceof Boolean)) { rhsString = rhsString.trim(); } try { // Try to find a suitable static valueOf method Method valueOfMethod = m_secureAction.getDeclaredMethod( lhs.getClass(), VALUE_OF_METHOD_NAME, STRING_CLASS); if (valueOfMethod.getReturnType().isAssignableFrom(lhs.getClass()) && ((valueOfMethod.getModifiers() & Modifier.STATIC) > 0)) { m_secureAction.setAccesssible(valueOfMethod); rhs = valueOfMethod.invoke(null, new Object[] { rhsString }); } } catch (Exception ex) { // Static valueOf fails, try the next conversion mechanism } if (rhs == null) { Constructor ctor = m_secureAction.getConstructor(lhs.getClass(), STRING_CLASS); m_secureAction.setAccesssible(ctor); rhs = ctor.newInstance(new Object[] { rhsString }); } } } catch (Exception ex) { throw new Exception( "Could not instantiate class " + lhs.getClass().getName() + " from string constructor with argument '" + rhsString + "' because " + ex); } return rhs; } /** * This is an ugly utility method to convert an array of primitives * to an array of primitive wrapper objects. This method simplifies * processing LDAP filters since the special case of primitive arrays * can be ignored. * @param array An array of primitive types. * @return An corresponding array using pritive wrapper objects. **/ private static List convertArrayToList(Object array) { int len = Array.getLength(array); List list = new ArrayList(len); for (int i = 0; i < len; i++) { list.add(Array.get(array, i)); } return list; } }
8,541
0
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/capabilityset/StringComparator.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.aries.subsystem.core.capabilityset; import java.util.Comparator; public class StringComparator implements Comparator<String> { public static final StringComparator COMPARATOR = new StringComparator(); public int compare(String s1, String s2) { int n1 = s1.length(); int n2 = s2.length(); int min = n1 < n2 ? n1 : n2; for ( int i = 0; i < min; i++ ) { char c1 = s1.charAt( i ); char c2 = s2.charAt( i ); if ( c1 != c2 ) { // Fast check for simple ascii codes if ( c1 <= 128 && c2 <= 128 ) { c1 = toLowerCaseFast(c1); c2 = toLowerCaseFast(c2); if ( c1 != c2 ) { return c1 - c2; } } else { c1 = Character.toUpperCase( c1 ); c2 = Character.toUpperCase( c2 ); if ( c1 != c2 ) { c1 = Character.toLowerCase( c1 ); c2 = Character.toLowerCase( c2 ); if ( c1 != c2 ) { // No overflow because of numeric promotion return c1 - c2; } } } } } return n1 - n2; } private static char toLowerCaseFast( char ch ) { return ( ch >= 'A' && ch <= 'Z' ) ? ( char ) ( ch + 'a' - 'A' ) : ch; } }
8,542
0
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/archive/AbstractDirective.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.aries.subsystem.core.archive; public abstract class AbstractDirective extends AbstractParameter implements Directive { public AbstractDirective(String name, String value) { super(name, value); } @Override public String getValue() { return (String)super.getValue(); } @Override public String toString() { return new StringBuilder() .append(getName()) .append(":=") .append(getValue()) .toString(); } }
8,543
0
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/archive/ImportPackageHeader.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.aries.subsystem.core.archive; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.aries.subsystem.core.capabilityset.SimpleFilter; import org.osgi.framework.Constants; import org.osgi.framework.namespace.PackageNamespace; import org.osgi.resource.Requirement; import org.osgi.resource.Resource; public class ImportPackageHeader extends AbstractClauseBasedHeader<ImportPackageHeader.Clause> implements RequirementHeader<ImportPackageHeader.Clause> { public static class Clause extends AbstractClause { private static final Collection<Parameter> defaultParameters = generateDefaultParameters(VersionRangeAttribute.DEFAULT_VERSION, ResolutionDirective.MANDATORY); public static Clause valueOf(Requirement requirement) { String namespace = requirement.getNamespace(); if (!ImportPackageRequirement.NAMESPACE.equals(namespace)) { throw new IllegalArgumentException("Invalid namespace:" + namespace); } Map<String, Parameter> parameters = new HashMap<String, Parameter>(); String filter = null; Map<String, String> directives = requirement.getDirectives(); for (Map.Entry<String, String> entry : directives.entrySet()) { String key = entry.getKey(); if (ImportPackageRequirement.DIRECTIVE_FILTER.equals(key)) { filter = entry.getValue(); } else { parameters.put(key, DirectiveFactory.createDirective(key, entry.getValue())); } } Map<String, List<SimpleFilter>> attributes = SimpleFilter.attributes(filter); String path = null; for (Map.Entry<String, List<SimpleFilter>> entry : attributes.entrySet()) { String key = entry.getKey(); List<SimpleFilter> value = entry.getValue(); if (ImportPackageRequirement.NAMESPACE.equals(key)) { path = String.valueOf(value.get(0).getValue()); } else if (ATTRIBUTE_VERSION.equals(key) || ATTRIBUTE_BUNDLE_VERSION.equals(key)) { parameters.put(key, new VersionRangeAttribute(key, parseVersionRange(value))); } else { parameters.put(key, AttributeFactory.createAttribute(key, String.valueOf(value.get(0).getValue()))); } } return new Clause(path, parameters, defaultParameters); } public Clause(String path, Map<String, Parameter> parameters, Collection<Parameter> defaultParameters) { super(path, parameters, defaultParameters == null ? Clause.defaultParameters : defaultParameters); } public Clause(String clause) { super( parsePath(clause, Patterns.PACKAGE_NAMES, true), parseParameters(clause, true), defaultParameters); } public Collection<String> getPackageNames() { return Arrays.asList(path.split(";")); } public VersionRangeAttribute getVersionRangeAttribute() { return (VersionRangeAttribute)getAttribute(Constants.VERSION_ATTRIBUTE); } public ImportPackageRequirement toRequirement(Resource resource) { return new ImportPackageRequirement(this, resource); } } public static final String ATTRIBUTE_BUNDLE_SYMBOLICNAME = PackageNamespace.CAPABILITY_BUNDLE_SYMBOLICNAME_ATTRIBUTE; public static final String ATTRIBUTE_BUNDLE_VERSION = PackageNamespace.CAPABILITY_BUNDLE_VERSION_ATTRIBUTE; public static final String ATTRIBUTE_VERSION = PackageNamespace.CAPABILITY_VERSION_ATTRIBUTE; public static final String NAME = Constants.IMPORT_PACKAGE; public static final String DIRECTIVE_RESOLUTION = PackageNamespace.REQUIREMENT_RESOLUTION_DIRECTIVE; public static final String RESOLUTION_MANDATORY = PackageNamespace.RESOLUTION_MANDATORY; public static final String RESOLUTION_OPTIONAL = PackageNamespace.RESOLUTION_OPTIONAL; public ImportPackageHeader(Collection<Clause> clauses) { super(clauses); } public ImportPackageHeader(String value) { super( value, new ClauseFactory<Clause>() { @Override public Clause newInstance(String clause) { return new Clause(clause); } }); } @Override public String getName() { return Constants.IMPORT_PACKAGE; } @Override public String getValue() { return toString(); } @Override public List<ImportPackageRequirement> toRequirements(Resource resource) { Collection<Clause> clauses = getClauses(); List<ImportPackageRequirement> result = new ArrayList<ImportPackageRequirement>(clauses.size()); for (Clause clause : clauses) { Collection<String> packageNames = clause.getPackageNames(); if (packageNames.size() > 1) { for (String packageName : packageNames) { Collection<Parameter> parameters = clause.getParameters(); Map<String, Parameter> name2parameter = new HashMap<String, Parameter>(parameters.size()); for (Parameter parameter : parameters) { name2parameter.put(parameter.getName(), parameter); } result.add(new Clause(packageName, name2parameter, null).toRequirement(resource)); } } else { result.add(clause.toRequirement(resource)); } } return result; } }
8,544
0
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/archive/GenericHeader.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.aries.subsystem.core.archive; import java.util.Collection; import java.util.Collections; public class GenericHeader extends AbstractClauseBasedHeader<GenericHeader.Clause> { public static class Clause extends AbstractClause { public Clause(String clause) { super( clause, Collections.<String, Parameter>emptyMap(), generateDefaultParameters()); } } private final String name; public GenericHeader(String name, Collection<Clause> clauses) { super(clauses); this.name = name; } public GenericHeader(String name, String value) { super( value.isEmpty() ? "\"\"" : value, new ClauseFactory<Clause>() { @Override public Clause newInstance(String clause) { return new Clause(clause); } }); this.name = name; } @Override public String getName() { return name; } @Override public String getValue() { return toString(); } }
8,545
0
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/archive/GenericClause.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.aries.subsystem.core.archive; public class GenericClause extends AbstractClause { public GenericClause(String clause) { super( parsePath(clause, Patterns.PATHS, false), parseParameters(clause, false), generateDefaultParameters()); } }
8,546
0
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/archive/AriesSubsystemParentsHeader.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.aries.subsystem.core.archive; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.apache.aries.subsystem.core.internal.BasicSubsystem; import org.apache.aries.subsystem.core.internal.OsgiIdentityRequirement; import org.osgi.framework.Version; import org.osgi.resource.Requirement; import org.osgi.resource.Resource; import org.osgi.service.subsystem.SubsystemConstants; public class AriesSubsystemParentsHeader extends AbstractClauseBasedHeader<AriesSubsystemParentsHeader.Clause> implements RequirementHeader<AriesSubsystemParentsHeader.Clause> { public static class Clause extends AbstractClause { public static final String ATTRIBUTE_VERSION = VersionRangeAttribute.NAME_VERSION; public static final String ATTRIBUTE_RESOURCEID = "resourceId"; public static final String ATTRIBUTE_TYPE = TypeAttribute.NAME; public Clause(String clause) { super( parsePath(clause, Patterns.SYMBOLIC_NAME, false), parseParameters(clause, true), generateDefaultParameters( TypeAttribute.newInstance(SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION), VersionRangeAttribute.DEFAULT_VERSION)); } public Clause(BasicSubsystem subsystem, boolean referenceCount) { this(appendSubsystem(subsystem, new StringBuilder(), referenceCount).toString()); } public boolean contains(BasicSubsystem subsystem) { return getSymbolicName().equals( subsystem.getSymbolicName()) && getVersion().equals( subsystem.getVersion()) && getType().equals( subsystem.getType()); } public long getId() { Attribute attribute = getAttribute(ATTRIBUTE_RESOURCEID); if (attribute == null) return -1; return Long.valueOf(String.valueOf(attribute.getValue())); } public String getSymbolicName() { return path; } public String getType() { return ((TypeAttribute)getAttribute(ATTRIBUTE_TYPE)).getType(); } public Version getVersion() { return ((VersionAttribute)getAttribute(ATTRIBUTE_VERSION)).getVersion(); } public OsgiIdentityRequirement toRequirement(Resource resource) { return new OsgiIdentityRequirement(getSymbolicName(), getVersion(), getType(), false); } } public static final String NAME = "AriesSubsystem-Parents"; private static StringBuilder appendSubsystem(BasicSubsystem subsystem, StringBuilder builder, boolean referenceCount) { String symbolicName = subsystem.getSymbolicName(); Version version = subsystem.getVersion(); String type = subsystem.getType(); builder.append(symbolicName) .append(';') .append(Clause.ATTRIBUTE_VERSION) .append('=') .append(version.toString()) .append(';') .append(Clause.ATTRIBUTE_TYPE) .append('=') .append(type) .append(';') .append(Clause.ATTRIBUTE_RESOURCEID) .append('=') .append(subsystem.getSubsystemId()); return builder; } public AriesSubsystemParentsHeader(Collection<Clause> clauses) { super(clauses); } public AriesSubsystemParentsHeader(String value) { super( value, new ClauseFactory<Clause>() { @Override public Clause newInstance(String clause) { return new Clause(clause); } }); } public boolean contains(BasicSubsystem subsystem) { return getClause(subsystem) != null; } public Clause getClause(BasicSubsystem subsystem) { String symbolicName = subsystem.getSymbolicName(); Version version = subsystem.getVersion(); String type = subsystem.getType(); for (Clause clause : clauses) { if (symbolicName.equals(clause.getPath()) && clause.getVersion().equals(version) && type.equals(clause.getType())) return clause; } return null; } @Override public String getName() { return NAME; } @Override public String getValue() { return toString(); } @Override public List<Requirement> toRequirements(Resource resource) { List<Requirement> requirements = new ArrayList<Requirement>(clauses.size()); for (Clause clause : clauses) requirements.add(clause.toRequirement(resource)); return requirements; } }
8,547
0
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/archive/ProvideCapabilityCapability.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.aries.subsystem.core.archive; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.apache.aries.subsystem.core.internal.AbstractCapability; import org.osgi.resource.Resource; public class ProvideCapabilityCapability extends AbstractCapability { private final Map<String, Object> attributes = new HashMap<String, Object>(); private final Map<String, String> directives = new HashMap<String, String>(); private final String namespace; private final Resource resource; public ProvideCapabilityCapability(ProvideCapabilityHeader.Clause clause, Resource resource) { namespace = clause.getNamespace(); for (Parameter parameter : clause.getParameters()) { if (parameter instanceof Attribute) attributes.put(parameter.getName(), parameter.getValue()); else directives.put(parameter.getName(), ((Directive)parameter).getValue()); } this.resource = resource; } @Override public Map<String, Object> getAttributes() { return Collections.unmodifiableMap(attributes); } @Override public Map<String, String> getDirectives() { return Collections.unmodifiableMap(directives); } @Override public String getNamespace() { return namespace; } @Override public Resource getResource() { return resource; } }
8,548
0
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/archive/ProvisionPolicyDirective.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.aries.subsystem.core.archive; import org.osgi.service.subsystem.SubsystemConstants; public class ProvisionPolicyDirective extends AbstractDirective { public static final String NAME = SubsystemConstants.PROVISION_POLICY_DIRECTIVE; public static final String VALUE_ACCEPT_DEPENDENCIES = SubsystemConstants.PROVISION_POLICY_ACCEPT_DEPENDENCIES; public static final String VALUE_REJECT_DEPENDENCIES = SubsystemConstants.PROVISION_POLICY_REJECT_DEPENDENCIES; public static final ProvisionPolicyDirective ACCEPT_DEPENDENCIES = new ProvisionPolicyDirective(VALUE_ACCEPT_DEPENDENCIES); public static final ProvisionPolicyDirective REJECT_DEPENDENCIES = new ProvisionPolicyDirective(VALUE_REJECT_DEPENDENCIES); public static final ProvisionPolicyDirective DEFAULT = REJECT_DEPENDENCIES; public static ProvisionPolicyDirective getInstance(String value) { if (VALUE_ACCEPT_DEPENDENCIES.equals(value)) return ACCEPT_DEPENDENCIES; if (VALUE_REJECT_DEPENDENCIES.equals(value)) return REJECT_DEPENDENCIES; return new ProvisionPolicyDirective(value); } public ProvisionPolicyDirective(String value) { super(NAME, value); if (!(VALUE_ACCEPT_DEPENDENCIES.equals(value) || VALUE_REJECT_DEPENDENCIES.equals(value))) { throw new IllegalArgumentException("Invalid " + NAME + " directive value: " + value); } } public String getProvisionPolicy() { return getValue(); } public boolean isAcceptDependencies() { return this == ACCEPT_DEPENDENCIES || VALUE_ACCEPT_DEPENDENCIES.equals(getProvisionPolicy()); } public boolean isRejectDependencies() { return this == REJECT_DEPENDENCIES || VALUE_REJECT_DEPENDENCIES.equals(getProvisionPolicy()); } }
8,549
0
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/archive/Patterns.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.aries.subsystem.core.archive; import java.util.regex.Pattern; import org.osgi.framework.namespace.PackageNamespace; public class Patterns { public static final Pattern NAMESPACE = Pattern.compile('(' + Grammar.NAMESPACE + ")(?=;|\\z)"); public static final Pattern OBJECTCLASS_OR_STAR = Pattern.compile("((" + Grammar.OBJECTCLASS + ")|[*])(?=;|\\z)"); public static final Pattern PACKAGE_NAMES = Pattern.compile('(' + Grammar.PACKAGENAMES + ")(?=;|\\z)"); public static final Pattern PACKAGE_NAMESPACE = Pattern.compile("\\((" + PackageNamespace.PACKAGE_NAMESPACE + ")(=)([^\\)]+)\\)"); public static final Pattern PARAMETER = Pattern.compile('(' + Grammar.PARAMETER + ")(?=;|\\z)"); public static final Pattern PATHS = Pattern.compile('(' + Grammar.PATH + "\\s*(?:\\;\\s*" + Grammar.PATH + ")*)(?=;|\\z)"); public static final Pattern SUBSYSTEM_TYPE = Pattern.compile('(' + SubsystemTypeHeader.TYPE_APPLICATION + '|' + SubsystemTypeHeader.TYPE_COMPOSITE + '|' + SubsystemTypeHeader.TYPE_FEATURE + ")(?=;|\\z)"); public static final Pattern SYMBOLIC_NAME = Pattern.compile('(' + Grammar.SYMBOLICNAME + ")(?=;|\\z)"); public static final Pattern WILDCARD_NAMES = Pattern.compile('(' + Grammar.WILDCARD_NAMES + ")(?=;|\\z)"); private static final String DIRECTIVE = '(' + Grammar.EXTENDED + ")(:=)(" + Grammar.ARGUMENT + ')'; private static final String TYPED_ATTR = '(' + Grammar.EXTENDED + ")(?:(\\:)(" + Grammar.TYPE + "))?=(" + Grammar.ARGUMENT + ')'; public static final Pattern TYPED_PARAMETER = Pattern.compile("(?:(?:" + DIRECTIVE + ")|(?:" + TYPED_ATTR + "))(?=;|\\z)"); public static final Pattern SCALAR_LIST = Pattern.compile("List(?:<(String|Long|Double|Version)>)?"); }
8,550
0
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/archive/DeployedContentRequirement.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.aries.subsystem.core.archive; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.apache.aries.subsystem.core.internal.AbstractRequirement; import org.osgi.framework.namespace.IdentityNamespace; import org.osgi.resource.Resource; public class DeployedContentRequirement extends AbstractRequirement { public static final String DIRECTIVE_FILTER = IdentityNamespace.REQUIREMENT_FILTER_DIRECTIVE; public static final String NAMESPACE = IdentityNamespace.IDENTITY_NAMESPACE; private final Map<String, String> directives = new HashMap<String, String>(); private final Resource resource; public DeployedContentRequirement( DeployedContentHeader.Clause clause, Resource resource) { StringBuilder builder = new StringBuilder("(&(") .append(NAMESPACE).append('=') .append(clause.getSymbolicName()).append(')'); for (Attribute attribute : clause.getAttributes()) attribute.appendToFilter(builder); directives.put(DIRECTIVE_FILTER, builder.append(')').toString()); this.resource = resource; } @Override public Map<String, Object> getAttributes() { return Collections.emptyMap(); } @Override public Map<String, String> getDirectives() { return Collections.unmodifiableMap(directives); } @Override public String getNamespace() { return NAMESPACE; } @Override public Resource getResource() { return resource; } }
8,551
0
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/archive/RequireBundleRequirement.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.aries.subsystem.core.archive; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.apache.aries.subsystem.core.internal.AbstractRequirement; import org.osgi.framework.namespace.BundleNamespace; import org.osgi.resource.Resource; public class RequireBundleRequirement extends AbstractRequirement { public static final String DIRECTIVE_FILTER = BundleNamespace.REQUIREMENT_FILTER_DIRECTIVE; public static final String NAMESPACE = BundleNamespace.BUNDLE_NAMESPACE; private final Map<String, String> directives; private final Resource resource; public RequireBundleRequirement( RequireBundleHeader.Clause clause, Resource resource) { directives = new HashMap<String, String>(clause.getDirectives().size() + 1); for (Directive directive : clause.getDirectives()) directives.put(directive.getName(), directive.getValue()); StringBuilder builder = new StringBuilder("(&(") .append(NAMESPACE).append('=') .append(clause.getSymbolicName()).append(')'); for (Attribute attribute : clause.getAttributes()) attribute.appendToFilter(builder); directives.put(DIRECTIVE_FILTER, builder.append(')').toString()); this.resource = resource; } @Override public Map<String, Object> getAttributes() { return Collections.emptyMap(); } @Override public Map<String, String> getDirectives() { return Collections.unmodifiableMap(directives); } @Override public String getNamespace() { return NAMESPACE; } @Override public Resource getResource() { return resource; } }
8,552
0
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/archive/StartOrderDirective.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.aries.subsystem.core.archive; import org.osgi.service.subsystem.SubsystemConstants; public class StartOrderDirective extends AbstractDirective { public static final String NAME = SubsystemConstants.START_ORDER_DIRECTIVE; private final int startOrder; public StartOrderDirective(String value) { super(NAME, value); this.startOrder = Integer.parseInt(value); } public int getStartOrder() { return startOrder; } }
8,553
0
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/archive/SubsystemImportServiceRequirement.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.aries.subsystem.core.archive; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.apache.aries.subsystem.core.internal.AbstractRequirement; import org.osgi.framework.Constants; import org.osgi.namespace.service.ServiceNamespace; import org.osgi.resource.Namespace; import org.osgi.resource.Resource; public class SubsystemImportServiceRequirement extends AbstractRequirement { public static final String DIRECTIVE_FILTER = Namespace.REQUIREMENT_FILTER_DIRECTIVE; public static final String NAMESPACE = ServiceNamespace.SERVICE_NAMESPACE; private final Map<String, String> directives = new HashMap<String, String>(1); private final Resource resource; public SubsystemImportServiceRequirement( SubsystemImportServiceHeader.Clause clause, Resource resource) { boolean appendObjectClass = !ServiceNamespace.SERVICE_NAMESPACE.equals(clause.getPath()); StringBuilder builder = new StringBuilder(); if (appendObjectClass) { builder.append("(&(").append(Constants.OBJECTCLASS).append('=').append(clause.getPath()).append(')'); } Directive filter = clause.getDirective(SubsystemExportServiceHeader.Clause.DIRECTIVE_FILTER); if (filter != null) { builder.append(filter.getValue()); } if (appendObjectClass) { builder.append(')'); } String filterStr = builder.toString(); if (!filterStr.isEmpty()) { directives.put(DIRECTIVE_FILTER, filterStr); } this.resource = resource; } @Override public Map<String, Object> getAttributes() { return Collections.emptyMap(); } @Override public Map<String, String> getDirectives() { return Collections.unmodifiableMap(directives); } @Override public String getNamespace() { return NAMESPACE; } @Override public Resource getResource() { return resource; } }
8,554
0
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/archive/ClauseTokenizer.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.aries.subsystem.core.archive; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; public class ClauseTokenizer { private final Collection<String> clauses = new ArrayList<String>(); public ClauseTokenizer(String value) { int numOfChars = value.length(); StringBuilder builder = new StringBuilder(numOfChars); int numOfQuotes = 0; for (char c : value.toCharArray()) { numOfChars--; if (c == ',') { if (numOfQuotes % 2 == 0) { addClause(builder.toString().trim()); builder = new StringBuilder(numOfChars); continue; } } else if (c == '"') numOfQuotes++; builder.append(c); } addClause(builder.toString().trim()); } public Collection<String> getClauses() { return Collections.unmodifiableCollection(clauses); } private void addClause(String clause) { if (clause.isEmpty()) return; clauses.add(clause); } }
8,555
0
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/archive/SubsystemManifest.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.aries.subsystem.core.archive; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.jar.Attributes; import java.util.jar.Manifest; import org.apache.aries.subsystem.core.internal.OsgiIdentityCapability; import org.apache.aries.util.manifest.ManifestProcessor; import org.osgi.framework.Constants; import org.osgi.framework.Version; import org.osgi.resource.Capability; import org.osgi.resource.Requirement; import org.osgi.resource.Resource; import org.osgi.service.subsystem.SubsystemConstants; public class SubsystemManifest { public static class Builder { private Map<String, Header<?>> headers = new HashMap<String, Header<?>>(); public SubsystemManifest build() { return new SubsystemManifest(headers); } public Builder content(String value) { return value == null ? this : content(new SubsystemContentHeader(value)); } public Builder content(Collection<Resource> value) { return value == null || value.isEmpty() ? this : content(SubsystemContentHeader.newInstance(value)); } public Builder content(SubsystemContentHeader value) { return header(value); } public Builder header(Header<?> value) { if (value != null) headers.put(value.getName(), value); return this; } public Builder manifest(SubsystemManifest value) { for (Entry<String, Header<?>> entry : value.getHeaders().entrySet()) header(entry.getValue()); return this; } public Builder symbolicName(String value) { return value == null ? this : symbolicName(new SubsystemSymbolicNameHeader(value)); } public Builder symbolicName(SubsystemSymbolicNameHeader value) { return header(value); } public Builder type(String value) { return value == null ? this : type(new SubsystemTypeHeader(value)); } public Builder type(SubsystemTypeHeader value) { return header(value); } public Builder version(String value) { return value == null ? this : version(Version.parseVersion(value)); } public Builder version(Version value) { return value == null ? this : version(new SubsystemVersionHeader(value)); } public Builder version(SubsystemVersionHeader value) { return header(value); } } public static final String EXPORT_PACKAGE = Constants.EXPORT_PACKAGE; public static final String IMPORT_PACKAGE = Constants.IMPORT_PACKAGE; public static final String PREFERRED_PROVIDER = SubsystemConstants.PREFERRED_PROVIDER; public static final String PROVIDE_CAPABILITY = Constants.PROVIDE_CAPABILITY; public static final String REQUIRE_BUNDLE = Constants.REQUIRE_BUNDLE; public static final String REQUIRE_CAPABILITY = Constants.REQUIRE_CAPABILITY; public static final String SUBSYSTEM_CONTENT = SubsystemConstants.SUBSYSTEM_CONTENT; public static final String SUBSYSTEM_DESCRIPTION = SubsystemConstants.SUBSYSTEM_DESCRIPTION; public static final String SUBSYSTEM_EXPORTSERVICE = SubsystemConstants.SUBSYSTEM_EXPORTSERVICE; public static final String SUBSYSTEM_IMPORTSERVICE = SubsystemConstants.SUBSYSTEM_IMPORTSERVICE; public static final String SUBSYTEM_LOCALIZATION = SubsystemConstants.SUBSYSTEM_LOCALIZATION; public static final String SUBSYSTEM_MANIFESTVERSION = SubsystemConstants.SUBSYSTEM_MANIFESTVERSION; public static final String SUBSYSTEM_NAME = SubsystemConstants.SUBSYSTEM_NAME; public static final String SUBSYSTEM_SYMBOLICNAME = SubsystemConstants.SUBSYSTEM_SYMBOLICNAME; public static final String SUBSYSTEM_TYPE = SubsystemConstants.SUBSYSTEM_TYPE; public static final String SUBSYSTEM_VERSION = SubsystemConstants.SUBSYSTEM_VERSION; private static Map<String, Header<?>> parseHeaders(java.util.jar.Manifest manifest) { Map<String, Header<?>> result = new HashMap<String, Header<?>>(); for (Entry<Object, Object> entry : manifest.getMainAttributes().entrySet()) { String key = String.valueOf(entry.getKey()); result.put(key, HeaderFactory.createHeader(key, String.valueOf(entry.getValue()))); } return result; } private static void fillInDefaults(Map<String, Header<?>> headers) { Header<?> header = headers.get(SUBSYSTEM_VERSION); if (header == null) { headers.put(SUBSYSTEM_VERSION, SubsystemVersionHeader.DEFAULT); } header = headers.get(SUBSYSTEM_TYPE); if (header == null) headers.put(SUBSYSTEM_TYPE, SubsystemTypeHeader.DEFAULT); header = headers.get(SUBSYTEM_LOCALIZATION); if (header == null) headers.put(SUBSYTEM_LOCALIZATION, SubsystemLocalizationHeader.DEFAULT); } private final Map<String, Header<?>> headers; private SubsystemManifest(Map<String, Header<?>> headers) { Map<String, Header<?>> map = new HashMap<String, Header<?>>(headers); fillInDefaults(map); this.headers = Collections.unmodifiableMap(map); } public SubsystemManifest(java.util.jar.Manifest manifest) { this(parseHeaders(manifest)); } public SubsystemManifest(File file) throws FileNotFoundException, IOException { this(new FileInputStream(file)); } public SubsystemManifest(InputStream in) throws IOException { Manifest manifest = ManifestProcessor.parseManifest(in); Attributes attributes = manifest.getMainAttributes(); Map<String, Header<?>> headers = new HashMap<String, Header<?>>(attributes.size() + 4); // Plus the # of potentially derived headers. for (Entry<Object, Object> entry : attributes.entrySet()) { String key = String.valueOf(entry.getKey()); headers.put(key, HeaderFactory.createHeader(key, String.valueOf(entry.getValue()))); } fillInDefaults(headers); this.headers = Collections.unmodifiableMap(headers); } public SubsystemManifest(String symbolicName, Version version, Collection<Resource> content) { this(null, symbolicName, version, content); } public SubsystemManifest(SubsystemManifest manifest, String symbolicName, Version version, Collection<Resource> content) { Map<String, Header<?>> headers; if (manifest == null) { headers = new HashMap<String, Header<?>>(4); } else { headers = new HashMap<String, Header<?>>(manifest.headers); } Header<?> header = headers.get(SUBSYSTEM_SYMBOLICNAME); if (header == null) headers.put(SUBSYSTEM_SYMBOLICNAME, new SubsystemSymbolicNameHeader(symbolicName)); header = headers.get(SUBSYSTEM_VERSION); if (header == null && !(version == null)) { headers.put(SUBSYSTEM_VERSION, new SubsystemVersionHeader(version)); } header = headers.get(SUBSYSTEM_CONTENT); if (header == null && content != null && !content.isEmpty()) { headers.put(SubsystemContentHeader.NAME, SubsystemContentHeader.newInstance(content)); } fillInDefaults(headers); this.headers = Collections.unmodifiableMap(headers); } public Map<String, Header<?>> getHeaders() { return headers; } public ExportPackageHeader getExportPackageHeader() { return (ExportPackageHeader)getHeaders().get(EXPORT_PACKAGE); } public ImportPackageHeader getImportPackageHeader() { return (ImportPackageHeader)getHeaders().get(IMPORT_PACKAGE); } public PreferredProviderHeader getPreferredProviderHeader() { return (PreferredProviderHeader)getHeaders().get(PREFERRED_PROVIDER); } public ProvideCapabilityHeader getProvideCapabilityHeader() { return (ProvideCapabilityHeader)getHeaders().get(PROVIDE_CAPABILITY); } public RequireBundleHeader getRequireBundleHeader() { return (RequireBundleHeader)getHeaders().get(REQUIRE_BUNDLE); } public RequireCapabilityHeader getRequireCapabilityHeader() { return (RequireCapabilityHeader)getHeaders().get(REQUIRE_CAPABILITY); } public SubsystemContentHeader getSubsystemContentHeader() { return (SubsystemContentHeader)getHeaders().get(SUBSYSTEM_CONTENT); } public SubsystemExportServiceHeader getSubsystemExportServiceHeader() { return (SubsystemExportServiceHeader)getHeaders().get(SUBSYSTEM_EXPORTSERVICE); } public SubsystemImportServiceHeader getSubsystemImportServiceHeader() { return (SubsystemImportServiceHeader)getHeaders().get(SUBSYSTEM_IMPORTSERVICE); } public SubsystemLocalizationHeader getSubsystemLocalizationHeader() { return (SubsystemLocalizationHeader)getHeaders().get(SUBSYTEM_LOCALIZATION); } public SubsystemSymbolicNameHeader getSubsystemSymbolicNameHeader() { return (SubsystemSymbolicNameHeader)getHeaders().get(SUBSYSTEM_SYMBOLICNAME); } public SubsystemTypeHeader getSubsystemTypeHeader() { return (SubsystemTypeHeader)getHeaders().get(SUBSYSTEM_TYPE); } public SubsystemVersionHeader getSubsystemVersionHeader() { return (SubsystemVersionHeader)getHeaders().get(SUBSYSTEM_VERSION); } public List<Capability> toCapabilities(Resource resource) { ArrayList<Capability> capabilities = new ArrayList<Capability>(); for (Header<?> header : headers.values()) if (header instanceof CapabilityHeader) capabilities.addAll(((CapabilityHeader<?>)header).toCapabilities(resource)); capabilities.add(new OsgiIdentityCapability( resource, getSubsystemSymbolicNameHeader().getSymbolicName(), getSubsystemVersionHeader().getVersion(), getSubsystemTypeHeader().getType())); capabilities.trimToSize(); return capabilities; } public List<Requirement> toRequirements(Resource resource) { ArrayList<Requirement> requirements = new ArrayList<Requirement>(); for (Header<?> header : headers.values()) if (header instanceof RequirementHeader && !((header instanceof SubsystemContentHeader) || (header instanceof PreferredProviderHeader))) requirements.addAll(((RequirementHeader<?>)header).toRequirements(resource)); requirements.trimToSize(); return requirements; } @Override public String toString() { StringBuilder builder = new StringBuilder("[Subsystem Manifest: "); Iterator<Header<?>> iterator = headers.values().iterator(); if (iterator.hasNext()) { Header<?> header = iterator.next(); builder.append(header.getName()).append('=').append(header.getValue()); while (iterator.hasNext()) { header = iterator.next(); builder.append(", ").append(header.getName()).append('=').append(header.getValue()); } } return builder.append(']').toString(); } public void write(OutputStream out) throws IOException { Manifest manifest = new Manifest(); Attributes attributes = manifest.getMainAttributes(); // The manifest won't write anything unless the following header is present. attributes.put(Attributes.Name.MANIFEST_VERSION, "1.0"); for (Entry<String, Header<?>> entry : headers.entrySet()) { attributes.putValue(entry.getKey(), entry.getValue().getValue()); } manifest.write(out); } @Override public int hashCode() { return 31 * 17 + headers.hashCode(); } @Override public boolean equals(Object o) { if (o == this) { return true; } if (!(o instanceof SubsystemManifest)) { return false; } SubsystemManifest that = (SubsystemManifest)o; return that.headers.equals(this.headers); } }
8,556
0
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/archive/BundleManifestVersionHeader.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.aries.subsystem.core.archive; import org.osgi.framework.Constants; public class BundleManifestVersionHeader extends VersionHeader { public static final String DEFAULT_VALUE = "2.0"; public static final String NAME = Constants.BUNDLE_MANIFESTVERSION; public BundleManifestVersionHeader() { this(DEFAULT_VALUE); } public BundleManifestVersionHeader(String value) { super(NAME, value); } }
8,557
0
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/archive/VersionHeader.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.aries.subsystem.core.archive; import org.osgi.framework.Version; public abstract class VersionHeader extends AbstractHeader { protected final Version version; public VersionHeader(String name, String value) { this(name, Version.parseVersion(value)); } public VersionHeader(String name, Version value) { super(name, value.toString()); version = value; } public Version getVersion() { return version; } }
8,558
0
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/archive/Grammar.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.aries.subsystem.core.archive; public interface Grammar { // section: *header +newline // nonempty-section: +header +newline // newline: CR LF | LF | CR (not followed by LF) // header: name : value // name: alphanum *headerchar // value: SPACE *otherchar newline *continuation // continuation: SPACE *otherchar newline // alphanum: {A-Z} | {a-z} | {0-9} // headerchar: alphanum | - | _ // otherchar: any UTF-8 character except NUL, CR and LF // public static final String ALPHA = "[A-Za-z]"; // public static final String DIGIT = "[0-9]"; // public static final String ALPHANUM = ALPHA + '|' + DIGIT; // public static final String NEWLINE = "\r\n|\n|\r"; // public static final String OTHERCHAR = "[^\u0000\r\n]"; // public static final String SPACE = " "; // public static final String CONTINUATION = SPACE + OTHERCHAR + "*(?:" + NEWLINE + ')'; // public static final String HEADERCHAR = ALPHANUM + "|-|_"; // public static final String NAME = "(?:" + ALPHANUM + ")(?:" + HEADERCHAR + ")*"; // public static final String VALUE = SPACE + OTHERCHAR + "*(?:" + NEWLINE + ")(?:" + CONTINUATION + ")*"; // public static final String HEADER = NAME + ':' + VALUE; // public static final String SECTION = "(?:" + HEADER + ")*(?:" + NEWLINE + ")+"; // public static final String NONEMPTY_SECTION = "(?:" + HEADER + ")+(?:" + NEWLINE + ")+"; // manifest-file: main-section newline *individual-section // main-section: version-info newline *main-attribute // version-info: Manifest-Version : version-number // version-number : digit+{.digit+}* // main-attribute: (any legitimate main attribute) newline // individual-section: Name : value newline *perentry-attribute // perentry-attribute: (any legitimate perentry attribute) newline // digit: {0-9} // public static final String VERSION_NUMBER = DIGIT + "+(?:\\." + DIGIT + "+)*"; // public static final String VERSION_INFO = "Manifest-Version: " + VERSION_NUMBER; // public static final String MAIN_ATTRIBUTE = HEADER + NEWLINE; // public static final String MAIN_SECTION = VERSION_INFO + NEWLINE + "(?:" + MAIN_ATTRIBUTE + ")*"; // public static final String PERENTRY_ATTRIBUTE = HEADER + NEWLINE; // public static final String INDIVIDUAL_SECTION = "Name: " + VALUE + NEWLINE + "(?:" + PERENTRY_ATTRIBUTE + ")*"; // public static final String MANIFEST_FILE = MAIN_SECTION + NEWLINE + "(?:" + INDIVIDUAL_SECTION + ")*"; // digit ::= [0..9] // alpha ::= [a..zA..Z] // alphanum ::= alpha | digit // extended ::= ( alphanum | _ | - | . )+ // quoted-string ::= " ( ~["\#x0D#x0A#x00] | \"|\\)* " // argument ::= extended | quoted-string // parameter ::= directive | attribute // directive ::= extended := argument // attribute ::= extended = argument // path ::= path-unquoted | (" path-unquoted ") // path-unquoted ::= path-sep | path-sep? path-element (path-sep path-element)* // path-element ::= ~[/"\#x0D#x0A#x00]+ // path-sep ::= / // header ::= clause ( , clause ) * // clause ::= path ( ; path ) * ( ; parameter ) * public static final String DIGIT = "[0-9]"; public static final String ALPHA = "[A-Za-z]"; public static final String ALPHANUM = DIGIT + '|' + ALPHA; public static final String TOKEN = "(?:" + ALPHANUM + "|_|-)+?"; public static final String EXTENDED = "(?:" + ALPHANUM + "|_|-|\\.)+"; public static final String QUOTED_STRING = "\"(?:[^\\\\\"\r\n\u0000]|\\\\\"|\\\\\\\\)*\""; public static final String ARGUMENT = EXTENDED + '|' + QUOTED_STRING; public static final String DIRECTIVE = EXTENDED + ":=(?:" + ARGUMENT + ')'; public static final String ATTRIBUTE = EXTENDED + "=(?:" + ARGUMENT + ')'; public static final String PARAMETER = "(?:" + DIRECTIVE + ")|(?:" + ATTRIBUTE + ')'; public static final String PATH_ELEMENT = "[^/\"\r\n\u0000]+"; public static final String PATH_ELEMENT_NT = "[^/\"\r\n\u0000\\:=;, ]+"; public static final String PATH_SEP = "/"; public static final String PATH_UNQUOTED = PATH_SEP + '|' + PATH_SEP + '?' + PATH_ELEMENT + "(?:" + PATH_SEP + PATH_ELEMENT + ")*"; public static final String PATH_UNQUOTED_NT = PATH_SEP + '|' + PATH_SEP + '?' + PATH_ELEMENT_NT + "(?:" + PATH_SEP + PATH_ELEMENT_NT + ")*"; public static final String PATH = "(?:" + PATH_UNQUOTED_NT + ")|\"(?:" + PATH_UNQUOTED + ")\""; public static final String CLAUSE = "(?:" + PATH + ")(?:;" + PATH + ")*(?:;\\s*(?:" + PARAMETER + "))*"; public static final String HEADERCHAR = ALPHANUM + "|_|-"; public static final String NAME = ALPHANUM + "(?:" + HEADERCHAR + ")*"; public static final String HEADER = NAME + ": " + CLAUSE + "(?:," + CLAUSE + ")*"; /* * jletter ::= a character for which the method Character.isJavaIdentifierStart(int) returns true * jletterordigit::= a character for which the method Character.isJavaIdentifierPart(int) returns true * identifier ::= jletter jletterordigit * * unique-name ::= identifier ( ’.’ identifier )* * package-name ::= unique-name * Import-Package ::= import ( ',' import )* * import ::= package-names ( ';' parameter )* * package-names ::= package-name ( ';' package-name )* // See 1.3.2 */ public static final String JLETTER = "\\p{javaJavaIdentifierStart}"; public static final String JLETTERORDIGIT = "\\p{javaJavaIdentifierPart}"; public static final String IDENTIFIER = JLETTER + "(?:" + JLETTERORDIGIT + ")*"; public static final String UNIQUENAME = IDENTIFIER + "(?:\\." + IDENTIFIER + ")*"; public static final String SYMBOLICNAME = TOKEN + "(?:\\." + TOKEN + ")*"; public static final String PACKAGENAME = UNIQUENAME; public static final String PACKAGENAMES = PACKAGENAME + "\\s*(?:\\;\\s*" + PACKAGENAME + ")*"; public static final String IMPORT = PACKAGENAMES + "(?:;\\s*(?:" + PARAMETER + "))*"; public static final String IMPORTPACKAGE = IMPORT + "(?:\\,\\s*" + IMPORT + ")*"; public static final String NAMESPACE = SYMBOLICNAME; public static final String BUNDLE_DESCRIPTION = SYMBOLICNAME + "(?:;\\s*(?:" + PARAMETER + "))*"; public static final String REQUIRE_BUNDLE = BUNDLE_DESCRIPTION + "(?:,\\s*(?:" + BUNDLE_DESCRIPTION + "))*"; public static final String EXPORT = PACKAGENAMES + "(?:;\\s*(?:" + PARAMETER + "))*"; public static final String EXPORT_PACKAGE = EXPORT + "(?:,\\s*(?:" + EXPORT + "))*"; public static final String SCALAR = "String|Version|Long|Double"; public static final String LIST = "List<(?:" + SCALAR + ")>"; public static final String TYPE = "(?:" + SCALAR + ")|" + LIST; public static final String TYPED_ATTR = EXTENDED + "(?:\\:" + TYPE + ")?=(?:" + ARGUMENT + ')'; public static final String REQUIREMENT = NAMESPACE + "(?:;\\s*(?:(?:" + DIRECTIVE + ")|(?:" + TYPED_ATTR + ")))*"; public static final String REQUIRE_CAPABILITY = REQUIREMENT + "(?:,\\s*(?:" + REQUIREMENT + "))*"; public static final String CAPABILITY = NAMESPACE + "(?:;\\s*(?:(?:" + DIRECTIVE + ")|(?:" + TYPED_ATTR + ")))*"; public static final String PROVIDE_CAPABILITY = CAPABILITY + "(?:,\\s*(?:" + CAPABILITY + "))*"; public static final String OBJECTCLASS = PACKAGENAME; public static final String SERVICE_OR_WILDCARD = "(" + OBJECTCLASS + "|[*])(?:;\\s*(?:" + PARAMETER + "))*"; public static final String RESOURCE = SYMBOLICNAME + "(?:;\\s*(?:" + PARAMETER + "))*"; public static final String PREFERRED_PROVIDER = RESOURCE + "(?:,\\s*(?:" + RESOURCE + "))*"; /* * number ::= digit+ * version ::= major( '.' minor ( '.' micro ( '.' qualifier )? )? )? * major ::= number // See 1.3.2 * minor ::= number * micro ::= number * qualifier ::= ( alphanum | ’_’ | '-' )+ * version-range ::= interval | atleast * interval ::= ( '[' | '(' ) floor ',' ceiling ( ']' | ')' ) * atleast ::= version * floor ::= version * ceiling ::= version */ public static final String NUMBER = DIGIT + '+'; public static final String MAJOR = NUMBER; public static final String MINOR = NUMBER; public static final String MICRO = NUMBER; public static final String QUALIFIER = "(?:" + ALPHANUM + "|_|-)+"; public static final String VERSION = MAJOR + "(?:\\." + MINOR + "(?:\\." + MICRO + "(?:\\." + QUALIFIER + ")?)?)?"; public static final String ATLEAST = VERSION; public static final String FLOOR = VERSION; public static final String CEILING = VERSION; public static final String INTERVAL = "[\\[\\(]" + FLOOR + ',' + CEILING + "[\\[\\)]"; public static final String VERSIONRANGE = INTERVAL + '|' + ATLEAST; public static final String WILDCARD_NAME = PACKAGENAME + '|' + PACKAGENAME + "\\.\\*" + "|\\*"; public static final String WILDCARD_NAMES = WILDCARD_NAME + "\\s*(?:\\;\\s*" + WILDCARD_NAME + ")*"; public static final String DYNAMIC_DESCRIPTION = WILDCARD_NAMES + "(?:;\\s*(?:" + PARAMETER + "))*"; public static final String DYNAMICIMPORT_PACKAGE = DYNAMIC_DESCRIPTION + "(?:\\,\\s*" + DYNAMIC_DESCRIPTION + ")*"; }
8,559
0
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/archive/PreferredProviderHeader.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.aries.subsystem.core.archive; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.apache.aries.subsystem.core.internal.ResourceHelper; import org.osgi.framework.VersionRange; import org.osgi.resource.Resource; import org.osgi.service.subsystem.SubsystemConstants; public class PreferredProviderHeader extends AbstractClauseBasedHeader<PreferredProviderHeader.Clause> implements RequirementHeader<PreferredProviderHeader.Clause> { public static class Clause extends AbstractClause { public static final String ATTRIBUTE_TYPE = TypeAttribute.NAME; public static final String ATTRIBUTE_VERSION = VersionRangeAttribute.NAME_VERSION; public Clause(String clause) { super( parsePath(clause, Patterns.SYMBOLIC_NAME, false), parseParameters(clause, true), generateDefaultParameters( VersionRangeAttribute.DEFAULT_VERSION, TypeAttribute.newInstance(SubsystemConstants.SUBSYSTEM_TYPE_COMPOSITE))); } public boolean contains(Resource resource) { return getSymbolicName().equals( ResourceHelper.getSymbolicNameAttribute(resource)) && getVersionRange().includes( ResourceHelper.getVersionAttribute(resource)) && getType().equals( ResourceHelper.getTypeAttribute(resource)); } public String getSymbolicName() { return path; } public String getType() { return (String)getAttribute(ATTRIBUTE_TYPE).getValue(); } public VersionRange getVersionRange() { Attribute attribute = getAttribute(ATTRIBUTE_VERSION); if (attribute instanceof VersionRangeAttribute) return ((VersionRangeAttribute)attribute).getVersionRange(); return new VersionRange(attribute.getValue().toString()); } public PreferredProviderRequirement toRequirement(Resource resource) { return new PreferredProviderRequirement(this, resource); } @Override public String toString() { StringBuilder builder = new StringBuilder() .append(getPath()); for (Parameter parameter : getParameters()) { builder.append(';').append(parameter); } return builder.toString(); } } public static final String NAME = SubsystemConstants.PREFERRED_PROVIDER; public PreferredProviderHeader(Collection<Clause> clauses) { super(clauses); } public PreferredProviderHeader(String value) { super( value, new ClauseFactory<Clause>() { @Override public Clause newInstance(String clause) { return new Clause(clause); } }); } public boolean contains(Resource resource) { for (Clause clause : getClauses()) if (clause.contains(resource)) return true; return false; } @Override public String getName() { return NAME; } @Override public String getValue() { return toString(); } @Override public List<PreferredProviderRequirement> toRequirements(Resource resource) { List<PreferredProviderRequirement> requirements = new ArrayList<PreferredProviderRequirement>(clauses.size()); for (Clause clause : clauses) requirements.add(clause.toRequirement(resource)); return requirements; } }
8,560
0
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/archive/DirectiveFactory.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.aries.subsystem.core.archive; import java.util.HashMap; import java.util.Map; public class DirectiveFactory { private interface Creator { Directive create(String value); } private static final Map<String, Creator> map = new HashMap<String, Creator>(); static { map.put(AriesProvisionDependenciesDirective.NAME, new Creator() { @Override public Directive create(String value) { return AriesProvisionDependenciesDirective.getInstance(value); } }); map.put(CardinalityDirective.NAME, new Creator() { @Override public Directive create(String value) { return CardinalityDirective.getInstance(value); } }); map.put(EffectiveDirective.NAME, new Creator() { @Override public Directive create(String value) { return EffectiveDirective.getInstance(value); } }); map.put(FilterDirective.NAME, new Creator() { @Override public Directive create(String value) { return new FilterDirective(value); } }); map.put(ProvisionPolicyDirective.NAME, new Creator() { @Override public Directive create(String value) { return ProvisionPolicyDirective.getInstance(value); } }); map.put(ReferenceDirective.NAME, new Creator() { @Override public Directive create(String value) { return ReferenceDirective.getInstance(value); } }); map.put(ResolutionDirective.NAME, new Creator() { @Override public Directive create(String value) { return ResolutionDirective.getInstance(value); } }); map.put(StartOrderDirective.NAME, new Creator() { @Override public Directive create(String value) { return new StartOrderDirective(value); } }); map.put(VisibilityDirective.NAME, new Creator() { @Override public Directive create(String value) { return VisibilityDirective.getInstance(value); } }); } public static Directive createDirective(String name, String value) { Creator creator = map.get(name); if (creator == null) { return new GenericDirective(name, value); } return creator.create(value); } }
8,561
0
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/archive/Parameter.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.aries.subsystem.core.archive; public interface Parameter { String getName(); Object getValue(); }
8,562
0
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/archive/ProvisionResourceHeader.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.aries.subsystem.core.archive; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.apache.aries.subsystem.core.internal.ResourceHelper; import org.apache.aries.subsystem.core.internal.Utils; import org.osgi.framework.Version; import org.osgi.resource.Requirement; import org.osgi.resource.Resource; import org.osgi.service.subsystem.SubsystemConstants; public class ProvisionResourceHeader extends AbstractClauseBasedHeader<ProvisionResourceHeader.Clause> implements RequirementHeader<ProvisionResourceHeader.Clause> { public static class Clause extends AbstractClause { public static final String ATTRIBUTE_DEPLOYEDVERSION = DeployedVersionAttribute.NAME; public static final String ATTRIBUTE_RESOURCEID = "resourceId"; public static final String ATTRIBUTE_TYPE = TypeAttribute.NAME; public Clause(String clause) { super( parsePath(clause, Patterns.SYMBOLIC_NAME, false), parseParameters(clause, false), generateDefaultParameters( TypeAttribute.DEFAULT)); } public Clause(Resource resource) { this(appendResource(resource, new StringBuilder()).toString()); } public boolean contains(Resource resource) { return getSymbolicName().equals( ResourceHelper.getSymbolicNameAttribute(resource)) && getDeployedVersion().equals( ResourceHelper.getVersionAttribute(resource)) && getType().equals( ResourceHelper.getTypeAttribute(resource)); } public Version getDeployedVersion() { return ((DeployedVersionAttribute)getAttribute(ATTRIBUTE_DEPLOYEDVERSION)).getVersion(); } public String getSymbolicName() { return path; } public String getType() { return ((TypeAttribute)getAttribute(ATTRIBUTE_TYPE)).getType(); } public ProvisionResourceRequirement toRequirement(Resource resource) { return new ProvisionResourceRequirement(this, resource); } } public static final String NAME = SubsystemConstants.PROVISION_RESOURCE; public static ProvisionResourceHeader newInstance(Collection<Resource> resources) { StringBuilder builder = new StringBuilder(); for (Resource resource : resources) { appendResource(resource, builder); builder.append(','); } // Remove the trailing comma. // TODO Intentionally letting the exception propagate since there must be at least one resource. builder.deleteCharAt(builder.length() - 1); return new ProvisionResourceHeader(builder.toString()); } private static StringBuilder appendResource(Resource resource, StringBuilder builder) { String symbolicName = ResourceHelper.getSymbolicNameAttribute(resource); Version version = ResourceHelper.getVersionAttribute(resource); String type = ResourceHelper.getTypeAttribute(resource); builder.append(symbolicName) .append(';') .append(Clause.ATTRIBUTE_DEPLOYEDVERSION) .append('=') .append(version.toString()) .append(';') .append(Clause.ATTRIBUTE_TYPE) .append('=') .append(type) .append(';') .append(Clause.ATTRIBUTE_RESOURCEID) .append('=') .append(Utils.getId(resource)); return builder; } public ProvisionResourceHeader(Collection<Clause> clauses) { super(clauses); } public ProvisionResourceHeader(String value) { super( value, new ClauseFactory<Clause>() { @Override public Clause newInstance(String clause) { return new Clause(clause); } }); } public boolean contains(Resource resource) { for (Clause clause : getClauses()) if (clause.contains(resource)) return true; return false; } public Clause getClause(Resource resource) { String symbolicName = ResourceHelper.getSymbolicNameAttribute(resource); Version version = ResourceHelper.getVersionAttribute(resource); String type = ResourceHelper.getTypeAttribute(resource); for (Clause clause : clauses) { if (symbolicName.equals(clause.getPath()) && clause.getDeployedVersion().equals(version) && type.equals(clause.getType())) return clause; } return null; } @Override public String getName() { return NAME; } @Override public String getValue() { return toString(); } @Override public List<Requirement> toRequirements(Resource resource) { List<Requirement> requirements = new ArrayList<Requirement>(clauses.size()); for (Clause clause : clauses) requirements.add(clause.toRequirement(resource)); return requirements; } }
8,563
0
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/archive/ExportPackageHeader.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.aries.subsystem.core.archive; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import org.osgi.framework.Constants; import org.osgi.resource.Resource; public class ExportPackageHeader extends AbstractClauseBasedHeader<ExportPackageHeader.Clause> implements CapabilityHeader<ExportPackageHeader.Clause> { public static class Clause extends AbstractClause { public static final String ATTRIBUTE_VERSION = Constants.VERSION_ATTRIBUTE; public static final String DIRECTIVE_EXCLUDE = Constants.EXCLUDE_DIRECTIVE; public static final String DIRECTIVE_INCLUDE = Constants.INCLUDE_DIRECTIVE; public static final String DIRECTIVE_MANDATORY = Constants.MANDATORY_DIRECTIVE; public static final String DIRECTIVE_USES = Constants.USES_DIRECTIVE; public Clause(String clause) { super( parsePath(clause, Patterns.PACKAGE_NAMES, false), parseParameters(clause, false), generateDefaultParameters( VersionAttribute.DEFAULT)); } @Override public Attribute getAttribute(String name) { Parameter result = parameters.get(name); if (result instanceof Attribute) { return (Attribute)result; } return null; } @Override public Collection<Attribute> getAttributes() { ArrayList<Attribute> attributes = new ArrayList<Attribute>(parameters.size()); for (Parameter parameter : parameters.values()) { if (parameter instanceof Attribute) { attributes.add((Attribute)parameter); } } attributes.trimToSize(); return attributes; } @Override public Directive getDirective(String name) { Parameter result = parameters.get(name); if (result instanceof Directive) { return (Directive)result; } return null; } @Override public Collection<Directive> getDirectives() { ArrayList<Directive> directives = new ArrayList<Directive>(parameters.size()); for (Parameter parameter : parameters.values()) { if (parameter instanceof Directive) { directives.add((Directive)parameter); } } directives.trimToSize(); return directives; } public Collection<String> getPackageNames() { return Arrays.asList(path.split(";")); } @Override public Parameter getParameter(String name) { return parameters.get(name); } @Override public Collection<Parameter> getParameters() { return Collections.unmodifiableCollection(parameters.values()); } @Override public String getPath() { return path; } public Collection<ExportPackageCapability> toCapabilities(Resource resource) { Collection<String> packageNames = getPackageNames(); Collection<ExportPackageCapability> result = new ArrayList<ExportPackageCapability>(packageNames.size()); for (String packageName : packageNames) { result.add(new ExportPackageCapability(packageName, parameters.values(), resource)); } return result; } } public static final String NAME = Constants.EXPORT_PACKAGE; public ExportPackageHeader(String value) { super( value, new ClauseFactory<Clause>() { @Override public Clause newInstance(String clause) { return new Clause(clause); } }); } @Override public String getName() { return NAME; } @Override public String getValue() { return toString(); } @Override public List<ExportPackageCapability> toCapabilities(Resource resource) { List<ExportPackageCapability> result = new ArrayList<ExportPackageCapability>(); for (Clause clause : clauses) result.addAll(clause.toCapabilities(resource)); return result; } @Override public String toString() { StringBuilder builder = new StringBuilder(); for (Clause clause : getClauses()) { builder.append(clause).append(','); } // Remove the trailing comma. Note at least one clause is guaranteed to exist. builder.deleteCharAt(builder.length() - 1); return builder.toString(); } }
8,564
0
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/archive/CardinalityDirective.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.aries.subsystem.core.archive; import org.osgi.resource.Namespace; public class CardinalityDirective extends AbstractDirective { public static final String NAME = Namespace.REQUIREMENT_CARDINALITY_DIRECTIVE; public static final String VALUE_MULTIPLE = Namespace.CARDINALITY_MULTIPLE; public static final String VALUE_SINGLE = Namespace.CARDINALITY_SINGLE; public static final CardinalityDirective MULTIPLE = new CardinalityDirective(VALUE_MULTIPLE); public static final CardinalityDirective SINGLE = new CardinalityDirective(VALUE_SINGLE); public static final CardinalityDirective DEFAULT = SINGLE; public static CardinalityDirective getInstance(String value) { if (VALUE_SINGLE.equals(value)) return SINGLE; if (VALUE_MULTIPLE.equals(value)) return MULTIPLE; return new CardinalityDirective(value); } public CardinalityDirective() { this(VALUE_SINGLE); } public CardinalityDirective(String value) { super(NAME, value); } public boolean isMultiple() { return MULTIPLE == this || VALUE_MULTIPLE.equals(getValue()); } public boolean isSingle() { return SINGLE == this || VALUE_SINGLE.equals(getValue()); } }
8,565
0
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/archive/ImportPackageRequirement.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.aries.subsystem.core.archive; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.apache.aries.subsystem.core.internal.AbstractRequirement; import org.osgi.framework.namespace.PackageNamespace; import org.osgi.resource.Resource; public class ImportPackageRequirement extends AbstractRequirement { public static final String DIRECTIVE_FILTER = PackageNamespace.REQUIREMENT_FILTER_DIRECTIVE; public static final String NAMESPACE = PackageNamespace.PACKAGE_NAMESPACE; private final Map<String, String> directives; private final Resource resource; public ImportPackageRequirement(ImportPackageHeader.Clause clause, Resource resource) { Collection<Directive> clauseDirectives = clause.getDirectives(); directives = new HashMap<String, String>(clauseDirectives.size() + 1); for (Directive directive : clauseDirectives) directives.put(directive.getName(), directive.getValue()); Collection<String> packageNames = clause.getPackageNames(); if (packageNames.isEmpty() || packageNames.size() > 1) throw new IllegalArgumentException("Only one package name per requirement allowed"); StringBuilder filter = new StringBuilder("(&(").append(NAMESPACE) .append('=').append(packageNames.iterator().next()).append(')'); VersionRangeAttribute versionRange = clause.getVersionRangeAttribute(); if (versionRange != null) { versionRange.appendToFilter(filter); } for(Attribute packageAttribute : clause.getAttributes()) { if (!(packageAttribute instanceof VersionRangeAttribute)) { packageAttribute.appendToFilter(filter); } } directives.put(DIRECTIVE_FILTER, filter.append(')').toString()); this.resource = resource; } @Override public Map<String, Object> getAttributes() { return Collections.emptyMap(); } @Override public Map<String, String> getDirectives() { return Collections.unmodifiableMap(directives); } @Override public String getNamespace() { return NAMESPACE; } @Override public Resource getResource() { return resource; } }
8,566
0
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/archive/SymbolicNameHeader.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.aries.subsystem.core.archive; import java.util.regex.Pattern; public abstract class SymbolicNameHeader extends AbstractHeader { public SymbolicNameHeader(String name, String value) { super(name, value); if (getClauses().size() != 1) throw new IllegalArgumentException("Symbolic name headers must have one, and only one, clause: " + getClauses().size()); if (!Pattern.matches(Grammar.SYMBOLICNAME, getClauses().get(0).getPath())) throw new IllegalArgumentException("Invalid symbolic name: " + getClauses().get(0).getPath()); } public String getSymbolicName() { return getClauses().get(0).getPath(); } }
8,567
0
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/archive/RequirementHeader.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.aries.subsystem.core.archive; import java.util.List; import org.osgi.resource.Requirement; import org.osgi.resource.Resource; public interface RequirementHeader<C extends Clause> extends Header<C> { List<? extends Requirement> toRequirements(Resource resource); }
8,568
0
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/archive/ResolutionDirective.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.aries.subsystem.core.archive; import org.osgi.framework.Constants; public class ResolutionDirective extends AbstractDirective { public static final String NAME = Constants.RESOLUTION_DIRECTIVE; public static final String VALUE_MANDATORY = Constants.RESOLUTION_MANDATORY; public static final String VALUE_OPTIONAL = Constants.RESOLUTION_OPTIONAL; public static final ResolutionDirective MANDATORY = new ResolutionDirective(VALUE_MANDATORY); public static final ResolutionDirective OPTIONAL = new ResolutionDirective(VALUE_OPTIONAL); public ResolutionDirective() { this(VALUE_MANDATORY); } public static ResolutionDirective getInstance(String value) { if (VALUE_MANDATORY.equals(value)) return MANDATORY; if (VALUE_OPTIONAL.equals(value)) return OPTIONAL; throw new IllegalArgumentException("Invalid " + Constants.RESOLUTION_DIRECTIVE + " directive: " + value); } private ResolutionDirective(String value) { super(NAME, value); } public boolean isMandatory() { return MANDATORY == this || VALUE_MANDATORY.equals(getValue()); } public boolean isOptional() { return OPTIONAL == this || VALUE_OPTIONAL.equals(getValue()); } }
8,569
0
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/archive/AbstractAttribute.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.aries.subsystem.core.archive; public abstract class AbstractAttribute extends AbstractParameter implements Attribute { public AbstractAttribute(String name, Object value) { super(name, value); } @Override public StringBuilder appendToFilter(StringBuilder builder) { return builder.append('(').append(getName()).append('=').append(getValue()).append(')'); } @Override public String toString() { return new StringBuilder() .append(getName()) .append('=') .append(getValue()) .toString(); } }
8,570
0
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/archive/ProvideCapabilityHeader.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.aries.subsystem.core.archive; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.osgi.framework.Constants; import org.osgi.resource.Resource; public class ProvideCapabilityHeader extends AbstractClauseBasedHeader<ProvideCapabilityHeader.Clause> implements CapabilityHeader<ProvideCapabilityHeader.Clause> { public static class Clause extends AbstractClause { public static final String DIRECTIVE_EFFECTIVE = EffectiveDirective.NAME; public static final String DIRECTIVE_USES = Constants.USES_DIRECTIVE; private static final Collection<Parameter> defaultParameters = generateDefaultParameters( EffectiveDirective.DEFAULT); public Clause(String clause) { super( parsePath(clause, Patterns.NAMESPACE, false), parseTypedParameters(clause), defaultParameters); } public String getNamespace() { return path; } public ProvideCapabilityCapability toCapability(Resource resource) { return new ProvideCapabilityCapability(this, resource); } @Override public String toString() { StringBuilder builder = new StringBuilder() .append(getPath()); for (Parameter parameter : getParameters()) { builder.append(';').append(parameter); } return builder.toString(); } } public static final String NAME = Constants.PROVIDE_CAPABILITY; public ProvideCapabilityHeader(String value) { super( value, new ClauseFactory<Clause>() { @Override public Clause newInstance(String clause) { return new Clause(clause); } }); } @Override public String getName() { return NAME; } @Override public String getValue() { return toString(); } @Override public List<ProvideCapabilityCapability> toCapabilities(Resource resource) { List<ProvideCapabilityCapability> result = new ArrayList<ProvideCapabilityCapability>(); for (Clause clause : clauses) result.add(clause.toCapability(resource)); return result; } }
8,571
0
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/archive/Manifest.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.aries.subsystem.core.archive; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.jar.Attributes; import org.apache.aries.util.manifest.ManifestProcessor; public abstract class Manifest { protected final Map<String, Header> headers = Collections.synchronizedMap(new HashMap<String, Header>()); protected final java.util.jar.Manifest manifest; public Manifest(InputStream in) throws IOException { this(ManifestProcessor.parseManifest(in)); } public Manifest(java.util.jar.Manifest manifest) { this.manifest = manifest; for (Map.Entry<Object, Object> entry : manifest.getMainAttributes().entrySet()) { Header header = HeaderFactory.createHeader(String.valueOf(entry.getKey()), String.valueOf(entry.getValue())); headers.put(header.getName(), header); } if (headers.get(ManifestVersionHeader.NAME) == null) headers.put(ManifestVersionHeader.NAME, ManifestVersionHeader.DEFAULT); } public Manifest(File manifestFile) throws IOException { this(new FileInputStream(manifestFile)); } protected Manifest() { manifest = null; } public Header getHeader(String name) { return headers.get(name); } public Collection<Header> getHeaders() { return Collections.unmodifiableCollection(headers.values()); } public java.util.jar.Manifest getManifest() { return manifest; } public Header getManifestVersion() { return getHeader(Attributes.Name.MANIFEST_VERSION.toString()); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append('[').append(getClass().getName()).append(": "); if (!headers.values().isEmpty()) { for (Header header : headers.values()) sb.append(header.getName()).append('=').append(header.getValue()).append(", "); sb.delete(sb.length() - 2, sb.length()); } sb.append(']'); return sb.toString(); } public void write(OutputStream out) throws IOException { java.util.jar.Manifest m = new java.util.jar.Manifest(); Attributes attributes = m.getMainAttributes(); for (Header header : headers.values()) { attributes.putValue(header.getName(), header.getValue()); } m.write(out); } }
8,572
0
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/archive/DeploymentManifest.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.aries.subsystem.core.archive; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.jar.Attributes; import java.util.jar.Manifest; import org.apache.aries.subsystem.core.internal.BasicSubsystem; import org.apache.aries.util.manifest.ManifestProcessor; import org.osgi.framework.Constants; import org.osgi.resource.Resource; import org.osgi.service.resolver.ResolutionException; import org.osgi.service.subsystem.Subsystem; import org.osgi.service.subsystem.SubsystemConstants; public class DeploymentManifest { public static class Builder { private Map<String, Header<?>> headers = new HashMap<String, Header<?>>(); public DeploymentManifest build() { return new DeploymentManifest(headers); } public Builder autostart(boolean value) { header(new GenericHeader(ARIESSUBSYSTEM_AUTOSTART, Boolean.toString(value))); return this; } public Builder content(Resource resource, boolean referenced) { DeployedContentHeader header = (DeployedContentHeader)headers.get(DeploymentManifest.DEPLOYED_CONTENT); if (header == null) { DeployedContentHeader.Clause clause = new DeployedContentHeader.Clause(resource, referenced); header(new DeployedContentHeader(Collections.singleton(clause))); return this; } DeployedContentHeader.Clause clause = header.getClause(resource); if (clause == null) { clause = new DeployedContentHeader.Clause(resource, referenced); List<DeployedContentHeader.Clause> clauses = new ArrayList<DeployedContentHeader.Clause>(header.getClauses().size() + 1); clauses.addAll(header.getClauses()); clauses.add(clause); header(new DeployedContentHeader(clauses)); return this; } Collection<DeployedContentHeader.Clause> clauses = new ArrayList<DeployedContentHeader.Clause>(header.getClauses()); for (Iterator<DeployedContentHeader.Clause> i = clauses.iterator(); i.hasNext();) if (clause.equals(i.next())) { i.remove(); break; } clauses.add(new DeployedContentHeader.Clause(resource, referenced)); header(new DeployedContentHeader(clauses)); return this; } public Builder header(Header<?> value) { if (value != null) headers.put(value.getName(), value); return this; } public Builder id(long value) { header(new GenericHeader(ARIESSUBSYSTEM_ID, Long.toString(value))); return this; } public Builder lastId(long value) { header(new GenericHeader(ARIESSUBSYSTEM_LASTID, Long.toString(value))); return this; } public Builder location(String value) { if (value != null) header(new AriesSubsystemLocationHeader(value)); return this; } public Builder manifest(DeploymentManifest value) { if (value != null) for (Entry<String, Header<?>> entry : value.getHeaders().entrySet()) header(entry.getValue()); return this; } public Builder manifest(SubsystemManifest value) { if (value != null) for (Entry<String, Header<?>> entry : value.getHeaders().entrySet()) header(entry.getValue()); return this; } public Builder parent(BasicSubsystem value, boolean referenceCount) { AriesSubsystemParentsHeader.Clause clause = new AriesSubsystemParentsHeader.Clause(value, referenceCount); AriesSubsystemParentsHeader header = (AriesSubsystemParentsHeader)headers.get(ARIESSUBSYSTEM_PARENTS); if (header == null) header(new AriesSubsystemParentsHeader(Collections.singleton(clause))); else { Collection<AriesSubsystemParentsHeader.Clause> clauses = new ArrayList<AriesSubsystemParentsHeader.Clause>(header.getClauses().size() + 1); clauses.addAll(header.getClauses()); clauses.add(clause); header(new AriesSubsystemParentsHeader(clauses)); } return this; } public Builder region(String value) { if (value != null) header(new GenericHeader(ARIESSUBSYSTEM_REGION, value)); return this; } public Builder region(org.eclipse.equinox.region.Region value) { if (value != null) region(value.getName()); return this; } public Builder state(Subsystem.State value) { if (value != null) header(new GenericHeader(ARIESSUBSYSTEM_STATE, value.toString())); return this; } } public static final String DEPLOYED_CONTENT = SubsystemConstants.DEPLOYED_CONTENT; public static final String DEPLOYMENT_MANIFESTVERSION = SubsystemConstants.DEPLOYMENT_MANIFESTVERSION; public static final String EXPORT_PACKAGE = Constants.EXPORT_PACKAGE; public static final String IMPORT_PACKAGE = Constants.IMPORT_PACKAGE; public static final String PROVIDE_CAPABILITY = Constants.PROVIDE_CAPABILITY; public static final String PROVISION_RESOURCE = SubsystemConstants.PROVISION_RESOURCE; public static final String REQUIRE_BUNDLE = Constants.REQUIRE_BUNDLE; public static final String REQUIRE_CAPABILITY = Constants.REQUIRE_CAPABILITY; public static final String SUBSYSTEM_EXPORTSERVICE = SubsystemConstants.SUBSYSTEM_EXPORTSERVICE; public static final String SUBSYSTEM_IMPORTSERVICE = SubsystemConstants.SUBSYSTEM_IMPORTSERVICE; public static final String SUBSYSTEM_SYMBOLICNAME = SubsystemConstants.SUBSYSTEM_SYMBOLICNAME; public static final String SUBSYSTEM_VERSION = SubsystemConstants.SUBSYSTEM_VERSION; public static final String ARIESSUBSYSTEM_AUTOSTART = "AriesSubsystem-Autostart"; public static final String ARIESSUBSYSTEM_ID = "AriesSubsystem-Id"; public static final String ARIESSUBSYSTEM_LASTID = "AriesSubsystem-LastId"; public static final String ARIESSUBSYSTEM_LOCATION = AriesSubsystemLocationHeader.NAME; public static final String ARIESSUBSYSTEM_PARENTS = "AriesSubsystem-Parents"; public static final String ARIESSUBSYSTEM_REGION = "AriesSubsystem-Region"; public static final String ARIESSUBSYSTEM_STATE = "AriesSubsystem-State"; private final Map<String, Header<?>> headers; public DeploymentManifest(java.util.jar.Manifest manifest) { headers = new HashMap<String, Header<?>>(); for (Entry<Object, Object> entry : manifest.getMainAttributes().entrySet()) { String key = String.valueOf(entry.getKey()); if (key.equals(SubsystemManifest.SUBSYSTEM_SYMBOLICNAME)) continue; headers.put(key, HeaderFactory.createHeader(key, String.valueOf(entry.getValue()))); } } public DeploymentManifest(File file) throws IOException { this(new FileInputStream(file)); } public DeploymentManifest(InputStream in) throws IOException { Manifest manifest = ManifestProcessor.parseManifest(in); Attributes attributes = manifest.getMainAttributes(); Map<String, Header<?>> headers = new HashMap<String, Header<?>>(attributes.size() + 4); // Plus the # of potentially derived headers. for (Entry<Object, Object> entry : attributes.entrySet()) { String key = String.valueOf(entry.getKey()); headers.put(key, HeaderFactory.createHeader(key, String.valueOf(entry.getValue()))); } this.headers = Collections.unmodifiableMap(headers); } public DeploymentManifest( DeploymentManifest deploymentManifest, SubsystemManifest subsystemManifest, boolean autostart, long id, long lastId, String location, boolean overwrite, boolean acceptDependencies) throws ResolutionException, IOException, URISyntaxException { Map<String, Header<?>> headers; if (deploymentManifest == null // We're generating a new deployment manifest. || (deploymentManifest != null && overwrite)) { // A deployment manifest already exists but overwriting it with subsystem manifest content is desired. headers = computeHeaders(subsystemManifest); } else { headers = new HashMap<String, Header<?>>(deploymentManifest.getHeaders()); } // TODO DEPLOYMENT_MANIFESTVERSION headers.put(ARIESSUBSYSTEM_AUTOSTART, new GenericHeader(ARIESSUBSYSTEM_AUTOSTART, Boolean.toString(autostart))); headers.put(ARIESSUBSYSTEM_ID, new GenericHeader(ARIESSUBSYSTEM_ID, Long.toString(id))); headers.put(ARIESSUBSYSTEM_LOCATION, new AriesSubsystemLocationHeader(location)); headers.put(ARIESSUBSYSTEM_LASTID, new GenericHeader(ARIESSUBSYSTEM_LASTID, Long.toString(lastId))); this.headers = Collections.unmodifiableMap(headers); } private DeploymentManifest(Map<String, Header<?>> headers) { Map<String, Header<?>> map = new HashMap<String, Header<?>>(headers); this.headers = Collections.unmodifiableMap(map); } public DeployedContentHeader getDeployedContentHeader() { return (DeployedContentHeader)getHeaders().get(DEPLOYED_CONTENT); } public ExportPackageHeader getExportPackageHeader() { return (ExportPackageHeader)getHeaders().get(EXPORT_PACKAGE); } public Map<String, Header<?>> getHeaders() { return headers; } public AriesSubsystemParentsHeader getAriesSubsystemParentsHeader() { return (AriesSubsystemParentsHeader)getHeaders().get(ARIESSUBSYSTEM_PARENTS); } public ImportPackageHeader getImportPackageHeader() { return (ImportPackageHeader)getHeaders().get(IMPORT_PACKAGE); } public ProvideCapabilityHeader getProvideCapabilityHeader() { return (ProvideCapabilityHeader)getHeaders().get(PROVIDE_CAPABILITY); } public ProvisionResourceHeader getProvisionResourceHeader() { return (ProvisionResourceHeader)getHeaders().get(PROVISION_RESOURCE); } public RequireBundleHeader getRequireBundleHeader() { return (RequireBundleHeader)getHeaders().get(REQUIRE_BUNDLE); } public RequireCapabilityHeader getRequireCapabilityHeader() { return (RequireCapabilityHeader)getHeaders().get(REQUIRE_CAPABILITY); } public SubsystemExportServiceHeader getSubsystemExportServiceHeader() { return (SubsystemExportServiceHeader)getHeaders().get(SUBSYSTEM_EXPORTSERVICE); } public SubsystemImportServiceHeader getSubsystemImportServiceHeader() { return (SubsystemImportServiceHeader)getHeaders().get(SUBSYSTEM_IMPORTSERVICE); } public void write(OutputStream out) throws IOException { Manifest manifest = new Manifest(); Attributes attributes = manifest.getMainAttributes(); // The manifest won't write anything unless the following header is present. attributes.put(Attributes.Name.MANIFEST_VERSION, "1.0"); for (Entry<String, Header<?>> entry : headers.entrySet()) { attributes.putValue(entry.getKey(), entry.getValue().getValue()); } manifest.write(out); } private Map<String, Header<?>> computeHeaders(SubsystemManifest manifest) { return new HashMap<String, Header<?>>(manifest.getHeaders()); } @Override public int hashCode() { return 31 * 17 + headers.hashCode(); } @Override public boolean equals(Object o) { if (o == this) { return true; } if (!(o instanceof SubsystemManifest)) { return false; } DeploymentManifest that = (DeploymentManifest)o; return that.headers.equals(this.headers); } }
8,573
0
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/archive/RequireCapabilityRequirement.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.aries.subsystem.core.archive; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.apache.aries.subsystem.core.internal.AbstractRequirement; import org.osgi.resource.Namespace; import org.osgi.resource.Resource; public class RequireCapabilityRequirement extends AbstractRequirement { public static final String DIRECTIVE_FILTER = Namespace.REQUIREMENT_FILTER_DIRECTIVE; private final Map<String, Object> attributes; private final Map<String, String> directives; private final String namespace; private final Resource resource; public RequireCapabilityRequirement(RequireCapabilityHeader.Clause clause, Resource resource) { namespace = clause.getNamespace(); attributes = new HashMap<String, Object>(clause.getAttributes().size()); for (Attribute attribute : clause.getAttributes()) { attributes.put(attribute.getName(), attribute.getValue()); } directives = new HashMap<String, String>(clause.getDirectives().size()); for (Directive directive : clause.getDirectives()) { directives.put(directive.getName(), directive.getValue()); } this.resource = resource; } @Override public Map<String, Object> getAttributes() { return Collections.unmodifiableMap(attributes); } @Override public Map<String, String> getDirectives() { return Collections.unmodifiableMap(directives); } @Override public String getNamespace() { return namespace; } @Override public Resource getResource() { return resource; } }
8,574
0
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/archive/SubsystemLocalizationHeader.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.aries.subsystem.core.archive; import org.osgi.service.subsystem.SubsystemConstants; public class SubsystemLocalizationHeader extends AbstractHeader { public static final String DEFAULT_VALUE = "OSGI-INF/l10n/subsystem"; public static final String NAME = SubsystemConstants.SUBSYSTEM_LOCALIZATION; public static final SubsystemLocalizationHeader DEFAULT = new SubsystemLocalizationHeader(); private final String baseFileName; private final String directoryName; public SubsystemLocalizationHeader() { this(DEFAULT_VALUE); } public SubsystemLocalizationHeader(String value) { super(NAME, value); int index = value.lastIndexOf('/'); baseFileName = index == -1 ? value : value.substring(index + 1); directoryName = index == -1 ? null : value.substring(0, index + 1); } public String getBaseFileName() { return baseFileName; } public String getDirectoryName() { return directoryName; } }
8,575
0
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/archive/ProvisionResourceRequirement.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.aries.subsystem.core.archive; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.apache.aries.subsystem.core.internal.AbstractRequirement; import org.osgi.framework.namespace.IdentityNamespace; import org.osgi.resource.Resource; public class ProvisionResourceRequirement extends AbstractRequirement { public static final String DIRECTIVE_FILTER = IdentityNamespace.REQUIREMENT_FILTER_DIRECTIVE; public static final String NAMESPACE = IdentityNamespace.IDENTITY_NAMESPACE; private final Map<String, String> directives = new HashMap<String, String>(); private final Resource resource; public ProvisionResourceRequirement( ProvisionResourceHeader.Clause clause, Resource resource) { StringBuilder builder = new StringBuilder("(&(") .append(NAMESPACE).append('=') .append(clause.getSymbolicName()).append(')'); for (Attribute attribute : clause.getAttributes()) attribute.appendToFilter(builder); directives.put(DIRECTIVE_FILTER, builder.append(')').toString()); this.resource = resource; } @Override public Map<String, Object> getAttributes() { return Collections.emptyMap(); } @Override public Map<String, String> getDirectives() { return Collections.unmodifiableMap(directives); } @Override public String getNamespace() { return NAMESPACE; } @Override public Resource getResource() { return resource; } }
8,576
0
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/archive/EffectiveDirective.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.aries.subsystem.core.archive; import org.osgi.framework.Constants; public class EffectiveDirective extends AbstractDirective { public static final String NAME = Constants.EFFECTIVE_DIRECTIVE; public static final String VALUE_ACTIVE = Constants.EFFECTIVE_ACTIVE; public static final String VALUE_RESOLVE = Constants.EFFECTIVE_RESOLVE; public static final EffectiveDirective ACTIVE = new EffectiveDirective(VALUE_ACTIVE); public static final EffectiveDirective RESOLVE = new EffectiveDirective(VALUE_RESOLVE); public static final EffectiveDirective DEFAULT = RESOLVE; public static EffectiveDirective getInstance(String value) { if (VALUE_ACTIVE.equals(value)) return ACTIVE; if (VALUE_RESOLVE.equals(value)) return RESOLVE; return new EffectiveDirective(value); } public EffectiveDirective() { this(Constants.EFFECTIVE_RESOLVE); } public EffectiveDirective(String value) { super(NAME, value); } public boolean isActive() { return ACTIVE == this || Constants.EFFECTIVE_ACTIVE.equals(getValue()); } public boolean isResolve() { return RESOLVE == this || Constants.EFFECTIVE_RESOLVE.equals(getValue()); } }
8,577
0
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/archive/DeployedVersionAttribute.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.aries.subsystem.core.archive; import org.osgi.framework.Version; import org.osgi.framework.VersionRange; import org.osgi.service.subsystem.SubsystemConstants; public class DeployedVersionAttribute extends AbstractAttribute { public static final String NAME = SubsystemConstants.DEPLOYED_VERSION_ATTRIBUTE; private final Version deployedVersion; public DeployedVersionAttribute(String value) { super(NAME, value); deployedVersion = Version.parseVersion(value); } @Override public StringBuilder appendToFilter(StringBuilder builder) { VersionRange versionRange = new VersionRange(VersionRange.LEFT_CLOSED, getVersion(), getVersion(), VersionRange.RIGHT_CLOSED); return builder.append(versionRange.toFilterString(VersionRangeAttribute.NAME_VERSION)); } public Version getDeployedVersion() { return deployedVersion; } public Version getVersion() { return deployedVersion; } }
8,578
0
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/archive/BundleRequiredExecutionEnvironmentHeader.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.aries.subsystem.core.archive; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.osgi.framework.Constants; import org.osgi.framework.Version; import org.osgi.resource.Requirement; import org.osgi.resource.Resource; public class BundleRequiredExecutionEnvironmentHeader implements RequirementHeader<BundleRequiredExecutionEnvironmentHeader.Clause> { public static class Clause implements org.apache.aries.subsystem.core.archive.Clause { public static class ExecutionEnvironment { public static class Parser { private static final String BREE = "(" + Grammar.TOKEN + ")(?:-(" + Grammar.VERSION + "))?(?:/(" + Grammar.TOKEN + ")(?:-(" + Grammar.VERSION + "))?)?"; private static final Pattern PATTERN = Pattern.compile(BREE); public ExecutionEnvironment parse(String clause) { Matcher matcher = PATTERN.matcher(clause); if (matcher.matches() && versionsMatch(matcher)) { return new ExecutionEnvironment( computeName(matcher), computeVersion(matcher)); } else return new ExecutionEnvironment(clause); } private String computeName(Matcher matcher) { return computeName(matcher.group(1), matcher.group(3)); } private String computeName(String left, String right) { if (left.equalsIgnoreCase("J2SE")) left = "JavaSE"; if (right == null) return left; return new StringBuilder(left).append('/').append(right).toString(); } private Version computeVersion(Matcher matcher) { String version = matcher.group(2); if (version == null) version = matcher.group(4); if (version == null) return null; return Version.parseVersion(version); } private boolean versionsMatch(Matcher matcher) { String version1 = matcher.group(2); String version2 = matcher.group(4); if (version1 == null || version2 == null) return true; return version1.equals(version2); } } private final String name; private final Version version; public ExecutionEnvironment(String name) { this(name, null); } public ExecutionEnvironment(String name, Version version) { if (name == null) throw new NullPointerException(); this.name = name; this.version = version; } public String getName() { return name; } public Version getVersion() { return version; } } private final ExecutionEnvironment executionEnvironment; private final String path; public Clause(String clause) { path = clause; executionEnvironment = new ExecutionEnvironment.Parser().parse(clause); } @Override public Attribute getAttribute(String name) { return null; } @Override public Collection<Attribute> getAttributes() { return Collections.emptyList(); } @Override public Directive getDirective(String name) { return null; } @Override public Collection<Directive> getDirectives() { return Collections.emptyList(); } public ExecutionEnvironment getExecutionEnvironment() { return executionEnvironment; } @Override public Parameter getParameter(String name) { return null; } @Override public Collection<Parameter> getParameters() { return Collections.emptyList(); } @Override public String getPath() { return path; } public OsgiExecutionEnvironmentRequirement toRequirement(Resource resource) { return new OsgiExecutionEnvironmentRequirement(this, resource); } @Override public String toString() { return getPath(); } } @SuppressWarnings("deprecation") public static final String NAME = Constants.BUNDLE_REQUIREDEXECUTIONENVIRONMENT; private final Collection<Clause> clauses; public BundleRequiredExecutionEnvironmentHeader(String value) { ClauseTokenizer tokenizer = new ClauseTokenizer(value); clauses = new ArrayList<Clause>(tokenizer.getClauses().size()); for (String clause : tokenizer.getClauses()) clauses.add(new Clause(clause)); } @Override public Collection<Clause> getClauses() { return Collections.unmodifiableCollection(clauses); } @Override public String getName() { return NAME; } @Override public String getValue() { StringBuilder builder = new StringBuilder(); for (Clause clause : getClauses()) { builder.append(clause).append(','); } // Remove the trailing comma. Note at least one clause is guaranteed to exist. builder.deleteCharAt(builder.length() - 1); return builder.toString(); } @Override public List<? extends Requirement> toRequirements(Resource resource) { return Collections.singletonList(new OsgiExecutionEnvironmentRequirement(getClauses(), resource)); } @Override public String toString() { return getValue(); } }
8,579
0
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/archive/HeaderFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.aries.subsystem.core.archive; public class HeaderFactory { // public static final String APPLICATIONCONTENT_HEADER = ApplicationContentHeader.NAME; // public static final String APPLICATIONSYMBOLICNAME_HEADER = ApplicationSymbolicNameHeader.NAME; // public static final String APPLICATIONVERSION_HEADER = ApplicationVersionHeader.NAME; // public static final String FEATURECONTENT_HEADER = FeatureContentHeader.NAME; // public static final String FEATURESYMBOLICNAME_HEADER = FeatureSymbolicNameHeader.NAME; // public static final String FEATUREVERSION_HEADER = FeatureVersionHeader.NAME; // // private static final String REGEX = '(' + Grammar.NAME + "):\\ (" + Grammar.CLAUSE + ")(?:,(" + Grammar.CLAUSE + "))*"; // private static final Pattern PATTERN = Pattern.compile(REGEX); // public static Header createHeader(String header) { // Matcher matcher = PATTERN.matcher(header); // if (!matcher.matches()) // throw new IllegalArgumentException("Invalid header: " + header); // String name = matcher.group(1); // Collection<Clause> clauses = new HashSet<Clause>(matcher.groupCount()); // for (int i = 2; i <= matcher.groupCount(); i++) { // String group = matcher.group(i); // if (group == null) continue; // AbstractClause clause = new AbstractClause(group); // clauses.add(clause); // } // if (FEATURESYMBOLICNAME_HEADER.equals(name)) // return new FeatureSymbolicNameHeader(clauses); // if (FEATUREVERSION_HEADER.equals(name)) // return new FeatureVersionHeader(clauses); // if (FEATURECONTENT_HEADER.equals(name)) // return new FeatureContentHeader(clauses); // if (APPLICATIONSYMBOLICNAME_HEADER.equals(name)) // return new ApplicationSymbolicNameHeader(clauses); // if (APPLICATIONVERSION_HEADER.equals(name)) // return new ApplicationVersionHeader(clauses); // if (APPLICATIONCONTENT_HEADER.equals(name)) // return new ApplicationContentHeader(clauses); // return new GenericHeader(name, clauses); // } // private static final String REGEX = '(' + Grammar.CLAUSE + ")(?:,(" + Grammar.CLAUSE + "))*"; // private static final Pattern PATTERN = Pattern.compile(REGEX); public static Header<?> createHeader(String name, String value) { // Matcher matcher = PATTERN.matcher(value); // if (!matcher.matches()) // throw new IllegalArgumentException("Invalid header: " + name + ": " + value); // Collection<Clause> clauses = new HashSet<Clause>(matcher.groupCount()); // for (int i = 2; i <= matcher.groupCount(); i++) { // String group = matcher.group(i); // if (group == null) continue; // AbstractClause clause = new AbstractClause(group); // clauses.add(clause); // } // if (name.equals(SubsystemConstants.FEATURE_SYMBOLICNAME)) // return new FeatureSymbolicNameHeader(value); // if (name.equals(SubsystemConstants.FEATURE_VERSION)) // return new FeatureVersionHeader(value); // if (name.equals(SubsystemConstants.FEATURE_CONTENT)) // return new FeatureContentHeader(value); // if (name.equals(SubsystemConstants.APPLICATION_SYMBOLICNAME)) // return new ApplicationSymbolicNameHeader(value); // if (name.equals(SubsystemConstants.APPLICATION_VERSION)) // return new ApplicationVersionHeader(value); // if (name.equals(SubsystemConstants.APPLICATION_CONTENT)) // return new ApplicationContentHeader(value); if (name.equals(SubsystemSymbolicNameHeader.NAME)) return new SubsystemSymbolicNameHeader(value); if (name.equals(SubsystemVersionHeader.NAME)) return new SubsystemVersionHeader(value); if (name.equals(SubsystemContentHeader.NAME)) return new SubsystemContentHeader(value); if (name.equals(SubsystemTypeHeader.NAME)) return new SubsystemTypeHeader(value); if (ExportPackageHeader.NAME.equals(name)) return new ExportPackageHeader(value); if (ImportPackageHeader.NAME.equals(name)) return new ImportPackageHeader(value); if (DeployedContentHeader.NAME.equals(name)) return new DeployedContentHeader(value); if (ProvisionResourceHeader.NAME.equals(name)) return new ProvisionResourceHeader(value); if (SubsystemManifestVersionHeader.NAME.equals(name)) return new SubsystemManifestVersionHeader(value); if (RequireCapabilityHeader.NAME.equals(name)) return new RequireCapabilityHeader(value); if (SubsystemImportServiceHeader.NAME.equals(name)) return new SubsystemImportServiceHeader(value); if (RequireBundleHeader.NAME.equals(name)) return new RequireBundleHeader(value); if (ProvideCapabilityHeader.NAME.equals(name)) return new ProvideCapabilityHeader(value); if (SubsystemExportServiceHeader.NAME.equals(name)) return new SubsystemExportServiceHeader(value); if (BundleSymbolicNameHeader.NAME.equals(name)) return new BundleSymbolicNameHeader(value); if (BundleVersionHeader.NAME.equals(name)) return new BundleVersionHeader(value); if (PreferredProviderHeader.NAME.equals(name)) return new PreferredProviderHeader(value); if (AriesSubsystemParentsHeader.NAME.equals(name)) return new AriesSubsystemParentsHeader(value); if (BundleRequiredExecutionEnvironmentHeader.NAME.equals(name)) return new BundleRequiredExecutionEnvironmentHeader(value); if (SubsystemLocalizationHeader.NAME.equals(name)) return new SubsystemLocalizationHeader(value); if (FragmentHostHeader.NAME.equals(name)) return new FragmentHostHeader(value); if (AriesSubsystemLocationHeader.NAME.equals(value)) return new AriesSubsystemLocationHeader(value); return new GenericHeader(name, value); } }
8,580
0
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/archive/RequireCapabilityHeader.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.aries.subsystem.core.archive; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import org.osgi.framework.Constants; import org.osgi.resource.Requirement; import org.osgi.resource.Resource; public class RequireCapabilityHeader extends AbstractClauseBasedHeader<RequireCapabilityHeader.Clause> implements RequirementHeader<RequireCapabilityHeader.Clause> { public static class Clause extends AbstractClause { public static final String DIRECTIVE_CARDINALITY = CardinalityDirective.NAME; public static final String DIRECTIVE_EFFECTIVE = EffectiveDirective.NAME; public static final String DIRECTIVE_FILTER = FilterDirective.NAME; public static final String DIRECTIVE_RESOLUTION = ResolutionDirective.NAME; private static final Collection<Parameter> defaultParameters = generateDefaultParameters( EffectiveDirective.DEFAULT, ResolutionDirective.MANDATORY, CardinalityDirective.DEFAULT); public Clause(String clause) { super( parsePath(clause, Patterns.NAMESPACE, false), parseTypedParameters(clause), defaultParameters); } public Clause(String path, Map<String, Parameter> parameters, Collection<Parameter> defaultParameters) { super(path, parameters, defaultParameters); } public static Clause valueOf(Requirement requirement) { String namespace = requirement.getNamespace(); if (namespace.startsWith("osgi.wiring.")) { throw new IllegalArgumentException(); } Map<String, Object> attributes = requirement.getAttributes(); Map<String, String> directives = requirement.getDirectives(); Map<String, Parameter> parameters = new HashMap<String, Parameter>(attributes.size() + directives.size()); for (Map.Entry<String, Object> entry : attributes.entrySet()) { String key = entry.getKey(); parameters.put(key, new TypedAttribute(key, entry.getValue())); } for (Map.Entry<String, String> entry : directives.entrySet()) { String key = entry.getKey(); parameters.put(key, DirectiveFactory.createDirective(key, entry.getValue())); } String path = namespace; return new Clause(path, parameters, defaultParameters); } public String getNamespace() { return path; } public RequireCapabilityRequirement toRequirement(Resource resource) { return new RequireCapabilityRequirement(this, resource); } @Override public String toString() { StringBuilder builder = new StringBuilder() .append(getPath()); for (Parameter parameter : getParameters()) { builder.append(';').append(parameter); } return builder.toString(); } } public static final String NAME = Constants.REQUIRE_CAPABILITY; public RequireCapabilityHeader(String value) { super( value, new ClauseFactory<Clause>() { @Override public Clause newInstance(String clause) { return new Clause(clause); } }); } public RequireCapabilityHeader(Collection<Clause> clauses) { super(clauses); } @Override public String getName() { return NAME; } @Override public String getValue() { return toString(); } @Override public List<RequireCapabilityRequirement> toRequirements(Resource resource) { List<RequireCapabilityRequirement> requirements = new ArrayList<RequireCapabilityRequirement>(clauses.size()); for (Clause clause : clauses) requirements.add(clause.toRequirement(resource)); return requirements; } }
8,581
0
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/archive/DeployedContentHeader.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.aries.subsystem.core.archive; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.apache.aries.subsystem.core.internal.ResourceHelper; import org.apache.aries.subsystem.core.internal.Utils; import org.osgi.framework.Version; import org.osgi.resource.Requirement; import org.osgi.resource.Resource; import org.osgi.service.subsystem.SubsystemConstants; public class DeployedContentHeader extends AbstractClauseBasedHeader<DeployedContentHeader.Clause> implements RequirementHeader<DeployedContentHeader.Clause> { public static class Clause extends AbstractClause { public static final String ATTRIBUTE_DEPLOYEDVERSION = DeployedVersionAttribute.NAME; public static final String ATTRIBUTE_RESOURCEID = "resourceId"; public static final String ATTRIBUTE_TYPE = TypeAttribute.NAME; public static final String DIRECTIVE_REFERENCE = ReferenceDirective.NAME; public static final String DIRECTIVE_STARTORDER = StartOrderDirective.NAME; public Clause(String clause) { super( parsePath(clause, Patterns.SYMBOLIC_NAME, false), parseParameters(clause, false), generateDefaultParameters( TypeAttribute.DEFAULT, ReferenceDirective.TRUE)); } public Clause(Resource resource) { this(resource, true); } public Clause(Resource resource, boolean referenced) { this(appendResource(resource, new StringBuilder(), referenced) .toString()); } public boolean contains(Resource resource) { return getSymbolicName() .equals(ResourceHelper.getSymbolicNameAttribute(resource)) && getDeployedVersion().equals( ResourceHelper.getVersionAttribute(resource)) && getType() .equals(ResourceHelper.getTypeAttribute(resource)); } public Version getDeployedVersion() { return ((DeployedVersionAttribute) getAttribute( ATTRIBUTE_DEPLOYEDVERSION)).getVersion(); } public String getSymbolicName() { return path; } public int getStartOrder() { return ((StartOrderDirective) getAttribute(DIRECTIVE_STARTORDER)) .getStartOrder(); } public String getType() { return ((TypeAttribute) getAttribute(ATTRIBUTE_TYPE)).getType(); } public boolean isReferenced() { return ((ReferenceDirective) getDirective(DIRECTIVE_REFERENCE)) .isReferenced(); } public DeployedContentRequirement toRequirement(Resource resource) { return new DeployedContentRequirement(this, resource); } } public static final String NAME = SubsystemConstants.DEPLOYED_CONTENT; public static DeployedContentHeader newInstance( Collection<Resource> resources) { StringBuilder builder = new StringBuilder(); for (Resource resource : resources) { appendResource(resource, builder, true); builder.append(','); } // Remove the trailing comma. // TODO Intentionally letting the exception propagate since there must // be at least one resource. builder.deleteCharAt(builder.length() - 1); return new DeployedContentHeader(builder.toString()); } private static StringBuilder appendResource(Resource resource, StringBuilder builder, boolean referenced) { String symbolicName = ResourceHelper.getSymbolicNameAttribute(resource); Version version = ResourceHelper.getVersionAttribute(resource); String type = ResourceHelper.getTypeAttribute(resource); builder.append(symbolicName).append(';') .append(Clause.ATTRIBUTE_DEPLOYEDVERSION).append('=') .append(version.toString()).append(';') .append(Clause.ATTRIBUTE_TYPE).append('=').append(type) .append(';').append(Clause.ATTRIBUTE_RESOURCEID).append('=') .append(Utils.getId(resource)).append(';') .append(Clause.DIRECTIVE_REFERENCE).append(":=") .append(referenced); return builder; } public DeployedContentHeader(Collection<Clause> clauses) { super(clauses); } public DeployedContentHeader(String value) { super( value, new ClauseFactory<Clause>() { @Override public Clause newInstance(String clause) { return new Clause(clause); } }); } public boolean contains(Resource resource) { for (Clause clause : getClauses()) if (clause.contains(resource)) return true; return false; } public Clause getClause(Resource resource) { String symbolicName = ResourceHelper.getSymbolicNameAttribute(resource); Version version = ResourceHelper.getVersionAttribute(resource); String type = ResourceHelper.getTypeAttribute(resource); for (Clause clause : clauses) { if (symbolicName.equals(clause.getPath()) && clause.getDeployedVersion().equals(version) && type.equals(clause.getType())) return clause; } return null; } @Override public String getName() { return NAME; } @Override public String getValue() { return toString(); } public boolean isReferenced(Resource resource) { DeployedContentHeader.Clause clause = getClause(resource); if (clause == null) return false; return clause.isReferenced(); } @Override public List<Requirement> toRequirements(Resource resource) { List<Requirement> requirements = new ArrayList<Requirement>( clauses.size()); for (Clause clause : clauses) requirements.add(clause.toRequirement(resource)); return requirements; } }
8,582
0
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/archive/BundleManifest.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.aries.subsystem.core.archive; import org.osgi.framework.Constants; public class BundleManifest extends Manifest { public BundleManifest(java.util.jar.Manifest manifest) { super(manifest); fillInDefaults(); } private void fillInDefaults() { Header<?> header = headers.get(Constants.BUNDLE_VERSION); if (header == null) headers.put(Constants.BUNDLE_VERSION, BundleVersionHeader.DEFAULT); } }
8,583
0
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/archive/FragmentHostRequirement.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.aries.subsystem.core.archive; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.apache.aries.subsystem.core.internal.AbstractRequirement; import org.osgi.framework.namespace.HostNamespace; import org.osgi.resource.Resource; public class FragmentHostRequirement extends AbstractRequirement { public static final String DIRECTIVE_EXTENSION = HostNamespace.REQUIREMENT_EXTENSION_DIRECTIVE; public static final String DIRECTIVE_FILTER = HostNamespace.REQUIREMENT_FILTER_DIRECTIVE; public static final String NAMESPACE = HostNamespace.HOST_NAMESPACE; private final Map<String, String> directives; private final Resource resource; public FragmentHostRequirement( FragmentHostHeader.Clause clause, Resource resource) { directives = new HashMap<String, String>(clause.getDirectives().size() + 1); for (Directive directive : clause.getDirectives()) directives.put(directive.getName(), directive.getValue()); StringBuilder builder = new StringBuilder("(&(") .append(NAMESPACE).append('=') .append(clause.getSymbolicName()).append(')'); for (Attribute attribute : clause.getAttributes()) attribute.appendToFilter(builder); directives.put(DIRECTIVE_FILTER, builder.append(')').toString()); this.resource = resource; } @Override public Map<String, Object> getAttributes() { return Collections.emptyMap(); } @Override public Map<String, String> getDirectives() { return Collections.unmodifiableMap(directives); } @Override public String getNamespace() { return NAMESPACE; } @Override public Resource getResource() { return resource; } }
8,584
0
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/archive/TypeAttribute.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.aries.subsystem.core.archive; import org.osgi.framework.namespace.IdentityNamespace; public class TypeAttribute extends AbstractAttribute { public static final TypeAttribute DEFAULT = new TypeAttribute(); // TODO Add to constants. public static final String DEFAULT_VALUE = IdentityNamespace.TYPE_BUNDLE; // TODO Add to constants. public static final String NAME = "type"; public static TypeAttribute newInstance(String value) { if (value == null || value.length() == 0) return DEFAULT; return new TypeAttribute(value); } public TypeAttribute() { this(DEFAULT_VALUE); } public TypeAttribute(String value) { super(NAME, value); } public String getType() { return (String)getValue(); } }
8,585
0
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/archive/AriesSubsystemLocationHeader.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.aries.subsystem.core.archive; import java.util.Collection; import java.util.Collections; public class AriesSubsystemLocationHeader implements Header<Clause> { public static final String NAME = "AriesSubsystem-Location"; private final String value; public AriesSubsystemLocationHeader(String value) { if (value == null) { throw new NullPointerException(); } this.value = value; } @Override public Collection<Clause> getClauses() { return Collections.<Clause>singleton( new Clause() { @Override public Attribute getAttribute(String name) { return null; } @Override public Collection<Attribute> getAttributes() { return Collections.emptyList(); } @Override public Directive getDirective(String name) { return null; } @Override public Collection<Directive> getDirectives() { return Collections.emptyList(); } @Override public Parameter getParameter(String name) { return null; } @Override public Collection<Parameter> getParameters() { return Collections.emptyList(); } @Override public String getPath() { return value; } }); } @Override public String getName() { return NAME; } @Override public String getValue() { return value; } @Override public String toString() { return value; } }
8,586
0
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/archive/VersionAttribute.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.aries.subsystem.core.archive; import org.osgi.framework.Constants; import org.osgi.framework.Version; public class VersionAttribute extends AbstractAttribute { public static final String NAME = Constants.VERSION_ATTRIBUTE; public static final VersionAttribute DEFAULT = new VersionAttribute(); public VersionAttribute() { this(Version.emptyVersion.toString()); } public VersionAttribute(String value) { super(NAME, Version.parseVersion(value)); } public Version getVersion() { return (Version)getValue(); } }
8,587
0
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/archive/ManifestVersionHeader.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.aries.subsystem.core.archive; import java.util.jar.Attributes; public class ManifestVersionHeader extends VersionHeader { public static final String DEFAULT_VALUE = "1.0"; public static final String NAME = Attributes.Name.MANIFEST_VERSION.toString(); public static final ManifestVersionHeader DEFAULT = new ManifestVersionHeader(DEFAULT_VALUE); public ManifestVersionHeader() { this(DEFAULT_VALUE); } public ManifestVersionHeader(String value) { super(NAME, value); } }
8,588
0
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/archive/Directive.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.aries.subsystem.core.archive; public interface Directive extends Parameter { String getValue(); }
8,589
0
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/archive/AbstractClause.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.aries.subsystem.core.archive; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.osgi.framework.VersionRange; public abstract class AbstractClause implements Clause { protected static Collection<Parameter> generateDefaultParameters(Parameter... parameters) { if (parameters == null || parameters.length == 0) { return Collections.emptyList(); } Collection<Parameter> defaults = new ArrayList<Parameter>(parameters.length); for (Parameter parameter : parameters) { defaults.add(parameter); } return defaults; } protected static Map<String, Parameter> parseParameters(String clause, boolean replaceVersionWithVersionRange) { Map<String, Parameter> parameters = new HashMap<String, Parameter>(); Matcher matcher = Patterns.PARAMETER.matcher(clause); while (matcher.find()) { Parameter parameter = ParameterFactory.create(matcher.group()); if (replaceVersionWithVersionRange && (parameter instanceof VersionAttribute)) { parameter = new VersionRangeAttribute(new VersionRange(String.valueOf(parameter.getValue()))); } parameters.put(parameter.getName(), parameter); } return parameters; } protected static Map<String, Parameter> parseTypedParameters(String clause) { Map<String, Parameter> parameters = new HashMap<String, Parameter>(); Matcher matcher = Patterns.TYPED_PARAMETER.matcher(clause); while (matcher.find()) { if (":=".equals(matcher.group(2))) { // This is a directive. parameters.put(matcher.group(1), DirectiveFactory.createDirective(matcher.group(1), removeQuotes(matcher.group(3)))); } else if (":".equals(matcher.group(5))) { // This is a typed attribute with a declared version. parameters.put(matcher.group(4), new TypedAttribute(matcher.group(4), removeQuotes(matcher.group(7)), matcher.group(6))); } else { // This is a typed attribute without a declared version. parameters.put(matcher.group(4), new TypedAttribute(matcher.group(4), removeQuotes(matcher.group(7)), "String")); } } return parameters; } protected static String removeQuotes(String value) { if (value == null) return null; if (value.startsWith("\"") && value.endsWith("\"")) return value.substring(1, value.length() - 1); return value; } protected static String parsePath(String clause, Pattern pattern, boolean replaceAllWhitespace) { Matcher matcher = pattern.matcher(clause); if (!matcher.find()) throw new IllegalArgumentException("Invalid path: " + clause); String path = matcher.group(); if (replaceAllWhitespace) { path = path.replaceAll("\\s", ""); } return path; } protected final Map<String, Parameter> parameters; protected final String path; public AbstractClause(String path, Map<String, Parameter> parameters, Collection<Parameter> defaultParameters) { if (path == null) { throw new NullPointerException(); } for (Parameter parameter : defaultParameters) { String name = parameter.getName(); if (parameters.containsKey(name)) { continue; } parameters.put(name, parameter); } this.path = path; this.parameters = Collections.synchronizedMap(parameters); } @Override public Attribute getAttribute(String name) { Parameter result = parameters.get(name); if (result instanceof Attribute) { return (Attribute) result; } return null; } @Override public Collection<Attribute> getAttributes() { ArrayList<Attribute> attributes = new ArrayList<Attribute>( parameters.size()); for (Parameter parameter : parameters.values()) { if (parameter instanceof Attribute) { attributes.add((Attribute) parameter); } } attributes.trimToSize(); return attributes; } @Override public Directive getDirective(String name) { Parameter result = parameters.get(name); if (result instanceof Directive) { return (Directive) result; } return null; } @Override public Collection<Directive> getDirectives() { ArrayList<Directive> directives = new ArrayList<Directive>( parameters.size()); for (Parameter parameter : parameters.values()) { if (parameter instanceof Directive) { directives.add((Directive) parameter); } } directives.trimToSize(); return directives; } @Override public Parameter getParameter(String name) { return parameters.get(name); } @Override public Collection<Parameter> getParameters() { return Collections.unmodifiableCollection(parameters.values()); } @Override public String getPath() { return path; } @Override public int hashCode() { int result = 17; result = 31 * result + path.hashCode(); result = 31 * result + parameters.hashCode(); return result; } @Override public boolean equals(Object o) { if (o == this) { return true; } if (!(o instanceof AbstractClause)) { return false; } AbstractClause that = (AbstractClause)o; return that.path.equals(this.path) && that.parameters.equals(this.parameters); } @Override public String toString() { StringBuilder builder = new StringBuilder().append(getPath()); for (Parameter parameter : getParameters()) { builder.append(';').append(parameter); } return builder.toString(); } }
8,590
0
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/archive/ProvideBundleCapability.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.aries.subsystem.core.archive; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.apache.aries.subsystem.core.internal.AbstractCapability; import org.osgi.framework.namespace.BundleNamespace; import org.osgi.resource.Resource; public class ProvideBundleCapability extends AbstractCapability { public static final String ATTRIBUTE_BUNDLE_VERSION = BundleNamespace.CAPABILITY_BUNDLE_VERSION_ATTRIBUTE; public static final String DIRECTIVE_EFFECTIVE = BundleNamespace.CAPABILITY_EFFECTIVE_DIRECTIVE; public static final String DIRECTIVE_FRAGMENT_ATTACHMENT = BundleNamespace.CAPABILITY_FRAGMENT_ATTACHMENT_DIRECTIVE; public static final String DIRECTIVE_MANDATORY = BundleNamespace.CAPABILITY_MANDATORY_DIRECTIVE; public static final String DIRECTIVE_SINGLETON = BundleNamespace.CAPABILITY_SINGLETON_DIRECTIVE; public static final String DIRECTIVE_USES = BundleNamespace.CAPABILITY_USES_DIRECTIVE; public static final String NAMESPACE = BundleNamespace.BUNDLE_NAMESPACE; private static Map<String, Object> initializeAttributes(BundleSymbolicNameHeader bsn, BundleVersionHeader version) { if (version == null) { version = new BundleVersionHeader(); } Clause clause = bsn.getClauses().get(0); Collection<Attribute> attributes = clause.getAttributes(); Map<String, Object> result = new HashMap<String, Object>(attributes.size() + 2); result.put(NAMESPACE, clause.getPath()); result.put(ATTRIBUTE_BUNDLE_VERSION, version.getValue()); for (Attribute attribute : attributes) { result.put(attribute.getName(), attribute.getValue()); } return Collections.unmodifiableMap(result); } private static Map<String, String> initializeDirectives(Collection<Directive> directives) { if (directives.isEmpty()) return Collections.emptyMap(); Map<String, String> result = new HashMap<String, String>(directives.size()); for (Directive directive : directives) { result.put(directive.getName(), directive.getValue()); } return Collections.unmodifiableMap(result); } private final Map<String, Object> attributes; private final Map<String, String> directives; private final Resource resource; public ProvideBundleCapability(BundleSymbolicNameHeader bsn, BundleVersionHeader version, Resource resource) { if (resource == null) throw new NullPointerException("Missing required parameter: resource"); this.resource = resource; attributes = initializeAttributes(bsn, version); directives = initializeDirectives(bsn.getClauses().get(0).getDirectives()); } @Override public Map<String, Object> getAttributes() { return attributes; } @Override public Map<String, String> getDirectives() { return directives; } @Override public String getNamespace() { return NAMESPACE; } @Override public Resource getResource() { return resource; } }
8,591
0
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/archive/AbstractHeader.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.aries.subsystem.core.archive; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import org.osgi.framework.Version; import org.osgi.framework.namespace.IdentityNamespace; import org.osgi.resource.Resource; public abstract class AbstractHeader implements Header<Clause> { // TODO This is specific to deployment manifests and shouldn't be at this level. protected static void appendResource(Resource resource, StringBuilder builder) { Map<String, Object> attributes = resource.getCapabilities(IdentityNamespace.IDENTITY_NAMESPACE).get(0).getAttributes(); String symbolicName = (String)attributes.get(IdentityNamespace.IDENTITY_NAMESPACE); Version version = (Version)attributes.get(IdentityNamespace.CAPABILITY_VERSION_ATTRIBUTE); String namespace = (String)attributes.get(IdentityNamespace.CAPABILITY_TYPE_ATTRIBUTE); builder.append(symbolicName) .append(';') .append(DeployedVersionAttribute.NAME) .append('=') .append(version.toString()) .append(';') .append(TypeAttribute.NAME) .append('=') .append(namespace); } protected final List<Clause> clauses; protected final String name; protected final String value; public AbstractHeader(String name, String value) { if (name == null) { throw new NullPointerException(); } ClauseTokenizer tokenizer = new ClauseTokenizer(value); List<Clause> clauses = new ArrayList<Clause>(tokenizer.getClauses().size()); for (String clause : tokenizer.getClauses()) { clauses.add(new GenericClause(clause)); } if (clauses.isEmpty()) { throw new IllegalArgumentException("Invalid header syntax -> " + name + ": " + value); } this.name = name; this.value = value; this.clauses = Collections.synchronizedList(clauses); } @Override public List<Clause> getClauses() { return Collections.unmodifiableList(clauses); } @Override public String getName() { return name; } @Override public String getValue() { return value; } @Override public boolean equals(Object o) { if (o == this) { return true; } if (!(o instanceof AbstractHeader)) { return false; } AbstractHeader that = (AbstractHeader)o; return that.name.equals(this.name) && that.clauses.equals(this.clauses); } @Override public int hashCode() { int result = 17; result = 31 * result + name.hashCode(); result = 31 * result + clauses.hashCode(); return result; } @Override public String toString() { return new StringBuilder(getClass().getName()) .append(": name=") .append(name) .append(", value=") .append(value) .toString(); } }
8,592
0
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/archive/VersionRangeAttribute.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.aries.subsystem.core.archive; import org.osgi.framework.Constants; import org.osgi.framework.Version; import org.osgi.framework.VersionRange; public class VersionRangeAttribute extends AbstractAttribute { public static final String NAME_BUNDLEVERSION = Constants.BUNDLE_VERSION_ATTRIBUTE; public static final String NAME_VERSION = Constants.VERSION_ATTRIBUTE; public static final VersionRangeAttribute DEFAULT_BUNDLEVERSION = new VersionRangeAttribute( NAME_BUNDLEVERSION, new VersionRange(Version.emptyVersion.toString())); public static final VersionRangeAttribute DEFAULT_VERSION = new VersionRangeAttribute(); private final VersionRange range; public VersionRangeAttribute() { this(Version.emptyVersion.toString()); } public VersionRangeAttribute(String value) { this(new VersionRange(value)); } public VersionRangeAttribute(VersionRange range) { this(Constants.VERSION_ATTRIBUTE, range); } public VersionRangeAttribute(String name, VersionRange range) { super(name, range.toString()); this.range = range; } @Override public StringBuilder appendToFilter(StringBuilder builder) { return builder.append(range.toFilterString(name)); } @Override public Object getValue() { return new StringBuilder().append('"').append(range.toString()).append('"').toString(); } public VersionRange getVersionRange() { return range; } }
8,593
0
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/archive/DynamicImportPackageRequirement.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.aries.subsystem.core.archive; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.apache.aries.subsystem.core.internal.AbstractRequirement; import org.osgi.framework.namespace.PackageNamespace; import org.osgi.resource.Resource; public class DynamicImportPackageRequirement extends AbstractRequirement { public static final String DIRECTIVE_FILTER = PackageNamespace.REQUIREMENT_FILTER_DIRECTIVE; public static final String NAMESPACE = PackageNamespace.PACKAGE_NAMESPACE; private final Map<String, String> directives; private final String packageName; private final Resource resource; public DynamicImportPackageRequirement(String pkg, DynamicImportPackageHeader.Clause clause, Resource resource) { packageName = pkg; Collection<Directive> clauseDirectives = clause.getDirectives(); directives = new HashMap<String, String>(clauseDirectives.size() + 1); for (Directive directive : clauseDirectives) directives.put(directive.getName(), directive.getValue()); StringBuilder filter = new StringBuilder("(&(").append(NAMESPACE) .append('=').append(pkg).append(')'); VersionRangeAttribute versionRange = clause.getVersionRangeAttribute(); if (versionRange != null) { versionRange.appendToFilter(filter); } directives.put(DIRECTIVE_FILTER, filter.append(')').toString()); this.resource = resource; } @Override public Map<String, Object> getAttributes() { return Collections.emptyMap(); } @Override public Map<String, String> getDirectives() { return Collections.unmodifiableMap(directives); } @Override public String getNamespace() { return NAMESPACE; } public String getPackageName() { return packageName; } @Override public Resource getResource() { return resource; } }
8,594
0
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/archive/BundleVersionHeader.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.aries.subsystem.core.archive; import org.osgi.framework.Constants; import org.osgi.framework.Version; public class BundleVersionHeader extends VersionHeader { public static final String DEFAULT_VALUE = Version.emptyVersion.toString(); public static final String NAME = Constants.BUNDLE_VERSION; public static final BundleVersionHeader DEFAULT = new BundleVersionHeader(); public BundleVersionHeader() { this(DEFAULT_VALUE); } public BundleVersionHeader(String value) { super(NAME, value); } }
8,595
0
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/archive/FragmentHostHeader.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.aries.subsystem.core.archive; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.osgi.framework.Constants; import org.osgi.framework.Version; import org.osgi.framework.VersionRange; import org.osgi.resource.Resource; public class FragmentHostHeader extends AbstractClauseBasedHeader<FragmentHostHeader.Clause> implements RequirementHeader<FragmentHostHeader.Clause> { public static class Clause extends AbstractClause { public static final String ATTRIBUTE_BUNDLEVERSION = Constants.BUNDLE_VERSION_ATTRIBUTE; public Clause(String clause) { super( parsePath(clause, Patterns.SYMBOLIC_NAME, false), parseParameters(clause, false), generateDefaultParameters( new BundleVersionAttribute( new VersionRange( VersionRange.LEFT_CLOSED, new Version("0"), null, VersionRange.RIGHT_OPEN)))); } public String getSymbolicName() { return path; } public FragmentHostRequirement toRequirement(Resource resource) { return new FragmentHostRequirement(this, resource); } } public static final String NAME = Constants.FRAGMENT_HOST; public FragmentHostHeader(Collection<Clause> clauses) { super(clauses); if (clauses.size() != 1) { throw new IllegalArgumentException("A " + NAME + " header must have one and only one clause"); } } public FragmentHostHeader(String value) { super( value, new ClauseFactory<Clause>() { @Override public Clause newInstance(String clause) { return new Clause(clause); } }); if (clauses.size() != 1) { throw new IllegalArgumentException("A " + NAME + " header must have one and only one clause"); } } @Override public String getName() { return NAME; } @Override public String getValue() { return toString(); } @Override public List<FragmentHostRequirement> toRequirements(Resource resource) { List<FragmentHostRequirement> requirements = new ArrayList<FragmentHostRequirement>(clauses.size()); for (Clause clause : clauses) requirements.add(clause.toRequirement(resource)); return requirements; } }
8,596
0
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/archive/CapabilityHeader.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.aries.subsystem.core.archive; import java.util.List; import org.osgi.resource.Capability; import org.osgi.resource.Resource; public interface CapabilityHeader<C extends Clause> extends Header<C> { List<? extends Capability> toCapabilities(Resource resource); }
8,597
0
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/archive/SubsystemExportServiceCapability.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.aries.subsystem.core.archive; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.apache.aries.subsystem.core.internal.AbstractCapability; import org.osgi.framework.Constants; import org.osgi.namespace.service.ServiceNamespace; import org.osgi.resource.Namespace; import org.osgi.resource.Resource; public class SubsystemExportServiceCapability extends AbstractCapability { public static final String DIRECTIVE_FILTER = Namespace.REQUIREMENT_FILTER_DIRECTIVE; public static final String NAMESPACE = ServiceNamespace.SERVICE_NAMESPACE; private final Map<String, Object> attributes = new HashMap<String, Object>(); private final Map<String, String> directives = new HashMap<String, String>(); private final Resource resource; public SubsystemExportServiceCapability(SubsystemExportServiceHeader.Clause clause, Resource resource) { StringBuilder builder = new StringBuilder("(&(") .append(Constants.OBJECTCLASS).append('=') .append(clause.getObjectClass()).append(')'); Directive filter = clause .getDirective(SubsystemExportServiceHeader.Clause.DIRECTIVE_FILTER); if (filter != null) builder.append(filter.getValue()); directives.put(DIRECTIVE_FILTER, builder.append(')').toString()); this.resource = resource; } @Override public Map<String, Object> getAttributes() { return Collections.unmodifiableMap(attributes); } @Override public Map<String, String> getDirectives() { return Collections.unmodifiableMap(directives); } @Override public String getNamespace() { return NAMESPACE; } @Override public Resource getResource() { return resource; } }
8,598
0
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core
Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/archive/VisibilityDirective.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.aries.subsystem.core.archive; import org.osgi.framework.Constants; public class VisibilityDirective extends AbstractDirective { public static final String NAME = Constants.VISIBILITY_DIRECTIVE; public static final String VALUE_PRIVATE = Constants.VISIBILITY_PRIVATE; public static final String VALUE_REEXPORT = Constants.VISIBILITY_REEXPORT; public static final VisibilityDirective PRIVATE = new VisibilityDirective(VALUE_PRIVATE); public static final VisibilityDirective REEXPORT = new VisibilityDirective(VALUE_REEXPORT); public static VisibilityDirective getInstance(String value) { if (VALUE_PRIVATE.equals(value)) return PRIVATE; if (VALUE_REEXPORT.equals(value)) return REEXPORT; return new VisibilityDirective(value); } public VisibilityDirective() { this(VALUE_PRIVATE); } public VisibilityDirective(String value) { super(NAME, value); } public boolean isPrivate() { return PRIVATE == this || VALUE_PRIVATE.equals(getValue()); } public boolean isReexport() { return REEXPORT == this || VALUE_REEXPORT.equals(getValue()); } }
8,599