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/sandbox/samples/dgoat/dgoat-cxf-sample-cli/src/main/java/org/apache/cxf/dosgi/samples/greeter
Create_ds/aries/sandbox/samples/dgoat/dgoat-cxf-sample-cli/src/main/java/org/apache/cxf/dosgi/samples/greeter/client/Activator.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.cxf.dosgi.samples.greeter.client; import java.util.Map; import org.apache.cxf.dosgi.samples.greeter.GreeterData; import org.apache.cxf.dosgi.samples.greeter.GreeterException; import org.apache.cxf.dosgi.samples.greeter.GreeterService; import org.apache.cxf.dosgi.samples.greeter.GreetingPhrase; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceReference; import org.osgi.util.tracker.ServiceTracker; public class Activator implements BundleActivator { private ServiceTracker tracker; public void start(final BundleContext bc) { tracker = new ServiceTracker(bc, GreeterService.class.getName(), null) { @Override public Object addingService(ServiceReference reference) { Object result = super.addingService(reference); useService(bc, reference); return result; } }; tracker.open(); } protected void useService(final BundleContext bc, ServiceReference reference) { Object svc = bc.getService(reference); if (!(svc instanceof GreeterService)) { return; } final GreeterService greeter = (GreeterService) svc; Thread t = new Thread(new Runnable() { public void run() { greeterUI(bc, greeter); } }); t.start(); } private void greeterUI(final BundleContext bc, final GreeterService greeter) { while (true) { System.out.println("*** Opening greeter client dialog ***"); Object gd = getGreeterData(); if (gd instanceof String) { System.out.println("*** Invoking greeter ***"); Map<GreetingPhrase, String> result = greeter.greetMe((String) gd); System.out.println("greetMe(\"" + gd + "\") returns:"); for (Map.Entry<GreetingPhrase, String> greeting : result.entrySet()) { System.out.println(" " + greeting.getKey().getPhrase() + " " + greeting.getValue()); } } else if (gd instanceof GreeterData) { System.out.println("*** Invoking greeter ***"); try { GreetingPhrase [] result = greeter.greetMe((GreeterData) gd); System.out.println("greetMe(\"" + gd + "\") returns:"); for (GreetingPhrase phrase : result) { System.out.println(" " + phrase.getPhrase()); } } catch (GreeterException ex) { System.out.println("GreeterException : " + ex.toString()); } } } } private static Object getGreeterData() { GreeterDialog gd = new GreeterDialog(); gd.setVisible(true); return gd.getSelection(); } public void stop(BundleContext bc) throws Exception { tracker.close(); } }
8,400
0
Create_ds/aries/sandbox/samples/dgoat/dgoat-cxf-sample-cli/src/main/java/org/apache/cxf/dosgi/samples/greeter
Create_ds/aries/sandbox/samples/dgoat/dgoat-cxf-sample-cli/src/main/java/org/apache/cxf/dosgi/samples/greeter/client/GreeterDataImpl.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.cxf.dosgi.samples.greeter.client; import org.apache.cxf.dosgi.samples.greeter.GreeterData; public class GreeterDataImpl implements GreeterData { private final String name; private final int age; private final boolean exception; public GreeterDataImpl(String n, int a, boolean b) { name = n; age = a; exception = b; } public String getName() { return name; } public int getAge() { return age; } public boolean isException() { return exception; } }
8,401
0
Create_ds/aries/sandbox/samples/dgoat/dgoat-web/src/main/java/org/apache/aries/samples/goat
Create_ds/aries/sandbox/samples/dgoat/dgoat-web/src/main/java/org/apache/aries/samples/goat/web/ServerSideClass.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.samples.goat.web; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Map; import javax.servlet.ServletContext; import org.apache.aries.samples.goat.info.ComponentInfoImpl; import org.apache.aries.samples.goat.info.RelationshipInfoImpl; import org.apache.aries.samples.goat.api.ComponentInfo; import org.apache.aries.samples.goat.api.ComponentInfoProvider; import org.apache.aries.samples.goat.api.ModelInfoService; import org.apache.aries.samples.goat.api.RelationshipInfo; import org.apache.aries.samples.goat.api.RelationshipInfoProvider; import org.directwebremoting.Browser; import org.directwebremoting.ScriptBuffer; import org.directwebremoting.ScriptSession; import org.directwebremoting.ServerContextFactory; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; import org.osgi.framework.InvalidSyntaxException; import org.osgi.framework.ServiceReference; import org.osgi.util.tracker.ServiceTracker; public class ServerSideClass { private String modelInfoServiceHint = ""; private ModelInfoService ModelInfoService = null; private ModelInfoService blah; private Map<ModelInfoService, ComponentInfoProvider.ComponentInfoListener> clisteners = new HashMap<ModelInfoService, ComponentInfoProvider.ComponentInfoListener>(); private Map<ModelInfoService, RelationshipInfoProvider.RelationshipInfoListener> rlisteners = new HashMap<ModelInfoService, RelationshipInfoProvider.RelationshipInfoListener>(); public ServerSideClass(ModelInfoService blah) { this.blah = blah; } private class ComponentInfoListenerImpl implements ComponentInfoProvider.ComponentInfoListener { String server; public ComponentInfoListenerImpl(String server) { this.server = server; } public void updateComponent(ComponentInfo b) { if (this.server.equals(modelInfoServiceHint)) { // todo: only issue the add for the new bundle, and affected // other bundles. //getInitialComponents(modelInfoServiceHint); //System.out.println("State is: " + b.getComponentProperties().get("State")); addFunctionCall("addComponent", b); } } public void removeComponent(ComponentInfo b) { // todo } } private class RelationshipInfoListenerImpl implements RelationshipInfoProvider.RelationshipInfoListener { String server; public RelationshipInfoListenerImpl(String server) { this.server = server; } public void updateRelationship(RelationshipInfo r) { if (this.server.equals(modelInfoServiceHint)) { addFunctionCall("addRelationship", r); } } public void removeRelationship(RelationshipInfo r) { // todo } } public ServerSideClass() { System.err.println("SSC Built!"); } @SuppressWarnings("unused") private String bundleStateToString(int bundleState) { switch (bundleState) { case Bundle.UNINSTALLED: return "UNINSTALLED"; case Bundle.INSTALLED: return "INSTALLED"; case Bundle.RESOLVED: return "RESOLVED"; case Bundle.STARTING: return "STARTING"; case Bundle.STOPPING: return "STOPPING"; case Bundle.ACTIVE: return "ACTIVE"; default: return "UNKNOWN[" + bundleState + "]"; } } /** * this is invoked by a page onload.. so until it's invoked.. we dont care * about components */ public void getInitialComponents(String dataProvider) { System.err.println("GET INITIAL BUNDLES ASKED TO USE DATAPROVIDER " + dataProvider); if (dataProvider == null) throw new IllegalArgumentException( "Unable to accept 'null' as a dataProvider"); // do we need to update? if (!this.modelInfoServiceHint.equals(dataProvider)) { this.modelInfoServiceHint = dataProvider; if (!(this.ModelInfoService == null)) { // we already had a provider.. we need to shut down the existing // components & relationships in the browsers.. addFunctionCall("forgetAboutEverything"); } ServletContext context = org.directwebremoting.ServerContextFactory .get().getServletContext(); Object o = context.getAttribute("osgi-bundlecontext"); if (o != null) { if (o instanceof BundleContext) { BundleContext b_ctx = (BundleContext) o; System.err.println("Looking up bcip"); try { ServiceReference sr[] = b_ctx.getServiceReferences( ModelInfoService.class.getName(), "(displayName=" + this.modelInfoServiceHint + ")"); if (sr != null) { System.err.println("Getting bcip"); this.ModelInfoService = (ModelInfoService) b_ctx .getService(sr[0]); System.err.println("Got bcip " + this.ModelInfoService); } else { System.err.println("UNABLE TO FIND BCIP!!"); System.err.println("UNABLE TO FIND BCIP!!"); System.err.println("UNABLE TO FIND BCIP!!"); } } catch (InvalidSyntaxException ise) { } if (this.ModelInfoService != null) { if (!rlisteners.containsKey(this.ModelInfoService)) { RelationshipInfoProvider.RelationshipInfoListener rl = new RelationshipInfoListenerImpl( this.modelInfoServiceHint); rlisteners.put(this.ModelInfoService, rl); this.ModelInfoService.getRelationshipInfoProvider() .registerRelationshipInfoListener(rl); } if (!clisteners.containsKey(this.ModelInfoService)) { ComponentInfoProvider.ComponentInfoListener cl = new ComponentInfoListenerImpl( this.modelInfoServiceHint); clisteners.put(this.ModelInfoService, cl); this.ModelInfoService.getComponentInfoProvider() .registerComponentInfoListener(cl); } } } } } Collection<ComponentInfo> bis = this.ModelInfoService .getComponentInfoProvider().getComponents(); System.err.println("Got " + (bis == null ? "null" : bis.size()) + " components back from the provider "); if (bis != null) { for (ComponentInfo b : bis) { System.err.println("Adding Component .. " + b.getId()); addFunctionCall("addComponent", b); } } Collection<RelationshipInfo> ris = this.ModelInfoService .getRelationshipInfoProvider().getRelationships(); System.err.println("Got " + (ris == null ? "null" : ris.size()) + " relationships back from the provider "); if (ris != null) { for (RelationshipInfo r : ris) { System.err.println("Adding relationship type " + r.getType() + " called " + r.getName() + " from " + r.getProvidedBy().getId()); addFunctionCall("addRelationship", r); } } } private void addFunctionCall(String name, Object... params) { final ScriptBuffer script = new ScriptBuffer(); script.appendScript(name).appendScript("("); for (int i = 0; i < params.length; i++) { if (i != 0) script.appendScript(","); script.appendData(params[i]); } script.appendScript(");"); Browser.withAllSessions(new Runnable() { public void run() { for (ScriptSession s : Browser.getTargetSessions()) { s.addScript(script); } } }); } public String[] getProviders() { System.err.println("Getting providers..."); ArrayList<String> result = new ArrayList<String>(); ServletContext context = ServerContextFactory.get().getServletContext(); Object o = context.getAttribute("osgi-bundlecontext"); if (o != null) { if (o instanceof BundleContext) { BundleContext b_ctx = (BundleContext) o; try { System.err.println("Getting providers [2]..."); ServiceReference[] srs = b_ctx.getServiceReferences( ModelInfoService.class.getName(), null); System.err.println("Got.. " + srs); if (srs == null || srs.length == 0) { System.err.println("NO DATA PROVIDERS"); throw new RuntimeException( "Unable to find any data providers"); } System.err.println("Processing srs as loop."); for (ServiceReference sr : srs) { System.err.println("Processing srs entry..."); String name = (String.valueOf(sr .getProperty("displayName"))); Long bid = sr.getBundle().getBundleId(); System.err.println("ZZZZ Name: " + name); System.err.println("ZZZZ Bundle Id: " + bid); result.add(name); } System.err.println("Processed srs as loop."); } catch (InvalidSyntaxException e) { // wont happen, the exception relates to the filter, (2nd // arg above), which is constant null. } } } System.err.println("Returning " + result.size()); String[] arr = new String[result.size()]; arr = result.toArray(arr); for (String x : arr) { System.err.println(" - " + x); } return arr; } }
8,402
0
Create_ds/aries/sandbox/samples/dgoat/dgoat-info-enhancer/src/main/java/org/apache/aries/samples/goat
Create_ds/aries/sandbox/samples/dgoat/dgoat-info-enhancer/src/main/java/org/apache/aries/samples/goat/enhancer/ServiceInterceptor.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.samples.goat.enhancer; import java.util.Dictionary; import java.util.HashMap; import java.util.Hashtable; import java.util.Map; import org.apache.aries.samples.goat.api.ModelInfoService; import org.osgi.framework.BundleContext; import org.osgi.framework.InvalidSyntaxException; import org.osgi.framework.ServiceEvent; import org.osgi.framework.ServiceListener; import org.osgi.framework.ServiceReference; import org.osgi.framework.ServiceRegistration; public class ServiceInterceptor implements ServiceListener { private static final String DISPLAY_NAME = "displayName"; /** * */ public static final String SERVICE_ID = "service.id"; private final BundleContext ctx; private final Map<String, ServiceRegistration> registrations = new HashMap<String, ServiceRegistration>(); public ServiceInterceptor(BundleContext ctx) { this.ctx = ctx; // Check all the existing services try { // Handle any existing services ServiceReference[] references = ctx.getAllServiceReferences( ModelInfoService.class.getName(), null); ctx.addServiceListener(this, "(objectclass='" + ModelInfoService.class.getName() + "')"); //If we found any service references... if(references != null && references.length != 0) { for (ServiceReference reference : references) { registerServiceEnhancer(reference); } } } catch (InvalidSyntaxException e) { e.printStackTrace(); } // We could listen for find events and mask the original services if we // wanted to // ServiceRegistration findRegistration = // ctx.registerService(FindHook.class.getName(), // new InterceptorFindHook(), null); } /* * (non-Javadoc) * * @see * org.osgi.framework.ServiceListener#serviceChanged(org.osgi.framework. * ServiceEvent) */ @Override public void serviceChanged(ServiceEvent event) { ServiceReference reference = event.getServiceReference(); if (event != null && event.getType() == ServiceEvent.REGISTERED) { registerServiceEnhancer(reference); } else if (event != null && event.getType() == ServiceEvent.UNREGISTERING) { // Better unregister our enhancer Object id = reference.getProperty(SERVICE_ID); ServiceRegistration registration = registrations.get(id); if (registration != null) { registration.unregister(); registrations.remove(id); } } } @SuppressWarnings({ "rawtypes", "unchecked" }) private void registerServiceEnhancer(ServiceReference reference) { Object actualService = ctx.getService(reference); if (actualService instanceof ModelInfoService) { ModelInfoService infoService = (ModelInfoService) actualService; Object serviceId = reference.getProperty(SERVICE_ID); Object enhancer = new ModelInfoEnhancerService(infoService); Dictionary properties = new Hashtable(); Object originalDisplayName = reference.getProperty(DISPLAY_NAME); properties.put(DISPLAY_NAME, originalDisplayName + " [enhanced]"); ServiceRegistration registration = ctx.registerService( ModelInfoService.class.getName(), enhancer, properties); registrations.put(serviceId + "", registration); } else { System.out.println("Oh dear - unexpected service " + actualService.getClass()); } } /** * */ public void stop() { for (ServiceRegistration registration : registrations.values()) { registration.unregister(); } } }
8,403
0
Create_ds/aries/sandbox/samples/dgoat/dgoat-info-enhancer/src/main/java/org/apache/aries/samples/goat
Create_ds/aries/sandbox/samples/dgoat/dgoat-info-enhancer/src/main/java/org/apache/aries/samples/goat/enhancer/ModelInfoEnhancerService.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.samples.goat.enhancer; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.aries.samples.goat.api.ComponentInfo; import org.apache.aries.samples.goat.api.ComponentInfoProvider; import org.apache.aries.samples.goat.api.ModelInfoService; import org.apache.aries.samples.goat.api.RelationshipInfo; import org.apache.aries.samples.goat.api.RelationshipInfoProvider; import org.apache.aries.samples.goat.info.ComponentInfoImpl; import org.apache.aries.samples.goat.info.RelationshipInfoImpl; public class ModelInfoEnhancerService implements ModelInfoService, ComponentInfoProvider, RelationshipInfoProvider, ComponentInfoProvider.ComponentInfoListener, RelationshipInfoProvider.RelationshipInfoListener { private static final String SERVICE_REGISTRATION = "Service registration"; private static final String SERVICE_USAGE = "Service usage"; // TODO where should we expose these shared strings? private static final String SERVICE = "Service"; private ModelInfoService originalService; private final Map<String, ComponentInfo> components = new HashMap<String, ComponentInfo>(); private final Map<String, RelationshipInfo> relationships = new HashMap<String, RelationshipInfo>(); private final List<ComponentInfoListener> clisteners; private final List<RelationshipInfoListener> rlisteners; public ModelInfoEnhancerService(ModelInfoService infoService) { clisteners = Collections .synchronizedList(new ArrayList<ComponentInfoListener>()); rlisteners = Collections .synchronizedList(new ArrayList<RelationshipInfoListener>()); this.originalService = infoService; Collection<ComponentInfo> originalComponents = originalService .getComponentInfoProvider().getComponents(); // We keep all the original components for (ComponentInfo info : originalComponents) { components.put(info.getId(), info); } // We add a new component for each service Collection<RelationshipInfo> originalRelationships = originalService .getRelationshipInfoProvider().getRelationships(); // We keep all the original components for (RelationshipInfo rel : originalRelationships) { if (SERVICE.equals(rel.getType())) { ComponentInfoImpl serviceComponent = new ComponentInfoImpl(); String id = constructServiceComponentId(rel); serviceComponent.setId(id); Map<String, String> componentProperties = new HashMap<String, String>(); componentProperties.put("Name", rel.getName()); serviceComponent.setComponentProperties(componentProperties); components.put(id, serviceComponent); // Make new relationships; RelationshipInfoImpl registration = new RelationshipInfoImpl(); registration.setType(SERVICE_REGISTRATION); registration.setName(rel.getName()); registration.setProvidedBy(rel.getProvidedBy()); registration.setRelationshipAspects(rel .getRelationshipAspects()); ArrayList<ComponentInfo> arrayList = new ArrayList<ComponentInfo>(); arrayList.add(serviceComponent); registration.setConsumedBy(arrayList); relationships.put(constructId(registration), registration); RelationshipInfoImpl consumption = new RelationshipInfoImpl(); consumption.setType(SERVICE_USAGE); consumption.setName(rel.getName()); consumption.setProvidedBy(serviceComponent); consumption.setConsumedBy(rel.getConsumedBy()); consumption .setRelationshipAspects(rel.getRelationshipAspects()); relationships.put(constructId(consumption), consumption); } else { // Pass non-service relationships through relationships.put(constructId(rel), rel); } originalService.getComponentInfoProvider() .registerComponentInfoListener(this); originalService.getRelationshipInfoProvider() .registerRelationshipInfoListener(this); } } @Override public String getName() { return "Model Enhancer Service"; } @Override public ComponentInfoProvider getComponentInfoProvider() { return this; } @Override public RelationshipInfoProvider getRelationshipInfoProvider() { return this; } @Override public Collection<RelationshipInfo> getRelationships() { return relationships.values(); } @Override public Collection<ComponentInfo> getComponents() { return components.values(); } @Override public ComponentInfo getComponentForId(String id) { return components.get(id); } @Override public void registerRelationshipInfoListener( RelationshipInfoListener listener) { rlisteners.add(listener); } @Override public void registerComponentInfoListener(ComponentInfoListener listener) { clisteners.add(listener); } @Override public void updateRelationship(RelationshipInfo r) { if (SERVICE.equals(r.getType())) { updateSyntheticServiceArtefactsAndNotifyListeners(r); } else { // Update our copy relationships.put(constructId(r), r); // This shouldn't affect us, but pass it on to our listeners for (RelationshipInfoListener listener : rlisteners) { listener.updateRelationship(r); } } } @Override public void removeRelationship(RelationshipInfo r) { if (SERVICE.equals(r.getType())) { removeSyntheticServiceArtefactsAndNotifyListeners(r); } else { // We don't want to track this relationship anymore String id = constructId(r); RelationshipInfo relationship = relationships.get(id); relationships.remove(id); if (relationship != null) { // This shouldn't affect us, but pass it on to our listeners for (RelationshipInfoListener listener : rlisteners) { listener.removeRelationship(relationship); } } } } @Override public void updateComponent(ComponentInfo b) { // Update our copy components.put(b.getId(), b); // This shouldn't affect us, but pass it on to our listeners for (ComponentInfoListener listener : clisteners) { listener.updateComponent(b); } } @Override public void removeComponent(ComponentInfo b) { // This shouldn't affect us unless it has relationships pointing to it // Cheerfully assume that gets handled upstream // We don't want to know about this component anymore ComponentInfo component = components.remove(b); if (component != null) {// This shouldn't affect us, but pass it on to // our listeners for (ComponentInfoListener listener : clisteners) { listener.removeComponent(component); } } } private String constructServiceComponentId(RelationshipInfo rel) { return "/syntheticenhancedservices/" + rel.getName() + "/" + rel.getProvidedBy().getId(); } private String constructId(RelationshipInfo b) { return b.getType() + "/" + b.getName() + "/" + b.getProvidedBy().getId(); } private void removeSyntheticServiceArtefactsAndNotifyListeners( RelationshipInfo r) { // We need to remove our two relationships and the synthetic // component String componentId = constructServiceComponentId(r); // Do the relationships first // The registration has type "service registration", and the // original provider and name String registrationRelationshipId = SERVICE_REGISTRATION + "/" + r.getName() + "/" + r.getProvidedBy().getId(); RelationshipInfo registrationRelationship = relationships .get(registrationRelationshipId); // The consumers have type "service usage", and the // original name, and the new provided by String usageRelationshipId = SERVICE_USAGE + "/" + r.getName() + "/" + componentId; RelationshipInfo usageRelationship = relationships .get(usageRelationshipId); relationships.remove(usageRelationshipId); relationships.remove(registrationRelationshipId); // Tell our listeners about the relationships first for (RelationshipInfoListener listener : rlisteners) { if (usageRelationship != null) { listener.removeRelationship(usageRelationship); } if (registrationRelationship != null) { listener.removeRelationship(registrationRelationship); } } ComponentInfo component = components.remove(componentId); if (component != null) { // Tell our listeners their service component went away for (ComponentInfoListener listener : clisteners) { listener.removeComponent(component); } } } private void updateSyntheticServiceArtefactsAndNotifyListeners( RelationshipInfo r) { // We need to update our two relationships and the synthetic // component // Hopefully the thing which changed won't prevent us // from finding our relationship String componentId = constructServiceComponentId(r); // Do the relationships first // The registration has type "service registration", and the // original provider and name String registrationRelationshipId = SERVICE_REGISTRATION + "/" + r.getName() + "/" + r.getProvidedBy().getId(); RelationshipInfoImpl registrationRelationship = (RelationshipInfoImpl) relationships .get(registrationRelationshipId); registrationRelationship.setName(r.getName()); registrationRelationship.setRelationshipAspects(r .getRelationshipAspects()); // The consumers have type "service usage", and the // original name, and the new provided by String usageRelationshipId = SERVICE_USAGE + "/" + r.getName() + "/" + componentId; RelationshipInfoImpl usageRelationship = (RelationshipInfoImpl) relationships .get(usageRelationshipId); // The consumers may have changed, so we update the usage relationship usageRelationship.setConsumedBy(r.getConsumedBy()); usageRelationship.setName(r.getName()); usageRelationship.setRelationshipAspects(r.getRelationshipAspects()); // Tell our listeners about the relationships first for (RelationshipInfoListener listener : rlisteners) { if (usageRelationship != null) { listener.updateRelationship(usageRelationship); } if (registrationRelationship != null) { listener.updateRelationship(registrationRelationship); } } ComponentInfo component = components.get(componentId); if (component != null) { // Tell our listeners their service component was updated for (ComponentInfoListener listener : clisteners) { listener.updateComponent(component); } } } }
8,404
0
Create_ds/aries/sandbox/samples/dgoat/dgoat-info-enhancer/src/main/java/org/apache/aries/samples/goat
Create_ds/aries/sandbox/samples/dgoat/dgoat-info-enhancer/src/main/java/org/apache/aries/samples/goat/enhancer/Activator.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.samples.goat.enhancer; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; public class Activator implements BundleActivator { private ServiceInterceptor interceptor; @Override public void start(BundleContext ctx) throws Exception { interceptor = new ServiceInterceptor(ctx); } /* * (non-Javadoc) * * @see * org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext) */ @Override public void stop(BundleContext arg0) throws Exception { interceptor.stop(); } }
8,405
0
Create_ds/aries/sandbox/samples/dgoat/dgoat-cxf-sample-server/src/main/java/org/apache/cxf/dosgi/samples/greeter
Create_ds/aries/sandbox/samples/dgoat/dgoat-cxf-sample-server/src/main/java/org/apache/cxf/dosgi/samples/greeter/impl/Activator.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.cxf.dosgi.samples.greeter.impl; import java.util.Dictionary; import java.util.Hashtable; import org.apache.cxf.dosgi.samples.greeter.GreeterService; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceRegistration; public class Activator implements BundleActivator { private ServiceRegistration registration; public void start(BundleContext bc) throws Exception { Dictionary props = new Hashtable(); props.put("service.exported.interfaces", "*"); props.put("service.exported.configs", "org.apache.cxf.ws"); props.put("org.apache.cxf.ws.address", "http://localhost:9090/greeter"); registration = bc.registerService(GreeterService.class.getName(), new GreeterServiceImpl(), props); } public void stop(BundleContext bc) throws Exception { registration.unregister(); } }
8,406
0
Create_ds/aries/sandbox/samples/dgoat/dgoat-cxf-sample-server/src/main/java/org/apache/cxf/dosgi/samples/greeter
Create_ds/aries/sandbox/samples/dgoat/dgoat-cxf-sample-server/src/main/java/org/apache/cxf/dosgi/samples/greeter/impl/GreeterServiceImpl.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.cxf.dosgi.samples.greeter.impl; import java.util.HashMap; import java.util.Map; import org.apache.cxf.dosgi.samples.greeter.GreeterData; import org.apache.cxf.dosgi.samples.greeter.GreeterException; import org.apache.cxf.dosgi.samples.greeter.GreeterService; import org.apache.cxf.dosgi.samples.greeter.GreetingPhrase; public class GreeterServiceImpl implements GreeterService { public Map<GreetingPhrase, String> greetMe(String name) { System.out.println("Invoking: greetMe(" + name + ")"); Map<GreetingPhrase, String> greetings = new HashMap<GreetingPhrase, String>(); greetings.put(new GreetingPhrase("Hello"), name); greetings.put(new GreetingPhrase("Hoi"), name); greetings.put(new GreetingPhrase("Hola"), name); greetings.put(new GreetingPhrase("Bonjour"), name); return greetings; } public GreetingPhrase [] greetMe(GreeterData gd) throws GreeterException { if (gd.isException()) { System.out.println("Throwing custom exception from: greetMe(" + gd.getName() + ")"); throw new GreeterException(gd.getName()); } String details = gd.getName() + "(" + gd.getAge() + ")"; System.out.println("Invoking: greetMe(" + details + ")"); GreetingPhrase [] greetings = new GreetingPhrase [] { new GreetingPhrase("Howdy " + details), new GreetingPhrase("Hallo " + details), new GreetingPhrase("Ni hao " + details) }; return greetings; } }
8,407
0
Create_ds/aries/sandbox/samples/dgoat/dgoat-bundlecontext-modelprovider/src/main/java/org/apache/aries/samples/goat
Create_ds/aries/sandbox/samples/dgoat/dgoat-bundlecontext-modelprovider/src/main/java/org/apache/aries/samples/goat/bundlecontextmodel/BundleContextInfoProvider.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.samples.goat.bundlecontextmodel; import java.util.ArrayList; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; import org.osgi.framework.BundleEvent; import org.osgi.framework.BundleListener; import org.osgi.framework.ServiceEvent; import org.osgi.framework.ServiceListener; import org.osgi.framework.ServiceReference; import org.osgi.service.packageadmin.ExportedPackage; import org.osgi.service.packageadmin.PackageAdmin; import org.apache.aries.samples.goat.info.ComponentInfoImpl; import org.apache.aries.samples.goat.info.RelationshipInfoImpl; import org.apache.aries.samples.goat.api.ComponentInfo; import org.apache.aries.samples.goat.api.ComponentInfoProvider; import org.apache.aries.samples.goat.api.ModelInfoService; import org.apache.aries.samples.goat.api.RelationshipAspect; import org.apache.aries.samples.goat.api.RelationshipInfo; import org.apache.aries.samples.goat.api.RelationshipInfoProvider; public class BundleContextInfoProvider implements ModelInfoService, RelationshipInfoProvider, ComponentInfoProvider, BundleListener, ServiceListener { private Map<String, ComponentInfo>biCache = new HashMap<String,ComponentInfo>(); private Map<String, RelationshipInfo>riCache = new HashMap<String,RelationshipInfo>(); private List<ComponentInfoListener> clisteners=null; private List<RelationshipInfoListener> rlisteners=null; private BundleContext ctx=null; public BundleContextInfoProvider(BundleContext ctx){ System.err.println("BCIP built!"); this.ctx = ctx; this.clisteners = Collections.synchronizedList(new ArrayList<ComponentInfoListener>()); this.rlisteners = Collections.synchronizedList(new ArrayList<RelationshipInfoListener>()); this.ctx.addBundleListener(this); this.ctx.addServiceListener(this); } public List<ComponentInfo> getComponents() { System.err.println("BCIP getBundles called"); Bundle[] bundles = this.ctx.getBundles(); List<ComponentInfo> result = new ArrayList<ComponentInfo>(); for(int i=0; i<bundles.length; i++){ System.err.println("BCIP converting "+i); result.add( getComponentForId( getKeyForBundle(bundles[i])) ); } System.err.println("BCIP returning data"); return result; } public void registerComponentInfoListener(ComponentInfoListener listener) { clisteners.add(listener); } public void registerRelationshipInfoListener(RelationshipInfoListener listener) { rlisteners.add(listener); } private Bundle getBundleForIDKey(BundleContext ctx, String id){ String s =id.substring("/root/".length()); Long l = Long.parseLong(s); return ctx.getBundle(l.longValue()); } private String bundleStateToString(int bundleState){ switch(bundleState){ case Bundle.UNINSTALLED : return "UNINSTALLED"; case Bundle.INSTALLED : return "INSTALLED"; case Bundle.RESOLVED : return "RESOLVED"; case Bundle.STARTING : return "STARTING"; case Bundle.STOPPING : return "STOPPING"; case Bundle.ACTIVE : return "ACTIVE"; default : return "UNKNOWN["+bundleState+"]"; } } public ComponentInfo getComponentForId(String id) { if(biCache.containsKey(id)){ return biCache.get(id); } Bundle b = getBundleForIDKey(ctx,id); ComponentInfoImpl bii = new ComponentInfoImpl(); bii.setId(getKeyForBundle(b)); HashSet<Long> allDepSet = new HashSet<Long>(); bii.setComponentProperties(new HashMap<String,String>()); bii.getComponentProperties().put("BundleID", ""+b.getBundleId()); bii.getComponentProperties().put("State", bundleStateToString(b.getState())); bii.getComponentProperties().put("SymbolicName", b.getSymbolicName()); bii.getComponentProperties().put("Version", ""+b.getVersion()); Enumeration<String> e = b.getHeaders().keys(); while(e.hasMoreElements()){ String key = e.nextElement(); //Ideally we'd add everything here.. but until we add the filtering in the ui //its easier to just filter here.. for now, all 'extra' properties are removed. if(! (key.equals("Import-Package") || key.equals("Export-Package")) ){ //bii.getComponentProperties().put(key, String.valueOf(b.getHeaders().get(key))); } } bii.setChildren(new ArrayList<ComponentInfo>()); biCache.put(id, bii); return bii; } public void bundleChanged(BundleEvent arg0) { String id = getKeyForBundle(arg0.getBundle()); if(biCache.containsKey(id)){ biCache.remove(id); } ComponentInfo bi = getComponentForId(getKeyForBundle(arg0.getBundle())); for(ComponentInfoListener bil : clisteners){ bil.updateComponent(bi); } } private String getKeyForBundle(Bundle b){ return "/root/"+b.getBundleId(); } @Override public List<RelationshipInfo> getRelationships() { ArrayList<RelationshipInfo> r = new ArrayList<RelationshipInfo>(); Bundle bundles[] = ctx.getBundles(); PackageAdmin pa = (PackageAdmin)ctx.getService(ctx.getServiceReference(PackageAdmin.class.getName().toString())); if(bundles!=null && bundles.length!=0){ for(Bundle b: bundles){ String bkey = getKeyForBundle(b); ComponentInfo ci = getComponentForId(bkey); //add all the packages.. //we only add exports, as imports are implied in the reverse ExportedPackage eps[] = pa.getExportedPackages(b); if(eps!=null && eps.length!=0){ for(ExportedPackage ep : eps){ RelationshipInfoImpl ri = new RelationshipInfoImpl(); ri.setProvidedBy( ci ); ri.setType("Package"); ri.setName(ep.getName()); ri.setRelationshipAspects(new ArrayList<RelationshipAspect>()); ri.setConsumedBy(new ArrayList<ComponentInfo>()); //TODO: add versioning aspect. Bundle imps[] = ep.getImportingBundles(); if(imps!=null && imps.length!=0){ for(Bundle imp : imps){ ri.getConsumedBy().add(getComponentForId(getKeyForBundle(imp))); } } r.add(ri); } } //add all the services.. //we only add registered services, as ones in use are handled in the reverse ServiceReference srs[] = b.getRegisteredServices(); if(srs!=null && srs.length!=0){ for(ServiceReference sr : srs){ RelationshipInfoImpl ri = getRIforSR(sr); ri.setProvidedBy( ci ); r.add(ri); } } } } return r; } private RelationshipInfoImpl getRIforSR(ServiceReference sr){ RelationshipInfoImpl ri = new RelationshipInfoImpl(); ri.setType("Service"); String serviceNames=""; String []objectClasses = (String[])sr.getProperty("objectClass"); if(objectClasses!=null){ for(String objectClass : objectClasses){ serviceNames+=","+objectClass; } } if(serviceNames.length()>1){ serviceNames = serviceNames.substring(1); } ri.setName(serviceNames); ri.setRelationshipAspects(new ArrayList<RelationshipAspect>()); //TODO: add service parameters ri.setConsumedBy(new ArrayList<ComponentInfo>()); Bundle using[] = sr.getUsingBundles(); if(using!=null && using.length!=0){ for(Bundle u : using){ ri.getConsumedBy().add(getComponentForId(getKeyForBundle(u))); } } return ri; } @Override public String getName() { return "Bundle Context Info Provider 1.0"; } @Override public ComponentInfoProvider getComponentInfoProvider() { return this; } @Override public RelationshipInfoProvider getRelationshipInfoProvider() { return this; } @Override public void serviceChanged(ServiceEvent arg0) { if(arg0.getType() == ServiceEvent.REGISTERED || arg0.getType() == ServiceEvent.MODIFIED || arg0.getType() == ServiceEvent.MODIFIED_ENDMATCH){ ServiceReference sr = arg0.getServiceReference(); RelationshipInfoImpl ri = getRIforSR(sr); ComponentInfo ci = getComponentForId(getKeyForBundle(sr.getBundle())); ri.setProvidedBy(ci); for(RelationshipInfoListener ril : rlisteners){ ril.updateRelationship(ri); } }else if(arg0.getType() == ServiceEvent.UNREGISTERING){ ServiceReference sr = arg0.getServiceReference(); RelationshipInfoImpl ri = getRIforSR(sr); ComponentInfo ci = getComponentForId(getKeyForBundle(sr.getBundle())); ri.setProvidedBy(ci); for(RelationshipInfoListener ril : rlisteners){ ril.removeRelationship(ri); } } } }
8,408
0
Create_ds/aries/sandbox/samples/dgoat/dgoat-api/src/main/java/org/apache/aries/samples/goat
Create_ds/aries/sandbox/samples/dgoat/dgoat-api/src/main/java/org/apache/aries/samples/goat/info/RelationshipInfoImpl.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.samples.goat.info; import java.util.List; import org.apache.aries.samples.goat.api.RelationshipInfo; import org.apache.aries.samples.goat.api.RelationshipAspect; import org.apache.aries.samples.goat.api.ComponentInfo;; public class RelationshipInfoImpl implements RelationshipInfo { List<ComponentInfo> consumedBy; List<RelationshipAspect> relationshipAspects; String name; ComponentInfo providedBy; String type; public List<ComponentInfo> getConsumedBy() { return consumedBy; } public void setConsumedBy(List<ComponentInfo> consumedBy) { this.consumedBy = consumedBy; } public List<RelationshipAspect> getRelationshipAspects() { return relationshipAspects; } public void setRelationshipAspects(List<RelationshipAspect> relationshipAspects) { this.relationshipAspects = relationshipAspects; } public String getName() { return name; } public void setName(String name) { this.name = name; } public ComponentInfo getProvidedBy() { return providedBy; } public void setProvidedBy(ComponentInfo providedBy) { this.providedBy = providedBy; } public String getType() { return type; } public void setType(String type) { this.type = type; } }
8,409
0
Create_ds/aries/sandbox/samples/dgoat/dgoat-api/src/main/java/org/apache/aries/samples/goat
Create_ds/aries/sandbox/samples/dgoat/dgoat-api/src/main/java/org/apache/aries/samples/goat/info/ComponentInfoImpl.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.samples.goat.info; import java.util.List; import java.util.Map; import org.apache.aries.samples.goat.api.ComponentInfo; public class ComponentInfoImpl implements ComponentInfo { List<ComponentInfo> children; Map<String,String> componentProperties; String id; public List<ComponentInfo> getChildren() { return children; } public void setChildren(List<ComponentInfo> children) { this.children = children; } public Map<String, String> getComponentProperties() { return componentProperties; } public void setComponentProperties(Map<String, String> componentProperties) { this.componentProperties = componentProperties; } public String getId() { return id; } public void setId(String id) { this.id = id; } }
8,410
0
Create_ds/aries/sandbox/samples/dgoat/dgoat-api/src/main/java/org/apache/aries/samples/goat
Create_ds/aries/sandbox/samples/dgoat/dgoat-api/src/main/java/org/apache/aries/samples/goat/api/ComponentInfoProvider.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.samples.goat.api; import java.util.Collection; /** * Provides information about components within a model. * * Good usage practice would be to subscribe a listener .. and THEN call * getComponents.. (doing it the other way round risks leaving a window during * which a change could occur, and you not be informed). (doing it this way * round, at worst, you'll see an update before you handle getComponents, and * since an update can be an add, you'll just process it twice) * */ public interface ComponentInfoProvider { /** * Callback interface implemented by users of the ComponentInfoProvider * interface, allowing notification of changes, or deletions to components * they have been informed about. */ static interface ComponentInfoListener { // called to add, or update a component. public void updateComponent(ComponentInfo b); public void removeComponent(ComponentInfo b); }; /** * Gets the current set of 'top level' components in this model. * * Any nested components are only obtainable via the 'getChildren' method on * ComponentInfo. * * @return */ Collection<ComponentInfo> getComponents(); /** * Gets a component for an id previously returned via getComponents, or * updateComponent * * @param id * @return component, or null if component id is either unknown, or deleted. */ ComponentInfo getComponentForId(String id); /** * Add a listener to this Info Provider, to be informed of * changes/deletions. * * @param listener */ public void registerComponentInfoListener(ComponentInfoListener listener); // TODO: unregisterComponentInfoListener ;-) }
8,411
0
Create_ds/aries/sandbox/samples/dgoat/dgoat-api/src/main/java/org/apache/aries/samples/goat
Create_ds/aries/sandbox/samples/dgoat/dgoat-api/src/main/java/org/apache/aries/samples/goat/api/ModelInfoService.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.samples.goat.api; /** * The top level service interface published to the service registry * * A model is something with components, with relationships between them. */ public interface ModelInfoService { String getName(); ComponentInfoProvider getComponentInfoProvider(); RelationshipInfoProvider getRelationshipInfoProvider(); }
8,412
0
Create_ds/aries/sandbox/samples/dgoat/dgoat-api/src/main/java/org/apache/aries/samples/goat
Create_ds/aries/sandbox/samples/dgoat/dgoat-api/src/main/java/org/apache/aries/samples/goat/api/ComponentInfo.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.samples.goat.api; import java.util.List; import java.util.Map; public interface ComponentInfo { String getId(); /** * always needed, id's must be unique globally, or within their containing component info. * (impl notes.. (for bundles) * Id's will probably NOT be bundle id's... we need the id to be fixed between framework restarts, * to enable things like storing coords for onscreen renderings of components * Id's will probably end up being path based, /component.id/component.id etc .. for sanities sake. * Component properties are information that forms part of a component, keys will vary depending on * what the component represents. The GUI will handle rendering based on key names. */ Map<String,String> getComponentProperties(); /** * children are only supported in concept currently.. no gui work done yet for them.. * List of any contained components for this component. */ List<ComponentInfo> getChildren(); }
8,413
0
Create_ds/aries/sandbox/samples/dgoat/dgoat-api/src/main/java/org/apache/aries/samples/goat
Create_ds/aries/sandbox/samples/dgoat/dgoat-api/src/main/java/org/apache/aries/samples/goat/api/ParameterizedRelationshipAspect.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.samples.goat.api; import java.util.List; public interface ParameterizedRelationshipAspect extends RelationshipAspect{ static class Parameter{ String key; String value; }; List<Parameter> getProvidedParameters(); //any parameters specified by the supplier of the dependency. List<Parameter> getConsumedParameters(); //any parameters specified by the consumer of the dependency. }
8,414
0
Create_ds/aries/sandbox/samples/dgoat/dgoat-api/src/main/java/org/apache/aries/samples/goat
Create_ds/aries/sandbox/samples/dgoat/dgoat-api/src/main/java/org/apache/aries/samples/goat/api/RelationshipAspect.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.samples.goat.api; public interface RelationshipAspect { public String getType(); }
8,415
0
Create_ds/aries/sandbox/samples/dgoat/dgoat-api/src/main/java/org/apache/aries/samples/goat
Create_ds/aries/sandbox/samples/dgoat/dgoat-api/src/main/java/org/apache/aries/samples/goat/api/RelationshipInfoProvider.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.samples.goat.api; import java.util.Collection; public interface RelationshipInfoProvider { static interface RelationshipInfoListener { public void updateRelationship(RelationshipInfo b); public void removeRelationship(RelationshipInfo b); }; Collection<RelationshipInfo> getRelationships(); public void registerRelationshipInfoListener( RelationshipInfoListener listener); }
8,416
0
Create_ds/aries/sandbox/samples/dgoat/dgoat-api/src/main/java/org/apache/aries/samples/goat
Create_ds/aries/sandbox/samples/dgoat/dgoat-api/src/main/java/org/apache/aries/samples/goat/api/RelationshipInfo.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.samples.goat.api; import java.util.List; //This represents a single dependency between two components public interface RelationshipInfo { //relationships are unique by type&name combined. String getType(); //String describing the type of this dependency. String getName(); //name of this dependency. //the provider/consumer side of this relationship. ComponentInfo getProvidedBy(); //consumers can of course, be empty. (thats empty.. NOT null) List<ComponentInfo> getConsumedBy(); //relationship aspects are not fully integrated yet.. avoid until stable ;-) List<RelationshipAspect> getRelationshipAspects(); }
8,417
0
Create_ds/aries/sandbox/samples/dgoat/dgoat-api/src/main/java/org/apache/aries/samples/goat
Create_ds/aries/sandbox/samples/dgoat/dgoat-api/src/main/java/org/apache/aries/samples/goat/api/VersionedRelationshipAspect.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.samples.goat.api; public interface VersionedRelationshipAspect extends RelationshipAspect { String getProvidedVersion(); //this will be an exact version. String getConsumedVersion(); //this will be either a range, or an exact version. //provided version will either match, or be in the range. }
8,418
0
Create_ds/aries/sandbox/samples/dgoat/dgoat-cxf-sample-api/src/main/java/org/apache/cxf/dosgi/samples
Create_ds/aries/sandbox/samples/dgoat/dgoat-cxf-sample-api/src/main/java/org/apache/cxf/dosgi/samples/greeter/GreeterData.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.cxf.dosgi.samples.greeter; public interface GreeterData { String getName(); int getAge(); boolean isException(); }
8,419
0
Create_ds/aries/sandbox/samples/dgoat/dgoat-cxf-sample-api/src/main/java/org/apache/cxf/dosgi/samples
Create_ds/aries/sandbox/samples/dgoat/dgoat-cxf-sample-api/src/main/java/org/apache/cxf/dosgi/samples/greeter/GreetingPhrase.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.cxf.dosgi.samples.greeter; public class GreetingPhrase { private String phrase; public GreetingPhrase() { } public GreetingPhrase(String phrase) { this.phrase = phrase; } public void setPhrase(String thePhrase) { this.phrase = thePhrase; } public String getPhrase() { return phrase; } @Override public int hashCode() { return phrase.hashCode(); } @Override public boolean equals(Object other) { if (!GreetingPhrase.class.isAssignableFrom(other.getClass())) { return false; } return phrase.equals(((GreetingPhrase)other).phrase); } }
8,420
0
Create_ds/aries/sandbox/samples/dgoat/dgoat-cxf-sample-api/src/main/java/org/apache/cxf/dosgi/samples
Create_ds/aries/sandbox/samples/dgoat/dgoat-cxf-sample-api/src/main/java/org/apache/cxf/dosgi/samples/greeter/GreeterException.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.cxf.dosgi.samples.greeter; public class GreeterException extends Exception { private String name; public GreeterException() { } public GreeterException(String name) { this.name = name; } public String getName() { return name; } public void setName(String theName) { name = theName; } @Override public String toString() { return "GreeterService can not greet " + name; } }
8,421
0
Create_ds/aries/sandbox/samples/dgoat/dgoat-cxf-sample-api/src/main/java/org/apache/cxf/dosgi/samples
Create_ds/aries/sandbox/samples/dgoat/dgoat-cxf-sample-api/src/main/java/org/apache/cxf/dosgi/samples/greeter/GreeterService.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.cxf.dosgi.samples.greeter; import java.util.Map; public interface GreeterService { Map<GreetingPhrase, String> greetMe(String name); GreetingPhrase [] greetMe(GreeterData name) throws GreeterException; }
8,422
0
Create_ds/aries/sandbox/samples/dgoat/dgoat-dummy-provider/src/main/java/org/apache/aries/samples/goat
Create_ds/aries/sandbox/samples/dgoat/dgoat-dummy-provider/src/main/java/org/apache/aries/samples/goat/dummy/DummyModelService.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.samples.goat.dummy; import org.apache.aries.samples.goat.api.ComponentInfoProvider; import org.apache.aries.samples.goat.api.ModelInfoService; import org.apache.aries.samples.goat.api.RelationshipInfoProvider; public class DummyModelService implements ModelInfoService { private final static ComponentInfoProvider cip = new DummyInfoProvider(); private final static RelationshipInfoProvider rip = new DummyRelationshipProvider(cip); @Override public String getName() { return "Dummy Model Service"; } @Override public ComponentInfoProvider getComponentInfoProvider() { return cip; } @Override public RelationshipInfoProvider getRelationshipInfoProvider() { return rip; } }
8,423
0
Create_ds/aries/sandbox/samples/dgoat/dgoat-dummy-provider/src/main/java/org/apache/aries/samples/goat
Create_ds/aries/sandbox/samples/dgoat/dgoat-dummy-provider/src/main/java/org/apache/aries/samples/goat/dummy/DummyInfoProvider.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.samples.goat.dummy; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.aries.samples.goat.info.ComponentInfoImpl; import org.apache.aries.samples.goat.api.ComponentInfo; import org.apache.aries.samples.goat.api.ComponentInfoProvider; public class DummyInfoProvider implements ComponentInfoProvider { ComponentInfoImpl a = new ComponentInfoImpl(); ComponentInfoImpl b = new ComponentInfoImpl(); ComponentInfoImpl c = new ComponentInfoImpl(); public DummyInfoProvider(){ a.setId("/root/"+1); Map<String,String> props = new HashMap<String,String>(); props.put("SymbolicName", "Uber.Bundle"); props.put("Version", "1.0.0"); props.put("State", "ACTIVE"); props.put("BundleID", "1"); a.setComponentProperties(props); b.setId("/root/"+2); props = new HashMap<String,String>(); props.put("SymbolicName", "Fred"); props.put("Version", "1.0.0"); props.put("State", "RESOLVED"); props.put("BundleID", "2"); b.setComponentProperties(props); c.setId("/root/"+3); props = new HashMap<String,String>(); props.put("SymbolicName", "Wilma"); props.put("Version", "1.0.0"); props.put("State", "ACTIVE"); props.put("BundleID", "3"); c.setComponentProperties(props); } @Override public List<ComponentInfo> getComponents() { List<ComponentInfo> result = new ArrayList<ComponentInfo>(); result.add(a); result.add(b); result.add(c); return result; } @Override public ComponentInfo getComponentForId(String id) { if("/root/1".equals(id)) return a; if("/root/2".equals(id)) return b; if("/root/3".equals(id)) return c; return null; } @Override public void registerComponentInfoListener(ComponentInfoListener listener) { //no-op } }
8,424
0
Create_ds/aries/sandbox/samples/dgoat/dgoat-dummy-provider/src/main/java/org/apache/aries/samples/goat
Create_ds/aries/sandbox/samples/dgoat/dgoat-dummy-provider/src/main/java/org/apache/aries/samples/goat/dummy/DummyRelationshipProvider.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.samples.goat.dummy; import java.util.ArrayList; import java.util.List; import org.apache.aries.samples.goat.info.RelationshipInfoImpl; import org.apache.aries.samples.goat.api.ComponentInfo; import org.apache.aries.samples.goat.api.ComponentInfoProvider; import org.apache.aries.samples.goat.api.RelationshipInfo; import org.apache.aries.samples.goat.api.RelationshipInfoProvider; public class DummyRelationshipProvider implements RelationshipInfoProvider { ComponentInfoProvider cip = null; public DummyRelationshipProvider(ComponentInfoProvider cip){ this.cip = cip; } @Override public List<RelationshipInfo> getRelationships() { ArrayList<RelationshipInfo> ris = new ArrayList<RelationshipInfo>(); ComponentInfo ci1 = cip.getComponentForId("/root/1"); ComponentInfo ci2 = cip.getComponentForId("/root/2"); ComponentInfo ci3 = cip.getComponentForId("/root/3"); RelationshipInfoImpl ri1 = new RelationshipInfoImpl(); RelationshipInfoImpl ri2 = new RelationshipInfoImpl(); RelationshipInfoImpl ri3 = new RelationshipInfoImpl(); RelationshipInfoImpl ri4 = new RelationshipInfoImpl(); RelationshipInfoImpl ri5 = new RelationshipInfoImpl(); RelationshipInfoImpl ri6 = new RelationshipInfoImpl(); ris.add(ri1); ris.add(ri2); ris.add(ri3); ris.add(ri4); ris.add(ri5); ris.add(ri6); ri1.setName("i.am.exported.by.1.and.used.by.2.and.3"); ri1.setProvidedBy(ci1); ArrayList<ComponentInfo> c = new ArrayList<ComponentInfo>(); c.add(ci2); c.add(ci3); ri1.setConsumedBy(c); ri1.setType("Package"); ri2.setName("i.am.exported.by.1.and.used.by.3"); ri2.setProvidedBy(ci1); c = new ArrayList<ComponentInfo>(); c.add(ci3); ri2.setConsumedBy(c); ri2.setType("Package"); ri3.setName("i.am.exported.by.2.and.used.by.3"); ri3.setProvidedBy(ci2); c = new ArrayList<ComponentInfo>(); c.add(ci3); ri3.setConsumedBy(c); ri3.setType("Package"); ri4.setName("i.am.exported.by.3.and.used.by.2"); ri4.setProvidedBy(ci3); c = new ArrayList<ComponentInfo>(); c.add(ci2); ri4.setConsumedBy(c); ri4.setType("Package"); ri5.setName("i.am.a.funky.service.from.3.used.by.2"); ri5.setProvidedBy(ci3); c = new ArrayList<ComponentInfo>(); c.add(ci2); ri5.setConsumedBy(c); ri5.setType("Service"); ri6.setName("i.am.a.funky.service.from.1.used.by.2"); ri6.setProvidedBy(ci1); c = new ArrayList<ComponentInfo>(); c.add(ci2); ri6.setConsumedBy(c); ri6.setType("Service"); return ris; } @Override public void registerRelationshipInfoListener(RelationshipInfoListener listener) { // TODO Auto-generated method stub } }
8,425
0
Create_ds/aries/sandbox/samples/transaction-sample/transaction-sample-web/src/main/java/org/apache/aries/samples
Create_ds/aries/sandbox/samples/transaction-sample/transaction-sample-web/src/main/java/org/apache/aries/samples/transaction/GenericJTAException.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.samples.transaction; import javax.transaction.RollbackException; public class GenericJTAException extends Exception { /** * */ private static final long serialVersionUID = 3760423779101497679L; public GenericJTAException(Exception e) { super (e); } }
8,426
0
Create_ds/aries/sandbox/samples/transaction-sample/transaction-sample-web/src/main/java/org/apache/aries/samples
Create_ds/aries/sandbox/samples/transaction-sample/transaction-sample-web/src/main/java/org/apache/aries/samples/transaction/TxDBServlet.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.samples.transaction; import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Properties; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.sql.XAConnection; import javax.sql.XADataSource; import javax.transaction.HeuristicMixedException; import javax.transaction.HeuristicRollbackException; import javax.transaction.NotSupportedException; import javax.transaction.RollbackException; import javax.transaction.SystemException; import javax.transaction.Transaction; import javax.transaction.TransactionManager; import javax.transaction.xa.XAResource; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceReference; import org.osgi.service.jdbc.DataSourceFactory; public class TxDBServlet extends HttpServlet { private static final long serialVersionUID = 1L; private static final String OSGI_BUNDLECONTEXT_ATTRIBUTE = "osgi-bundlecontext"; private static final String CLEAN_TABLE = "delete from txDemo"; private static final String SELECT_TABLE = "SELECT * FROM txDemo"; private static final String INSERT_INTO_TABLE = "INSERT INTO txDemo VALUES(?)"; private static final String LOGO_HEADER = "<TABLE border='0\' cellpadding=\'0\' cellspacing='0' width='100%'> " + "<TR> " + "<TD align='left' class='topbardiv' nowrap=''>" + "<A href='http://incubator.apache.org/aries/' title='Apache Aries (incubating)'>" + "<IMG border='0' src='http://incubator.apache.org/aries/images/Arieslogo_Horizontal.gif'>" + "</A>" + "</TD>" + "<TD align='right' nowrap=''>" + "<A href='http://www.apache.org/' title='The Apache Software Foundation'>" + "<IMG border='0' src='http://incubator.apache.org/aries/images/apache-incubator-logo.png'>" + "</A>"+ "</TD>"+ "</TR>"+ "</TABLE>"; private PrintWriter pw = null; public void init() throws ServletException { } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { pw = response.getWriter(); pw.write(LOGO_HEADER); // Get the bundle context from ServletContext attributes BundleContext ctx = (BundleContext) getServletContext().getAttribute(OSGI_BUNDLECONTEXT_ATTRIBUTE); pw.println("<html>"); pw.println("<head>"); pw.println("<link rel=\"stylesheet\" type=\"text/css\" href=\"tableTemplate.css\"/>"); pw.println("<body>"); pw.println("<h2 align=center><p><font face=\"Tahoma\">Sample Application for JDBC usage in JTA Transactions.</font></h2>"); pw.println("<p><p>"); ServiceReference tmServiceRef = ctx.getServiceReference("javax.transaction.TransactionManager"); ServiceReference derbyServiceRef = ctx.getServiceReference(DataSourceFactory.class.getName()); if(tmServiceRef == null || derbyServiceRef == null){ pw.println("<font face=\"Tahoma\">TransactionManager or Derby driver are not available in the OSGI registry.</font><br>"); } else { TransactionManager tm = (TransactionManager)ctx.getService(tmServiceRef); DataSourceFactory derbyRegistry = (DataSourceFactory)ctx.getService(derbyServiceRef); try{ // Set the needed properties for the database connection Properties props = new Properties(); props.put(DataSourceFactory.JDBC_URL, "jdbc:derby:txDemo"); props.put(DataSourceFactory.JDBC_DATABASE_NAME, "txDemo"); props.put(DataSourceFactory.JDBC_USER, ""); props.put(DataSourceFactory.JDBC_PASSWORD, ""); XADataSource xaDataSource = derbyRegistry.createXADataSource(props); pw.println("<center><form><table><tr><td align='right'>Value: </td><td align=left><input type='text' name='value' value='' size='12'/><input type='submit' name='action' value='InsertAndCommit' size='100'/></td></tr>"); pw.println("<tr><td align='right'>Value: </td><td align=left><input type='text' name='value' value='' size='12'/><input type='submit' name='action' value='InsertAndRollback' size='100'/></center></td></tr>"); pw.println("<tr colspan='2' align='center'><td>&nbsp;</td><td><input type='submit' name='action' value='cleanTable' size='100' />&nbsp;<input type='submit' name='action' value='printTable' size='100'/></td><tr></table></form></center>"); String value = request.getParameter("value"); String action = request.getParameter("action"); if(action != null && action.equals("InsertAndCommit")){ insertIntoTransaction(xaDataSource, tm, value, true); } else if(action != null && action.equals("InsertAndRollback")){ insertIntoTransaction(xaDataSource, tm, value, false); } else if(action != null && action.equals("cleanTable")){ cleanTable(xaDataSource); } printTable(xaDataSource); } catch (Exception e){ pw.println("<font face=\"Tahoma\">Unexpected exception occurred "+ e.toString()+".</font><br>"); e.printStackTrace(pw); } } pw.println("</body>"); pw.println("</html>"); pw.flush(); }// end of doGet(HttpServletRequest request, HttpServletResponse response) protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); }// end of doPost(HttpServletRequest request, HttpServletResponse response) /** * Prints the table * @param xaDataSource * @throws SQLException */ private void printTable(XADataSource xaDataSource) throws SQLException { XAConnection xaConnection = xaDataSource.getXAConnection(); Connection connection = xaConnection.getConnection(); PreparedStatement selectStatement = connection.prepareStatement(SELECT_TABLE); ResultSet set = selectStatement.executeQuery(); pw.write("<center><br><table>"); pw.write("<tr BGCOLOR=#FFCC33>"); pw.write("<td><font face=\"Tahoma\"><b>VALUES</font></td>"); pw.write("</tr>"); while (set.next()) { pw.write("<tr>"); pw.write("<td><font face=\"Tahoma\">"); pw.write(set.getString("value")); pw.write("</font></td>"); pw.write("</tr>"); } pw.write("</table><br></center>"); } /** * This method demonstrates how to enlist JDBC connection into Transaction according OSGi enterprise specification. * * @param xads XADataSource * @param tm TransactionManager * @param value which will be inserted into table * @param toCommit Specify if the transaction will be committed or rolledback * @throws SQLException * @throws GenericJTAException */ private void insertIntoTransaction(XADataSource xads, TransactionManager tm, String value, boolean toCommit) throws SQLException, GenericJTAException{ XAConnection xaConnection = xads.getXAConnection(); Connection connection = xaConnection.getConnection(); XAResource xaResource = xaConnection.getXAResource(); try{ tm.begin(); Transaction transaction = tm.getTransaction(); transaction.enlistResource(xaResource); PreparedStatement insertStatement = connection.prepareStatement(INSERT_INTO_TABLE); insertStatement.setString(1, value); insertStatement.executeUpdate(); if(toCommit){ transaction.commit(); } else { transaction.rollback(); } }catch(RollbackException e){ throw new GenericJTAException(e); } catch (SecurityException e) { throw new GenericJTAException(e); } catch (IllegalStateException e) { throw new GenericJTAException(e); } catch (HeuristicMixedException e) { throw new GenericJTAException(e); } catch (HeuristicRollbackException e) { throw new GenericJTAException(e); } catch (SystemException e) { throw new GenericJTAException(e); } catch (NotSupportedException e) { throw new GenericJTAException(e); } } /** * Cleans the Table * * @param xaDataSource * @throws SQLException */ private void cleanTable(XADataSource xaDataSource) throws SQLException { XAConnection xaConnection = xaDataSource.getXAConnection(); Connection connection = xaConnection.getConnection(); PreparedStatement statement = connection.prepareStatement(CLEAN_TABLE); statement.executeUpdate(); } }
8,427
0
Create_ds/aries/sandbox/samples/transaction-sample/osgi-jdbc-api/src/main/java/org/osgi/service
Create_ds/aries/sandbox/samples/transaction-sample/osgi-jdbc-api/src/main/java/org/osgi/service/jdbc/DataSourceFactory.java
/* * Copyright (c) OSGi Alliance (2008). 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.osgi.service.jdbc; import java.sql.Driver; import java.sql.SQLException; import java.util.Properties; import javax.sql.ConnectionPoolDataSource; import javax.sql.DataSource; import javax.sql.XADataSource; /** * DataSource providers should implement this interface and register it as an * OSGi service with the JDBC driver class name in the "jdbc.driver" property. */ public interface DataSourceFactory { /** * Common property keys that DataSource clients should supply values for. */ public static final String JDBC_URL = "url"; public static final String JDBC_USER = "user"; public static final String JDBC_PASSWORD = "password"; public static final String JDBC_DATABASE_NAME = "databaseName"; public static final String JDBC_DATASOURCE_NAME = "dataSourceName"; public static final String JDBC_DESCRIPTION = "description"; public static final String JDBC_NETWORK_PROTOCOL = "networkProtocol"; public static final String JDBC_PORT_NUMBER = "portNumber"; public static final String JDBC_ROLE_NAME = "roleName"; public static final String JDBC_SERVER_NAME = "serverName"; /** * XA specific. Additional property keys that ConnectionPoolDataSource and * XADataSource clients should supply values for */ public static final String JDBC_INITIAL_POOL_SIZE = "initialPoolSize"; public static final String JDBC_MAX_IDLE_TIME = "maxIdleTime"; public static final String JDBC_MAX_POOL_SIZE = "maxPoolSize"; public static final String JDBC_MAX_STATEMENTS = "maxStatements"; public static final String JDBC_MIN_POOL_SIZE = "minPoolSize"; public static final String JDBC_PROPERTY_CYCLE = "propertyCycle"; /** * Vendor-specific properties meant to further describe the driver. Clients * may filter or test this property to determine if the driver is suitable, * or the desired one. */ public static final String JDBC_DRIVER_CLASS = "osgi.jdbc.driver.class"; public static final String JDBC_DRIVER_NAME = "osgi.jdbc.driver.name"; public static final String JDBC_DRIVER_VERSION = "osgi.jdbc.driver.version"; /** * Create a new {@link DataSource} using the given properties. * * @param props properties used to configure the DataSource * @return configured DataSource */ public DataSource createDataSource( Properties props ) throws SQLException; public XADataSource createXADataSource( Properties props ) throws SQLException; public ConnectionPoolDataSource createConnectionPoolDataSource( Properties props ) throws SQLException; public Driver getDriver( Properties props ) throws SQLException; }
8,428
0
Create_ds/aries/sandbox/samples/transaction-sample/osgi-jdbc-derby/src/main/java/org/apache/aries/samples/osgijdbc
Create_ds/aries/sandbox/samples/transaction-sample/osgi-jdbc-derby/src/main/java/org/apache/aries/samples/osgijdbc/derby/DerbyActivator.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.samples.osgijdbc.derby; import java.sql.Driver; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Properties; import javax.sql.ConnectionPoolDataSource; import javax.sql.DataSource; import javax.sql.XADataSource; import org.apache.derby.jdbc.EmbeddedConnectionPoolDataSource; import org.apache.derby.jdbc.EmbeddedDataSource; import org.apache.derby.jdbc.EmbeddedDriver; import org.apache.derby.jdbc.EmbeddedXADataSource; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; import org.osgi.service.jdbc.DataSourceFactory; public class DerbyActivator implements DataSourceFactory, BundleActivator { public ConnectionPoolDataSource createConnectionPoolDataSource( Properties props) { EmbeddedConnectionPoolDataSource embeddedCPDataSource = new EmbeddedConnectionPoolDataSource(); embeddedCPDataSource.setDataSourceName(props.getProperty(JDBC_DATASOURCE_NAME)); embeddedCPDataSource.setDatabaseName(props.getProperty(JDBC_DATABASE_NAME)); embeddedCPDataSource.setUser(props.getProperty(JDBC_USER)); embeddedCPDataSource.setPassword(props.getProperty(JDBC_PASSWORD)); return embeddedCPDataSource; } public DataSource createDataSource(Properties props) { EmbeddedDataSource embeddedDataSource = new EmbeddedDataSource(); embeddedDataSource.setDataSourceName(props.getProperty(JDBC_DATASOURCE_NAME)); embeddedDataSource.setDatabaseName(props.getProperty(JDBC_DATABASE_NAME)); embeddedDataSource.setUser(props.getProperty(JDBC_USER)); embeddedDataSource.setPassword(props.getProperty(JDBC_PASSWORD)); return embeddedDataSource; } public XADataSource createXADataSource(Properties props) { EmbeddedXADataSource embeddedXADataSource = new EmbeddedXADataSource(); embeddedXADataSource.setDataSourceName(props.getProperty(JDBC_DATASOURCE_NAME)); embeddedXADataSource.setDatabaseName(props.getProperty(JDBC_DATABASE_NAME)); embeddedXADataSource.setUser(props.getProperty(JDBC_USER)); embeddedXADataSource.setPassword(props.getProperty(JDBC_PASSWORD)); return embeddedXADataSource; } public Driver getDriver(Properties props) { EmbeddedDriver embeddedDriver = new EmbeddedDriver(); return embeddedDriver; } public void start(BundleContext context) throws Exception { new EmbeddedDriver(); context.registerService(DataSourceFactory.class.getName(), this, new Properties()); } public void stop(BundleContext context) throws Exception { try { DriverManager.getConnection("jdbc:derby:;shutdown=true"); } catch (SQLException sqlexception) { } } }
8,429
0
Create_ds/aries/sandbox/samples/words-sample/words-web/src/org/apache/words
Create_ds/aries/sandbox/samples/words-sample/words-web/src/org/apache/words/web/AssociateWord.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.words.web; import java.io.IOException; import java.io.PrintWriter; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.words.AssociationRecorderService; import org.apache.words.WordGetterService; /** * Servlet implementation class AssociateWord */ public class AssociateWord extends HttpServlet { private static final long serialVersionUID = 1L; /** * Default constructor. */ public AssociateWord() { } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse * response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); out.println("<html>"); String randomWord = null; WordGetterService getter = null; try { getter = (WordGetterService) new InitialContext() .lookup("aries:services/" + WordGetterService.class.getName()); } catch (NamingException e) { e.printStackTrace(); } if (getter != null) { randomWord = getter.getRandomWord(); out.println("The word is " + randomWord); } else { out.println("Oh dear. We couldn't find our service."); } out.println("</br>"); out.println("<form action=\"AssociateWord\" method=\"post\">"); out.println("What do you associate with " + randomWord + "? <input type=\"text\" name=\"association\" /> <br /> "); out.println("<input type=\"hidden\" name=\"word\" value=\"" + randomWord + "\"/>"); out.println("<input type=\"submit\" name=\"Submit\"/>"); out.println("</form>"); out.println("</html>"); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String word = request.getParameter("word"); String association = request.getParameter("association"); AssociationRecorderService recorder = null; try { recorder = (AssociationRecorderService) new InitialContext() .lookup("aries:services/" + AssociationRecorderService.class.getName()); } catch (NamingException e) { e.printStackTrace(); } String previousAssociation = null; if (recorder != null) { previousAssociation = recorder.getLastAssociation(word); recorder.recordAssociation(word, association); } PrintWriter out = response.getWriter(); out.println("The last person associated " + word + " with " + previousAssociation + "."); } }
8,430
0
Create_ds/aries/sandbox/samples/words-sample/words-jpa/src/org/apache/words
Create_ds/aries/sandbox/samples/words-sample/words-jpa/src/org/apache/words/jpa/Association.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.words.jpa; import javax.persistence.Entity; import javax.persistence.Id; @Entity(name = "ASSOCIATION") public class Association { @Id private String word; private String associated; public String getWord() { return word; } public void setWord(String word) { this.word = word; } public String getAssociated() { return associated; } public void setAssociated(String associated) { this.associated = associated; } }
8,431
0
Create_ds/aries/sandbox/samples/words-sample/words-jpa/src/org/apache/words
Create_ds/aries/sandbox/samples/words-sample/words-jpa/src/org/apache/words/jpa/Recorder.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.words.jpa; import javax.persistence.EntityManager; import org.apache.words.AssociationRecorderService; /** * * A JPA-backed implementation of the association recorder service. * */ public class Recorder implements AssociationRecorderService { private EntityManager em; @Override public void recordAssociation(String word, String association) { Association found = em.find(Association.class, word); if (found != null) { found.setAssociated(association); } else { Association a = new Association(); a.setWord(word); a.setAssociated(association); em.persist(a); } } @Override public String getLastAssociation(String word) { Association found = em.find(Association.class, word); if (found != null) { return found.getAssociated(); } else { return "nothing"; } } public void setEntityManager(EntityManager e) { em = e; } }
8,432
0
Create_ds/aries/sandbox/samples/words-sample/words-jpa/src/org/apache/words
Create_ds/aries/sandbox/samples/words-sample/words-jpa/src/org/apache/words/jpa/WordLister.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.words.jpa; import java.util.Random; import org.apache.words.WordGetterService; /** * * A class which provides a random word. This implementation is deliberately * simple and cycles through only three words so that the same words are likely * to crop up more than once in testing. * */ public class WordLister implements WordGetterService { /** A list of three words we'll cycle through at random. */ String[] words = { "computers", "Java", "coffee" }; public WordLister() { } @Override public String getRandomWord() { return words[new Random().nextInt(3)]; } }
8,433
0
Create_ds/aries/sandbox/samples/words-sample/words-api/src/org/apache
Create_ds/aries/sandbox/samples/words-sample/words-api/src/org/apache/words/WordGetterService.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.words; /** * * A service which provides a random dictionary word. * */ public interface WordGetterService { public String getRandomWord(); }
8,434
0
Create_ds/aries/sandbox/samples/words-sample/words-api/src/org/apache
Create_ds/aries/sandbox/samples/words-sample/words-api/src/org/apache/words/AssociationRecorderService.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.words; /** * * A service which records an association between two words. It can also look up * the most recently persisted association. * */ public interface AssociationRecorderService { public void recordAssociation(String word, String association); public String getLastAssociation(String word); }
8,435
0
Create_ds/aries/tutorials/blueprint/tutorial-modules/greeter-client-blueprint/src/main/java/org/apache/aries/tutorials/blueprint/greeter
Create_ds/aries/tutorials/blueprint/tutorial-modules/greeter-client-blueprint/src/main/java/org/apache/aries/tutorials/blueprint/greeter/client/GreeterBlueprintClient.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.tutorials.blueprint.greeter.client; import org.apache.aries.tutorials.blueprint.greeter.api.GreeterMessageService; public class GreeterBlueprintClient { GreeterMessageService greeterMessageService; String clientID; public GreeterBlueprintClient(String clientID){ this.clientID = clientID; } public void setGreeterMessageService(GreeterMessageService gms){ this.greeterMessageService = gms; } public void doRequests(){ System.out.println("Invoking injected service..."); printResult(greeterMessageService.getGreetingMessage()); } private void printResult(String response){ System.out.println("**********************************"); System.out.println("*"+clientID); System.out.println("*"+response); System.out.println("**********************************"); } }
8,436
0
Create_ds/aries/tutorials/blueprint/tutorial-modules/greeter-server-osgi/src/main/java/org/apache/aries/tutorials/blueprint/greeter/server
Create_ds/aries/tutorials/blueprint/tutorial-modules/greeter-server-osgi/src/main/java/org/apache/aries/tutorials/blueprint/greeter/server/osgi/ServiceRegisteringActivator.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.tutorials.blueprint.greeter.server.osgi; import java.util.Properties; import org.apache.aries.tutorials.blueprint.greeter.api.GreeterMessageService; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceRegistration; public class ServiceRegisteringActivator implements BundleActivator { private ServiceRegistration greeterServiceRegistration=null; public void start(BundleContext context) throws Exception { //create the class providing service, and initialise it GreeterMessageServiceImpl helloService = new GreeterMessageServiceImpl(); helloService.setSender("OSGI via BundleActivator"); //register the service greeterServiceRegistration = context.registerService(GreeterMessageService.class.getName(), helloService, new Properties()); } public void stop(BundleContext context) throws Exception { //unregister the service if(greeterServiceRegistration!=null) greeterServiceRegistration.unregister(); } }
8,437
0
Create_ds/aries/tutorials/blueprint/tutorial-modules/greeter-server-osgi/src/main/java/org/apache/aries/tutorials/blueprint/greeter/server
Create_ds/aries/tutorials/blueprint/tutorial-modules/greeter-server-osgi/src/main/java/org/apache/aries/tutorials/blueprint/greeter/server/osgi/GreeterMessageServiceImpl.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.tutorials.blueprint.greeter.server.osgi; import org.apache.aries.tutorials.blueprint.greeter.api.GreeterMessageService; public class GreeterMessageServiceImpl implements GreeterMessageService{ private String sender="<unset>"; public String getGreetingMessage() { return "Hello World! from : "+sender; } public void setSender(String sender){ this.sender=sender; if(this.sender==null) this.sender=""; } }
8,438
0
Create_ds/aries/tutorials/blueprint/tutorial-modules/greeter-api/src/main/java/org/apache/aries/tutorials/blueprint/greeter
Create_ds/aries/tutorials/blueprint/tutorial-modules/greeter-api/src/main/java/org/apache/aries/tutorials/blueprint/greeter/api/GreeterMessageService.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.tutorials.blueprint.greeter.api; public interface GreeterMessageService { public String getGreetingMessage(); }
8,439
0
Create_ds/aries/tutorials/blueprint/tutorial-modules/greeter-client-osgi/src/main/java/org/apache/aries/tutorials/blueprint/greeter/client
Create_ds/aries/tutorials/blueprint/tutorial-modules/greeter-client-osgi/src/main/java/org/apache/aries/tutorials/blueprint/greeter/client/osgi/ClientBundleActivator.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.tutorials.blueprint.greeter.client.osgi; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; public class ClientBundleActivator implements BundleActivator { public void start(BundleContext context) throws Exception { //We use the 'start' notification to kick off our client. GreeterTestClient hwc = new GreeterTestClient(context, "OSGI-Client"); hwc.doRequests(); } public void stop(BundleContext context) throws Exception { } }
8,440
0
Create_ds/aries/tutorials/blueprint/tutorial-modules/greeter-client-osgi/src/main/java/org/apache/aries/tutorials/blueprint/greeter/client
Create_ds/aries/tutorials/blueprint/tutorial-modules/greeter-client-osgi/src/main/java/org/apache/aries/tutorials/blueprint/greeter/client/osgi/GreeterTestClient.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.tutorials.blueprint.greeter.client.osgi; import org.apache.aries.tutorials.blueprint.greeter.api.GreeterMessageService; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceReference; import org.osgi.util.tracker.ServiceTracker; /** * Example of various approaches to using an osgi service. */ public class GreeterTestClient { String clientID = "<unset>"; ServiceTracker tracker = null; GreeterMessageService cachedService = null; BundleContext owningContext; GreeterMessageService proxy = null; /** * A simple class to hide if a service is available to invoke. */ class GreeterMessageServiceProxy implements GreeterMessageService{ ServiceTracker greetingServiceTracker = null; public GreeterMessageServiceProxy(BundleContext ctx){ greetingServiceTracker = new ServiceTracker(ctx, GreeterMessageService.class.getName(), null); greetingServiceTracker.open(); } public String getGreetingMessage(){ if(greetingServiceTracker.getTrackingCount()>0){ return ((GreeterMessageService)greetingServiceTracker.getService()).getGreetingMessage(); }else{ return "<No Service Available>"; } } } public GreeterTestClient(BundleContext ctx, String clientID){ this.clientID = clientID; owningContext = ctx; //setup for proxied service usage. proxy = new GreeterMessageServiceProxy(ctx); //setup for tracker usage. tracker = new ServiceTracker(ctx, GreeterMessageService.class.getName(), null); tracker.open(); //setup for super optimistic osgi service usage ;-) try{ cachedService = (GreeterMessageService)ctx.getService(ctx.getServiceReference(GreeterMessageService.class.getName())); }catch(RuntimeException e){ System.err.println("Unable to cache service at bundle start!"); } } public void doRequests(){ System.out.println("Proxy based..."); doRequestUsingProxy(); System.out.println("Tracker based..."); doRequestUsingTracker(); System.out.println("Immediate Lookup... "); doRequestUsingImmediateLookup(owningContext); System.out.println("Extremely hopeful..."); doRequestUsingCachedService(); } private void doRequestUsingImmediateLookup(BundleContext ctx){ ServiceReference ref = ctx.getServiceReference(GreeterMessageService.class.getName()); if(ref!=null){ GreeterMessageService greetingService = (GreeterMessageService)ctx.getService(ref); if(greetingService!=null){ String response = greetingService.getGreetingMessage(); printResult(response); }else{ System.err.println("Immediate lookup gave null for getService"); } ctx.ungetService(ref); // dont forget this!! }else{ System.err.println("Immediate lookup gave null service reference"); } } private void doRequestUsingTracker(){ System.out.println("Tracker is tracking.. "+tracker.getTrackingCount()+" services"); GreeterMessageService greetingService = (GreeterMessageService)tracker.getService(); if(greetingService!=null){ String response = greetingService.getGreetingMessage(); printResult(response); }else{ System.err.println("Tracker gave null for service.."); } } private void doRequestUsingCachedService(){ try{ printResult(cachedService.getGreetingMessage()); }catch(RuntimeException e){ System.err.println("Unable to use cached service. "+e); } } private void doRequestUsingProxy(){ try{ printResult(proxy.getGreetingMessage()); }catch(RuntimeException e){ System.err.println("Unable to use proxied service. "+e); } } private void printResult(String response){ System.out.println("**********************************"); System.out.println("*"+clientID); System.out.println("*"+response); System.out.println("**********************************"); } }
8,441
0
Create_ds/aries/tutorials/blueprint/tutorial-modules/greeter-server-blueprint/src/main/java/org/apache/aries/tutorials/blueprint/greeter/server
Create_ds/aries/tutorials/blueprint/tutorial-modules/greeter-server-blueprint/src/main/java/org/apache/aries/tutorials/blueprint/greeter/server/blueprint/GreeterMessageServiceImpl.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.tutorials.blueprint.greeter.server.blueprint; import org.apache.aries.tutorials.blueprint.greeter.api.GreeterMessageService; public class GreeterMessageServiceImpl implements GreeterMessageService{ private String sender="<unset>"; public String getGreetingMessage() { return "Hello World! from : "+sender; } public void setSender(String sender){ this.sender=sender; if(this.sender==null) this.sender=""; } }
8,442
0
Create_ds/aries/subsystem/subsystem-executor/src/main/java/org/apache/aries/subsystem
Create_ds/aries/subsystem/subsystem-executor/src/main/java/org/apache/aries/subsystem/executor/Activator.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.executor; import java.util.concurrent.Executor; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceRegistration; public class Activator implements BundleActivator { private ServiceRegistration executorSR; public void start(BundleContext context) throws Exception { Executor executor = new SimpleExecutor(); executorSR = context.registerService(java.util.concurrent.Executor.class.getName(), executor, null); } public void stop(BundleContext context) throws Exception { executorSR.unregister(); } }
8,443
0
Create_ds/aries/subsystem/subsystem-executor/src/main/java/org/apache/aries/subsystem
Create_ds/aries/subsystem/subsystem-executor/src/main/java/org/apache/aries/subsystem/executor/SimpleExecutor.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.executor; import java.util.concurrent.Executor; /** * A simple <code>Executor</code> that just runs each job submitted on a * new thread. This executor is intended to be registered as a services for * use by the SubsystemAdmin. It can be replaced by a different executor with * different policies (e.g. maybe using a host runtime's thread pool). * */ public class SimpleExecutor implements Executor { /** * Runs any submitted job on a new thread. * * @param command * The <code>Runnable</code> to be executed on a new thread. */ public void execute(Runnable command) { new Thread(command).start(); } }
8,444
0
Create_ds/aries/subsystem/subsystem-install/src/main/java/org/apache/aries/subsystem/install
Create_ds/aries/subsystem/subsystem-install/src/main/java/org/apache/aries/subsystem/install/internal/SubsystemInstaller.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.install.internal; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.util.jar.Attributes; import java.util.jar.JarFile; import java.util.jar.Manifest; import org.apache.aries.subsystem.Subsystem; import org.apache.aries.subsystem.SubsystemConstants; import org.apache.felix.fileinstall.ArtifactInstaller; public class SubsystemInstaller implements ArtifactInstaller { private Subsystem root; public Subsystem getRootSubsystem() { return root; } public void setRootSubsystem(Subsystem subsystem) { this.root = subsystem; } public void install(File file) throws Exception { root.install(getLocation(file)); } public void update(File file) throws Exception { String location = getLocation(file); getSubsystem(location).update(); } public void uninstall(File file) throws Exception { getSubsystem(getLocation(file)).uninstall(); } protected Subsystem getSubsystem(String location) { for (Subsystem s : root.getChildren()) { if (s.getLocation().equals(location)) { return s; } } return null; } protected String getLocation(File file) throws MalformedURLException { if (file.isDirectory()) { return "jardir:" + file.getPath(); } else { return file.toURI().toURL().toExternalForm(); } } public boolean canHandle(File artifact) { JarFile jar = null; try { // Handle OSGi bundles with the default deployer String name = artifact.getName(); if (!artifact.canRead() || name.endsWith(".txt") || name.endsWith(".xml") || name.endsWith(".properties") || name.endsWith(".cfg")) { // that's file type which is not supported as bundle and avoid // exception in the log return false; } jar = new JarFile(artifact); Manifest m = jar.getManifest(); if (m.getMainAttributes().getValue(new Attributes.Name(SubsystemConstants.SUBSYSTEM_MANIFESTVERSION)) != null && m.getMainAttributes().getValue(new Attributes.Name(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME)) != null && m.getMainAttributes().getValue(new Attributes.Name(SubsystemConstants.SUBSYSTEM_VERSION)) != null) { return true; } } catch (Exception e) { // Ignore } finally { if (jar != null) { try { jar.close(); } catch (IOException e) { // Ignore } } } return false; } }
8,445
0
Create_ds/aries/subsystem/subsystem-example/subsystem-helloIsolationRef/src/main/java/org/apache/aries/subsystem/example
Create_ds/aries/subsystem/subsystem-example/subsystem-helloIsolationRef/src/main/java/org/apache/aries/subsystem/example/helloIsolationRef/HelloIsolationRef.java
package org.apache.aries.subsystem.example.helloIsolationRef; import org.apache.aries.subsystem.example.helloIsolation.HelloIsolation; public interface HelloIsolationRef { public void helloRef(); public HelloIsolation getHelloIsolationService(); }
8,446
0
Create_ds/aries/subsystem/subsystem-example/subsystem-helloIsolationRef/src/main/java/org/apache/aries/subsystem/example
Create_ds/aries/subsystem/subsystem-example/subsystem-helloIsolationRef/src/main/java/org/apache/aries/subsystem/example/helloIsolationRef/Activator.java
package org.apache.aries.subsystem.example.helloIsolationRef; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceReference; import org.apache.aries.subsystem.example.helloIsolation.HelloIsolation; public class Activator implements BundleActivator { /* * (non-Javadoc) * @see org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext) */ public void start(BundleContext context) throws Exception { System.out.println("bundle helloIsolationRef start"); // check to see if we can see helloIsolation service from service registry ServiceReference sr = context.getServiceReference(HelloIsolation.class.getName()); if (sr != null) { System.out.println("Able to obtain service reference from bundle " + sr.getBundle().getSymbolicName() + "_" + sr.getBundle().getVersion().toString()); HelloIsolation hi = (HelloIsolation) context.getService(sr); hi.hello(); } } /* * (non-Javadoc) * @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext) */ public void stop(BundleContext context) throws Exception { System.out.println("bundle helloIsolationRef stop"); } }
8,447
0
Create_ds/aries/subsystem/subsystem-example/subsystem-helloIsolationRef/src/main/java/org/apache/aries/subsystem/example
Create_ds/aries/subsystem/subsystem-example/subsystem-helloIsolationRef/src/main/java/org/apache/aries/subsystem/example/helloIsolationRef/HelloIsolationRefImpl.java
package org.apache.aries.subsystem.example.helloIsolationRef; import org.apache.aries.subsystem.example.helloIsolation.HelloIsolation; public class HelloIsolationRefImpl implements HelloIsolationRef { HelloIsolation helloIsolation = null; public HelloIsolation getHelloIsolationService() { return this.helloIsolation; } public void helloRef() { System.out.println("helloRef from HelloIsolationImpl"); this.helloIsolation.hello(); } public void setHelloIsolationService(HelloIsolation hi) { this.helloIsolation = hi; } }
8,448
0
Create_ds/aries/subsystem/subsystem-example/subsystem-helloIsolation/src/main/java/org/apache/aries/subsystem/example
Create_ds/aries/subsystem/subsystem-example/subsystem-helloIsolation/src/main/java/org/apache/aries/subsystem/example/helloIsolation/HelloIsolation.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.example.helloIsolation; import java.security.Permission; public interface HelloIsolation { public void hello(); public void checkPermission(final Permission permission) throws SecurityException; }
8,449
0
Create_ds/aries/subsystem/subsystem-example/subsystem-helloIsolation/src/main/java/org/apache/aries/subsystem/example
Create_ds/aries/subsystem/subsystem-example/subsystem-helloIsolation/src/main/java/org/apache/aries/subsystem/example/helloIsolation/Activator.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.example.helloIsolation; import org.osgi.framework.Bundle; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; import org.osgi.framework.BundleEvent; import org.osgi.framework.ServiceRegistration; import org.osgi.util.tracker.BundleTracker; import org.osgi.util.tracker.BundleTrackerCustomizer; public class Activator implements BundleActivator { private ServiceRegistration sr; private BundleTracker bt; int addEventCount = 0; int removeEventCount = 0; int modifyEventCount = 0; /* * (non-Javadoc) * * @see * org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext * ) */ public void start(BundleContext context) throws Exception { System.out.println("bundle helloIsolation start"); SecurityManager security = System.getSecurityManager(); if (security != null) { System.out.println("HelloIsolationImpl: system manager is not null"); } else { System.out.println("HelloIsolationImpl: system manager is still null"); } sr = context.registerService(HelloIsolation.class.getName(), new HelloIsolationImpl(), null); bt = new BundleTracker(context, Bundle.INSTALLED | Bundle.UNINSTALLED | Bundle.ACTIVE, new BundleTrackerCustomizer() { public synchronized Object addingBundle(Bundle bundle, BundleEvent event) { if (event == null) { System.out.println("HelloIsolation " + bundle.getSymbolicName() + "_" + bundle.getVersion().toString() + " - adding Bundle: " + bundle.getSymbolicName() + " event: null"); } else { System.out.println("HelloIsolation " + bundle.getSymbolicName() + "_" + bundle.getVersion().toString() + " - adding Bundle: " + bundle.getSymbolicName() + " event: " + event.getType()); } addEventCount++; return bundle; } public synchronized void modifiedBundle(Bundle bundle, BundleEvent event, Object object) { if (event == null) { System.out.println("HelloIsolation " + bundle.getSymbolicName() + "_" + bundle.getVersion().toString() + " - modifying Bundle: " + bundle.getSymbolicName() + " event: null"); } else { System.out.println("HelloIsolation " + bundle.getSymbolicName() + "_" + bundle.getVersion().toString() + " - modifying Bundle: " + bundle.getSymbolicName() + " event: " + event.getType()); } modifyEventCount++; } public synchronized void removedBundle(Bundle bundle, BundleEvent event, Object object) { if (event == null) { System.out.println("HelloIsolation " + bundle.getSymbolicName() + "_" + bundle.getVersion().toString() + " - removing Bundle: " + bundle.getSymbolicName() + " event: null"); } else { System.out.println("HelloIsolation " + bundle.getSymbolicName() + "_" + bundle.getVersion().toString() + " - removing Bundle: " + bundle.getSymbolicName() + " event: " + event.getType()); } removeEventCount++; } }); bt.open(); } public int getAddEventCount() { return addEventCount; } /* * (non-Javadoc) * * @see * org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext) */ public void stop(BundleContext context) throws Exception { System.out.println("bundle helloIsolation stop"); if (sr != null) { sr.unregister(); } if (bt != null) { bt.close(); } } }
8,450
0
Create_ds/aries/subsystem/subsystem-example/subsystem-helloIsolation/src/main/java/org/apache/aries/subsystem/example
Create_ds/aries/subsystem/subsystem-example/subsystem-helloIsolation/src/main/java/org/apache/aries/subsystem/example/helloIsolation/HelloIsolationImpl.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.example.helloIsolation; import java.security.AccessController; import java.security.Permission; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; public class HelloIsolationImpl implements HelloIsolation { public void hello() { System.out.println("hello from HelloIsolationImpl"); } // test java2 security public void checkPermission(final Permission permission) throws SecurityException { System.out.println("HelloIsolationImpl: enter checkpermission"); try { AccessController.doPrivileged(new PrivilegedExceptionAction() { public Object run() throws SecurityException { SecurityManager security = System.getSecurityManager(); if (security != null) { System.out.println("HelloIsolationImpl: system manager is not null"); security.checkPermission(permission); return null; } System.out.println("HelloIsolationImpl: system manager is still null"); return null; } }); } catch (PrivilegedActionException e) { throw (SecurityException) e.getException(); } } }
8,451
0
Create_ds/aries/subsystem/subsystem-obr/src/test/java/org/apache/aries/subsystem/obr
Create_ds/aries/subsystem/subsystem-obr/src/test/java/org/apache/aries/subsystem/obr/internal/OsgiRequirementAdapterTest.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.obr.internal; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.util.HashMap; import java.util.Map; import org.apache.aries.subsystem.util.felix.OsgiRequirementAdapter; import org.apache.felix.bundlerepository.Capability; import org.easymock.EasyMock; import org.junit.Test; import org.osgi.framework.namespace.BundleNamespace; import org.osgi.framework.namespace.PackageNamespace; import org.osgi.namespace.service.ServiceNamespace; import org.osgi.resource.Namespace; import org.osgi.resource.Requirement; public class OsgiRequirementAdapterTest { @Test public void testGetNameBundle() { Requirement req = EasyMock.createNiceMock(Requirement.class); EasyMock.expect(req.getNamespace()).andReturn(BundleNamespace.BUNDLE_NAMESPACE); EasyMock.replay(req); OsgiRequirementAdapter adapter = new OsgiRequirementAdapter(req); assertEquals("Wrong name", Capability.BUNDLE, adapter.getName()); } @Test public void testGetNamePackage() { Requirement req = EasyMock.createNiceMock(Requirement.class); EasyMock.expect(req.getNamespace()).andReturn(PackageNamespace.PACKAGE_NAMESPACE); EasyMock.replay(req); OsgiRequirementAdapter adapter = new OsgiRequirementAdapter(req); assertEquals("Wrong name", Capability.PACKAGE, adapter.getName()); } @Test public void testGetNameService() { Requirement req = EasyMock.createNiceMock(Requirement.class); EasyMock.expect(req.getNamespace()).andReturn(ServiceNamespace.SERVICE_NAMESPACE); EasyMock.replay(req); OsgiRequirementAdapter adapter = new OsgiRequirementAdapter(req); assertEquals("Wrong name", Capability.SERVICE, adapter.getName()); } @Test public void testIsMultipleFalse() { Requirement req = EasyMock.createNiceMock(Requirement.class); Map<String, String> directives = new HashMap<String, String>(); directives.put(Namespace.REQUIREMENT_CARDINALITY_DIRECTIVE, Namespace.CARDINALITY_SINGLE); EasyMock.expect(req.getDirectives()).andReturn(directives); EasyMock.replay(req); OsgiRequirementAdapter adapter = new OsgiRequirementAdapter(req); assertFalse("Requirement was multiple", adapter.isMultiple()); } @Test public void testIsMultipleTrue() { Requirement req = EasyMock.createNiceMock(Requirement.class); Map<String, String> directives = new HashMap<String, String>(); directives.put(Namespace.REQUIREMENT_CARDINALITY_DIRECTIVE, Namespace.CARDINALITY_MULTIPLE); EasyMock.expect(req.getDirectives()).andReturn(directives); EasyMock.replay(req); OsgiRequirementAdapter adapter = new OsgiRequirementAdapter(req); assertTrue("Requirement was not multiple", adapter.isMultiple()); } }
8,452
0
Create_ds/aries/subsystem/subsystem-obr/src/test/java/org/apache/aries/subsystem/obr
Create_ds/aries/subsystem/subsystem-obr/src/test/java/org/apache/aries/subsystem/obr/internal/FelixCapabilityAdapterTest.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.obr.internal; import static org.junit.Assert.assertEquals; import java.util.HashMap; import java.util.Map; import org.apache.aries.subsystem.util.felix.FelixCapabilityAdapter; import org.apache.felix.bundlerepository.Capability; import org.apache.felix.bundlerepository.Resource; import org.easymock.EasyMock; import org.junit.Test; import org.osgi.framework.namespace.BundleNamespace; import org.osgi.framework.namespace.PackageNamespace; import org.osgi.namespace.service.ServiceNamespace; public class FelixCapabilityAdapterTest { @Test public void testObjectClassAttribute() { String objectClass = "com.foo.Bar"; Capability cap = EasyMock.createNiceMock(Capability.class); EasyMock.expect(cap.getName()).andReturn(Capability.SERVICE); Map<String, Object> props = new HashMap<String, Object>(); props.put(ServiceNamespace.CAPABILITY_OBJECTCLASS_ATTRIBUTE.toLowerCase(), objectClass); EasyMock.expect(cap.getPropertiesAsMap()).andReturn(props); EasyMock.replay(cap); FelixCapabilityAdapter adapter = new FelixCapabilityAdapter(cap, EasyMock.createNiceMock(org.osgi.resource.Resource.class)); assertEquals("Wrong value for attribute " + ServiceNamespace.CAPABILITY_OBJECTCLASS_ATTRIBUTE, objectClass, adapter.getAttributes().get(ServiceNamespace.CAPABILITY_OBJECTCLASS_ATTRIBUTE)); } @Test public void testOsgiServiceNamespace() { Capability cap = EasyMock.createNiceMock(Capability.class); EasyMock.expect(cap.getName()).andReturn(Capability.SERVICE); EasyMock.replay(cap); FelixCapabilityAdapter adapter = new FelixCapabilityAdapter(cap, EasyMock.createNiceMock(org.osgi.resource.Resource.class)); assertEquals("Wrong namespace", ServiceNamespace.SERVICE_NAMESPACE, adapter.getNamespace()); } @Test public void testOsgiWiringPackageAttribute() { String pkg = "com.foo.Bar"; Capability cap = EasyMock.createNiceMock(Capability.class); EasyMock.expect(cap.getName()).andReturn(Capability.PACKAGE).anyTimes(); Map<String, Object> props = new HashMap<String, Object>(); props.put(Capability.PACKAGE, pkg); EasyMock.expect(cap.getPropertiesAsMap()).andReturn(props); EasyMock.replay(cap); FelixCapabilityAdapter adapter = new FelixCapabilityAdapter(cap, EasyMock.createNiceMock(org.osgi.resource.Resource.class)); assertEquals("Wrong value for attribute " + PackageNamespace.PACKAGE_NAMESPACE, pkg, adapter.getAttributes().get(PackageNamespace.PACKAGE_NAMESPACE)); } @Test public void testOsgiWiringPackageNamespace() { Capability cap = EasyMock.createNiceMock(Capability.class); EasyMock.expect(cap.getName()).andReturn(Capability.PACKAGE); EasyMock.replay(cap); FelixCapabilityAdapter adapter = new FelixCapabilityAdapter(cap, EasyMock.createNiceMock(org.osgi.resource.Resource.class)); assertEquals("Wrong namespace", PackageNamespace.PACKAGE_NAMESPACE, adapter.getNamespace()); } @Test public void testOsgiWiringBundleNamespace() { Capability cap = EasyMock.createNiceMock(Capability.class); EasyMock.expect(cap.getName()).andReturn(Capability.BUNDLE); EasyMock.replay(cap); FelixCapabilityAdapter adapter = new FelixCapabilityAdapter(cap, EasyMock.createNiceMock(org.osgi.resource.Resource.class)); assertEquals("Wrong namespace", BundleNamespace.BUNDLE_NAMESPACE, adapter.getNamespace()); } @Test public void testOsgiWiringBundleAttribute() { String symbolicName = "derbyclient"; Capability cap = EasyMock.createNiceMock(Capability.class); EasyMock.expect(cap.getName()).andReturn(Capability.BUNDLE).anyTimes(); Map<String, Object> props = new HashMap<String, Object>(); props.put(Resource.SYMBOLIC_NAME, symbolicName); EasyMock.expect(cap.getPropertiesAsMap()).andReturn(props); EasyMock.replay(cap); FelixCapabilityAdapter adapter = new FelixCapabilityAdapter(cap, EasyMock.createNiceMock(org.osgi.resource.Resource.class)); assertEquals("Wrong value for attribute " + BundleNamespace.BUNDLE_NAMESPACE, symbolicName, adapter.getAttributes().get(BundleNamespace.BUNDLE_NAMESPACE)); } }
8,453
0
Create_ds/aries/subsystem/subsystem-obr/src/test/java/org/apache/aries/subsystem/obr
Create_ds/aries/subsystem/subsystem-obr/src/test/java/org/apache/aries/subsystem/obr/internal/FelixResourceAdapterTest.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.obr.internal; import static org.junit.Assert.assertEquals; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.aries.subsystem.util.felix.FelixResourceAdapter; import org.apache.felix.bundlerepository.Capability; import org.apache.felix.bundlerepository.Resource; import org.easymock.EasyMock; import org.junit.Test; public class FelixResourceAdapterTest { @Test public void testGetCapabilitiesWithNullNamespace() { Resource resource = EasyMock.createNiceMock(Resource.class); Capability capability = EasyMock.createNiceMock(Capability.class); EasyMock.expect(capability.getName()).andReturn(Capability.PACKAGE); Map<String, Object> properties = new HashMap<String, Object>(); properties.put(Capability.PACKAGE, "org.foo.bar"); EasyMock.expect(capability.getPropertiesAsMap()).andReturn(properties); Capability[] capabilities = new Capability[] { capability }; EasyMock.expect(resource.getCapabilities()).andReturn(capabilities); EasyMock.replay(resource); FelixResourceAdapter adapter = new FelixResourceAdapter(resource); List<org.osgi.resource.Capability> caps = adapter.getCapabilities(null); // osgi.identity, osgi.content. osgi.wiring.host, and osgi.wiring.package assertEquals("Null namespace should return all capabilities", 4, caps.size()); } }
8,454
0
Create_ds/aries/subsystem/subsystem-obr/src/test/java/org/apache/aries/subsystem/obr
Create_ds/aries/subsystem/subsystem-obr/src/test/java/org/apache/aries/subsystem/obr/internal/FelixRequirementAdapterTest.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.obr.internal; import static org.junit.Assert.assertEquals; import org.apache.aries.subsystem.util.felix.FelixRequirementAdapter; import org.apache.felix.bundlerepository.Requirement; import org.easymock.EasyMock; import org.junit.Test; import org.osgi.resource.Namespace; import org.osgi.resource.Resource; public class FelixRequirementAdapterTest { @Test public void testCardinalityDirectiveMultiple() { Requirement req = EasyMock.createNiceMock(Requirement.class); EasyMock.expect(req.getFilter()).andReturn(""); EasyMock.expect(req.isMultiple()).andReturn(true); EasyMock.replay(req); FelixRequirementAdapter adapter = new FelixRequirementAdapter(req, EasyMock.createNiceMock(Resource.class)); assertEquals("Wrong value for directive " + Namespace.REQUIREMENT_CARDINALITY_DIRECTIVE, Namespace.CARDINALITY_MULTIPLE, adapter.getDirectives().get(Namespace.REQUIREMENT_CARDINALITY_DIRECTIVE)); } @Test public void testCardinalityDirectiveSingle() { Requirement req = EasyMock.createNiceMock(Requirement.class); EasyMock.expect(req.getFilter()).andReturn(""); EasyMock.expect(req.isMultiple()).andReturn(false); EasyMock.replay(req); FelixRequirementAdapter adapter = new FelixRequirementAdapter(req, EasyMock.createNiceMock(Resource.class)); assertEquals("Wrong value for directive " + Namespace.REQUIREMENT_CARDINALITY_DIRECTIVE, Namespace.CARDINALITY_SINGLE, adapter.getDirectives().get(Namespace.REQUIREMENT_CARDINALITY_DIRECTIVE)); } @Test public void testResolutionDirectiveMandatory() { Requirement req = EasyMock.createNiceMock(Requirement.class); EasyMock.expect(req.getFilter()).andReturn(""); EasyMock.expect(req.isOptional()).andReturn(false); EasyMock.replay(req); FelixRequirementAdapter adapter = new FelixRequirementAdapter(req, EasyMock.createNiceMock(Resource.class)); assertEquals("Wrong value for directive " + Namespace.REQUIREMENT_RESOLUTION_DIRECTIVE, Namespace.RESOLUTION_MANDATORY, adapter.getDirectives().get(Namespace.REQUIREMENT_RESOLUTION_DIRECTIVE)); } @Test public void testResolutionDirectiveOptional() { Requirement req = EasyMock.createNiceMock(Requirement.class); EasyMock.expect(req.getFilter()).andReturn(""); EasyMock.expect(req.isOptional()).andReturn(true); EasyMock.replay(req); FelixRequirementAdapter adapter = new FelixRequirementAdapter(req, EasyMock.createNiceMock(Resource.class)); assertEquals("Wrong value for directive " + Namespace.REQUIREMENT_RESOLUTION_DIRECTIVE, Namespace.RESOLUTION_OPTIONAL, adapter.getDirectives().get(Namespace.REQUIREMENT_RESOLUTION_DIRECTIVE)); } }
8,455
0
Create_ds/aries/subsystem/subsystem-obr/src/main/java/org/apache/aries/subsystem/util
Create_ds/aries/subsystem/subsystem-obr/src/main/java/org/apache/aries/subsystem/util/felix/OsgiWiringHostCapability.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.util.felix; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.apache.aries.subsystem.obr.internal.AbstractCapability; import org.osgi.framework.Version; import org.osgi.framework.namespace.HostNamespace; import org.osgi.resource.Resource; public class OsgiWiringHostCapability extends AbstractCapability { private final Map<String, Object> attributes = new HashMap<String, Object>(); private final Resource resource; public OsgiWiringHostCapability(Resource resource, String symbolicName, Version version) { attributes.put(HostNamespace.HOST_NAMESPACE, symbolicName); attributes.put(HostNamespace.CAPABILITY_BUNDLE_VERSION_ATTRIBUTE, version); this.resource = resource; } public Map<String, Object> getAttributes() { return Collections.unmodifiableMap(attributes); } public Map<String, String> getDirectives() { return Collections.emptyMap(); } public String getNamespace() { return HostNamespace.HOST_NAMESPACE; } public Resource getResource() { return resource; } }
8,456
0
Create_ds/aries/subsystem/subsystem-obr/src/main/java/org/apache/aries/subsystem/util
Create_ds/aries/subsystem/subsystem-obr/src/main/java/org/apache/aries/subsystem/util/felix/OsgiIdentityCapability.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.util.felix; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.apache.aries.subsystem.obr.internal.AbstractCapability; import org.osgi.framework.Version; import org.osgi.framework.namespace.IdentityNamespace; import org.osgi.resource.Resource; public class OsgiIdentityCapability extends AbstractCapability { private final Map<String, Object> attributes = new HashMap<String, Object>(); private final Resource resource; public OsgiIdentityCapability(Resource resource, String symbolicName, Version version) { this(resource, symbolicName, version, IdentityNamespace.TYPE_BUNDLE); } public OsgiIdentityCapability(Resource resource, String symbolicName, Version version, String identityType) { this.resource = resource; attributes.put( IdentityNamespace.IDENTITY_NAMESPACE, symbolicName); attributes.put( IdentityNamespace.CAPABILITY_VERSION_ATTRIBUTE, version); attributes.put( IdentityNamespace.CAPABILITY_TYPE_ATTRIBUTE, identityType); // TODO Add directives, particularly "effective" and "singleton". } public Map<String, Object> getAttributes() { return Collections.unmodifiableMap(attributes); } public Map<String, String> getDirectives() { return Collections.emptyMap(); } public String getNamespace() { return IdentityNamespace.IDENTITY_NAMESPACE; } public Resource getResource() { return resource; } }
8,457
0
Create_ds/aries/subsystem/subsystem-obr/src/main/java/org/apache/aries/subsystem/util
Create_ds/aries/subsystem/subsystem-obr/src/main/java/org/apache/aries/subsystem/util/felix/FelixRepositoryAdapter.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.util.felix; import java.util.ArrayList; 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.regex.Matcher; import java.util.regex.Pattern; import org.apache.aries.subsystem.obr.internal.ResourceHelper; import org.osgi.framework.Constants; import org.osgi.framework.namespace.IdentityNamespace; import org.osgi.resource.Capability; import org.osgi.resource.Requirement; import org.osgi.resource.Resource; import org.osgi.service.repository.Repository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class FelixRepositoryAdapter implements Repository { private static class IdentityRequirementFilter { private static final String REGEX = "\\(osgi.identity=([^\\)]*)\\)"; private static final Pattern PATTERN = Pattern.compile(REGEX); private final String symbolicName; public IdentityRequirementFilter(String filter) { Matcher matcher = PATTERN.matcher(filter); if (!matcher.find()) throw new IllegalArgumentException("Could not find pattern '" + REGEX + "' in filter string '" + filter + "'"); symbolicName = matcher.group(1); } public String getSymbolicName() { return symbolicName; } } private static final Logger logger = LoggerFactory.getLogger(FelixRepositoryAdapter.class); private final Map<String, Collection<Capability>> identityIndex = Collections.synchronizedMap(new HashMap<String, Collection<Capability>>()); private final org.apache.felix.bundlerepository.Repository repository; private long lastUpdated; public FelixRepositoryAdapter(org.apache.felix.bundlerepository.Repository repository) { if (repository == null) throw new NullPointerException("Missing required parameter: repository"); this.repository = repository; } public Collection<Capability> findProviders(Requirement requirement) { update(); List<Capability> result = Collections.emptyList(); if (IdentityNamespace.IDENTITY_NAMESPACE.equals(requirement.getNamespace())) { String symbolicName = new IdentityRequirementFilter(requirement.getDirectives().get(Constants.FILTER_DIRECTIVE)).getSymbolicName(); logger.debug("Looking for symbolic name {}", symbolicName); Collection<Capability> capabilities = identityIndex.get(symbolicName); if (capabilities != null) { result = new ArrayList<Capability>(capabilities.size()); for (Capability capability : capabilities) { if (ResourceHelper.matches(requirement, capability)) { result.add(capability); } } ((ArrayList<Capability>)result).trimToSize(); } } else { org.apache.felix.bundlerepository.Resource[] resources = repository.getResources(); if (resources != null && resources.length != 0) { result = new ArrayList<Capability>(resources.length); for (final org.apache.felix.bundlerepository.Resource resource : resources) { Resource r = new FelixResourceAdapter(resource); for (Capability capability : r.getCapabilities(requirement.getNamespace())) if (ResourceHelper.matches(requirement, capability)) result.add(capability); } ((ArrayList<Capability>)result).trimToSize(); } } return result; } @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) result.put(requirement, findProviders(requirement)); return result; } private synchronized void update() { long lastModified = repository.getLastModified(); logger.debug("The repository adaptor was last updated at {}. The repository was last modified at {}", lastUpdated, lastModified); if (lastModified > lastUpdated) { logger.debug("Updating the adapter with the modified repository contents..."); lastUpdated = lastModified; synchronized (identityIndex) { identityIndex.clear(); org.apache.felix.bundlerepository.Resource[] resources = repository.getResources(); logger.debug("There are {} resources to evaluate", resources == null ? 0 : resources.length); if (resources != null && resources.length != 0) { for (org.apache.felix.bundlerepository.Resource resource : resources) { logger.debug("Evaluating resource {}", resource); String symbolicName = resource.getSymbolicName(); Collection<Capability> capabilities = identityIndex.get(symbolicName); if (capabilities == null) { capabilities = new HashSet<Capability>(); identityIndex.put(symbolicName, capabilities); } OsgiIdentityCapability capability = new OsgiIdentityCapability( new FelixResourceAdapter(resource), symbolicName, resource.getVersion(), // TODO Assuming all resources are bundles. Need to support // type fragment as well, but how do we know? IdentityNamespace.TYPE_BUNDLE); logger.debug("Indexing capability {}", capability); capabilities.add(capability); } } } } } }
8,458
0
Create_ds/aries/subsystem/subsystem-obr/src/main/java/org/apache/aries/subsystem/util
Create_ds/aries/subsystem/subsystem-obr/src/main/java/org/apache/aries/subsystem/util/felix/OsgiContentCapability.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.util.felix; import java.net.URL; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.apache.aries.subsystem.obr.internal.AbstractCapability; import org.osgi.resource.Resource; public class OsgiContentCapability extends AbstractCapability { private final Map<String, Object> attributes = new HashMap<String, Object>(); private final Resource resource; public OsgiContentCapability(Resource resource, String url) { // TOOD Add to constants. attributes.put("osgi.content", url); // TODO Any directives? this.resource = resource; } public OsgiContentCapability(Resource resource, URL url) { this(resource, url.toExternalForm()); } public Map<String, Object> getAttributes() { return Collections.unmodifiableMap(attributes); } public Map<String, String> getDirectives() { return Collections.emptyMap(); } public String getNamespace() { // TODO Add to constants. return "osgi.content"; } public Resource getResource() { return resource; } }
8,459
0
Create_ds/aries/subsystem/subsystem-obr/src/main/java/org/apache/aries/subsystem/util
Create_ds/aries/subsystem/subsystem-obr/src/main/java/org/apache/aries/subsystem/util/felix/OsgiCapabilityAdapter.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.util.felix; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Map; import org.apache.aries.subsystem.obr.internal.NamespaceTranslator; import org.apache.felix.bundlerepository.Capability; import org.apache.felix.bundlerepository.Property; public class OsgiCapabilityAdapter implements Capability { private final org.osgi.resource.Capability capability; public OsgiCapabilityAdapter(org.osgi.resource.Capability capability) { if (capability == null) throw new NullPointerException("Missing required parameter: capability"); this.capability = capability; } @Override public boolean equals(Object o) { return capability.equals(o); } public String getName() { return NamespaceTranslator.translate(capability.getNamespace()); } public Property[] getProperties() { Map<String, Object> attributes = capability.getAttributes(); Collection<Property> result = new ArrayList<Property>(attributes.size()); for (final Map.Entry<String, Object> entry : capability.getAttributes().entrySet()) { if (entry.getKey().equals(capability.getNamespace())) { result.add(new FelixProperty(getName(), entry.getValue())); continue; } result.add(new FelixProperty(entry)); } return result.toArray(new Property[result.size()]); } @SuppressWarnings("rawtypes") public Map getPropertiesAsMap() { Map<String, Object> result = new HashMap<String, Object>(capability.getAttributes()); result.put(getName(), result.get(capability.getNamespace())); return result; } @Override public int hashCode() { return capability.hashCode(); } }
8,460
0
Create_ds/aries/subsystem/subsystem-obr/src/main/java/org/apache/aries/subsystem/util
Create_ds/aries/subsystem/subsystem-obr/src/main/java/org/apache/aries/subsystem/util/felix/FelixCapabilityAdapter.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.util.felix; import java.util.Collections; import java.util.Map; import org.apache.aries.subsystem.obr.internal.AbstractCapability; import org.apache.aries.subsystem.obr.internal.NamespaceTranslator; import org.osgi.framework.namespace.BundleNamespace; import org.osgi.namespace.service.ServiceNamespace; import org.osgi.resource.Resource; public class FelixCapabilityAdapter extends AbstractCapability { private final org.apache.felix.bundlerepository.Capability capability; private final Resource resource; public FelixCapabilityAdapter(org.apache.felix.bundlerepository.Capability capability, Resource resource) { if (capability == null) throw new NullPointerException("Missing required parameter: capability"); this.capability = capability; this.resource = resource; } public Map<String, Object> getAttributes() { Map<String, Object> result = capability.getPropertiesAsMap(); String namespace = getNamespace(); if (ServiceNamespace.SERVICE_NAMESPACE.equals(namespace)) result.put(ServiceNamespace.CAPABILITY_OBJECTCLASS_ATTRIBUTE, result.get(ServiceNamespace.CAPABILITY_OBJECTCLASS_ATTRIBUTE.toLowerCase())); else if (BundleNamespace.BUNDLE_NAMESPACE.equals(namespace)) { result.put(BundleNamespace.BUNDLE_NAMESPACE, result.get(org.apache.felix.bundlerepository.Resource.SYMBOLIC_NAME)); result.put(BundleNamespace.CAPABILITY_BUNDLE_VERSION_ATTRIBUTE, result.get(org.apache.felix.bundlerepository.Resource.VERSION)); } else result.put(namespace, result.get(capability.getName())); return result; } public Map<String, String> getDirectives() { return Collections.emptyMap(); } public String getNamespace() { return NamespaceTranslator.translate(capability.getName()); } public Resource getResource() { return resource; } }
8,461
0
Create_ds/aries/subsystem/subsystem-obr/src/main/java/org/apache/aries/subsystem/util
Create_ds/aries/subsystem/subsystem-obr/src/main/java/org/apache/aries/subsystem/util/felix/OsgiRequirementAdapter.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.util.felix; import static org.apache.aries.application.utils.AppConstants.LOG_ENTRY; import static org.apache.aries.application.utils.AppConstants.LOG_EXIT; import org.apache.aries.subsystem.obr.internal.NamespaceTranslator; import org.apache.aries.subsystem.obr.internal.ResourceHelper; import org.apache.felix.bundlerepository.Capability; import org.apache.felix.bundlerepository.Requirement; import org.osgi.framework.Constants; import org.osgi.resource.Namespace; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class OsgiRequirementAdapter implements Requirement { private static final Logger logger = LoggerFactory.getLogger(OsgiRequirementAdapter.class); private final org.osgi.resource.Requirement requirement; public OsgiRequirementAdapter(org.osgi.resource.Requirement requirement) { if (requirement == null) throw new NullPointerException("Missing required parameter: requirement"); this.requirement = requirement; } public String getComment() { return null; } public String getFilter() { return requirement.getDirectives().get(Constants.FILTER_DIRECTIVE); } public String getName() { return NamespaceTranslator.translate(requirement.getNamespace()); } public boolean isExtend() { return false; } public boolean isMultiple() { String multiple = requirement.getDirectives().get(Namespace.REQUIREMENT_CARDINALITY_DIRECTIVE); return Namespace.CARDINALITY_MULTIPLE.equals(multiple); } public boolean isOptional() { String resolution = requirement.getDirectives().get(Constants.RESOLUTION_DIRECTIVE); return Constants.RESOLUTION_OPTIONAL.equals(resolution); } public boolean isSatisfied(Capability capability) { logger.debug(LOG_ENTRY, "isSatisfied", capability); boolean result = ResourceHelper.matches(requirement, new FelixCapabilityAdapter(capability, null)); logger.debug(LOG_EXIT, "isSatisfied", result); return result; } }
8,462
0
Create_ds/aries/subsystem/subsystem-obr/src/main/java/org/apache/aries/subsystem/util
Create_ds/aries/subsystem/subsystem-obr/src/main/java/org/apache/aries/subsystem/util/felix/FelixResourceAdapter.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.util.felix; import java.io.InputStream; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import org.apache.aries.subsystem.obr.internal.NamespaceTranslator; import org.apache.aries.subsystem.obr.internal.ResourceHelper; import org.osgi.framework.namespace.HostNamespace; import org.osgi.framework.namespace.IdentityNamespace; import org.osgi.resource.Capability; import org.osgi.resource.Requirement; import org.osgi.resource.Resource; import org.osgi.service.repository.RepositoryContent; public class FelixResourceAdapter implements Resource, RepositoryContent { private final org.apache.felix.bundlerepository.Resource resource; public FelixResourceAdapter(final org.apache.felix.bundlerepository.Resource resource) { this.resource = resource; } public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof FelixResourceAdapter)) return false; FelixResourceAdapter that = (FelixResourceAdapter)o; if (!ResourceHelper.getTypeAttribute(that).equals(ResourceHelper.getTypeAttribute(this))) return false; if (!ResourceHelper.getSymbolicNameAttribute(that).equals(ResourceHelper.getSymbolicNameAttribute(this))) return false; if (!ResourceHelper.getVersionAttribute(that).equals(ResourceHelper.getVersionAttribute(this))) return false; return true; } public int hashCode() { int result = 17; result = 31 * result + ResourceHelper.getTypeAttribute(this).hashCode(); result = 31 * result + ResourceHelper.getSymbolicNameAttribute(this).hashCode(); result = 31 * result + ResourceHelper.getVersionAttribute(this).hashCode(); return result; } public List<Capability> getCapabilities(String namespace) { ArrayList<Capability> result = new ArrayList<Capability>(); namespace = NamespaceTranslator.translate(namespace); if (namespace == null || namespace.equals(IdentityNamespace.IDENTITY_NAMESPACE)) { result.add(new OsgiIdentityCapability(this, resource.getSymbolicName(), resource.getVersion())); if (namespace != null) { result.trimToSize(); return Collections.unmodifiableList(result); } } // TODO Add to constants. if (namespace == null || namespace.equals("osgi.content")) { result.add(new OsgiContentCapability(this, resource.getURI())); if (namespace != null) { result.trimToSize(); return Collections.unmodifiableList(result); } } if (namespace == null || namespace.equals(HostNamespace.HOST_NAMESPACE)) { result.add(new OsgiWiringHostCapability(this, resource.getSymbolicName(), resource.getVersion())); if (namespace != null) { result.trimToSize(); return Collections.unmodifiableList(result); } } org.apache.felix.bundlerepository.Capability[] capabilities = resource.getCapabilities(); for (org.apache.felix.bundlerepository.Capability capability : capabilities) { if (namespace == null || capability.getName().equals(namespace)) { result.add(new FelixCapabilityAdapter(capability, this)); } } result.trimToSize(); return Collections.unmodifiableList(result); } @Override public InputStream getContent() { try { return new URL(resource.getURI()).openStream(); } catch (Exception e) { throw new RuntimeException(e); } } public List<Requirement> getRequirements(String namespace) { namespace = NamespaceTranslator.translate(namespace); org.apache.felix.bundlerepository.Requirement[] requirements = resource.getRequirements(); ArrayList<Requirement> result = new ArrayList<Requirement>(requirements.length); for (final org.apache.felix.bundlerepository.Requirement requirement : requirements) { if (namespace == null || requirement.getName().equals(namespace)) result.add(new FelixRequirementAdapter(requirement, this)); } result.trimToSize(); return result; } @Override public String toString() { Capability c = getCapabilities(IdentityNamespace.IDENTITY_NAMESPACE) .iterator().next(); Map<String, Object> atts = c.getAttributes(); return new StringBuilder() .append(atts.get(IdentityNamespace.IDENTITY_NAMESPACE)) .append(';') .append(atts .get(IdentityNamespace.CAPABILITY_VERSION_ATTRIBUTE)) .append(';') .append(atts.get(IdentityNamespace.CAPABILITY_TYPE_ATTRIBUTE)) .toString(); } }
8,463
0
Create_ds/aries/subsystem/subsystem-obr/src/main/java/org/apache/aries/subsystem/util
Create_ds/aries/subsystem/subsystem-obr/src/main/java/org/apache/aries/subsystem/util/felix/FelixRequirementAdapter.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.util.felix; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.apache.aries.subsystem.obr.internal.AbstractRequirement; import org.apache.aries.subsystem.obr.internal.NamespaceTranslator; import org.osgi.framework.namespace.BundleNamespace; import org.osgi.resource.Capability; import org.osgi.resource.Namespace; import org.osgi.resource.Resource; public class FelixRequirementAdapter extends AbstractRequirement { private final Map<String, String> directives; private final org.apache.felix.bundlerepository.Requirement requirement; private final Resource resource; public FelixRequirementAdapter(org.apache.felix.bundlerepository.Requirement requirement, Resource resource) { if (requirement == null) throw new NullPointerException("Missing required parameter: requirement"); if (resource == null) throw new NullPointerException("Missing required parameter: resource"); this.requirement = requirement; this.resource = resource; directives = computeDirectives(); } public Map<String, Object> getAttributes() { return Collections.emptyMap(); } public Map<String, String> getDirectives() { return directives; } public String getNamespace() { return NamespaceTranslator.translate(requirement.getName()); } public Resource getResource() { return resource; } public boolean matches(Capability capability) { return requirement.isSatisfied(new OsgiCapabilityAdapter(capability)); } private Map<String, String> computeDirectives() { Map<String, String> result = new HashMap<String, String>(3); /* (1) The Felix OBR specific "mandatory:<*" syntax must be stripped out of the filter. * (2) The namespace must be translated. */ String namespace = getNamespace(); String filter = requirement.getFilter() .replaceAll("\\(mandatory\\:\\<\\*[^\\)]*\\)", "") .replaceAll("\\(service\\=[^\\)]*\\)", "") .replaceAll("objectclass", "objectClass") .replaceAll(requirement.getName() + '=', namespace + '='); if (BundleNamespace.BUNDLE_NAMESPACE.equals(namespace)) { filter = filter.replaceAll("symbolicname", namespace) .replaceAll("version", BundleNamespace.CAPABILITY_BUNDLE_VERSION_ATTRIBUTE); } result.put(Namespace.REQUIREMENT_FILTER_DIRECTIVE, filter); result.put(Namespace.REQUIREMENT_RESOLUTION_DIRECTIVE, requirement.isOptional() ? Namespace.RESOLUTION_OPTIONAL : Namespace.RESOLUTION_MANDATORY); result.put(Namespace.REQUIREMENT_CARDINALITY_DIRECTIVE, requirement.isMultiple() ? Namespace.CARDINALITY_MULTIPLE : Namespace.CARDINALITY_SINGLE); return Collections.unmodifiableMap(result); } }
8,464
0
Create_ds/aries/subsystem/subsystem-obr/src/main/java/org/apache/aries/subsystem/util
Create_ds/aries/subsystem/subsystem-obr/src/main/java/org/apache/aries/subsystem/util/felix/OsgiResourceAdapter.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.util.felix; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Map; import org.apache.aries.subsystem.obr.internal.ResourceHelper; import org.apache.felix.bundlerepository.Capability; import org.apache.felix.bundlerepository.Requirement; import org.apache.felix.bundlerepository.Resource; import org.osgi.framework.Version; // TODO Need to distinguish between resources that have already been deployed (local) and those that have not. public class OsgiResourceAdapter implements Resource { private final org.osgi.resource.Resource resource; public OsgiResourceAdapter(org.osgi.resource.Resource resource) { if (resource == null) throw new NullPointerException("Missing required parameter: resource"); this.resource = resource; } public Capability[] getCapabilities() { Collection<org.osgi.resource.Capability> capabilities = resource.getCapabilities(null); Collection<Capability> result = new ArrayList<Capability>(capabilities.size()); for (org.osgi.resource.Capability capability : capabilities) result.add(new OsgiCapabilityAdapter(capability)); return result.toArray(new Capability[result.size()]); } public String[] getCategories() { return new String[0]; } public String getId() { String symbolicName = ResourceHelper.getSymbolicNameAttribute(resource); Version version = ResourceHelper.getVersionAttribute(resource); return symbolicName + ";version=" + version; } public String getPresentationName() { return ResourceHelper.getSymbolicNameAttribute(resource); } public Map getProperties() { return Collections.emptyMap(); } public Requirement[] getRequirements() { Collection<org.osgi.resource.Requirement> requirements = resource.getRequirements(null); Collection<Requirement> result = new ArrayList<Requirement>(requirements.size()); for (org.osgi.resource.Requirement requirement : requirements) result.add(new OsgiRequirementAdapter(requirement)); return result.toArray(new Requirement[result.size()]); } public Long getSize() { return -1L; } public String getSymbolicName() { return ResourceHelper.getSymbolicNameAttribute(resource); } public String getURI() { return ResourceHelper.getContentAttribute(resource); } public Version getVersion() { return ResourceHelper.getVersionAttribute(resource); } public boolean isLocal() { return false; } }
8,465
0
Create_ds/aries/subsystem/subsystem-obr/src/main/java/org/apache/aries/subsystem/util
Create_ds/aries/subsystem/subsystem-obr/src/main/java/org/apache/aries/subsystem/util/felix/FelixProperty.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.util.felix; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.felix.bundlerepository.Property; import org.osgi.framework.Version; public class FelixProperty implements Property { private static Set<?> asSet(List<?> list) { return new HashSet<Object>(list); } private final String name; private final Object value; public FelixProperty(String name, Object value) { if (name == null) throw new NullPointerException("Missing required parameter: name"); if (value == null) throw new NullPointerException("Missing required parameter: value"); this.name = name; this.value = value; } public FelixProperty(Map.Entry<String, Object> entry) { this(entry.getKey(), entry.getValue()); } public Object getConvertedValue() { if (value instanceof List) return asSet((List<?>)value); return value; } public String getName() { return name; } public String getType() { if (value instanceof Version) return Property.VERSION; if (value instanceof Long) return Property.LONG; if (value instanceof Double) return Property.DOUBLE; if (value instanceof List<?>) return Property.SET; return null; } public String getValue() { return String.valueOf(value); } }
8,466
0
Create_ds/aries/subsystem/subsystem-obr/src/main/java/org/apache/aries/subsystem/obr
Create_ds/aries/subsystem/subsystem-obr/src/main/java/org/apache/aries/subsystem/obr/internal/AbstractRequirement.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.obr.internal; import org.osgi.resource.Requirement; public abstract class AbstractRequirement implements Requirement { @Override public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof Requirement)) return false; Requirement c = (Requirement)o; return c.getNamespace().equals(getNamespace()) && c.getAttributes().equals(getAttributes()) && c.getDirectives().equals(getDirectives()) && c.getResource() != null ? c.getResource().equals( getResource()) : getResource() == null; } @Override public int hashCode() { int result = 17; result = 31 * result + getNamespace().hashCode(); result = 31 * result + getAttributes().hashCode(); result = 31 * result + getDirectives().hashCode(); result = 31 * result + (getResource() == null ? 0 : getResource().hashCode()); return result; } @Override public String toString() { return new StringBuffer().append(getClass().getName()).append(": ") .append("namespace=").append(getNamespace()) .append(", attributes=").append(getAttributes()) .append(", directives=").append(getDirectives()) .append(", resource=").append(getResource()).toString(); } }
8,467
0
Create_ds/aries/subsystem/subsystem-obr/src/main/java/org/apache/aries/subsystem/obr
Create_ds/aries/subsystem/subsystem-obr/src/main/java/org/apache/aries/subsystem/obr/internal/AbstractCapability.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.obr.internal; import org.osgi.resource.Capability; public abstract class AbstractCapability implements Capability { @Override public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof Capability)) return false; Capability c = (Capability)o; return c.getNamespace().equals(getNamespace()) && c.getAttributes().equals(getAttributes()) && c.getDirectives().equals(getDirectives()) && c.getResource().equals(getResource()); } @Override public int hashCode() { int result = 17; result = 31 * result + getNamespace().hashCode(); result = 31 * result + getAttributes().hashCode(); result = 31 * result + getDirectives().hashCode(); result = 31 * result + getResource().hashCode(); return result; } @Override public String toString() { return new StringBuilder().append("[Capability: ") .append("namespace=").append(getNamespace()) .append(", attributes=").append(getAttributes()) .append(", directives=").append(getDirectives()) .append(", resource=").append(getResource()).append(']') .toString(); } }
8,468
0
Create_ds/aries/subsystem/subsystem-obr/src/main/java/org/apache/aries/subsystem/obr
Create_ds/aries/subsystem/subsystem-obr/src/main/java/org/apache/aries/subsystem/obr/internal/Activator.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 WARRANTIESOR 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.obr.internal; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.apache.felix.bundlerepository.RepositoryAdmin; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceReference; import org.osgi.framework.ServiceRegistration; import org.osgi.service.repository.Repository; import org.osgi.util.tracker.ServiceTracker; public class Activator implements BundleActivator { private final Map<ServiceReference<RepositoryAdmin>, ServiceRegistration<Repository>> registrations = Collections.synchronizedMap(new HashMap<ServiceReference<RepositoryAdmin>, ServiceRegistration<Repository>>()); private ServiceTracker<RepositoryAdmin, RepositoryAdmin> tracker; @Override public void start(final BundleContext context) { tracker = new ServiceTracker<RepositoryAdmin, RepositoryAdmin>(context, RepositoryAdmin.class.getName(), null) { @Override public RepositoryAdmin addingService(ServiceReference<RepositoryAdmin> reference) { registrations.put(reference, context.registerService( Repository.class, new RepositoryAdminRepository(context.getService(reference)), null)); return super.addingService(reference); } @Override public void removedService(ServiceReference<RepositoryAdmin> reference, RepositoryAdmin service) { ServiceRegistration<Repository> registration = registrations.get(reference); if (registration == null) return; registration.unregister(); super.removedService(reference, service); } }; tracker.open(); } @Override public void stop(BundleContext context) { tracker.close(); } }
8,469
0
Create_ds/aries/subsystem/subsystem-obr/src/main/java/org/apache/aries/subsystem/obr
Create_ds/aries/subsystem/subsystem-obr/src/main/java/org/apache/aries/subsystem/obr/internal/ResourceHelper.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.obr.internal; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Map; import org.osgi.framework.Constants; import org.osgi.framework.FrameworkUtil; import org.osgi.framework.InvalidSyntaxException; 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; import org.osgi.service.repository.Repository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ResourceHelper { private static final Logger logger = LoggerFactory.getLogger(ResourceHelper.class); public static String getContentAttribute(Resource resource) { // TODO Add to constants. return (String)getContentAttribute(resource, "osgi.content"); } public static Object getContentAttribute(Resource resource, String name) { // TODO Add to constants. List<Capability> capabilities = resource.getCapabilities("osgi.content"); Capability capability = capabilities.get(0); return capability.getAttributes().get(name); } public static Object getIdentityAttribute(Resource resource, String name) { List<Capability> capabilities = resource.getCapabilities(IdentityNamespace.IDENTITY_NAMESPACE); Capability capability = capabilities.get(0); return capability.getAttributes().get(name); } public static Resource getResource(Requirement requirement, Repository repository) { Map<Requirement, Collection<Capability>> map = repository.findProviders(Arrays.asList(requirement)); Collection<Capability> capabilities = map.get(requirement); return capabilities == null ? null : capabilities.size() == 0 ? null : capabilities.iterator().next().getResource(); } public static String getSymbolicNameAttribute(Resource resource) { return (String)getIdentityAttribute(resource, IdentityNamespace.IDENTITY_NAMESPACE); } public static String getTypeAttribute(Resource resource) { String result = (String)getIdentityAttribute(resource, IdentityNamespace.CAPABILITY_TYPE_ATTRIBUTE); if (result == null) result = IdentityNamespace.TYPE_BUNDLE; return result; } public static Version getVersionAttribute(Resource resource) { Version result = (Version)getIdentityAttribute(resource, IdentityNamespace.CAPABILITY_VERSION_ATTRIBUTE); if (result == null) result = Version.emptyVersion; return result; } public static boolean matches(Requirement requirement, Capability capability) { // if (logger.isDebugEnabled()) // logger.debug(LOG_ENTRY, "matches", new Object[]{requirement, capability}); boolean result = false; if (requirement == null && capability == null) result = true; else if (requirement == null || capability == null) result = false; else if (!capability.getNamespace().equals(requirement.getNamespace())) result = false; else { String filterStr = requirement.getDirectives().get(Constants.FILTER_DIRECTIVE); if (filterStr == null) result = true; else { try { if (FrameworkUtil.createFilter(filterStr).matches(capability.getAttributes())) result = true; } catch (InvalidSyntaxException e) { logger.debug("Requirement had invalid filter string: " + requirement, e); result = false; } } } // TODO Check directives. // logger.debug(LOG_EXIT, "matches", result); return result; } }
8,470
0
Create_ds/aries/subsystem/subsystem-obr/src/main/java/org/apache/aries/subsystem/obr
Create_ds/aries/subsystem/subsystem-obr/src/main/java/org/apache/aries/subsystem/obr/internal/RepositoryAdminRepository.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.obr.internal; import static org.apache.aries.application.utils.AppConstants.LOG_ENTRY; import static org.apache.aries.application.utils.AppConstants.LOG_EXIT; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.apache.aries.subsystem.util.felix.FelixCapabilityAdapter; import org.apache.aries.subsystem.util.felix.FelixRepositoryAdapter; import org.apache.aries.subsystem.util.felix.FelixResourceAdapter; import org.apache.aries.subsystem.util.felix.OsgiRequirementAdapter; import org.apache.felix.bundlerepository.RepositoryAdmin; import org.apache.felix.bundlerepository.Resource; import org.osgi.framework.namespace.IdentityNamespace; import org.osgi.resource.Capability; import org.osgi.resource.Requirement; import org.osgi.service.repository.Repository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class RepositoryAdminRepository implements Repository { private static final Logger logger = LoggerFactory.getLogger(RepositoryAdminRepository.class); private final RepositoryAdmin repositoryAdmin; public RepositoryAdminRepository(RepositoryAdmin repositoryAdmin) { this.repositoryAdmin = repositoryAdmin; } public Collection<Capability> findProviders(Requirement requirement) { logger.debug(LOG_ENTRY, "findProviders", requirement); Collection<Capability> result = Collections.emptyList(); if (IdentityNamespace.IDENTITY_NAMESPACE.equals(requirement.getNamespace())) { result = new ArrayList<Capability>(); for (org.apache.felix.bundlerepository.Repository r : repositoryAdmin.listRepositories()) { FelixRepositoryAdapter repository = new FelixRepositoryAdapter(r); Map<Requirement, Collection<Capability>> map = repository.findProviders(Arrays.asList(requirement)); Collection<Capability> capabilities = map.get(requirement); if (capabilities != null) result.addAll(capabilities); } return result; } else { Resource[] resources = repositoryAdmin.discoverResources( new org.apache.felix.bundlerepository.Requirement[]{ new OsgiRequirementAdapter(requirement)}); logger.debug("Found {} resources with capabilities satisfying {}", resources == null ? 0 : resources.length, requirement); if (resources != null && resources.length != 0) { result = new ArrayList<Capability>(result.size()); OsgiRequirementAdapter adapter = new OsgiRequirementAdapter(requirement); for (Resource resource : resources) { logger.debug("Evaluating resource {}", resource); for (org.apache.felix.bundlerepository.Capability capability : resource.getCapabilities()) { logger.debug("Evaluating capability {}", capability); if (adapter.isSatisfied(capability)) { logger.debug("Adding capability {}", capability); result.add(new FelixCapabilityAdapter(capability, new FelixResourceAdapter(resource))); } } } } } logger.debug(LOG_EXIT, "findProviders", result); return result; } @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) result.put(requirement, findProviders(requirement)); return result; } }
8,471
0
Create_ds/aries/subsystem/subsystem-obr/src/main/java/org/apache/aries/subsystem/obr
Create_ds/aries/subsystem/subsystem-obr/src/main/java/org/apache/aries/subsystem/obr/internal/NamespaceTranslator.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.obr.internal; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.osgi.framework.namespace.BundleNamespace; import org.osgi.framework.namespace.PackageNamespace; import org.osgi.namespace.service.ServiceNamespace; public class NamespaceTranslator { private static final Map<String, String> namespaces = computeNamespaces(); private static Map<String, String> computeNamespaces() { Map<String, String> result = new HashMap<String, String>(8); result.put(PackageNamespace.PACKAGE_NAMESPACE, org.apache.felix.bundlerepository.Capability.PACKAGE); result.put(ServiceNamespace.SERVICE_NAMESPACE, org.apache.felix.bundlerepository.Capability.SERVICE); result.put(BundleNamespace.BUNDLE_NAMESPACE, org.apache.felix.bundlerepository.Capability.BUNDLE); result.put(org.apache.felix.bundlerepository.Capability.PACKAGE, PackageNamespace.PACKAGE_NAMESPACE); result.put(org.apache.felix.bundlerepository.Capability.SERVICE, ServiceNamespace.SERVICE_NAMESPACE); result.put(org.apache.felix.bundlerepository.Capability.BUNDLE, BundleNamespace.BUNDLE_NAMESPACE); return Collections.unmodifiableMap(result); } public static String translate(String namespace) { String result = namespaces.get(namespace); if (result == null) result = namespace; return result; } }
8,472
0
Create_ds/aries/subsystem/subsystem-gogo-command/src/main/java/org/apache/aries/subsystem
Create_ds/aries/subsystem/subsystem-gogo-command/src/main/java/org/apache/aries/subsystem/gogo/Activator.java
/* * Licensed under the Apache License, Version 2.0 (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.gogo; import java.io.IOException; import java.net.URL; import java.util.Dictionary; import java.util.Hashtable; import java.util.Map; import java.util.TreeMap; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; import org.osgi.framework.InvalidSyntaxException; import org.osgi.framework.ServiceReference; import org.osgi.service.subsystem.Subsystem; public class Activator implements BundleActivator { private BundleContext bundleContext; public void start(BundleContext context) throws Exception { bundleContext = context; Dictionary<String, Object> props = new Hashtable<String, Object>(); props.put("osgi.command.function", new String[] { "install", "uninstall", "start", "stop", "list" }); props.put("osgi.command.scope", "subsystem"); context.registerService(getClass().getName(), this, props); } public void install(String url) throws IOException { Subsystem rootSubsystem = getSubsystem(0); System.out.println("Installing subsystem: " + url); Subsystem s = rootSubsystem.install(url, new URL(url).openStream()); System.out.println("Subsystem successfully installed: " + s.getSymbolicName() + "; id: " + s.getSubsystemId()); } public void uninstall(long id) { getSubsystem(id).uninstall(); } public void start(long id) { getSubsystem(id).start(); } public void stop(long id) { getSubsystem(id).stop(); } public void list() throws InvalidSyntaxException { Map<Long, String> subsystems = new TreeMap<Long, String>(); for (ServiceReference<Subsystem> ref : bundleContext.getServiceReferences(Subsystem.class, null)) { Subsystem s = bundleContext.getService(ref); if (s != null) { subsystems.put(s.getSubsystemId(), String.format("%d\t%s\t%s %s", s.getSubsystemId(), s.getState(), s.getSymbolicName(), s.getVersion())); } } for (String entry : subsystems.values()) { System.out.println(entry); } } private Subsystem getSubsystem(long id) { try { for (ServiceReference<Subsystem> ref : bundleContext.getServiceReferences(Subsystem.class, "(subsystem.id=" + id + ")")) { Subsystem svc = bundleContext.getService(ref); if (svc != null) return svc; } } catch (InvalidSyntaxException e) { throw new RuntimeException(e); } throw new RuntimeException("Unable to find subsystem " + id); } public void stop(BundleContext context) throws Exception { } }
8,473
0
Create_ds/aries/subsystem/subsystem-itests-api-bundle/src/main/java/org/apache/aries/subsystem/itests/hello
Create_ds/aries/subsystem/subsystem-itests-api-bundle/src/main/java/org/apache/aries/subsystem/itests/hello/api/Hello.java
package org.apache.aries.subsystem.itests.hello.api; public interface Hello { public String saySomething(); }
8,474
0
Create_ds/aries/subsystem/subsystem-api/src/main/java/org/osgi/service
Create_ds/aries/subsystem/subsystem-api/src/main/java/org/osgi/service/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.osgi.service.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,475
0
Create_ds/aries/subsystem/subsystem-api/src/main/java/org/osgi/service
Create_ds/aries/subsystem/subsystem-api/src/main/java/org/osgi/service/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.osgi.service.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,476
0
Create_ds/aries/subsystem/subsystem-api/src/main/java/org/osgi/service
Create_ds/aries/subsystem/subsystem-api/src/main/java/org/osgi/service/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.osgi.service.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,477
0
Create_ds/aries/subsystem/subsystem-api/src/main/java/org/osgi/service
Create_ds/aries/subsystem/subsystem-api/src/main/java/org/osgi/service/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.osgi.service.repository;
8,478
0
Create_ds/aries/subsystem/subsystem-api/src/main/java/org/osgi/service
Create_ds/aries/subsystem/subsystem-api/src/main/java/org/osgi/service/subsystem/SubsystemConstants.java
/* * Copyright (c) OSGi Alliance (2011, 2013). 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.osgi.service.subsystem; /** * Defines the constants used by Subsystem service property, manifest header, * attribute and directive keys. * <p> * The values associated with these keys are of type {@code String}, unless * otherwise indicated. * * @Immutable * @author $Id: 36e2190a16d3bd0e4ed0e34799286284c0986974 $ */ public class SubsystemConstants { private SubsystemConstants() { // non-instantiable } /** * Manifest header identifying the resources to be deployed. */ public static final String DEPLOYED_CONTENT = "Deployed-Content"; /** * Manifest header attribute identifying the deployed version. */ public static final String DEPLOYED_VERSION_ATTRIBUTE = "deployed-version"; /** * Manifest header identifying the deployment manifest version. If not * present, the default value is {@code 1}. */ public static final String DEPLOYMENT_MANIFESTVERSION = "Deployment-ManifestVersion"; /** * Manifest header used to express a preference for particular resources to * satisfy implicit package dependencies. */ public static final String PREFERRED_PROVIDER = "Preferred-Provider"; /** * Manifest header directive identifying the provision policy. The default * value is {@link #PROVISION_POLICY_REJECT_DEPENDENCIES rejectDependencies} * * @see #PROVISION_POLICY_ACCEPT_DEPENDENCIES * @see #PROVISION_POLICY_REJECT_DEPENDENCIES */ public static final String PROVISION_POLICY_DIRECTIVE = "provision-policy"; /** * A value for the {@link #PROVISION_POLICY_DIRECTIVE provision-policy} * directive indicating the subsystem accepts dependency resources. The root * subsystem has this provision policy. */ public static final String PROVISION_POLICY_ACCEPT_DEPENDENCIES = "acceptDependencies"; /** * A value for the {@link #PROVISION_POLICY_DIRECTIVE provision-policy} * directive indicating the subsystem does not accept dependency resources. * This is the default value. */ public static final String PROVISION_POLICY_REJECT_DEPENDENCIES = "rejectDependencies"; /** * Manifest header identifying the resources to be deployed to satisfy the * dependencies of a subsystem. */ public static final String PROVISION_RESOURCE = "Provision-Resource"; /** * Manifest header directive identifying the start order of subsystem * contents. There is no default value. Specified values are of type * {@code String} and must represent an integer. */ public static final String START_ORDER_DIRECTIVE = "start-order"; /** * Manifest header identifying the categories of a subsystem as a * comma-delimited list. * * @since 1.1 */ public static final String SUBSYSTEM_CATEGORY = "Subsystem-Category"; /** * Manifest header identifying the contact address where problems with a * subsystem may be reported; for example, an email address. * * @since 1.1 */ public static final String SUBSYSTEM_CONTACTADDRESS = "Subsystem-ContactAddress"; /** * Manifest header identifying the list of subsystem contents identified by * a symbolic name and version. */ public static final String SUBSYSTEM_CONTENT = "Subsystem-Content"; /** * Manifest header identifying a subsystem's copyright information. * * @since 1.1 */ public static final String SUBSYSTEM_COPYRIGHT = "Subsystem-Copyright"; /** * Manifest header identifying the human readable description. */ public static final String SUBSYSTEM_DESCRIPTION = "Subsystem-Description"; /** * Manifest header identifying a subsystem's documentation URL, from which * further information about the subsystem may be obtained. * * @since 1.1 */ public static final String SUBSYSTEM_DOCURL = "Subsystem-DocURL"; /** * Manifest header identifying services offered for export. */ public static final String SUBSYSTEM_EXPORTSERVICE = "Subsystem-ExportService"; /** * Manifest header identifying the icon URL for the subsystem. * * @since 1.1 */ public static final String SUBSYSTEM_ICON = "Subsystem-Icon"; /** * The name of the service property for the * {@link Subsystem#getSubsystemId() subsystem ID}. The value of this * property must be of type {@code Long}. */ public static final String SUBSYSTEM_ID_PROPERTY = "subsystem.id"; /** * Manifest header identifying services required for import. */ public static final String SUBSYSTEM_IMPORTSERVICE = "Subsystem-ImportService"; /** * Manifest header identifying a subsystem's license. * * @since 1.1 */ public static final String SUBSYSTEM_LICENSE = "Subsystem-License"; /** * Manifest header identifying the base name of a subsystem's localization * entries. * * @since 1.1 */ public static final String SUBSYSTEM_LOCALIZATION = "Subsystem-Localization"; /** * Default value for the {@link #SUBSYSTEM_LOCALIZATION * Subsystem-Localization} manifest header. * * @since 1.1 */ public static final String SUBSYSTEM_LOCALIZATION_DEFAULT_BASENAME = "OSGI-INF/l10n/subsystem"; /** * Manifest header identifying the subsystem manifest version. If not * present, the default value is {@code 1}. */ public static final String SUBSYSTEM_MANIFESTVERSION = "Subsystem-ManifestVersion"; /** * Manifest header identifying the human readable subsystem name. */ public static final String SUBSYSTEM_NAME = "Subsystem-Name"; /** * The name of the service property for the subsystem * {@link Subsystem#getState() state}. The value of this property must be of * type {@link Subsystem.State}. */ public static final String SUBSYSTEM_STATE_PROPERTY = "subsystem.state"; /** * Manifest header value identifying the symbolic name for the subsystem. * Must be present. */ public static final String SUBSYSTEM_SYMBOLICNAME = "Subsystem-SymbolicName"; /** * The name of the service property for the subsystem * {@link Subsystem#getSymbolicName() symbolic name}. */ public static final String SUBSYSTEM_SYMBOLICNAME_PROPERTY = "subsystem.symbolicName"; /** * The symbolic name of the root subsystem. */ public static final String ROOT_SUBSYSTEM_SYMBOLICNAME = "org.osgi.service.subsystem.root"; /** * Manifest header identifying the subsystem type. * * @see #SUBSYSTEM_TYPE_APPLICATION * @see #SUBSYSTEM_TYPE_COMPOSITE * @see #SUBSYSTEM_TYPE_FEATURE */ public static final String SUBSYSTEM_TYPE = "Subsystem-Type"; /** * The name of the service property for the {@link #SUBSYSTEM_TYPE subsystem * type}. * * @see #SUBSYSTEM_TYPE_APPLICATION * @see #SUBSYSTEM_TYPE_COMPOSITE * @see #SUBSYSTEM_TYPE_FEATURE */ public static final String SUBSYSTEM_TYPE_PROPERTY = "subsystem.type"; /** * The resource type value identifying an application subsystem. * * <p> * This value is used for the {@code osgi.identity} capability attribute * {@code type}, the {@link #SUBSYSTEM_TYPE} manifest header and the * {@link #SUBSYSTEM_TYPE_PROPERTY} service property. */ public static final String SUBSYSTEM_TYPE_APPLICATION = "osgi.subsystem.application"; /** * The resource type value identifying an composite subsystem. * * <p> * This value is used for the {@code osgi.identity} capability attribute * {@code type}, the {@link #SUBSYSTEM_TYPE} manifest header and the * {@link #SUBSYSTEM_TYPE_PROPERTY} service property. */ public static final String SUBSYSTEM_TYPE_COMPOSITE = "osgi.subsystem.composite"; /** * The resource type value identifying an feature subsystem. * * <p> * This value is used for the {@code osgi.identity} capability attribute * {@code type}, the {@link #SUBSYSTEM_TYPE} manifest header and the * {@link #SUBSYSTEM_TYPE_PROPERTY} service property. */ public static final String SUBSYSTEM_TYPE_FEATURE = "osgi.subsystem.feature"; /** * Manifest header identifying a subsystem's vendor. * * @since 1.1 */ public static final String SUBSYSTEM_VENDOR = "Subsystem-Vendor"; /** * Manifest header value identifying the version of the subsystem. If not * present, the default value is {@code 0.0.0}. */ public static final String SUBSYSTEM_VERSION = "Subsystem-Version"; /** * The name of the service property for the subsystem * {@link Subsystem#getVersion() version}. The value of this property must * be of type {@code Version}. */ public static final String SUBSYSTEM_VERSION_PROPERTY = "subsystem.version"; }
8,479
0
Create_ds/aries/subsystem/subsystem-api/src/main/java/org/osgi/service
Create_ds/aries/subsystem/subsystem-api/src/main/java/org/osgi/service/subsystem/SubsystemPermission.java
/* * Copyright (c) OSGi Alliance (2000, 2013). 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.osgi.service.subsystem; import java.io.IOException; import java.io.NotSerializableException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.ObjectStreamField; import java.security.AccessController; import java.security.BasicPermission; import java.security.Permission; import java.security.PermissionCollection; import java.security.PrivilegedAction; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; import org.osgi.framework.Filter; import org.osgi.framework.FrameworkUtil; import org.osgi.framework.InvalidSyntaxException; /** * A bundle's authority to perform specific privileged administrative operations * on or to get sensitive information about a subsystem. The actions for this * permission are: * * <pre> * Action Methods * context Subsystem.getBundleContext * execute Subsystem.start * Subsystem.stop * lifecycle Subsystem.install * Subsystem.uninstall * metadata Subsystem.getSubsystemHeaders * Subsystem.getLocation * </pre> * * <p> * The name of this permission is a filter expression. The filter gives access * to the following attributes: * <ul> * <li>location - The location of a subsystem.</li> * <li>id - The subsystem ID of the designated subsystem.</li> * <li>name - The symbolic name of a subsystem.</li> * </ul> * Filter attribute names are processed in a case sensitive manner. * * @ThreadSafe * @author $Id: 5c71d73cc6a3e8b2c2a7a3f188ebcf79b5ef7888 $ */ public final class SubsystemPermission extends BasicPermission { static final long serialVersionUID = 307051004521261705L; /** * The action string {@code execute}. */ public final static String EXECUTE = "execute"; /** * The action string {@code lifecycle}. */ public final static String LIFECYCLE = "lifecycle"; /** * The action string {@code metadata}. */ public final static String METADATA = "metadata"; /** * The action string {@code context}. */ public final static String CONTEXT = "context"; private final static int ACTION_EXECUTE = 0x00000001; private final static int ACTION_LIFECYCLE = 0x00000002; private final static int ACTION_METADATA = 0x00000004; private final static int ACTION_CONTEXT = 0x00000008; private final static int ACTION_ALL = ACTION_EXECUTE | ACTION_LIFECYCLE | ACTION_METADATA | ACTION_CONTEXT; final static int ACTION_NONE = 0; /** * The actions in canonical form. * * @serial */ private volatile String actions = null; /** * The actions mask. */ transient int action_mask; /** * If this SubsystemPermission was constructed with a filter, this holds a * Filter matching object used to evaluate the filter in implies. */ transient Filter filter; /** * The subsystem governed by this SubsystemPermission - only used if filter * == null */ transient final Subsystem subsystem; /** * This map holds the properties of the permission, used to match a filter * in implies. This is not initialized until necessary, and then cached in * this object. */ private transient volatile Map<String, Object> properties; /** * ThreadLocal used to determine if we have recursively called * getProperties. */ private static final ThreadLocal<Subsystem> recurse = new ThreadLocal<Subsystem>(); /** * Create a new SubsystemPermission. * * This constructor must only be used to create a permission that is going * to be checked. * <p> * Examples: * * <pre> * (name=com.acme.*)(location=http://www.acme.com/subsystems/*)) * (id&gt;=1) * </pre> * * @param filter A filter expression that can use, location, id, and name * keys. Filter attribute names are processed in a case sensitive * manner. A special value of {@code "*"} can be used to match all * subsystems. * @param actions {@code execute}, {@code lifecycle}, {@code metadata}, or * {@code context}. * @throws IllegalArgumentException If the filter has an invalid syntax. */ public SubsystemPermission(String filter, String actions) { this(parseFilter(filter), parseActions(actions)); } /** * Creates a new requested {@code SubsystemPermission} object to be used by * the code that must perform {@code checkPermission}. * {@code SubsystemPermission} objects created with this constructor cannot * be added to an {@code SubsystemPermission} permission collection. * * @param subsystem A subsystem. * @param actions {@code execute}, {@code lifecycle}, {@code metadata}, or * {@code context}. */ public SubsystemPermission(Subsystem subsystem, String actions) { super(createName(subsystem)); setTransients(null, parseActions(actions)); this.subsystem = subsystem; } /** * Create a permission name from a Subsystem * * @param subsystem Subsystem to use to create permission name. * @return permission name. */ private static String createName(Subsystem subsystem) { if (subsystem == null) { throw new IllegalArgumentException("subsystem must not be null"); } StringBuffer sb = new StringBuffer("(id="); sb.append(subsystem.getSubsystemId()); sb.append(")"); return sb.toString(); } /** * Package private constructor used by SubsystemPermissionCollection. * * @param filter name filter or {@code null} for wildcard. * @param mask action mask */ SubsystemPermission(Filter filter, int mask) { super((filter == null) ? "*" : filter.toString()); setTransients(filter, mask); this.subsystem = null; } /** * Called by constructors and when deserialized. * * @param filter Permission's filter or {@code null} for wildcard. * @param mask action mask */ private void setTransients(Filter filter, int mask) { this.filter = filter; if ((mask == ACTION_NONE) || ((mask & ACTION_ALL) != mask)) { throw new IllegalArgumentException("invalid action string"); } this.action_mask = mask; } /** * Parse action string into action mask. * * @param actions Action string. * @return action mask. */ private static int parseActions(String actions) { boolean seencomma = false; int mask = ACTION_NONE; if (actions == null) { return mask; } char[] a = actions.toCharArray(); int i = a.length - 1; if (i < 0) return mask; while (i != -1) { char c; // skip whitespace while ((i != -1) && ((c = a[i]) == ' ' || c == '\r' || c == '\n' || c == '\f' || c == '\t')) i--; // check for the known strings int matchlen; if (i >= 6 && (a[i - 6] == 'e' || a[i - 6] == 'E') && (a[i - 5] == 'x' || a[i - 5] == 'X') && (a[i - 4] == 'e' || a[i - 4] == 'E') && (a[i - 3] == 'c' || a[i - 3] == 'C') && (a[i - 2] == 'u' || a[i - 2] == 'U') && (a[i - 1] == 't' || a[i - 1] == 'T') && (a[i] == 'e' || a[i] == 'E')) { matchlen = 7; mask |= ACTION_EXECUTE; } else if (i >= 8 && (a[i - 8] == 'l' || a[i - 8] == 'L') && (a[i - 7] == 'i' || a[i - 7] == 'I') && (a[i - 6] == 'f' || a[i - 6] == 'F') && (a[i - 5] == 'e' || a[i - 5] == 'E') && (a[i - 4] == 'c' || a[i - 4] == 'C') && (a[i - 3] == 'y' || a[i - 3] == 'Y') && (a[i - 2] == 'c' || a[i - 2] == 'C') && (a[i - 1] == 'l' || a[i - 1] == 'L') && (a[i] == 'e' || a[i] == 'E')) { matchlen = 9; mask |= ACTION_LIFECYCLE; } else if (i >= 7 && (a[i - 7] == 'm' || a[i - 7] == 'M') && (a[i - 6] == 'e' || a[i - 6] == 'E') && (a[i - 5] == 't' || a[i - 5] == 'T') && (a[i - 4] == 'a' || a[i - 4] == 'A') && (a[i - 3] == 'd' || a[i - 3] == 'D') && (a[i - 2] == 'a' || a[i - 2] == 'A') && (a[i - 1] == 't' || a[i - 1] == 'T') && (a[i] == 'a' || a[i] == 'A')) { matchlen = 8; mask |= ACTION_METADATA; } else if (i >= 6 && (a[i - 6] == 'c' || a[i - 6] == 'C') && (a[i - 5] == 'o' || a[i - 5] == 'O') && (a[i - 4] == 'n' || a[i - 4] == 'N') && (a[i - 3] == 't' || a[i - 3] == 'T') && (a[i - 2] == 'e' || a[i - 2] == 'E') && (a[i - 1] == 'x' || a[i - 1] == 'X') && (a[i] == 't' || a[i] == 'T')) { matchlen = 7; mask |= ACTION_CONTEXT; } else { // parse error throw new IllegalArgumentException("invalid permission: " + actions); } // make sure we didn't just match the tail of a word // like "ackbarfexecute". Also, skip to the comma. seencomma = false; while (i >= matchlen && !seencomma) { switch (a[i - matchlen]) { case ',' : seencomma = true; /* FALLTHROUGH */ case ' ' : case '\r' : case '\n' : case '\f' : case '\t' : break; default : throw new IllegalArgumentException("invalid permission: " + actions); } i--; } // point i at the location of the comma minus one (or -1). i -= matchlen; } if (seencomma) { throw new IllegalArgumentException("invalid permission: " + actions); } return mask; } /** * Parse filter string into a Filter object. * * @param filterString The filter string to parse. * @return a Filter for this subsystem. If the specified filterString equals * "*", then {@code null} is returned to indicate a wildcard. * @throws IllegalArgumentException If the filter syntax is invalid. */ private static Filter parseFilter(String filterString) { filterString = filterString.trim(); if (filterString.equals("*")) { return null; } try { return FrameworkUtil.createFilter(filterString); } catch (InvalidSyntaxException e) { IllegalArgumentException iae = new IllegalArgumentException("invalid filter"); iae.initCause(e); throw iae; } } /** * Determines if the specified permission is implied by this object. This * method throws an exception if the specified permission was not * constructed with a subsystem. * * <p> * This method returns {@code true} if the specified permission is a * SubsystemPermission AND * <ul> * <li>this object's filter matches the specified permission's subsystem ID, * subsystem symbolic name, and subsystem location OR</li> * <li>this object's filter is "*"</li> * </ul> * AND this object's actions include all of the specified permission's * actions. * <p> * Special case: if the specified permission was constructed with "*" * filter, then this method returns {@code true} if this object's filter is * "*" and this object's actions include all of the specified permission's * actions * * @param p The requested permission. * @return {@code true} if the specified permission is implied by this * object; {@code false} otherwise. */ @Override public boolean implies(Permission p) { if (!(p instanceof SubsystemPermission)) { return false; } SubsystemPermission requested = (SubsystemPermission) p; if (subsystem != null) { return false; } // if requested permission has a filter, then it is an invalid argument if (requested.filter != null) { return false; } return implies0(requested, ACTION_NONE); } /** * Internal implies method. Used by the implies and the permission * collection implies methods. * * @param requested The requested SubsystemPermision which has already been * validated as a proper argument. The requested SubsystemPermission * must not have a filter expression. * @param effective The effective actions with which to start. * @return {@code true} if the specified permission is implied by this * object; {@code false} otherwise. */ boolean implies0(SubsystemPermission requested, int effective) { /* check actions first - much faster */ effective |= action_mask; final int desired = requested.action_mask; if ((effective & desired) != desired) { return false; } /* Get our filter */ Filter f = filter; if (f == null) { // it's "*" return true; } /* is requested a wildcard filter? */ if (requested.subsystem == null) { return false; } Map<String, Object> requestedProperties = requested.getProperties(); if (requestedProperties == null) { /* * If the requested properties are null, then we have detected a * recursion getting the subsystem location. So we return true to * permit the subsystem location request in the SubsystemPermission * check up the stack to succeed. */ return true; } return f.matches(requestedProperties); } /** * Returns the canonical string representation of the * {@code SubsystemPermission} actions. * * <p> * Always returns present {@code SubsystemPermission} actions in the * following order: {@code execute}, {@code lifecycle}, {@code metadata}, * {@code context}. * * @return Canonical string representation of the * {@code SubsystemPermission} actions. */ @Override public String getActions() { String result = actions; if (result == null) { StringBuffer sb = new StringBuffer(); int mask = action_mask; if ((mask & ACTION_EXECUTE) == ACTION_EXECUTE) { sb.append(EXECUTE); sb.append(','); } if ((mask & ACTION_LIFECYCLE) == ACTION_LIFECYCLE) { sb.append(LIFECYCLE); sb.append(','); } if ((mask & ACTION_METADATA) == ACTION_METADATA) { sb.append(METADATA); sb.append(','); } if ((mask & ACTION_CONTEXT) == ACTION_CONTEXT) { sb.append(CONTEXT); sb.append(','); } // remove trailing comma if (sb.length() > 0) { sb.setLength(sb.length() - 1); } actions = result = sb.toString(); } return result; } /** * Returns a new {@code PermissionCollection} object suitable for storing * {@code SubsystemPermission}s. * * @return A new {@code PermissionCollection} object. */ @Override public PermissionCollection newPermissionCollection() { return new SubsystemPermissionCollection(); } /** * Determines the equality of two {@code SubsystemPermission} objects. * * @param obj The object being compared for equality with this object. * @return {@code true} if {@code obj} is equivalent to this * {@code SubsystemPermission}; {@code false} otherwise. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof SubsystemPermission)) { return false; } SubsystemPermission sp = (SubsystemPermission) obj; return (action_mask == sp.action_mask) && ((subsystem == sp.subsystem) || ((subsystem != null) && subsystem.equals(sp.subsystem))) && (filter == null ? sp.filter == null : filter.equals(sp.filter)); } /** * Returns the hash code value for this object. * * @return Hash code value for this object. */ @Override public int hashCode() { int h = 31 * 17 + getName().hashCode(); h = 31 * h + getActions().hashCode(); if (subsystem != null) { h = 31 * h + subsystem.hashCode(); } return h; } /** * WriteObject is called to save the state of this permission object to a * stream. The actions are serialized, and the superclass takes care of the * name. */ private synchronized void writeObject(java.io.ObjectOutputStream s) throws IOException { if (subsystem != null) { throw new NotSerializableException("cannot serialize"); } // Write out the actions. The superclass takes care of the name // call getActions to make sure actions field is initialized if (actions == null) getActions(); s.defaultWriteObject(); } /** * readObject is called to restore the state of this permission from a * stream. */ private synchronized void readObject(java.io.ObjectInputStream s) throws IOException, ClassNotFoundException { // Read in the data, then initialize the transients s.defaultReadObject(); setTransients(parseFilter(getName()), parseActions(actions)); } /** * Called by {@code implies0} on an SubsystemPermission which was * constructed with a Subsystem. This method loads a map with the * filter-matchable properties of this subsystem. The map is cached so this * lookup only happens once. * * This method should only be called on an SubsystemPermission which was * constructed with a subsystem * * @return a map of properties for this subsystem */ private Map<String, Object> getProperties() { Map<String, Object> result = properties; if (result != null) { return result; } /* * We may have recursed here due to the Subsystem.getLocation call in * the doPrivileged below. If this is the case, return null to allow * implies to return true. */ final Object mark = recurse.get(); if (mark == subsystem) { return null; } recurse.set(subsystem); try { final Map<String, Object> map = new HashMap<String, Object>(4); AccessController.doPrivileged(new PrivilegedAction<Void>() { public Void run() { map.put("id", new Long(subsystem.getSubsystemId())); map.put("location", subsystem.getLocation()); map.put("name", subsystem.getSymbolicName()); return null; } }); return properties = map; } finally { recurse.set(null); } } } /** * Stores a collection of {@code SubsystemPermission}s. */ final class SubsystemPermissionCollection extends PermissionCollection { private static final long serialVersionUID = 3906372644575328048L; /** * Collection of permissions. * * @GuardedBy this */ private transient Map<String, SubsystemPermission> permissions; /** * Boolean saying if "*" is in the collection. * * @serial * @GuardedBy this */ private boolean all_allowed; /** * Create an empty SubsystemPermissionCollection object. * */ public SubsystemPermissionCollection() { permissions = new HashMap<String, SubsystemPermission>(); } /** * Adds a permission to this permission collection. * * @param permission The {@code SubsystemPermission} object to add. * @throws IllegalArgumentException If the specified permission is not an * {@code SubsystemPermission} instance or was constructed with a * Subsystem object. * @throws SecurityException If this {@code SubsystemPermissionCollection} * object has been marked read-only. */ @Override public void add(Permission permission) { if (!(permission instanceof SubsystemPermission)) { throw new IllegalArgumentException("invalid permission: " + permission); } if (isReadOnly()) { throw new SecurityException("attempt to add a Permission to a " + "readonly PermissionCollection"); } final SubsystemPermission sp = (SubsystemPermission) permission; if (sp.subsystem != null) { throw new IllegalArgumentException("cannot add to collection: " + sp); } final String name = sp.getName(); synchronized (this) { Map<String, SubsystemPermission> pc = permissions; SubsystemPermission existing = pc.get(name); if (existing != null) { int oldMask = existing.action_mask; int newMask = sp.action_mask; if (oldMask != newMask) { pc.put(name, new SubsystemPermission(existing.filter, oldMask | newMask)); } } else { pc.put(name, sp); } if (!all_allowed) { if (name.equals("*")) { all_allowed = true; } } } } /** * Determines if the specified permissions implies the permissions expressed * in {@code permission}. * * @param permission The Permission object to compare with the * {@code SubsystemPermission} objects in this collection. * @return {@code true} if {@code permission} is implied by an * {@code SubsystemPermission} in this collection, {@code false} * otherwise. */ @Override public boolean implies(Permission permission) { if (!(permission instanceof SubsystemPermission)) { return false; } SubsystemPermission requested = (SubsystemPermission) permission; // if requested permission has a filter, then it is an invalid argument if (requested.filter != null) { return false; } int effective = SubsystemPermission.ACTION_NONE; Collection<SubsystemPermission> perms; synchronized (this) { Map<String, SubsystemPermission> pc = permissions; // short circuit if the "*" Permission was added if (all_allowed) { SubsystemPermission sp = pc.get("*"); if (sp != null) { effective |= sp.action_mask; final int desired = requested.action_mask; if ((effective & desired) == desired) { return true; } } } perms = pc.values(); } // just iterate one by one for (SubsystemPermission perm : perms) { if (perm.implies0(requested, effective)) { return true; } } return false; } /** * Returns an enumeration of all {@code SubsystemPermission} objects in the * container. * * @return Enumeration of all {@code SubsystemPermission} objects. */ @Override public synchronized Enumeration<Permission> elements() { List<Permission> all = new ArrayList<Permission>(permissions.values()); return Collections.enumeration(all); } /* serialization logic */ private static final ObjectStreamField[] serialPersistentFields = {new ObjectStreamField("permissions", HashMap.class), new ObjectStreamField("all_allowed", Boolean.TYPE)}; private synchronized void writeObject(ObjectOutputStream out) throws IOException { ObjectOutputStream.PutField pfields = out.putFields(); pfields.put("permissions", permissions); pfields.put("all_allowed", all_allowed); out.writeFields(); } private synchronized void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { ObjectInputStream.GetField gfields = in.readFields(); @SuppressWarnings("unchecked") HashMap<String, SubsystemPermission> p = (HashMap<String, SubsystemPermission>) gfields.get("permissions", null); permissions = p; all_allowed = gfields.get("all_allowed", false); } }
8,480
0
Create_ds/aries/subsystem/subsystem-api/src/main/java/org/osgi/service
Create_ds/aries/subsystem/subsystem-api/src/main/java/org/osgi/service/subsystem/Subsystem.java
/* * Copyright (c) OSGi Alliance (2012, 2013). 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.osgi.service.subsystem; import java.io.InputStream; import java.util.Collection; import java.util.Locale; import java.util.Map; import org.osgi.annotation.versioning.ProviderType; import org.osgi.framework.BundleContext; import org.osgi.framework.Version; import org.osgi.framework.namespace.IdentityNamespace; import org.osgi.resource.Resource; /** * A subsystem is a collection of resources constituting a logical, possibly * isolated, unit of functionality. * * <p> * A subsystem may be <i>scoped</i> or <i>unscoped</i>. Scoped subsystems are * isolated by implicit or explicit sharing policies. Unscoped subsystems are * not isolated and, therefore, have no sharing policy. There are three standard * {@link SubsystemConstants#SUBSYSTEM_TYPE types} of subsystems. * <ul> * <li>{@link SubsystemConstants#SUBSYSTEM_TYPE_APPLICATION Application} - An * implicitly scoped subsystem. Nothing is exported, and imports are computed * based on any unsatisfied content requirements.</li> * <li>{@link SubsystemConstants#SUBSYSTEM_TYPE_COMPOSITE Composite} - An * explicitly scoped subsystem. The sharing policy is defined by metadata within * the subsystem archive.</li> * <li>{@link SubsystemConstants#SUBSYSTEM_TYPE_FEATURE Feature} - An unscoped * subsystem.</li> * </ul> * Conceptually, a subsystem may be thought of as existing in an isolated region * along with zero or more other subsystems. Each region has one and only one * scoped subsystem, which dictates the sharing policy. The region may, however, * have many unscoped subsystems. It is, therefore, possible to have shared * constituents across multiple subsystems within a region. Associated with each * region is a bundle whose context may be {@link #getBundleContext() retrieved} * from any subsystem within that region. This context may be used to monitor * activity occurring within the region. * * <p> * A subsystem may have {@link #getChildren() children} and, unless it's the * root subsystem, must have at least one {@link #getParents() parent}. * Subsystems become children of the subsystem in which they are installed. * Unscoped subsystems have more than one parent if they are installed in more * than one subsystem within the same region. The subsystem graph may be thought * of as an <a * href="http://en.wikipedia.org/wiki/Directed_acyclic_graph">acyclic * digraph</a> with one and only one source vertex, which is the root subsystem. * The edges have the child as the head and parent as the tail. * * <p> * A subsystem has several identifiers. * <ul> * <li>{@link #getLocation() Location} - An identifier specified by the client * as part of installation. It is guaranteed to be unique within the same * framework.</li> * <li>{@link #getSubsystemId() ID} - An identifier generated by the * implementation as part of installation. It is guaranteed to be unique within * the same framework.</li> * <li>{@link #getSymbolicName() Symbolic Name}/{@link #getVersion() Version} - * The combination of symbolic name and version is guaranteed to be unique * within the same region. Although {@link #getType() type} is not formally part * of the identity, two subsystems with the same symbolic names and versions but * different types are not considered to be equal.</li> * </ul> * A subsystem has a well-defined {@link State life cycle}. Which stage a * subsystem is in may be obtained from the subsystem's {@link #getState() * state} and is dependent on which life cycle operation is currently active or * was last invoked. * * <p> * A subsystem archive is a ZIP file having an {@code .esa} extension and * containing metadata describing the subsystem. The form of the metadata may be * a subsystem or deployment manifest, as well as any content resource files. * The manifests are optional and will be computed if not present. The subsystem * manifest headers may be {@link #getSubsystemHeaders(Locale) retrieved} in raw * or localized forms. There are five standard * {@link IdentityNamespace#CAPABILITY_TYPE_ATTRIBUTE types} of resources that * may be included in a subsystem. * <ul> * <li>{@link IdentityNamespace#TYPE_BUNDLE Bundle} - A bundle that is not a * fragment.</li> * <li>{@link IdentityNamespace#TYPE_FRAGMENT Fragment} - A fragment bundle.</li> * <li>{@link SubsystemConstants#SUBSYSTEM_TYPE_APPLICATION Application * Subsystem} - An application subsystem.</li> * <li>{@link SubsystemConstants#SUBSYSTEM_TYPE_COMPOSITE Composite Subsystem} - * A composite subsystem.</li> * <li>{@link SubsystemConstants#SUBSYSTEM_TYPE_FEATURE Feature Subsystem} - A * feature subsystem.</li> * </ul> * Resources contained by a subsystem are called {@link #getConstituents() * constituents}. There are several ways a resource may become a constituent of * a subsystem: * <ul> * <li>A resource is listed as part of the subsystem's content.</li> * <li>A subsystem resource is a child of the subsystem.</li> * <li>The subsystem has a provision policy of accept dependencies.</li> * <li>A bundle resource is installed using the region bundle context.</li> * <li>A bundle resource is installed using the bundle context of another * resource contained by the subsystem.</li> * </ul> * * <p> * In addition to invoking one of the install methods, a subsystem instance may * be obtained through the service registry. Each installed subsystem has a * corresponding service registration. A subsystem service has the following * properties. * * <ul> * <li>{@link SubsystemConstants#SUBSYSTEM_ID_PROPERTY ID} - The ID of the * subsystem.</li> * <li>{@link SubsystemConstants#SUBSYSTEM_SYMBOLICNAME_PROPERTY Symbolic Name} * - The symbolic name of the subsystem.</li> * <li>{@link SubsystemConstants#SUBSYSTEM_VERSION_PROPERTY Version} - The * version of the subsystem.</li> * <li>{@link SubsystemConstants#SUBSYSTEM_TYPE_PROPERTY Type} - The type of the * subsystem.</li> * <li>{@link SubsystemConstants#SUBSYSTEM_STATE_PROPERTY State} - The state of * the subsystem.</li> * </ul> * * <p> * Because a subsystem must be used to install other subsystems, a root * subsystem is provided as a starting point. The root subsystem may only be * obtained as a service and has the following characteristics. * * <ul> * <li>The ID is {@code 0}.</li> * <li>The symbolic name is * {@link SubsystemConstants#ROOT_SUBSYSTEM_SYMBOLICNAME * org.osgi.service.subsystem.root}.</li> * <li>The version matches this specification's version.</li> * <li>It has no parents.</li> * <li>All existing bundles, including the system and subsystem implementation * bundles, are constituents.</li> * <li>The type is {@link SubsystemConstants#SUBSYSTEM_TYPE_APPLICATION * osgi.subsystem.application} with no imports.</li> * <li>The provision policy is * {@link SubsystemConstants#PROVISION_POLICY_ACCEPT_DEPENDENCIES * acceptDependencies}.</li> * </ul> * * @ThreadSafe * @author $Id: 46dbc3d05b6c0fcd6962ffe433b62cbd284c3d0d $ */ @ProviderType public interface Subsystem { /** * An enumeration of the possible states of a subsystem. * * <p> * These states are a reflection of what constituent resources are permitted * to do and not an aggregation of constituent resource states. */ public static enum State { /** * The subsystem is in the process of installing. * <p> * A subsystem is in the {@code INSTALLING} state when the * {@link Subsystem#install(String, InputStream) install} method of its * parent is active, and attempts are being made to install its content * resources. If the install method completes without exception, then * the subsystem has successfully installed and must move to the * {@link #INSTALLED} state. Otherwise, the subsystem has failed to * install and must move to the {@link #INSTALL_FAILED} state. */ INSTALLING, /** * The subsystem is installed but not yet resolved. * <p> * A subsystem is in the {@code INSTALLED} state when it has been * installed in a parent subsystem but is not or cannot be resolved. * This state is visible if the dependencies of the subsystem's content * resources cannot be resolved. */ INSTALLED, /** * The subsystem failed to install. * <p> * A subsystem is in the {@code INSTALL_FAILED} state when an * unrecoverable error occurred during installation. The subsystem is in * an unusable state but references to the subsystem object may still be * available and used for introspection. */ INSTALL_FAILED, /** * The subsystem is in the process of resolving. * <p> * A subsystem is in the {@code RESOLVING} state when the * {@link Subsystem#start() start} method is active, and attempts are * being made to resolve its content resources. If the resolve method * completes without exception, then the subsystem has successfully * resolved and must move to the {@link #RESOLVED} state. Otherwise, the * subsystem has failed to resolve and must move to the INSTALLED state. */ RESOLVING, /** * The subsystem is resolved and able to be started. * <p> * A subsystem is in the {@code RESOLVED} state when all of its content * resources are resolved. Note that the subsystem is not active yet. */ RESOLVED, /** * The subsystem is in the process of starting. * <p> * A subsystem is in the {@code STARTING} state when its * {@link Subsystem#start() start} method is active, and attempts are * being made to start its content and dependencies. If the start method * completes without exception, then the subsystem has successfully * started and must move to the {@link #ACTIVE} state. Otherwise, the * subsystem has failed to start and must move to the {@link #RESOLVED} * state. */ STARTING, /** * The subsystem is now running. * <p> * A subsystem is in the {@code ACTIVE} state when its content and * dependencies have been successfully started. */ ACTIVE, /** * The subsystem is in the process of stopping. * <p> * A subsystem is in the {@code STOPPING} state when its * {@link Subsystem#stop() stop} method is active, and attempts are * being made to stop its content and dependencies. When the stop method * completes, the subsystem is stopped and must move to the * {@link #RESOLVED} state. */ STOPPING, /** * The subsystem is in the process of uninstalling. * <p> * A subsystem is in the {@code UNINSTALLING} state when its * {@link Subsystem#uninstall() uninstall} method is active, and * attempts are being made to uninstall its constituent and * dependencies. When the uninstall method completes, the subsystem is * uninstalled and must move to the {@link #UNINSTALLED} state. */ UNINSTALLING, /** * The subsystem is uninstalled and may not be used. * <p> * The {@code UNINSTALLED} state is only visible after a subsystem's * constituent and dependencies are uninstalled. The subsystem is in an * unusable state but references to the subsystem object may still be * available and used for introspection. */ UNINSTALLED } /** * Returns the bundle context of the region within which this subsystem * resides. * <p> * The bundle context offers the same perspective of any resource contained * by a subsystem within the region. It may be used, for example, to monitor * events internal to the region as well as external events visible to the * region. All subsystems within the same region have the same bundle * context. If this subsystem is in a state where the bundle context would * be invalid, {@code null} is returned. * * @return The bundle context of the region within which this subsystem * resides or {@code null} if this subsystem's state is in * {@link State#INSTALL_FAILED INSTALL_FAILED}, * {@link State#UNINSTALLED UNINSTALLED}. * @throws SecurityException If the caller does not have the appropriate * {@link SubsystemPermission}[this,CONTEXT], and the runtime * supports permissions. */ public BundleContext getBundleContext(); /** * Returns the child subsystems of this subsystem. * * @return The child subsystems of this subsystem. The returned collection * is an unmodifiable snapshot of all subsystems that are installed * in this subsystem. The collection will be empty if no subsystems * are installed in this subsystem. * @throws IllegalStateException If this subsystem's state is in * {@link State#INSTALL_FAILED INSTALL_FAILED}, * {@link State#UNINSTALLED UNINSTALLED}. */ public Collection<Subsystem> getChildren(); /** * Returns the headers for this subsystem's subsystem manifest. * <p> * Each key in the map is a header name and the value of the key is the * corresponding header value. Because header names are case-insensitive, * the methods of the map must treat the keys in a case-insensitive manner. * If the header name is not found, {@code null} is returned. Both original * and derived headers will be included in the map. * <p> * This method must continue to return the headers while this subsystem is * in the {@link State#INSTALL_FAILED INSTALL_FAILED} or * {@link State#UNINSTALLED UNINSTALLED} states. * * @param locale The locale for which translations are desired. The header * values are translated according to the specified locale. If the * specified locale is {@code null} or not supported, the raw values * are returned. If the translation for a particular header is not * found, the raw value is returned. * @return The headers for this subsystem's subsystem manifest. The returned * map is unmodifiable. * @throws SecurityException If the caller does not have the appropriate * {@link SubsystemPermission}[this,METADATA], and the runtime * supports permissions. */ public Map<String, String> getSubsystemHeaders(Locale locale); /** * Returns the location identifier of this subsystem. * <p> * The location identifier is the {@code location} that was passed to the * {@link #install(String, InputStream) install} method of the * {@link #getParents() parent} subsystem. It is unique within the * framework. * <p> * This method must continue to return this subsystem's headers while this * subsystem is in the {@link State#INSTALL_FAILED INSTALL_FAILED} or * {@link State#UNINSTALLED UNINSTALLED} states. * * @return The location identifier of this subsystem. * @throws SecurityException If the caller does not have the appropriate * {@link SubsystemPermission}[this,METADATA], and the runtime * supports permissions. */ public String getLocation(); /** * Returns the parent subsystems of this subsystem. * * @return The parent subsystems of this subsystem. The returned collection * is an unmodifiable snapshot of all subsystems in which this * subsystem is installed. The collection will be empty for the root * subsystem; otherwise, it must contain at least one parent. Scoped * subsystems always have only one parent. Unscoped subsystems may * have multiple parents. * @throws IllegalStateException If this subsystem's state is in * {@link State#INSTALL_FAILED INSTALL_FAILED}, * {@link State#UNINSTALLED UNINSTALLED}. */ public Collection<Subsystem> getParents(); /** * Returns the constituent resources of this subsystem. * * @return The constituent resources of this subsystem. The returned * collection is an unmodifiable snapshot of the constituent * resources of this subsystem. If this subsystem has no * constituents, the collection will be empty. * @throws IllegalStateException If this subsystem's state is in * {@link State#INSTALL_FAILED INSTALL_FAILED}, * {@link State#UNINSTALLED UNINSTALLED}. */ public Collection<Resource> getConstituents(); /** * Returns the headers for this subsystem's deployment manifest. * <p> * Each key in the map is a header name and the value of the key is the * corresponding header value. Because header names are case-insensitive, * the methods of the map must treat the keys in a case-insensitive manner. * If the header name is not found, {@code null} is returned. Both original * and derived headers will be included in the map. * <p> * This method must continue to return the headers while this subsystem is * in the {@link State#INSTALL_FAILED INSTALL_FAILED} or * {@link State#UNINSTALLED UNINSTALLED} states. * * @return The headers for this subsystem's deployment manifest. The * returned map is unmodifiable. * @throws SecurityException If the caller does not have the appropriate * {@link SubsystemPermission}[this,METADATA], and the runtime * supports permissions. * @since 1.1 */ public Map<String, String> getDeploymentHeaders(); /** * Returns the current state of this subsystem. * <p> * This method must continue to return this subsystem's state while this * subsystem is in the {@link State#INSTALL_FAILED INSTALL_FAILED} or * {@link State#UNINSTALLED UNINSTALLED} states. * * @return The current state of this subsystem. */ public State getState(); /** * Returns the identifier of this subsystem. * <p> * The identifier is a monotonically increasing, non-negative integer * automatically generated at installation time and guaranteed to be unique * within the framework. The identifier of the root subsystem is zero. * <p> * This method must continue to return this subsystem's identifier while * this subsystem is in the {@link State#INSTALL_FAILED INSTALL_FAILED} or * {@link State#UNINSTALLED UNINSTALLED} states. * * @return The identifier of this subsystem. */ public long getSubsystemId(); /** * Returns the symbolic name of this subsystem. * <p> * The subsystem symbolic name conforms to the same grammar rules as the * bundle symbolic name and is derived from one of the following, in order. * <ul> * <li>The value of the {@link SubsystemConstants#SUBSYSTEM_SYMBOLICNAME * Subsystem-SymbolicName} header, if specified.</li> * <li>The subsystem URI if passed as the {@code location} along with the * {@code content} to the {@link #install(String, InputStream) install} * method.</li> * <li>Optionally generated in an implementation specific way.</li> * </ul> * The combination of subsystem symbolic name and {@link #getVersion() * version} is unique within a region. The symbolic name of the root * subsystem is {@link SubsystemConstants#ROOT_SUBSYSTEM_SYMBOLICNAME * org.osgi.service.subsystem.root}. * <p> * This method must continue to return this subsystem's symbolic name while * this subsystem is in the {@link State#INSTALL_FAILED INSTALL_FAILED} or * {@link State#UNINSTALLED UNINSTALLED} states. * * @return The symbolic name of this subsystem. */ public String getSymbolicName(); /** * Returns the {@link SubsystemConstants#SUBSYSTEM_TYPE type} of this * subsystem. * <p> * This method must continue to return this subsystem's type while this * subsystem is in the {@link State#INSTALL_FAILED INSTALL_FAILED} or * {@link State#UNINSTALLED UNINSTALLED} states. * * @return The type of this subsystem. */ public String getType(); /** * Returns the {@link SubsystemConstants#SUBSYSTEM_VERSION version} of this * subsystem. * <p> * The subsystem version conforms to the same grammar rules as the bundle * version and is derived from one of the following, in order. * <ul> * <li>The value of the {@link SubsystemConstants#SUBSYSTEM_VERSION * Subsystem-Version} header, if specified.</li> * <li>The subsystem URI if passed as the {@code location} along with the * {@code content} to the {@link #install(String, InputStream) install} * method.</li> * <li>Defaults to {@code 0.0.0}.</li> * </ul> * The combination of subsystem {@link #getSymbolicName() symbolic name} and * version is unique within a region. The version of the root subsystem * matches this specification's version. * <p> * This method must continue to return this subsystem's version while this * subsystem is in the {@link State#INSTALL_FAILED INSTALL_FAILED} or * {@link State#UNINSTALLED UNINSTALLED} states. * * @return The version of this subsystem. */ public Version getVersion(); /** * Installs a subsystem from the specified location identifier. * <p> * This method performs the same function as calling * {@link #install(String, InputStream)} with the specified location * identifier and {@code null} as the content. * * @param location The location identifier of the subsystem to install. * @return The installed subsystem. * @throws IllegalStateException If this subsystem's state is in * {@link State#INSTALLING INSTALLING}, {@link State#INSTALL_FAILED * INSTALL_FAILED}, {@link State#UNINSTALLING UNINSTALLING}, * {@link State#UNINSTALLED UNINSTALLED}. * @throws SubsystemException If the installation failed. * @throws SecurityException If the caller does not have the appropriate * {@link SubsystemPermission}[installed subsystem,LIFECYCLE], and * the runtime supports permissions. * @see #install(String, InputStream) */ public Subsystem install(String location); /** * Installs a subsystem from the specified content. * <p> * The specified location will be used as an identifier of the subsystem. * Every installed subsystem is uniquely identified by its location, which * is typically in the form of a URI. If the specified location conforms to * the {@code subsystem-uri} grammar, the required symbolic name and * optional version information will be used as default values. * <p> * If the specified content is {@code null}, a new input stream must be * created from which to read the subsystem by interpreting, in an * implementation dependent manner, the specified location. * <p> * A subsystem installation must be persistent. That is, an installed * subsystem must remain installed across Framework and VM restarts. * <p> * All references to changing the state of this subsystem include both * changing the state of the subsystem object as well as the state property * of the subsystem service registration. * <p> * The following steps are required to install a subsystem. * <ol> * <li>If an installed subsystem with the specified location identifier * already exists, return the installed subsystem.</li> * <li>Read the specified content in order to determine the symbolic name, * version, and type of the installing subsystem. If an error occurs while * reading the content, an installation failure results.</li> * <li>If an installed subsystem with the same symbolic name and version * already exists within this subsystem's region, complete the installation * with one of the following. * <ul> * <li>If the installing and installed subsystems' types are not equal, an * installation failure results.</li> * <li>If the installing and installed subsystems' types are equal, and the * installed subsystem is already a child of this subsystem, return the * installed subsystem.</li> * <li>If the installing and installed subsystems' types are equal, and the * installed subsystem is not already a child of this subsystem, add the * installed subsystem as a child of this subsystem, increment the installed * subsystem's reference count by one, and return the installed subsystem.</li> * </ul> * <li>Create a new subsystem based on the specified location and content.</li> * <li>If the subsystem is scoped, install and start a new region context * bundle.</li> * <li>Change the state to {@link State#INSTALLING INSTALLING} and register * a new subsystem service.</li> * <li>Discover the subsystem's content resources. If any mandatory resource * is missing, an installation failure results.</li> * <li>Discover the dependencies required by the content resources. If any * mandatory dependency is missing, an installation failure results.</li> * <li>Using a framework {@code ResolverHook}, disable runtime resolution * for the resources.</li> * <li>For each resource, increment the reference count by one. If the * reference count is one, install the resource. If an error occurs while * installing a resource, an install failure results with that error as the * cause.</li> * <li>If the subsystem is scoped, enable the import sharing policy.</li> * <li>Enable runtime resolution for the resources.</li> * <li>Change the state of the subsystem to {@link State#INSTALLED * INSTALLED}.</li> * <li>Return the new subsystem.</li> * </ol> * <p> * Implementations should be sensitive to the potential for long running * operations and periodically check the current thread for interruption. An * interrupted thread should result in a {@link SubsystemException} with an * InterruptedException as the cause and be treated as an installation * failure. * <p> * All installation failure flows include the following, in order. * <ol> * <li>Change the state to {@link State#INSTALL_FAILED INSTALL_FAILED}.</li> * <li>Change the state to {@link State#UNINSTALLING UNINSTALLING}.</li> * <li>All content and dependencies which may have been installed by the * installing process must be uninstalled.</li> * <li>Change the state to {@link State#UNINSTALLED UNINSTALLED}.</li> * <li>Unregister the subsystem service.</li> * <li>If the subsystem is a scoped subsystem then, uninstall the region * context bundle.</li> * <li>Throw a {@link SubsystemException} with the cause of the installation * failure.</li> * </ol> * * @param location The location identifier of the subsystem to be installed. * @param content The input stream from which this subsystem will be read or * {@code null} to indicate the input stream must be created from the * specified location identifier. The input stream will always be * closed when this method completes, even if an exception is thrown. * @return The installed subsystem. * @throws IllegalStateException If this subsystem's state is in * {@link State#INSTALLING INSTALLING}, {@link State#INSTALL_FAILED * INSTALL_FAILED}, {@link State#UNINSTALLING UNINSTALLING}, * {@link State#UNINSTALLED UNINSTALLED}. * @throws SubsystemException If the installation failed. * @throws SecurityException If the caller does not have the appropriate * {@link SubsystemPermission}[installed subsystem,LIFECYCLE], and * the runtime supports permissions. */ public Subsystem install(String location, InputStream content); /** * Installs a subsystem from the specified content according to the * specified deployment manifest. * <p> * This method installs a subsystem using the provided deployment manifest * instead of the one in the archive, if any, or a computed one. If the * deployment manifest is {@code null}, the behavior is exactly the same as * in the {@link #install(String, InputStream)} method. Implementations must * support deployment manifest input streams in the format described by * section 134.2 of the Subsystem Service Specification. If the deployment * manifest does not conform to the subsystem manifest (see 134.15.2), the * installation fails. * * @param location The location identifier of the subsystem to be installed. * @param content The input stream from which this subsystem will be read or * {@code null} to indicate the input stream must be created from the * specified location identifier. The input stream will always be * closed when this method completes, even if an exception is thrown. * @param deploymentManifest The deployment manifest to use in lieu of the * one in the archive, if any, or a computed one. * @return The installed subsystem. * @throws IllegalStateException If this subsystem's state is in * {@link State#INSTALLING INSTALLING}, {@link State#INSTALL_FAILED * INSTALL_FAILED}, {@link State#UNINSTALLING UNINSTALLING}, * {@link State#UNINSTALLED UNINSTALLED}. * @throws SubsystemException If the installation failed. * @throws SecurityException If the caller does not have the appropriate * {@link SubsystemPermission}[installed subsystem,LIFECYCLE], and * the runtime supports permissions. * @since 1.1 */ public Subsystem install(String location, InputStream content, InputStream deploymentManifest); /** * Starts this subsystem. * <p> * The following table shows which actions are associated with each state. * An action of {@code Wait} means this method will block until a state * transition occurs, upon which the new state will be evaluated in order to * determine how to proceed. If a state transition does not occur in a * reasonable time while waiting then no action is taken and a * SubsystemException is thrown to indicate the subsystem was unable to be * started. An action of {@code Return} means this method returns * immediately without taking any other action. * </p> * <table> * <tr> * <th>State</th> * <th width="4">Action</th> * </tr> * <tr> * <td>{@link State#INSTALLING INSTALLING}</td> * <td>{@code Wait}</td> * </tr> * <tr> * <td>{@link State#INSTALLED INSTALLED}</td> * <td>{@code Resolve}, {@code Start}</td> * </tr> * <tr> * <td>{@link State#INSTALL_FAILED INSTALL_FAILED}</td> * <td>{@code IllegalStateException}</td> * </tr> * <tr> * <td>{@link State#RESOLVING RESOLVING}</td> * <td>{@code Wait}</td> * </tr> * <tr> * <td>{@link State#RESOLVED RESOLVED}</td> * <td>{@code Start}</td> * </tr> * <tr> * <td>{@link State#STARTING STARTING}</td> * <td>{@code Wait}</td> * </tr> * <tr> * <td>{@link State#ACTIVE ACTIVE}</td> * <td>{@code Return}</td> * </tr> * <tr> * <td>{@link State#STOPPING STOPPING}</td> * <td>{@code Wait}</td> * </tr> * <tr> * <td>{@link State#UNINSTALLING UNINSTALLING}</td> * <td>{@code IllegalStateException}</td> * </tr> * <tr> * <td>{@link State#UNINSTALLED UNINSTALLED}</td> * <td>{@code IllegalStateException}</td> * </tr> * </table> * <p> * All references to changing the state of this subsystem include both * changing the state of the subsystem object as well as the state property * of the subsystem service registration. * <p> * A subsystem must be persistently started. That is, a started subsystem * must be restarted across Framework and VM restarts, even if a start * failure occurs. * <p> * The following steps are required to start this subsystem. * <ol> * <li>Set the subsystem <i>autostart setting</i> to <i>started</i>.</li> * <li>If this subsystem is in the {@link State#RESOLVED RESOLVED} state, * proceed to step 7.</li> * <li>Change the state to {@link State#RESOLVING RESOLVING}.</li> * <li>Resolve the content resources. A resolution failure results in a * start failure with a state of {@link State#INSTALLED INSTALLED}.</li> * <li>Change the state to {@link State#RESOLVED RESOLVED}.</li> * <li>If this subsystem is scoped, enable the export sharing policy.</li> * <li>Change the state to {@link State#STARTING STARTING}.</li> * <li>For each eligible resource, increment the active use count by one. If * the active use count is one, start the resource. All dependencies must be * started before any content resource, and content resources must be * started according to the specified * {@link SubsystemConstants#START_ORDER_DIRECTIVE start order}. If an error * occurs while starting a resource, a start failure results with that error * as the cause.</li> * <li>Change the state to {@link State#ACTIVE ACTIVE}.</li> * </ol> * <p> * Implementations should be sensitive to the potential for long running * operations and periodically check the current thread for interruption. An * interrupted thread should be treated as a start failure with an * {@code InterruptedException} as the cause. * <p> * All start failure flows include the following, in order. * <ol> * <li>If the subsystem state is {@link State#STARTING STARTING} then change * the state to {@link State#STOPPING STOPPING} and stop all resources that * were started as part of this operation.</li> * <li>Change the state to either {@link State#INSTALLED INSTALLED} or * {@link State#RESOLVED RESOLVED}.</li> * <li>Throw a SubsystemException with the specified cause.</li> * </ol> * * @throws SubsystemException If this subsystem fails to start. * @throws IllegalStateException If this subsystem's state is in * {@link State#INSTALL_FAILED INSTALL_FAILED}, * {@link State#UNINSTALLING UNINSTALLING}, or * {@link State#UNINSTALLED UNINSTALLED}, or if the state of at * least one of this subsystem's parents is not in * {@link State#STARTING STARTING}, {@link State#ACTIVE ACTIVE}. * @throws SecurityException If the caller does not have the appropriate * {@link SubsystemPermission}[this,EXECUTE], and the runtime * supports permissions. */ public void start(); /** * Stops this subsystem. * <p> * The following table shows which actions are associated with each state. * An action of {@code Wait} means this method will block until a state * transition occurs, upon which the new state will be evaluated in order to * determine how to proceed. If a state transition does not occur in a * reasonable time while waiting then no action is taken and a * SubsystemException is thrown to indicate the subsystem was unable to be * stopped. An action of {@code Return} means this method returns * immediately without taking any other action. * </p> * <table> * <tr> * <th>State</th> * <th width="4">Action</th> * </tr> * <tr> * <td>{@link State#INSTALLING INSTALLING}</td> * <td>{@code Wait}</td> * </tr> * <tr> * <td>{@link State#INSTALLED INSTALLED}</td> * <td>{@code Return}</td> * <td> * <tr> * <td>{@link State#INSTALL_FAILED INSTALL_FAILED}</td> * <td>{@code IllegalStateException}</td> * <td> * <tr> * <td>{@link State#RESOLVING RESOLVING}</td> * <td>{@code Wait}</td> * <td> * <tr> * <td>{@link State#RESOLVED RESOLVED}</td> * <td>{@code Return}</td> * <td> * <tr> * <td>{@link State#STARTING STARTING}</td> * <td>{@code Wait}</td> * <td> * <tr> * <td>{@link State#ACTIVE ACTIVE}</td> * <td>{@code Stop}</td> * <td> * <tr> * <td>{@link State#STOPPING STOPPING}</td> * <td>{@code Wait}</td> * <td> * <tr> * <td>{@link State#UNINSTALLING UNINSTALLING}</td> * <td>{@code IllegalStateException}</td> * <td> * <tr> * <td>{@link State#UNINSTALLED UNINSTALLED}</td> * <td>{@code IllegalStateException}</td> * <td> * </table> * <p> * A subsystem must be persistently stopped. That is, a stopped subsystem * must remain stopped across Framework and VM restarts. * <p> * All references to changing the state of this subsystem include both * changing the state of the subsystem object as well as the state property * of the subsystem service registration. * <p> * The following steps are required to stop this subsystem. * <ol> * <li>Set the subsystem <i>autostart setting</i> to <i>stopped</i>.</li> * <li>Change the state to {@link State#STOPPING STOPPING}.</li> * <li>For each eligible resource, decrement the active use count by one. If * the active use count is zero, stop the resource. All content resources * must be stopped before any dependencies, and content resources must be * stopped in reverse {@link SubsystemConstants#START_ORDER_DIRECTIVE start * order}.</li> * <li>Change the state to {@link State#RESOLVED RESOLVED}.</li> * </ol> * With regard to error handling, once this subsystem has transitioned to * the {@link State#STOPPING STOPPING} state, every part of each step above * must be attempted. Errors subsequent to the first should be logged. Once * the stop process has completed, a SubsystemException must be thrown with * the initial error as the specified cause. * <p> * Implementations should be sensitive to the potential for long running * operations and periodically check the current thread for interruption, in * which case a SubsystemException with an InterruptedException as the cause * should be thrown. If an interruption occurs while waiting, this method * should terminate immediately. Once the transition to the * {@link State#STOPPING STOPPING} state has occurred, however, this method * must not terminate due to an interruption until the stop process has * completed. * * @throws SubsystemException If this subsystem fails to stop cleanly. * @throws IllegalStateException If this subsystem's state is in * {@link State#INSTALL_FAILED INSTALL_FAILED}, * {@link State#UNINSTALLING UNINSTALLING}, or * {@link State#UNINSTALLED UNINSTALLED}. * @throws SecurityException If the caller does not have the appropriate * {@link SubsystemPermission}[this,EXECUTE], and the runtime * supports permissions. */ public void stop(); /** * Uninstalls this subsystem. * <p> * The following table shows which actions are associated with each state. * An action of {@code Wait} means this method will block until a state * transition occurs, upon which the new state will be evaluated in order to * determine how to proceed. If a state transition does not occur in a * reasonable time while waiting then no action is taken and a * SubsystemException is thrown to indicate the subsystem was unable to be * uninstalled. An action of {@code Return} means this method returns * immediately without taking any other action. * <table> * <tr> * <th>State</th> * <th width="4">Action</th> * </tr> * <tr> * <td>{@link State#INSTALLING INSTALLING}</td> * <td>{@code Wait}</td> * </tr> * <tr> * <td>{@link State#INSTALLED INSTALLED}</td> * <td>{@code Uninstall}</td> * </tr> * <tr> * <td>{@link State#INSTALL_FAILED INSTALL_FAILED}</td> * <td>{@code Wait}</td> * </tr> * <tr> * <td>{@link State#RESOLVING RESOLVING}</td> * <td>{@code Wait}</td> * </tr> * <tr> * <td>{@link State#RESOLVED RESOLVED}</td> * <td>{@code Uninstall}</td> * </tr> * <tr> * <td>{@link State#STARTING STARTING}</td> * <td>{@code Wait}</td> * </tr> * <tr> * <td>{@link State#ACTIVE ACTIVE}</td> * <td>{@code Stop}, {@code Uninstall}</td> * </tr> * <tr> * <td>{@link State#STOPPING STOPPING}</td> * <td>{@code Wait}</td> * </tr> * <tr> * <td>{@link State#UNINSTALLING UNINSTALLING}</td> * <td>{@code Wait}</td> * </tr> * <tr> * <td>{@link State#UNINSTALLED UNINSTALLED}</td> * <td>{@code Return}</td> * </tr> * </table> * <p> * All references to changing the state of this subsystem include both * changing the state of the subsystem object as well as the state property * of the subsystem service registration. * <p> * The following steps are required to uninstall this subsystem after being * stopped if necessary. * <ol> * <li>Change the state to {@link State#INSTALLED INSTALLED}.</li> * <li>Change the state to {@link State#UNINSTALLING UNINSTALLING}.</li> * <li>For each referenced resource, decrement the reference count by one. * If the reference count is zero, uninstall the resource. All content * resources must be uninstalled before any dependencies.</li> * <li>Change the state to {@link State#UNINSTALLED UNINSTALLED}.</li> * <li>Unregister the subsystem service.</li> * <li>If the subsystem is scoped, uninstall the region context bundle.</li> * </ol> * With regard to error handling, once this subsystem has transitioned to * the {@link State#UNINSTALLING UNINSTALLING} state, every part of each * step above must be attempted. Errors subsequent to the first should be * logged. Once the uninstall process has completed, a * {@code SubsystemException} must be thrown with the specified cause. * <p> * Implementations should be sensitive to the potential for long running * operations and periodically check the current thread for interruption, in * which case a {@code SubsystemException} with an * {@code InterruptedException} as the cause should be thrown. If an * interruption occurs while waiting, this method should terminate * immediately. Once the transition to the {@link State#UNINSTALLING * UNINSTALLING} state has occurred, however, this method must not terminate * due to an interruption until the uninstall process has completed. * * @throws SubsystemException If this subsystem fails to uninstall cleanly. * @throws SecurityException If the caller does not have the appropriate * {@link SubsystemPermission}[this,LIFECYCLE], and the runtime * supports permissions. */ public void uninstall(); }
8,481
0
Create_ds/aries/subsystem/subsystem-api/src/main/java/org/osgi/service
Create_ds/aries/subsystem/subsystem-api/src/main/java/org/osgi/service/subsystem/package-info.java
/* * Copyright (c) OSGi Alliance (2010, 2013). 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. */ /** * Subsystem Service Package Version 1.1. * * <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.subsystem; version="[1.1,2.0)"} * <p> * Example import for providers implementing the API in this package: * <p> * {@code Import-Package: org.osgi.service.subsystem; version="[1.1,1.2)"} * * @author $Id: ef9042c42a3fbb135031bf4446e4e0fa0a579d22 $ */ @Version("1.1") package org.osgi.service.subsystem; import org.osgi.annotation.versioning.Version;
8,482
0
Create_ds/aries/subsystem/subsystem-api/src/main/java/org/osgi/service
Create_ds/aries/subsystem/subsystem-api/src/main/java/org/osgi/service/subsystem/SubsystemException.java
/* * Copyright (c) OSGi Alliance (2011, 2013). 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.osgi.service.subsystem; /** * A Subsystem exception used to indicate a problem. * * @author $Id: ad56ae269d24c698380e80d2f91c76d61ee121ff $ */ public class SubsystemException extends RuntimeException { private static final long serialVersionUID = 1L; /** * Construct a Subsystem exception with no message. */ public SubsystemException() { super(); } /** * Construct a Subsystem exception specifying a message. * * @param message The message to include in the exception. */ public SubsystemException(String message) { super(message); } /** * Construct a Subsystem exception specifying a cause. * * @param cause The cause of the exception. */ public SubsystemException(Throwable cause) { super(cause); } /** * Construct a Subsystem exception specifying a message and a cause. * * @param message The message to include in the exception. * @param cause The cause of the exception. */ public SubsystemException(String message, Throwable cause) { super(message, cause); } }
8,483
0
Create_ds/aries/subsystem/subsystem-api/src/main/java/org/apache/aries
Create_ds/aries/subsystem/subsystem-api/src/main/java/org/apache/aries/subsystem/AriesSubsystem.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; import java.io.InputStream; import java.util.Collection; import org.apache.aries.util.filesystem.IDirectory; import org.osgi.resource.Requirement; import org.osgi.service.subsystem.Subsystem; import org.osgi.service.subsystem.SubsystemException; import org.osgi.service.subsystem.SubsystemPermission; public interface AriesSubsystem extends Subsystem { /** * Adds the specified requirements to this subsystem's sharing policy. * <p> * The sharing policy of this subsystem's region is updated with the * specified requirements (i.e. imports). Requirements already part of the * sharing policy are ignored. Upon return, constituents of this subsystem * will be allowed to resolve against matching capabilities that are visible * to the parent subsystems. * * @param requirement The requirement to add to the sharing policy. * @throws SubsystemException If the requirement did not already exist and * could not be added. * @throws UnsupportedOperationException If this is the root subsystem or * the type does not support additional requirements. */ void addRequirements(Collection<Requirement> requirements); @Override AriesSubsystem install(String location); @Override AriesSubsystem install(String location, InputStream content); @Override AriesSubsystem install(String location, InputStream content, InputStream deploymentManifest); /** * Installs a subsystem from the specified location identifier and content. * <p> * This method performs the same function as calling * {@link #install(String, IDirectory, InputStream)} with a null deployment * manifest. * * @param location The location identifier of the subsystem to install. * @param content The directory from which this subsystem will be read or * {@code null} to indicate the directory must be created from the * specified location identifier. * @return The installed subsystem. * @throws IllegalStateException If this subsystem's state is in * {@link State#INSTALLING INSTALLING}, {@link State#INSTALL_FAILED * INSTALL_FAILED}, {@link State#UNINSTALLING UNINSTALLING}, * {@link State#UNINSTALLED UNINSTALLED}. * @throws SubsystemException If the installation failed. * @throws SecurityException If the caller does not have the appropriate * {@link SubsystemPermission}[installed subsystem,LIFECYCLE], and * the runtime supports permissions. * @see #install(String, IDirectory, InputStream) */ AriesSubsystem install(String location, IDirectory content); /** * Installs a subsystem from the specified location identifier and content * but uses the provided deployment manifest, if any, rather than the * computed one or the one provided as part of the content. * <p> * This method performs the same function as calling * {@link #install(String, InputStream, InputStream)} except the content is * retrieved from the specified {@link IDirectory} instead. * * @param location The location identifier of the subsystem to install. * @param content The directory from which this subsystem will be read or * {@code null} to indicate the directory must be created from the * specified location identifier. * @param deploymentManifest The deployment manifest to use in lieu of any * others. * @return The installed subsystem. * @throws IllegalStateException If this subsystem's state is in * {@link State#INSTALLING INSTALLING}, {@link State#INSTALL_FAILED * INSTALL_FAILED}, {@link State#UNINSTALLING UNINSTALLING}, * {@link State#UNINSTALLED UNINSTALLED}. * @throws SubsystemException If the installation failed. * @throws SecurityException If the caller does not have the appropriate * {@link SubsystemPermission}[installed subsystem,LIFECYCLE], and * the runtime supports permissions. * @see #install(String, InputStream, InputStream) */ AriesSubsystem install(String location, IDirectory content, InputStream deploymentManifest); }
8,484
0
Create_ds/aries/subsystem/subsystem-api/src/main/java/org/apache/aries
Create_ds/aries/subsystem/subsystem-api/src/main/java/org/apache/aries/subsystem/ContentHandler.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; import java.io.InputStream; import org.osgi.service.coordinator.Coordination; import org.osgi.service.subsystem.Subsystem; /** * A handler for custom content in Subsystems. This handler must be registered as Whiteboard * services with the {@link #CONTENT_TYPE_PROPERTY} property indicating the content type this * handler must be invoked for. <p> * * Custom content embedded inside an subsystem archive (e.g. {@code .esa} file) must be declared * in the {@code Subsystem-Content} header where the {@link #EMBEDDED_RESOURCE_ATTRIBUTE} can * be used to associate it with the name of a file inside the archive. */ public interface ContentHandler { static final String CONTENT_TYPE_PROPERTY = "org.aries.subsystem.contenthandler.type"; static final String EMBEDDED_RESOURCE_ATTRIBUTE = "embedded-resource"; /** * Install this custom content. * @param is An input stream to the content. * @param symbolicName The name of the content. * @param contentType The type of the content. * @param subsystem The target subsystem. * @param coordination The current coordination. Can be used to register a compensation in case of * failure or to fail the installation action. */ void install(InputStream is, String symbolicName, String contentType, Subsystem subsystem, Coordination coordination); /** * Start this custom content. * @param symbolicName The name of the content. * @param contentType The type of the content. * @param subsystem The target subsystem. * @param coordination The current coordination. Can be used to register a compensation in case of * failure or to fail the start action. */ void start(String symbolicName, String contentType, Subsystem subsystem, Coordination coordination); /** * Stop this custom content. * @param symbolicName The name of the content. * @param contentType The type of the content. * @param subsystem The target subsystem. */ void stop(String symbolicName, String contentType, Subsystem subsystem); /** * Uninstall this custom content. * @param symbolicName The name of the content. * @param contentType The type of the content. * @param subsystem The target subsystem. */ void uninstall(String symbolicName, String contentType, Subsystem subsystem); }
8,485
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/BasicTest.java
package org.apache.aries.subsystem.scope.itests; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.net.URL; import java.util.Arrays; import java.util.Collection; 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.junit.Test; import org.osgi.framework.Bundle; import org.osgi.framework.BundleException; public class BasicTest extends AbstractTest { /** * Basic test of the initial state of the root scope. */ @Test public void testRootScopeInitialState() { Scope scope = getScope(); Collection<Bundle> bundles = Arrays.asList(bundleContext.getBundles()); assertCollectionEquals(bundles, scope.getBundles()); assertEmpty(scope.getChildren()); assertEquals(0, scope.getId()); assertNull(scope.getLocation()); assertEquals("root", scope.getName()); assertNull(scope.getParent()); assertEmpty(scope.getSharePolicies(SharePolicy.TYPE_EXPORT)); assertEmpty(scope.getSharePolicies(SharePolicy.TYPE_IMPORT)); assertNotNull(scope.newScopeUpdate()); } /** * Basic test of the initial state of the root scope from another bundle. * The root scope instance should be the same as in the previous test. * @throws Exception */ @Test public void testRootScopeInitialStateFromOtherBundle() throws Exception { Bundle tb1 = installBundle("tb-1.jar"); try { tb1.start(); } catch (BundleException e) { if (e.getCause() instanceof AssertionError) { throw (AssertionError)e.getCause(); } throw e; } finally { tb1.uninstall(); } } @Test public void testInstallBundleIntoRootScope() throws Exception { Scope scope = getScope(); int previousSize = scope.getBundles().size(); String location = getBundleLocation("tb-2.jar"); URL url = new URL(location); InstallInfo tb2Info = new InstallInfo(location, url.openStream()); ScopeUpdate scopeUpdate = scope.newScopeUpdate(); scopeUpdate.getBundlesToInstall().add(tb2Info); assertTrue(scopeUpdate.commit()); Bundle b = bundleContext.getBundle(location); assertNotNull(b); Collection<Bundle> bundles = scope.getBundles(); assertEquals(previousSize + 1, bundles.size()); assertTrue(bundles.contains(b)); } @Test public void testCreateChildScope() throws Exception { Scope scope = getScope(); String name = "scope1"; ScopeUpdate parent = scope.newScopeUpdate(); ScopeUpdate child = parent.newChild(name); parent.getChildren().add(child); assertTrue(parent.commit()); Collection<Scope> children = scope.getChildren(); assertEquals(1, children.size()); Scope feature1 = null; for (Scope s : children) { if (name.equals(s.getName())) { feature1 = s; break; } } assertNotNull(feature1); assertEmpty(feature1.getBundles()); assertEmpty(feature1.getChildren()); assertEquals(1, feature1.getId()); assertNull(feature1.getLocation()); assertEquals(name, feature1.getName()); assertEquals(scope, feature1.getParent()); assertEmpty(feature1.getSharePolicies(SharePolicy.TYPE_EXPORT)); assertEmpty(feature1.getSharePolicies(SharePolicy.TYPE_IMPORT)); } }
8,486
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/BundleProvider.java
package org.apache.aries.subsystem.scope.itests; import java.util.Collection; import org.osgi.framework.Bundle; public interface BundleProvider { Bundle getBundle(long id); Collection<Bundle> getBundles(); }
8,487
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/BundleVisibilityTest.java
package org.apache.aries.subsystem.scope.itests; import static org.junit.Assert.assertEquals; 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.net.URL; import java.util.Arrays; import java.util.Collection; import org.apache.aries.subsystem.scope.InstallInfo; import org.apache.aries.subsystem.scope.Scope; import org.apache.aries.subsystem.scope.ScopeUpdate; import org.junit.Test; import org.osgi.framework.Bundle; import org.osgi.framework.ServiceReference; /** * Bundles may only see other bundles within the same scope. The one exception * is the system bundle, which may be seen by all bundles regardless of scope. */ public class BundleVisibilityTest extends AbstractTest { /** * Install a bundle into the same scope as this one. Both bundles should be * able to see each other. * @throws Exception */ @Test public void test1() throws Exception { Scope scope = getScope(); assertTrue(scope.getBundles().contains(bundleContext.getBundle())); ScopeUpdate scopeUpdate = scope.newScopeUpdate(); String location = getBundleLocation("tb-4.jar"); assertNull(bundleContext.getBundle(location)); URL url = new URL(location); InstallInfo installInfo = new InstallInfo(location, url.openStream()); scopeUpdate.getBundlesToInstall().add(installInfo); scopeUpdate.commit(); Bundle bundle = bundleContext.getBundle(location); assertTrue(scope.getBundles().contains(bundle)); bundle.start(); ServiceReference<BundleProvider> bundleProviderRef = bundleContext.getServiceReference(BundleProvider.class); BundleProvider bundleProvider = bundleContext.getService(bundleProviderRef); assertTrue(bundleProvider.getBundles().contains(bundleContext.getBundle())); assertTrue(Arrays.asList(bundleContext.getBundles()).contains(bundle)); assertNotNull(bundleContext.getBundle(bundle.getBundleId())); assertNotNull(bundleProvider.getBundle(bundle.getBundleId())); bundleContext.ungetService(bundleProviderRef); bundle.uninstall(); } /** * Install a bundle into a different scope than this one. Neither bundle * should be able to see the other. * @throws Exception */ @Test public void test2() throws Exception { Scope scope = getScope(); assertTrue(scope.getBundles().contains(bundleContext.getBundle())); ScopeUpdate scopeUpdate = scope.newScopeUpdate(); ScopeUpdate child = scopeUpdate.newChild("tb4"); scopeUpdate.getChildren().add(child); String location = getBundleLocation("tb-4.jar"); assertNull(bundleContext.getBundle(location)); URL url = new URL(location); InstallInfo installInfo = new InstallInfo(location, url.openStream()); child.getBundlesToInstall().add(installInfo); addPackageImportPolicy("org.osgi.framework", child); addPackageImportPolicy("org.apache.aries.subsystem.scope", child); addPackageImportPolicy("org.apache.aries.subsystem.scope.itests", child); addServiceExportPolicy(BundleProvider.class, child); scopeUpdate.commit(); Bundle bundle = bundleContext.getBundle(location); assertNotNull(bundle); Collection<Scope> childScopes = scope.getChildren(); assertEquals(1, childScopes.size()); assertTrue(childScopes.iterator().next().getBundles().contains(bundle)); bundle.start(); ServiceReference<BundleProvider> bundleProviderRef = bundleContext.getServiceReference(BundleProvider.class); BundleProvider bundleProvider = bundleContext.getService(bundleProviderRef); assertFalse(Arrays.asList(bundleContext.getBundles()).contains(bundle)); assertNull(bundleContext.getBundle(bundle.getBundleId())); assertFalse(bundleProvider.getBundles().contains(bundleContext.getBundle())); assertNull(bundleProvider.getBundle(bundleContext.getBundle().getBundleId())); bundleContext.ungetService(bundleProviderRef); bundle.uninstall(); } }
8,488
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/ScopeSecurityTest.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.itests; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.ops4j.pax.exam.CoreOptions.mavenBundle; import static org.ops4j.pax.exam.CoreOptions.options; import static org.ops4j.pax.exam.CoreOptions.systemProperty; import java.net.URL; import java.security.Permission; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import org.apache.aries.itest.AbstractIntegrationTest; import org.apache.aries.subsystem.example.helloIsolation.HelloIsolation; 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.junit.After; import org.junit.Ignore; import org.ops4j.pax.exam.Configuration; import org.ops4j.pax.exam.CoreOptions; import org.ops4j.pax.exam.Option; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; import org.osgi.framework.Filter; import org.osgi.framework.FrameworkUtil; import org.osgi.framework.PackagePermission; import org.osgi.framework.ServiceReference; import org.osgi.framework.wiring.BundleRevision; import org.osgi.service.condpermadmin.ConditionInfo; import org.osgi.service.condpermadmin.ConditionalPermissionAdmin; import org.osgi.service.condpermadmin.ConditionalPermissionInfo; import org.osgi.service.condpermadmin.ConditionalPermissionUpdate; import org.osgi.service.permissionadmin.PermissionInfo; import org.osgi.util.tracker.BundleTracker; @Ignore public class ScopeSecurityTest extends AbstractTest { /* Use @Before not @BeforeClass so as to ensure that these resources * are created in the paxweb temp directory, and not in the svn tree */ static boolean createdApplications = false; BundleTracker bt; int addEventCount; int modifyEventCount; int removeEventCount; private final static PermissionInfo[] adminAllowInfo = { new PermissionInfo("java.security.AllPermission", "*", "*"), new PermissionInfo("java.lang.RuntimePermission", "loadLibrary.*", "*"), new PermissionInfo("java.lang.RuntimePermission", "queuePrintJob", "*"), new PermissionInfo("java.net.SocketPermission", "*", "connect"), new PermissionInfo("java.util.PropertyPermission", "*", "read"), new PermissionInfo("org.osgi.framework.PackagePermission", "*", "exportonly,import"), new PermissionInfo("org.osgi.framework.ServicePermission", "*", "get,register"), new PermissionInfo("org.osgi.framework.AdminPermission", "*", "execute,resolve"), }; @After public void tearDown() throws Exception { if (bt != null) { bt.close(); } } //@Test public void testScopeSecurityWithServiceIsolation() throws Exception { ScopeUpdate su = scope.newScopeUpdate(); ScopeUpdate childScopeUpdate = su.newChild("scope_test1"); // build up installInfo object for the scope InstallInfo info1 = new InstallInfo("helloIsolation", new URL("mvn:org.apache.aries.subsystem.example/org.apache.aries.subsystem.example.helloIsolation/0.4-SNAPSHOT")); InstallInfo info2 = new InstallInfo("helloIsolationRef", new URL("mvn:org.apache.aries.subsystem.example/org.apache.aries.subsystem.example.helloIsolationRef/0.4-SNAPSHOT")); List<InstallInfo> bundlesToInstall = childScopeUpdate.getBundlesToInstall(); bundlesToInstall.add(info1); bundlesToInstall.add(info2); // add bundles to be installed, based on subsystem content su.commit(); // start all bundles in the scope scope_test1 Collection<Bundle> bundlesToStart = childScopeUpdate.getBundles(); for (Bundle b : bundlesToStart) { b.start(); } try { ServiceReference sr = bundleContext.getServiceReference("org.apache.aries.subsystem.example.helloIsolation.HelloIsolation"); fail("should not be able to get the sr for HelloIsolation service"); } catch (Exception ex) { // expected } catch (Error er) { // expected } // test bundle find hooks Bundle[] bundles = bundleContext.getBundles(); for (Bundle b : bundles) { System.out.println("Bundle is " + b.getBundleId() + ": " + b.getSymbolicName()); if (b.getSymbolicName().indexOf("org.apache.aries.subsystem.example.helloIsolation") > -1) { fail("bundles with name starts with org.apache.aries.subsystem.example.helloIsolation should be in a different scope"); } } // test bundle service find hook //ServiceReference sr = bundleContext.getServiceReference(HelloIsolation.class.getName()); //assertNull("sr should be null", sr); Collection<Scope> children = scope.getChildren(); assertEquals(1, children.size()); for (Scope child : children) { if (child.getName().equals("scope_test1")) { Collection<Bundle> buns = child.getBundles(); assertEquals(2, buns.size()); assertEquals(0, child.getChildren().size()); BundleContext childScopebundleContext = null; for (Bundle b : buns) { assertTrue(b.getSymbolicName().indexOf("org.apache.aries.subsystem.example.helloIsolation") > -1); if (b.getSymbolicName().indexOf("org.apache.aries.subsystem.example.helloIsolationRef") > -1) { childScopebundleContext = b.getBundleContext(); } } assertNotNull(childScopebundleContext); ServiceReference sr = childScopebundleContext.getServiceReference("org.apache.aries.subsystem.example.helloIsolation.HelloIsolation"); assertNotNull("sr is not null", sr); System.out.println("got the sr, go get service next"); Object obj = childScopebundleContext.getService(sr); //HelloIsolation hi = (HelloIsolation)childScopebundleContext.getService(sr); } } // install a test bundle in the root scope URL url = new URL("mvn:org.apache.felix/org.apache.felix.fileinstall/2.0.8"); bundleContext.installBundle("org.apache.felix.fileinstall-rootScope", url.openStream()); // remove child scope su = scope.newScopeUpdate(); Collection<ScopeUpdate> scopes = su.getChildren(); // obtain child scope admin from service registry // String filter = "ScopeName=scope_test1"; Scope childScopeAdmin = childScopeUpdate.getScope(); assertEquals(scope, childScopeAdmin.getParent()); scopes.remove(childScopeUpdate); su.commit(); assertFalse(scope.getChildren().contains(childScopeAdmin)); su = scope.newScopeUpdate(); assertFalse(su.getChildren().contains(childScopeUpdate)); // childScopeAdmin = null; // try { // childScopeAdmin = getOsgiService(Scope.class, filter, DEFAULT_TIMEOUT); // } catch (Exception ex) { // // ignore // } // assertNull("scope admin service for the scope should be unregistered", childScopeAdmin); } //@Test public void testScopeSecurityWithServiceShared() throws Exception { SecurityManager security = System.getSecurityManager(); assertNotNull("Security manager should not be null", security); Bundle[] bundles = bundleContext.getBundles(); for (Bundle b : bundles) { // set up condition permission for scope if (b.getSymbolicName().indexOf("subsystem.scope.impl") > -1) { ServiceReference permRef = bundleContext.getServiceReference(ConditionalPermissionAdmin.class.getName()); ConditionalPermissionAdmin permAdmin = (ConditionalPermissionAdmin) bundleContext.getService(permRef); ConditionalPermissionUpdate update = permAdmin.newConditionalPermissionUpdate(); List<ConditionalPermissionInfo> infos = update.getConditionalPermissionInfos(); //infos.clear(); // set up the conditionInfo ConditionInfo[] conditionInfo = new ConditionInfo[] {new ConditionInfo("org.osgi.service.condpermadmin.BundleLocationCondition", new String[]{b.getLocation()})}; // Set up permissions which are common to all applications infos.add(permAdmin.newConditionalPermissionInfo(null, conditionInfo, adminAllowInfo, "allow")); update.commit(); } } ScopeUpdate su = scope.newScopeUpdate(); ScopeUpdate childScopeUpdate = su.newChild("scope_test1"); Map<String, List<SharePolicy>> sharePolicies = childScopeUpdate.getSharePolicies(SharePolicy.TYPE_EXPORT); final Filter filter1 = FrameworkUtil.createFilter( "(&" + "(osgi.package=org.apache.aries.subsystem.example.helloIsolation)" + ")"); final Filter filter2 = FrameworkUtil.createFilter( "(&" + "(osgi.service=org.apache.aries.subsystem.example.helloIsolation.HelloIsolation)" + ")"); List<SharePolicy> packagePolicies = sharePolicies.get(BundleRevision.PACKAGE_NAMESPACE); if (packagePolicies == null) { packagePolicies = new ArrayList<SharePolicy>(); sharePolicies.put(BundleRevision.PACKAGE_NAMESPACE, packagePolicies); } packagePolicies.add(new SharePolicy(SharePolicy.TYPE_EXPORT, BundleRevision.PACKAGE_NAMESPACE, filter1)); List<SharePolicy> servicePolicies = sharePolicies.get("scope.share.service"); if (servicePolicies == null) { servicePolicies = new ArrayList<SharePolicy>(); sharePolicies.put("scope.share.service", servicePolicies); } servicePolicies.add(new SharePolicy(SharePolicy.TYPE_EXPORT, "scope.share.service", filter2)); // build up installInfo object for the scope InstallInfo info1 = new InstallInfo("helloIsolation", new URL("mvn:org.apache.aries.subsystem.example/org.apache.aries.subsystem.example.helloIsolation/0.4-SNAPSHOT")); InstallInfo info2 = new InstallInfo("helloIsolationRef", new URL("mvn:org.apache.aries.subsystem.example/org.apache.aries.subsystem.example.helloIsolationRef/0.4-SNAPSHOT")); List<InstallInfo> bundlesToInstall = childScopeUpdate.getBundlesToInstall(); bundlesToInstall.add(info1); bundlesToInstall.add(info2); // add bundles to be installed, based on subsystem content su.commit(); // start all bundles in the scope scope_test1 Collection<Bundle> bundlesToStart = childScopeUpdate.getBundles(); for (Bundle b : bundlesToStart) { b.start(); } try { ServiceReference sr = bundleContext.getServiceReference("org.apache.aries.subsystem.example.helloIsolation.HelloIsolation"); fail("should not be able to get the sr for HelloIsolation service"); } catch (Exception ex) { // expected } catch (Error er) { // expected } // test bundle find hooks bundles = bundleContext.getBundles(); for (Bundle b : bundles) { System.out.println("Bundle is " + b.getBundleId() + ": " + b.getSymbolicName()); if (b.getSymbolicName().indexOf("org.apache.aries.subsystem.example.helloIsolation") > -1) { fail("bundles with name starts with org.apache.aries.subsystem.example.helloIsolation should be in a different scope"); } } // test bundle service find hook //ServiceReference sr = bundleContext.getServiceReference(HelloIsolation.class.getName()); //assertNull("sr should be null", sr); Collection<Scope> children = scope.getChildren(); assertEquals(1, children.size()); for (Scope child : children) { if (child.getName().equals("scope_test1")) { Collection<Bundle> buns = child.getBundles(); assertEquals(2, buns.size()); assertEquals(0, child.getChildren().size()); BundleContext childScopebundleContext = null; for (Bundle b : buns) { assertTrue(b.getSymbolicName().indexOf("org.apache.aries.subsystem.example.helloIsolation") > -1); if (b.getSymbolicName().indexOf("org.apache.aries.subsystem.example.helloIsolationRef") > -1) { childScopebundleContext = b.getBundleContext(); } } assertNotNull(childScopebundleContext); ServiceReference sr = childScopebundleContext.getServiceReference("org.apache.aries.subsystem.example.helloIsolation.HelloIsolation"); assertNotNull("sr is not null", sr); System.out.println("got the sr, go get service next"); HelloIsolation hi = (HelloIsolation)childScopebundleContext.getService(sr); hi.hello(); Permission permission = new PackagePermission("*", PackagePermission.IMPORT); hi.checkPermission(permission); } } // install a test bundle in the root scope URL url = new URL("mvn:org.apache.felix/org.apache.felix.fileinstall/2.0.8"); bundleContext.installBundle("org.apache.felix.fileinstall-rootScope", url.openStream()); // remove child scope su = scope.newScopeUpdate(); Collection<ScopeUpdate> scopes = su.getChildren(); // obtain child scope admin from service registry // String filter = "ScopeName=scope_test1"; Scope childScopeAdmin = childScopeUpdate.getScope(); assertEquals(scope, childScopeAdmin.getParent()); scopes.remove(childScopeUpdate); su.commit(); assertFalse(scope.getChildren().contains(childScopeAdmin)); su = scope.newScopeUpdate(); assertFalse(su.getChildren().contains(childScopeUpdate)); // childScopeAdmin = null; // try { // childScopeAdmin = getOsgiService(Scope.class, filter, DEFAULT_TIMEOUT); // } catch (Exception ex) { // // ignore // } // assertNull("scope admin service for the scope should be unregistered", childScopeAdmin); } @Configuration public Option[] configuration() { return options( baseOptions(), // Bundles mavenBundle("org.apache.aries.testsupport", "org.apache.aries.testsupport.unit"), mavenBundle("org.apache.aries.application", "org.apache.aries.application.api"), mavenBundle("org.apache.aries", "org.apache.aries.util"), mavenBundle("org.apache.aries.application", "org.apache.aries.application.utils"), mavenBundle("org.apache.felix", "org.apache.felix.bundlerepository"), mavenBundle("org.apache.aries.subsystem", "org.apache.aries.subsystem.api"), mavenBundle("org.apache.aries.subsystem", "org.apache.aries.subsystem.scope.api"), mavenBundle("org.apache.aries.subsystem", "org.apache.aries.subsystem.scope.impl") // uncomment the following line if you want to turn on security. the policy file can be found in src/test/resources dir and you want to update the value of -Djava.security.policy to // the exact location of the policy file. //org.ops4j.pax.exam.container.def.PaxRunnerOptions.vmOption("-Declipse.security=osgi -Djava.security.policy=/policy"), ); } }
8,489
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/PersistenceTest.java
package org.apache.aries.subsystem.scope.itests; import static org.junit.Assert.assertEquals; 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.net.URL; import java.util.Arrays; 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.junit.Ignore; import org.junit.Test; import org.osgi.framework.Bundle; public class PersistenceTest extends AbstractTest { /** * When starting from a clean slate (i.e. nothing was persisted), only the * root scope with its default configuration should exist. * * @throws Exception */ @Test public void test1() throws Exception { Scope scope = getScope(); assertEquals(0, scope.getId()); assertEquals("root", scope.getName()); assertEquals(null, scope.getLocation()); assertEquals(null, scope.getParent()); assertEquals(0, scope.getChildren().size()); assertCollectionEquals(Arrays.asList(bundleContext.getBundles()), scope.getBundles()); assertEquals(0, scope.getSharePolicies(SharePolicy.TYPE_EXPORT).size()); assertEquals(0, scope.getSharePolicies(SharePolicy.TYPE_IMPORT).size()); } /** * Stopping and starting the Scope Admin bundle should cause it to pull * from the persistent storage. If nothing changed after the original * bundle start, the persisted root bundle should look exactly the same * as before. * * @throws Exception */ @Test public void test2() throws Exception { Scope scope = getScope(); Bundle bundle = findBundle("org.apache.aries.subsystem.scope.impl"); assertNotNull(bundle); bundle.stop(); bundle.start(); assertEquals(0, scope.getId()); assertEquals("root", scope.getName()); assertEquals(null, scope.getLocation()); assertEquals(null, scope.getParent()); assertEquals(0, scope.getChildren().size()); assertCollectionEquals(Arrays.asList(bundleContext.getBundles()), scope.getBundles()); assertEquals(0, scope.getSharePolicies(SharePolicy.TYPE_EXPORT).size()); assertEquals(0, scope.getSharePolicies(SharePolicy.TYPE_IMPORT).size()); } /** * A scope's persisted bundle data will become stale if bundles are * installed or uninstalled while Scope Admin is not connected to the * environment. This should be detected and dealt with. * * @throws Exception */ @Test @Ignore public void test3() throws Exception { Scope scope = getScope(); Bundle tb1 = findBundle("org.apache.aries.subsystem.scope.itests.tb1", scope); assertNull(tb1); tb1 = installBundle("tb-1.jar"); assertTrue(scope.getBundles().contains(tb1)); Bundle scopeAdmin = findBundle("org.apache.aries.subsystem.scope.impl"); assertNotNull(scopeAdmin); scopeAdmin.stop(); scopeAdmin.start(); scope = getScope(); assertTrue(scope.getBundles().contains(tb1)); scopeAdmin.stop(); tb1.uninstall(); Bundle tb2 = findBundle("org.apache.aries.subsystem.scope.itests.tb2", scope); assertNull(tb2); tb2 = installBundle("tb-2.jar"); scopeAdmin.start(); scope = getScope(); assertFalse(scope.getBundles().contains(tb1)); assertTrue(scope.getBundles().contains(tb2)); tb2.uninstall(); assertFalse(scope.getBundles().contains(tb2)); } /** * Create two scopes off of the root scope with the following structure. * * R * / \ * S1 S2 * * S1 contains bundle tb1, one import policy, and one export policy. * S2 contains bundle tb2 and two import policies. * * This configuration should persist between restarts of the Scope Admin * bundle. * * @throws Exception */ @Test public void test4() throws Exception { Scope root = getScope(); ScopeUpdate rootUpdate = root.newScopeUpdate(); ScopeUpdate s1Update = rootUpdate.newChild("S1"); rootUpdate.getChildren().add(s1Update); ScopeUpdate s2Update = rootUpdate.newChild("S2"); rootUpdate.getChildren().add(s2Update); s1Update.getBundlesToInstall().add( new InstallInfo( null, new URL(getBundleLocation("tb-1.jar")))); s2Update.getBundlesToInstall().add( new InstallInfo( null, new URL(getBundleLocation("tb-2.jar")))); addPackageImportPolicy("org.osgi.framework", s1Update); addPackageExportPolicy("org.apache.aries.subsystem.scope.itests.tb1", s1Update); addPackageImportPolicy("org.osgi.framework", s2Update); addPackageImportPolicy("org.apache.aries.subsystem.scope.itests.tb1", s2Update); assertTrue(rootUpdate.commit()); root = getScope(); assertEquals(2, root.getChildren().size()); Scope s1 = findChildScope("S1", root); Bundle tb1 = findBundle("org.apache.aries.subsystem.scope.itests.tb1", s1); assertNotNull(tb1); assertTrue(s1.getBundles().contains(tb1)); assertEquals(1, s1.getSharePolicies(SharePolicy.TYPE_IMPORT).get("osgi.wiring.package").size()); assertEquals(1, s1.getSharePolicies(SharePolicy.TYPE_EXPORT).get("osgi.wiring.package").size()); Scope s2 = findChildScope("S2", root); Bundle tb2 = findBundle("org.apache.aries.subsystem.scope.itests.tb2", s2); assertNotNull(tb2); assertTrue(s2.getBundles().contains(tb2)); assertEquals(2, s2.getSharePolicies(SharePolicy.TYPE_IMPORT).get("osgi.wiring.package").size()); Bundle scopeAdmin = findBundle("org.apache.aries.subsystem.scope.impl"); assertNotNull(scopeAdmin); scopeAdmin.stop(); scopeAdmin.start(); root = getScope(); assertEquals(2, root.getChildren().size()); s1 = findChildScope("S1", root); assertTrue(s1.getBundles().contains(tb1)); assertEquals(1, s1.getSharePolicies(SharePolicy.TYPE_IMPORT).get("osgi.wiring.package").size()); assertEquals(1, s1.getSharePolicies(SharePolicy.TYPE_EXPORT).get("osgi.wiring.package").size()); s2 = findChildScope("S2", root); assertTrue(s2.getBundles().contains(tb2)); assertEquals(2, s2.getSharePolicies(SharePolicy.TYPE_IMPORT).get("osgi.wiring.package").size()); } }
8,490
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/ServiceVisibilityTest.java
package org.apache.aries.subsystem.scope.itests; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.net.URL; import org.apache.aries.subsystem.scope.InstallInfo; import org.apache.aries.subsystem.scope.ScopeUpdate; import org.junit.Test; import org.osgi.framework.Bundle; import org.osgi.framework.ServiceReference; /** * Bundles may only see other services registered by other bundles within the * same scope. The one exception is the system bundle, whose services may be * seen by all bundles regardless of scope. */ public class ServiceVisibilityTest extends AbstractTest { /** * Install a bundle registering a service into the same scope as this one. * This bundle should be able to see the service. * @throws Exception */ @Test public void test1() throws Exception { assertTrue(getScope().getBundles().contains(bundleContext.getBundle())); ScopeUpdate scopeUpdate = getScope().newScopeUpdate(); String location = getBundleLocation("tb-7.jar"); assertNull(bundleContext.getBundle(location)); URL url = new URL(location); InstallInfo installInfo = new InstallInfo(location, url.openStream()); scopeUpdate.getBundlesToInstall().add(installInfo); scopeUpdate.commit(); Bundle bundle = bundleContext.getBundle(location); assertNotNull(bundle); assertTrue(getScope().getBundles().contains(bundle)); bundle.start(); ServiceReference<Service> serviceRef = bundleContext.getServiceReference(Service.class); assertNotNull(serviceRef); Service service = bundleContext.getService(serviceRef); assertNotNull(service); bundleContext.ungetService(serviceRef); bundle.uninstall(); } /** * Install a bundle registering a service into a different scope than this * one. This bundle should not be able to see the service. * @throws Exception */ @Test public void test2() throws Exception { assertTrue(getScope().getBundles().contains(bundleContext.getBundle())); String location = getBundleLocation("tb-7.jar"); assertNull(bundleContext.getBundle(location)); URL url = new URL(location); InstallInfo installInfo = new InstallInfo(location, url.openStream()); ScopeUpdate scopeUpdate = getScope().newScopeUpdate(); ScopeUpdate child = scopeUpdate.newChild("tb7"); scopeUpdate.getChildren().add(child); child.getBundlesToInstall().add(installInfo); addPackageImportPolicy("org.osgi.framework", child); addPackageImportPolicy("org.apache.aries.subsystem.scope.itests", child); scopeUpdate.commit(); Bundle bundle = bundleContext.getBundle(location); assertNotNull(bundle); assertTrue(child.getScope().getBundles().contains(bundle)); bundle.start(); ServiceReference<Service> serviceRef = bundleContext.getServiceReference(Service.class); assertNull(serviceRef); bundle.uninstall(); } }
8,491
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/ScopeAdminTest.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.itests; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import org.apache.aries.subsystem.example.helloIsolation.HelloIsolation; 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.junit.After; import org.junit.Ignore; import org.junit.Test; import org.osgi.framework.Bundle; import org.osgi.framework.BundleEvent; import org.osgi.framework.BundleException; import org.osgi.framework.Filter; import org.osgi.framework.FrameworkUtil; import org.osgi.framework.InvalidSyntaxException; import org.osgi.framework.ServiceReference; import org.osgi.framework.wiring.BundleRevision; import org.osgi.util.tracker.BundleTracker; import org.osgi.util.tracker.BundleTrackerCustomizer; public class ScopeAdminTest extends AbstractTest { /* Use @Before not @BeforeClass so as to ensure that these resources * are created in the paxweb temp directory, and not in the svn tree */ static boolean createdApplications = false; BundleTracker bt; int addEventCount; int modifyEventCount; int removeEventCount; @After public void tearDown() throws Exception { if (bt != null) { bt.close(); } } @Test public void testBundleServiceIsolation() throws Exception { // make sure we are using a framework that provides composite admin service assertNotNull("scope admin should not be null", scope); System.out.println("able to get scope admin service"); bt = new BundleTracker(bundleContext, Bundle.INSTALLED | Bundle.UNINSTALLED | Bundle.ACTIVE, new BundleTrackerCustomizer() { public synchronized Object addingBundle(Bundle bundle, BundleEvent event) { if (event == null) { System.out.println("ScopeAdminTest - adding Bundle: " + bundle.getSymbolicName() + " event: null"); } else { System.out.println("ScopeAdminTest - adding Bundle: " + bundle.getSymbolicName() + " event: " + event.getType()); addEventCount++; } return bundle; } public synchronized void modifiedBundle(Bundle bundle, BundleEvent event, Object object) { if (event == null) { System.out.println("ScopeAdminTest - modifying Bundle: " + bundle.getSymbolicName() + " event: null"); } else { System.out.println("ScopeAdminTest - modifying Bundle: " + bundle.getSymbolicName() + " event: " + event.getType()); modifyEventCount++; } } public synchronized void removedBundle(Bundle bundle, BundleEvent event, Object object) { if (event == null) { System.out.println("ScopeAdminTest - removing Bundle: " + bundle.getSymbolicName() + " event: null"); } else { System.out.println("ScopeAdminTest - removing Bundle: " + bundle.getSymbolicName() + " event: " + event.getType()); removeEventCount++; } } }); bt.open(); ScopeUpdate su = scope.newScopeUpdate(); ScopeUpdate childScopeUpdate = su.newChild("scope_test1"); su.getChildren().add(childScopeUpdate); addPackageImportPolicy("org.osgi.framework", childScopeUpdate); addPackageImportPolicy("org.osgi.util.tracker", childScopeUpdate); // build up installInfo object for the scope InstallInfo info1 = new InstallInfo("helloIsolation", new URL("mvn:org.apache.aries.subsystem/org.apache.aries.subsystem.example.helloIsolation/0.1-SNAPSHOT")); InstallInfo info2 = new InstallInfo("helloIsolationRef", new URL("mvn:org.apache.aries.subsystem/org.apache.aries.subsystem.example.helloIsolationRef/0.1-SNAPSHOT")); List<InstallInfo> bundlesToInstall = childScopeUpdate.getBundlesToInstall(); bundlesToInstall.add(info1); bundlesToInstall.add(info2); // add bundles to be installed, based on subsystem content su.commit(); assertEquals("add event count should be 0 since 0 bundles are installed in root scope", 0, addEventCount); assertEquals("modify event count should be 0", 0, modifyEventCount); assertEquals("remove event count should be 0", 0, removeEventCount); // start all bundles in the scope scope_test1 Collection<Bundle> bundlesToStart = childScopeUpdate.getScope().getBundles(); for (Bundle b : bundlesToStart) { b.start(); } assertEquals("add event count should be 0 since 0 bundles are installed in root scope", 0, addEventCount); assertEquals("modify event count should be 0", 0, modifyEventCount); assertEquals("remove event count should be 0", 0, removeEventCount); try { ServiceReference sr = bundleContext.getServiceReference(HelloIsolation.class.getName()); fail("should not be able to get the sr for HelloIsolation service"); } catch (Exception ex) { // expected } catch (Error er) { // expected } // test bundle find hooks Bundle[] bundles = bundleContext.getBundles(); for (Bundle b : bundles) { System.out.println("Bundle is " + b.getBundleId() + ": " + b.getSymbolicName()); if (b.getSymbolicName().indexOf("org.apache.aries.subsystem.example.helloIsolation") > -1) { fail("bundles with name starts with org.apache.aries.subsystem.example.helloIsolation should be in a different scope"); } } // test bundle service find hook //ServiceReference sr = bundleContext.getServiceReference(HelloIsolation.class.getName()); //assertNull("sr should be null", sr); Collection<Scope> children = scope.getChildren(); assertEquals(1, children.size()); for (Scope child : children) { if (child.getName().equals("scope_test1")) { Collection<Bundle> buns = child.getBundles(); assertEquals(2, buns.size()); assertEquals(0, child.getChildren().size()); for (Bundle b : buns) { assertTrue(b.getSymbolicName().indexOf("org.apache.aries.subsystem.example.helloIsolation") > -1); } } } // install a test bundle in the root scope URL url = new URL("mvn:org.apache.felix/org.apache.felix.fileinstall/2.0.8"); bundleContext.installBundle("org.apache.felix.fileinstall-rootScope", url.openStream()); assertEquals("add event count should be 1 since 1 bundles are installed", 1, addEventCount); assertEquals("modify event count should be 0", 0, modifyEventCount); assertEquals("remove event count should be 0", 0, removeEventCount); // remove child scope su = scope.newScopeUpdate(); // Collection<Scope> scopes = su.getToBeRemovedChildren(); Collection<ScopeUpdate> scopes = su.getChildren(); childScopeUpdate = scopes.iterator().next(); // obtain child scope admin from service registry // String filter = "ScopeName=scope_test1"; // Scope childscope = getOsgiService(Scope.class, filter, DEFAULT_TIMEOUT); Scope childScopeAdmin = childScopeUpdate.getScope(); assertEquals(scope, childScopeAdmin.getParent()); // scopes.add(childScopeAdmin); scopes.remove(childScopeUpdate); su.commit(); assertFalse(scope.getChildren().contains(childScopeAdmin)); su = scope.newScopeUpdate(); assertFalse(su.getChildren().contains(childScopeUpdate)); // childScopeAdmin = null; // try { // childScopeAdmin = getOsgiService(Scope.class, filter, DEFAULT_TIMEOUT); // } catch (Exception ex) { // // ignore // } // assertNull("scope admin service for the scope should be unregistered", childScopeAdmin); } @Test @Ignore public void testPackageIsolation() throws Exception { // make sure we are using a framework that provides composite admin service assertNotNull("scope admin should not be null", scope); System.out.println("able to get scope admin service"); ScopeUpdate su = scope.newScopeUpdate(); ScopeUpdate childScopeUpdate = su.newChild("scope_test1"); su.getChildren().add(childScopeUpdate); addPackageImportPolicy("org.osgi.framework", childScopeUpdate); addPackageImportPolicy("org.osgi.util.tracker", childScopeUpdate); // build up installInfo object for the scope InstallInfo info1 = new InstallInfo("helloIsolation", new URL("mvn:org.apache.aries.subsystem/org.apache.aries.subsystem.example.helloIsolation/0.1-SNAPSHOT")); InstallInfo info2 = new InstallInfo("helloIsolationRef", new URL("mvn:org.apache.aries.subsystem/org.apache.aries.subsystem.example.helloIsolationRef/0.1-SNAPSHOT")); List<InstallInfo> bundlesToInstall = childScopeUpdate.getBundlesToInstall(); bundlesToInstall.add(info1); bundlesToInstall.add(info2); // add bundles to be installed, based on subsystem content su.commit(); // start all bundles in the scope scope_test1 Collection<Bundle> bundlesToStart = childScopeUpdate.getScope().getBundles(); for (Bundle b : bundlesToStart) { b.start(); } // install helloIsolationRef1 bundle in the root scope URL url1 = new URL("mvn:org.apache.aries.subsystem/org.apache.aries.subsystem.example.helloIsolationRef/0.1-SNAPSHOT"); Bundle helloIsolationRef = bundleContext.installBundle("helloIsolationRef1-rootScope", url1.openStream()); try { helloIsolationRef.start(); fail("should not be able to start helloIsolationRef since missing import packages"); } catch (Exception ex) { // expect resolving error } URL url2 = new URL("mvn:org.apache.aries.subsystem/org.apache.aries.subsystem.example.helloIsolation/0.1-SNAPSHOT"); Bundle helloIsolation = bundleContext.installBundle("helloIsolation1-rootScope", url2.openStream()); helloIsolation.start(); // should be able to start the bundle now. helloIsolationRef.start(); // remove helloIsolationRef & helloIsolation helloIsolationRef.uninstall(); helloIsolation.uninstall(); // remove child scope su = scope.newScopeUpdate(); // Collection<Scope> scopes = su.getToBeRemovedChildren(); Collection<ScopeUpdate> scopes = su.getChildren(); childScopeUpdate = scopes.iterator().next(); // obtain child scope admin from service registry // String filter = "ScopeName=scope_test1"; // Scope childScopeAdmin = getOsgiService(Scope.class, filter, DEFAULT_TIMEOUT); Scope childScopeAdmin = childScopeUpdate.getScope(); assertEquals(scope, childScopeAdmin.getParent()); // scopes.add(childScopeAdmin); scopes.remove(childScopeUpdate); su.commit(); assertFalse(scope.getChildren().contains(childScopeAdmin)); su = scope.newScopeUpdate(); assertFalse(su.getChildren().contains(childScopeUpdate)); // childScopeAdmin = null; // try { // childScopeAdmin = getOsgiService(Scope.class, filter, DEFAULT_TIMEOUT); // } catch (Exception ex) { // // ignore // } // assertNull("scope admin service for the scope should be unregistered", childScopeAdmin); } // test sharing the helloIsolation package from the test scope. @Test @Ignore public void testPackageSharingFromTestScope() throws Exception { // make sure we are using a framework that provides composite admin service assertNotNull("scope admin should not be null", scope); System.out.println("able to get scope admin service"); ScopeUpdate su = scope.newScopeUpdate(); ScopeUpdate childScopeUpdate = su.newChild("scope_test1"); su.getChildren().add(childScopeUpdate); addPackageImportPolicy("org.osgi.framework", childScopeUpdate); addPackageImportPolicy("org.osgi.util.tracker", childScopeUpdate); Map<String, List<SharePolicy>> sharePolicies = childScopeUpdate.getSharePolicies(SharePolicy.TYPE_EXPORT); final Filter filter1 = FrameworkUtil.createFilter( "(&" + "(osgi.wiring.package=org.apache.aries.subsystem.example.helloIsolation)" + ")"); final Filter filter2 = FrameworkUtil.createFilter( "(&" + "(scope.share.service=org.apache.aries.subsystem.example.helloIsolation.HelloIsolation)" + ")"); List<SharePolicy> packagePolicies = sharePolicies.get(BundleRevision.PACKAGE_NAMESPACE); if (packagePolicies == null) { packagePolicies = new ArrayList<SharePolicy>(); sharePolicies.put(BundleRevision.PACKAGE_NAMESPACE, packagePolicies); } packagePolicies.add(new SharePolicy(SharePolicy.TYPE_EXPORT, BundleRevision.PACKAGE_NAMESPACE, filter1)); List<SharePolicy> servicePolicies = sharePolicies.get("scope.share.service"); if (servicePolicies == null) { servicePolicies = new ArrayList<SharePolicy>(); sharePolicies.put("scope.share.service", servicePolicies); } servicePolicies.add(new SharePolicy(SharePolicy.TYPE_EXPORT, "scope.share.service", filter2)); // build up installInfo object for the scope InstallInfo info1 = new InstallInfo("helloIsolation", new URL("mvn:org.apache.aries.subsystem/org.apache.aries.subsystem.example.helloIsolation/0.1-SNAPSHOT")); InstallInfo info2 = new InstallInfo("helloIsolationRef", new URL("mvn:org.apache.aries.subsystem/org.apache.aries.subsystem.example.helloIsolationRef/0.1-SNAPSHOT")); List<InstallInfo> bundlesToInstall = childScopeUpdate.getBundlesToInstall(); bundlesToInstall.add(info1); bundlesToInstall.add(info2); // add bundles to be installed, based on subsystem content su.commit(); // start all bundles in the scope scope_test1 Collection<Bundle> bundlesToStart = childScopeUpdate.getScope().getBundles(); for (Bundle b : bundlesToStart) { b.start(); } // install helloIsolationRef1 bundle in the root scope URL url1 = new URL("mvn:org.apache.aries.subsystem/org.apache.aries.subsystem.example.helloIsolationRef/0.1-SNAPSHOT"); Bundle helloIsolationRef = bundleContext.installBundle("helloIsolationRef1-rootScope", url1.openStream()); try { helloIsolationRef.start(); } catch (Exception ex) { fail("should be able to start helloIsolationRef by import packages from scope_test1"); } // remove helloIsolationRef helloIsolationRef.uninstall(); // remove child scope su = scope.newScopeUpdate(); Collection<ScopeUpdate> scopes = su.getChildren(); childScopeUpdate = scopes.iterator().next(); // obtain child scope admin from service registry // String filter = "ScopeName=scope_test1"; Scope childScopeAdmin = childScopeUpdate.getScope(); assertEquals(scope, childScopeAdmin.getParent()); scopes.remove(childScopeUpdate); su.commit(); assertFalse(scope.getChildren().contains(childScopeAdmin)); su = scope.newScopeUpdate(); assertFalse(su.getChildren().contains(childScopeUpdate)); // childScopeAdmin = null; // try { // childScopeAdmin = getOsgiService(Scope.class, filter, DEFAULT_TIMEOUT); // } catch (Exception ex) { // // ignore // } // assertNull("scope admin service for the scope should be unregistered", childScopeAdmin); } // test sharing the helloIsolation package & service from the root scope. @Test public void testPackageSharingFromRootScope() throws Exception { // install helloIsolationRef1 bundle in the root scope URL url1 = new URL("mvn:org.apache.aries.subsystem/org.apache.aries.subsystem.example.helloIsolation/0.1-SNAPSHOT"); Bundle helloIsolation = bundleContext.installBundle("helloIsolation1-rootScope", url1.openStream()); try { helloIsolation.start(); } catch (Exception ex) { fail("should be able to start helloIsolation"); } // make sure we are using a framework that provides composite admin service ScopeUpdate su = scope.newScopeUpdate(); ScopeUpdate childScopeUpdate = su.newChild("scope_test1"); su.getChildren().add(childScopeUpdate); addPackageImportPolicy("org.osgi.framework", childScopeUpdate); Map<String, List<SharePolicy>> sharePolicies = childScopeUpdate.getSharePolicies(SharePolicy.TYPE_IMPORT); final Filter filter1 = FrameworkUtil.createFilter( "(&" + "(osgi.wiring.package=org.apache.aries.subsystem.example.helloIsolation)" + ")"); final Filter filter2 = FrameworkUtil.createFilter( "(&" + "(scope.share.service=org.apache.aries.subsystem.example.helloIsolation.HelloIsolation)" + ")"); List<SharePolicy> packagePolicies = sharePolicies.get(BundleRevision.PACKAGE_NAMESPACE); if (packagePolicies == null) { packagePolicies = new ArrayList<SharePolicy>(); sharePolicies.put(BundleRevision.PACKAGE_NAMESPACE,packagePolicies); } packagePolicies.add(new SharePolicy(SharePolicy.TYPE_IMPORT, BundleRevision.PACKAGE_NAMESPACE, filter1)); List<SharePolicy> servicePolicies = sharePolicies.get("scope.share.service"); if (servicePolicies == null) { servicePolicies = new ArrayList<SharePolicy>(); sharePolicies.put("scope.share.service", servicePolicies); } servicePolicies.add(new SharePolicy(SharePolicy.TYPE_IMPORT, "scope.share.service", filter2)); // build up installInfo object for the scope InstallInfo info2 = new InstallInfo("helloIsolationRef", new URL("mvn:org.apache.aries.subsystem/org.apache.aries.subsystem.example.helloIsolationRef/0.1-SNAPSHOT")); List<InstallInfo> bundlesToInstall = childScopeUpdate.getBundlesToInstall(); bundlesToInstall.add(info2); // add bundles to be installed, based on subsystem content su.commit(); // start all bundles in the scope scope_test1 Collection<Bundle> bundlesToStart = childScopeUpdate.getScope().getBundles(); for (Bundle b : bundlesToStart) { try { b.start(); } catch (Exception ex) { ex.printStackTrace(); fail("should be able to start helloIsolationRef in scope_test1"); } } // remove helloIsolation in root scope helloIsolation.uninstall(); // remove child scope su = scope.newScopeUpdate(); Collection<ScopeUpdate> scopes = su.getChildren(); childScopeUpdate = scopes.iterator().next(); // obtain child scope admin from service registry // String filter = "ScopeName=scope_test1"; Scope childScopeAdmin = childScopeUpdate.getScope(); assertEquals(scope, childScopeAdmin.getParent()); scopes.remove(childScopeUpdate); su.commit(); assertFalse(scope.getChildren().contains(childScopeAdmin)); su = scope.newScopeUpdate(); assertFalse(su.getChildren().contains(childScopeUpdate)); // childScopeAdmin = null; // try { // childScopeAdmin = getOsgiService(Scope.class, filter, DEFAULT_TIMEOUT); // } catch (Exception ex) { // // ignore // } // assertNull("scope admin service for the scope should be unregistered", childScopeAdmin); } // test ability to select the helloIsolation package from which scope it wants to use // not necessarily the highest version one by default. @Test @Ignore public void testScopeAffinity() throws Exception { // install helloIsolation 0.3 in scope_test1 Scope scope1 = createScope(scope, "scope_test1", "mvn:org.apache.aries.subsystem/org.apache.aries.subsystem.example.helloIsolation/0.1-SNAPSHOT", "0.3"); // install helloIsolation 2.0 in scope_test2 Scope scope2 = createScope(scope, "scope_test2", "mvn:org.apache.aries.subsystem/org.apache.aries.subsystem.example.helloIsolation/0.1-SNAPSHOT", "2.0"); // install helloIsolationRef 2.0 in scope_test3 ScopeUpdate su = scope.newScopeUpdate(); ScopeUpdate childScopeUpdate = su.newChild("scope_test3"); su.getChildren().add(childScopeUpdate); addPackageImportPolicy("org.osgi.framework", childScopeUpdate); Scope scope3 = childScopeUpdate.getScope(); Map<String, List<SharePolicy>> sharePolicies = childScopeUpdate.getSharePolicies(SharePolicy.TYPE_IMPORT); /*final Filter filter1 = FrameworkUtil.createFilter( "(&" + "(osgi.package=org.apache.aries.subsystem.example.helloIsolation)" + "(bundle-symbolic-name=org.apache.aries.subsystem.example.helloIsolation)" + "(bundle-version<=1.1)" + ")");*/ final Filter filter1 = FrameworkUtil.createFilter( "(&" + "(osgi.wiring.package=org.apache.aries.subsystem.example.helloIsolation)" + //"(scopeName=scope_test1)" + ")"); final Filter filter2 = FrameworkUtil.createFilter( "(&" + "(scope.share.service=org.apache.aries.subsystem.example.helloIsolation.HelloIsolation)" + ")"); List<SharePolicy> packagePolicies = sharePolicies.get(BundleRevision.PACKAGE_NAMESPACE); if (packagePolicies == null) { packagePolicies = new ArrayList<SharePolicy>(); sharePolicies.put(BundleRevision.PACKAGE_NAMESPACE,packagePolicies); } packagePolicies.add(new SharePolicy(SharePolicy.TYPE_IMPORT, BundleRevision.PACKAGE_NAMESPACE, filter1)); List<SharePolicy> servicePolicies = sharePolicies.get("scope.share.service"); if (servicePolicies == null) { servicePolicies = new ArrayList<SharePolicy>(); sharePolicies.put("scope.share.service", servicePolicies); } servicePolicies.add(new SharePolicy(SharePolicy.TYPE_IMPORT, "scope.share.service", filter2)); // build up installInfo object for the scope InstallInfo info2 = new InstallInfo("helloIsolationRef", new URL("mvn:org.apache.aries.subsystem/org.apache.aries.subsystem.example.helloIsolationRef/0.1-SNAPSHOT")); List<InstallInfo> bundlesToInstall = childScopeUpdate.getBundlesToInstall(); bundlesToInstall.add(info2); // add bundles to be installed, based on subsystem content su.commit(); // start all bundles in the scope scope_test3 Collection<Bundle> bundlesToStart = childScopeUpdate.getScope().getBundles(); for (Bundle b : bundlesToStart) { try { b.start(); } catch (Exception ex) { ex.printStackTrace(); fail("should be able to start helloIsolationRef in scope_test1"); } } /* // install helloIsolationRef in root scope URL url1 = new URL("mvn:org.apache.aries.subsystem/org.apache.aries.subsystem.example.helloIsolationRef/0.1-SNAPSHOT"); Bundle helloIsolationRef = bundleContext.installBundle("helloIsolationRef1-rootScope", url1.openStream()); try { helloIsolationRef.start(); } catch (Exception ex) { fail("should be able to start helloIsolationRef"); }*/ // remove child scope - cleanup su = scope.newScopeUpdate(); Collection<ScopeUpdate> scopes = su.getChildren(); scopes.clear(); // scopes.add(scope1); // scopes.add(scope2); // scopes.add(scope3); su.commit(); assertTrue(scope.getChildren().isEmpty()); assertTrue(scope.newScopeUpdate().getChildren().isEmpty()); } // @org.ops4j.pax.exam.junit.Configuration // public static Option[] configuration() { // Option[] options = options( // // Log // mavenBundle("org.ops4j.pax.logging", "pax-logging-api"), // mavenBundle("org.ops4j.pax.logging", "pax-logging-service"), // // Felix Config Admin // mavenBundle("org.apache.felix", "org.apache.felix.configadmin"), // // Felix mvn url handler // mavenBundle("org.ops4j.pax.url", "pax-url-mvn"), // // // // this is how you set the default log level when using pax logging (logProfile) // systemProperty("org.ops4j.pax.logging.DefaultServiceLog.level").value("DEBUG"), // // // Bundles // mavenBundle("org.apache.aries.testsupport", "org.apache.aries.testsupport.unit"), // mavenBundle("org.apache.aries.application", "org.apache.aries.application.api"), // mavenBundle("org.apache.aries", "org.apache.aries.util"), // mavenBundle("org.apache.aries.application", "org.apache.aries.application.utils"), // mavenBundle("org.apache.felix", "org.apache.felix.bundlerepository"), // mavenBundle("org.apache.aries.subsystem", "org.apache.aries.subsystem.api"), // mavenBundle("org.apache.aries.subsystem", "org.apache.aries.subsystem.scope.api"), // mavenBundle("org.apache.aries.subsystem", "org.apache.aries.subsystem.scope.impl"), // // // org.ops4j.pax.exam.container.def.PaxRunnerOptions.vmOption("-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005"), // // PaxRunnerOptions.rawPaxRunnerOption("config", "classpath:ss-runner.properties"), // // equinox().version("3.7.0.v20110221") // ); // options = updateOptions(options); // return options; // } private Scope createScope(Scope scope, String scopeName, String loc, String version) throws MalformedURLException, InvalidSyntaxException, BundleException, IOException { ScopeUpdate su = scope.newScopeUpdate(); ScopeUpdate childScopeUpdate = su.newChild(scopeName); su.getChildren().add(childScopeUpdate); addPackageImportPolicy("org.osgi.framework", childScopeUpdate); addPackageImportPolicy("org.osgi.util.tracker", childScopeUpdate); Map<String, List<SharePolicy>> sharePolicies = childScopeUpdate.getSharePolicies(SharePolicy.TYPE_EXPORT); final Filter filter1 = FrameworkUtil.createFilter( "(&" + "(osgi.wiring.package=org.apache.aries.subsystem.example.helloIsolation)" + "(version=" + version + ")" + ")"); final Filter filter2 = FrameworkUtil.createFilter( "(&" + "(scope.share.service=org.apache.aries.subsystem.example.helloIsolation.HelloIsolation)" + ")"); List<SharePolicy> packagePolicies = sharePolicies.get(BundleRevision.PACKAGE_NAMESPACE); if (packagePolicies == null) { packagePolicies = new ArrayList<SharePolicy>(); sharePolicies.put(BundleRevision.PACKAGE_NAMESPACE, packagePolicies); } packagePolicies.add(new SharePolicy(SharePolicy.TYPE_EXPORT, BundleRevision.PACKAGE_NAMESPACE, filter1)); List<SharePolicy> servicePolicies = sharePolicies.get("scope.share.service"); if (servicePolicies == null) { servicePolicies = new ArrayList<SharePolicy>(); sharePolicies.put("scope.share.service", servicePolicies); } servicePolicies.add(new SharePolicy(SharePolicy.TYPE_EXPORT, "scope.share.service", filter2)); // build up installInfo object for the scope InstallInfo info1 = new InstallInfo("helloIsolation_" + scopeName, new URL(loc)); List<InstallInfo> bundlesToInstall = childScopeUpdate.getBundlesToInstall(); bundlesToInstall.add(info1); // add bundles to be installed, based on subsystem content su.commit(); // start all bundles in the scope scope_test1 Collection<Bundle> bundlesToStart = childScopeUpdate.getScope().getBundles(); for (Bundle b : bundlesToStart) { b.start(); } return childScopeUpdate.getScope(); } }
8,492
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/Utils.java
package org.apache.aries.subsystem.scope.itests; import org.apache.aries.subsystem.scope.Scope; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceReference; import org.osgi.framework.ServiceRegistration; public class Utils { public static Bundle findBundle(String symbolicName, BundleContext bundleContext) { Bundle[] bundles = bundleContext.getBundles(); for (Bundle bundle : bundles) { if (bundle.getSymbolicName().equals(symbolicName)) { return bundle; } } return null; } public static Bundle findBundle(String symbolicName, Scope scope) { if (scope == null) return null; for (Bundle b : scope.getBundles()) { if (symbolicName == null) { if (b.getSymbolicName() == null) return b; } else if (symbolicName.equals(b.getSymbolicName())) return b; } return null; } public static void ungetQuietly(ServiceReference<?> serviceReference, BundleContext bundleContext) { if (serviceReference == null) return; try { bundleContext.ungetService(serviceReference); } catch (Exception e) { // ignore } } public static void uninstallQuietly(Bundle bundle) { if (bundle == null) return; try { bundle.uninstall(); } catch (Exception e) { // ignore } } public static void unregisterQuietly(ServiceRegistration<?> serviceRegistration) { if (serviceRegistration == null) return; try { serviceRegistration.unregister(); } catch (Exception e) { // ignore } } }
8,493
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/SharePolicyTest.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.assertTrue; import java.net.URL; import java.util.Arrays; import org.apache.aries.subsystem.scope.InstallInfo; import org.apache.aries.subsystem.scope.ScopeUpdate; import org.junit.Test; import org.osgi.framework.Bundle; import org.osgi.framework.wiring.FrameworkWiring; public class SharePolicyTest extends AbstractTest { /** * Bundle tb5 * Bundle tb6 * tb5 imports package exported by tb6 * tb5 and tb6 in same scope * tb5 should resolve * * Share policies have no effect within the same scope. * * @throws Exception */ @Test public void test1() throws Exception { Bundle tb5 = null; Bundle tb6 = null; try { String tb5Location = getBundleLocation("tb-5.jar"); String tb6Location = getBundleLocation("tb-6.jar"); InstallInfo tb5Info = new InstallInfo(tb5Location, new URL(tb5Location)); InstallInfo tb6Info = new InstallInfo(tb6Location, new URL(tb6Location)); ScopeUpdate scopeUpdate = getScope().newScopeUpdate(); scopeUpdate.getBundlesToInstall().add(tb5Info); scopeUpdate.commit(); tb5 = findBundleInRootScope("org.apache.aries.subsystem.scope.itests.tb5"); assertNotNull(tb5); FrameworkWiring frameworkWiring = bundleContext.getBundle(0).adapt(FrameworkWiring.class); assertFalse(frameworkWiring.resolveBundles(Arrays.asList(new Bundle[]{tb5}))); scopeUpdate = getScope().newScopeUpdate(); scopeUpdate.getBundlesToInstall().add(tb6Info); scopeUpdate.commit(); tb6 = findBundleInRootScope("org.apache.aries.subsystem.scope.itests.tb6"); assertNotNull(tb6); assertTrue(frameworkWiring.resolveBundles(Arrays.asList(new Bundle[]{tb5,tb6}))); } finally { uninstallQuietly(tb6); uninstallQuietly(tb5); } } /** * Bundle tb5 * Bundle tb6 * tb5 imports package exported by tb6 * tb5 in root scope * tb6 in child scope of root * tb6 scope does not export tb6 package * tb5 should not resolve * @throws Exception */ @Test public void test2() throws Exception { Bundle tb5 = null; Bundle tb6 = null; try { String tb5Location = getBundleLocation("tb-5.jar"); String tb6Location = getBundleLocation("tb-6.jar"); InstallInfo tb5Info = new InstallInfo(tb5Location, new URL(tb5Location)); InstallInfo tb6Info = new InstallInfo(tb6Location, new URL(tb6Location)); ScopeUpdate scopeUpdate = getScope().newScopeUpdate(); scopeUpdate.getBundlesToInstall().add(tb5Info); scopeUpdate.commit(); tb5 = findBundleInRootScope("org.apache.aries.subsystem.scope.itests.tb5"); assertNotNull(tb5); FrameworkWiring frameworkWiring = bundleContext.getBundle(0).adapt(FrameworkWiring.class); assertFalse(frameworkWiring.resolveBundles(Arrays.asList(new Bundle[]{tb5}))); scopeUpdate = getScope().newScopeUpdate(); ScopeUpdate tb6ScopeUpdate = scopeUpdate.newChild("tb6"); scopeUpdate.getChildren().add(tb6ScopeUpdate); tb6ScopeUpdate.getBundlesToInstall().add(tb6Info); scopeUpdate.commit(); tb6 = findBundle("org.apache.aries.subsystem.scope.itests.tb6", tb6ScopeUpdate.getScope()); assertNotNull(tb6); assertFalse(frameworkWiring.resolveBundles(Arrays.asList(new Bundle[]{tb5,tb6}))); } finally { uninstallQuietly(tb6); uninstallQuietly(tb5); } } /** * Bundle tb5 * Bundle tb6 * tb5 imports package exported by tb6 * tb5 in root scope * tb6 in child scope of root * tb6 scope exports tb6 package * tb5 should resolve * * There is an implicit import between parent and child. In other words, * anything exported by a child is automatically available without the * parent explicitly importing it. * * @throws Exception */ @Test public void test3() throws Exception { Bundle tb5 = null; Bundle tb6 = null; try { String tb5Location = getBundleLocation("tb-5.jar"); String tb6Location = getBundleLocation("tb-6.jar"); InstallInfo tb5Info = new InstallInfo(tb5Location, new URL(tb5Location)); InstallInfo tb6Info = new InstallInfo(tb6Location, new URL(tb6Location)); ScopeUpdate scopeUpdate = getScope().newScopeUpdate(); scopeUpdate.getBundlesToInstall().add(tb5Info); scopeUpdate.commit(); tb5 = findBundleInRootScope("org.apache.aries.subsystem.scope.itests.tb5"); assertNotNull(tb5); FrameworkWiring frameworkWiring = bundleContext.getBundle(0).adapt(FrameworkWiring.class); assertFalse(frameworkWiring.resolveBundles(Arrays.asList(new Bundle[]{tb5}))); scopeUpdate = getScope().newScopeUpdate(); ScopeUpdate tb6ScopeUpdate = scopeUpdate.newChild("tb6"); scopeUpdate.getChildren().add(tb6ScopeUpdate); tb6ScopeUpdate.getBundlesToInstall().add(tb6Info); addPackageExportPolicy("org.apache.aries.subsystem.scope.itests.tb6", tb6ScopeUpdate); scopeUpdate.commit(); tb6 = findBundle("org.apache.aries.subsystem.scope.itests.tb6", tb6ScopeUpdate.getScope()); assertNotNull(tb6); tb5.start(); assertTrue(frameworkWiring.resolveBundles(Arrays.asList(new Bundle[]{tb5,tb6}))); } finally { uninstallQuietly(tb6); uninstallQuietly(tb5); } } /** * Bundle tb5 * Bundle tb6 * tb5 imports package exported by tb6 * tb5 in child scope of root * tb6 in different child scope of root * tb6 scope exports tb6 package * root scope exports tb6 package * tb5 scope imports tb6 package * tb5 should resolve * * @throws Exception */ @Test public void test4() throws Exception { Bundle tb5 = null; Bundle tb6 = null; try { String tb5Location = getBundleLocation("tb-5.jar"); String tb6Location = getBundleLocation("tb-6.jar"); InstallInfo tb5Info = new InstallInfo(tb5Location, new URL(tb5Location)); InstallInfo tb6Info = new InstallInfo(tb6Location, new URL(tb6Location)); ScopeUpdate rootUpdate = getScope().newScopeUpdate(); addPackageExportPolicy("org.apache.aries.subsystem.scope.itests.tb6", rootUpdate); ScopeUpdate tb5Update = rootUpdate.newChild("tb5"); rootUpdate.getChildren().add(tb5Update); tb5Update.getBundlesToInstall().add(tb5Info); addPackageImportPolicy("org.apache.aries.subsystem.scope.itests.tb6", tb5Update); rootUpdate.commit(); tb5 = findBundle("org.apache.aries.subsystem.scope.itests.tb5", tb5Update.getScope()); assertNotNull(tb5); FrameworkWiring frameworkWiring = bundleContext.getBundle(0).adapt(FrameworkWiring.class); assertFalse(frameworkWiring.resolveBundles(Arrays.asList(new Bundle[]{tb5}))); rootUpdate = getScope().newScopeUpdate(); ScopeUpdate tb6Update = rootUpdate.newChild("tb6"); rootUpdate.getChildren().add(tb6Update); tb6Update.getBundlesToInstall().add(tb6Info); addPackageExportPolicy("org.apache.aries.subsystem.scope.itests.tb6", tb6Update); rootUpdate.commit(); tb6 = findBundle("org.apache.aries.subsystem.scope.itests.tb6", tb6Update.getScope()); assertNotNull(tb6); assertTrue(frameworkWiring.resolveBundles(Arrays.asList(new Bundle[]{tb5,tb6}))); } finally { uninstallQuietly(tb6); uninstallQuietly(tb5); } } }
8,494
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/GetScopeServiceTest.java
package org.apache.aries.subsystem.scope.itests; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.net.URL; import org.apache.aries.subsystem.scope.InstallInfo; import org.apache.aries.subsystem.scope.Scope; import org.apache.aries.subsystem.scope.ScopeUpdate; import org.junit.Test; import org.osgi.framework.Bundle; import org.osgi.framework.ServiceReference; /** * Tests that bundles requesting a Scope service receive the correct one. * Bundles should receive the Scope within which they exist. Requesting bundles * are in the root scope by default. */ public class GetScopeServiceTest extends AbstractTest { /** * The test bundle should be in and receive the root scope by default. The * root scope will always have an ID of '0' and name of 'root'. * @throws Exception */ @Test public void test1() throws Exception { Scope scope = getScope(); assertEquals(0, scope.getId()); assertEquals("root", scope.getName()); assertTrue(scope.getBundles().contains(bundleContext.getBundle())); } /** * The tb3 bundle should also be in and receive the root scope by default. * @throws Exception */ @Test public void test2() throws Exception { Bundle bundle = installBundle("tb-3.jar"); bundle.start(); ServiceReference<ScopeProvider> scopeProviderRef = bundleContext.getServiceReference(ScopeProvider.class); ScopeProvider scopeProvider = bundleContext.getService(scopeProviderRef); Scope scope = scopeProvider.getScope(); assertEquals(getScope(), scope); assertTrue(scope.getBundles().contains(bundle)); bundleContext.ungetService(scopeProviderRef); bundle.uninstall(); } /** * A new scope is created as a child of the root scope and the tb3 bundle * is added to it. The tb3 bundle should receive and be in the new scope. * @throws Exception */ @Test public void test3() throws Exception { Scope scope = getScope(); ScopeUpdate scopeUpdate = scope.newScopeUpdate(); ScopeUpdate child = scopeUpdate.newChild("tb3"); scopeUpdate.getChildren().add(child); String location = getBundleLocation("tb-3.jar"); URL url = new URL(location); InstallInfo installInfo = new InstallInfo(location, url.openStream()); child.getBundlesToInstall().add(installInfo); addPackageImportPolicy("org.osgi.framework", child); addPackageImportPolicy("org.apache.aries.subsystem.scope", child); addPackageImportPolicy("org.apache.aries.subsystem.scope.itests", child); addServiceImportPolicy(Scope.class, child); addServiceExportPolicy(ScopeProvider.class, child); scopeUpdate.commit(); Bundle bundle = bundleContext.getBundle(location); bundle.start(); ServiceReference<ScopeProvider> scopeProviderRef = bundleContext.getServiceReference(ScopeProvider.class); ScopeProvider scopeProvider = bundleContext.getService(scopeProviderRef); scope = scopeProvider.getScope(); assertEquals("tb3", scope.getName()); assertTrue(scope.getBundles().contains(bundle)); bundleContext.ungetService(scopeProviderRef); bundle.uninstall(); } /** * A new scope is created as a child of the root scope and the tb3 bundle * is added to it. The tb3 bundle should receive and be in the new scope. * The bundle is added directly as opposed to via an InstallInfo. * @throws Exception */ @Test public void test4() throws Exception { Scope scope = getScope(); Bundle bundle = installBundle("tb-3.jar"); ScopeUpdate scopeUpdate = scope.newScopeUpdate(); scopeUpdate.getBundles().remove(bundle); ScopeUpdate child = scopeUpdate.newChild("tb3"); scopeUpdate.getChildren().add(child); child.getBundles().add(bundle); addPackageImportPolicy("org.osgi.framework", child); addPackageImportPolicy("org.apache.aries.subsystem.scope", child); addPackageImportPolicy("org.apache.aries.subsystem.scope.itests", child); addServiceImportPolicy(Scope.class, child); addServiceExportPolicy(ScopeProvider.class, child); scopeUpdate.commit(); bundle.start(); ServiceReference<ScopeProvider> scopeProviderRef = bundleContext.getServiceReference(ScopeProvider.class); ScopeProvider scopeProvider = bundleContext.getService(scopeProviderRef); scope = scopeProvider.getScope(); assertEquals("tb3", scope.getName()); assertTrue(scope.getBundles().contains(bundle)); bundleContext.ungetService(scopeProviderRef); bundle.uninstall(); } }
8,495
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/JarCreator.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.itests; import java.io.File; import java.io.FileOutputStream; import java.util.jar.Attributes; import java.util.jar.JarInputStream; import java.util.jar.JarOutputStream; import java.util.jar.Manifest; import java.util.zip.ZipEntry; import org.osgi.framework.Constants; /** * create multiple version of the same jars for testing purpose * as OSGi require install bundles have unique jar by symbolicname and version. * */ public class JarCreator { public static void main(String[] args) throws Exception{ createJar("1.0.0"); createJar("2.0.0"); } private static void createJar(String version) throws Exception { createJarFromFile("../subsystem-example/subsystem-helloIsolation/target/org.apache.aries.subsystem.example.helloIsolation-0.4-SNAPSHOT.jar", version); createJarFromFile("../subsystem-example/subsystem-helloIsolationRef/target/org.apache.aries.subsystem.example.helloIsolationRef-0.4-SNAPSHOT.jar", version); } private static void createJarFromFile(String fileName, String version) throws Exception { JarOutputStream jos = null; FileOutputStream fos = null; ZipEntry entry = null; try { // let's get hold of jars on disk File jarFile = new File(fileName); JarInputStream jarInput = new JarInputStream(jarFile.toURL().openStream()); Manifest manifest = jarInput.getManifest(); //update manifest, Bundle-Version Attributes attr = manifest.getMainAttributes(); attr.putValue(Constants.BUNDLE_VERSION, version); if (fileName.indexOf("helloIsolationRef") < 0) { attr.putValue(Constants.EXPORT_PACKAGE, "org.apache.aries.subsystem.example.helloIsolation;uses:=\"org.osgi.util.tracker,org.osgi.framework\";version=" + version); } int lastSlash = fileName.lastIndexOf("/"); // trim the path fileName = fileName.substring(lastSlash + 1); int loc = fileName.indexOf("-"); String jarFilePath = fileName.substring(0, loc + 1) + version + ".jar"; if (fileName.indexOf("helloIsolationRef") < 0) { File directory = new File(System.getProperty("user.home") + "/.m2/repository/org/apache/aries/subsystem/example/org.apache.aries.subsystem.example.helloIsolation/" + version + "/"); if (!directory.exists()) { directory.mkdir(); } fos = new FileOutputStream(directory.getAbsolutePath() + "/" + jarFilePath); } else { File directory = new File(System.getProperty("user.home") + "/.m2/repository/org/apache/aries/subsystem/example/org.apache.aries.subsystem.example.helloIsolationRef/" + version + "/"); if (!directory.exists()) { directory.mkdir(); } fos = new FileOutputStream(directory.getAbsolutePath() + "/" + jarFilePath); } jos = new JarOutputStream(fos, manifest); //Copy across all entries from the original jar int val; while ((entry = jarInput.getNextEntry()) != null) { jos.putNextEntry(entry); byte[] buffer = new byte[4096]; while ((val = jarInput.read(buffer)) != -1) jos.write(buffer, 0, val); } jos.closeEntry(); jos.finish(); System.out.println("finishing creating jar file: " + jarFilePath + " in local m2 repo"); } finally { if (jos != null) { jos.close(); } if (fos != null) { fos.close(); } } } }
8,496
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/Service.java
package org.apache.aries.subsystem.scope.itests; public interface Service { }
8,497
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/MoveBundleTest.java
package org.apache.aries.subsystem.scope.itests; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import org.apache.aries.subsystem.scope.Scope; import org.apache.aries.subsystem.scope.ScopeUpdate; import org.junit.Ignore; import org.junit.Test; import org.osgi.framework.Bundle; /** * Bundles may be moved from one scope to another. */ public class MoveBundleTest extends AbstractTest { /** * Create two scopes off of the root scope with the following structure. * R * / \ * S1 S2 * Install a bundle using the test bundle's bundle context. This should add * the bundle to R since the test bundle is in R. Next, move the bundle * into S1. Finally, move the bundle into S2. * @throws Exception */ @Test @Ignore public void test1() throws Exception { Bundle tb2 = installBundle("tb-2.jar"); Scope root = getScope(); ScopeUpdate rootUpdate = root.newScopeUpdate(); ScopeUpdate s1Update = rootUpdate.newChild("S1"); ScopeUpdate s2Update = rootUpdate.newChild("S2"); rootUpdate.getChildren().add(s1Update); rootUpdate.getChildren().add(s2Update); rootUpdate.commit(); Scope s1 = s1Update.getScope(); Scope s2 = s2Update.getScope(); assertTrue(root.getBundles().contains(tb2)); assertFalse(s1.getBundles().contains(tb2)); assertFalse(s2.getBundles().contains(tb2)); rootUpdate = root.newScopeUpdate(); rootUpdate.getBundles().remove(tb2); s1Update = findChildUpdate("S1", rootUpdate); s1Update.getBundles().add(tb2); rootUpdate.commit(); assertFalse(root.getBundles().contains(tb2)); assertTrue(s1.getBundles().contains(tb2)); assertFalse(s2.getBundles().contains(tb2)); rootUpdate = root.newScopeUpdate(); s1Update = findChildUpdate("S1", rootUpdate); s1Update.getBundles().remove(tb2); s2Update = findChildUpdate("S2", rootUpdate); s2Update.getBundles().add(tb2); rootUpdate.commit(); assertFalse(root.getBundles().contains(tb2)); assertFalse(s1.getBundles().contains(tb2)); assertTrue(s2.getBundles().contains(tb2)); tb2.uninstall(); } /** * Create one scope off of the root scope with the following structure. * R * | * S * Install a bundle using the test bundle's bundle context. This should add * the bundle to R since the test bundle is in R. Next, move the bundle into * S without removing it from R. This should result in an * IllegalStateException. Finally, correct the error using the same * ScopeUpdate objects and commit again. This should succeed, and the bundle * should now be in S. * @throws Exception */ @Test public void test2() throws Exception { Bundle tb2 = installBundle("tb-2.jar"); Scope root = getScope(); ScopeUpdate rootUpdate = root.newScopeUpdate(); ScopeUpdate sUpdate = rootUpdate.newChild("S"); rootUpdate.getChildren().add(sUpdate); rootUpdate.commit(); Scope s = sUpdate.getScope(); assertTrue(root.getBundles().contains(tb2)); assertFalse(s.getBundles().contains(tb2)); rootUpdate = root.newScopeUpdate(); sUpdate = findChildUpdate("S", rootUpdate); sUpdate.getBundles().add(tb2); try { rootUpdate.commit(); fail(); } catch (IllegalStateException e) { // Okay. } assertTrue(root.getBundles().contains(tb2)); assertFalse(s.getBundles().contains(tb2)); rootUpdate.getBundles().remove(tb2); rootUpdate.commit(); assertFalse(root.getBundles().contains(tb2)); assertTrue(s.getBundles().contains(tb2)); tb2.uninstall(); } }
8,498
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/AbstractTest.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.assertTrue; import static org.ops4j.pax.exam.CoreOptions.composite; import static org.ops4j.pax.exam.CoreOptions.junitBundles; import static org.ops4j.pax.exam.CoreOptions.mavenBundle; import static org.ops4j.pax.exam.CoreOptions.systemProperty; import static org.ops4j.pax.exam.CoreOptions.vmOption; import static org.ops4j.pax.exam.CoreOptions.when; import java.io.InputStream; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.inject.Inject; import org.apache.aries.itest.AbstractIntegrationTest; 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.junit.runner.RunWith; import org.ops4j.pax.exam.Configuration; import org.ops4j.pax.exam.CoreOptions; import org.ops4j.pax.exam.Option; import org.ops4j.pax.exam.ProbeBuilder; import org.ops4j.pax.exam.TestProbeBuilder; import org.ops4j.pax.exam.junit.PaxExam; import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy; import org.ops4j.pax.exam.spi.reactors.PerClass; import org.ops4j.pax.exam.spi.reactors.PerMethod; import org.ops4j.pax.tinybundles.core.TinyBundles; import org.osgi.framework.Bundle; import org.osgi.framework.BundleException; import org.osgi.framework.Constants; import org.osgi.framework.Filter; import org.osgi.framework.InvalidSyntaxException; @RunWith(PaxExam.class) @ExamReactorStrategy(PerMethod.class) public abstract class AbstractTest extends AbstractIntegrationTest { @Inject Scope scope; protected void addPackageExportPolicy(String packageName, ScopeUpdate scopeUpdate) throws InvalidSyntaxException { Filter filter = bundleContext.createFilter("(osgi.wiring.package=" + packageName + ')'); SharePolicy policy = new SharePolicy(SharePolicy.TYPE_EXPORT, "osgi.wiring.package", filter); Map<String, List<SharePolicy>> policyMap = scopeUpdate.getSharePolicies(SharePolicy.TYPE_EXPORT); List<SharePolicy> policies = policyMap.get("osgi.wiring.package"); if (policies == null) { policies = new ArrayList<SharePolicy>(); policyMap.put("osgi.wiring.package", policies); } policies.add(policy); } protected void addPackageImportPolicy(String packageName, ScopeUpdate scopeUpdate) throws InvalidSyntaxException { Filter filter = bundleContext.createFilter("(osgi.wiring.package=" + packageName + ')'); SharePolicy policy = new SharePolicy(SharePolicy.TYPE_IMPORT, "osgi.wiring.package", filter); Map<String, List<SharePolicy>> policyMap = scopeUpdate.getSharePolicies(SharePolicy.TYPE_IMPORT); List<SharePolicy> policies = policyMap.get("osgi.wiring.package"); if (policies == null) { policies = new ArrayList<SharePolicy>(); policyMap.put("osgi.wiring.package", policies); } policies.add(policy); } protected void addServiceExportPolicy(Class<?> clazz, ScopeUpdate scopeUpdate) throws InvalidSyntaxException { Filter filter = bundleContext.createFilter('(' + Constants.OBJECTCLASS + '=' + clazz.getName() + ')'); SharePolicy policy = new SharePolicy(SharePolicy.TYPE_EXPORT, "scope.share.service", filter); Map<String, List<SharePolicy>> policyMap = scopeUpdate.getSharePolicies(SharePolicy.TYPE_EXPORT); List<SharePolicy> policies = policyMap.get("scope.share.service"); if (policies == null) { policies = new ArrayList<SharePolicy>(); policyMap.put("scope.share.service", policies); } policies.add(policy); } protected void addServiceImportPolicy(Class<?> clazz, ScopeUpdate scopeUpdate) throws InvalidSyntaxException { Filter filter = bundleContext.createFilter('(' + Constants.OBJECTCLASS + '=' + clazz.getName() + ')'); SharePolicy policy = new SharePolicy(SharePolicy.TYPE_IMPORT, "scope.share.service", filter); Map<String, List<SharePolicy>> policyMap = scopeUpdate.getSharePolicies(SharePolicy.TYPE_IMPORT); List<SharePolicy> policies = policyMap.get("scope.share.service"); if (policies == null) { policies = new ArrayList<SharePolicy>(); policyMap.put("scope.share.service", policies); } policies.add(policy); } protected void assertEmpty(Collection<?> c) { assertNotNull(c); assertTrue(c.isEmpty()); } protected void assertEmpty(Map<?, ?> m) { assertNotNull(m); assertTrue(m.isEmpty()); } protected void assertCollectionEquals(Collection<?> c1, Collection<?> c2) { assertFalse((c1 == null && c2 != null) || (c1 != null && c2 == null)); assertTrue(c1.size() == c2.size()); for (Iterator<?> i = c2.iterator(); i.hasNext();) { assertTrue(c2.contains(i.next())); } } protected Bundle findBundle(String symbolicName) { return Utils.findBundle(symbolicName, bundleContext); } protected Bundle findBundle(String symbolicName, Scope scope) { return Utils.findBundle(symbolicName, scope); } protected Bundle findBundleInRootScope(String symbolicName) { return findBundle(symbolicName, getScope()); } protected Scope findChildScope(String name, Scope parent) { assertNotNull(name); assertNotNull(parent); Scope result = null; for (Scope child : parent.getChildren()) { if (name.equals(child.getName())) { result = child; break; } } assertNotNull(result); return result; } protected ScopeUpdate findChildUpdate(String name, ScopeUpdate parent) { assertNotNull(name); assertNotNull(parent); ScopeUpdate result = null; for (ScopeUpdate child : parent.getChildren()) { if (name.equals(child.getName())) { result = child; break; } } assertNotNull(result); return result; } protected String getBundleLocation(String bundle) { URL url = AbstractTest.class.getClassLoader().getResource(bundle); return url.toExternalForm(); } protected Scope getScope() { return scope; } protected Bundle installBundle(String name) throws BundleException { URL url = AbstractTest.class.getClassLoader().getResource(name); return bundleContext.installBundle(url.toExternalForm()); } protected void installBundles(Scope scope, String[] bundleNames) throws Exception { installBundles(scope, Arrays.asList(bundleNames)); } protected void installBundles(Scope scope, Collection<String> bundleNames) throws Exception { ScopeUpdate scopeUpdate = scope.newScopeUpdate(); for (String bundleName : bundleNames) { URL url = AbstractTest.class.getClassLoader().getResource(bundleName); InstallInfo installInfo = new InstallInfo(url.toExternalForm(), url.openStream()); scopeUpdate.getBundlesToInstall().add(installInfo); } scopeUpdate.commit(); } protected void uninstallQuietly(Bundle bundle) { Utils.uninstallQuietly(bundle); } protected Option baseOptions() { String localRepo = System.getProperty("maven.repo.local"); if (localRepo == null) { localRepo = System.getProperty("org.ops4j.pax.url.mvn.localRepository"); } return composite( junitBundles(), mavenBundle("org.ops4j.pax.logging", "pax-logging-api", "1.7.2"), mavenBundle("org.ops4j.pax.logging", "pax-logging-service", "1.7.2"), mavenBundle("org.apache.aries.testsupport", "org.apache.aries.testsupport.unit").versionAsInProject(), // this is how you set the default log level when using pax // logging (logProfile) systemProperty("org.ops4j.pax.logging.DefaultServiceLog.level").value("INFO"), when(localRepo != null).useOptions(vmOption("-Dorg.ops4j.pax.url.mvn.localRepository=" + localRepo)) ); } @ProbeBuilder public TestProbeBuilder probeConfiguration(TestProbeBuilder probe) { probe.setHeader(Constants.EXPORT_PACKAGE, this.getClass().getPackage().getName()); return probe; } @Configuration public Option[] subsystemScope() { //InputStream itestBundle = TinyBundles.bundle().add(); return CoreOptions.options( baseOptions(), mavenBundle("org.apache.aries.testsupport", "org.apache.aries.testsupport.unit").versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.api").versionAsInProject(), mavenBundle("org.apache.aries", "org.apache.aries.util").versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.utils").versionAsInProject(), mavenBundle("org.apache.felix", "org.apache.felix.bundlerepository").versionAsInProject(), mavenBundle("org.eclipse.equinox", "org.eclipse.equinox.coordinator").versionAsInProject(), mavenBundle("org.apache.aries.subsystem", "org.apache.aries.subsystem.api").versionAsInProject(), mavenBundle("org.apache.aries.subsystem", "org.apache.aries.subsystem.scope.api").versionAsInProject(), mavenBundle("org.apache.aries.subsystem", "org.apache.aries.subsystem.scope.impl").versionAsInProject() //CoreOptions.streamBundle(itestBundle ) ); } }
8,499