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/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/utils/threading | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/utils/threading/impl/WrappedFuture.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.blueprint.utils.threading.impl;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class WrappedFuture<T> implements Future<T> {
private Discardable<?> _discardable;
private Future<T> _future;
public WrappedFuture(Future<T> f, Discardable<?> d) {
_future = f;
_discardable = d;
}
public boolean cancel(boolean arg0) {
boolean result = _future.cancel(arg0);
if (result) _discardable.discard();
return result;
}
public T get() throws InterruptedException, ExecutionException {
return _future.get();
}
public T get(long timeout, TimeUnit timeunit) throws InterruptedException, ExecutionException,
TimeoutException {
return _future.get(timeout, timeunit);
}
public boolean isCancelled() {
return _future.isCancelled();
}
public boolean isDone() {
return _future.isDone();
}
} | 9,500 |
0 | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/utils/threading | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/utils/threading/impl/Discardable.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.blueprint.utils.threading.impl;
public interface Discardable<T> {
<T> T discard();
} | 9,501 |
0 | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/utils/threading | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/utils/threading/impl/DiscardableCallable.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.blueprint.utils.threading.impl;
import java.util.Collections;
import java.util.Queue;
import java.util.concurrent.Callable;
import java.util.concurrent.CancellationException;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicReference;
public class DiscardableCallable<V> implements Callable<V>, Runnable, Discardable<Runnable> {
private AtomicReference<Callable<V>> c = new AtomicReference<Callable<V>>();
private Queue<Discardable<Runnable>> _removeFromListOnCall;
public DiscardableCallable(Callable<V> call, Queue<Discardable<Runnable>> _unprocessedWork) {
c.set(call);
_removeFromListOnCall = _unprocessedWork;
_removeFromListOnCall.add(this);
}
private DiscardableCallable(Callable<V> call) {
c.set(call);
_removeFromListOnCall = new LinkedBlockingQueue<Discardable<Runnable>>();
}
public Runnable discard() {
_removeFromListOnCall.remove(this);
return new DiscardableCallable<V>(c.getAndSet(null));
}
public V call() throws Exception {
_removeFromListOnCall.remove(this);
Callable<V> call = c.get();
if (call != null) {
return call.call();
}
throw new CancellationException();
}
public void run() {
try {
call();
} catch (Exception e) {
}
}
} | 9,502 |
0 | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/utils/threading | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/utils/threading/impl/WrappedScheduledFuture.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.blueprint.utils.threading.impl;
import java.util.concurrent.Delayed;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class WrappedScheduledFuture<T> implements ScheduledFuture<T> {
private Discardable<?> _discardable;
private ScheduledFuture<T> _future;
public WrappedScheduledFuture(ScheduledFuture<T> f, Discardable<?> d) {
_future = f;
_discardable = d;
}
public long getDelay(TimeUnit timeunit) {
return _future.getDelay(timeunit);
}
public int compareTo(Delayed other) {
return _future.compareTo(other);
}
public boolean cancel(boolean arg0) {
boolean result = _future.cancel(arg0);
if (result) _discardable.discard();
return result;
}
public T get() throws InterruptedException, ExecutionException {
return _future.get();
}
public T get(long timeout, TimeUnit timeunit) throws InterruptedException, ExecutionException,
TimeoutException {
return _future.get(timeout, timeunit);
}
public boolean isCancelled() {
return _future.isCancelled();
}
public boolean isDone() {
return _future.isDone();
}
} | 9,503 |
0 | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/container/ServiceRecipe.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.blueprint.container;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Dictionary;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.aries.blueprint.BlueprintConstants;
import org.apache.aries.blueprint.ComponentDefinitionRegistry;
import org.apache.aries.blueprint.Interceptor;
import org.apache.aries.blueprint.ServiceProcessor;
import org.apache.aries.blueprint.container.AggregateConverter.Convertible;
import org.apache.aries.blueprint.container.BeanRecipe.UnwrapperedBeanHolder;
import org.apache.aries.blueprint.di.AbstractRecipe;
import org.apache.aries.blueprint.di.CollectionRecipe;
import org.apache.aries.blueprint.di.ExecutionContext;
import org.apache.aries.blueprint.di.MapRecipe;
import org.apache.aries.blueprint.di.Recipe;
import org.apache.aries.blueprint.di.Repository;
import org.apache.aries.blueprint.proxy.CollaboratorFactory;
import org.apache.aries.blueprint.proxy.ProxyUtils;
import org.apache.aries.blueprint.utils.JavaUtils;
import org.apache.aries.blueprint.utils.ReflectionUtils;
import org.apache.aries.blueprint.utils.ServiceListener;
import org.apache.aries.blueprint.utils.ServiceUtil;
import org.apache.aries.proxy.InvocationListener;
import org.osgi.framework.Bundle;
import org.osgi.framework.Constants;
import org.osgi.framework.FrameworkUtil;
import org.osgi.framework.ServiceFactory;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.blueprint.container.ComponentDefinitionException;
import org.osgi.service.blueprint.container.ReifiedType;
import org.osgi.service.blueprint.reflect.ComponentMetadata;
import org.osgi.service.blueprint.reflect.RefMetadata;
import org.osgi.service.blueprint.reflect.ServiceMetadata;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A <code>Recipe</code> to export services into the OSGi registry.
*
* @version $Rev$, $Date$
*/
public class ServiceRecipe extends AbstractRecipe {
private static final Logger LOGGER = LoggerFactory.getLogger(ServiceRecipe.class);
final static String LOG_ENTRY = "Method entry: {}, args {}";
final static String LOG_EXIT = "Method exit: {}, returning {}";
private final BlueprintContainerImpl blueprintContainer;
private final ServiceMetadata metadata;
private final Recipe serviceRecipe;
private final CollectionRecipe listenersRecipe;
private final MapRecipe propertiesRecipe;
private final List<Recipe> explicitDependencies;
private Map properties;
private final AtomicReference<ServiceRegistration> registration = new AtomicReference<ServiceRegistration>();
private Map registrationProperties;
private List<ServiceListener> listeners;
private volatile Object service;
private final Object monitor = new Object();
private final AtomicInteger activeCalls = new AtomicInteger(0);
private volatile boolean quiesce;
/** Only ever access when holding a lock on <code>monitor</code> */
private Collection<DestroyCallback> destroyCallbacks = new ArrayList<DestroyCallback>();
private boolean initialServiceRegistration = true;
public ServiceRecipe(String name,
BlueprintContainerImpl blueprintContainer,
ServiceMetadata metadata,
Recipe serviceRecipe,
CollectionRecipe listenersRecipe,
MapRecipe propertiesRecipe,
List<Recipe> explicitDependencies) {
super(name);
this.prototype = false;
this.blueprintContainer = blueprintContainer;
this.metadata = metadata;
this.serviceRecipe = serviceRecipe;
this.listenersRecipe = listenersRecipe;
this.propertiesRecipe = propertiesRecipe;
this.explicitDependencies = explicitDependencies;
}
public Recipe getServiceRecipe() {
return serviceRecipe;
}
public CollectionRecipe getListenersRecipe() {
return listenersRecipe;
}
@Override
public List<Recipe> getConstructorDependencies() {
List<Recipe> recipes = new ArrayList<Recipe>();
if (explicitDependencies != null) {
recipes.addAll(explicitDependencies);
}
return recipes;
}
public List<Recipe> getDependencies() {
List<Recipe> recipes = new ArrayList<Recipe>();
if (serviceRecipe != null) {
recipes.add(serviceRecipe);
}
if (listenersRecipe != null) {
recipes.add(listenersRecipe);
}
if (propertiesRecipe != null) {
recipes.add(propertiesRecipe);
}
recipes.addAll(getConstructorDependencies());
return recipes;
}
protected Object internalCreate() throws ComponentDefinitionException {
ServiceRegistrationProxy proxy = new ServiceRegistrationProxy();
addPartialObject(proxy);
internalGetService(null, null); // null bundle means we don't want to retrieve the actual service when used with a ServiceFactory
return proxy;
}
public boolean isRegistered() {
return registration.get() != null;
}
public void register() {
int state = blueprintContainer.getBundleContext().getBundle().getState();
if (state != Bundle.ACTIVE && state != Bundle.STARTING) {
return;
}
createExplicitDependencies();
Hashtable props = new Hashtable();
if (properties == null) {
properties = (Map) createRecipe(propertiesRecipe);
}
props.putAll(properties);
if (metadata.getRanking() == 0) {
props.remove(Constants.SERVICE_RANKING);
} else {
props.put(Constants.SERVICE_RANKING, metadata.getRanking());
}
String componentName = getComponentName();
if (componentName != null) {
props.put(BlueprintConstants.COMPONENT_NAME_PROPERTY, componentName);
} else {
props.remove(BlueprintConstants.COMPONENT_NAME_PROPERTY);
}
for (ServiceProcessor processor : blueprintContainer.getProcessors(ServiceProcessor.class)) {
processor.updateProperties(new PropertiesUpdater(), props);
}
registrationProperties = props;
Set<String> classes = getClasses();
String[] classArray = classes.toArray(new String[classes.size()]);
LOGGER.debug("Registering service {} with interfaces {} and properties {}",
new Object[] { name, classes, props });
if (registration.get() == null) {
ServiceRegistration reg = blueprintContainer.registerService(classArray, new TriggerServiceFactory(this, metadata), props);
if (!registration.compareAndSet(null, reg) && registration.get() != reg) {
ServiceUtil.safeUnregisterService(reg);
}
}
initialServiceRegistration = false;
}
public void unregister() {
ServiceRegistration reg = registration.get();
if (reg != null) {
LOGGER.debug("Unregistering service {}", name);
// This method needs to allow reentrance, so if we need to make sure the registration is
// set to null before actually unregistering the service
if (listeners != null) {
LOGGER.debug("Calling listeners for service unregistration");
for (ServiceListener listener : listeners) {
listener.unregister(service, registrationProperties);
}
}
ServiceUtil.safeUnregisterService(reg);
registration.compareAndSet(reg, null);
}
}
protected ServiceReference getReference() {
ServiceRegistration reg = registration.get();
if (reg == null) {
throw new IllegalStateException("Service is not registered");
} else {
return reg.getReference();
}
}
protected void setProperties(Dictionary props) {
ServiceRegistration reg = registration.get();
if (reg == null) {
throw new IllegalStateException("Service is not registered");
} else {
reg.setProperties(props);
// TODO: set serviceProperties? convert somehow? should listeners be notified of this?
}
}
protected Object internalGetService() {
return internalGetService(blueprintContainer.getBundleContext().getBundle(), null);
}
/**
* Create the service object.
*
* @param bundle
* @param registration
* @return
*/
private Object internalGetService(Bundle bundle, ServiceRegistration registration) {
LOGGER.debug("Retrieving service for bundle {} and service registration {}", bundle, registration);
createService();
Object service = this.service;
// We need the real service ...
if (bundle != null) {
if (service instanceof ServiceFactory) {
service = ((ServiceFactory) service).getService(bundle, registration);
}
if (service == null) {
throw new IllegalStateException("service is null");
}
// Check if the service actually implement all the requested interfaces
validateClasses(service);
// We're not really interested in the service, but perform some sanity checks nonetheless
} else {
if (!(service instanceof ServiceFactory)) {
// Check if the service actually implement all the requested interfaces
validateClasses(service);
}
}
return service;
}
private void createService() {
try {
if (service == null) {
LOGGER.debug("Creating service instance");
//We can't use the BlueprintRepository because we don't know what interfaces
//to use yet! We have to be a bit smarter.
ExecutionContext old = ExecutionContext.Holder.setContext(blueprintContainer.getRepository());
try {
Object o = serviceRecipe.create();
if (o instanceof Convertible) {
o = blueprintContainer.getRepository().convert(o, new ReifiedType(Object.class));
validateClasses(o);
} else if (o instanceof UnwrapperedBeanHolder) {
UnwrapperedBeanHolder holder = (UnwrapperedBeanHolder) o;
if (holder.unwrapperedBean instanceof ServiceFactory) {
//If a service factory is used, make sure the proxy classes implement this
//interface so that later on, internalGetService will create the real
//service from it.
LOGGER.debug("{} implements ServiceFactory, creating proxy that also implements this", holder.unwrapperedBean);
Collection<Class<?>> cls = getClassesForProxying(holder.unwrapperedBean);
cls.add(blueprintContainer.loadClass("org.osgi.framework.ServiceFactory"));
o = BeanRecipe.wrap(holder, cls);
} else {
validateClasses(holder.unwrapperedBean);
o = BeanRecipe.wrap(holder, getClassesForProxying(holder.unwrapperedBean));
}
} else if (!(o instanceof ServiceFactory)) {
validateClasses(o);
}
service = o;
} catch (Exception e) {
LOGGER.error("Error retrieving service from " + this, e);
throw new ComponentDefinitionException(e);
} finally {
ExecutionContext.Holder.setContext(old);
}
LOGGER.debug("Service created: {}", service);
}
// When the service is first requested, we need to create listeners and call them
if (!initialServiceRegistration && listeners == null) {
LOGGER.debug("Creating listeners");
if (listenersRecipe != null) {
listeners = (List) createRecipe(listenersRecipe);
} else {
listeners = Collections.emptyList();
}
LOGGER.debug("Listeners created: {}", listeners);
if (registration.get() != null) {
LOGGER.debug("Calling listeners for initial service registration");
for (ServiceListener listener : listeners) {
listener.register(service, registrationProperties);
}
} else {
LOGGER.debug("Calling listeners for initial service unregistration");
for (ServiceListener listener : listeners) {
listener.unregister(service, registrationProperties);
}
}
}
} catch (RuntimeException e) {
LOGGER.error("Error retrieving service from " + this, e);
throw e;
}
}
private void validateClasses(Object service) {
// Check if the service actually implement all the requested interfaces
if (metadata.getAutoExport() == ServiceMetadata.AUTO_EXPORT_DISABLED) {
Set<String> allClasses = new HashSet<String>();
ReflectionUtils.getSuperClasses(allClasses, service.getClass());
ReflectionUtils.getImplementedInterfaces(allClasses, service.getClass());
//This call is safe because we know that we don't need to call internalGet to get the answer
Set<String> classes = getClasses();
classes.removeAll(allClasses);
if (!classes.isEmpty()) {
throw new ComponentDefinitionException("The service implementation does not implement the required interfaces: " + classes);
}
}
}
public Object getService(Bundle bundle, ServiceRegistration registration) {
/** getService() can get called before registerService() returns with the registration object.
* So we need to set the registration object in case registration listeners call
* getServiceReference().
*/
this.registration.compareAndSet(null, registration);
return internalGetService(bundle, registration);
}
public void ungetService(Bundle bundle, ServiceRegistration registration, Object service) {
if (this.service instanceof ServiceFactory) {
((ServiceFactory) this.service).ungetService(bundle, registration, service);
}
}
/**
* Be careful to avoid calling this method from internalGetService or createService before the service
* field has been set. If you get this wrong you will get a StackOverflowError!
* @return
*/
private Set<String> getClasses() {
Set<String> classes;
switch (metadata.getAutoExport()) {
case ServiceMetadata.AUTO_EXPORT_INTERFACES:
classes = ReflectionUtils.getImplementedInterfaces(new HashSet<String>(), internalGetService().getClass());
break;
case ServiceMetadata.AUTO_EXPORT_CLASS_HIERARCHY:
classes = ReflectionUtils.getSuperClasses(new HashSet<String>(), internalGetService().getClass());
break;
case ServiceMetadata.AUTO_EXPORT_ALL_CLASSES:
classes = ReflectionUtils.getSuperClasses(new HashSet<String>(), internalGetService().getClass());
classes = ReflectionUtils.getImplementedInterfaces(classes, internalGetService().getClass());
break;
default:
classes = new HashSet<String>(metadata.getInterfaces());
break;
}
return classes;
}
/**
* Get the classes we need to proxy, for auto-export interfaces only, those
* will be just the interfaces implemented by the bean, for auto-export classes
* or everything, then just proxying the real bean class will give us everything we
* need, if none of the above then we need the class forms of the interfaces in
* the metadata
*
* Note that we use a template object here because we have already instantiated the bean
* that we're going to proxy. We can't call internalGetService because it would Stack Overflow.
* @return
* @throws ClassNotFoundException
*/
private Collection<Class<?>> getClassesForProxying(Object template) throws ClassNotFoundException {
Collection<Class<?>> classes;
switch (metadata.getAutoExport()) {
case ServiceMetadata.AUTO_EXPORT_INTERFACES:
classes = ReflectionUtils.getImplementedInterfacesAsClasses(new HashSet<Class<?>>(), template.getClass());
break;
case ServiceMetadata.AUTO_EXPORT_CLASS_HIERARCHY:
case ServiceMetadata.AUTO_EXPORT_ALL_CLASSES:
classes = ProxyUtils.asList(template.getClass());
break;
default:
classes = new HashSet<Class<?>>(convertStringsToClasses(metadata.getInterfaces()));
break;
}
return classes;
}
private Collection<? extends Class<?>> convertStringsToClasses(
List<String> interfaces) throws ClassNotFoundException {
Set<Class<?>> classes = new HashSet<Class<?>>();
for (String s : interfaces) {
classes.add(blueprintContainer.loadClass(s));
}
return classes;
}
private void createExplicitDependencies() {
if (explicitDependencies != null) {
for (Recipe recipe : explicitDependencies) {
createRecipe(recipe);
}
}
}
private Object createRecipe(Recipe recipe) {
String name = recipe.getName();
Repository repo = blueprintContainer.getRepository();
if (repo.getRecipe(name) != recipe) {
repo.putRecipe(name, recipe);
}
return repo.create(name);
}
private String getComponentName() {
if (metadata.getServiceComponent() instanceof RefMetadata) {
RefMetadata ref = (RefMetadata) metadata.getServiceComponent();
return ref.getComponentId();
} else {
return null;
}
}
protected void incrementActiveCalls()
{
// can be improved with LongAdder but Java 8 or backport (like guava) is needed
activeCalls.incrementAndGet();
}
protected void decrementActiveCalls()
{
int currentCount = activeCalls.decrementAndGet();
if (currentCount == 0 && quiesce) {
List<DestroyCallback> callbacksToCall;
synchronized (monitor) {
callbacksToCall = new ArrayList<DestroyCallback>(destroyCallbacks);
destroyCallbacks.clear();
}
for (DestroyCallback cbk : callbacksToCall) {
cbk.callback();
}
}
}
/*
The following problem is possible sometimes:
some threads already got a service and start to call it but incrementActiveCalls have not called yet
as a result activeCalls after service unregistration is not strongly decreasing and can be 0 but then not 0
*/
public void quiesce(DestroyCallback destroyCallback)
{
unregister();
quiesce = true;
DestroyCallback safeDestroyCallback = new DestroyOnceCallback(destroyCallback);
synchronized (monitor) {
destroyCallbacks.add(safeDestroyCallback);
}
if (activeCalls.get() == 0) {
safeDestroyCallback.callback();
synchronized (monitor) {
destroyCallbacks.remove(safeDestroyCallback);
}
}
}
private static class DestroyOnceCallback implements DestroyCallback {
private final DestroyCallback destroyCallback;
private final AtomicBoolean isDestroyed = new AtomicBoolean(false);
public DestroyOnceCallback(DestroyCallback destroyCallback) {
this.destroyCallback = destroyCallback;
}
@Override
public void callback() {
if (isDestroyed.compareAndSet(false, true)) {
destroyCallback.callback();
}
}
}
private class TriggerServiceFactory implements ServiceFactory {
private ServiceRecipe serviceRecipe;
private ComponentMetadata cm;
private ServiceMetadata sm;
private boolean isQuiesceAvailable;
public TriggerServiceFactory(ServiceRecipe serviceRecipe, ServiceMetadata cm) {
this.serviceRecipe = serviceRecipe;
this.cm = cm;
this.sm = cm;
this.isQuiesceAvailable = isClassAvailable("org.apache.aries.quiesce.participant.QuiesceParticipant");
}
public Object getService(Bundle bundle, ServiceRegistration registration) {
Object original = ServiceRecipe.this.getService(bundle, registration);
LOGGER.debug(LOG_ENTRY, "getService", original);
List<Interceptor> interceptors = new ArrayList<Interceptor>();
ComponentDefinitionRegistry reg = blueprintContainer.getComponentDefinitionRegistry();
List<Interceptor> registeredInterceptors = reg.getInterceptors(cm);
if (registeredInterceptors != null) {
interceptors.addAll(registeredInterceptors);
}
// Add quiesce interceptor if needed
if (isQuiesceAvailable)
{
interceptors.add(new QuiesceInterceptor(serviceRecipe));
}
// Exit if no interceptors configured
if (interceptors.isEmpty()) {
return original;
}
Object intercepted;
try {
Bundle b = FrameworkUtil.getBundle(original.getClass());
if (b == null) {
// we have a class from the framework parent, so use our bundle for proxying.
b = blueprintContainer.getBundleContext().getBundle();
}
InvocationListener collaborator = CollaboratorFactory.create(cm, interceptors);
intercepted = blueprintContainer.getProxyManager().createInterceptingProxy(b,
getClassesForProxying(original), original, collaborator);
} catch (Exception u) {
Bundle b = blueprintContainer.getBundleContext().getBundle();
LOGGER.info("Unable to create a proxy object for the service " + getName() + " defined in bundle " + b.getSymbolicName() + "/" + b.getVersion() + " with id. Returning the original object instead.", u);
LOGGER.debug(LOG_EXIT, "getService", original);
return original;
}
LOGGER.debug(LOG_EXIT, "getService", intercepted);
return intercepted;
}
public void ungetService(Bundle bundle, ServiceRegistration registration, Object service) {
ServiceRecipe.this.ungetService(bundle, registration, service);
}
}
private class ServiceRegistrationProxy implements ServiceRegistration {
public ServiceReference getReference() {
return ServiceRecipe.this.getReference();
}
public void setProperties(Dictionary properties) {
ServiceRecipe.this.setProperties(properties);
}
public void unregister() {
throw new UnsupportedOperationException();
}
}
private class PropertiesUpdater implements ServiceProcessor.ServicePropertiesUpdater {
public String getId() {
return metadata.getId();
}
public void updateProperties(Dictionary properties) {
Hashtable table = JavaUtils.getProperties(ServiceRecipe.this.getReference());
JavaUtils.copy(table, properties);
ServiceRecipe.this.setProperties(table);
}
}
private boolean isClassAvailable(String clazz) {
try {
getClass().getClassLoader().loadClass(clazz);
return true;
}
catch (ClassNotFoundException e) {
return false;
}
catch (NoClassDefFoundError e) {
return false;
}
}
}
| 9,504 |
0 | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/container/AbstractTracked.java | /*
* Copyright (c) OSGi Alliance (2007, 2012). All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.blueprint.container;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
/**
* Abstract class to track items. If a Tracker is reused (closed then reopened),
* then a new AbstractTracked object is used. This class acts a map of tracked
* item -> customized object. Subclasses of this class will act as the listener
* object for the tracker. This class is used to synchronize access to the
* tracked items. This is not a public class. It is only for use by the
* implementation of the Tracker class.
*
* @param <S> The tracked item. It is the key.
* @param <T> The value mapped to the tracked item.
* @param <R> The reason the tracked item is being tracked or untracked.
* @ThreadSafe
* @version $Id: 16340086b98d308c2d12f13bcd87fc6467a5a367 $
* @since 1.4
*/
abstract class AbstractTracked<S, T, R> {
/* set this to true to compile in debug messages */
static final boolean DEBUG = false;
/**
* Map of tracked items to customized objects.
*
* @GuardedBy this
*/
private final Map<S, T> tracked;
/**
* Modification count. This field is initialized to zero and incremented by
* modified.
*
* @GuardedBy this
*/
private int trackingCount;
/**
* List of items in the process of being added. This is used to deal with
* nesting of events. Since events may be synchronously delivered, events
* can be nested. For example, when processing the adding of a service and
* the customizer causes the service to be unregistered, notification to the
* nested call to untrack that the service was unregistered can be made to
* the track method.
*
* Since the ArrayList implementation is not synchronized, all access to
* this list must be protected by the same synchronized object for
* thread-safety.
*
* @GuardedBy this
*/
private final List<S> adding;
/**
* true if the tracked object is closed.
*
* This field is volatile because it is set by one thread and read by
* another.
*/
volatile boolean closed;
/**
* Initial list of items for the tracker. This is used to correctly process
* the initial items which could be modified before they are tracked. This
* is necessary since the initial set of tracked items are not "announced"
* by events and therefore the event which makes the item untracked could be
* delivered before we track the item.
*
* An item must not be in both the initial and adding lists at the same
* time. An item must be moved from the initial list to the adding list
* "atomically" before we begin tracking it.
*
* Since the LinkedList implementation is not synchronized, all access to
* this list must be protected by the same synchronized object for
* thread-safety.
*
* @GuardedBy this
*/
private final LinkedList<S> initial;
/**
* AbstractTracked constructor.
*/
AbstractTracked() {
tracked = new HashMap<S, T>();
trackingCount = 0;
adding = new ArrayList<S>(6);
initial = new LinkedList<S>();
closed = false;
}
/**
* Set initial list of items into tracker before events begin to be
* received.
*
* This method must be called from Tracker's open method while synchronized
* on this object in the same synchronized block as the add listener call.
*
* @param list The initial list of items to be tracked. {@code null} entries
* in the list are ignored.
* @GuardedBy this
*/
void setInitial(S[] list) {
if (list == null) {
return;
}
for (S item : list) {
if (item == null) {
continue;
}
if (DEBUG) {
System.out.println("AbstractTracked.setInitial: " + item); //$NON-NLS-1$
}
initial.add(item);
}
}
/**
* Track the initial list of items. This is called after events can begin to
* be received.
*
* This method must be called from Tracker's open method while not
* synchronized on this object after the add listener call.
*
*/
void trackInitial() {
while (true) {
S item;
synchronized (this) {
if (closed || (initial.size() == 0)) {
/*
* if there are no more initial items
*/
return; /* we are done */
}
/*
* move the first item from the initial list to the adding list
* within this synchronized block.
*/
item = initial.removeFirst();
if (tracked.get(item) != null) {
/* if we are already tracking this item */
if (DEBUG) {
System.out.println("AbstractTracked.trackInitial[already tracked]: " + item); //$NON-NLS-1$
}
continue; /* skip this item */
}
if (adding.contains(item)) {
/*
* if this item is already in the process of being added.
*/
if (DEBUG) {
System.out.println("AbstractTracked.trackInitial[already adding]: " + item); //$NON-NLS-1$
}
continue; /* skip this item */
}
adding.add(item);
}
if (DEBUG) {
System.out.println("AbstractTracked.trackInitial: " + item); //$NON-NLS-1$
}
trackAdding(item, null); /*
* Begin tracking it. We call trackAdding
* since we have already put the item in the
* adding list.
*/
}
}
/**
* Called by the owning Tracker object when it is closed.
*/
void close() {
closed = true;
}
/**
* Begin to track an item.
*
* @param item Item to be tracked.
* @param related Action related object.
*/
void track(final S item, final R related) {
final T object;
synchronized (this) {
if (closed) {
return;
}
object = tracked.get(item);
if (object == null) { /* we are not tracking the item */
if (adding.contains(item)) {
/* if this item is already in the process of being added. */
if (DEBUG) {
System.out.println("AbstractTracked.track[already adding]: " + item); //$NON-NLS-1$
}
return;
}
adding.add(item); /* mark this item is being added */
} else { /* we are currently tracking this item */
if (DEBUG) {
System.out.println("AbstractTracked.track[modified]: " + item); //$NON-NLS-1$
}
modified(); /* increment modification count */
}
}
if (object == null) { /* we are not tracking the item */
trackAdding(item, related);
} else {
/* Call customizer outside of synchronized region */
customizerModified(item, related, object);
/*
* If the customizer throws an unchecked exception, it is safe to
* let it propagate
*/
}
}
/**
* Common logic to add an item to the tracker used by track and
* trackInitial. The specified item must have been placed in the adding list
* before calling this method.
*
* @param item Item to be tracked.
* @param related Action related object.
*/
private void trackAdding(final S item, final R related) {
if (DEBUG) {
System.out.println("AbstractTracked.trackAdding: " + item); //$NON-NLS-1$
}
T object = null;
boolean becameUntracked = false;
/* Call customizer outside of synchronized region */
try {
object = customizerAdding(item, related);
/*
* If the customizer throws an unchecked exception, it will
* propagate after the finally
*/
} finally {
synchronized (this) {
if (adding.remove(item) && !closed) {
/*
* if the item was not untracked during the customizer
* callback
*/
if (object != null) {
tracked.put(item, object);
modified(); /* increment modification count */
notifyAll(); /* notify any waiters */
}
} else {
becameUntracked = true;
}
}
}
/*
* The item became untracked during the customizer callback.
*/
if (becameUntracked && (object != null)) {
if (DEBUG) {
System.out.println("AbstractTracked.trackAdding[removed]: " + item); //$NON-NLS-1$
}
/* Call customizer outside of synchronized region */
customizerRemoved(item, related, object);
/*
* If the customizer throws an unchecked exception, it is safe to
* let it propagate
*/
}
}
/**
* Discontinue tracking the item.
*
* @param item Item to be untracked.
* @param related Action related object.
*/
void untrack(final S item, final R related) {
final T object;
synchronized (this) {
if (initial.remove(item)) { /*
* if this item is already in the list
* of initial references to process
*/
if (DEBUG) {
System.out.println("AbstractTracked.untrack[removed from initial]: " + item); //$NON-NLS-1$
}
return; /*
* we have removed it from the list and it will not be
* processed
*/
}
if (adding.remove(item)) { /*
* if the item is in the process of
* being added
*/
if (DEBUG) {
System.out.println("AbstractTracked.untrack[being added]: " + item); //$NON-NLS-1$
}
return; /*
* in case the item is untracked while in the process of
* adding
*/
}
object = tracked.remove(item); /*
* must remove from tracker before
* calling customizer callback
*/
if (object == null) { /* are we actually tracking the item */
return;
}
modified(); /* increment modification count */
}
if (DEBUG) {
System.out.println("AbstractTracked.untrack[removed]: " + item); //$NON-NLS-1$
}
/* Call customizer outside of synchronized region */
customizerRemoved(item, related, object);
/*
* If the customizer throws an unchecked exception, it is safe to let it
* propagate
*/
}
/**
* Returns the number of tracked items.
*
* @return The number of tracked items.
*
* @GuardedBy this
*/
int size() {
return tracked.size();
}
/**
* Returns if the tracker is empty.
*
* @return Whether the tracker is empty.
*
* @GuardedBy this
* @since 1.5
*/
boolean isEmpty() {
return tracked.isEmpty();
}
/**
* Return the customized object for the specified item
*
* @param item The item to lookup in the map
* @return The customized object for the specified item.
*
* @GuardedBy this
*/
T getCustomizedObject(final S item) {
return tracked.get(item);
}
/**
* Copy the tracked items into an array.
*
* @param list An array to contain the tracked items.
* @return The specified list if it is large enough to hold the tracked
* items or a new array large enough to hold the tracked items.
* @GuardedBy this
*/
S[] copyKeys(final S[] list) {
return tracked.keySet().toArray(list);
}
/**
* Increment the modification count. If this method is overridden, the
* overriding method MUST call this method to increment the tracking count.
*
* @GuardedBy this
*/
void modified() {
trackingCount++;
}
/**
* Returns the tracking count for this {@code ServiceTracker} object.
*
* The tracking count is initialized to 0 when this object is opened. Every
* time an item is added, modified or removed from this object the tracking
* count is incremented.
*
* @GuardedBy this
* @return The tracking count for this object.
*/
int getTrackingCount() {
return trackingCount;
}
/**
* Copy the tracked items and associated values into the specified map.
*
* @param <M> Type of {@code Map} to hold the tracked items and associated
* values.
* @param map The map into which to copy the tracked items and associated
* values. This map must not be a user provided map so that user code
* is not executed while synchronized on this.
* @return The specified map.
* @GuardedBy this
* @since 1.5
*/
<M extends Map<? super S, ? super T>> M copyEntries(final M map) {
map.putAll(tracked);
return map;
}
/**
* Call the specific customizer adding method. This method must not be
* called while synchronized on this object.
*
* @param item Item to be tracked.
* @param related Action related object.
* @return Customized object for the tracked item or {@code null} if the
* item is not to be tracked.
*/
abstract T customizerAdding(final S item, final R related);
/**
* Call the specific customizer modified method. This method must not be
* called while synchronized on this object.
*
* @param item Tracked item.
* @param related Action related object.
* @param object Customized object for the tracked item.
*/
abstract void customizerModified(final S item, final R related, final T object);
/**
* Call the specific customizer removed method. This method must not be
* called while synchronized on this object.
*
* @param item Tracked item.
* @param related Action related object.
* @param object Customized object for the tracked item.
*/
abstract void customizerRemoved(final S item, final R related, final T object);
}
| 9,505 |
0 | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/container/SatisfiableRecipe.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.blueprint.container;
import org.apache.aries.blueprint.di.Recipe;
/**
* Interface used to describe an object which can satisfy a constraint or not.
*
* If the state of the object changes, registered SatisfactionListener objects
* will be notified of the change.
*
* @version $Rev$, $Date$
*/
public interface SatisfiableRecipe extends Recipe {
/**
* A listener that will be notified when the constraint satisfaction changes.
*
* @version $Rev$, $Date$
*/
public interface SatisfactionListener {
void notifySatisfaction(SatisfiableRecipe satisfiable);
}
void start(SatisfactionListener listener);
void stop();
boolean isSatisfied();
String getOsgiFilter();
boolean isStaticLifecycle();
}
| 9,506 |
0 | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/container/DestroyCallback.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.blueprint.container;
/**
* A callback to indicate that a destroy operation has completed
*/
public interface DestroyCallback {
void callback();
}
| 9,507 |
0 | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/container/BlueprintQuiesceParticipant.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.blueprint.container;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.aries.blueprint.di.Recipe;
import org.apache.aries.quiesce.manager.QuiesceCallback;
import org.apache.aries.quiesce.participant.QuiesceParticipant;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
public class BlueprintQuiesceParticipant implements QuiesceParticipant {
private final BundleContext ctx;
private final BlueprintExtender extender;
public BlueprintQuiesceParticipant(BundleContext context, BlueprintExtender extender) {
this.ctx = context;
this.extender = extender;
}
/**
* A Threadpool for running quiesce operations
*/
private final ExecutorService executor = new ThreadPoolExecutor(0, 10, 10, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new ThreadFactory() {
public Thread newThread(Runnable r) {
Thread t = new Thread(r, "Blueprint-Container-ThreadPool");
t.setDaemon(true);
return t;
}
});
public void quiesce(QuiesceCallback callback, List<Bundle> bundlesToQuiesce) {
boolean shutdownMe = false;
for (Bundle b : bundlesToQuiesce) {
try {
executor.execute(new QuiesceBundle(callback, b, extender));
} catch (RejectedExecutionException re) {
}
//If we are quiescing, then we need to quiesce this threadpool!
shutdownMe |= b.equals(ctx.getBundle());
}
if (shutdownMe) executor.shutdown();
}
/**
* A runnable Quiesce operation for a single bundle
*/
private static final class QuiesceBundle implements Runnable {
/**
* The bundle being quiesced
*/
private final Bundle bundleToQuiesce;
private final QuiesceCallback callback;
private final BlueprintExtender extender;
public QuiesceBundle(QuiesceCallback callback, Bundle bundleToQuiesce,
BlueprintExtender extender) {
super();
this.callback = callback;
this.bundleToQuiesce = bundleToQuiesce;
this.extender = extender;
}
public void run() {
BlueprintContainerImpl container = extender.getBlueprintContainerImpl(bundleToQuiesce);
// have we got an actual blueprint bundle
if (container != null) {
BlueprintRepository repository = container.getRepository();
Set<String> names = repository.getNames();
container.quiesce();
QuiesceDelegatingCallback qdcbk = new QuiesceDelegatingCallback(callback, bundleToQuiesce);
for (String name : names) {
Recipe recipe = repository.getRecipe(name);
if (recipe instanceof ServiceRecipe) {
qdcbk.callCountDown.incrementAndGet();
((ServiceRecipe) recipe).quiesce(qdcbk);
}
}
//Either there were no services and we win, or there were services but they
//have all finished and we win, or they still have tidy up to do, but we
//end up at 0 eventually
qdcbk.callback();
} else {
// for non-Blueprint bundles just call return completed
callback.bundleQuiesced(bundleToQuiesce);
}
}
}
/**
* A wrapper to protect our internals from the Quiesce API so that we can make it
* an optional dependency
*/
private static final class QuiesceDelegatingCallback implements DestroyCallback {
/**
* The callback to delegate to
*/
private final QuiesceCallback callback;
/**
* The single bundle being quiesced by this DestroyCallback
*/
private final Bundle toQuiesce;
/**
* A countdown that starts at one so it can't finish before we do!
*/
private final AtomicInteger callCountDown = new AtomicInteger(1);
public QuiesceDelegatingCallback(QuiesceCallback cbk, Bundle b) {
callback = cbk;
toQuiesce = b;
}
public void callback() {
if (callCountDown.decrementAndGet() == 0) {
callback.bundleQuiesced(toQuiesce);
}
}
}
}
| 9,508 |
0 | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/container/AbstractServiceReferenceRecipe.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.blueprint.container;
import java.lang.reflect.Method;
import java.security.AccessControlContext;
import java.security.AccessController;
import java.security.DomainCombiner;
import java.security.Permission;
import java.security.PrivilegedAction;
import java.security.ProtectionDomain;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.aries.blueprint.BlueprintConstants;
import org.apache.aries.blueprint.ExtendedReferenceMetadata;
import org.apache.aries.blueprint.ExtendedServiceReferenceMetadata;
import org.apache.aries.blueprint.di.AbstractRecipe;
import org.apache.aries.blueprint.di.CollectionRecipe;
import org.apache.aries.blueprint.di.ExecutionContext;
import org.apache.aries.blueprint.di.Recipe;
import org.apache.aries.blueprint.di.ValueRecipe;
import org.apache.aries.blueprint.services.ExtendedBlueprintContainer;
import org.apache.aries.blueprint.utils.ReflectionUtils;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceEvent;
import org.osgi.framework.ServiceListener;
import org.osgi.framework.ServiceReference;
import org.osgi.service.blueprint.container.ComponentDefinitionException;
import org.osgi.service.blueprint.container.ReifiedType;
import org.osgi.service.blueprint.reflect.ReferenceListener;
import org.osgi.service.blueprint.reflect.ReferenceMetadata;
import org.osgi.service.blueprint.reflect.ServiceReferenceMetadata;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Abstract class for service reference recipes.
*
* TODO: if we have a single interface (which is the standard behavior), then we should be able to get rid of
* the proxyClassloader and just use this interface classloader to define the proxy
*
* TODO: it is allowed to have no interface defined at all, which should result in an empty proxy
*
* @version $Rev$, $Date$
*/
@SuppressWarnings("rawtypes")
public abstract class AbstractServiceReferenceRecipe extends AbstractRecipe implements ServiceListener, SatisfiableRecipe {
private static final Logger LOGGER = LoggerFactory.getLogger(AbstractServiceReferenceRecipe.class);
protected final ExtendedBlueprintContainer blueprintContainer;
protected final ServiceReferenceMetadata metadata;
protected final ValueRecipe filterRecipe;
protected final CollectionRecipe listenersRecipe;
protected final List<Recipe> explicitDependencies;
protected final boolean optional;
/** The OSGi filter for tracking references */
protected final String filter;
/** The list of listeners for this reference. This list will be lazy created */
protected List<Listener> listeners;
private final AtomicBoolean started = new AtomicBoolean();
private final AtomicBoolean satisfied = new AtomicBoolean();
private volatile SatisfactionListener satisfactionListener;
private final AccessControlContext accessControlContext;
private final Tracked tracked = new Tracked();
protected AbstractServiceReferenceRecipe(String name,
ExtendedBlueprintContainer blueprintContainer,
ServiceReferenceMetadata metadata,
ValueRecipe filterRecipe,
CollectionRecipe listenersRecipe,
List<Recipe> explicitDependencies) {
super(name);
this.prototype = false;
this.blueprintContainer = blueprintContainer;
this.metadata = metadata;
this.filterRecipe = filterRecipe;
this.listenersRecipe = listenersRecipe;
this.explicitDependencies = explicitDependencies;
this.optional = (metadata.getAvailability() == ReferenceMetadata.AVAILABILITY_OPTIONAL);
this.filter = createOsgiFilter(metadata, null);
accessControlContext = (System.getSecurityManager() != null) ? createAccessControlContext() : null;
}
public CollectionRecipe getListenersRecipe() {
return listenersRecipe;
}
public void start(SatisfactionListener listener) {
if (listener == null) throw new NullPointerException("satisfactionListener is null");
if (started.compareAndSet(false, true)) {
try {
satisfactionListener = listener;
satisfied.set(optional);
// Synchronized block on references so that service events won't interfere with initial references tracking
// though this may not be sufficient because we don't control ordering of those events
synchronized (tracked) {
getBundleContextForServiceLookup().addServiceListener(this, getOsgiFilter());
ServiceReference[] references = getBundleContextForServiceLookup().getServiceReferences((String) null, getOsgiFilter());
tracked.setInitial(references != null ? references : new ServiceReference[0]);
}
tracked.trackInitial();
satisfied.set(optional || !tracked.isEmpty());
retrack();
LOGGER.debug("Found initial references {} for OSGi service {}", getServiceReferences(), getOsgiFilter());
} catch (InvalidSyntaxException e) {
throw new ComponentDefinitionException(e);
}
}
}
public void stop() {
if (started.compareAndSet(true, false)) {
tracked.close();
try {
getBundleContextForServiceLookup().removeServiceListener(this);
} catch (IllegalStateException e) {
// Ignore in case bundle context is already invalidated
}
doStop();
for (ServiceReference ref : getServiceReferences()) {
untrack(ref);
}
satisfied.set(false);
satisfactionListener = null;
}
}
protected void doStop() {
}
protected boolean isStarted() {
return started.get();
}
public boolean isSatisfied() {
return satisfied.get();
}
@Override
public List<Recipe> getConstructorDependencies() {
List<Recipe> recipes = new ArrayList<Recipe>();
if (explicitDependencies != null) {
recipes.addAll(explicitDependencies);
}
return recipes;
}
public List<Recipe> getDependencies() {
List<Recipe> recipes = new ArrayList<Recipe>();
if (listenersRecipe != null) {
recipes.add(listenersRecipe);
}
recipes.addAll(getConstructorDependencies());
return recipes;
}
public String getOsgiFilter() {
if (filterRecipe != null && blueprintContainer instanceof BlueprintContainerImpl) {
BlueprintContainerImpl.State state = ((BlueprintContainerImpl) blueprintContainer).getState();
switch (state) {
case InitialReferencesSatisfied:
case WaitForInitialReferences2:
case Create:
case Created:
return createOsgiFilter(metadata, getExtendedOsgiFilter());
}
}
return filter;
}
private String getExtendedOsgiFilter() {
if (filterRecipe != null) {
Object object;
BlueprintRepository repository = ((BlueprintContainerImpl) blueprintContainer).getRepository();
ExecutionContext oldContext = null;
try {
oldContext = ExecutionContext.Holder.setContext(repository);
object = filterRecipe.create();
} finally {
ExecutionContext.Holder.setContext(oldContext);
}
if (object != null) {
String flt = object.toString();
if (flt != null && flt.length() > 0) {
if (!flt.startsWith("(")) {
flt = "(" + flt + ")";
}
return flt;
}
}
}
return null;
}
@SuppressWarnings("unchecked")
protected Object getServiceSecurely(final ServiceReference serviceReference) {
if (accessControlContext == null) {
return getBundleContextForServiceLookup().getService(serviceReference);
} else {
// If we're operating with security, use the privileges of the bundle
// we're managing to do the lookup
return AccessController.doPrivileged(new PrivilegedAction<Object>() {
public Object run() {
return getBundleContextForServiceLookup().getService(serviceReference);
}
}, accessControlContext);
}
}
/**
* We may need to execute code within a doPrivileged block, and if so, it should be the privileges of the
* bundle with the blueprint file that get used, not the privileges of blueprint-core. To achieve this we
* use an access context.
*
* @return
*/
private AccessControlContext createAccessControlContext() {
return new AccessControlContext(AccessController.getContext(), new DomainCombiner() {
public ProtectionDomain[] combine(ProtectionDomain[] arg0, ProtectionDomain[] arg1) {
ProtectionDomain protectionDomain = new ProtectionDomain(null, null) {
public boolean implies(Permission permission) {
return getBundleContextForServiceLookup().getBundle().hasPermission(permission);
}
};
return new ProtectionDomain[] {
protectionDomain
};
}
});
}
@SuppressWarnings("unchecked")
protected void createListeners() {
if (listenersRecipe != null) {
List<Listener> listeners = (List<Listener>) listenersRecipe.create();
for (Listener listener : listeners) {
List<Class> classList = new ArrayList<Class>();
Class clz = getInterfaceClass();
if (clz != null) {
classList.add(clz);
} else {
classList.add(Object.class);
}
listener.init(classList);
}
this.listeners = listeners;
} else {
this.listeners = Collections.emptyList();
}
}
protected List<Class<?>> loadAllClasses(Iterable<String> interfaceNames) {
List<Class<?>> classes = new ArrayList<Class<?>>();
for (String name : interfaceNames) {
Class<?> clazz = loadClass(name);
classes.add(clazz);
}
return classes;
}
protected ReifiedType loadType(String typeName, ClassLoader fromClassLoader) {
if (typeName == null) {
return null;
}
try {
// this method is overriden to use the blueprint container directly
// because proxies can be created outside of the recipe creation which
// would lead to an exception because the context is not set
// TODO: consider having the context as a property on the recipe rather than a thread local
return GenericType.parse(typeName, fromClassLoader != null ? fromClassLoader : blueprintContainer);
} catch (ClassNotFoundException e) {
throw new ComponentDefinitionException("Unable to load class " + typeName + " from recipe " + this, e);
}
}
protected Object createProxy(final Callable<Object> dispatcher, Set<Class<?>> interfaces) throws Exception {
if (!interfaces.iterator().hasNext()) {
return new Object();
} else {
// Check class proxying
boolean proxyClass = false;
if (metadata instanceof ExtendedServiceReferenceMetadata) {
proxyClass = (((ExtendedServiceReferenceMetadata) metadata).getProxyMethod() & ExtendedServiceReferenceMetadata.PROXY_METHOD_CLASSES) != 0;
}
if (!proxyClass) {
for (Class cl : interfaces) {
if (!cl.isInterface()) {
throw new ComponentDefinitionException("A class " + cl.getName() + " was found in the interfaces list, but class proxying is not allowed by default. The ext:proxy-method='classes' attribute needs to be added to this service reference.");
}
}
}
//We don't use the #getBundleContextForServiceLookup() method here, the bundle requesting the proxy is the
//blueprint client, not the context of the lookup
return blueprintContainer.getProxyManager().createDelegatingProxy(blueprintContainer.getBundleContext().getBundle(), interfaces, dispatcher, null);
}
}
public void serviceChanged(ServiceEvent event) {
int eventType = event.getType();
ServiceReference ref = event.getServiceReference();
switch (eventType) {
case ServiceEvent.REGISTERED:
serviceAdded(ref, event);
break;
case ServiceEvent.MODIFIED:
serviceModified(ref, event);
break;
case ServiceEvent.UNREGISTERING:
serviceRemoved(ref, event);
break;
}
}
private void serviceAdded(ServiceReference ref, ServiceEvent event) {
LOGGER.debug("Tracking reference {} for OSGi service {}", ref, getOsgiFilter());
if (isStarted()) {
tracked.track(ref, event);
boolean satisfied;
synchronized (tracked) {
satisfied = optional || !tracked.isEmpty();
}
track(ref);
setSatisfied(satisfied);
}
}
private void serviceModified(ServiceReference ref, ServiceEvent event) {
// ref must be in references and must be satisfied
if (isStarted()) {
tracked.track(ref, event);
track(ref);
}
}
private void serviceRemoved(ServiceReference ref, ServiceEvent event) {
if (isStarted()) {
LOGGER.debug("Untracking reference {} for OSGi service {}", ref, getOsgiFilter());
tracked.untrack(ref, event);
boolean satisfied;
synchronized (tracked) {
satisfied = optional || !tracked.isEmpty();
}
setSatisfied(satisfied);
untrack(ref);
}
}
protected Class getInterfaceClass() {
Class clz = getRuntimeClass(metadata);
if (clz != null)
return clz;
else if (metadata.getInterface() != null)
return loadClass(metadata.getInterface());
return null;
}
protected static Class getRuntimeClass(ServiceReferenceMetadata metadata) {
if (metadata instanceof ExtendedServiceReferenceMetadata && ((ExtendedServiceReferenceMetadata) metadata).getRuntimeInterface() != null) {
return ((ExtendedServiceReferenceMetadata) metadata).getRuntimeInterface();
}
return null;
}
protected BundleContext getBundleContextForServiceLookup() {
if (metadata instanceof ExtendedServiceReferenceMetadata && ((ExtendedServiceReferenceMetadata) metadata).getRuntimeInterface() != null) {
BundleContext context = ((ExtendedServiceReferenceMetadata) metadata).getBundleContext();
if (context != null) {
return context;
}
}
return blueprintContainer.getBundleContext();
}
protected void setSatisfied(boolean s) {
// This check will ensure an atomic comparision and set
// so that it will only be true if the value actually changed
if (satisfied.getAndSet(s) != s) {
LOGGER.debug("Service reference with filter {} satisfied {}", getOsgiFilter(), this.satisfied);
SatisfactionListener listener = this.satisfactionListener;
if (listener != null) {
listener.notifySatisfaction(this);
}
}
}
protected abstract void track(ServiceReference reference);
protected abstract void untrack(ServiceReference reference);
protected abstract void retrack();
protected void updateListeners() {
boolean empty;
synchronized (tracked) {
empty = tracked.isEmpty();
}
if (empty) {
unbind(null, null);
} else {
retrack();
}
}
protected void bind(ServiceReference reference, Object service) {
if (listeners != null) {
for (Listener listener : listeners) {
if (listener != null) {
listener.bind(reference, service);
}
}
}
}
protected void unbind(ServiceReference reference, Object service) {
if (listeners != null) {
for (Listener listener : listeners) {
if (listener != null) {
listener.unbind(reference, service);
}
}
}
}
public List<ServiceReference> getServiceReferences() {
ServiceReference[] refs;
synchronized (tracked) {
refs = new ServiceReference[tracked.size()];
tracked.copyKeys(refs);
}
return Arrays.asList(refs);
}
public ServiceReference getBestServiceReference() {
List<ServiceReference> references = getServiceReferences();
int length = references.size();
if (length == 0) { /* if no service is being tracked */
return null;
}
int index = 0;
if (length > 1) { /* if more than one service, select highest ranking */
int maxRanking = Integer.MIN_VALUE;
long minId = Long.MAX_VALUE;
for (int i = 0; i < length; i++) {
Object property = references.get(i).getProperty(Constants.SERVICE_RANKING);
int ranking = (property instanceof Integer) ? (Integer) property : 0;
long id = (Long) references.get(i).getProperty(Constants.SERVICE_ID);
if ((ranking > maxRanking) || (ranking == maxRanking && id < minId)) {
index = i;
maxRanking = ranking;
minId = id;
}
}
}
return references.get(index);
}
public static class Listener {
private static final Logger LOGGER = LoggerFactory.getLogger(Listener.class);
private Object listener;
private ReferenceListener metadata;
private ExtendedBlueprintContainer blueprintContainer;
private Set<Method> bindMethodsReference = new HashSet<Method>();
private Set<Method> bindMethodsObjectProp = new HashSet<Method>();
private Set<Method> bindMethodsObject = new HashSet<Method>();
private Set<Method> unbindMethodsReference = new HashSet<Method>();
private Set<Method> unbindMethodsObject = new HashSet<Method>();
private Set<Method> unbindMethodsObjectProp = new HashSet<Method>();
public void setListener(Object listener) {
this.listener = listener;
}
public void setMetadata(ReferenceListener metadata) {
this.metadata = metadata;
}
public void setBlueprintContainer(ExtendedBlueprintContainer blueprintContainer) {
this.blueprintContainer = blueprintContainer;
}
public void init(Collection<Class> classes) {
Set<Class> clazzes = new HashSet<Class>(classes);
clazzes.add(Object.class);
Class listenerClass = listener.getClass();
String bindName = metadata.getBindMethod();
if (bindName != null) {
bindMethodsReference.addAll(ReflectionUtils.findCompatibleMethods(listenerClass, bindName, new Class[] { ServiceReference.class }));
for (Class clazz : clazzes) {
bindMethodsObject.addAll(ReflectionUtils.findCompatibleMethods(listenerClass, bindName, new Class[] { clazz }));
bindMethodsObjectProp.addAll(ReflectionUtils.findCompatibleMethods(listenerClass, bindName, new Class[] { clazz, Map.class }));
}
if (bindMethodsReference.size() + bindMethodsObject.size() + bindMethodsObjectProp.size() == 0) {
throw new ComponentDefinitionException("No matching methods found for listener bind method: " + bindName);
}
}
String unbindName = metadata.getUnbindMethod();
if (unbindName != null) {
unbindMethodsReference.addAll(ReflectionUtils.findCompatibleMethods(listenerClass, unbindName, new Class[] { ServiceReference.class }));
for (Class clazz : clazzes) {
unbindMethodsObject.addAll(ReflectionUtils.findCompatibleMethods(listenerClass, unbindName, new Class[] { clazz }));
unbindMethodsObjectProp.addAll(ReflectionUtils.findCompatibleMethods(listenerClass, unbindName, new Class[] { clazz, Map.class }));
}
if (unbindMethodsReference.size() + unbindMethodsObject.size() + unbindMethodsObjectProp.size() == 0) {
throw new ComponentDefinitionException("No matching methods found for listener unbind method: " + unbindName);
}
}
}
public void bind(ServiceReference reference, Object service) {
invokeMethods(bindMethodsReference, bindMethodsObject, bindMethodsObjectProp, reference, service);
}
public void unbind(ServiceReference reference, Object service) {
invokeMethods(unbindMethodsReference, unbindMethodsObject, unbindMethodsObjectProp, reference, service);
}
private void invokeMethods(Set<Method> referenceMethods, Set<Method> objectMethods, Set<Method> objectPropMethods, ServiceReference reference, Object service) {
for (Method method : referenceMethods) {
try {
ReflectionUtils.invoke(blueprintContainer.getAccessControlContext(),
method, listener, reference);
} catch (Exception e) {
LOGGER.error("Error calling listener method " + method, e);
}
}
for (Method method : objectMethods) {
try {
ReflectionUtils.invoke(blueprintContainer.getAccessControlContext(),
method, listener, service);
} catch (Exception e) {
LOGGER.error("Error calling listener method " + method, e);
}
}
Map<String, Object> props = null;
for (Method method : objectPropMethods) {
if (props == null) {
props = new HashMap<String, Object>();
if (reference != null) {
for (String name : reference.getPropertyKeys()) {
props.put(name, reference.getProperty(name));
}
}
}
try {
ReflectionUtils.invoke(blueprintContainer.getAccessControlContext(),
method, listener, service, props);
} catch (Exception e) {
LOGGER.error("Error calling listener method " + method, e);
}
}
}
}
/**
* Create the OSGi filter corresponding to the ServiceReferenceMetadata constraints
*
* @param metadata the service reference metadata
* @return the OSGi filter
*/
private static String createOsgiFilter(ServiceReferenceMetadata metadata, String extendedFilter) {
List<String> members = new ArrayList<String>();
// Handle filter
String flt = metadata.getFilter();
if (flt != null && flt.length() > 0) {
if (!flt.startsWith("(")) {
flt = "(" + flt + ")";
}
members.add(flt);
}
// Handle extended filter
if (extendedFilter != null && extendedFilter.length() > 0) {
if (!extendedFilter.startsWith("(")) {
extendedFilter = "(" + extendedFilter + ")";
}
members.add(extendedFilter);
}
// Handle interfaces
String interfaceName = metadata.getInterface();
Class runtimeClass = getRuntimeClass(metadata);
if (runtimeClass != null) {
interfaceName = runtimeClass.getName();
}
if (interfaceName != null && interfaceName.length() > 0) {
if (metadata instanceof ExtendedReferenceMetadata) {
ExtendedReferenceMetadata erm = (ExtendedReferenceMetadata) metadata;
if (!erm.getExtraInterfaces().isEmpty()) {
StringBuilder sb = new StringBuilder("(&");
sb.append("(" + Constants.OBJECTCLASS + "=" + interfaceName + ")");
for (String s : erm.getExtraInterfaces()) {
sb.append("(" + Constants.OBJECTCLASS + "=" + s + ")");
}
sb.append(")");
members.add(sb.toString());
} else {
members.add("(" + Constants.OBJECTCLASS + "=" + interfaceName + ")");
}
} else {
members.add("(" + Constants.OBJECTCLASS + "=" + interfaceName + ")");
}
}
// Handle component name
String componentName = metadata.getComponentName();
if (componentName != null && componentName.length() > 0) {
members.add("(" + BlueprintConstants.COMPONENT_NAME_PROPERTY + "=" + componentName + ")");
}
// Create filter
if (members.isEmpty()) {
throw new IllegalStateException("No constraints were specified on the service reference");
}
if (members.size() == 1) {
return members.get(0);
}
StringBuilder sb = new StringBuilder("(&");
for (String member : members) {
sb.append(member);
}
sb.append(")");
return sb.toString();
}
private class Tracked extends AbstractTracked<ServiceReference, ServiceReference, ServiceEvent> {
@Override
ServiceReference customizerAdding(ServiceReference item, ServiceEvent related) {
return item;
}
@Override
void customizerModified(ServiceReference item, ServiceEvent related, ServiceReference object) {
}
@Override
void customizerRemoved(ServiceReference item, ServiceEvent related, ServiceReference object) {
}
}
}
| 9,509 |
0 | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/container/BlueprintContainerImpl.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.blueprint.container;
import java.net.URI;
import java.net.URL;
import java.security.AccessControlContext;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Dictionary;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.aries.blueprint.BlueprintConstants;
import org.apache.aries.blueprint.ComponentDefinitionRegistryProcessor;
import org.apache.aries.blueprint.ExtendedBeanMetadata;
import org.apache.aries.blueprint.NamespaceHandler;
import org.apache.aries.blueprint.NamespaceHandler2;
import org.apache.aries.blueprint.Processor;
import org.apache.aries.blueprint.di.ExecutionContext;
import org.apache.aries.blueprint.di.Recipe;
import org.apache.aries.blueprint.di.Repository;
import org.apache.aries.blueprint.namespace.MissingNamespaceException;
import org.apache.aries.blueprint.namespace.NamespaceHandlerRegistryImpl;
import org.apache.aries.blueprint.parser.ComponentDefinitionRegistryImpl;
import org.apache.aries.blueprint.parser.NamespaceHandlerSet;
import org.apache.aries.blueprint.parser.Parser;
import org.apache.aries.blueprint.proxy.ProxyUtils;
import org.apache.aries.blueprint.reflect.MetadataUtil;
import org.apache.aries.blueprint.reflect.PassThroughMetadataImpl;
import org.apache.aries.blueprint.services.ExtendedBlueprintContainer;
import org.apache.aries.blueprint.utils.HeaderParser;
import org.apache.aries.blueprint.utils.HeaderParser.PathElement;
import org.apache.aries.blueprint.utils.JavaUtils;
import org.apache.aries.blueprint.utils.ServiceUtil;
import org.apache.aries.proxy.ProxyManager;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.ServiceRegistration;
import org.osgi.framework.wiring.BundleWiring;
import org.osgi.service.blueprint.container.BlueprintContainer;
import org.osgi.service.blueprint.container.BlueprintEvent;
import org.osgi.service.blueprint.container.BlueprintListener;
import org.osgi.service.blueprint.container.ComponentDefinitionException;
import org.osgi.service.blueprint.container.Converter;
import org.osgi.service.blueprint.container.NoSuchComponentException;
import org.osgi.service.blueprint.reflect.BeanArgument;
import org.osgi.service.blueprint.reflect.BeanMetadata;
import org.osgi.service.blueprint.reflect.BeanProperty;
import org.osgi.service.blueprint.reflect.CollectionMetadata;
import org.osgi.service.blueprint.reflect.ComponentMetadata;
import org.osgi.service.blueprint.reflect.MapEntry;
import org.osgi.service.blueprint.reflect.MapMetadata;
import org.osgi.service.blueprint.reflect.Metadata;
import org.osgi.service.blueprint.reflect.PropsMetadata;
import org.osgi.service.blueprint.reflect.RefMetadata;
import org.osgi.service.blueprint.reflect.ReferenceListener;
import org.osgi.service.blueprint.reflect.RegistrationListener;
import org.osgi.service.blueprint.reflect.ServiceMetadata;
import org.osgi.service.blueprint.reflect.ServiceReferenceMetadata;
import org.osgi.service.blueprint.reflect.Target;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
/**
* TODO: javadoc
*
* @version $Rev$, $Date$
*/
@SuppressWarnings("deprecation") // due to the deprecated org.apache.aries.blueprint.ExtendedBlueprintContainer
public class BlueprintContainerImpl
implements ExtendedBlueprintContainer, NamespaceHandlerSet.Listener,
Runnable, SatisfiableRecipe.SatisfactionListener,
org.apache.aries.blueprint.ExtendedBlueprintContainer {
private static final String DEFAULT_TIMEOUT_PROPERTY = "org.apache.aries.blueprint.default.timeout";
private static final long DEFAULT_TIMEOUT = 5 * 60 * 1000;
private static final Logger LOGGER = LoggerFactory.getLogger(BlueprintContainerImpl.class);
private static final Class[] SECURITY_BUGFIX = {
BlueprintDomainCombiner.class,
BlueprintProtectionDomain.class,
};
public enum State {
Unknown,
WaitForNamespaceHandlers,
Populated,
WaitForInitialReferences,
InitialReferencesSatisfied,
WaitForInitialReferences2,
Create,
Created,
Failed,
}
private final BundleContext bundleContext;
private final Bundle bundle;
private final Bundle extenderBundle;
private final BlueprintListener eventDispatcher;
private final NamespaceHandlerRegistry handlers;
private final List<URL> pathList;
private final ComponentDefinitionRegistryImpl componentDefinitionRegistry;
private final AggregateConverter converter;
private final ExecutorService executors;
private final ScheduledExecutorService timer;
private final Collection<URI> additionalNamespaces;
private Set<URI> namespaces;
private State state = State.Unknown;
private NamespaceHandlerSet handlerSet;
private final AtomicBoolean destroyed = new AtomicBoolean(false);
private Parser parser;
private BlueprintRepository repository;
private ServiceRegistration registration;
private final List<Processor> processors;
private final Object satisfiablesLock = new Object();
private Map<String, List<SatisfiableRecipe>> satisfiables;
private long timeout;
private boolean waitForDependencies = true;
private String xmlValidation;
private ScheduledFuture timeoutFuture;
private final AtomicBoolean scheduled = new AtomicBoolean();
private List<ServiceRecipe> services;
private final AccessControlContext accessControlContext;
private final IdSpace tempRecipeIdSpace = new IdSpace();
private final ProxyManager proxyManager;
public BlueprintContainerImpl(Bundle bundle, BundleContext bundleContext, Bundle extenderBundle, BlueprintListener eventDispatcher,
NamespaceHandlerRegistry handlers, ExecutorService executor, ScheduledExecutorService timer,
List<URL> pathList, ProxyManager proxyManager, Collection<URI> namespaces) {
this.bundle = bundle;
this.bundleContext = bundleContext;
this.extenderBundle = extenderBundle;
this.eventDispatcher = eventDispatcher;
this.handlers = handlers;
this.pathList = pathList;
this.converter = new AggregateConverter(this);
this.componentDefinitionRegistry = new ComponentDefinitionRegistryImpl();
this.executors = executor != null ? new ExecutorServiceWrapper(executor) : null;
this.timer = timer;
this.timeout = getDefaultTimeout();
this.processors = new ArrayList<Processor>();
if (System.getSecurityManager() != null) {
this.accessControlContext = BlueprintDomainCombiner.createAccessControlContext(bundle);
} else {
this.accessControlContext = null;
}
this.proxyManager = proxyManager;
this.additionalNamespaces = namespaces;
}
public ExecutorService getExecutors() {
return executors;
}
public Bundle getExtenderBundle() {
return extenderBundle;
}
public ProxyManager getProxyManager() {
return proxyManager;
}
public <T extends Processor> List<T> getProcessors(Class<T> clazz) {
List<T> p = new ArrayList<T>();
for (Processor processor : processors) {
if (clazz.isInstance(processor)) {
p.add(clazz.cast(processor));
}
}
return p;
}
public BlueprintListener getEventDispatcher() {
return eventDispatcher;
}
private long getDefaultTimeout() {
long timeout = DEFAULT_TIMEOUT;
try {
timeout = Long.getLong(DEFAULT_TIMEOUT_PROPERTY, DEFAULT_TIMEOUT);
if (timeout != DEFAULT_TIMEOUT) {
LOGGER.debug(DEFAULT_TIMEOUT_PROPERTY + " is set to " + timeout + ".");
}
}
catch (Exception e) {
LOGGER.error(DEFAULT_TIMEOUT_PROPERTY + " is not a number. Using default value " + timeout + ".");
}
return timeout;
}
private void readDirectives() {
Dictionary headers = bundle.getHeaders();
String symbolicName = (String) headers.get(Constants.BUNDLE_SYMBOLICNAME);
List<PathElement> paths = HeaderParser.parseHeader(symbolicName);
String timeoutDirective = paths.get(0).getDirective(BlueprintConstants.TIMEOUT_DIRECTIVE);
if (timeoutDirective != null) {
LOGGER.debug("Timeout directive: {}", timeoutDirective);
timeout = Integer.parseInt(timeoutDirective);
}
else {
timeout = getDefaultTimeout();
}
String graceperiod = paths.get(0).getDirective(BlueprintConstants.GRACE_PERIOD);
if (graceperiod != null) {
LOGGER.debug("Grace-period directive: {}", graceperiod);
waitForDependencies = Boolean.parseBoolean(graceperiod);
}
xmlValidation = bundleContext.getProperty(BlueprintConstants.XML_VALIDATION_PROPERTY);
if (xmlValidation == null) {
xmlValidation = paths.get(0).getDirective(BlueprintConstants.XML_VALIDATION);
}
// enabled if null or "true"; structure-only if "structure"; disabled otherwise
LOGGER.debug("Xml-validation directive: {}", xmlValidation);
}
public void schedule() {
if (scheduled.compareAndSet(false, true)) {
executors.submit(this);
}
}
public void reload() {
synchronized (scheduled) {
if (destroyed.get()) {
return;
}
tidyupComponents();
resetComponentDefinitionRegistry();
cancelFutureIfPresent();
this.repository = null;
this.processors.clear();
timeout = 5 * 60 * 1000;
waitForDependencies = true;
xmlValidation = null;
if (handlerSet != null) {
handlerSet.removeListener(this);
handlerSet.destroy();
handlerSet = null;
}
state = State.Unknown;
schedule();
}
}
protected void resetComponentDefinitionRegistry() {
this.componentDefinitionRegistry.reset();
componentDefinitionRegistry.registerComponentDefinition(new PassThroughMetadataImpl("blueprintContainer", this));
componentDefinitionRegistry.registerComponentDefinition(new PassThroughMetadataImpl("blueprintBundle", bundle));
componentDefinitionRegistry.registerComponentDefinition(new PassThroughMetadataImpl("blueprintBundleContext", bundleContext));
componentDefinitionRegistry.registerComponentDefinition(new PassThroughMetadataImpl("blueprintConverter", converter));
}
public void run() {
scheduled.set(false);
synchronized (scheduled) {
doRun();
}
}
public State getState() {
return state;
}
/**
* This method must be called inside a synchronized block to ensure this method is not run concurrently
*/
private void doRun() {
try {
for (;;) {
if (destroyed.get()) {
return;
}
if (bundle.getState() != Bundle.ACTIVE && bundle.getState() != Bundle.STARTING) {
return;
}
if (bundle.getBundleContext() != bundleContext) {
return;
}
LOGGER.debug("Running container for blueprint bundle {}/{} in state {}", getBundle().getSymbolicName(), getBundle().getVersion(), state);
switch (state) {
case Unknown:
readDirectives();
eventDispatcher.blueprintEvent(new BlueprintEvent(BlueprintEvent.CREATING, getBundle(), getExtenderBundle()));
parser = new Parser();
parser.parse(pathList);
namespaces = parser.getNamespaces();
if (additionalNamespaces != null) {
namespaces.addAll(additionalNamespaces);
}
handlerSet = handlers.getNamespaceHandlers(namespaces, getBundle());
handlerSet.addListener(this);
state = State.WaitForNamespaceHandlers;
break;
case WaitForNamespaceHandlers:
{
List<String> missing = new ArrayList<String>();
List<URI> missingURIs = new ArrayList<URI>();
for (URI ns : handlerSet.getNamespaces()) {
if (handlerSet.getNamespaceHandler(ns) == null) {
missing.add("(&(" + Constants.OBJECTCLASS + "=" + NamespaceHandler.class.getName() + ")(" + NamespaceHandlerRegistryImpl.NAMESPACE + "=" + ns + "))");
missingURIs.add(ns);
}
}
if (missing.size() > 0) {
LOGGER.info("Blueprint bundle {}/{} is waiting for namespace handlers {}", getBundle().getSymbolicName(), getBundle().getVersion(), missingURIs);
eventDispatcher.blueprintEvent(new BlueprintEvent(BlueprintEvent.GRACE_PERIOD, getBundle(), getExtenderBundle(), missing.toArray(new String[missing.size()])));
return;
}
resetComponentDefinitionRegistry();
if (xmlValidation == null || "true".equals(xmlValidation)) {
for (URI ns : handlerSet.getNamespaces()) {
NamespaceHandler handler = handlerSet.getNamespaceHandler(ns);
if (handler instanceof NamespaceHandler2) {
if (((NamespaceHandler2) handler).usePsvi()) {
xmlValidation = "psvi";
break;
}
}
}
}
try {
if (xmlValidation == null || "true".equals(xmlValidation)) {
parser.validate(handlerSet.getSchema(parser.getSchemaLocations()));
} else if ("structure".equals(xmlValidation)) {
parser.validate(handlerSet.getSchema(parser.getSchemaLocations()), new ValidationHandler());
} else if ("psvi".equals(xmlValidation)) {
parser.validatePsvi(handlerSet.getSchema(parser.getSchemaLocations()));
}
parser.populate(handlerSet, componentDefinitionRegistry);
state = State.Populated;
} catch (MissingNamespaceException e) {
// If we found a missing namespace when parsing the schema,
// we remain in the current state
handlerSet.getNamespaces().add(e.getNamespace());
}
break;
}
case Populated:
getRepository();
trackServiceReferences();
Runnable r = new Runnable() {
public void run() {
synchronized (scheduled) {
if (destroyed.get()) {
return;
}
String[] missingDependecies = getMissingDependencies();
if (missingDependecies.length == 0) {
return;
}
Throwable t = new TimeoutException();
state = State.Failed;
tidyupComponents();
LOGGER.error("Unable to start container for blueprint bundle {}/{} due to unresolved dependencies {}", getBundle().getSymbolicName(), getBundle().getVersion(), Arrays.asList(missingDependecies), t);
eventDispatcher.blueprintEvent(new BlueprintEvent(BlueprintEvent.FAILURE, getBundle(), getExtenderBundle(), missingDependecies, t));
}
}
};
timeoutFuture = timer.schedule(r, timeout, TimeUnit.MILLISECONDS);
state = State.WaitForInitialReferences;
break;
case WaitForInitialReferences:
if (waitForDependencies) {
String[] missingDependencies = getMissingDependencies();
if (missingDependencies.length > 0) {
LOGGER.info("Blueprint bundle {}/{} is waiting for dependencies {}", getBundle().getSymbolicName(), getBundle().getVersion(), Arrays.asList(missingDependencies));
eventDispatcher.blueprintEvent(new BlueprintEvent(BlueprintEvent.GRACE_PERIOD, getBundle(), getExtenderBundle(), missingDependencies));
return;
}
}
state = State.InitialReferencesSatisfied;
break;
case InitialReferencesSatisfied:
processTypeConverters();
processProcessors();
state = State.WaitForInitialReferences2;
break;
case WaitForInitialReferences2:
if (waitForDependencies) {
String[] missingDependencies = getMissingDependencies();
if (missingDependencies.length > 0) {
LOGGER.info("Blueprint bundle {}/{} is waiting for dependencies {}", getBundle().getSymbolicName(), getBundle().getVersion(), Arrays.asList(missingDependencies));
eventDispatcher.blueprintEvent(new BlueprintEvent(BlueprintEvent.GRACE_PERIOD, getBundle(), getExtenderBundle(), missingDependencies));
return;
}
}
state = State.Create;
break;
case Create:
cancelFutureIfPresent();
instantiateEagerComponents();
//Register the services after the eager components are ready, as per 121.6
registerServices();
// Register the BlueprintContainer in the OSGi registry
int bs = bundle.getState();
if (registration == null && (bs == Bundle.ACTIVE || bs == Bundle.STARTING)) {
Properties props = new Properties();
props.put(BlueprintConstants.CONTAINER_SYMBOLIC_NAME_PROPERTY,
bundle.getSymbolicName());
props.put(BlueprintConstants.CONTAINER_VERSION_PROPERTY,
JavaUtils.getBundleVersion(bundle));
registration = registerService(new String[]{BlueprintContainer.class.getName()}, this, props);
}
LOGGER.info("Blueprint bundle {}/{} has been started", getBundle().getSymbolicName(), getBundle().getVersion());
eventDispatcher.blueprintEvent(new BlueprintEvent(BlueprintEvent.CREATED, getBundle(), getExtenderBundle()));
state = State.Created;
break;
case Created:
case Failed:
return;
}
}
} catch (Throwable t) {
try {
state = State.Failed;
cancelFutureIfPresent();
tidyupComponents();
LOGGER.error("Unable to start container for blueprint bundle {}/{}", getBundle().getSymbolicName(), getBundle().getVersion(), t);
eventDispatcher.blueprintEvent(new BlueprintEvent(BlueprintEvent.FAILURE, getBundle(), getExtenderBundle(), t));
} catch (RuntimeException re) {
LOGGER.debug("Tidying up components failed. ", re);
throw re;
}
}
}
public Class loadClass(final String name) throws ClassNotFoundException {
if (accessControlContext == null) {
return bundle.loadClass(name);
} else {
try {
return AccessController.doPrivileged(new PrivilegedExceptionAction<Class>() {
public Class run() throws Exception {
return bundle.loadClass(name);
}
}, accessControlContext);
} catch (PrivilegedActionException e) {
Exception cause = e.getException();
if (cause instanceof ClassNotFoundException) {
throw (ClassNotFoundException) cause;
}
throw new IllegalStateException("Unexpected checked exception", cause);
}
}
}
@Override
public ClassLoader getClassLoader() {
return getBundle().adapt(BundleWiring.class).getClassLoader();
}
public ServiceRegistration registerService(final String[] classes, final Object service, final Dictionary properties) {
if (accessControlContext == null) {
return bundleContext.registerService(classes, service, properties);
} else {
return AccessController.doPrivileged(new PrivilegedAction<ServiceRegistration>() {
public ServiceRegistration run() {
return bundleContext.registerService(classes, service, properties);
}
}, accessControlContext);
}
}
public Object getService(final ServiceReference reference) {
if (accessControlContext == null) {
return bundleContext.getService(reference);
} else {
return AccessController.doPrivileged(new PrivilegedAction<Object>() {
public Object run() {
return bundleContext.getService(reference);
}
}, accessControlContext);
}
}
public AccessControlContext getAccessControlContext() {
return accessControlContext;
}
public BlueprintRepository getRepository() {
if (repository == null) {
repository = new RecipeBuilder(this, tempRecipeIdSpace).createRepository();
}
return repository;
}
protected void processTypeConverters() throws Exception {
List<String> typeConverters = new ArrayList<String>();
for (Target target : componentDefinitionRegistry.getTypeConverters()) {
if (target instanceof ComponentMetadata) {
typeConverters.add(((ComponentMetadata) target).getId());
} else if (target instanceof RefMetadata) {
typeConverters.add(((RefMetadata) target).getComponentId());
} else {
throw new ComponentDefinitionException("Unexpected metadata for type converter: " + target);
}
}
Map<String, Object> objects = getRepository().createAll(typeConverters, ProxyUtils.asList(Converter.class));
for (String name : typeConverters) {
Object obj = objects.get(name);
if (obj instanceof Converter) {
converter.registerConverter((Converter) obj);
} else {
throw new ComponentDefinitionException("Type converter " + obj + " does not implement the " + Converter.class.getName() + " interface");
}
}
}
protected void processProcessors() throws Exception {
// Instantiate ComponentDefinitionRegistryProcessor and BeanProcessor
for (BeanMetadata bean : getMetadata(BeanMetadata.class)) {
if (bean instanceof ExtendedBeanMetadata && !((ExtendedBeanMetadata) bean).isProcessor()) {
continue;
}
Class clazz = null;
if (bean instanceof ExtendedBeanMetadata) {
clazz = ((ExtendedBeanMetadata) bean).getRuntimeClass();
}
if (clazz == null && bean.getClassName() != null) {
clazz = loadClass(bean.getClassName());
}
if (clazz == null) {
continue;
}
Object obj = null;
if (ComponentDefinitionRegistryProcessor.class.isAssignableFrom(clazz)) {
obj = repository.create(bean.getId(), ProxyUtils.asList(ComponentDefinitionRegistryProcessor.class));
((ComponentDefinitionRegistryProcessor) obj).process(componentDefinitionRegistry);
}
if (Processor.class.isAssignableFrom(clazz)) {
obj = repository.create(bean.getId(), ProxyUtils.asList(Processor.class));
this.processors.add((Processor) obj);
}
if (obj == null) {
continue;
}
untrackServiceReferences();
updateUninstantiatedRecipes();
getSatisfiableDependenciesMap(true);
trackServiceReferences();
}
}
private void updateUninstantiatedRecipes() {
Repository tmpRepo = new RecipeBuilder(this, tempRecipeIdSpace).createRepository();
LOGGER.debug("Updating blueprint repository");
for (String name : repository.getNames()) {
if (repository.getInstance(name) == null) {
LOGGER.debug("Removing uninstantiated recipe {}", new Object[] { name });
repository.removeRecipe(name);
} else {
LOGGER.debug("Recipe {} is already instantiated", new Object[] { name });
}
}
for (String name : tmpRepo.getNames()) {
if (repository.getInstance(name) == null) {
LOGGER.debug("Adding new recipe {}", new Object[] { name });
Recipe r = tmpRepo.getRecipe(name);
if (r != null) {
repository.putRecipe(name, r);
}
} else {
LOGGER.debug("Recipe {} is already instantiated and cannot be updated", new Object[] { name });
}
}
}
private Map<String, List<SatisfiableRecipe>> getSatisfiableDependenciesMap() {
return getSatisfiableDependenciesMap(false);
}
private Map<String, List<SatisfiableRecipe>> getSatisfiableDependenciesMap(boolean recompute) {
synchronized (satisfiablesLock) {
if ((recompute || satisfiables == null) && repository != null) {
satisfiables = new HashMap<String, List<SatisfiableRecipe>>();
for (Recipe r : repository.getAllRecipes()) {
List<SatisfiableRecipe> recipes = repository.getAllRecipes(SatisfiableRecipe.class, r.getName());
if (!recipes.isEmpty()) {
satisfiables.put(r.getName(), recipes);
}
}
}
return satisfiables;
}
}
private void trackServiceReferences() {
Map<String, List<SatisfiableRecipe>> dependencies = getSatisfiableDependenciesMap();
Set<String> satisfiables = new HashSet<String>();
for (List<SatisfiableRecipe> recipes : dependencies.values()) {
for (SatisfiableRecipe satisfiable : recipes) {
if (satisfiables.add(satisfiable.getName())) {
satisfiable.start(this);
}
}
}
LOGGER.debug("Tracking service references: {}", satisfiables);
}
private void untrackServiceReferences() {
Map<String, List<SatisfiableRecipe>> dependencies = getSatisfiableDependenciesMap();
if (dependencies != null) {
Set<String> stopped = new HashSet<String>();
for (List<SatisfiableRecipe> recipes : dependencies.values()) {
for (SatisfiableRecipe satisfiable : recipes) {
untrackServiceReference(satisfiable, stopped, dependencies);
}
}
}
synchronized (satisfiablesLock) {
satisfiables = null;
}
}
private void untrackServiceReference(SatisfiableRecipe recipe, Set<String> stopped, Map<String, List<SatisfiableRecipe>> dependencies) {
if (stopped.add(recipe.getName())) {
for (Map.Entry<String, List<SatisfiableRecipe>> entry : dependencies.entrySet()) {
if (entry.getValue().contains(recipe)) {
Recipe r = getRepository().getRecipe(entry.getKey());
if (r instanceof SatisfiableRecipe) {
untrackServiceReference((SatisfiableRecipe) r, stopped, dependencies);
}
}
}
recipe.stop();
}
}
public void notifySatisfaction(SatisfiableRecipe satisfiable) {
if (destroyed.get()) {
return;
}
LOGGER.debug("Notified satisfaction {} in bundle {}/{}: {}",
satisfiable.getName(), bundle.getSymbolicName(), getBundle().getVersion(), satisfiable.isSatisfied());
if ((state == State.Create || state == State.Created) && satisfiable.isStaticLifecycle()) {
if (satisfiable.isSatisfied()) {
repository.reCreateInstance(satisfiable.getName());
}
else {
repository.destroyInstance(satisfiable.getName());
}
}
else if (state == State.Create || state == State.Created) {
Map<String, List<SatisfiableRecipe>> dependencies = getSatisfiableDependenciesMap();
for (Map.Entry<String, List<SatisfiableRecipe>> entry : dependencies.entrySet()) {
String name = entry.getKey();
ComponentMetadata metadata = componentDefinitionRegistry.getComponentDefinition(name);
if (metadata instanceof ServiceMetadata) {
ServiceRecipe reg = (ServiceRecipe) repository.getRecipe(name);
synchronized (reg) {
boolean satisfied = true;
for (SatisfiableRecipe recipe : entry.getValue()) {
if (!recipe.isSatisfied()) {
satisfied = false;
break;
}
}
if (satisfied && !reg.isRegistered()) {
LOGGER.debug("Registering service {} due to satisfied references", name);
reg.register();
} else if (!satisfied && reg.isRegistered()) {
LOGGER.debug("Unregistering service {} due to unsatisfied references", name);
reg.unregister();
}
}
}
}
} else {
schedule();
}
}
private void instantiateEagerComponents() {
List<String> components = new ArrayList<String>();
for (String name : componentDefinitionRegistry.getComponentDefinitionNames()) {
ComponentMetadata component = componentDefinitionRegistry.getComponentDefinition(name);
boolean eager = component.getActivation() == ComponentMetadata.ACTIVATION_EAGER;
if (component instanceof BeanMetadata) {
BeanMetadata local = (BeanMetadata) component;
eager &= MetadataUtil.isSingletonScope(local);
}
if (eager) {
components.add(name);
}
}
LOGGER.debug("Instantiating components: {}", components);
try {
repository.createAll(components);
} catch (ComponentDefinitionException e) {
throw e;
} catch (Throwable t) {
throw new ComponentDefinitionException("Unable to instantiate components", t);
}
}
private void registerServices() {
services = repository.getAllRecipes(ServiceRecipe.class);
for (ServiceRecipe r : services) {
List<SatisfiableRecipe> dependencies = getSatisfiableDependenciesMap().get(r.getName());
boolean enabled = true;
if (dependencies != null) {
for (SatisfiableRecipe recipe : dependencies) {
if (!recipe.isSatisfied()) {
enabled = false;
break;
}
}
}
if (enabled) {
r.register();
}
}
}
protected void unregisterServices() {
if (repository != null) {
List<ServiceRecipe> recipes = this.services;
this.services = null;
if (recipes != null) {
for (ServiceRecipe r : recipes) {
r.unregister();
}
}
}
}
private void destroyComponents() {
if (repository != null) {
repository.destroy();
}
}
private String[] getMissingDependencies() {
List<String> missing = new ArrayList<String>();
Map<String, List<SatisfiableRecipe>> dependencies = getSatisfiableDependenciesMap();
Set<SatisfiableRecipe> recipes = new HashSet<SatisfiableRecipe>();
for (List<SatisfiableRecipe> deps : dependencies.values()) {
for (SatisfiableRecipe recipe : deps) {
if (!recipe.isSatisfied()) {
recipes.add(recipe);
}
}
}
for (SatisfiableRecipe recipe : recipes) {
missing.add(recipe.getOsgiFilter());
}
return missing.toArray(new String[missing.size()]);
}
public Set<String> getComponentIds() {
return new LinkedHashSet<String>(componentDefinitionRegistry.getComponentDefinitionNames());
}
public Object getComponentInstance(String id) throws NoSuchComponentException {
if (repository == null || destroyed.get()) {
throw new NoSuchComponentException(id);
}
try {
LOGGER.debug("Instantiating component {}", id);
return repository.create(id);
} catch (NoSuchComponentException e) {
throw e;
} catch (ComponentDefinitionException e) {
throw e;
} catch (Throwable t) {
throw new ComponentDefinitionException("Cound not create component instance for " + id, t);
}
}
public ComponentMetadata getComponentMetadata(String id) {
ComponentMetadata metadata = componentDefinitionRegistry.getComponentDefinition(id);
if (metadata == null) {
throw new NoSuchComponentException(id);
}
return metadata;
}
public <T extends ComponentMetadata> Collection<T> getMetadata(Class<T> clazz) {
Collection<T> metadatas = new ArrayList<T>();
for (String name : componentDefinitionRegistry.getComponentDefinitionNames()) {
ComponentMetadata component = componentDefinitionRegistry.getComponentDefinition(name);
getMetadata(clazz, component, metadatas);
}
metadatas = Collections.unmodifiableCollection(metadatas);
return metadatas;
}
private <T extends ComponentMetadata> void getMetadata(Class<T> clazz, Metadata component, Collection<T> metadatas) {
if (component == null) {
return;
}
if (clazz.isInstance(component)) {
metadatas.add(clazz.cast(component));
}
if (component instanceof BeanMetadata) {
getMetadata(clazz, ((BeanMetadata) component).getFactoryComponent(), metadatas);
for (BeanArgument arg : ((BeanMetadata) component).getArguments()) {
getMetadata(clazz, arg.getValue(), metadatas);
}
for (BeanProperty prop : ((BeanMetadata) component).getProperties()) {
getMetadata(clazz, prop.getValue(), metadatas);
}
}
if (component instanceof CollectionMetadata) {
for (Metadata m : ((CollectionMetadata) component).getValues()) {
getMetadata(clazz, m, metadatas);
}
}
if (component instanceof MapMetadata) {
for (MapEntry m : ((MapMetadata) component).getEntries()) {
getMetadata(clazz, m.getKey(), metadatas);
getMetadata(clazz, m.getValue(), metadatas);
}
}
if (component instanceof PropsMetadata) {
for (MapEntry m : ((PropsMetadata) component).getEntries()) {
getMetadata(clazz, m.getKey(), metadatas);
getMetadata(clazz, m.getValue(), metadatas);
}
}
if (component instanceof ServiceReferenceMetadata) {
for (ReferenceListener l : ((ServiceReferenceMetadata) component).getReferenceListeners()) {
getMetadata(clazz, l.getListenerComponent(), metadatas);
}
}
if (component instanceof ServiceMetadata) {
getMetadata(clazz, ((ServiceMetadata) component).getServiceComponent(), metadatas);
for (MapEntry m : ((ServiceMetadata) component).getServiceProperties()) {
getMetadata(clazz, m.getKey(), metadatas);
getMetadata(clazz, m.getValue(), metadatas);
}
for (RegistrationListener l : ((ServiceMetadata) component).getRegistrationListeners()) {
getMetadata(clazz, l.getListenerComponent(), metadatas);
}
}
}
public Converter getConverter() {
return converter;
}
public ComponentDefinitionRegistryImpl getComponentDefinitionRegistry() {
return componentDefinitionRegistry;
}
public BundleContext getBundleContext() {
return bundleContext;
}
public Bundle getBundle() {
return bundle;
}
public void destroy() {
synchronized (scheduled) {
destroyed.set(true);
}
cancelFutureIfPresent();
eventDispatcher.blueprintEvent(new BlueprintEvent(BlueprintEvent.DESTROYING, getBundle(), getExtenderBundle()));
executors.shutdownNow();
if (handlerSet != null) {
handlerSet.removeListener(this);
handlerSet.destroy();
}
try {
executors.awaitTermination(5 * 60, TimeUnit.SECONDS);
} catch (InterruptedException e) {
LOGGER.debug("Interrupted waiting for executor to shut down");
}
tidyupComponents();
eventDispatcher.blueprintEvent(new BlueprintEvent(BlueprintEvent.DESTROYED, getBundle(), getExtenderBundle()));
LOGGER.debug("Container destroyed for blueprint bundle {}/{}", getBundle().getSymbolicName(), getBundle().getVersion());
}
public static void safeUnregisterService(ServiceRegistration reg) {
if (reg != null) {
try {
reg.unregister();
} catch (IllegalStateException e) {
//This can be safely ignored
}
}
}
protected void quiesce() {
destroyed.set(true);
eventDispatcher.blueprintEvent(new BlueprintEvent(BlueprintEvent.DESTROYING, getBundle(), getExtenderBundle()));
cancelFutureIfPresent();
ServiceUtil.safeUnregisterService(registration);
if (handlerSet != null) {
handlerSet.removeListener(this);
handlerSet.destroy();
}
LOGGER.debug("Blueprint container {} quiesced", getBundle().getSymbolicName(), getBundle().getVersion());
}
private void cancelFutureIfPresent() {
if (timeoutFuture != null) {
timeoutFuture.cancel(false);
}
}
public void namespaceHandlerRegistered(URI uri) {
if (handlerSet != null && handlerSet.getNamespaces().contains(uri)) {
schedule();
}
}
public void namespaceHandlerUnregistered(URI uri) {
if (handlerSet != null && handlerSet.getNamespaces().contains(uri)) {
synchronized (scheduled) {
if (destroyed.get()) {
return;
}
tidyupComponents();
resetComponentDefinitionRegistry();
cancelFutureIfPresent();
this.repository = null;
this.processors.clear();
handlerSet.removeListener(this);
handlerSet.destroy();
handlerSet = handlers.getNamespaceHandlers(namespaces, getBundle());
handlerSet.addListener(this);
state = State.WaitForNamespaceHandlers;
schedule();
}
}
}
private void tidyupComponents() {
unregisterServices();
destroyComponents();
untrackServiceReferences();
}
public void injectBeanInstance(BeanMetadata bmd, Object o)
throws IllegalArgumentException, ComponentDefinitionException {
ExecutionContext origContext
= ExecutionContext.Holder.setContext((ExecutionContext) getRepository());
try {
ComponentMetadata cmd = componentDefinitionRegistry.getComponentDefinition(bmd.getId());
if (cmd == null || cmd != bmd) {
throw new IllegalArgumentException(bmd.getId() + " not found in blueprint container");
}
Recipe r = this.getRepository().getRecipe(bmd.getId());
if (r instanceof BeanRecipe) {
BeanRecipe br = (BeanRecipe) r;
if (!br.getType().isInstance(o)) {
throw new IllegalArgumentException("Instance class " + o.getClass().getName()
+ " is not an instance of " + br.getClass());
}
br.setProperties(o);
} else {
throw new IllegalArgumentException(bmd.getId() + " does not refer to a BeanRecipe");
}
} finally {
ExecutionContext.Holder.setContext(origContext);
}
}
// this could be parameterized/customized, but for now, hard-coded for ignoring datatype validation
private static class ValidationHandler implements ErrorHandler {
@Override
public void warning(SAXParseException exception) throws SAXException {
// ignore
}
@Override
public void error(SAXParseException exception) throws SAXException {
final String cvctext = exception.getMessage();
if (cvctext != null &&
(cvctext.startsWith("cvc-datatype-valid.1") || cvctext.startsWith("cvc-attribute.3"))) {
return;
}
throw exception;
}
@Override
public void fatalError(SAXParseException exception) throws SAXException {
throw exception;
}
}
}
| 9,510 |
0 | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/container/BlueprintProtectionDomain.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.blueprint.container;
import java.security.Permission;
import java.security.ProtectionDomain;
import org.osgi.framework.Bundle;
public class BlueprintProtectionDomain extends ProtectionDomain {
private final Bundle bundle;
public BlueprintProtectionDomain(Bundle bundle) {
super(null, null);
this.bundle = bundle;
}
public boolean implies(Permission permission) {
try {
return bundle.hasPermission(permission);
} catch (IllegalStateException e) {
return false;
}
}
}
| 9,511 |
0 | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/container/BlueprintRepository.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.blueprint.container;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import org.apache.aries.blueprint.reflect.MetadataUtil;
import org.apache.aries.blueprint.services.ExtendedBlueprintContainer;
import org.apache.aries.blueprint.container.BeanRecipe.UnwrapperedBeanHolder;
import org.apache.aries.blueprint.di.CircularDependencyException;
import org.apache.aries.blueprint.di.ExecutionContext;
import org.apache.aries.blueprint.di.IdRefRecipe;
import org.apache.aries.blueprint.di.Recipe;
import org.apache.aries.blueprint.di.RefRecipe;
import org.apache.aries.blueprint.di.Repository;
import org.apache.aries.blueprint.di.CollectionRecipe;
import org.osgi.service.blueprint.container.ReifiedType;
import org.osgi.service.blueprint.container.ComponentDefinitionException;
import org.osgi.service.blueprint.container.NoSuchComponentException;
import org.osgi.service.blueprint.reflect.BeanMetadata;
import org.osgi.service.blueprint.reflect.ComponentMetadata;
/**
* The default repository implementation
*/
public class BlueprintRepository implements Repository, ExecutionContext {
/**
* The blueprint container
*/
private final ExtendedBlueprintContainer blueprintContainer;
/**
* Contains object recipes
*/
private final Map<String, Recipe> recipes = new ConcurrentHashMap<String, Recipe>();
/**
* Contains object instances. Objects are stored as futures by the first task that wants to create it.
* All other listeners should call get on the future.
*/
private final ConcurrentMap<String, Future<Object>> instances = new ConcurrentHashMap<String, Future<Object>>();
/**
* Keep track of creation order
*/
private final List<String> creationOrder = new CopyOnWriteArrayList<String>();
/**
* Contains partial objects.
*/
private final ThreadLocal<Map<String, Object>> partialObjects = new ThreadLocal<Map<String, Object>>();
/**
* Before each recipe is executed it is pushed on the stack. The
* stack is used to detect circular dependencies.
*/
private final ThreadLocal<LinkedList<Recipe>> stack = new ThreadLocal<LinkedList<Recipe>>();
private Map<String, Set<String>> invertedDependencies;
public BlueprintRepository(ExtendedBlueprintContainer container) {
blueprintContainer = container;
}
public Object getInstance(String name) {
Future<Object> future = instances.get(name);
if (future != null && future.isDone()) {
try {
return future.get();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return null;
} catch (ExecutionException e) {
return null;
}
} else {
return null;
}
}
public Recipe getRecipe(String name) {
return recipes.get(name);
}
public Set<String> getNames() {
Set<String> names = new HashSet<String>();
names.addAll(recipes.keySet());
names.addAll(instances.keySet());
return names;
}
public void putRecipe(String name, Recipe recipe) {
if (instances.containsKey(name)) {
throw new ComponentDefinitionException("Name " + name + " is already registered to instance " + getInstance(name));
}
recipes.put(name, recipe);
invertedDependencies = null;
}
public void removeRecipe(String name) {
if (instances.containsKey(name))
throw new ComponentDefinitionException("Name " + name + " is already instanciated as " + getInstance(name) + " and cannot be removed.");
recipes.remove(name);
invertedDependencies = null;
}
private Object convert(String name, Object instance) throws ComponentDefinitionException {
try {
// Make sure to go through the conversion step in case we have a Convertible object
return convert(instance, new ReifiedType(Object.class));
} catch (Exception e) {
throw new ComponentDefinitionException("Unable to convert instance " + name, e);
}
}
public Object create(String name) throws ComponentDefinitionException {
ExecutionContext oldContext = ExecutionContext.Holder.setContext(this);
try {
Object instance = createInstance(name);
return convert(name, instance);
} finally {
ExecutionContext.Holder.setContext(oldContext);
}
}
public Object create(String name, Collection<Class<?>> proxyInterfaces) throws ComponentDefinitionException {
ExecutionContext oldContext = ExecutionContext.Holder.setContext(this);
try {
Object instance = createInstance(name);
if (instance instanceof UnwrapperedBeanHolder)
instance = BeanRecipe.wrap((UnwrapperedBeanHolder) instance, proxyInterfaces);
return convert(name, instance);
} finally {
ExecutionContext.Holder.setContext(oldContext);
}
}
public Map<String, Object> createAll(Collection<String> names, Collection<Class<?>> proxyInterfaces) throws ComponentDefinitionException {
ExecutionContext oldContext = ExecutionContext.Holder.setContext(this);
try {
Map<String, Object> instances = createInstances(names);
for (String name : instances.keySet()) {
Object obj = instances.get(name);
if (obj instanceof UnwrapperedBeanHolder)
obj = BeanRecipe.wrap((UnwrapperedBeanHolder) obj, proxyInterfaces);
instances.put(name, convert(name, obj));
}
return instances;
} finally {
ExecutionContext.Holder.setContext(oldContext);
}
}
public void createAll(Collection<String> names) throws ComponentDefinitionException {
ExecutionContext oldContext = ExecutionContext.Holder.setContext(this);
try {
createInstances(names);
return;
} finally {
ExecutionContext.Holder.setContext(oldContext);
}
}
public <T> List<T> getAllRecipes(Class<T> clazz, String... names) {
List<T> recipes = new ArrayList<T>();
for (Recipe r : getAllRecipes(names)) {
if (clazz.isInstance(r)) {
recipes.add(clazz.cast(r));
}
}
return recipes;
}
public Set<Recipe> getAllRecipes(String... names) {
ExecutionContext oldContext = ExecutionContext.Holder.setContext(this);
try {
Set<Recipe> allRecipes = new HashSet<Recipe>();
Collection<String> topLevel = names != null && names.length > 0 ? Arrays.asList(names) : recipes.keySet();
for (String name : topLevel) {
internalGetAllRecipes(allRecipes, getRecipe(name));
}
return allRecipes;
} finally {
ExecutionContext.Holder.setContext(oldContext);
}
}
private static <S, T> void addToMapSet(Map<S, Set<T>> map, S key, T value) {
Set<T> values = map.get(key);
if (values == null) {
values = new HashSet<T>();
map.put(key, values);
}
values.add(value);
}
private Map<String, Set<String>> getInvertedDependencies() {
if (invertedDependencies == null) {
Map<String, Set<String>> deps = new HashMap<String, Set<String>>();
for (String n : recipes.keySet()) {
Recipe r = recipes.get(n);
Set<Recipe> d = new HashSet<Recipe>();
internalGetAllRecipes(d, r);
for (Recipe e : d) {
addToMapSet(deps, e.getName(), r.getName());
}
}
invertedDependencies = deps;
}
return invertedDependencies;
}
public void reCreateInstance(String name) {
ExecutionContext oldContext = ExecutionContext.Holder.setContext(this);
try {
Set<String> toCreate = new HashSet<String>();
Set<String> deps = getInvertedDependencies().get(name);
if (deps == null) {
throw new NoSuchComponentException(name);
}
for (String dep : deps) {
boolean ok = true;
for (SatisfiableRecipe r : getAllRecipes(SatisfiableRecipe.class, dep)) {
if (!r.isSatisfied()) {
ok = false;
break;
}
}
if (ok) {
toCreate.add(dep);
}
}
createInstances(toCreate);
for (String n : toCreate) {
Recipe r = recipes.get(n);
if (r instanceof ServiceRecipe) {
ServiceRecipe sr = (ServiceRecipe) r;
if (!sr.isRegistered()) {
sr.register();
}
}
}
} finally {
ExecutionContext.Holder.setContext(oldContext);
}
}
public void destroyInstance(String name) {
ExecutionContext oldContext = ExecutionContext.Holder.setContext(this);
try {
Map<Recipe, Future<Object>> toDestroy = new LinkedHashMap<Recipe, Future<Object>>();
doGetInstancesToDestroy(toDestroy, name);
for (Map.Entry<Recipe, Future<Object>> entry : toDestroy.entrySet()) {
try {
Recipe recipe = entry.getKey();
Future<Object> future = entry.getValue();
Object instance = future.get();
if (instance != null) {
recipe.destroy(instance);
}
} catch (Exception e) {
throw new ComponentDefinitionException("Error destroying instance", e);
}
}
} finally {
ExecutionContext.Holder.setContext(oldContext);
}
}
protected void doGetInstancesToDestroy(Map<Recipe, Future<Object>> toDestroy, String name) {
Recipe recipe = recipes.get(name);
if (recipe != null) {
if (recipe instanceof ServiceRecipe) {
((ServiceRecipe) recipe).unregister();
}
Future<Object> future = instances.remove(name);
if (future != null && future.isDone()) {
Set<String> deps = getInvertedDependencies().get(name);
for (String dep : deps) {
doGetInstancesToDestroy(toDestroy, dep);
}
toDestroy.put(recipe, future);
}
} else {
throw new NoSuchComponentException(name);
}
}
/*
* This method should not be called directly, only from one of the getAllRecipes() methods.
*/
private void internalGetAllRecipes(Set<Recipe> allRecipes, Recipe r) {
if (r != null) {
if (allRecipes.add(r)) {
for (Recipe c : r.getDependencies()) {
internalGetAllRecipes(allRecipes, c);
}
}
}
}
private Object createInstance(String name) {
Object instance = getInstance(name);
if (instance == null) {
Map<String, Object> instances = createInstances(Arrays.asList(name));
instance = instances.get(name);
if (instance == null) {
throw new NoSuchComponentException(name);
}
}
return instance;
}
private Map<String, Object> createInstances(Collection<String> names) {
// Instance creation is synchronized inside each create method (via the use of futures), so that
// a recipe will only created once where appropriate
DependencyGraph graph = new DependencyGraph(this);
HashMap<String, Object> objects = new LinkedHashMap<String, Object>();
for (Map.Entry<String, Recipe> entry : graph.getSortedRecipes(names).entrySet()) {
String name = entry.getKey();
ComponentMetadata component = blueprintContainer.getComponentDefinitionRegistry().getComponentDefinition(name);
boolean prototype = (component instanceof BeanMetadata)
&& MetadataUtil.isPrototypeScope((BeanMetadata) component);
if (!prototype || names.contains(name)) {
objects.put(
name,
entry.getValue().create());
}
}
return objects;
}
public void validate() {
for (Recipe recipe : getAllRecipes()) {
// Check that references are satisfied
String ref = null;
if (recipe instanceof RefRecipe) {
ref = ((RefRecipe) recipe).getIdRef();
} else if (recipe instanceof IdRefRecipe) {
ref = ((IdRefRecipe) recipe).getIdRef();
}
if (ref != null && getRecipe(ref) == null) {
throw new ComponentDefinitionException("Unresolved ref/idref to component: " + ref);
}
// Check service
if (recipe instanceof ServiceRecipe) {
Recipe r = ((ServiceRecipe) recipe).getServiceRecipe();
if (r instanceof RefRecipe) {
r = getRecipe(((RefRecipe) r).getIdRef());
}
if (r instanceof ServiceRecipe) {
throw new ComponentDefinitionException("The target for a <service> element must not be <service> element");
}
if (r instanceof ReferenceListRecipe) {
throw new ComponentDefinitionException("The target for a <service> element must not be <reference-list> element");
}
CollectionRecipe listeners = ((ServiceRecipe) recipe).getListenersRecipe();
for (Recipe lr : listeners.getDependencies()) {
// The listener recipe is a bean recipe with the listener being set in a property
for (Recipe l : lr.getDependencies()) {
if (l instanceof RefRecipe) {
l = getRecipe(((RefRecipe) l).getIdRef());
}
if (l instanceof ServiceRecipe) {
throw new ComponentDefinitionException("The target for a <registration-listener> element must not be <service> element");
}
if (l instanceof ReferenceListRecipe) {
throw new ComponentDefinitionException("The target for a <registration-listener> element must not be <reference-list> element");
}
}
}
}
// Check references
if (recipe instanceof AbstractServiceReferenceRecipe) {
CollectionRecipe listeners = ((AbstractServiceReferenceRecipe) recipe).getListenersRecipe();
for (Recipe lr : listeners.getDependencies()) {
// The listener recipe is a bean recipe with the listener being set in a property
for (Recipe l : lr.getDependencies()) {
if (l instanceof RefRecipe) {
l = getRecipe(((RefRecipe) l).getIdRef());
}
if (l instanceof ServiceRecipe) {
throw new ComponentDefinitionException("The target for a <reference-listener> element must not be <service> element");
}
if (l instanceof ReferenceListRecipe) {
throw new ComponentDefinitionException("The target for a <reference-listener> element must not be <reference-list> element");
}
}
}
}
}
}
public void destroy() {
// destroy objects in reverse creation order
List<String> order = new ArrayList<String>(creationOrder);
Collections.reverse(order);
for (String name : order) {
Recipe recipe = recipes.get(name);
if (recipe != null) {
recipe.destroy(getInstance(name));
}
}
instances.clear();
creationOrder.clear();
}
public void push(Recipe recipe) {
LinkedList<Recipe> list = stack.get();
if (list != null && list.contains(recipe)) {
ArrayList<Recipe> circularity = new ArrayList<Recipe>(list.subList(list.indexOf(recipe), list.size()));
// remove anonymous nodes from circularity list
for (Iterator<Recipe> iterator = circularity.iterator(); iterator.hasNext();) {
Recipe item = iterator.next();
if (item != recipe && item.getName() == null) {
iterator.remove();
}
}
// add ending node to list so a full circuit is shown
circularity.add(recipe);
throw new CircularDependencyException(circularity);
}
if (list == null) {
list = new LinkedList<Recipe>();
stack.set(list);
}
list.add(recipe);
}
public Recipe pop() {
LinkedList<Recipe> list = stack.get();
return list.removeLast();
}
public boolean containsObject(String name) {
return instances.containsKey(name) || getRecipe(name) != null;
}
public Object getObject(String name) {
Future<Object> future = instances.get(name);
Object result = null;
if (future != null && future.isDone()) {
try {
result = future.get();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
result = getRecipe(name);
} catch (ExecutionException e) {
result = getRecipe(name);
}
} else {
result = getRecipe(name);
}
return result;
}
public Future<Object> addFullObject(String name, Future<Object> object) {
return instances.putIfAbsent(name, object);
}
public void addPartialObject(String name, Object object) {
if (partialObjects.get() == null)
partialObjects.set(new HashMap<String, Object>());
partialObjects.get().put(name, object);
}
public Object getPartialObject(String name) {
return (partialObjects.get() != null) ? partialObjects.get().get(name) : null;
}
public void removePartialObject(String name) {
creationOrder.add(name);
if (partialObjects.get() != null)
partialObjects.get().remove(name);
}
public Object convert(Object value, ReifiedType type) throws Exception {
return blueprintContainer.getConverter().convert(value, type);
}
public boolean canConvert(Object value, ReifiedType type) {
return blueprintContainer.getConverter().canConvert(value, type);
}
public Class loadClass(String typeName) throws ClassNotFoundException {
return blueprintContainer.loadClass(typeName);
}
}
| 9,512 |
0 | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/container/BlueprintEventDispatcher.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.blueprint.container;
import java.util.Arrays;
import java.util.Collections;
import java.util.Dictionary;
import java.util.Hashtable;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.service.blueprint.container.BlueprintEvent;
import org.osgi.service.blueprint.container.BlueprintListener;
import org.osgi.service.blueprint.container.EventConstants;
import org.osgi.service.event.Event;
import org.osgi.service.event.EventAdmin;
import org.osgi.util.tracker.ServiceTracker;
import org.osgi.util.tracker.ServiceTrackerCustomizer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.aries.blueprint.utils.JavaUtils;
import org.apache.aries.blueprint.utils.threading.ScheduledExecutorServiceWrapper;
import org.apache.aries.blueprint.utils.threading.ScheduledExecutorServiceWrapper.ScheduledExecutorServiceFactory;
/**
* The delivery of {@link BlueprintEvent}s is complicated. The blueprint extender and its containers use this class to
* deliver {@link BlueprintEvent}s.
*
* @version $Rev$, $Date$
*/
class BlueprintEventDispatcher implements BlueprintListener {
private static final Logger LOGGER = LoggerFactory.getLogger(BlueprintEventDispatcher.class);
private final Set<BlueprintListener> listeners = new CopyOnWriteArraySet<BlueprintListener>();
private final Map<Bundle, BlueprintEvent> states = new ConcurrentHashMap<Bundle, BlueprintEvent>();
private final ExecutorService executor;
private final EventAdminListener eventAdminListener;
private final ServiceTracker containerListenerTracker;
BlueprintEventDispatcher(final BundleContext bundleContext) {
assert bundleContext != null;
executor = new ScheduledExecutorServiceWrapper(bundleContext, "Blueprint Event Dispatcher", new ScheduledExecutorServiceFactory() {
public ScheduledExecutorService create(String name) {
return Executors.newScheduledThreadPool(1, new BlueprintThreadFactory(name));
}
});
EventAdminListener listener = null;
try {
getClass().getClassLoader().loadClass("org.osgi.service.event.EventAdmin");
listener = new EventAdminListener(bundleContext);
} catch (Throwable t) {
// Ignore, if the EventAdmin package is not available, just don't use it
LOGGER.debug("EventAdmin package is not available, just don't use it");
}
this.eventAdminListener = listener;
this.containerListenerTracker = new ServiceTracker<BlueprintListener, BlueprintListener>(bundleContext, BlueprintListener.class, new ServiceTrackerCustomizer<BlueprintListener, BlueprintListener>() {
public BlueprintListener addingService(ServiceReference<BlueprintListener> reference) {
BlueprintListener listener = bundleContext.getService(reference);
synchronized (listeners) {
sendInitialEvents(listener);
listeners.add(listener);
}
return listener;
}
public void modifiedService(ServiceReference<BlueprintListener> reference, BlueprintListener service) {
}
public void removedService(ServiceReference<BlueprintListener> reference, BlueprintListener service) {
listeners.remove(service);
bundleContext.ungetService(reference);
}
});
this.containerListenerTracker.open();
}
private void sendInitialEvents(BlueprintListener listener) {
for (Map.Entry<Bundle, BlueprintEvent> entry : states.entrySet()) {
try {
callListener(listener, new BlueprintEvent(entry.getValue(), true));
} catch (RejectedExecutionException ree) {
LOGGER.warn("Executor shut down", ree);
break;
}
}
}
public void blueprintEvent(final BlueprintEvent event) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Sending blueprint container event {} for bundle {}/{}", toString(event), event.getBundle().getSymbolicName(), event.getBundle().getVersion());
}
synchronized (listeners) {
callListeners(event);
states.put(event.getBundle(), event);
}
if (eventAdminListener != null) {
try {
eventAdminListener.blueprintEvent(event);
} catch (RejectedExecutionException ree) {
LOGGER.warn("Executor shut down", ree);
}
}
}
@SuppressWarnings({"ThrowableResultOfMethodCallIgnored"})
private static String toString(BlueprintEvent event) {
return "BlueprintEvent[type=" + getEventType(event.getType())
+ (event.getDependencies() != null ? ", dependencies=" + Arrays.asList(event.getDependencies()) : "")
+ (event.getCause() != null ? ", exception=" + event.getCause().getMessage() : "")
+ "]";
}
private static String getEventType(int type) {
switch (type) {
case BlueprintEvent.CREATING:
return "CREATING";
case BlueprintEvent.CREATED:
return "CREATED";
case BlueprintEvent.DESTROYING:
return "DESTROYING";
case BlueprintEvent.DESTROYED:
return "DESTROYED";
case BlueprintEvent.FAILURE:
return "FAILURE";
case BlueprintEvent.GRACE_PERIOD:
return "GRACE_PERIOD";
case BlueprintEvent.WAITING:
return "WAITING";
default:
return "UNKNOWN";
}
}
private void callListeners(BlueprintEvent event) {
for (final BlueprintListener listener : listeners) {
try {
callListener(listener, event);
} catch (RejectedExecutionException ree) {
LOGGER.warn("Executor shut down", ree);
break;
}
}
}
private void callListener(final BlueprintListener listener, final BlueprintEvent event) throws RejectedExecutionException {
try {
long executorTimeout = 60L;
if (System.getenv("BLUEPRINT_EXECUTOR_TIMEOUT") != null) {
executorTimeout = Long.parseLong(System.getenv("BLUEPRINT_EXECUTOR_TIMEOUT"));
}
if (System.getProperty("blueprint.executor.timeout") != null) {
executorTimeout = Long.parseLong(System.getProperty("blueprint.executor.timeout"));
}
executor.invokeAny(Collections.<Callable<Void>>singleton(new Callable<Void>() {
public Void call() throws Exception {
listener.blueprintEvent(event);
return null;
}
}), executorTimeout, TimeUnit.SECONDS);
} catch (InterruptedException ie) {
LOGGER.warn("Thread interrupted", ie);
Thread.currentThread().interrupt();
} catch (TimeoutException te) {
LOGGER.warn("Listener timed out, will be ignored", te);
listeners.remove(listener);
} catch (ExecutionException ee) {
LOGGER.warn("Listener caused an exception, will be ignored", ee);
listeners.remove(listener);
}
}
void destroy() {
executor.shutdown();
// wait for the queued tasks to execute
try {
long executorTimeout = 60L;
if (System.getenv("BLUEPRINT_EXECUTOR_TIMEOUT") != null) {
executorTimeout = Long.parseLong(System.getenv("BLUEPRINT_EXECUTOR_TIMEOUT"));
}
if (System.getProperty("blueprint.executor.timeout") != null) {
executorTimeout = Long.parseLong(System.getProperty("blueprint.executor.timeout"));
}
executor.awaitTermination(executorTimeout, TimeUnit.SECONDS);
} catch (InterruptedException e) {
// ignore
}
containerListenerTracker.close();
// clean up the EventAdmin tracker if we're using that
if (eventAdminListener != null) {
eventAdminListener.destroy();
}
}
public void removeBlueprintBundle(Bundle bundle) {
states.remove(bundle);
}
private static class EventAdminListener implements BlueprintListener {
private final ServiceTracker tracker;
EventAdminListener(BundleContext context) {
tracker = new ServiceTracker<BlueprintListener, BlueprintListener>(context, EventAdmin.class.getName(), null);
tracker.open();
}
@SuppressWarnings({"ThrowableResultOfMethodCallIgnored"})
public void blueprintEvent(BlueprintEvent event) {
EventAdmin eventAdmin = (EventAdmin) tracker.getService();
if (eventAdmin == null) {
return;
}
Dictionary<String, Object> props = new Hashtable<String, Object>();
props.put(EventConstants.TYPE, event.getType());
props.put(EventConstants.EVENT, event);
props.put(EventConstants.TIMESTAMP, event.getTimestamp());
props.put(EventConstants.BUNDLE, event.getBundle());
props.put(EventConstants.BUNDLE_SYMBOLICNAME, event.getBundle().getSymbolicName());
props.put(EventConstants.BUNDLE_ID, event.getBundle().getBundleId());
props.put(EventConstants.BUNDLE_VERSION, JavaUtils.getBundleVersion(event.getBundle()));
props.put(EventConstants.EXTENDER_BUNDLE, event.getExtenderBundle());
props.put(EventConstants.EXTENDER_BUNDLE_ID, event.getExtenderBundle().getBundleId());
props.put(EventConstants.EXTENDER_BUNDLE_SYMBOLICNAME, event.getExtenderBundle().getSymbolicName());
props.put(EventConstants.EXTENDER_BUNDLE_VERSION, JavaUtils.getBundleVersion(event.getExtenderBundle()));
if (event.getCause() != null) {
props.put(EventConstants.CAUSE, event.getCause());
}
if (event.getDependencies() != null) {
props.put(EventConstants.DEPENDENCIES, event.getDependencies());
}
String topic;
switch (event.getType()) {
case BlueprintEvent.CREATING:
topic = EventConstants.TOPIC_CREATING;
break;
case BlueprintEvent.CREATED:
topic = EventConstants.TOPIC_CREATED;
break;
case BlueprintEvent.DESTROYING:
topic = EventConstants.TOPIC_DESTROYING;
break;
case BlueprintEvent.DESTROYED:
topic = EventConstants.TOPIC_DESTROYED;
break;
case BlueprintEvent.FAILURE:
topic = EventConstants.TOPIC_FAILURE;
break;
case BlueprintEvent.GRACE_PERIOD:
topic = EventConstants.TOPIC_GRACE_PERIOD;
break;
case BlueprintEvent.WAITING:
topic = EventConstants.TOPIC_WAITING;
break;
default:
throw new IllegalStateException("Unknown blueprint event type: " + event.getType());
}
eventAdmin.postEvent(new Event(topic, props));
}
/**
* Perform cleanup at Blueprint extender shutdown.
*/
public void destroy() {
tracker.close();
}
}
}
| 9,513 |
0 | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/container/ReferenceListRecipe.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.blueprint.container;
import java.util.*;
import java.util.concurrent.Callable;
import org.apache.aries.blueprint.di.ValueRecipe;
import org.apache.aries.blueprint.services.ExtendedBlueprintContainer;
import org.apache.aries.blueprint.ExtendedReferenceListMetadata;
import org.apache.aries.blueprint.di.Recipe;
import org.apache.aries.blueprint.di.CollectionRecipe;
import org.apache.aries.blueprint.utils.DynamicCollection;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.framework.ServiceReference;
import org.osgi.service.blueprint.container.ReifiedType;
import org.osgi.service.blueprint.container.ComponentDefinitionException;
import org.osgi.service.blueprint.container.ServiceUnavailableException;
import org.osgi.service.blueprint.reflect.ReferenceListMetadata;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A recipe to create a managed collection of service references
*
* @version $Rev$, $Date$
*/
public class ReferenceListRecipe extends AbstractServiceReferenceRecipe {
private static final Logger LOGGER = LoggerFactory.getLogger(ReferenceListRecipe.class);
private final ReferenceListMetadata metadata;
private final List<ManagedCollection> collections = new ArrayList<ManagedCollection>();
private final DynamicCollection<ServiceDispatcher> storage = new DynamicCollection<ServiceDispatcher>();
private final List<ServiceDispatcher> unboundDispatchers = new ArrayList<ServiceDispatcher>();
private final Object monitor = new Object();
public ReferenceListRecipe(String name,
ExtendedBlueprintContainer blueprintContainer,
ReferenceListMetadata metadata,
ValueRecipe filterRecipe,
CollectionRecipe listenersRecipe,
List<Recipe> explicitDependencies) {
super(name, blueprintContainer, metadata, filterRecipe, listenersRecipe, explicitDependencies);
this.metadata = metadata;
}
@Override
public boolean isStaticLifecycle() {
return false;
}
@Override
protected Object internalCreate() throws ComponentDefinitionException {
try {
if (explicitDependencies != null) {
for (Recipe recipe : explicitDependencies) {
recipe.create();
}
}
ProvidedObject object = new ProvidedObject();
addPartialObject(object);
// Handle initial references
createListeners();
updateListeners();
return object;
} catch (ComponentDefinitionException t) {
throw t;
} catch (Throwable t) {
throw new ComponentDefinitionException(t);
}
}
protected void retrack() {
List<ServiceReference> refs = getServiceReferences();
if (refs != null) {
for (ServiceReference ref : refs) {
track(ref);
}
}
}
protected void track(ServiceReference reference) {
synchronized (monitor) {
try {
// ServiceReferences may be tracked at multiple points:
// * first after the collection creation in #internalCreate()
// * in #postCreate() after listeners are created
// * after creation time if a new reference shows up
//
// In the first step, listeners are not created, so we add
// the dispatcher to the unboundDispatchers list. In the second
// step, the dispatcher has already been added to the collection
// so we just call the listener.
//
ServiceDispatcher dispatcher = findDispatcher(reference);
if (dispatcher != null) {
if (!unboundDispatchers.remove(dispatcher)) {
return;
}
} else {
dispatcher = new ServiceDispatcher(reference);
Set<Class<?>> interfaces = new HashSet<Class<?>>();
Class<?> clz = getInterfaceClass();
if (clz != null) interfaces.add(clz);
if (metadata instanceof ExtendedReferenceListMetadata) {
boolean greedy = (((ExtendedReferenceListMetadata) metadata).getProxyMethod() & ExtendedReferenceListMetadata.PROXY_METHOD_GREEDY) != 0;
if (greedy) {
List<String> ifs = Arrays.asList((String[]) reference.getProperty(Constants.OBJECTCLASS));
interfaces.addAll(loadAllClasses(ifs));
}
}
dispatcher.proxy = createProxy(dispatcher, interfaces);
if (!storage.add(dispatcher)) {
dispatcher.destroy();
return;
}
}
if (listeners != null) {
bind(dispatcher.reference, dispatcher.proxy);
} else {
unboundDispatchers.add(dispatcher);
}
} catch (Throwable t) {
LOGGER.info("Error tracking new service reference", t);
}
}
}
protected void untrack(ServiceReference reference) {
synchronized (monitor) {
ServiceDispatcher dispatcher = findDispatcher(reference);
if (dispatcher != null) {
unbind(dispatcher.reference, dispatcher.proxy);
storage.remove(dispatcher);
dispatcher.destroy();
}
}
}
protected ServiceDispatcher findDispatcher(ServiceReference reference) {
for (ServiceDispatcher dispatcher : storage) {
if (dispatcher.reference == reference) {
return dispatcher;
}
}
return null;
}
protected ManagedCollection getManagedCollection(boolean useReferences) {
for (ManagedCollection col : collections) {
if (col.references == useReferences) {
return col;
}
}
ManagedCollection collection = new ManagedCollection(useReferences, storage);
collections.add(collection);
return collection;
}
/**
* The ServiceDispatcher is used when creating the cglib proxy.
* Thic class is responsible for getting the actual service that will be used.
*/
public class ServiceDispatcher implements Callable<Object> {
public ServiceReference reference;
public Object service;
public Object proxy;
public ServiceDispatcher(ServiceReference reference) throws Exception {
this.reference = reference;
}
public synchronized void destroy() {
if (reference != null) {
ServiceReference ref = reference;
reference = null;
service = null;
proxy = null;
Bundle bundle = ref.getBundle();
if (bundle != null) {
BundleContext ctx = getBundleContextForServiceLookup();
if (ctx != null) {
try {
ctx.ungetService(ref);
} catch (IllegalStateException ise) {
// we don't care it doesn't exist so, shrug.
}
}
}
}
}
public synchronized Object call() throws Exception {
if (service == null && reference != null) {
service = getServiceSecurely(reference);
}
if (service == null) {
throw new ServiceUnavailableException("Service is unavailable", getOsgiFilter());
}
return service;
}
}
public class ProvidedObject implements AggregateConverter.Convertible {
public Object convert(ReifiedType type) {
LOGGER.debug("Converting ManagedCollection to {}", type);
if (!type.getRawClass().isAssignableFrom(List.class)) {
throw new ComponentDefinitionException("<reference-list/> can only be converted to a List, not " + type);
}
int memberType = metadata.getMemberType();
boolean useRef = false;
if (type.size() == 1) {
useRef = (type.getActualTypeArgument(0).getRawClass() == ServiceReference.class);
if ( (useRef && memberType == ReferenceListMetadata.USE_SERVICE_OBJECT) ||
(!useRef && memberType == ReferenceListMetadata.USE_SERVICE_REFERENCE)) {
throw new ComponentDefinitionException("The memeber-type specified is incompatible with generic injection type");
}
}
boolean references;
if (memberType == ReferenceListMetadata.USE_SERVICE_REFERENCE) {
references = true;
} else if (memberType == ReferenceListMetadata.USE_SERVICE_OBJECT) {
references = false;
} else {
references = useRef;
}
LOGGER.debug("ManagedCollection references={}", references);
return getManagedCollection(references);
}
}
/**
* Base class for managed collections.
*
* TODO: list iterators should not be supported
* TODO: rework the iteration so that if hasNext() has returned false, it will always return false
* TODO: implement subList()
*/
public static class ManagedCollection extends AbstractCollection implements List, RandomAccess {
protected final DynamicCollection<ServiceDispatcher> dispatchers;
protected boolean references;
public ManagedCollection(boolean references, DynamicCollection<ServiceDispatcher> dispatchers) {
this.references = references;
this.dispatchers = dispatchers;
LOGGER.debug("ManagedCollection references={}", references);
}
public boolean addDispatcher(ServiceDispatcher dispatcher) {
return dispatchers.add(dispatcher);
}
public boolean removeDispatcher(ServiceDispatcher dispatcher) {
return dispatchers.remove(dispatcher);
}
public DynamicCollection<ServiceDispatcher> getDispatchers() {
return dispatchers;
}
public Iterator iterator() {
return new ManagedListIterator(dispatchers.iterator());
}
public int size() {
return dispatchers.size();
}
@Override
public boolean add(Object o) {
throw new UnsupportedOperationException("This collection is read only");
}
@Override
public boolean remove(Object o) {
throw new UnsupportedOperationException("This collection is read only");
}
@Override
public boolean addAll(Collection c) {
throw new UnsupportedOperationException("This collection is read only");
}
@Override
public void clear() {
throw new UnsupportedOperationException("This collection is read only");
}
@Override
public boolean retainAll(Collection c) {
throw new UnsupportedOperationException("This collection is read only");
}
@Override
public boolean removeAll(Collection c) {
throw new UnsupportedOperationException("This collection is read only");
}
public Object get(int index) {
return references ? dispatchers.get(index).reference : dispatchers.get(index).proxy;
}
public int indexOf(Object o) {
if (o == null) {
throw new NullPointerException();
}
ListIterator e = listIterator();
while (e.hasNext()) {
if (o.equals(e.next())) {
return e.previousIndex();
}
}
return -1;
}
public int lastIndexOf(Object o) {
if (o == null) {
throw new NullPointerException();
}
ListIterator e = listIterator(size());
while (e.hasPrevious()) {
if (o.equals(e.previous())) {
return e.nextIndex();
}
}
return -1;
}
public ListIterator listIterator() {
return listIterator(0);
}
public ListIterator listIterator(int index) {
return new ManagedListIterator(dispatchers.iterator(index));
}
public List<ServiceDispatcher> subList(int fromIndex, int toIndex) {
throw new UnsupportedOperationException("Not implemented");
}
public Object set(int index, Object element) {
throw new UnsupportedOperationException("This collection is read only");
}
public void add(int index, Object element) {
throw new UnsupportedOperationException("This collection is read only");
}
public Object remove(int index) {
throw new UnsupportedOperationException("This collection is read only");
}
public boolean addAll(int index, Collection c) {
throw new UnsupportedOperationException("This collection is read only");
}
public class ManagedListIterator implements ListIterator {
protected final ListIterator<ServiceDispatcher> iterator;
public ManagedListIterator(ListIterator<ServiceDispatcher> iterator) {
this.iterator = iterator;
}
public boolean hasNext() {
return iterator.hasNext();
}
public Object next() {
return references ? iterator.next().reference : iterator.next().proxy;
}
public boolean hasPrevious() {
return iterator.hasPrevious();
}
public Object previous() {
return references ? iterator.previous().reference : iterator.previous().proxy;
}
public int nextIndex() {
return iterator.nextIndex();
}
public int previousIndex() {
return iterator.previousIndex();
}
public void remove() {
throw new UnsupportedOperationException("This collection is read only");
}
public void set(Object o) {
throw new UnsupportedOperationException("This collection is read only");
}
public void add(Object o) {
throw new UnsupportedOperationException("This collection is read only");
}
}
}
}
| 9,514 |
0 | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/container/BlueprintExtender.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.blueprint.container;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
import java.util.concurrent.ScheduledExecutorService;
import org.apache.aries.blueprint.BlueprintConstants;
import org.apache.aries.blueprint.annotation.service.BlueprintAnnotationScanner;
import org.apache.aries.blueprint.namespace.NamespaceHandlerRegistryImpl;
import org.apache.aries.blueprint.services.BlueprintExtenderService;
import org.apache.aries.blueprint.services.ParserService;
import org.apache.aries.blueprint.utils.HeaderParser;
import org.apache.aries.blueprint.utils.HeaderParser.PathElement;
import org.apache.aries.blueprint.utils.ServiceUtil;
import org.apache.aries.blueprint.utils.threading.ScheduledExecutorServiceWrapper;
import org.apache.aries.blueprint.utils.threading.ScheduledExecutorServiceWrapper.ScheduledExecutorServiceFactory;
import org.apache.aries.proxy.ProxyManager;
import org.apache.aries.util.tracker.RecursiveBundleTracker;
import org.apache.aries.util.tracker.SingleServiceTracker;
import org.apache.aries.util.tracker.SingleServiceTracker.SingleServiceListener;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleEvent;
import org.osgi.framework.Constants;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.ServiceRegistration;
import org.osgi.framework.SynchronousBundleListener;
import org.osgi.service.blueprint.container.BlueprintContainer;
import org.osgi.service.blueprint.container.BlueprintEvent;
import org.osgi.util.tracker.BundleTracker;
import org.osgi.util.tracker.BundleTrackerCustomizer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This is the blueprint extender that listens to blueprint bundles.
*
* @version $Rev$, $Date$
*/
public class BlueprintExtender implements BundleActivator, BundleTrackerCustomizer, SynchronousBundleListener {
/** The QuiesceParticipant implementation class name */
private static final String CONTAINER_ADDITIONAL_NAMESPACES = "org.apache.aries.blueprint.extender.additional.namespaces";
private static final String QUIESCE_PARTICIPANT_CLASS = "org.apache.aries.quiesce.participant.QuiesceParticipant";
private static final String EXTENDER_THREADS_PROPERTY = "org.apache.aries.blueprint.extender.threads";
private static final int DEFAULT_NUMBER_OF_THREADS = 3;
private static final Logger LOGGER = LoggerFactory.getLogger(BlueprintExtender.class);
private BundleContext context;
private ScheduledExecutorService executors;
private final ConcurrentMap<Bundle, BlueprintContainerImpl> containers = new ConcurrentHashMap<Bundle, BlueprintContainerImpl>();
private final ConcurrentMap<Bundle, FutureTask> destroying = new ConcurrentHashMap<Bundle, FutureTask>();
private BlueprintEventDispatcher eventDispatcher;
private NamespaceHandlerRegistry handlers;
private Object bt;
private ServiceRegistration parserServiceReg;
private ServiceRegistration blueprintServiceReg;
private ServiceRegistration quiesceParticipantReg;
private SingleServiceTracker<ProxyManager> proxyManager;
private ExecutorServiceFinder executorServiceFinder;
private volatile boolean stopping;
public void start(BundleContext ctx) {
LOGGER.debug("Starting blueprint extender...");
this.context = ctx;
boolean useSystemContext = Boolean.parseBoolean(ctx.getProperty(BlueprintConstants.USE_SYSTEM_CONTEXT_PROPERTY));
BundleContext trackingContext = useSystemContext ? ctx.getBundle(Constants.SYSTEM_BUNDLE_LOCATION).getBundleContext() : ctx;
handlers = new NamespaceHandlerRegistryImpl(trackingContext);
executors = new ScheduledExecutorServiceWrapper(ctx, "Blueprint Extender", new ScheduledExecutorServiceFactory() {
public ScheduledExecutorService create(String name) {
int extenderThreads = DEFAULT_NUMBER_OF_THREADS;
try {
extenderThreads = Integer.getInteger(EXTENDER_THREADS_PROPERTY, DEFAULT_NUMBER_OF_THREADS);
if (extenderThreads != DEFAULT_NUMBER_OF_THREADS) {
LOGGER.debug(EXTENDER_THREADS_PROPERTY + " is set to " + extenderThreads + ".");
}
}
catch (Exception e) {
LOGGER.error(EXTENDER_THREADS_PROPERTY + " is not a number. Using default value " + DEFAULT_NUMBER_OF_THREADS + ".");
}
return Executors.newScheduledThreadPool(extenderThreads, new BlueprintThreadFactory(name));
}
});
eventDispatcher = new BlueprintEventDispatcher(ctx);
// Ideally we'd want to only track STARTING and ACTIVE bundle, but this is not supported
// when using equinox composites. This would ensure that no STOPPING event is lost while
// tracking the initial bundles. To work around this issue, we need to register
// a synchronous bundle listener that will ensure the stopping event will be correctly
// handled.
context.addBundleListener(this);
int mask = Bundle.INSTALLED | Bundle.RESOLVED | Bundle.STARTING | Bundle.STOPPING | Bundle.ACTIVE;
bt = useSystemContext ? new BundleTracker(trackingContext, mask, this) : new RecursiveBundleTracker(ctx, mask, this);
proxyManager = new SingleServiceTracker<ProxyManager>(ctx, ProxyManager.class, new SingleServiceListener() {
public void serviceFound() {
LOGGER.debug("Found ProxyManager service, starting to process blueprint bundles");
if (bt instanceof BundleTracker) {
((BundleTracker) bt).open();
} else if (bt instanceof RecursiveBundleTracker) {
((RecursiveBundleTracker) bt).open();
}
}
public void serviceLost() {
while (!containers.isEmpty()) {
for (Bundle bundle : getBundlesToDestroy()) {
destroyContainer(bundle);
}
}
if (bt instanceof BundleTracker) {
((BundleTracker) bt).close();
} else if (bt instanceof RecursiveBundleTracker) {
((RecursiveBundleTracker) bt).close();
}
}
public void serviceReplaced() {
}
});
proxyManager.open();
// Determine if the ParserService should ignore unknown namespace handlers
boolean ignoreUnknownNamespaceHandlers = Boolean.parseBoolean(ctx.getProperty(BlueprintConstants.IGNORE_UNKNOWN_NAMESPACE_HANDLERS_PROPERTY));
// Create and publish a ParserService
parserServiceReg = ctx.registerService(ParserService.class.getName(),
new ParserServiceImpl(handlers, ignoreUnknownNamespaceHandlers),
new Hashtable<String, Object>());
// Create and publish a BlueprintContainerService
blueprintServiceReg = ctx.registerService(
BlueprintExtenderService.class.getName(),
new BlueprintContainerServiceImpl(),
new Hashtable<String, Object>());
try {
ctx.getBundle().loadClass(QUIESCE_PARTICIPANT_CLASS);
//Class was loaded, register
quiesceParticipantReg = ctx.registerService(QUIESCE_PARTICIPANT_CLASS,
new BlueprintQuiesceParticipant(ctx, this),
new Hashtable<String, Object>());
} catch (ClassNotFoundException e) {
LOGGER.info("No quiesce support is available, so blueprint components will not participate in quiesce operations");
}
LOGGER.debug("Blueprint extender started");
}
public void stop(BundleContext context) {
LOGGER.debug("Stopping blueprint extender...");
stopping = true;
ServiceUtil.safeUnregisterService(parserServiceReg);
ServiceUtil.safeUnregisterService(blueprintServiceReg);
ServiceUtil.safeUnregisterService(quiesceParticipantReg);
// Orderly shutdown of containers
while (!containers.isEmpty()) {
for (Bundle bundle : getBundlesToDestroy()) {
destroyContainer(bundle);
}
}
if (bt instanceof BundleTracker) {
((BundleTracker) bt).close();
} else if (bt instanceof RecursiveBundleTracker) {
((RecursiveBundleTracker) bt).close();
}
proxyManager.close();
this.eventDispatcher.destroy();
this.handlers.destroy();
executors.shutdown();
LOGGER.debug("Blueprint extender stopped");
}
/*
* SynchronousBundleListener
*/
public void bundleChanged(BundleEvent event) {
Bundle bundle = event.getBundle();
if (bundle.getState() != Bundle.ACTIVE && bundle.getState() != Bundle.STARTING) {
// The bundle is not in STARTING or ACTIVE state anymore
// so destroy the context. Ignore our own bundle since it
// needs to kick the orderly shutdown and not unregister the namespaces.
if (bundle != this.context.getBundle()) {
destroyContainer(bundle);
}
}
}
/*
* BundleTrackerCustomizer
*/
public Object addingBundle(Bundle bundle, BundleEvent event) {
modifiedBundle(bundle, event, bundle);
return bundle;
}
public void modifiedBundle(Bundle bundle, BundleEvent event, Object object) {
// If the bundle being stopped is the system bundle,
// do an orderly shutdown of all blueprint contexts now
// so that service usage can actually be useful
if (context.getBundle(0).equals(bundle) && bundle.getState() == Bundle.STOPPING) {
String val = context.getProperty(BlueprintConstants.PREEMPTIVE_SHUTDOWN_PROPERTY);
if (val == null || Boolean.parseBoolean(val)) {
stop(context);
return;
}
}
if (bundle.getState() != Bundle.ACTIVE && bundle.getState() != Bundle.STARTING) {
// The bundle is not in STARTING or ACTIVE state anymore
// so destroy the context. Ignore our own bundle since it
// needs to kick the orderly shutdown and not unregister the namespaces.
if (bundle != this.context.getBundle()) {
destroyContainer(bundle);
}
return;
}
// Do not track bundles given we are stopping
if (stopping) {
return;
}
// For starting bundles, ensure, it's a lazy activation,
// else we'll wait for the bundle to become ACTIVE
if (bundle.getState() == Bundle.STARTING) {
String activationPolicyHeader = (String) bundle.getHeaders().get(Constants.BUNDLE_ACTIVATIONPOLICY);
if (activationPolicyHeader == null || !activationPolicyHeader.startsWith(Constants.ACTIVATION_LAZY)) {
// Do not track this bundle yet
return;
}
}
createContainer(bundle);
}
public void removedBundle(Bundle bundle, BundleEvent event, Object object) {
// Nothing to do
destroyContainer(bundle);
}
private boolean createContainer(Bundle bundle) {
List<URL> paths = getBlueprintPaths(bundle);
return createContainer(bundle, paths);
}
private boolean createContainer(Bundle bundle, List<URL> paths) {
return createContainer(bundle, paths, getAdditionalNamespaces(bundle));
}
private Collection<URI> getAdditionalNamespaces(Bundle bundle) {
String additionalNamespacesProperty = bundle.getBundleContext().getProperty(CONTAINER_ADDITIONAL_NAMESPACES);
Set<URI> uris = null;
if(additionalNamespacesProperty != null) {
uris = new HashSet<URI>();
String[] strings = additionalNamespacesProperty.split(",");
for (String str : strings) {
str = str.trim();
if (str.length() != 0) {
uris.add(URI.create(str));
}
}
}
return uris;
}
private boolean createContainer(Bundle bundle, List<URL> paths, Collection<URI> namespaces) {
try {
if (paths == null || paths.isEmpty()) {
// This bundle is not a blueprint bundle, so ignore it
return false;
}
ProxyManager pm = proxyManager.getService();
if (pm == null) {
// The pm isn't available. It may be because it is being untracked
return false;
}
BundleContext bundleContext = bundle.getBundleContext();
if (bundleContext == null) {
// The bundle has been stopped in the mean time
return false;
}
BlueprintContainerImpl blueprintContainer = new BlueprintContainerImpl(bundle, bundleContext,
context.getBundle(), eventDispatcher,
handlers, getExecutorService(bundle),
executors, paths, pm, namespaces);
synchronized (containers) {
if (containers.putIfAbsent(bundle, blueprintContainer) != null) {
return false;
}
}
String val = context.getProperty(BlueprintConstants.SYNCHRONOUS_PROPERTY);
if (Boolean.parseBoolean(val)) {
LOGGER.debug("Starting creation of blueprint bundle {}/{} synchronously", bundle.getSymbolicName(), bundle.getVersion());
blueprintContainer.run();
} else {
LOGGER.debug("Scheduling creation of blueprint bundle {}/{} asynchronously", bundle.getSymbolicName(), bundle.getVersion());
blueprintContainer.schedule();
}
return true;
} catch (Throwable t) {
LOGGER.warn("Error while creating container for blueprint bundle {}/{}", bundle.getSymbolicName(), bundle.getVersion(), t);
return false;
}
}
private void destroyContainer(final Bundle bundle) {
FutureTask future;
synchronized (containers) {
LOGGER.debug("Starting container destruction process for blueprint bundle {}/{}", bundle.getSymbolicName(), bundle.getVersion());
future = destroying.get(bundle);
if (future == null) {
final BlueprintContainerImpl blueprintContainer = containers.remove(bundle);
if (blueprintContainer != null) {
LOGGER.debug("Scheduling container destruction for blueprint bundle {}/{}.", bundle.getSymbolicName(), bundle.getVersion());
future = new FutureTask<Void>(new Runnable() {
public void run() {
LOGGER.info("Destroying container for blueprint bundle {}/{}", bundle.getSymbolicName(), bundle.getVersion());
try {
blueprintContainer.destroy();
} finally {
LOGGER.debug("Finished destroying container for blueprint bundle {}/{}", bundle.getSymbolicName(), bundle.getVersion());
eventDispatcher.removeBlueprintBundle(bundle);
synchronized (containers) {
destroying.remove(bundle);
}
}
}
}, null);
destroying.put(bundle, future);
} else {
LOGGER.debug("Not a blueprint bundle or destruction of container already finished for {}/{}.", bundle.getSymbolicName(), bundle.getVersion());
}
} else {
LOGGER.debug("Destruction already scheduled for blueprint bundle {}/{}.", bundle.getSymbolicName(), bundle.getVersion());
}
}
if (future != null) {
try {
LOGGER.debug("Waiting for container destruction for blueprint bundle {}/{}.", bundle.getSymbolicName(), bundle.getVersion());
future.run();
future.get();
} catch (Throwable t) {
LOGGER.warn("Error while destroying container for blueprint bundle {}/{}", bundle.getSymbolicName(), bundle.getVersion(), t);
}
}
}
private List<URL> resolvePaths(Bundle bundle, List<Object> paths) {
if (paths == null || paths.isEmpty()) {
return null;
}
List<URL> resolved = new ArrayList<URL>(paths.size());
for (Object path : paths) {
if (path instanceof URL) {
resolved.add((URL) path);
} else if (path instanceof String) {
String name = (String) path;
if (name.endsWith("/")) {
addEntries(bundle, name, "*.xml", resolved);
} else {
String baseName;
String filePattern;
int pos = name.lastIndexOf('/');
if (pos < 0) {
baseName = "/";
filePattern = name;
} else {
baseName = name.substring(0, pos + 1);
filePattern = name.substring(pos + 1);
}
addEntries(bundle, baseName, filePattern, resolved);
}
} else {
throw new IllegalArgumentException("Unexpected path type: " + path.getClass());
}
}
return resolved;
}
private List<URL> getBlueprintPaths(Bundle bundle) {
LOGGER.debug("Scanning bundle {}/{} for blueprint application", bundle.getSymbolicName(), bundle.getVersion());
try {
List<URL> pathList = new ArrayList<URL>();
String blueprintHeader = bundle.getHeaders().get(BlueprintConstants.BUNDLE_BLUEPRINT_HEADER);
String blueprintHeaderAnnotation = bundle.getHeaders().get(BlueprintConstants.BUNDLE_BLUEPRINT_ANNOTATION_HEADER);
if (blueprintHeader == null) {
blueprintHeader = "OSGI-INF/blueprint/";
}
List<PathElement> paths = HeaderParser.parseHeader(blueprintHeader);
for (PathElement path : paths) {
String name = path.getName();
if (name.endsWith("/")) {
addEntries(bundle, name, "*.xml", pathList);
} else {
String baseName;
String filePattern;
int pos = name.lastIndexOf('/');
if (pos < 0) {
baseName = "/";
filePattern = name;
} else {
baseName = name.substring(0, pos + 1);
filePattern = name.substring(pos + 1);
}
addEntries(bundle, baseName, filePattern, pathList);
}
}
// Check annotations
if (blueprintHeaderAnnotation != null && blueprintHeaderAnnotation.trim().equalsIgnoreCase("true")) {
LOGGER.debug("Scanning bundle {}/{} for blueprint annotations", bundle.getSymbolicName(), bundle.getVersion());
ServiceReference sr = this.context.getServiceReference(BlueprintAnnotationScanner.class.getName());
if (sr != null) {
BlueprintAnnotationScanner bas = (BlueprintAnnotationScanner) this.context.getService(sr);
try {
// try to generate the blueprint definition XML
URL url = bas.createBlueprintModel(bundle);
if (url != null) {
pathList.add(url);
}
} finally {
this.context.ungetService(sr);
}
}
}
if (!pathList.isEmpty()) {
LOGGER.debug("Found blueprint application in bundle {}/{} with paths: {}", bundle.getSymbolicName(), bundle.getVersion(), pathList);
// Check compatibility
// TODO: For lazy bundles, the class is either loaded from an imported package or not found, so it should
// not trigger the activation. If it does, we need to use something else like package admin or
// ServiceReference, or just not do this check, which could be quite harmful.
if (isCompatible(bundle)) {
return pathList;
} else {
LOGGER.info("Bundle {}/{} is not compatible with this blueprint extender", bundle.getSymbolicName(), bundle.getVersion());
}
} else {
LOGGER.debug("No blueprint application found in bundle {}/{}", bundle.getSymbolicName(), bundle.getVersion());
}
} catch (Throwable t) {
if (!stopping) {
LOGGER.warn("Error creating blueprint container for bundle {}/{}", bundle.getSymbolicName(), bundle.getVersion(), t);
eventDispatcher.blueprintEvent(new BlueprintEvent(BlueprintEvent.FAILURE, bundle, context.getBundle(), t));
}
}
return null;
}
private List<Bundle> getBundlesToDestroy() {
List<Bundle> bundlesToDestroy = new ArrayList<Bundle>();
for (Bundle bundle : containers.keySet()) {
ServiceReference[] references = bundle.getRegisteredServices();
int usage = 0;
if (references != null) {
for (ServiceReference reference : references) {
usage += getServiceUsage(reference);
}
}
LOGGER.debug("Usage for bundle {}/{} is {}", bundle.getSymbolicName(), bundle.getVersion(), usage);
if (usage == 0) {
bundlesToDestroy.add(bundle);
}
}
if (!bundlesToDestroy.isEmpty()) {
Collections.sort(bundlesToDestroy, new Comparator<Bundle>() {
public int compare(Bundle b1, Bundle b2) {
return (int) (b2.getLastModified() - b1.getLastModified());
}
});
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Selected bundles {} for destroy (no services in use)", toString(bundlesToDestroy));
}
} else {
ServiceReference ref = null;
for (Bundle bundle : containers.keySet()) {
ServiceReference[] references = bundle.getRegisteredServices();
for (ServiceReference reference : references) {
if (getServiceUsage(reference) == 0) {
continue;
}
if (ref == null || reference.compareTo(ref) < 0) {
LOGGER.debug("Currently selecting bundle {}/{} for destroy (with reference {})", bundle.getSymbolicName(), bundle.getVersion(), reference);
ref = reference;
}
}
}
if (ref != null) {
bundlesToDestroy.add(ref.getBundle());
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Selected bundles {} for destroy (lowest ranking service)", toString(bundlesToDestroy));
}
}
return bundlesToDestroy;
}
private static String toString(List<Bundle> bundles) {
StringBuilder sb = new StringBuilder();
sb.append("[");
for (int i = 0; i < bundles.size(); i++) {
if (i > 0) {
sb.append(", ");
}
sb.append(bundles.get(i).getSymbolicName());
sb.append("/");
sb.append(bundles.get(i).getVersion());
}
sb.append("]");
return sb.toString();
}
private static int getServiceUsage(ServiceReference ref) {
Bundle[] usingBundles = ref.getUsingBundles();
return (usingBundles != null) ? usingBundles.length : 0;
}
private ExecutorService getExecutorService(Bundle bundle) {
if (executorServiceFinder != null) {
return executorServiceFinder.find(bundle);
} else {
return executors;
}
}
interface ExecutorServiceFinder {
ExecutorService find(Bundle bundle);
}
private boolean isCompatible(Bundle bundle) {
// Check compatibility
boolean compatible;
if (bundle.getState() == Bundle.ACTIVE) {
try {
Class<?> clazz = bundle.getBundleContext().getBundle().loadClass(BlueprintContainer.class.getName());
compatible = (clazz == BlueprintContainer.class);
} catch (ClassNotFoundException e) {
compatible = true;
}
} else {
// for lazy bundle, we can't load the class, so just assume it's ok
compatible = true;
}
return compatible;
}
private String getFilePart(URL url) {
String path = url.getPath();
int index = path.lastIndexOf('/');
return path.substring(index + 1);
}
private String cachePath(Bundle bundle, String filePath) {
return Integer.toHexString(bundle.hashCode()) + "/" + filePath;
}
private URL getOverrideURLForCachePath(String privatePath) {
URL override = null;
File privateDataVersion = context.getDataFile(privatePath);
if (privateDataVersion != null
&& privateDataVersion.exists()) {
try {
override = privateDataVersion.toURI().toURL();
} catch (MalformedURLException e) {
LOGGER.error("Unexpected URL Conversion Issue", e);
}
}
return override;
}
private URL getOverrideURL(Bundle bundle, URL path, String basePath) {
String cachePath = cachePath(bundle, basePath + getFilePart(path));
return getOverrideURLForCachePath(cachePath);
}
private void addEntries(Bundle bundle, String path, String filePattern, List<URL> pathList) {
Enumeration<?> e = bundle.findEntries(path, filePattern, false);
while (e != null && e.hasMoreElements()) {
URL u = (URL) e.nextElement();
URL override = getOverrideURL(bundle, u, path);
if (override == null) {
pathList.add(u);
} else {
pathList.add(override);
}
}
}
protected BlueprintContainerImpl getBlueprintContainerImpl(Bundle bundle) {
return containers.get(bundle);
}
private class BlueprintContainerServiceImpl implements BlueprintExtenderService {
public BlueprintContainer createContainer(Bundle bundle) {
if (BlueprintExtender.this.createContainer(bundle)) {
return getContainer(bundle);
} else {
return null;
}
}
public BlueprintContainer createContainer(Bundle bundle, List<Object> blueprintPaths) {
if (BlueprintExtender.this.createContainer(bundle, resolvePaths(bundle, blueprintPaths))) {
return getContainer(bundle);
} else {
return null;
}
}
public BlueprintContainer createContainer(Bundle bundle, List<Object> blueprintPaths, Collection<URI> namespaces) {
if (BlueprintExtender.this.createContainer(bundle, resolvePaths(bundle, blueprintPaths), namespaces)) {
return getContainer(bundle);
} else {
return null;
}
}
public void destroyContainer(Bundle bundle, BlueprintContainer container) {
BlueprintContainer bundleContainer = getContainer(bundle);
if (bundleContainer != container) {
String error = "Unexpected Blueprint Container";
LOGGER.error(error);
throw new IllegalArgumentException(error);
}
BlueprintExtender.this.destroyContainer(bundle);
}
public BlueprintContainer getContainer(Bundle bundle) {
return BlueprintExtender.this.getBlueprintContainerImpl(bundle);
}
}
}
| 9,515 |
0 | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/container/AggregateConverter.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.blueprint.container;
import java.io.ByteArrayInputStream;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.security.AccessControlContext;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.security.PrivilegedExceptionAction;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Dictionary;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.regex.Pattern;
import org.apache.aries.blueprint.container.BeanRecipe.UnwrapperedBeanHolder;
import org.apache.aries.blueprint.container.GenericType.BoundType;
import org.apache.aries.blueprint.di.CollectionRecipe;
import org.apache.aries.blueprint.di.MapRecipe;
import org.apache.aries.blueprint.services.ExtendedBlueprintContainer;
import org.apache.aries.blueprint.utils.ReflectionUtils;
import org.osgi.service.blueprint.container.Converter;
import org.osgi.service.blueprint.container.ReifiedType;
import static org.apache.aries.blueprint.utils.ReflectionUtils.getRealCause;
/**
* Implementation of the Converter.
*
* This object contains all the registered Converters which can be registered
* by using {@link #registerConverter(Converter)}
* and unregistered using {@link #unregisterConverter(Converter)}.
*
* Each {@link org.osgi.service.blueprint.container.BlueprintContainer} has its own AggregateConverter
* used to register converters defined by the related blueprint bundle.
*
* @version $Rev$, $Date$
*/
public class AggregateConverter implements Converter {
/**
* Objects implementing this interface will bypass the default conversion rules
* and be called directly to transform into the expected type.
*/
public static interface Convertible {
Object convert(ReifiedType type) throws Exception;
}
private static class ConversionResult {
public final Converter converter;
public final Object value;
public ConversionResult(Converter converter, Object value) {
this.converter = converter;
this.value = value;
}
}
private ExtendedBlueprintContainer blueprintContainer;
private List<Converter> converters = new ArrayList<Converter>();
public AggregateConverter(ExtendedBlueprintContainer blueprintContainer) {
this.blueprintContainer = blueprintContainer;
}
public void registerConverter(Converter converter) {
converters.add(converter);
}
public void unregisterConverter(Converter converter) {
converters.remove(converter);
}
public boolean canConvert(Object fromValue, final ReifiedType toType) {
if (fromValue == null) {
return true;
} else if (fromValue instanceof UnwrapperedBeanHolder) {
fromValue = ((UnwrapperedBeanHolder) fromValue).unwrapperedBean;
}
if (isAssignable(fromValue, toType)) {
return true;
}
final Object toTest = fromValue;
boolean canConvert = false;
AccessControlContext acc = blueprintContainer.getAccessControlContext();
if (acc == null) {
canConvert = canConvertWithConverters(toTest, toType);
} else {
canConvert = AccessController.doPrivileged(new PrivilegedAction<Boolean>() {
public Boolean run() {
return canConvertWithConverters(toTest, toType);
}
}, acc);
}
if (canConvert) {
return true;
}
// TODO implement better logic ?!
try {
convert(toTest, toType);
return true;
} catch (Exception e) {
return false;
}
}
public Object convert(Object fromValue, final ReifiedType type) throws Exception {
// Discard null values
if (fromValue == null) {
return null;
}
// First convert service proxies
if (fromValue instanceof Convertible) {
return ((Convertible) fromValue).convert(type);
} else if (fromValue instanceof UnwrapperedBeanHolder) {
UnwrapperedBeanHolder holder = (UnwrapperedBeanHolder) fromValue;
if (isAssignable(holder.unwrapperedBean, type)) {
return BeanRecipe.wrap(holder, type.getRawClass());
} else {
fromValue = BeanRecipe.wrap(holder, Object.class);
}
} else if (isAssignable(fromValue, type)) {
// If the object is an instance of the type, just return it
return fromValue;
}
final Object finalFromValue = fromValue;
ConversionResult result = null;
AccessControlContext acc = blueprintContainer.getAccessControlContext();
if (acc == null) {
result = convertWithConverters(fromValue, type);
} else {
result = AccessController.doPrivileged(new PrivilegedExceptionAction<ConversionResult>() {
public ConversionResult run() throws Exception {
return convertWithConverters(finalFromValue, type);
}
}, acc);
}
if (result == null) {
if (fromValue instanceof Number && Number.class.isAssignableFrom(unwrap(toClass(type)))) {
return convertToNumber((Number) fromValue, toClass(type));
} else if (fromValue instanceof String) {
return convertFromString((String) fromValue, toClass(type), blueprintContainer);
} else if (toClass(type).isArray() && (fromValue instanceof Collection || fromValue.getClass().isArray())) {
return convertToArray(fromValue, type);
} else if (Map.class.isAssignableFrom(toClass(type)) && (fromValue instanceof Map || fromValue instanceof Dictionary)) {
return convertToMap(fromValue, type);
} else if (Dictionary.class.isAssignableFrom(toClass(type)) && (fromValue instanceof Map || fromValue instanceof Dictionary)) {
return convertToDictionary(fromValue, type);
} else if (Collection.class.isAssignableFrom(toClass(type)) && (fromValue instanceof Collection || fromValue.getClass().isArray())) {
return convertToCollection(fromValue, type);
} else {
throw new Exception("Unable to convert value " + fromValue + " to type " + type);
}
}
return result.value;
}
private Converter selectMatchingConverter(Object source, ReifiedType type) {
for (Converter converter : converters) {
if (converter.canConvert(source, type)) {
return converter;
}
}
return null;
}
private boolean canConvertWithConverters(Object source, ReifiedType type) {
return selectMatchingConverter(source, type) != null;
}
private ConversionResult convertWithConverters(Object source, ReifiedType type) throws Exception {
Converter converter = selectMatchingConverter(source, type);
if (converter == null) return null;
Object value = converter.convert(source, type);
return new ConversionResult(converter, value);
}
public Object convertToNumber(Number value, Class toType) throws Exception {
toType = unwrap(toType);
if (AtomicInteger.class == toType) {
return new AtomicInteger((Integer) convertToNumber(value, Integer.class));
} else if (AtomicLong.class == toType) {
return new AtomicLong((Long) convertToNumber(value, Long.class));
} else if (Integer.class == toType) {
return value.intValue();
} else if (Short.class == toType) {
return value.shortValue();
} else if (Long.class == toType) {
return value.longValue();
} else if (Float.class == toType) {
return value.floatValue();
} else if (Double.class == toType) {
return value.doubleValue();
} else if (Byte.class == toType) {
return value.byteValue();
} else if (BigInteger.class == toType) {
return new BigInteger(value.toString());
} else if (BigDecimal.class == toType) {
return new BigDecimal(value.toString());
} else {
throw new Exception("Unable to convert number " + value + " to " + toType);
}
}
public Object convertFromString(String value, Class toType, Object loader) throws Exception {
toType = unwrap(toType);
if (ReifiedType.class == toType) {
try {
return GenericType.parse(value, loader);
} catch (ClassNotFoundException e) {
throw new Exception("Unable to convert", e);
}
} else if (Class.class == toType) {
try {
return GenericType.parse(value, loader).getRawClass();
} catch (ClassNotFoundException e) {
throw new Exception("Unable to convert", e);
}
} else if (Locale.class == toType) {
String[] tokens = value.split("_");
if (tokens.length == 1) {
return new Locale(tokens[0]);
} else if (tokens.length == 2) {
return new Locale(tokens[0], tokens[1]);
} else if (tokens.length == 3) {
return new Locale(tokens[0], tokens[1], tokens[2]);
} else {
throw new Exception("Invalid locale string:" + value);
}
} else if (Pattern.class == toType) {
return Pattern.compile(value);
} else if (Properties.class == toType) {
Properties props = new Properties();
ByteArrayInputStream in = new ByteArrayInputStream(value.getBytes("UTF8"));
props.load(in);
return props;
} else if (Boolean.class == toType) {
if ("yes".equalsIgnoreCase(value) || "true".equalsIgnoreCase(value) || "on".equalsIgnoreCase(value)) {
return Boolean.TRUE;
} else if ("no".equalsIgnoreCase(value) || "false".equalsIgnoreCase(value) || "off".equalsIgnoreCase(value)) {
return Boolean.FALSE;
} else {
throw new RuntimeException("Invalid boolean value: " + value);
}
} else if (Integer.class == toType) {
return Integer.valueOf(value);
} else if (Short.class == toType) {
return Short.valueOf(value);
} else if (Long.class == toType) {
return Long.valueOf(value);
} else if (Float.class == toType) {
return Float.valueOf(value);
} else if (Double.class == toType) {
return Double.valueOf(value);
} else if (Character.class == toType) {
if (value.length() == 6 && value.startsWith("\\u")) {
int code = Integer.parseInt(value.substring(2), 16);
return (char) code;
} else if (value.length() == 1) {
return value.charAt(0);
} else {
throw new Exception("Invalid value for character type: " + value);
}
} else if (Byte.class == toType) {
return Byte.valueOf(value);
} else if (Enum.class.isAssignableFrom(toType)) {
return Enum.valueOf((Class<Enum>) toType, value);
} else {
return createObject(value, toType);
}
}
private Object createObject(String value, Class type) throws Exception {
if (type.isInterface() || Modifier.isAbstract(type.getModifiers())) {
throw new Exception("Unable to convert value " + value + " to type " + type + ". Type " + type + " is an interface or an abstract class");
}
Constructor constructor = null;
try {
constructor = type.getConstructor(String.class);
} catch (NoSuchMethodException e) {
throw new RuntimeException("Unable to convert to " + type);
}
try {
return ReflectionUtils.newInstance(blueprintContainer.getAccessControlContext(), constructor, value);
} catch (Exception e) {
throw new Exception("Unable to convert ", getRealCause(e));
}
}
private Object convertToCollection(Object obj, ReifiedType type) throws Exception {
ReifiedType valueType = type.getActualTypeArgument(0);
Collection newCol = (Collection) ReflectionUtils.newInstance(blueprintContainer.getAccessControlContext(),
CollectionRecipe.getCollection(toClass(type)));
if (obj.getClass().isArray()) {
for (int i = 0; i < Array.getLength(obj); i++) {
try {
Object ov = Array.get(obj, i);
Object cv = convert(ov, valueType);
newCol.add(cv);
} catch (Exception t) {
throw new Exception("Unable to convert from " + obj + " to " + type + "(error converting array element)", t);
}
}
return newCol;
} else {
boolean converted = !toClass(type).isAssignableFrom(obj.getClass());
for (Object item : (Collection) obj) {
try {
Object cv = convert(item, valueType);
converted |= item != cv;
newCol.add(cv);
} catch (Exception t) {
throw new Exception("Unable to convert from " + obj + " to " + type + "(error converting collection entry)", t);
}
}
return converted ? newCol : obj;
}
}
private Object convertToDictionary(Object obj, ReifiedType type) throws Exception {
ReifiedType keyType = type.getActualTypeArgument(0);
ReifiedType valueType = type.getActualTypeArgument(1);
if (obj instanceof Dictionary) {
Dictionary newDic = new Hashtable();
Dictionary dic = (Dictionary) obj;
boolean converted = false;
for (Enumeration keyEnum = dic.keys(); keyEnum.hasMoreElements();) {
Object key = keyEnum.nextElement();
try {
Object nk = convert(key, keyType);
Object ov = dic.get(key);
Object nv = convert(ov, valueType);
newDic.put(nk, nv);
converted |= nk != key || nv != ov;
} catch (Exception t) {
throw new Exception("Unable to convert from " + obj + " to " + type + "(error converting map entry)", t);
}
}
return converted ? newDic : obj;
} else {
Dictionary newDic = new Hashtable();
for (Map.Entry e : ((Map<Object, Object>) obj).entrySet()) {
try {
newDic.put(convert(e.getKey(), keyType), convert(e.getValue(), valueType));
} catch (Exception t) {
throw new Exception("Unable to convert from " + obj + " to " + type + "(error converting map entry)", t);
}
}
return newDic;
}
}
private Object convertToMap(Object obj, ReifiedType type) throws Exception {
ReifiedType keyType = type.getActualTypeArgument(0);
ReifiedType valueType = type.getActualTypeArgument(1);
Map newMap = (Map) ReflectionUtils.newInstance(blueprintContainer.getAccessControlContext(),
MapRecipe.getMap(toClass(type)));
if (obj instanceof Dictionary) {
Dictionary dic = (Dictionary) obj;
for (Enumeration keyEnum = dic.keys(); keyEnum.hasMoreElements();) {
Object key = keyEnum.nextElement();
try {
newMap.put(convert(key, keyType), convert(dic.get(key), valueType));
} catch (Exception t) {
throw new Exception("Unable to convert from " + obj + " to " + type + "(error converting map entry)", t);
}
}
return newMap;
} else {
boolean converted = false;
for (Map.Entry e : ((Map<Object, Object>) obj).entrySet()) {
try {
Object nk = convert(e.getKey(), keyType);
Object nv = convert(e.getValue(), valueType);
converted |= nk != e.getKey() || nv != e.getValue();
newMap.put(nk, nv);
} catch (Exception t) {
throw new Exception("Unable to convert from " + obj + " to " + type + "(error converting map entry)", t);
}
}
return converted ? newMap : obj;
}
}
private Object convertToArray(Object obj, ReifiedType type) throws Exception {
if (obj instanceof Collection) {
obj = ((Collection) obj).toArray();
}
if (!obj.getClass().isArray()) {
throw new Exception("Unable to convert from " + obj + " to " + type);
}
ReifiedType componentType;
if (type.size() > 0) {
componentType = type.getActualTypeArgument(0);
} else {
componentType = new GenericType(type.getRawClass().getComponentType());
}
Object array = Array.newInstance(toClass(componentType), Array.getLength(obj));
boolean converted = array.getClass() != obj.getClass();
for (int i = 0; i < Array.getLength(obj); i++) {
try {
Object ov = Array.get(obj, i);
Object nv = convert(ov, componentType);
converted |= nv != ov;
Array.set(array, i, nv);
} catch (Exception t) {
throw new Exception("Unable to convert from " + obj + " to " + type + "(error converting array element)", t);
}
}
return converted ? array : obj;
}
public static boolean isAssignable(Object source, ReifiedType target) {
if (source == null) {
return true;
}
if (target.size() == 0) {
return unwrap(target.getRawClass()).isAssignableFrom(unwrap(source.getClass()));
} else {
return isTypeAssignable(getType(source), target);
}
}
private static ReifiedType getType(Object source) {
if (source instanceof Class) {
return new GenericType(Class.class, new GenericType((Class) source));
} else {
return new GenericType(source.getClass());
}
}
public static boolean isTypeAssignable(ReifiedType from, ReifiedType to) {
if (from.equals(to)) {
return true;
}
if (from.getRawClass() == to.getRawClass()) {
if (to.size() == 0) {
return true;
}
if (from.size() == to.size()) {
boolean ok = true;
for (int i = 0; i < from.size(); i++) {
ReifiedType tf = from.getActualTypeArgument(i);
ReifiedType tt = to.getActualTypeArgument(i);
if (!isWildcardCompatible(tf, tt)) {
ok = false;
break;
}
}
if (ok) {
return true;
}
}
} else {
ReifiedType t = getExactSuperType(from, to.getRawClass());
if (t != null) {
return isTypeAssignable(t, to);
}
}
return false;
}
private static ReifiedType getExactSuperType(ReifiedType from, Class<?> to) {
if (from.getRawClass() == to) {
return from;
}
if (!to.isAssignableFrom(from.getRawClass())) {
return null;
}
for (ReifiedType superType : getExactDirectSuperTypes(from)) {
ReifiedType result = getExactSuperType(superType, to);
if (result != null)
return result;
}
return null;
}
public static ReifiedType[] getExactDirectSuperTypes(ReifiedType type) {
Class<?> clazz = type.getRawClass();
Type[] superInterfaces = clazz.getGenericInterfaces();
Type superClass = clazz.getGenericSuperclass();
// the only supertype of an interface without superinterfaces is Object
if (superClass == null && superInterfaces.length == 0 && clazz.isInterface()) {
return new ReifiedType[] { new GenericType(Object.class) };
}
ReifiedType[] result;
int resultIndex;
if (superClass == null) {
result = new ReifiedType[superInterfaces.length];
resultIndex = 0;
} else {
result = new ReifiedType[superInterfaces.length + 1];
resultIndex = 1;
result[0] = mapTypeParameters(superClass, type);
}
for (Type superInterface : superInterfaces) {
result[resultIndex++] = mapTypeParameters(superInterface, type);
}
return result;
}
private static ReifiedType mapTypeParameters(Type toMapType, ReifiedType typeAndParams) {
if (typeAndParams.size() == 0 && typeAndParams.getRawClass().getTypeParameters().length > 0) {
// Missing generics information, return erased type
return new GenericType(new GenericType(toMapType).getRawClass());
}
if (toMapType instanceof Class) {
return new GenericType(toMapType);
}
Map<TypeVariable<?>, GenericType> map = new HashMap<TypeVariable<?>, GenericType>();
for (int i = 0; i < typeAndParams.size(); i++) {
map.put(typeAndParams.getRawClass().getTypeParameters()[i], (GenericType) typeAndParams.getActualTypeArgument(i));
}
return map(map, toMapType);
}
private static GenericType map(Map<TypeVariable<?>, GenericType> map, Type type) {
if (type instanceof Class) {
return new GenericType(type);
}
if (type instanceof TypeVariable) {
TypeVariable<?> tv = (TypeVariable<?>) type;
if (!map.containsKey(type)) {
throw new IllegalArgumentException("Unable to resolve TypeVariable: " + tv);
}
return map.get(type);
}
if (type instanceof ParameterizedType) {
ParameterizedType pType = (ParameterizedType) type;
GenericType[] args = new GenericType[pType.getActualTypeArguments().length];
for (int i = 0; i < args.length; i++) {
args[i] = map(map, pType.getActualTypeArguments()[i]);
}
return new GenericType((Class<?>) pType.getRawType(), args);
}
throw new RuntimeException("not implemented: mapping " + type.getClass() + " (" + type + ")");
}
private static boolean isWildcardCompatible(ReifiedType from, ReifiedType to) {
BoundType fromBoundType = GenericType.boundType(from);
BoundType toBoundType = GenericType.boundType(to);
if (toBoundType == BoundType.Extends) {
return fromBoundType != BoundType.Super && isTypeAssignable(from, GenericType.bound(to));
} else if (toBoundType == BoundType.Super) {
return fromBoundType != BoundType.Extends && isTypeAssignable(GenericType.bound(to), from);
} else {
return fromBoundType == BoundType.Exact && GenericType.bound(from).equals(GenericType.bound(to));
}
}
private static Class unwrap(Class c) {
Class u = primitives.get(c);
return u != null ? u : c;
}
private static final Map<Class, Class> primitives;
static {
primitives = new HashMap<Class, Class>();
primitives.put(byte.class, Byte.class);
primitives.put(short.class, Short.class);
primitives.put(char.class, Character.class);
primitives.put(int.class, Integer.class);
primitives.put(long.class, Long.class);
primitives.put(float.class, Float.class);
primitives.put(double.class, Double.class);
primitives.put(boolean.class, Boolean.class);
}
public Object convert(Object source, Type target) throws Exception {
return convert(source, new GenericType(target));
}
private Class toClass(ReifiedType type) {
return type.getRawClass();
}
} | 9,516 |
0 | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/container/BlueprintDomainCombiner.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.blueprint.container;
import java.security.AccessControlContext;
import java.security.AccessController;
import java.security.DomainCombiner;
import java.security.ProtectionDomain;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
public class BlueprintDomainCombiner implements DomainCombiner {
private final Bundle bundle;
public static AccessControlContext createAccessControlContext(Bundle bundle) {
return new AccessControlContext(AccessController.getContext(), new BlueprintDomainCombiner(bundle));
}
BlueprintDomainCombiner(Bundle bundle) {
this.bundle = bundle;
}
public ProtectionDomain[] combine(ProtectionDomain[] arg0,
ProtectionDomain[] arg1) {
return new ProtectionDomain[] { new BlueprintProtectionDomain(bundle) };
}
}
| 9,517 |
0 | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/container/QuiesceInterceptor.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.blueprint.container;
import java.lang.reflect.Method;
import org.apache.aries.blueprint.Interceptor;
import org.osgi.service.blueprint.reflect.ComponentMetadata;
public class QuiesceInterceptor implements Interceptor {
private ServiceRecipe serviceRecipe;
public QuiesceInterceptor(ServiceRecipe serviceRecipe) {
this.serviceRecipe = serviceRecipe;
}
public Object preCall(ComponentMetadata cm, Method m, Object... parameters) throws Throwable {
serviceRecipe.incrementActiveCalls();
return null;
}
public void postCallWithReturn(ComponentMetadata cm, Method m, Object returnType, Object preCallToken) throws Throwable {
serviceRecipe.decrementActiveCalls();
}
public void postCallWithException(ComponentMetadata cm, Method m, Throwable ex, Object preCallToken) throws Throwable {
serviceRecipe.decrementActiveCalls();
}
public int getRank() {
return 0;
}
}
| 9,518 |
0 | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/container/NamespaceHandlerRegistry.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.blueprint.container;
import java.net.URI;
import java.util.Set;
import javax.xml.validation.Schema;
import org.apache.aries.blueprint.parser.NamespaceHandlerSet;
import org.osgi.framework.Bundle;
/**
* Registry of NamespaceHandler.
*
* @version $Rev$, $Date$
*/
public interface NamespaceHandlerRegistry {
/**
* Retrieve the <code>NamespaceHandler</code> for the specified URI. Make sure
*
* @param uri the namespace identifying the namespace handler
* @param bundle the blueprint bundle to be checked for class space consistency
*
* @return a set of registered <code>NamespaceHandler</code>s compatible with the class space of the given bundle
*/
NamespaceHandlerSet getNamespaceHandlers(Set<URI> uri, Bundle bundle);
/**
* Destroy this registry
*/
void destroy();
}
| 9,519 |
0 | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/container/ReferenceRecipe.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.blueprint.container;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Callable;
import org.apache.aries.blueprint.ExtendedReferenceMetadata;
import org.apache.aries.blueprint.di.CollectionRecipe;
import org.apache.aries.blueprint.di.ExecutionContext;
import org.apache.aries.blueprint.di.Recipe;
import org.apache.aries.blueprint.di.ValueRecipe;
import org.apache.aries.blueprint.services.ExtendedBlueprintContainer;
import org.osgi.framework.ServiceReference;
import org.osgi.service.blueprint.container.BlueprintEvent;
import org.osgi.service.blueprint.container.ComponentDefinitionException;
import org.osgi.service.blueprint.container.ReifiedType;
import org.osgi.service.blueprint.container.ServiceUnavailableException;
import org.osgi.service.blueprint.reflect.ReferenceMetadata;
import org.osgi.service.blueprint.reflect.ServiceReferenceMetadata;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A recipe to create an unary OSGi service reference.
*
* TODO: check synchronization / thread safety
*
* TODO: looks there is a potential problem if the service is unregistered between a call
* to ServiceDispatcher#loadObject() and when the actual invocation finish
*
* @version $Rev$, $Date$
*/
@SuppressWarnings("rawtypes")
public class ReferenceRecipe extends AbstractServiceReferenceRecipe {
private static final Logger LOGGER = LoggerFactory.getLogger(ReferenceRecipe.class);
private final ReferenceMetadata metadata;
private Object proxy;
private final Object monitor = new Object();
private volatile ServiceReference trackedServiceReference;
private volatile Object trackedService;
private Object defaultBean;
private final Collection<Class<?>> proxyChildBeanClasses;
private final Collection<WeakReference<Voidable>> proxiedChildren;
private final boolean staticLifecycle;
public ReferenceRecipe(String name,
ExtendedBlueprintContainer blueprintContainer,
ReferenceMetadata metadata,
ValueRecipe filterRecipe,
CollectionRecipe listenersRecipe,
List<Recipe> explicitDependencies) {
super(name, blueprintContainer, metadata, filterRecipe, listenersRecipe, explicitDependencies);
this.metadata = metadata;
if (metadata instanceof ExtendedReferenceMetadata) {
staticLifecycle = ((ExtendedReferenceMetadata) metadata).getLifecycle()
== ExtendedReferenceMetadata.LIFECYCLE_STATIC;
if (!staticLifecycle) {
proxyChildBeanClasses = ((ExtendedReferenceMetadata) metadata).getProxyChildBeanClasses();
if (proxyChildBeanClasses != null) {
proxiedChildren = new ArrayList<WeakReference<Voidable>>();
} else {
proxiedChildren = null;
}
} else {
proxyChildBeanClasses = null;
proxiedChildren = null;
}
} else {
staticLifecycle = false;
proxyChildBeanClasses = null;
proxiedChildren = null;
}
}
@Override
protected Object internalCreate() throws ComponentDefinitionException {
try {
if (explicitDependencies != null) {
for (Recipe recipe : explicitDependencies) {
recipe.create();
}
}
// Create the proxy
Set<Class<?>> interfaces = new HashSet<Class<?>>();
Class<?> clz = getInterfaceClass();
if (clz != null) interfaces.add(clz);
if (metadata instanceof ExtendedReferenceMetadata) {
interfaces.addAll(loadAllClasses(((ExtendedReferenceMetadata) metadata).getExtraInterfaces()));
}
Object result;
if (isStaticLifecycle()) {
result = getService();
}
else {
proxy = createProxy(new ServiceDispatcher(), interfaces);
// Add partially created proxy to the context
result = new ServiceProxyWrapper();
}
addPartialObject(result);
// Handle initial references
createListeners();
updateListeners();
return result;
} catch (ComponentDefinitionException e) {
throw e;
} catch (Throwable t) {
throw new ComponentDefinitionException(t);
}
}
protected void doStop() {
synchronized (monitor) {
unbind();
monitor.notifyAll();
}
}
protected void retrack() {
ServiceReference ref = getBestServiceReference();
if (ref != null) {
bind(ref);
} else {
unbind();
}
}
protected void track(ServiceReference ref) {
boolean replace;
if (metadata instanceof ExtendedReferenceMetadata) {
replace = ((ExtendedReferenceMetadata) metadata).getDamping()
== ExtendedReferenceMetadata.DAMPING_GREEDY;
} else {
replace = false;
}
synchronized (monitor) {
if (trackedServiceReference == null || replace) {
retrack();
}
}
}
protected void untrack(ServiceReference ref) {
synchronized (monitor) {
if (trackedServiceReference == ref) {
retrack();
}
}
}
@Override
public boolean isStaticLifecycle() {
return staticLifecycle;
}
protected void bind(ServiceReference ref) {
LOGGER.debug("Binding reference {} to {}", getName(), ref);
synchronized (monitor) {
ServiceReference oldReference = trackedServiceReference;
trackedServiceReference = ref;
voidProxiedChildren();
bind(trackedServiceReference, proxy);
if (ref != oldReference) {
if (oldReference != null && trackedService != null) {
try {
blueprintContainer.getBundleContext().ungetService(oldReference);
} catch (IllegalStateException ise) {
// In case the service no longer exists lets just cope and ignore.
}
}
trackedService = null;
}
monitor.notifyAll();
}
}
private void unbind() {
LOGGER.debug("Unbinding reference {}", getName());
synchronized (monitor) {
if (trackedServiceReference != null) {
unbind(trackedServiceReference, proxy);
ServiceReference oldReference = trackedServiceReference;
trackedServiceReference = null;
voidProxiedChildren();
if (trackedService != null) {
try {
getBundleContextForServiceLookup().ungetService(oldReference);
} catch (IllegalStateException ise) {
// In case the service no longer exists lets just cope and ignore.
}
trackedService = null;
}
monitor.notifyAll();
}
}
}
private Object getService() throws InterruptedException {
synchronized (monitor) {
if (isStarted() && trackedServiceReference == null && metadata.getTimeout() > 0
&& metadata.getAvailability() == ServiceReferenceMetadata.AVAILABILITY_MANDATORY) {
//Here we want to get the blueprint bundle itself, so don't use #getBundleContextForServiceLookup()
blueprintContainer.getEventDispatcher().blueprintEvent(createWaitingevent());
monitor.wait(metadata.getTimeout());
}
Object result = null;
if (trackedServiceReference == null) {
if (isStarted()) {
boolean failed = true;
if (metadata.getAvailability() == ReferenceMetadata.AVAILABILITY_OPTIONAL &&
metadata instanceof ExtendedReferenceMetadata) {
if (defaultBean == null) {
String defaultBeanId = ((ExtendedReferenceMetadata) metadata).getDefaultBean();
if (defaultBeanId != null) {
defaultBean = blueprintContainer.getComponentInstance(defaultBeanId);
failed = false;
}
} else {
failed = false;
}
BlueprintRepository repository = ((BlueprintContainerImpl) blueprintContainer).getRepository();
ExecutionContext oldContext = null;
try {
oldContext = ExecutionContext.Holder.setContext(repository);
result = convert(defaultBean, new GenericType(getInterfaceClass()));
} catch (Exception e) {
throw new IllegalStateException("Wrong type for defaultBean", e);
} finally {
ExecutionContext.Holder.setContext(oldContext);
}
}
if (failed) {
if (metadata.getAvailability() == ServiceReferenceMetadata.AVAILABILITY_MANDATORY) {
LOGGER.info("Timeout expired when waiting for mandatory OSGi service reference {}", getOsgiFilter());
throw new ServiceUnavailableException("Timeout expired when waiting for mandatory OSGi service reference: " + getOsgiFilter(), getOsgiFilter());
} else {
LOGGER.info("No matching service for optional OSGi service reference {}", getOsgiFilter());
throw new ServiceUnavailableException("No matching service for optional OSGi service reference: " + getOsgiFilter(), getOsgiFilter());
}
}
} else {
throw new ServiceUnavailableException("The Blueprint container is being or has been destroyed: " + getOsgiFilter(), getOsgiFilter());
}
} else {
if (trackedService == null) {
trackedService = getServiceSecurely(trackedServiceReference);
}
if (trackedService == null) {
throw new IllegalStateException("getService() returned null for " + trackedServiceReference);
}
result = trackedService;
}
return result;
}
}
private BlueprintEvent createWaitingevent() {
return new BlueprintEvent(BlueprintEvent.WAITING,
blueprintContainer.getBundleContext().getBundle(),
blueprintContainer.getExtenderBundle(),
new String[]{getOsgiFilter()});
}
private ServiceReference getServiceReference() throws InterruptedException {
synchronized (monitor) {
if (!optional) {
getService();
}
return trackedServiceReference;
}
}
private void voidProxiedChildren() {
if (proxyChildBeanClasses != null) {
synchronized (proxiedChildren) {
for (Iterator<WeakReference<Voidable>> it = proxiedChildren.iterator(); it.hasNext(); ) {
Voidable v = it.next().get();
if (v == null)
it.remove();
else
v.voidReference();
}
}
}
}
public void addVoidableChild(Voidable v) {
if (proxyChildBeanClasses != null) {
synchronized (proxiedChildren) {
proxiedChildren.add(new WeakReference<Voidable>(v));
}
} else {
throw new IllegalStateException("Proxying of child beans is disabled for this recipe");
}
}
public Collection<Class<?>> getProxyChildBeanClasses() {
return proxyChildBeanClasses;
}
public class ServiceDispatcher implements Callable<Object> {
public Object call() throws Exception {
return getService();
}
}
public class ServiceProxyWrapper implements AggregateConverter.Convertible {
public Object convert(ReifiedType type) throws Exception {
if (type.getRawClass() == ServiceReference.class) {
return getServiceReference();
} else if (type.getRawClass().isInstance(proxy)) {
return proxy;
} else {
throw new ComponentDefinitionException("Unable to convert to " + type);
}
}
}
}
| 9,520 |
0 | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/container/ExecutorServiceWrapper.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.blueprint.container;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
public class ExecutorServiceWrapper extends AbstractExecutorService implements Runnable {
private final ExecutorService delegate;
private final ConcurrentLinkedQueue<Runnable> queue = new ConcurrentLinkedQueue<Runnable>();
private final AtomicBoolean triggered = new AtomicBoolean();
private final AtomicBoolean shutdown = new AtomicBoolean();
private Thread runningThread;
public ExecutorServiceWrapper(ExecutorService delegate) {
this.delegate = delegate;
}
public void shutdown() {
shutdown.set(true);
}
public List<Runnable> shutdownNow() {
List<Runnable> pending = new ArrayList<Runnable>();
if (shutdown.compareAndSet(false, true)) {
Runnable runnable;
while ((runnable = queue.poll()) != null) {
pending.add(runnable);
}
}
return pending;
}
public boolean isShutdown() {
return shutdown.get();
}
public boolean isTerminated() {
return delegate.isTerminated() || isShutdown() && queue.isEmpty() && !triggered.get();
}
public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
long millis = unit.toMillis(timeout);
if (millis > 0) {
long max = System.currentTimeMillis() + millis;
synchronized (triggered) {
while (System.currentTimeMillis() < max) {
if (isTerminated()) {
return true;
} else {
triggered.wait(millis);
}
}
}
}
return isTerminated();
}
public void execute(Runnable command) {
if (isShutdown()) {
throw new RejectedExecutionException("Executor has been shut down");
}
queue.add(command);
triggerExecution();
}
protected void triggerExecution() {
if (triggered.compareAndSet(false, true)) {
delegate.execute(this);
}
}
public void run() {
try {
Runnable runnable;
synchronized (triggered) {
runningThread = Thread.currentThread();
}
while (true) {
runnable = queue.poll();
if (runnable == null) {
return;
}
try {
runnable.run();
} catch (Throwable e) {
Thread thread = Thread.currentThread();
thread.getUncaughtExceptionHandler().uncaughtException(thread, e);
}
}
} finally {
synchronized (triggered) {
runningThread = null;
triggered.set(false);
triggered.notifyAll();
}
if (!isShutdown() && !queue.isEmpty()) {
triggerExecution();
}
}
}
}
| 9,521 |
0 | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/container/RecipeBuilder.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.blueprint.container;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import org.apache.aries.blueprint.ComponentDefinitionRegistry;
import org.apache.aries.blueprint.ExtendedBeanMetadata;
import org.apache.aries.blueprint.ExtendedReferenceMetadata;
import org.apache.aries.blueprint.ExtendedServiceReferenceMetadata;
import org.apache.aries.blueprint.utils.ServiceListener;
import org.apache.aries.blueprint.PassThroughMetadata;
import org.apache.aries.blueprint.di.ArrayRecipe;
import org.apache.aries.blueprint.di.CollectionRecipe;
import org.apache.aries.blueprint.di.ComponentFactoryRecipe;
import org.apache.aries.blueprint.di.DependentComponentFactoryRecipe;
import org.apache.aries.blueprint.di.IdRefRecipe;
import org.apache.aries.blueprint.di.MapRecipe;
import org.apache.aries.blueprint.di.PassThroughRecipe;
import org.apache.aries.blueprint.di.Recipe;
import org.apache.aries.blueprint.di.RefRecipe;
import org.apache.aries.blueprint.di.ValueRecipe;
import org.apache.aries.blueprint.ext.ComponentFactoryMetadata;
import org.apache.aries.blueprint.ext.DependentComponentFactoryMetadata;
import org.apache.aries.blueprint.mutable.MutableMapMetadata;
import org.apache.aries.blueprint.reflect.MetadataUtil;
import org.osgi.service.blueprint.reflect.BeanArgument;
import org.osgi.service.blueprint.reflect.BeanMetadata;
import org.osgi.service.blueprint.reflect.BeanProperty;
import org.osgi.service.blueprint.reflect.CollectionMetadata;
import org.osgi.service.blueprint.reflect.ComponentMetadata;
import org.osgi.service.blueprint.reflect.IdRefMetadata;
import org.osgi.service.blueprint.reflect.MapEntry;
import org.osgi.service.blueprint.reflect.MapMetadata;
import org.osgi.service.blueprint.reflect.Metadata;
import org.osgi.service.blueprint.reflect.NullMetadata;
import org.osgi.service.blueprint.reflect.PropsMetadata;
import org.osgi.service.blueprint.reflect.RefMetadata;
import org.osgi.service.blueprint.reflect.ReferenceListMetadata;
import org.osgi.service.blueprint.reflect.ReferenceListener;
import org.osgi.service.blueprint.reflect.ReferenceMetadata;
import org.osgi.service.blueprint.reflect.RegistrationListener;
import org.osgi.service.blueprint.reflect.ServiceMetadata;
import org.osgi.service.blueprint.reflect.ValueMetadata;
/**
* TODO: javadoc
*
* @version $Rev$, $Date$
*/
public class RecipeBuilder {
private final Set<String> names = new HashSet<String>();
private final BlueprintContainerImpl blueprintContainer;
private final ComponentDefinitionRegistry registry;
private final IdSpace recipeIdSpace;
public RecipeBuilder(BlueprintContainerImpl blueprintContainer, IdSpace recipeIdSpace) {
this.recipeIdSpace = recipeIdSpace;
this.blueprintContainer = blueprintContainer;
this.registry = blueprintContainer.getComponentDefinitionRegistry();
}
public BlueprintRepository createRepository() {
BlueprintRepository repository = new BlueprintRepository(blueprintContainer);
// Create component recipes
for (String name : registry.getComponentDefinitionNames()) {
ComponentMetadata component = registry.getComponentDefinition(name);
Recipe recipe = createRecipe(component);
repository.putRecipe(recipe.getName(), recipe);
}
repository.validate();
return repository;
}
public Recipe createRecipe(ComponentMetadata component) {
// Custom components should be handled before built-in ones
// in case we have a custom component that also implements a built-in metadata
if (component instanceof DependentComponentFactoryMetadata) {
return createDependentComponentFactoryMetadata((DependentComponentFactoryMetadata) component);
} else if (component instanceof ComponentFactoryMetadata) {
return createComponentFactoryMetadata((ComponentFactoryMetadata) component);
} else if (component instanceof BeanMetadata) {
return createBeanRecipe((BeanMetadata) component);
} else if (component instanceof ServiceMetadata) {
return createServiceRecipe((ServiceMetadata) component);
} else if (component instanceof ReferenceMetadata) {
return createReferenceRecipe((ReferenceMetadata) component);
} else if (component instanceof ReferenceListMetadata) {
return createReferenceListRecipe((ReferenceListMetadata) component);
} else if (component instanceof PassThroughMetadata) {
return createPassThroughRecipe((PassThroughMetadata) component);
} else {
throw new IllegalStateException("Unsupported component type " + component.getClass());
}
}
private Recipe createComponentFactoryMetadata(ComponentFactoryMetadata metadata) {
return new ComponentFactoryRecipe<ComponentFactoryMetadata>(
metadata.getId(), metadata, blueprintContainer, getDependencies(metadata));
}
private Recipe createDependentComponentFactoryMetadata(DependentComponentFactoryMetadata metadata) {
return new DependentComponentFactoryRecipe(
metadata.getId(), metadata, blueprintContainer, getDependencies(metadata));
}
private List<Recipe> getDependencies(ComponentMetadata metadata) {
List<Recipe> deps = new ArrayList<Recipe>();
for (String name : metadata.getDependsOn()) {
deps.add(new RefRecipe(getName(null), name));
}
return deps;
}
private Recipe createPassThroughRecipe(PassThroughMetadata passThroughMetadata) {
return new PassThroughRecipe(getName(passThroughMetadata.getId()),
passThroughMetadata.getObject());
}
private Recipe createReferenceListRecipe(ReferenceListMetadata metadata) {
ValueRecipe filterRecipe = null;
if (metadata instanceof ExtendedReferenceMetadata) {
ValueMetadata filterMetadata = ((ExtendedServiceReferenceMetadata) metadata).getExtendedFilter();
if (filterMetadata != null) {
filterRecipe = (ValueRecipe) getValue(filterMetadata, null);
}
}
CollectionRecipe listenersRecipe = null;
if (metadata.getReferenceListeners() != null) {
listenersRecipe = new CollectionRecipe(getName(null), ArrayList.class, Object.class.getName());
for (ReferenceListener listener : metadata.getReferenceListeners()) {
listenersRecipe.add(createRecipe(listener));
}
}
ReferenceListRecipe recipe = new ReferenceListRecipe(getName(metadata.getId()),
blueprintContainer,
metadata,
filterRecipe,
listenersRecipe,
getDependencies(metadata));
return recipe;
}
private ReferenceRecipe createReferenceRecipe(ReferenceMetadata metadata) {
ValueRecipe filterRecipe = null;
if (metadata instanceof ExtendedReferenceMetadata) {
ValueMetadata filterMetadata = ((ExtendedServiceReferenceMetadata) metadata).getExtendedFilter();
if (filterMetadata != null) {
filterRecipe = (ValueRecipe) getValue(filterMetadata, null);
}
}
CollectionRecipe listenersRecipe = null;
if (metadata.getReferenceListeners() != null) {
listenersRecipe = new CollectionRecipe(getName(null), ArrayList.class, Object.class.getName());
for (ReferenceListener listener : metadata.getReferenceListeners()) {
listenersRecipe.add(createRecipe(listener));
}
}
ReferenceRecipe recipe = new ReferenceRecipe(getName(metadata.getId()),
blueprintContainer,
metadata,
filterRecipe,
listenersRecipe,
getDependencies(metadata));
return recipe;
}
private Recipe createServiceRecipe(ServiceMetadata serviceExport) {
CollectionRecipe listenersRecipe = new CollectionRecipe(getName(null), ArrayList.class, Object.class.getName());
if (serviceExport.getRegistrationListeners() != null) {
for (RegistrationListener listener : serviceExport.getRegistrationListeners()) {
listenersRecipe.add(createRecipe(listener));
}
}
ServiceRecipe recipe = new ServiceRecipe(getName(serviceExport.getId()),
blueprintContainer,
serviceExport,
getValue(serviceExport.getServiceComponent(), null),
listenersRecipe,
getServicePropertiesRecipe(serviceExport),
getDependencies(serviceExport));
return recipe;
}
protected MapRecipe getServicePropertiesRecipe(ServiceMetadata metadata) {
List<MapEntry> properties = metadata.getServiceProperties();
if (properties != null) {
MutableMapMetadata map = MetadataUtil.createMetadata(MutableMapMetadata.class);
for (MapEntry e : properties) {
map.addEntry(e);
}
return createMapRecipe(map);
} else {
return null;
}
}
private Object getBeanClass(BeanMetadata beanMetadata) {
if (beanMetadata instanceof ExtendedBeanMetadata) {
ExtendedBeanMetadata extBeanMetadata = (ExtendedBeanMetadata) beanMetadata;
if (extBeanMetadata.getRuntimeClass() != null) {
return extBeanMetadata.getRuntimeClass();
}
}
return beanMetadata.getClassName();
}
private boolean allowFieldInjection(BeanMetadata beanMetadata) {
if (beanMetadata instanceof ExtendedBeanMetadata) {
return ((ExtendedBeanMetadata) beanMetadata).getFieldInjection();
}
return false;
}
private boolean allowRawConversion(BeanMetadata beanMetadata) {
if (beanMetadata instanceof ExtendedBeanMetadata) {
return ((ExtendedBeanMetadata) beanMetadata).getRawConversion();
}
return false;
}
private boolean allowNonStandardSetters(BeanMetadata beanMetadata) {
if (beanMetadata instanceof ExtendedBeanMetadata) {
return ((ExtendedBeanMetadata) beanMetadata).getNonStandardSetters();
}
return false;
}
private BeanRecipe createBeanRecipe(BeanMetadata beanMetadata) {
BeanRecipe recipe = new BeanRecipe(
getName(beanMetadata.getId()),
blueprintContainer,
getBeanClass(beanMetadata),
allowFieldInjection(beanMetadata),
allowRawConversion(beanMetadata),
allowNonStandardSetters(beanMetadata));
// Create refs for explicit dependencies
recipe.setExplicitDependencies(getDependencies(beanMetadata));
recipe.setPrototype(MetadataUtil.isPrototypeScope(beanMetadata) || MetadataUtil.isCustomScope(beanMetadata));
recipe.setInitMethod(beanMetadata.getInitMethod());
recipe.setDestroyMethod(beanMetadata.getDestroyMethod());
recipe.setInterceptorLookupKey(beanMetadata);
List<BeanArgument> beanArguments = beanMetadata.getArguments();
if (beanArguments != null && !beanArguments.isEmpty()) {
boolean hasIndex = (beanArguments.get(0).getIndex() >= 0);
if (hasIndex) {
List<BeanArgument> beanArgumentsCopy = new ArrayList<BeanArgument>(beanArguments);
Collections.sort(beanArgumentsCopy, MetadataUtil.BEAN_COMPARATOR);
beanArguments = beanArgumentsCopy;
}
List<Object> arguments = new ArrayList<Object>();
List<String> argTypes = new ArrayList<String>();
for (BeanArgument argument : beanArguments) {
Recipe value = getValue(argument.getValue(), null);
arguments.add(value);
argTypes.add(argument.getValueType());
}
recipe.setArguments(arguments);
recipe.setArgTypes(argTypes);
recipe.setReorderArguments(!hasIndex);
}
recipe.setFactoryMethod(beanMetadata.getFactoryMethod());
if (beanMetadata.getFactoryComponent() != null) {
recipe.setFactoryComponent(getValue(beanMetadata.getFactoryComponent(), null));
}
for (BeanProperty property : beanMetadata.getProperties()) {
Recipe value = getValue(property.getValue(), null);
recipe.setProperty(property.getName(), value);
}
return recipe;
}
private Recipe createRecipe(RegistrationListener listener) {
BeanRecipe recipe = new BeanRecipe(getName(null), blueprintContainer, ServiceListener.class, false, false, false);
recipe.setProperty("listener", getValue(listener.getListenerComponent(), null));
if (listener.getRegistrationMethod() != null) {
recipe.setProperty("registerMethod", listener.getRegistrationMethod());
}
if (listener.getUnregistrationMethod() != null) {
recipe.setProperty("unregisterMethod", listener.getUnregistrationMethod());
}
recipe.setProperty("blueprintContainer", blueprintContainer);
return recipe;
}
private Recipe createRecipe(ReferenceListener listener) {
BeanRecipe recipe = new BeanRecipe(getName(null), blueprintContainer, AbstractServiceReferenceRecipe.Listener.class, false, false, false);
recipe.setProperty("listener", getValue(listener.getListenerComponent(), null));
recipe.setProperty("metadata", listener);
recipe.setProperty("blueprintContainer", blueprintContainer);
return recipe;
}
private Recipe getValue(Metadata v, Object groupingType) {
if (v instanceof NullMetadata) {
return null;
} else if (v instanceof ComponentMetadata) {
return createRecipe((ComponentMetadata) v);
} else if (v instanceof ValueMetadata) {
ValueMetadata stringValue = (ValueMetadata) v;
Object type = stringValue.getType();
type = (type == null) ? groupingType : type;
ValueRecipe vr = new ValueRecipe(getName(null), stringValue, type);
return vr;
} else if (v instanceof RefMetadata) {
// TODO: make it work with property-placeholders?
String componentName = ((RefMetadata) v).getComponentId();
RefRecipe rr = new RefRecipe(getName(null), componentName);
return rr;
} else if (v instanceof CollectionMetadata) {
CollectionMetadata collectionMetadata = (CollectionMetadata) v;
Class<?> cl = collectionMetadata.getCollectionClass();
String type = collectionMetadata.getValueType();
if (cl == Object[].class) {
ArrayRecipe ar = new ArrayRecipe(getName(null), type);
for (Metadata lv : collectionMetadata.getValues()) {
ar.add(getValue(lv, type));
}
return ar;
} else {
CollectionRecipe cr = new CollectionRecipe(getName(null), cl != null ? cl : ArrayList.class, type);
for (Metadata lv : collectionMetadata.getValues()) {
cr.add(getValue(lv, type));
}
return cr;
}
} else if (v instanceof MapMetadata) {
return createMapRecipe((MapMetadata) v);
} else if (v instanceof PropsMetadata) {
PropsMetadata mapValue = (PropsMetadata) v;
MapRecipe mr = new MapRecipe(getName(null), Properties.class, String.class, String.class);
for (MapEntry entry : mapValue.getEntries()) {
Recipe key = getValue(entry.getKey(), String.class);
Recipe val = getValue(entry.getValue(), String.class);
mr.put(key, val);
}
return mr;
} else if (v instanceof IdRefMetadata) {
// TODO: make it work with property-placeholders?
String componentName = ((IdRefMetadata) v).getComponentId();
IdRefRecipe rnr = new IdRefRecipe(getName(null), componentName);
return rnr;
} else {
throw new IllegalStateException("Unsupported value: " + (v != null ? v.getClass().getName() : "null"));
}
}
private MapRecipe createMapRecipe(MapMetadata mapValue) {
String keyType = mapValue.getKeyType();
String valueType = mapValue.getValueType();
MapRecipe mr = new MapRecipe(getName(null), HashMap.class, keyType, valueType);
for (MapEntry entry : mapValue.getEntries()) {
Recipe key = getValue(entry.getKey(), keyType);
Recipe val = getValue(entry.getValue(), valueType);
mr.put(key, val);
}
return mr;
}
private String getName(String name) {
if (name == null) {
do {
name = "#recipe-" + recipeIdSpace.nextId();
} while (names.contains(name) || registry.containsComponentDefinition(name));
}
names.add(name);
return name;
}
}
| 9,522 |
0 | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/container/BeanRecipe.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.blueprint.container;
import java.lang.reflect.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.aries.blueprint.BeanProcessor;
import org.apache.aries.blueprint.ComponentDefinitionRegistry;
import org.apache.aries.blueprint.Interceptor;
import org.apache.aries.blueprint.di.AbstractRecipe;
import org.apache.aries.blueprint.di.Recipe;
import org.apache.aries.blueprint.proxy.CollaboratorFactory;
import org.apache.aries.blueprint.proxy.ProxyUtils;
import org.apache.aries.blueprint.services.ExtendedBlueprintContainer;
import org.apache.aries.blueprint.utils.ReflectionUtils;
import org.apache.aries.blueprint.utils.ReflectionUtils.PropertyDescriptor;
import org.apache.aries.blueprint.utils.generics.OwbParametrizedTypeImpl;
import org.apache.aries.blueprint.utils.generics.TypeInference;
import org.apache.aries.proxy.UnableToProxyException;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.FrameworkUtil;
import org.osgi.service.blueprint.container.ComponentDefinitionException;
import org.osgi.service.blueprint.container.ReifiedType;
import org.osgi.service.blueprint.reflect.BeanMetadata;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.apache.aries.blueprint.utils.ReflectionUtils.getRealCause;
/**
* A <code>Recipe</code> to create POJOs.
*
* @version $Rev$, $Date$
*/
@SuppressWarnings("rawtypes")
public class BeanRecipe extends AbstractRecipe {
static class UnwrapperedBeanHolder {
final Object unwrapperedBean;
final BeanRecipe recipe;
public UnwrapperedBeanHolder(Object unwrapperedBean, BeanRecipe recipe) {
this.unwrapperedBean = unwrapperedBean;
this.recipe = recipe;
}
}
public class VoidableCallable implements Callable<Object>, Voidable {
private final AtomicReference<Object> ref = new AtomicReference<Object>();
private final Semaphore sem = new Semaphore(1);
private final ThreadLocal<Object> deadlockDetector = new ThreadLocal<Object>();
public void voidReference() {
ref.set(null);
}
public Object call() throws ComponentDefinitionException {
Object o = ref.get();
if (o == null) {
if(deadlockDetector.get() != null) {
deadlockDetector.remove();
throw new ComponentDefinitionException("Construction cycle detected for bean " + name);
}
sem.acquireUninterruptibly();
try {
o = ref.get();
if (o == null) {
deadlockDetector.set(this);
try {
o = internalCreate2();
ref.set(o);
} finally {
deadlockDetector.remove();
}
}
} finally {
sem.release();
}
}
return o;
}
}
private static final Logger LOGGER = LoggerFactory.getLogger(BeanRecipe.class);
private final ExtendedBlueprintContainer blueprintContainer;
private final LinkedHashMap<String,Object> properties = new LinkedHashMap<String,Object>();
private final Object type;
private String initMethod;
private String destroyMethod;
private List<Recipe> explicitDependencies;
private Recipe factory;
private String factoryMethod;
private List<Object> arguments;
private List<String> argTypes;
private boolean reorderArguments;
private final boolean allowFieldInjection;
private final boolean allowRawConversion;
private final boolean allowNonStandardSetters;
private BeanMetadata interceptorLookupKey;
public BeanRecipe(String name, ExtendedBlueprintContainer blueprintContainer, Object type, boolean allowFieldInjection, boolean allowRawConversion, boolean allowNonStandardSetters) {
super(name);
this.blueprintContainer = blueprintContainer;
this.type = type;
this.allowFieldInjection = allowFieldInjection;
this.allowRawConversion = allowRawConversion;
this.allowNonStandardSetters = allowNonStandardSetters;
}
public Object getProperty(String name) {
return properties.get(name);
}
public Map<String, Object> getProperties() {
return new LinkedHashMap<String, Object>(properties);
}
public void setProperty(String name, Object value) {
properties.put(name, value);
}
public void setFactoryMethod(String method) {
this.factoryMethod = method;
}
public void setFactoryComponent(Recipe factory) {
this.factory = factory;
}
public void setArgTypes(List<String> argTypes) {
this.argTypes = argTypes;
}
public void setArguments(List<Object> arguments) {
this.arguments = arguments;
}
public void setReorderArguments(boolean reorder) {
this.reorderArguments = reorder;
}
public void setInitMethod(String initMethod) {
this.initMethod = initMethod;
}
public String getInitMethod() {
return initMethod;
}
public void setDestroyMethod(String destroyMethod) {
this.destroyMethod = destroyMethod;
}
public String getDestroyMethod() {
return destroyMethod;
}
public List<Recipe> getExplicitDependencies() {
return explicitDependencies;
}
public void setExplicitDependencies(List<Recipe> explicitDependencies) {
this.explicitDependencies = explicitDependencies;
}
public void setInterceptorLookupKey(BeanMetadata metadata) {
interceptorLookupKey = metadata;
}
@Override
public List<Recipe> getConstructorDependencies() {
List<Recipe> recipes = new ArrayList<Recipe>();
if (explicitDependencies != null) {
recipes.addAll(explicitDependencies);
}
if (arguments != null) {
for (Object argument : arguments) {
if (argument instanceof Recipe) {
recipes.add((Recipe)argument);
}
}
}
return recipes;
}
public List<Recipe> getDependencies() {
List<Recipe> recipes = new ArrayList<Recipe>();
for (Object o : properties.values()) {
if (o instanceof Recipe) {
Recipe recipe = (Recipe) o;
recipes.add(recipe);
}
}
if (factory != null) {
recipes.add(factory);
}
recipes.addAll(getConstructorDependencies());
return recipes;
}
private void instantiateExplicitDependencies() {
if (explicitDependencies != null) {
for (Recipe recipe : explicitDependencies) {
recipe.create();
}
}
}
@Override
protected Class loadClass(String className) {
ClassLoader loader = type instanceof Class ? ((Class) type).getClassLoader() : null;
ReifiedType t = loadType(className, loader);
return t != null ? t.getRawClass() : null;
}
@Override
protected ReifiedType loadType(String className) {
return loadType(className, type instanceof Class ? ((Class) type).getClassLoader() : null);
}
private Object getInstance() throws ComponentDefinitionException {
// Instanciate arguments
List<Object> args = new ArrayList<Object>();
List<ReifiedType> argTypes = new ArrayList<ReifiedType>();
if (arguments != null) {
for (int i = 0; i < arguments.size(); i++) {
Object arg = arguments.get(i);
if (arg instanceof Recipe) {
args.add(((Recipe) arg).create());
} else {
args.add(arg);
}
if (this.argTypes != null) {
argTypes.add(this.argTypes.get(i) != null ? loadType(this.argTypes.get(i)) : null);
}
}
}
if (factory != null) {
return getInstanceFromFactory(args, argTypes);
} else if (factoryMethod != null) {
return getInstanceFromStaticFactory(args, argTypes);
} else {
return getInstanceFromType(args, argTypes);
}
}
private Object getInstanceFromFactory(List<Object> args, List<ReifiedType> argTypes) {
Object factoryObj = getFactoryObj();
// Map of matching methods
Map<Method, List<Object>> matches = findMatchingMethods(factoryObj.getClass(), factoryMethod, true, args, argTypes);
if (matches.size() == 1) {
try {
Map.Entry<Method, List<Object>> match = matches.entrySet().iterator().next();
return invoke(match.getKey(), factoryObj, match.getValue().toArray());
} catch (Throwable e) {
throw wrapAsCompDefEx(e);
}
} else if (matches.size() == 0) {
throw new ComponentDefinitionException("Unable to find a matching factory method " + factoryMethod + " on class " + factoryObj.getClass().getName() + " for arguments " + argsToString(args) + " when instanciating bean " + getName());
} else {
throw new ComponentDefinitionException("Multiple matching factory methods " + factoryMethod + " found on class " + factoryObj.getClass().getName() + " for arguments " + argsToString(args) + " when instanciating bean " + getName() + ": " + matches.keySet());
}
}
private Object getFactoryObj() {
// look for instance method on factory object
Object factoryObj = factory.create();
// If the factory is a service reference, we need to get hold of the actual proxy for the service
if (factoryObj instanceof ReferenceRecipe.ServiceProxyWrapper) {
try {
factoryObj = ((ReferenceRecipe.ServiceProxyWrapper) factoryObj).convert(new ReifiedType(Object.class));
} catch (Exception e) {
throw wrapAsCompDefEx(e);
}
} else if (factoryObj instanceof UnwrapperedBeanHolder) {
factoryObj = wrap((UnwrapperedBeanHolder) factoryObj, Object.class);
}
return factoryObj;
}
private Object getInstanceFromStaticFactory(List<Object> args, List<ReifiedType> argTypes) {
// Map of matching methods
Map<Method, List<Object>> matches = findMatchingMethods(getType(), factoryMethod, false, args, argTypes);
if (matches.size() == 1) {
try {
Map.Entry<Method, List<Object>> match = matches.entrySet().iterator().next();
return invoke(match.getKey(), null, match.getValue().toArray());
} catch (Throwable e) {
throw wrapAsCompDefEx(e);
}
} else if (matches.size() == 0) {
throw new ComponentDefinitionException("Unable to find a matching factory method " + factoryMethod + " on class " + getTypeName() + " for arguments " + argsToString(args) + " when instanciating bean " + getName());
} else {
throw new ComponentDefinitionException("Multiple matching factory methods " + factoryMethod + " found on class " + getTypeName() + " for arguments " + argsToString(args) + " when instanciating bean " + getName() + ": " + matches.keySet());
}
}
private Object getInstanceFromType(List<Object> args, List<ReifiedType> argTypes) {
if (getType() == null) {
throw new ComponentDefinitionException("No factoryMethod nor class is defined for this bean");
}
// Map of matching constructors
Map<Constructor<?>, List<Object>> matches = findMatchingConstructors(getType(), args, argTypes);
if (matches.size() == 1) {
try {
Map.Entry<Constructor<?>, List<Object>> match = matches.entrySet().iterator().next();
return newInstance(match.getKey(), match.getValue().toArray());
} catch (Throwable e) {
throw wrapAsCompDefEx(e);
}
} else if (matches.size() == 0) {
throw new ComponentDefinitionException("Unable to find a matching constructor on class " + getTypeName() + " for arguments " + argsToString(args) + " when instanciating bean " + getName());
} else {
throw new ComponentDefinitionException("Multiple matching constructors found on class " + getTypeName() + " for arguments " + argsToString(args) + " when instanciating bean " + getName() + ": " + matches.keySet());
}
}
private ComponentDefinitionException wrapAsCompDefEx(Throwable e) {
return new ComponentDefinitionException("Error when instantiating bean " + getName() + " of class " + getTypeName(), getRealCause(e));
}
private String getTypeName() {
Class<?> type = getType();
return type == null ? null : type.getName();
}
private Map<Constructor<?>, List<Object>> findMatchingConstructors(Class type, List<Object> args, List<ReifiedType> types) {
List<TypeInference.TypedObject> targs = getTypedObjects(args, types);
TypeInference.Converter cnv = new TIConverter();
List<TypeInference.Match<Constructor<?>>> m = TypeInference.findMatchingConstructors(type, targs, cnv, reorderArguments);
if (!m.isEmpty()) {
int score = m.iterator().next().getScore();
final Iterator<TypeInference.Match<Constructor<?>>> each = m.iterator();
while (each.hasNext()) {
if (each.next().getScore() > score) {
each.remove();
}
}
}
Map<Constructor<?>, List<Object>> map = new HashMap<Constructor<?>, List<Object>>();
for (TypeInference.Match<Constructor<?>> match : m) {
List<Object> nargs = new ArrayList<Object>();
for (TypeInference.TypedObject to : match.getArgs()) {
nargs.add(to.getValue());
}
map.put(match.getMember(), nargs);
}
return map;
}
private Map<Method, List<Object>> findMatchingMethods(Class type, String name, boolean instance, List<Object> args, List<ReifiedType> types) {
List<TypeInference.TypedObject> targs = getTypedObjects(args, types);
TypeInference.Converter cnv = new TIConverter();
List<TypeInference.Match<Method>> m;
if (instance) {
m = TypeInference.findMatchingMethods(type, name, targs, cnv, reorderArguments);
} else {
m = TypeInference.findMatchingStatics(type, name, targs, cnv, reorderArguments);
}
if (!m.isEmpty()) {
int score = m.iterator().next().getScore();
final Iterator<TypeInference.Match<Method>> each = m.iterator();
while (each.hasNext()) {
if (each.next().getScore() > score) {
each.remove();
}
}
}
Map<Method, List<Object>> map = new HashMap<Method, List<Object>>();
for (TypeInference.Match<Method> match : m) {
List<Object> nargs = new ArrayList<Object>();
for (TypeInference.TypedObject to : match.getArgs()) {
nargs.add(to.getValue());
}
map.put(match.getMember(), nargs);
}
return map;
}
protected Object convert(Object obj, Type from, Type to) throws Exception {
if (allowRawConversion
&& (from instanceof ParameterizedType || to instanceof ParameterizedType)
&& GenericType.getConcreteClass(from) == GenericType.getConcreteClass(to)) {
boolean assignable = true;
if (from instanceof ParameterizedType) {
for (Type t : ((ParameterizedType) from).getActualTypeArguments()) {
assignable &= t == Object.class;
}
}
if (to instanceof ParameterizedType) {
for (Type t : ((ParameterizedType) to).getActualTypeArguments()) {
assignable &= t == Object.class;
}
}
if (assignable) {
return obj instanceof UnwrapperedBeanHolder
? ((UnwrapperedBeanHolder) obj).unwrapperedBean : obj;
}
}
return convert(obj, to);
}
private class TIConverter implements TypeInference.Converter {
public TypeInference.TypedObject convert(TypeInference.TypedObject from, Type to) throws Exception {
Object arg = BeanRecipe.this.convert(from.getValue(), from.getType(), to);
return new TypeInference.TypedObject(to, arg);
}
}
private Type toType(ReifiedType rt) {
if (rt.size() > 0) {
Type[] at = new Type[rt.size()];
for (int j = 0; j < at.length; j++) {
at[j] = toType(rt.getActualTypeArgument(j));
}
return new OwbParametrizedTypeImpl(null, rt.getRawClass(), at);
} else {
return rt.getRawClass();
}
}
private List<TypeInference.TypedObject> getTypedObjects(List<Object> args, List<ReifiedType> types) {
List<TypeInference.TypedObject> targs = new ArrayList<TypeInference.TypedObject>();
for (int i = 0; i < args.size(); i++) {
Type t;
Object o = args.get(i);
ReifiedType rt = types.get(i);
if (rt == null && o != null) {
Object ot = o instanceof UnwrapperedBeanHolder ? ((UnwrapperedBeanHolder) o).unwrapperedBean : o;
rt = new GenericType(ot.getClass());
}
if (rt != null) {
if (rt.size() == 0 && rt.getRawClass().getTypeParameters().length > 0 && rt.getRawClass() != Class.class) {
GenericType[] tt = new GenericType[rt.getRawClass().getTypeParameters().length];
Arrays.fill(tt, 0, tt.length, new GenericType(Object.class));
rt = new GenericType(rt.getRawClass(), tt);
}
t = toType(rt);
} else {
t = null;
}
targs.add(new TypeInference.TypedObject(t, o));
}
return targs;
}
/**
* Returns init method (if any). Throws exception if the init-method was set explicitly on the bean
* and the method is not found on the instance.
*/
protected Method getInitMethod(Object instance) throws ComponentDefinitionException {
Method method = null;
if (initMethod != null && initMethod.length() > 0) {
method = ReflectionUtils.getLifecycleMethod(instance.getClass(), initMethod);
if (method == null) {
throw new ComponentDefinitionException("Component '" + getName() + "' does not have init-method: " + initMethod);
}
}
return method;
}
/**
* Returns destroy method (if any). Throws exception if the destroy-method was set explicitly on the bean
* and the method is not found on the instance.
*/
public Method getDestroyMethod(Object instance) throws ComponentDefinitionException {
Method method = null;
if (instance != null && destroyMethod != null && destroyMethod.length() > 0) {
method = ReflectionUtils.getLifecycleMethod(instance.getClass(), destroyMethod);
if (method == null) {
throw new ComponentDefinitionException("Component '" + getName() + "' does not have destroy-method: " + destroyMethod);
}
}
return method;
}
/**
* Small helper class, to construct a chain of BeanCreators.
* <br>
* Each bean creator in the chain will return a bean that has been
* processed by every BeanProcessor in the chain before it.
*/
private static class BeanCreatorChain implements BeanProcessor.BeanCreator {
public enum ChainType{Before,After};
private final BeanProcessor.BeanCreator parentBeanCreator;
private final BeanProcessor parentBeanProcessor;
private final BeanMetadata beanData;
private final String beanName;
private final ChainType when;
public BeanCreatorChain(BeanProcessor.BeanCreator parentBeanCreator,
BeanProcessor parentBeanProcessor,
BeanMetadata beanData,
String beanName,
ChainType when) {
this.parentBeanCreator = parentBeanCreator;
this.parentBeanProcessor = parentBeanProcessor;
this.beanData = beanData;
this.beanName = beanName;
this.when = when;
}
public Object getBean() {
Object previousBean = parentBeanCreator.getBean();
Object processed = null;
switch (when) {
case Before:
processed = parentBeanProcessor.beforeInit(previousBean, beanName, parentBeanCreator, beanData);
break;
case After:
processed = parentBeanProcessor.afterInit(previousBean, beanName, parentBeanCreator, beanData);
break;
}
return processed;
}
}
private Object runBeanProcPreInit(Object obj) {
String beanName = getName();
BeanMetadata beanData = (BeanMetadata) blueprintContainer
.getComponentDefinitionRegistry().getComponentDefinition(beanName);
List<BeanProcessor> processors = blueprintContainer.getProcessors(BeanProcessor.class);
//The start link of the chain, that provides the
//original, unprocessed bean to the head of the chain.
BeanProcessor.BeanCreator initialBeanCreator = new BeanProcessor.BeanCreator() {
public Object getBean() {
Object obj = getInstance();
//getinit, getdestroy, addpartial object don't need calling again.
//however, property injection does.
setProperties(obj);
return obj;
}
};
BeanProcessor.BeanCreator currentCreator = initialBeanCreator;
for (BeanProcessor processor : processors) {
obj = processor.beforeInit(obj, getName(), currentCreator, beanData);
currentCreator = new BeanCreatorChain(currentCreator, processor, beanData, beanName, BeanCreatorChain.ChainType.Before);
}
return obj;
}
private void runBeanProcInit(Method initMethod, Object obj){
// call init method
if (initMethod != null) {
try {
invoke(initMethod, obj, (Object[]) null);
} catch (Throwable t) {
throw new ComponentDefinitionException("Unable to initialize bean " + getName(), getRealCause(t));
}
}
}
private Object runBeanProcPostInit(Object obj) {
String beanName = getName();
BeanMetadata beanData = (BeanMetadata) blueprintContainer
.getComponentDefinitionRegistry().getComponentDefinition(beanName);
List<BeanProcessor> processors = blueprintContainer.getProcessors(BeanProcessor.class);
//The start link of the chain, that provides the
//original, unprocessed bean to the head of the chain.
BeanProcessor.BeanCreator initialBeanCreator = new BeanProcessor.BeanCreator() {
public Object getBean() {
Object obj = getInstance();
//getinit, getdestroy, addpartial object don't need calling again.
//however, property injection does.
setProperties(obj);
//as this is the post init chain, new beans need to go thru
//the pre-init chain, and then have init called, before
//being passed along the post-init chain.
obj = runBeanProcPreInit(obj);
runBeanProcInit(getInitMethod(obj), obj);
return obj;
}
};
BeanProcessor.BeanCreator currentCreator = initialBeanCreator;
for (BeanProcessor processor : processors) {
obj = processor.afterInit(obj, getName(), currentCreator, beanData);
currentCreator = new BeanCreatorChain(currentCreator, processor, beanData, beanName, BeanCreatorChain.ChainType.After);
}
return obj;
}
private Object addInterceptors(final Object original, Collection<Class<?>> requiredInterfaces)
throws ComponentDefinitionException {
Object intercepted = null;
if (requiredInterfaces.isEmpty())
requiredInterfaces.add(original.getClass());
ComponentDefinitionRegistry reg = blueprintContainer
.getComponentDefinitionRegistry();
List<Interceptor> interceptors = reg.getInterceptors(interceptorLookupKey);
if (interceptors != null && interceptors.size() > 0) {
try {
Bundle b = FrameworkUtil.getBundle(original.getClass());
if (b == null) {
// we have a class from the framework parent, so use our bundle for proxying.
b = blueprintContainer.getBundleContext().getBundle();
}
intercepted = blueprintContainer.getProxyManager().createInterceptingProxy(b,
requiredInterfaces, original, CollaboratorFactory.create(interceptorLookupKey, interceptors));
} catch (org.apache.aries.proxy.UnableToProxyException e) {
Bundle b = blueprintContainer.getBundleContext().getBundle();
throw new ComponentDefinitionException("Unable to create proxy for bean " + name + " in bundle " + b.getSymbolicName() + "/" + b.getVersion(), e);
}
} else {
intercepted = original;
}
return intercepted;
}
@Override
protected Object internalCreate() throws ComponentDefinitionException {
if (factory instanceof ReferenceRecipe) {
ReferenceRecipe rr = (ReferenceRecipe) factory;
if (rr.getProxyChildBeanClasses() != null) {
return createProxyBean(rr);
}
}
return new UnwrapperedBeanHolder(internalCreate2(), this);
}
private Object createProxyBean(ReferenceRecipe rr) {
try {
VoidableCallable vc = new VoidableCallable();
rr.addVoidableChild(vc);
return blueprintContainer.getProxyManager().createDelegatingProxy(
blueprintContainer.getBundleContext().getBundle(), rr.getProxyChildBeanClasses(),
vc, vc.call());
} catch (UnableToProxyException e) {
throw new ComponentDefinitionException(e);
}
}
private Object internalCreate2() throws ComponentDefinitionException {
instantiateExplicitDependencies();
Object obj = getInstance();
// check for init lifecycle method (if any)
Method initMethod = getInitMethod(obj);
// check for destroy lifecycle method (if any)
getDestroyMethod(obj);
// Add partially created object to the container
// if (initMethod == null) {
addPartialObject(obj);
// }
// inject properties
setProperties(obj);
obj = runBeanProcPreInit(obj);
runBeanProcInit(initMethod, obj);
obj = runBeanProcPostInit(obj);
//Replaced by calling wrap on the UnwrapperedBeanHolder
// obj = addInterceptors(obj);
return obj;
}
static Object wrap(UnwrapperedBeanHolder holder, Collection<Class<?>> requiredViews) {
return holder.recipe.addInterceptors(holder.unwrapperedBean, requiredViews);
}
static Object wrap(UnwrapperedBeanHolder holder, Class<?> requiredView) {
if (requiredView == Object.class) {
//We don't know what we need so we have to do everything
return holder.recipe.addInterceptors(holder.unwrapperedBean, new ArrayList<Class<?>>(1));
} else {
return holder.recipe.addInterceptors(holder.unwrapperedBean, ProxyUtils.asList(requiredView));
}
}
@Override
public void destroy(Object obj) {
if (!(obj instanceof UnwrapperedBeanHolder)) {
LOGGER.warn("Object to be destroyed is not an instance of UnwrapperedBeanHolder, type: " + obj);
return;
}
obj = ((UnwrapperedBeanHolder) obj).unwrapperedBean;
for (BeanProcessor processor : blueprintContainer.getProcessors(BeanProcessor.class)) {
processor.beforeDestroy(obj, getName());
}
try {
Method method = getDestroyMethod(obj);
if (method != null) {
invoke(method, obj, (Object[]) null);
}
} catch (ComponentDefinitionException e) {
// This exception occurs if the destroy method does not exist, so we just output the exception message.
LOGGER.error(e.getMessage());
} catch (InvocationTargetException ite) {
Throwable t = ite.getTargetException();
BundleContext ctx = blueprintContainer.getBundleContext();
Bundle b = ctx.getBundle();
LOGGER.error("The blueprint bean {} in bundle {}/{} incorrectly threw an exception from its destroy method.", getName(), b.getSymbolicName(), b.getVersion(), t);
} catch (Exception e) {
BundleContext ctx = blueprintContainer.getBundleContext();
Bundle b = ctx.getBundle();
LOGGER.error("An exception occurred while calling the destroy method of the blueprint bean in bundle {}/{}.", getName(), b.getSymbolicName(), b.getVersion(), getRealCause(e));
}
for (BeanProcessor processor : blueprintContainer.getProcessors(BeanProcessor.class)) {
processor.afterDestroy(obj, getName());
}
}
public void setProperties(Object instance) throws ComponentDefinitionException {
// clone the properties so they can be used again
Map<String, Object> propertyValues = new LinkedHashMap<String, Object>(properties);
setProperties(propertyValues, instance, instance.getClass());
}
public Class getType() {
if (type instanceof Class) {
return (Class) type;
} else if (type instanceof String) {
return loadClass((String) type);
} else {
return null;
}
}
private void setProperties(Map<String, Object> propertyValues, Object instance, Class clazz) {
// set remaining properties
for (Map.Entry<String, Object> entry : propertyValues.entrySet()) {
String propertyName = entry.getKey();
Object propertyValue = entry.getValue();
setProperty(instance, clazz, propertyName, propertyValue);
}
}
private void setProperty(Object instance, Class clazz, String propertyName, Object propertyValue) {
String[] names = propertyName.split("\\.");
for (int i = 0; i < names.length - 1; i++) {
PropertyDescriptor pd = getPropertyDescriptor(clazz, names[i]);
if (pd.allowsGet()) {
try {
instance = pd.get(instance, blueprintContainer);
} catch (Exception e) {
throw new ComponentDefinitionException("Error getting property: " + names[i] + " on bean " + getName() + " when setting property " + propertyName + " on class " + clazz.getName(), getRealCause(e));
}
if (instance == null) {
throw new ComponentDefinitionException("Error setting compound property " + propertyName + " on bean " + getName() + ". Property " + names[i] + " is null");
}
clazz = instance.getClass();
} else {
throw new ComponentDefinitionException("No getter for " + names[i] + " property on bean " + getName() + " when setting property " + propertyName + " on class " + clazz.getName());
}
}
// Instantiate value
if (propertyValue instanceof Recipe) {
propertyValue = ((Recipe) propertyValue).create();
}
final PropertyDescriptor pd = getPropertyDescriptor(clazz, names[names.length - 1]);
if (pd.allowsSet()) {
try {
pd.set(instance, propertyValue, blueprintContainer);
} catch (Exception e) {
throw new ComponentDefinitionException("Error setting property: " + pd, getRealCause(e));
}
} else {
throw new ComponentDefinitionException("No setter for " + names[names.length - 1] + " property");
}
}
private ReflectionUtils.PropertyDescriptor getPropertyDescriptor(Class<?> clazz, String name) {
for (ReflectionUtils.PropertyDescriptor pd : ReflectionUtils.getPropertyDescriptors(clazz, allowFieldInjection, allowNonStandardSetters)) {
if (pd.getName().equals(name)) {
return pd;
}
}
throw new ComponentDefinitionException("Unable to find property descriptor " + name + " on class " + clazz.getName());
}
private Object invoke(Method method, Object instance, Object... args) throws Exception {
return ReflectionUtils.invoke(blueprintContainer.getAccessControlContext(), method, instance, args);
}
private Object newInstance(Constructor constructor, Object... args) throws Exception {
return ReflectionUtils.newInstance(blueprintContainer.getAccessControlContext(), constructor, args);
}
private String argsToString(List<Object> args) {
Iterator<Object> it = args.iterator();
if (!it.hasNext())
return "[]";
StringBuilder sb = new StringBuilder();
sb.append('[');
for (;;) {
Object e = it.next();
if (e instanceof UnwrapperedBeanHolder) {
e = ((UnwrapperedBeanHolder) e).unwrapperedBean;
}
sb.append(e).append(" (").append(e.getClass()).append(")");
if (!it.hasNext())
return sb.append(']').toString();
sb.append(',').append(' ');
}
}
private static Object UNMATCHED = new Object();
private class ArgumentMatcher {
private final List<TypeEntry> entries;
private final boolean convert;
public ArgumentMatcher(Type[] types, boolean convert) {
entries = new ArrayList<TypeEntry>();
for (Type type : types) {
entries.add(new TypeEntry(new GenericType(type)));
}
this.convert = convert;
}
public List<Object> match(List<Object> arguments, List<ReifiedType> forcedTypes) {
if (find(arguments, forcedTypes)) {
return getArguments();
}
return null;
}
private List<Object> getArguments() {
List<Object> list = new ArrayList<Object>();
for (TypeEntry entry : entries) {
if (entry.argument == UNMATCHED) {
throw new RuntimeException("There are unmatched generics");
} else {
list.add(entry.argument);
}
}
return list;
}
private boolean find(List<Object> arguments, List<ReifiedType> forcedTypes) {
if (entries.size() == arguments.size()) {
boolean matched = true;
for (int i = 0; i < arguments.size() && matched; i++) {
matched = find(arguments.get(i), forcedTypes.get(i));
}
return matched;
}
return false;
}
private boolean find(Object arg, ReifiedType forcedType) {
for (TypeEntry entry : entries) {
Object val = arg;
if (entry.argument != UNMATCHED) {
continue;
}
if (forcedType != null) {
if (!forcedType.equals(entry.type)) {
continue;
}
} else if (arg != null) {
if (convert) {
if (canConvert(arg, entry.type)) {
try {
val = convert(arg, entry.type);
} catch (Exception e) {
throw new ComponentDefinitionException(e);
}
} else {
continue;
}
} else {
UnwrapperedBeanHolder holder = null;
if (arg instanceof UnwrapperedBeanHolder) {
holder = (UnwrapperedBeanHolder) arg;
arg = holder.unwrapperedBean;
}
if (!AggregateConverter.isAssignable(arg, entry.type)) {
continue;
} else if (holder != null) {
val = wrap(holder, entry.type.getRawClass());
}
}
}
entry.argument = val;
return true;
}
return false;
}
}
private static class TypeEntry {
private final ReifiedType type;
private Object argument;
public TypeEntry(ReifiedType type) {
this.type = type;
this.argument = UNMATCHED;
}
}
}
| 9,523 |
0 | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/container/ParserServiceImpl.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.blueprint.container;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import org.apache.aries.blueprint.ComponentDefinitionRegistry;
import org.apache.aries.blueprint.parser.ComponentDefinitionRegistryImpl;
import org.apache.aries.blueprint.parser.NamespaceHandlerSet;
import org.apache.aries.blueprint.parser.Parser;
import org.apache.aries.blueprint.services.ParserService;
import org.osgi.framework.Bundle;
import org.xml.sax.SAXException;
public class ParserServiceImpl implements ParserService {
final NamespaceHandlerRegistry _namespaceHandlerRegistry;
final boolean _ignoreUnknownNamespaceHandlers;
public ParserServiceImpl(NamespaceHandlerRegistry nhr, boolean ignoreUnknownNamespaceHandlers) {
_namespaceHandlerRegistry = nhr;
_ignoreUnknownNamespaceHandlers = ignoreUnknownNamespaceHandlers;
}
public ComponentDefinitionRegistry parse(URL url, Bundle clientBundle) throws Exception {
return parse(url, clientBundle, false);
}
public ComponentDefinitionRegistry parse(URL url, Bundle clientBundle, boolean validate)
throws Exception {
List<URL> urls = new ArrayList<URL>();
urls.add(url);
return parse(urls, clientBundle, validate);
}
public ComponentDefinitionRegistry parse(List<URL> urls, Bundle clientBundle) throws Exception {
return parse(urls, clientBundle, false);
}
public ComponentDefinitionRegistry parse(List<URL> urls, Bundle clientBundle, boolean validate) throws Exception {
Parser parser = new Parser(null, _ignoreUnknownNamespaceHandlers);
parser.parse(urls);
return validateAndPopulate(parser, clientBundle, validate);
}
public ComponentDefinitionRegistry parse(InputStream is, Bundle clientBundle) throws Exception {
return parse(is, clientBundle, false);
}
public ComponentDefinitionRegistry parse(InputStream is, Bundle clientBundle, boolean validate) throws Exception {
Parser parser = new Parser(null, _ignoreUnknownNamespaceHandlers);
parser.parse(is);
return validateAndPopulate(parser, clientBundle, validate);
}
private ComponentDefinitionRegistry validateAndPopulate(Parser parser, Bundle clientBundle, boolean validate)
throws IOException, SAXException {
Set<URI> nsuris = parser.getNamespaces();
ComponentDefinitionRegistry cdr;
NamespaceHandlerSet nshandlers = _namespaceHandlerRegistry.getNamespaceHandlers(nsuris, clientBundle);
try {
if (validate) {
parser.validate(nshandlers.getSchema());
}
cdr = new ComponentDefinitionRegistryImpl();
parser.populate(nshandlers, cdr);
} finally {
nshandlers.destroy();
}
return cdr;
}
}
| 9,524 |
0 | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/container/IdSpace.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.blueprint.container;
import java.util.concurrent.atomic.AtomicLong;
public class IdSpace {
private AtomicLong currentId = new AtomicLong(0);
public long nextId() {
return currentId.getAndIncrement();
}
}
| 9,525 |
0 | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/container/BlueprintThreadFactory.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.blueprint.container;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;
public class BlueprintThreadFactory implements ThreadFactory {
private final ThreadFactory factory = Executors.defaultThreadFactory();
private final AtomicInteger count = new AtomicInteger();
private final String name;
public BlueprintThreadFactory(String name) {
this.name = name;
}
public Thread newThread(Runnable r) {
final Thread t = factory.newThread(r);
t.setName(name + ": " + count.incrementAndGet());
t.setDaemon(true);
return t;
}
}
| 9,526 |
0 | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/container/NullProxy.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.blueprint.container;
import org.apache.aries.blueprint.container.AggregateConverter.Convertible;
import org.apache.aries.blueprint.services.ExtendedBlueprintContainer;
import org.osgi.service.blueprint.container.ReifiedType;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class NullProxy implements Convertible {
private static final Map<Class<?>, Object> returns;
static {
Map<Class<?>, Object> tmp = new HashMap<Class<?>, Object>();
tmp.put(boolean.class, false);
tmp.put(byte.class, Byte.valueOf("0"));
tmp.put(short.class, Short.valueOf("0"));
tmp.put(char.class, Character.valueOf((char)0));
tmp.put(int.class, Integer.valueOf("0"));
tmp.put(float.class, Float.valueOf("0"));
tmp.put(long.class, Long.valueOf("0"));
tmp.put(Double.class, Double.valueOf("0"));
returns = Collections.unmodifiableMap(tmp);
}
private final ExtendedBlueprintContainer container;
private final InvocationHandler nullProxyHandler = new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if ("toString".equals(method.getName()) && (args == null || args.length == 0)) {
return NullProxy.this.toString();
} else {
return returns.get(method.getReturnType());
}
}
};
public NullProxy(ExtendedBlueprintContainer container) {
this.container = container;
}
@Override
public Object convert(ReifiedType type) {
ClassLoader cl = container.getClassLoader();
return Proxy.newProxyInstance(cl, new Class<?>[] { type.getRawClass() }, nullProxyHandler);
}
@Override
public String toString() {
return "Aries Blueprint Null Proxy";
}
}
| 9,527 |
0 | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/container/Voidable.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.blueprint.container;
public interface Voidable {
void voidReference();
}
| 9,528 |
0 | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/container/DependencyGraph.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.blueprint.container;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.apache.aries.blueprint.di.CircularDependencyException;
import org.apache.aries.blueprint.di.Recipe;
import org.apache.aries.blueprint.di.RefRecipe;
import org.osgi.service.blueprint.container.NoSuchComponentException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class DependencyGraph {
private static final Logger LOGGER = LoggerFactory.getLogger(DependencyGraph.class);
private BlueprintRepository repository;
public DependencyGraph(BlueprintRepository repository) {
this.repository = repository;
}
public LinkedHashMap<String, Recipe> getSortedRecipes(Collection<String> names) {
// construct the graph
Map<String, Node> nodes = new LinkedHashMap<String, Node>();
for (String name : names) {
Object object = repository.getObject(name);
if (object == null) {
throw new NoSuchComponentException(name);
}
if (object instanceof Recipe) {
Recipe recipe = (Recipe) object;
if (!recipe.getName().equals(name)) {
throw new RuntimeException("Recipe '" + name + "' returned from the repository has name '" + name + "'");
}
createNode(name, recipe, nodes);
}
}
// find all initial leaf nodes (and islands)
List<Node> sortedNodes = new ArrayList<Node>(nodes.size());
LinkedList<Node> leafNodes = new LinkedList<Node>();
for (Node n : nodes.values()) {
if (n.referenceCount == 0) {
// if the node is totally isolated (no in or out refs),
// move it directly to the finished list, so they are first
if (n.references.size() == 0) {
sortedNodes.add(n);
} else {
leafNodes.add(n);
}
}
}
// pluck the leaves until there are no leaves remaining
while (!leafNodes.isEmpty()) {
Node node = leafNodes.removeFirst();
sortedNodes.add(node);
for (Node ref : node.references) {
ref.referenceCount--;
if (ref.referenceCount == 0) {
leafNodes.add(ref);
}
}
}
// There are no more leaves so if there are there still
// unprocessed nodes in the graph, we have one or more curcuits
if (sortedNodes.size() != nodes.size()) {
findCircuit(nodes.values().iterator().next(), new ArrayList<Recipe>(nodes.size()));
// find circuit should never fail, if it does there is a programming error
throw new RuntimeException("Internal Error: expected a CircularDependencyException");
}
// return the recipes
LinkedHashMap<String, Recipe> sortedRecipes = new LinkedHashMap<String, Recipe>();
for (Node node : sortedNodes) {
sortedRecipes.put(node.name, node.recipe);
}
return sortedRecipes;
}
private void findCircuit(Node node, ArrayList<Recipe> stack) {
if (stack.contains(node.recipe)) {
ArrayList<Recipe> circularity = new ArrayList<Recipe>(stack.subList(stack.indexOf(node.recipe), stack.size()));
// remove anonymous nodes from circularity list
for (Iterator<Recipe> iterator = circularity.iterator(); iterator.hasNext();) {
Recipe recipe = iterator.next();
if (recipe != node.recipe && recipe.getName() == null) {
iterator.remove();
}
}
// add ending node to list so a full circuit is shown
circularity.add(node.recipe);
throw new CircularDependencyException(circularity);
}
stack.add(node.recipe);
for (Node reference : node.references) {
findCircuit(reference, stack);
}
}
private Node createNode(String name, Recipe recipe, Map<String, Node> nodes) {
// if node already exists, verify that the exact same recipe instnace is used for both
if (nodes.containsKey(name)) {
Node node = nodes.get(name);
if (node.recipe != recipe) {
throw new RuntimeException("The name '" + name + "' is assigned to multiple recipies");
}
return node;
}
// create the node
Node node = new Node();
node.name = name;
node.recipe = recipe;
nodes.put(name, node);
// link in the references
LinkedList<Recipe> constructorRecipes = new LinkedList<Recipe>(recipe.getConstructorDependencies());
while (!constructorRecipes.isEmpty()) {
Recipe nestedRecipe = constructorRecipes.removeFirst();
if (nestedRecipe instanceof RefRecipe) {
nestedRecipe = nestedRecipe.getDependencies().get(0);
String nestedName = nestedRecipe.getName();
Node nestedNode = createNode(nestedName, nestedRecipe, nodes);
node.referenceCount++;
nestedNode.references.add(node);
} else {
constructorRecipes.addAll(nestedRecipe.getDependencies());
}
}
return node;
}
private class Node {
String name;
Recipe recipe;
final List<Node> references = new ArrayList<Node>();
int referenceCount;
public String toString() {
StringBuffer buf = new StringBuffer();
buf.append("Node[").append(name);
if (references.size() > 0) {
buf.append(" <- ");
Iterator<Node> iter = references.iterator();
while (iter.hasNext()) {
buf.append(iter.next().name);
if (iter.hasNext()) {
buf.append(", ");
}
}
}
buf.append("]");
return buf.toString();
}
}
}
| 9,529 |
0 | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/container/GenericType.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.blueprint.container;
import java.lang.reflect.Array;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.lang.reflect.WildcardType;
import java.security.AccessController;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.HashMap;
import java.util.Map;
import org.apache.aries.blueprint.services.ExtendedBlueprintContainer;
import org.apache.aries.blueprint.di.ExecutionContext;
import org.osgi.framework.Bundle;
import org.osgi.service.blueprint.container.ReifiedType;
/**
* XXXX: Currently, in case of arrays getActualTypeArgument(0) returns something similar to what
* Class.getComponentType() does for arrays. I don't think this is quite right since getActualTypeArgument()
* should return the given parameterized type not the component type. Need to check this behavior with the spec.
*/
public class GenericType extends ReifiedType {
private static final GenericType[] EMPTY = new GenericType[0];
private static final Map<String, Class> primitiveClasses = new HashMap<String, Class>();
static {
primitiveClasses.put("int", int.class);
primitiveClasses.put("short", short.class);
primitiveClasses.put("long", long.class);
primitiveClasses.put("byte", byte.class);
primitiveClasses.put("char", char.class);
primitiveClasses.put("float", float.class);
primitiveClasses.put("double", double.class);
primitiveClasses.put("boolean", boolean.class);
}
enum BoundType {
Exact,
Extends,
Super
}
private GenericType[] parameters;
private BoundType boundType;
public GenericType(Type type) {
this(getConcreteClass(type), boundType(type), parametersOf(type));
}
public GenericType(Class clazz, GenericType... parameters) {
this(clazz, BoundType.Exact, parameters);
}
public GenericType(Class clazz, BoundType boundType, GenericType... parameters) {
super(clazz);
this.parameters = parameters;
this.boundType = boundType;
}
public static GenericType parse(String rawType, final Object loader) throws ClassNotFoundException, IllegalArgumentException {
final String type = rawType.trim();
// Check if this is an array
if (type.endsWith("[]")) {
GenericType t = parse(type.substring(0, type.length() - 2), loader);
return new GenericType(Array.newInstance(t.getRawClass(), 0).getClass(), t);
}
// Check if this is a generic
int genericIndex = type.indexOf('<');
if (genericIndex > 0) {
if (!type.endsWith(">")) {
throw new IllegalArgumentException("Can not load type: " + type);
}
GenericType base = parse(type.substring(0, genericIndex), loader);
String[] params = type.substring(genericIndex + 1, type.length() - 1).split(",");
GenericType[] types = new GenericType[params.length];
for (int i = 0; i < params.length; i++) {
types[i] = parse(params[i], loader);
}
return new GenericType(base.getRawClass(), types);
}
// Primitive
if (primitiveClasses.containsKey(type)) {
return new GenericType(primitiveClasses.get(type));
}
// Extends
if (type.startsWith("? extends ")) {
String raw = type.substring("? extends ".length());
return new GenericType(((ClassLoader) loader).loadClass(raw), BoundType.Extends);
}
// Super
if (type.startsWith("? super ")) {
String raw = type.substring("? extends ".length());
return new GenericType(((ClassLoader) loader).loadClass(raw), BoundType.Super);
}
// Class
if (loader instanceof ClassLoader) {
return new GenericType(((ClassLoader) loader).loadClass(type));
} else if (loader instanceof Bundle) {
try {
return AccessController.doPrivileged(new PrivilegedExceptionAction<GenericType>() {
public GenericType run() throws ClassNotFoundException {
return new GenericType(((Bundle) loader).loadClass(type));
}
});
} catch (PrivilegedActionException pae) {
Exception e = pae.getException();
if (e instanceof ClassNotFoundException)
throw (ClassNotFoundException) e;
else
throw (RuntimeException) e;
}
} else if (loader instanceof ExecutionContext) {
return new GenericType(((ExecutionContext) loader).loadClass(type));
} else if (loader instanceof ExtendedBlueprintContainer) {
return new GenericType(((ExtendedBlueprintContainer) loader).loadClass(type));
} else {
throw new IllegalArgumentException("Unsupported loader: " + loader);
}
}
@Override
public ReifiedType getActualTypeArgument(int i) {
if (parameters.length == 0) {
return super.getActualTypeArgument(i);
}
return parameters[i];
}
@Override
public int size() {
return parameters.length;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
if (boundType == BoundType.Extends) {
sb.append("? extends ");
} else if (boundType == BoundType.Super) {
sb.append("? super ");
}
Class cl = getRawClass();
if (cl.isArray()) {
if (parameters.length > 0) {
return parameters[0].toString() + "[]";
} else {
return cl.getComponentType().getName() + "[]";
}
}
sb.append(cl.getName());
if (parameters.length > 0) {
sb.append("<");
for (int i = 0; i < parameters.length; i++) {
if (i > 0) {
sb.append(",");
}
sb.append(parameters[i].toString());
}
sb.append(">");
}
return sb.toString();
}
public boolean equals(Object object) {
if (!(object instanceof GenericType)) {
return false;
}
GenericType other = (GenericType) object;
if (getRawClass() != other.getRawClass()) {
return false;
}
if (boundType != other.boundType) {
return false;
}
if (parameters == null) {
return (other.parameters == null);
} else {
if (other.parameters == null) {
return false;
}
if (parameters.length != other.parameters.length) {
return false;
}
for (int i = 0; i < parameters.length; i++) {
if (!parameters[i].equals(other.parameters[i])) {
return false;
}
}
return true;
}
}
static ReifiedType bound(ReifiedType type) {
if (type instanceof GenericType
&& ((GenericType) type).boundType != BoundType.Exact) {
GenericType t = (GenericType) type;
return new GenericType(t.getRawClass(), BoundType.Exact, t.parameters);
}
return type;
}
static BoundType boundType(ReifiedType type) {
if (type instanceof GenericType) {
return ((GenericType) type).boundType;
} else {
return BoundType.Exact;
}
}
static BoundType boundType(Type type) {
if (type instanceof WildcardType) {
WildcardType wct = (WildcardType) type;
return wct.getLowerBounds().length == 0
? BoundType.Extends : BoundType.Super;
}
return BoundType.Exact;
}
static GenericType[] parametersOf(Type type) {
if (type instanceof Class) {
Class clazz = (Class) type;
if (clazz.isArray()) {
GenericType t = new GenericType(clazz.getComponentType());
if (t.size() > 0) {
return new GenericType[] { t };
} else {
return EMPTY;
}
} else {
return EMPTY;
}
}
if (type instanceof ParameterizedType) {
ParameterizedType pt = (ParameterizedType) type;
Type[] parameters = pt.getActualTypeArguments();
GenericType[] gts = new GenericType[parameters.length];
for (int i = 0; i < gts.length; i++) {
gts[i] = new GenericType(parameters[i]);
}
return gts;
}
if (type instanceof GenericArrayType) {
return new GenericType[]{new GenericType(((GenericArrayType) type).getGenericComponentType())};
}
if (type instanceof WildcardType) {
return EMPTY;
}
if (type instanceof TypeVariable) {
return EMPTY;
}
throw new IllegalStateException();
}
static Class<?> getConcreteClass(Type type) {
Type ntype = collapse(type);
if (ntype instanceof Class)
return (Class<?>) ntype;
if (ntype instanceof ParameterizedType)
return getConcreteClass(collapse(((ParameterizedType) ntype).getRawType()));
throw new RuntimeException("Unknown type " + type);
}
static Type collapse(Type target) {
if (target instanceof Class || target instanceof ParameterizedType) {
return target;
} else if (target instanceof TypeVariable) {
return collapse(((TypeVariable<?>) target).getBounds()[0]);
} else if (target instanceof GenericArrayType) {
Type t = collapse(((GenericArrayType) target)
.getGenericComponentType());
while (t instanceof ParameterizedType)
t = collapse(((ParameterizedType) t).getRawType());
return Array.newInstance((Class<?>) t, 0).getClass();
} else if (target instanceof WildcardType) {
WildcardType wct = (WildcardType) target;
if (wct.getLowerBounds().length == 0)
return collapse(wct.getUpperBounds()[0]);
else
return collapse(wct.getLowerBounds()[0]);
}
throw new RuntimeException("Huh? " + target);
}
}
| 9,530 |
0 | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/services/BlueprintExtenderService.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.blueprint.services;
import java.net.URI;
import java.util.Collection;
import java.util.List;
import org.osgi.framework.Bundle;
import org.osgi.service.blueprint.container.BlueprintContainer;
public interface BlueprintExtenderService {
/**
* Create Blueprint container for the application bundle
* @param bundle the application bundle
* @return container
*/
BlueprintContainer createContainer(Bundle bundle);
/**
* Create Blueprint container for the application bundle using a list of Blueprint resources
* @param bundle the application bundle
* @param blueprintPaths the application blueprint resources
* @return container
*/
BlueprintContainer createContainer(Bundle bundle, List<Object> blueprintPaths);
/**
* Create Blueprint container for the application bundle using a list of Blueprint resources
* @param bundle the application bundle
* @param blueprintPaths the application blueprint resources
* @param namespaces additional namespaces to force reference to
* @return container
*/
BlueprintContainer createContainer(Bundle bundle, List<Object> blueprintPaths, Collection<URI> namespaces);
/**
* Get an existing container for the application bundle
* @param bundle the application bundle
* @return container
*/
BlueprintContainer getContainer(Bundle bundle);
/**
* Destroy Blueprint container for the application bundle
* @param bundle the application bundle
* @param container the container
*/
void destroyContainer(Bundle bundle, BlueprintContainer container);
}
| 9,531 |
0 | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/services/ExtendedBlueprintContainer.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.blueprint.services;
import java.security.AccessControlContext;
import java.util.Dictionary;
import java.util.List;
import java.util.concurrent.ExecutorService;
import org.apache.aries.blueprint.ComponentDefinitionRegistry;
import org.apache.aries.blueprint.Processor;
import org.apache.aries.proxy.ProxyManager;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.blueprint.container.BlueprintContainer;
import org.osgi.service.blueprint.container.BlueprintListener;
import org.osgi.service.blueprint.container.ComponentDefinitionException;
import org.osgi.service.blueprint.container.Converter;
import org.osgi.service.blueprint.reflect.BeanMetadata;
/**
* TODO: javadoc
*
* @version $Rev$, $Date$
*/
public interface ExtendedBlueprintContainer extends BlueprintContainer {
BundleContext getBundleContext();
Bundle getExtenderBundle();
BlueprintListener getEventDispatcher();
Converter getConverter();
Class loadClass(String name) throws ClassNotFoundException;
ComponentDefinitionRegistry getComponentDefinitionRegistry();
<T extends Processor> List<T> getProcessors(Class<T> type);
ServiceRegistration registerService(String[] classes, Object service, Dictionary properties);
Object getService(ServiceReference reference);
AccessControlContext getAccessControlContext();
void reload();
ProxyManager getProxyManager();
/**
* Inject (or reinject) an Object instance with the blueprint properties defined by a BeanMetadata
*
* Throws IllegalArgumentException if the bean metadata does not exist in this blueprint container
* Throws ComponentDefinitionException if the injection process fails - this may have rendered the supplied Object unusable by partially completing the injection process
*/
void injectBeanInstance(BeanMetadata bmd, Object o)
throws IllegalArgumentException, ComponentDefinitionException;
ExecutorService getExecutors();
ClassLoader getClassLoader();
}
| 9,532 |
0 | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/services/ParserService.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.blueprint.services;
import java.io.InputStream;
import java.net.URL;
import java.util.List;
import org.apache.aries.blueprint.ComponentDefinitionRegistry;
import org.osgi.framework.Bundle;
public interface ParserService {
/**
* Parse a single InputStream containing blueprint xml. No validation will be performed. The caller
* is responsible for closing the InputStream afterwards.
* @param is InputStream containing blueprint xml.
* @param clientBundle The client's bundle
* @return ComponentDefinitionRegistry containing metadata generated by the parser.
* @throws Exception
*/
ComponentDefinitionRegistry parse(InputStream is, Bundle clientBundle) throws Exception;
/**
* Parse a single InputStream containing blueprint xml. The caller is responsible for
* closing the InputStream afterwards.
* @param is Input stream containing blueprint xml
* @param clientBundle The client's bundle
* @param validate Indicates whether or not to validate the blueprint xml
* @return ComponentDefinitionRegistry containing metadata generated by the parser.
* @throws Exception
*/
ComponentDefinitionRegistry parse(InputStream is, Bundle clientBundle, boolean validate) throws Exception;
/**
* Parse blueprint xml referred to by a single URL. No validation will be performed.
* @param url URL reference to the blueprint xml to parse
* @param clientBundle The client's bundle
* @return ComponentDefinitionRegistry containing metadata generated by the parser.
* @throws Exception
*/
ComponentDefinitionRegistry parse(URL url, Bundle clientBundle) throws Exception;
/**
* Parse blueprint xml referred to by a single URL.
* @param url URL reference to the blueprint xml to parse
* @param clientBundle The client's bundle
* @param validate Indicates whether or not to validate the blueprint xml
* @return ComponentDefinitionRegistry containing metadata generated by the parser.
* @throws Exception
*/
ComponentDefinitionRegistry parse(URL url, Bundle clientBundle, boolean validate) throws Exception;
/**
* Parse blueprint xml referred to by a list of URLs. No validation will be performed.
* @param urls URL reference to the blueprint xml to parse
* @param clientBundle The client's bundle
* @return ComponentDefinitionRegistry containing metadata generated by the parser.
* @throws Exception
*/
ComponentDefinitionRegistry parse(List<URL> urls, Bundle clientBundle) throws Exception;
/**
* Parse blueprint xml referred to by a list of URLs.
* @param urls URL reference to the blueprint xml to parse
* @param clientBundle The client's bundle
* @param validate Indicates whether or not to validate the blueprint xml
* @return ComponentDefinitionRegistry containing metadata generated by the parser.
* @throws Exception
*/
ComponentDefinitionRegistry parse(List<URL> urls, Bundle clientBundle, boolean validate) throws Exception;
}
| 9,533 |
0 | Create_ds/aries/blueprint/examples/blueprint-sample-fragment/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/examples/blueprint-sample-fragment/src/main/java/org/apache/aries/blueprint/fragment/FragmentBean.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.blueprint.fragment;
import org.apache.aries.blueprint.annotation.Bean;
@Bean(id="fragment")
public class FragmentBean {}
| 9,534 |
0 | Create_ds/aries/blueprint/examples/blueprint-sample-war/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/examples/blueprint-sample-war/src/main/java/org/apache/aries/blueprint/sample/AccountsServlet.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.blueprint.sample;
import org.apache.aries.blueprint.web.BlueprintContextListener;
import org.osgi.service.blueprint.container.BlueprintContainer;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
public class AccountsServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
BlueprintContainer container = (BlueprintContainer) getServletContext().getAttribute(BlueprintContextListener.CONTAINER_ATTRIBUTE);
StringBuilder sb = new StringBuilder();
sb.append("<html><body>");
List<Account> accounts = (List<Account>) container.getComponentInstance("accounts");
sb.append("<h2>Accounts</h2>");
sb.append("<ul>");
for (Account account : accounts) {
sb.append("<li>").append(account.getAccountNumber()).append("</li>");
}
sb.append("</ul>");
sb.append("<br/>");
Foo foo = (Foo) container.getComponentInstance("foo");
sb.append("<h2>Foo</h2>");
sb.append("<ul>");
sb.append("<li>").append("a = ").append(foo.getA()).append("</li>");
sb.append("<li>").append("b = ").append(foo.getB()).append("</li>");
sb.append("<li>").append("currency = ").append(foo.getCurrency()).append("</li>");
sb.append("<li>").append("date = ").append(foo.getDate()).append("</li>");
sb.append("</ul>");
sb.append("</body></html>");
resp.getWriter().write(sb.toString());
}
}
| 9,535 |
0 | Create_ds/aries/blueprint/examples/blueprint-sample-war/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/examples/blueprint-sample-war/src/main/java/org/apache/aries/blueprint/sample/StaticAccountFactory.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.blueprint.sample;
public class StaticAccountFactory {
public static Account createAccount(long number) {
return new Account(number);
}
}
| 9,536 |
0 | Create_ds/aries/blueprint/examples/blueprint-sample-war/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/examples/blueprint-sample-war/src/main/java/org/apache/aries/blueprint/sample/Account.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.blueprint.sample;
public class Account {
private long accountNumber;
public Account(long number) {
this.accountNumber = number;
}
public long getAccountNumber() {
return this.accountNumber;
}
public void setAccountNumber(long number) {
this.accountNumber = number;
}
}
| 9,537 |
0 | Create_ds/aries/blueprint/examples/blueprint-sample-war/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/examples/blueprint-sample-war/src/main/java/org/apache/aries/blueprint/sample/Foo.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.blueprint.sample;
import java.io.Serializable;
import java.util.Currency;
import java.util.Date;
import java.util.Map;
public class Foo implements Serializable {
private int a;
private int b;
private Currency currency;
private Date date;
public boolean initialized;
public boolean destroyed;
private Map<String, Object> props;
public int getA() {
return a;
}
public void setA(int i) {
a = i;
}
public int getB() {
return b;
}
public void setB(int i) {
b = i;
}
public Currency getCurrency() {
return currency;
}
public void setCurrency(Currency c) {
currency = c;
}
public Date getDate() {
return date;
}
public void setDate(Date d) {
date = d;
}
public String toString() {
return a + " " + b + " " + currency + " " + date;
}
public void init() {
System.out.println("======== Initializing Foo =========");
initialized = true;
}
public void destroy() {
System.out.println("======== Destroying Foo =========");
destroyed = true;
}
public boolean isInitialized() {
return initialized;
}
public boolean isDestroyed() {
return destroyed;
}
public void update(Map<String,Object> props) {
this.props = props;
}
public Map<String, Object> getProps() {
return props;
}
}
| 9,538 |
0 | Create_ds/aries/blueprint/examples/blueprint-sample-war/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/examples/blueprint-sample-war/src/main/java/org/apache/aries/blueprint/sample/DateTypeConverter.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.blueprint.sample;
import org.osgi.service.blueprint.container.Converter;
import org.osgi.service.blueprint.container.ReifiedType;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateTypeConverter implements Converter {
DateFormat dateFormat;
public void setFormat(String format) {
dateFormat = new SimpleDateFormat(format);
}
public Object convert(Object source, ReifiedType toType) throws Exception {
return dateFormat.parse(source.toString());
}
public boolean canConvert(Object fromValue, ReifiedType toType) {
return Date.class.isAssignableFrom(toType.getRawClass());
}
}
| 9,539 |
0 | Create_ds/aries/blueprint/examples/blueprint-sample-war/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/examples/blueprint-sample-war/src/main/java/org/apache/aries/blueprint/sample/CurrencyTypeConverter.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.blueprint.sample;
import org.osgi.service.blueprint.container.Converter;
import org.osgi.service.blueprint.container.ReifiedType;
import java.util.Currency;
public class CurrencyTypeConverter implements Converter {
public boolean canConvert(Object fromValue, ReifiedType toType) {
return Currency.class.isAssignableFrom(toType.getRawClass());
}
public Object convert(Object source, ReifiedType toType) throws Exception {
return Currency.getInstance(source.toString());
}
}
| 9,540 |
0 | Create_ds/aries/blueprint/examples/blueprint-sample-war/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/examples/blueprint-sample-war/src/main/java/org/apache/aries/blueprint/sample/AccountFactory.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.blueprint.sample;
public class AccountFactory {
private String factoryName;
public AccountFactory(String factoryName) {
this.factoryName = factoryName;
}
public Account createAccount(long number) {
return new Account(number);
}
public String getFactoryName() {
return this.factoryName;
}
}
| 9,541 |
0 | Create_ds/aries/blueprint/examples/blueprint-sample/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/examples/blueprint-sample/src/main/java/org/apache/aries/blueprint/sample/InterfaceA.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.blueprint.sample;
public interface InterfaceA {
String hello(String msg);
}
| 9,542 |
0 | Create_ds/aries/blueprint/examples/blueprint-sample/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/examples/blueprint-sample/src/main/java/org/apache/aries/blueprint/sample/DefaultRunnable.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.blueprint.sample;
import java.util.concurrent.atomic.AtomicInteger;
public class DefaultRunnable implements Runnable
{
private static AtomicInteger count = new AtomicInteger();
public void run()
{
count.incrementAndGet();
}
public int getCount()
{
return count.get();
}
} | 9,543 |
0 | Create_ds/aries/blueprint/examples/blueprint-sample/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/examples/blueprint-sample/src/main/java/org/apache/aries/blueprint/sample/DodgyListener.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.blueprint.sample;
import java.util.Set;
import java.util.Map;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
public class DodgyListener {
private BundleContext ctx;
public void setBundleContext(BundleContext ctx) {
this.ctx = ctx;
}
public void bind(Set a, Map props) {
System.out.println("Attempting to provoke deadlock");
Thread t = new Thread() {
public void run() {
// we pretend to be another bundle (otherwise we'll deadlock in Equinox itself :(
BundleContext otherCtx = ctx.getBundle(0).getBundleContext();
ServiceReference ref = otherCtx.getServiceReference("java.util.List");
otherCtx.getService(ref);
}
};
t.start();
// let the other thread go first
try {
Thread.sleep(100);
} catch (Exception e) {}
ServiceReference ref = ctx.getServiceReference("java.util.List");
ctx.getService(ref);
}
} | 9,544 |
0 | Create_ds/aries/blueprint/examples/blueprint-sample/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/examples/blueprint-sample/src/main/java/org/apache/aries/blueprint/sample/FooRegistrationListener.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.blueprint.sample;
import java.io.Serializable;
import java.util.Map;
public class FooRegistrationListener {
private Map props;
private Object lock = new Object();
public void serviceRegistered(Serializable foo, Map props) {
System.out.println("Service registration notification: " + foo + " " + props);
synchronized (lock) {
this.props = props;
}
}
public void serviceUnregistered(Foo foo, Map props) {
System.out.println("Service unregistration notification: " + foo + " " + props);
}
public Map getProperties() {
synchronized (lock) {
return this.props;
}
}
}
| 9,545 |
0 | Create_ds/aries/blueprint/examples/blueprint-sample/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/examples/blueprint-sample/src/main/java/org/apache/aries/blueprint/sample/StaticAccountFactory.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.blueprint.sample;
public class StaticAccountFactory {
public static Account createAccount(long number) {
return new Account(number);
}
}
| 9,546 |
0 | Create_ds/aries/blueprint/examples/blueprint-sample/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/examples/blueprint-sample/src/main/java/org/apache/aries/blueprint/sample/Bar.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.blueprint.sample;
import java.util.List;
import org.osgi.framework.BundleContext;
public class Bar {
private BundleContext context;
private String value;
private List list;
public BundleContext getContext() {
return context;
}
public void setContext(BundleContext ctx) {
context = ctx;
}
public String getValue() {
return value;
}
public void setValue(String s) {
value = s;
}
public List getList() {
return list;
}
public void setList(List l) {
list = l;
}
public String toString() {
return hashCode() + ": " + value + " " + context + " " + list;
}
}
| 9,547 |
0 | Create_ds/aries/blueprint/examples/blueprint-sample/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/examples/blueprint-sample/src/main/java/org/apache/aries/blueprint/sample/Account.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.blueprint.sample;
public class Account {
private long accountNumber;
public Account(long number) {
this.accountNumber = number;
}
public long getAccountNumber() {
return this.accountNumber;
}
public void setAccountNumber(long number) {
this.accountNumber = number;
}
}
| 9,548 |
0 | Create_ds/aries/blueprint/examples/blueprint-sample/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/examples/blueprint-sample/src/main/java/org/apache/aries/blueprint/sample/Foo.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.blueprint.sample;
import java.io.Serializable;
import java.util.Currency;
import java.util.Date;
import java.util.Map;
public class Foo implements Serializable {
/**
*
*/
private static final long serialVersionUID = 5557730221435945564L;
private int a;
private int b;
private Bar bar;
private Currency currency;
private Date date;
public boolean initialized;
public boolean destroyed;
private Map<String, Object> props;
public int getA() {
return a;
}
public void setA(int i) {
a = i;
}
public int getB() {
return b;
}
public void setB(int i) {
b = i;
}
public Bar getBar() {
return bar;
}
public void setBar(Bar b) {
bar = b;
}
public Currency getCurrency() {
return currency;
}
public void setCurrency(Currency c) {
currency = c;
}
public Date getDate() {
return date;
}
public void setDate(Date d) {
date = d;
}
public String toString() {
return a + " " + b + " " + bar + " " + currency + " " + date;
}
public void init() {
System.out.println("======== Initializing Foo =========");
initialized = true;
}
public void destroy() {
System.out.println("======== Destroying Foo =========");
destroyed = true;
}
public boolean isInitialized() {
return initialized;
}
public boolean isDestroyed() {
return destroyed;
}
public void update(Map<String,Object> props) {
this.props = props;
}
public Map<String, Object> getProps() {
return props;
}
}
| 9,549 |
0 | Create_ds/aries/blueprint/examples/blueprint-sample/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/examples/blueprint-sample/src/main/java/org/apache/aries/blueprint/sample/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.blueprint.sample;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
public class Activator implements BundleActivator {
public void start(BundleContext context) {
System.out.println("Bundle start");
}
public void stop(BundleContext context) {
System.out.println("Bundle stop");
}
}
| 9,550 |
0 | Create_ds/aries/blueprint/examples/blueprint-sample/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/examples/blueprint-sample/src/main/java/org/apache/aries/blueprint/sample/DateTypeConverter.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.blueprint.sample;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.osgi.service.blueprint.container.Converter;
import org.osgi.service.blueprint.container.ReifiedType;
public class DateTypeConverter implements Converter {
DateFormat dateFormat;
public void setFormat(String format) {
dateFormat = new SimpleDateFormat(format);
}
public Object convert(Object source, ReifiedType toType) throws Exception {
return dateFormat.parse(source.toString());
}
public boolean canConvert(Object fromValue, ReifiedType toType) {
return Date.class.isAssignableFrom(toType.getRawClass());
}
}
| 9,551 |
0 | Create_ds/aries/blueprint/examples/blueprint-sample/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/examples/blueprint-sample/src/main/java/org/apache/aries/blueprint/sample/BindingListener.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.blueprint.sample;
import java.util.Map;
import java.util.List;
import java.io.Serializable;
import org.osgi.framework.ServiceReference;
public class BindingListener {
private InterfaceA a;
private Map props;
private ServiceReference reference;
private List list;
public InterfaceA getA() {
return a;
}
public Map getProps() {
return props;
}
public ServiceReference getReference() {
return reference;
}
public List getList() {
return list;
}
public void setList(List list) {
this.list = list;
}
public void init() {
}
public void bind(InterfaceA a, Map props) {
this.a = a;
this.props = props;
}
public void bind(ServiceReference ref) {
this.reference = ref;
}
public void unbind(InterfaceA a, Map props) {
this.a = null;
this.props = null;
}
public void unbind(ServiceReference ref) {
this.reference = null;
}
}
| 9,552 |
0 | Create_ds/aries/blueprint/examples/blueprint-sample/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/examples/blueprint-sample/src/main/java/org/apache/aries/blueprint/sample/DestroyTest.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.blueprint.sample;
public class DestroyTest
{
private Runnable target;
private Exception destroyFailure;
private boolean destroyed;
public void setTarget(Runnable r)
{
target = r;
}
public Exception getDestroyFailure()
{
return destroyFailure;
}
public void destroy()
{
try {
target.run();
} catch (Exception e) {
destroyFailure = e;
}
synchronized (this) {
destroyed = true;
notifyAll();
}
}
public synchronized boolean waitForDestruction(int timeout)
{
long startTime = System.currentTimeMillis();
while (!!!destroyed && System.currentTimeMillis() - startTime < timeout) {
try {
wait(100);
} catch (InterruptedException e) {
}
}
return destroyed;
}
} | 9,553 |
0 | Create_ds/aries/blueprint/examples/blueprint-sample/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/examples/blueprint-sample/src/main/java/org/apache/aries/blueprint/sample/CurrencyTypeConverter.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.blueprint.sample;
import java.util.Currency;
import org.osgi.service.blueprint.container.Converter;
import org.osgi.service.blueprint.container.ReifiedType;
public class CurrencyTypeConverter implements Converter {
public boolean canConvert(Object fromValue, ReifiedType toType) {
return Currency.class.isAssignableFrom(toType.getRawClass());
}
public Object convert(Object source, ReifiedType toType) throws Exception {
return Currency.getInstance(source.toString());
}
}
| 9,554 |
0 | Create_ds/aries/blueprint/examples/blueprint-sample/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/examples/blueprint-sample/src/main/java/org/apache/aries/blueprint/sample/AccountFactory.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.blueprint.sample;
public class AccountFactory {
private String factoryName;
public AccountFactory(String factoryName) {
this.factoryName = factoryName;
}
public Account createAccount(long number) {
return new Account(number);
}
public String getFactoryName() {
return this.factoryName;
}
}
| 9,555 |
0 | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint/Interceptor.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.blueprint;
import java.lang.reflect.Method;
import org.osgi.service.blueprint.reflect.ComponentMetadata;
/**
* An Interceptor interface provides support for custom interceptor implementation.
*/
public interface Interceptor {
/**
* This is called just before the method m is invocation.
* @param cm : the component's metada
* @param m: the method to be invoked
* @param parameters: method parameters
* @return token which will subsequently be passed to postCall
* @throws Throwable
*/
Object preCall(ComponentMetadata cm, Method m, Object... parameters) throws Throwable;
/**
* This method is called after the method m is invoked and returned normally.
* @param cm: the component metadata
* @param m: the method invoked
* @param returnType : the return object
* @param preCallToken token returned by preCall
* @throws Throwable
*/
void postCallWithReturn(ComponentMetadata cm, Method m, Object returnType, Object preCallToken) throws Throwable;
/**
* The method is called after the method m is invoked and causes an exception.
* @param cm : the component metadata
* @param m : the method invoked
* @param ex : the <code>Throwable</code> thrown
* @param preCallToken token returned by preCall
* @throws Throwable
*/
void postCallWithException(ComponentMetadata cm, Method m, Throwable ex, Object preCallToken) throws Throwable;
/**
* Return the rank of the interceptor, which is used to determine the order of the interceptors to be invoked
* Rank is between Integer.MIN_VALUE and Integer.MAX_VALUE, interceptors are called in the order of highest value
* rank first to lowest value rank last i.e. an interceptor with rank Integer.MAX_VALUE will be called before
* all others (except of the same rank).
* @return the rank of the interceptor
*/
int getRank();
}
| 9,556 |
0 | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint/BlueprintConstants.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.blueprint;
public interface BlueprintConstants {
String BUNDLE_BLUEPRINT_HEADER = "Bundle-Blueprint";
String BUNDLE_BLUEPRINT_ANNOTATION_HEADER = "Bundle-Blueprint-Annotation";
String TIMEOUT_DIRECTIVE = "blueprint.timeout";
String GRACE_PERIOD = "blueprint.graceperiod";
String BUNDLE_VERSION = "bundle.version";
String COMPONENT_NAME_PROPERTY = "osgi.service.blueprint.compname";
String CONTAINER_SYMBOLIC_NAME_PROPERTY = "osgi.blueprint.container.symbolicname";
String CONTAINER_VERSION_PROPERTY = "osgi.blueprint.container.version";
String XML_VALIDATION = "blueprint.aries.xml-validation";
String USE_SYSTEM_CONTEXT_PROPERTY = "org.apache.aries.blueprint.use.system.context";
String IGNORE_UNKNOWN_NAMESPACE_HANDLERS_PROPERTY = "org.apache.aries.blueprint.parser.service.ignore.unknown.namespace.handlers";
String PREEMPTIVE_SHUTDOWN_PROPERTY = "org.apache.aries.blueprint.preemptiveShutdown";
String SYNCHRONOUS_PROPERTY = "org.apache.aries.blueprint.synchronous";
String XML_VALIDATION_PROPERTY = "org.apache.aries.blueprint.xml.validation";
}
| 9,557 |
0 | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint/ExtendedReferenceMetadata.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.blueprint;
import java.util.Collection;
import org.osgi.service.blueprint.reflect.ReferenceMetadata;
public interface ExtendedReferenceMetadata extends ReferenceMetadata, ExtendedServiceReferenceMetadata
{
int DAMPING_RELUCTANT = 0;
int DAMPING_GREEDY = 1;
int LIFECYCLE_DYNAMIC = 0;
int LIFECYCLE_STATIC = 1;
String getDefaultBean();
Collection<Class<?>> getProxyChildBeanClasses();
Collection<String> getExtraInterfaces();
int getDamping();
int getLifecycle();
} | 9,558 |
0 | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint/ParserContext.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.blueprint;
import java.net.URI;
import java.util.Set;
import org.osgi.service.blueprint.reflect.ComponentMetadata;
import org.osgi.service.blueprint.reflect.Metadata;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
public interface ParserContext {
/**
* Returns the DOM Node that was passed to the NamespaceHandler call for which
* this ParserContext instance was created.
*/
Node getSourceNode();
ComponentDefinitionRegistry getComponentDefinitionRegistry();
/**
* Retrieve the <code>ComponentMetadata</code> of the component that
* encloses the current <code>Node</code> that is to be parsed by a
* namespace handler.
*
* In case of top-level components this method will return <code>null</code>.
* @return the enclosing component's metadata or null if there is no enclosing component
*/
ComponentMetadata getEnclosingComponent();
/**
* Create a new metadata instance of the given type. The returned
* object will also implement the appropriate <code>MutableComponentMetadata</code>
* interface, so as to allow the caller to set the properties of the
* metadata.
*
* Note that the returned object may not be initialised, so callers
* should take care to assure every property needed by the blueprint
* extender is set.
*
* @param type the class of the Metadata object to create
* @param <T> The expected Metadata type to be created
* @return a new instance
*/
<T extends Metadata> T createMetadata(Class<T> type);
/**
* Invoke the blueprint parser to parse a DOM element.
* @param type the class of the Metadata type to be parsed
* @param enclosingComponent The component metadata that contains the Element
* to be parsed
* @param element The DOM element that is to be parsed
* @param <T> The expected metadata type to be parsed
*/
<T> T parseElement(Class<T> type, ComponentMetadata enclosingComponent, Element element);
/**
* Generate a unique id following the same scheme that the blueprint container
* uses internally
*/
String generateId();
/**
* Get the default activation setting for the current blueprint file
*/
String getDefaultActivation();
/**
* Get the default availability setting for the current blueprint file
*/
String getDefaultAvailability();
/**
* Get the default timeout setting for the current blueprint file
*/
String getDefaultTimeout();
/**
* Retrieve the set of namespaces
*/
Set<URI> getNamespaces();
/**
* Retrieve the namespace handler for the given uri
*/
NamespaceHandler getNamespaceHandler(URI namespaceUri);
}
| 9,559 |
0 | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint/ExtendedReferenceListMetadata.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.blueprint;
import org.osgi.service.blueprint.reflect.ReferenceListMetadata;
/**
* TODO: javadoc
*
* @version $Rev$, $Date$
*/
public interface ExtendedReferenceListMetadata extends ReferenceListMetadata, ExtendedServiceReferenceMetadata {
int PROXY_METHOD_GREEDY = 2;
}
| 9,560 |
0 | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint/NamespaceHandler.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.blueprint;
import java.net.URL;
import java.util.Set;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.osgi.service.blueprint.reflect.ComponentMetadata;
import org.osgi.service.blueprint.reflect.Metadata;
/**
* A processor for custom blueprint extensions
*
* Namespace handlers must be registered in the OSGi service registry with the
* <code>osgi.service.blueprint.namespace</code> service property denoting the namespace URIs this
* handler can process. The service property value can be either a single <code>String</code> or <code>URI</code>,
* or a <code>Collection</code> respectively array of <code>String</code> or <code>URI</code>.
*
* During parsing when the blueprint extender encounters an element from a non-blueprint namespace it will search
* for a namespace handler for the namespace that is compatible with blueprint bundle being processed. Then
* for a stand-alone component the parser will invoke the <code>parse</code> method
* to create the <code>Metadata</code> for the xml element while for an element that is part
* of an existing component the parser will invoke the <code>decorated</code> method to augment
* the enclosing <code>ComponentMetadata</code> instance. Various utilities to interact with
* the blueprint parser are available to a namespace handler via the <code>ParserContext</code> argument
* passed to <code>parse</code> and <code>decorate</code>.
*
* Recommended behaviour:
* <ul>
* <li>New metadata objects should be created via calling <code>ParserContext.createMetadata(..)</code> and
* casting the returned object to the appropriate <code>MutableComponentMetadata</code> interface.
* This method ensures that the metadata object implements the interfaces necessary for other namespace handlers
* to be able to use the metadata object.<br>
* Also, to prevent id clashes, component ids should be generated by calling <code>ParserContext.generateId()</code>.
* </li>
* <li>A namespace handler should not return new metadata instances from the <code>decorate</code> method if
* the same result could also be achieved by operating on a <code>MutableComponentMetadata</code> instance.
* </li>
* <li>A namespace handler should not assume the existence of predefined entries in the component definition
* registry such as <code>blueprintBundle</code> or <code>blueprintBundleContext</code>. In the case of a dry
* parse (i.e. a parse of the blueprint xml files without a backing OSGi bundle), these values will not be
* available
* </li>
* </ul>
*/
public interface NamespaceHandler {
/**
* Retrieve a URL from where the schema for a given namespace can be retrieved
* @param namespace The schema's namespace
* @return A URL that points to the location of the schema or null if the namespace validation
* is not needed
*/
URL getSchemaLocation(String namespace);
/**
* Specify a set of classes that must be consistent between a blueprint bundle and this namespace handler
*
* The blueprint extender will not invoke a namespace handler if any of the managed classes are inconsistent
* with the class space of the blueprint bundle (i.e. if the blueprint bundle loads any of the managed classes
* from a different classloader).
*
* @return a <code>Set</code> of classes that must be compatible with any blueprint bundle for which this namespace
* handler is to apply or <code>null</code> if no compatibility checks are to be performed
*/
Set<Class> getManagedClasses();
/**
* Parse a stand-alone blueprint component
*
* Given an <code>Element</code> node as a root, this method parses the stand-alone component and returns its
* metadata. The supplied <code>ParserContext</code> should be used to parse embedded blueprint elements as well
* as creating metadata.
*
* @param element The DOM element representing the custom component
* @param context The <code>ParserContext</code> for parsing sub-components and creating metadata objects
* @return A metadata instance representing the custom component. This should be an instance of an appropriate
* <code>MutableMetadata</code> type to enable further decoration by other namespace handlers
*/
Metadata parse(Element element, ParserContext context);
/**
* Process a child node of an enclosing blueprint component.
*
* If the decorator method returns a new <code>ComponentMetadata</code> instance, this will replace the argument
* <code>ComponentMetadata</code> in subsequent parsing and namespace handler invocations. A namespace
* handler that elects to return a new <code>ComponentMetadata</code> instance should
* ensure that existing interceptors are registered against the new instance if appropriate.
*
* Due to the interaction with interceptors, a namespace handler should prefer to change a component metadata
* instead of returning a new instance wherever possible. This can be achieved by casting a
* <code>ComponentMetadata</code> to its corresponding <code>MutabableComponentMetadata</code> instance.
* Note however that a given <code>ComponentMetadata</code> instance cannot be guaranteed to implement
* the mutable interface if it was constructed by an agent other than the blueprint extender.
*
* @param node The node associated with this NamespaceHandler that should be used to decorate the enclosing
* component
* @param component The enclosing blueprint component
* @param context The parser context
* @return The decorated component to be used instead of the original enclosing component. This can of course be
* the original component.
*/
ComponentMetadata decorate(Node node, ComponentMetadata component, ParserContext context);
}
| 9,561 |
0 | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint/ComponentDefinitionRegistryProcessor.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.blueprint;
/**
* A processor that processes Blueprint component definitions after they have been parsed but before
* component managers are created.
*
* Component definition registry processors must be advertised as such in the blueprint xml. Do this by using
* the custom attribute defined in the extension schema.
* <pre>
* <bp:bean ext:role="processor" ...>
* </pre>
*
* When a definition registry processor is invoked type converters and registry processors have been already
* been created. Hence, changing component definitions for these or any components referenced by them will have
* no effect.
*
* Note: a processor that replaces existing component definitions with new ones should take care to copy
* interceptors defined against the old component definition if appropriate
*
* @version $Rev$, $Date$
*/
public interface ComponentDefinitionRegistryProcessor {
/**
* Process a <code>ComponentDefinitionRegistry</code>
* @param registry
*/
void process(ComponentDefinitionRegistry registry);
}
| 9,562 |
0 | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint/ExtendedBeanMetadata.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.blueprint;
import org.osgi.service.blueprint.reflect.BeanMetadata;
/**
* An extended <code>BeanMetadata</code> that allows specifying if
* the bean instances are processors or not.
*
* Such processors have to be instantiated before instantiating all
* other singletons, but to avoid breaking the lazy activation of
* bundles, the Blueprint container needs to be aware of those and not
* try to load the class to perform some introspection.
*/
public interface ExtendedBeanMetadata extends BeanMetadata {
boolean isProcessor();
/**
* Provide an actual class, this overrides the class name if set. This is
* useful for Namespace Handler services that do not want to force the
* Blueprint bundle to import implementation classes.
*
* @return Return the class to use in runtime or <code>null</code>.
*/
Class<?> getRuntimeClass();
/**
* Whether the bean allows properties to be injected directly into its fields in the case
* where an appropriate setter method is not available.
* @return Whether field injection is allowed
*/
boolean getFieldInjection();
/**
* Whether arguments / properties conversion is strict or lenient.
* @return The type of conversion.
*/
boolean getRawConversion();
/**
* Whether setters returning non void types can be used or not.
* @return a boolean allowing the used of non standard setters
*/
boolean getNonStandardSetters();
}
| 9,563 |
0 | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint/NamespaceHandler2.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.blueprint;
/**
* Additional namespace features
*/
public interface NamespaceHandler2 extends NamespaceHandler {
/**
* A namespace can return true if its parsing relies on PSVI,
* i.e. extensions from the schema for default attributes values
* for example.
*/
boolean usePsvi();
}
| 9,564 |
0 | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint/Namespaces.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.blueprint;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Lists the namespaces supported by a given <code>NamespaceHandler</code>.
* <code>NamespaceHandler</code> implementations may optionally use this annotation to
* simplify the auto-registration process in some deployment scenarios.
*/
@Inherited
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Namespaces {
/**
* A list of namespaces supported by <code>NamespaceHandler</code>.
*/
String[] value();
}
| 9,565 |
0 | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint/ExtendedServiceReferenceMetadata.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.blueprint;
import org.osgi.framework.BundleContext;
import org.osgi.service.blueprint.reflect.ServiceReferenceMetadata;
import org.osgi.service.blueprint.reflect.ValueMetadata;
/**
* TODO: javadoc
*
* @version $Rev$, $Date$
*/
public interface ExtendedServiceReferenceMetadata extends ServiceReferenceMetadata {
int PROXY_METHOD_DEFAULT = 0;
int PROXY_METHOD_CLASSES = 1;
int getProxyMethod();
Class getRuntimeInterface();
BundleContext getBundleContext();
ValueMetadata getExtendedFilter();
}
| 9,566 |
0 | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint/ExtendedValueMetadata.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.blueprint;
import org.osgi.service.blueprint.reflect.ValueMetadata;
public interface ExtendedValueMetadata extends ValueMetadata {
Object getValue();
}
| 9,567 |
0 | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint/Processor.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.blueprint;
/**
* Marker interface for blueprint processors such as <code>BeanProcessor</code> or
* <code>ServiceProcessor</code>
*/
public interface Processor {}
| 9,568 |
0 | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint/PassThroughMetadata.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.blueprint;
import org.osgi.service.blueprint.reflect.ComponentMetadata;
import org.osgi.service.blueprint.reflect.Target;
/**
* Metadata used to bypass the creation of the object.
* This is mostly usefull when creating custom namespace handlers
* that end-up with already instanciated objects.
*/
public interface PassThroughMetadata extends ComponentMetadata, Target {
Object getObject();
}
| 9,569 |
0 | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint/ServiceProcessor.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.blueprint;
import java.util.Dictionary;
/**
*/
public interface ServiceProcessor extends Processor {
void updateProperties(ServicePropertiesUpdater service, Dictionary properties);
interface ServicePropertiesUpdater {
String getId();
void updateProperties(Dictionary properties);
}
}
| 9,570 |
0 | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint/ComponentNameAlreadyInUseException.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.blueprint;
public class ComponentNameAlreadyInUseException extends RuntimeException {
private String conflictingName;
public ComponentNameAlreadyInUseException(String conflictingName) {
this.conflictingName = conflictingName;
}
public String getMessage() {
return "Name '" + this.conflictingName + "' is already in use by a registered component";
}
public String getConflictingName() {
return this.conflictingName;
}}
| 9,571 |
0 | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint/ComponentDefinitionRegistry.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.blueprint;
import java.util.List;
import java.util.Set;
import org.osgi.service.blueprint.reflect.ComponentMetadata;
import org.osgi.service.blueprint.reflect.Target;
public interface ComponentDefinitionRegistry {
/**
* Determine if the component registry contains a component definition for the given id
* @param id
* @return
*/
boolean containsComponentDefinition(String id);
/**
* Retrieve a component's metadata by id
* @param id The id of the component. This is either the id specified in the Blueprint xml or the
* generated id of an unnamed component
* @return the <code>ComponentMetadata</code> or <code>null</code> if the id does not match
* any registered component
*/
ComponentMetadata getComponentDefinition(String id);
/**
* Returns a set of the id of top-level blueprint components (both named and unnamed).
*
* The ids of unnamed components are Blueprint generated. Anonymous components, which have no
* id, are not part of the set.
* @return
*/
Set<String> getComponentDefinitionNames();
/**
* Register a new component
*
* The <code>ComponentMetadata</code> argument must have an id. So unnamed components should have an id
* generated prior to invoking this method. Also, no component definition may already be registered
* under the same id.
*
* @param component the component to be registered
* @throws IllegalArgumentException if the component has no id
* @throws ComponentNameAlreadyInUseException if there already exists a component definition
* in the registry with the same id
*/
void registerComponentDefinition(ComponentMetadata component);
/**
* Remove the component definition with a given id
*
* If no component is registered under the id, this method is a no-op.
* @param id the id of the component definition to be removed
*/
void removeComponentDefinition(String id);
void registerTypeConverter(Target component);
List<Target> getTypeConverters();
/**
* Register an interceptor for a given component
*
* Since the interceptor is registered against a <code>ComponentMetadata</code> instance and not an id,
* interceptors can be registered for anonymous components as well as named and unnamed components.
*
* Note: Although an interceptor is registered against a specific <code>ComponentMetadata</code> instance,
* an interceptor should not rely on this fact. This will allow <code>NamespaceHandlers</code> and
* <code>ComponentDefinitionRegistryProcessors</code> to respect registered interceptors even when
* the actual <code>ComponentMetadata</code> instance is changed or augmented. If an interceptor does
* not support such a scenario it should nevertheless fail gracefully in the case of modified
* <code>ComponentMetadata</code> instances.
*
* Note: at the time of this writing (version 0.1) interceptors are only supported for <code>BeanMetadata</code>.
* Interceptors registered against other component types will be ignored.
*
* @param component the component the interceptor is to be registered against
* @param interceptor the interceptor to be used
*/
void registerInterceptorWithComponent(ComponentMetadata component, Interceptor interceptor);
/**
* Retrieve all interceptors registered against a <code>ComponentMetadata</code> instance
* @param component
* @return a list of interceptors sorted by decreasing rank. The list may be empty if no interceptors have been defined
*/
List<Interceptor> getInterceptors(ComponentMetadata component);
}
| 9,572 |
0 | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint/BeanProcessor.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.blueprint;
import org.osgi.service.blueprint.reflect.BeanMetadata;
/**
* TODO: javadoc
*
* Processors must be advertized as being such. This can be done by using
* the custom attribute defined in the extension schema.
* <pre>
* <bp:bean ext:role="processor" ...>
* </pre>
*
* @version $Rev$, $Date$
*/
public interface BeanProcessor extends Processor {
/**
* Interface from which a BeanProcessor can obtain another bean.
*/
interface BeanCreator {
/**
* Obtains a new instance of the Bean this BeanProcessor handled. <br>
* New instances have been processed by the same chain of BeanProcessors
* that the original Bean had been.
* @return new instance of bean.
*/
Object getBean();
}
Object beforeInit(Object bean, String beanName, BeanCreator beanCreator, BeanMetadata beanData);
Object afterInit(Object bean, String beanName, BeanCreator beanCreator, BeanMetadata beanData);
void beforeDestroy(Object bean, String beanName);
void afterDestroy(Object bean, String beanName);
}
| 9,573 |
0 | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint/mutable/MutablePropsMetadata.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.blueprint.mutable;
import org.osgi.service.blueprint.reflect.MapEntry;
import org.osgi.service.blueprint.reflect.Metadata;
import org.osgi.service.blueprint.reflect.NonNullMetadata;
import org.osgi.service.blueprint.reflect.PropsMetadata;
/**
* A mutable version of the <code>PropsMetadata</code> that allows modifications.
*
* @version $Rev$, $Date$
*/
public interface MutablePropsMetadata extends PropsMetadata {
void addEntry(MapEntry entry);
MapEntry addEntry(NonNullMetadata key, Metadata value);
void removeEntry(MapEntry entry);
} | 9,574 |
0 | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint/mutable/MutableBeanArgument.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.blueprint.mutable;
import org.osgi.service.blueprint.reflect.BeanArgument;
import org.osgi.service.blueprint.reflect.Metadata;
/**
* A mutable version of the <code>BeanArgument</code> that allows modifications.
*
* @version $Rev$, $Date$
*/
public interface MutableBeanArgument extends BeanArgument {
void setValue(Metadata value);
void setValueType(String valueType);
void setIndex(int index);
}
| 9,575 |
0 | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint/mutable/MutableBeanProperty.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.blueprint.mutable;
import org.osgi.service.blueprint.reflect.BeanProperty;
import org.osgi.service.blueprint.reflect.Metadata;
/**
* A mutable version of the <code>BeanProperty</code> that allows modifications.
*
* @version $Rev$, $Date$
*/
public interface MutableBeanProperty extends BeanProperty {
void setName(String name);
void setValue(Metadata value);
}
| 9,576 |
0 | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint/mutable/MutableMapEntry.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.blueprint.mutable;
import org.osgi.service.blueprint.reflect.MapEntry;
import org.osgi.service.blueprint.reflect.Metadata;
import org.osgi.service.blueprint.reflect.NonNullMetadata;
/**
* A mutable version of the <code>MapEntry</code> that allows modifications.
*
* @version $Rev$, $Date$
*/
public interface MutableMapEntry extends MapEntry {
void setKey(NonNullMetadata key);
void setValue(Metadata value);
} | 9,577 |
0 | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint/mutable/MutableServiceMetadata.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.blueprint.mutable;
import org.osgi.service.blueprint.reflect.MapEntry;
import org.osgi.service.blueprint.reflect.Metadata;
import org.osgi.service.blueprint.reflect.NonNullMetadata;
import org.osgi.service.blueprint.reflect.RegistrationListener;
import org.osgi.service.blueprint.reflect.ServiceMetadata;
import org.osgi.service.blueprint.reflect.Target;
/**
* A mutable version of the <code>ServiceMetadata</code> that allows modifications.
*
* @version $Rev$, $Date$
*/
public interface MutableServiceMetadata extends ServiceMetadata, MutableComponentMetadata {
void setServiceComponent(Target serviceComponent);
void addInterface(String interfaceName);
void removeInterface(String interfaceName);
void setAutoExport(int autoExportMode);
void addServiceProperty(MapEntry serviceProperty);
MapEntry addServiceProperty(NonNullMetadata key, Metadata value);
void removeServiceProperty(MapEntry serviceProperty);
void setRanking(int ranking);
void addRegistrationListener(RegistrationListener listener);
RegistrationListener addRegistrationListener(Target listenerComponent,
String registrationMethodName,
String unregistrationMethodName);
void removeRegistrationListener(RegistrationListener listener);
} | 9,578 |
0 | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint/mutable/MutableReferenceListMetadata.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.blueprint.mutable;
import org.apache.aries.blueprint.ExtendedReferenceListMetadata;
/**
* A mutable version of the <code>RefCollectionMetadata</code> that allows modifications.
*
* @version $Rev$, $Date$
*/
public interface MutableReferenceListMetadata extends ExtendedReferenceListMetadata, MutableServiceReferenceMetadata {
void setMemberType(int memberType);
} | 9,579 |
0 | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint/mutable/MutableIdRefMetadata.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.blueprint.mutable;
import org.osgi.service.blueprint.reflect.IdRefMetadata;
/**
* A mutable version of the <code>IdRefMetadata</code> that allows modifications.
*
* @version $Rev$, $Date$
*/
public interface MutableIdRefMetadata extends IdRefMetadata {
void setComponentId(String componentId);
}
| 9,580 |
0 | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint/mutable/MutableRefMetadata.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.blueprint.mutable;
import org.osgi.service.blueprint.reflect.RefMetadata;
/**
* A mutable version of the <code>RefMetadata</code> that allows modifications.
*
* @version $Rev$, $Date$
*/
public interface MutableRefMetadata extends RefMetadata {
void setComponentId(String componentId);
}
| 9,581 |
0 | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint/mutable/MutableReferenceListener.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.blueprint.mutable;
import org.osgi.service.blueprint.reflect.ReferenceListener;
import org.osgi.service.blueprint.reflect.Target;
/**
* A mutable version of the <code>Listener</code> that allows modifications.
*
* @version $Rev$, $Date$
*/
public interface MutableReferenceListener extends ReferenceListener {
void setListenerComponent(Target listenerComponent);
void setBindMethod(String bindMethodName);
void setUnbindMethod(String unbindMethodName);
}
| 9,582 |
0 | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint/mutable/MutableMapMetadata.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.blueprint.mutable;
import org.osgi.service.blueprint.reflect.MapEntry;
import org.osgi.service.blueprint.reflect.MapMetadata;
import org.osgi.service.blueprint.reflect.Metadata;
import org.osgi.service.blueprint.reflect.NonNullMetadata;
/**
* A mutable version of the <code>MapMetadata</code> that allows modifications.
*
* @version $Rev$, $Date$
*/
public interface MutableMapMetadata extends MapMetadata {
void setKeyType(String keyType);
void setValueType(String valueType);
void addEntry(MapEntry entry);
MapEntry addEntry(NonNullMetadata key, Metadata value);
void removeEntry(MapEntry entry);
} | 9,583 |
0 | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint/mutable/MutableServiceReferenceMetadata.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.blueprint.mutable;
import org.apache.aries.blueprint.ExtendedServiceReferenceMetadata;
import org.osgi.service.blueprint.reflect.ReferenceListener;
import org.osgi.service.blueprint.reflect.Target;
import org.osgi.framework.BundleContext;
import org.osgi.service.blueprint.reflect.ValueMetadata;
/**
* A mutable version of the <code>ServiceReferenceMetadata</code> that allows modifications.
*
* @version $Rev$, $Date$
*/
public interface MutableServiceReferenceMetadata extends ExtendedServiceReferenceMetadata, MutableComponentMetadata {
void setAvailability(int availability);
void setInterface(String interfaceName);
void setComponentName(String componentName);
void addServiceListener(ReferenceListener listener);
ReferenceListener addServiceListener(Target listenerComponent,
String bindMethodName,
String unbindMethodName);
void removeReferenceListener(ReferenceListener listener);
void setProxyMethod(int proxyMethod);
void setFilter(String filter);
void setRuntimeInterface(Class clazz);
/**
* Used to set a {@link BundleContext} for this reference lookup. If this
* is set to null (or left unset) then the bundle context of the blueprint
* bundle will be used (normal behaviour)
* @param bc
*/
void setBundleContext(BundleContext bc);
void setExtendedFilter(ValueMetadata filter);
}
| 9,584 |
0 | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint/mutable/MutableCollectionMetadata.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.blueprint.mutable;
import org.osgi.service.blueprint.reflect.CollectionMetadata;
import org.osgi.service.blueprint.reflect.Metadata;
/**
* A mutable version of the <code>CollectionMetadata</code> that allows modifications.
*
* @version $Rev$, $Date$
*/
public interface MutableCollectionMetadata extends CollectionMetadata {
void setCollectionClass(Class clazz);
void setValueType(String valueType);
void addValue(Metadata value);
void removeValue(Metadata value);
} | 9,585 |
0 | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint/mutable/MutableBeanMetadata.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.blueprint.mutable;
import org.apache.aries.blueprint.ExtendedBeanMetadata;
import org.osgi.service.blueprint.reflect.BeanArgument;
import org.osgi.service.blueprint.reflect.BeanProperty;
import org.osgi.service.blueprint.reflect.Metadata;
import org.osgi.service.blueprint.reflect.Target;
/**
* A mutable version of the <code>BeanMetadata</code> that allows modifications.
*
* @version $Rev$, $Date$
*/
public interface MutableBeanMetadata extends ExtendedBeanMetadata, MutableComponentMetadata {
void setClassName(String className);
void setInitMethod(String initMethodName);
void setDestroyMethod(String destroyMethodName);
void addArgument(BeanArgument argument);
BeanArgument addArgument(Metadata value, String valueType, int index);
void removeArgument(BeanArgument argument);
void addProperty(BeanProperty property);
BeanProperty addProperty(String name, Metadata value);
void removeProperty(BeanProperty property);
void setFactoryMethod(String factoryMethodName);
void setFactoryComponent(Target factoryComponent);
void setScope(String scope);
void setRuntimeClass(Class runtimeClass);
void setProcessor(boolean processor);
void setFieldInjection(boolean allowFieldInjection);
void setRawConversion(boolean rawConversion);
void setNonStandardSetters(boolean nonStandardSetters);
}
| 9,586 |
0 | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint/mutable/MutableReferenceMetadata.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.blueprint.mutable;
import java.util.Collection;
import org.apache.aries.blueprint.ExtendedReferenceMetadata;
/**
* A mutable version of the <code>ReferenceMetadata</code> that allows modifications.
*
* @version $Rev$, $Date$
*/
public interface MutableReferenceMetadata extends ExtendedReferenceMetadata, MutableServiceReferenceMetadata {
void setTimeout(long timeout);
void setDefaultBean(String value);
void setProxyChildBeanClasses(Collection<Class<?>> classes);
void setExtraInterfaces(Collection<String> interfaces);
void setDamping(int damping);
void setLifecycle(int lifecycle);
} | 9,587 |
0 | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint/mutable/MutableComponentMetadata.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.blueprint.mutable;
import java.util.List;
import org.osgi.service.blueprint.reflect.ComponentMetadata;
/**
* A mutable version of the <code>ComponentMetadata</code> that allows modifications.
*
* @version $Rev$, $Date$
*/
public interface MutableComponentMetadata extends ComponentMetadata {
void setId(String id);
void setActivation(int activation);
void setDependsOn(List<String> dependsOn);
void addDependsOn(String dependency);
void removeDependsOn(String dependency);
} | 9,588 |
0 | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint/mutable/MutableRegistrationListener.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.blueprint.mutable;
import org.osgi.service.blueprint.reflect.RegistrationListener;
import org.osgi.service.blueprint.reflect.Target;
/**
* A mutable version of the <code>RegistrationListener</code> that allows modifications.
*
* @version $Rev$, $Date$
*/
public interface MutableRegistrationListener extends RegistrationListener {
void setListenerComponent(Target listenerComponent);
void setRegistrationMethod(String registrationMethodName);
void setUnregistrationMethod(String unregistrationMethodName);
} | 9,589 |
0 | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint/mutable/MutablePassThroughMetadata.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.blueprint.mutable;
import org.apache.aries.blueprint.PassThroughMetadata;
/**
* The mutable version of the PassThroughMetadata interface
*/
public interface MutablePassThroughMetadata extends PassThroughMetadata, MutableComponentMetadata {
void setObject(Object object);
}
| 9,590 |
0 | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint/mutable/MutableValueMetadata.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.blueprint.mutable;
import org.apache.aries.blueprint.ExtendedValueMetadata;
import org.osgi.service.blueprint.reflect.ValueMetadata;
/**
* A mutable version of the <code>ValueMetadata</code> that allows modifications.
*
* @version $Rev$, $Date$
*/
public interface MutableValueMetadata extends ExtendedValueMetadata {
void setStringValue(String stringValue);
void setType(String type);
void setValue(Object value);
}
| 9,591 |
0 | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint/reflect/PropsMetadataImpl.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.blueprint.reflect;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.apache.aries.blueprint.mutable.MutablePropsMetadata;
import org.osgi.service.blueprint.reflect.MapEntry;
import org.osgi.service.blueprint.reflect.Metadata;
import org.osgi.service.blueprint.reflect.NonNullMetadata;
import org.osgi.service.blueprint.reflect.PropsMetadata;
/**
* Implementation of PropsMetadata
*
* @version $Rev$, $Date$
*/
public class PropsMetadataImpl implements MutablePropsMetadata {
private List<MapEntry> entries;
public PropsMetadataImpl() {
}
public PropsMetadataImpl(List<MapEntry> entries) {
this.entries = entries;
}
public PropsMetadataImpl(PropsMetadata source) {
for (MapEntry entry : source.getEntries()) {
addEntry(new MapEntryImpl(entry));
}
}
public List<MapEntry> getEntries() {
if (this.entries == null) {
return Collections.emptyList();
} else {
return Collections.unmodifiableList(this.entries);
}
}
public void setEntries(List<MapEntry> entries) {
this.entries = entries != null ? new ArrayList<MapEntry>(entries) : null;
}
public void addEntry(MapEntry entry) {
if (this.entries == null) {
this.entries = new ArrayList<MapEntry>();
}
this.entries.add(entry);
}
public MapEntry addEntry(NonNullMetadata key, Metadata value) {
MapEntry entry = new MapEntryImpl(key, value);
addEntry(entry);
return entry;
}
public void removeEntry(MapEntry entry) {
if (this.entries != null) {
this.entries.remove(entry);
}
}
@Override
public String toString() {
return "PropsMetadata[" +
"entries=" + entries +
']';
}
}
| 9,592 |
0 | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint/reflect/ReferenceMetadataImpl.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.blueprint.reflect;
import java.util.Collection;
import java.util.Collections;
import org.apache.aries.blueprint.mutable.MutableReferenceMetadata;
import org.osgi.service.blueprint.reflect.ReferenceMetadata;
/**
* Implementation of ReferenceMetadata
*
* @version $Rev$, $Date$
*/
public class ReferenceMetadataImpl extends ServiceReferenceMetadataImpl implements MutableReferenceMetadata {
private long timeout;
private String defaultBeanId;
private Collection<Class<?>> proxyChildBeanClasses;
private Collection<String> extraInterfaces;
private int damping;
private int lifecycle;
public ReferenceMetadataImpl() {
}
public ReferenceMetadataImpl(ReferenceMetadata source) {
super(source);
timeout = source.getTimeout();
}
public long getTimeout() {
return timeout;
}
public void setTimeout(long timeout) {
this.timeout = timeout;
}
public void setDefaultBean(String defaultBeanId) {
this.defaultBeanId = defaultBeanId;
}
public String getDefaultBean() {
return defaultBeanId;
}
@Override
public String toString() {
return "ReferenceMetadata[" +
"id='" + id + '\'' +
", activation=" + activation +
", dependsOn=" + dependsOn +
", availability=" + availability +
", interface='" + interfaceName + '\'' +
", componentName='" + componentName + '\'' +
", filter='" + filter + '\'' +
", referenceListeners=" + referenceListeners +
", timeout=" + timeout +
", additonalInterfaces=" + getExtraInterfaces() +
", damping=" + getDamping() +
", lifecycle=" + getLifecycle() +
']';
}
public Collection<Class<?>> getProxyChildBeanClasses() {
return proxyChildBeanClasses;
}
public void setProxyChildBeanClasses(Collection<Class<?>> c) {
proxyChildBeanClasses = c;
}
public Collection<String> getExtraInterfaces() {
if (extraInterfaces == null) {
return Collections.emptyList();
}
return extraInterfaces;
}
public void setExtraInterfaces(Collection<String> interfaces) {
extraInterfaces = interfaces;
}
public int getDamping() {
return damping;
}
public void setDamping(int damping) {
this.damping = damping;
}
public int getLifecycle() {
return lifecycle;
}
public void setLifecycle(int lifecycle) {
this.lifecycle = lifecycle;
}
}
| 9,593 |
0 | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint/reflect/ServiceMetadataImpl.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.blueprint.reflect;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import org.apache.aries.blueprint.mutable.MutableServiceMetadata;
import org.osgi.service.blueprint.reflect.MapEntry;
import org.osgi.service.blueprint.reflect.Metadata;
import org.osgi.service.blueprint.reflect.NonNullMetadata;
import org.osgi.service.blueprint.reflect.RegistrationListener;
import org.osgi.service.blueprint.reflect.ServiceMetadata;
import org.osgi.service.blueprint.reflect.Target;
/**
* Implementation of ServiceMetadata
*
* @version $Rev$, $Date$
*/
public class ServiceMetadataImpl extends ComponentMetadataImpl implements MutableServiceMetadata {
private Target serviceComponent;
private List<String> interfaceNames;
private int autoExport;
private List<MapEntry> serviceProperties;
private int ranking;
private Collection<RegistrationListener> registrationListeners;
public ServiceMetadataImpl() {
}
public ServiceMetadataImpl(ServiceMetadata source) {
super(source);
this.serviceComponent = MetadataUtil.cloneTarget(source.getServiceComponent());
this.interfaceNames = new ArrayList<String>(source.getInterfaces());
this.autoExport = source.getAutoExport();
for (MapEntry serviceProperty : source.getServiceProperties()) {
addServiceProperty(new MapEntryImpl(serviceProperty));
}
this.ranking = source.getRanking();
for (RegistrationListener listener : source.getRegistrationListeners()) {
addRegistrationListener(new RegistrationListenerImpl(listener));
}
}
public Target getServiceComponent() {
return serviceComponent;
}
public void setServiceComponent(Target exportedComponent) {
this.serviceComponent = exportedComponent;
}
public List<String> getInterfaces() {
if (this.interfaceNames == null) {
return Collections.emptyList();
} else {
return Collections.unmodifiableList(this.interfaceNames);
}
}
public void setInterfaceNames(List<String> interfaceNames) {
this.interfaceNames = interfaceNames != null ? new ArrayList<String>(interfaceNames) : null;
}
public void addInterface(String interfaceName) {
if (this.interfaceNames == null) {
this.interfaceNames = new ArrayList<String>();
}
this.interfaceNames.add(interfaceName);
}
public void removeInterface(String interfaceName) {
if (this.interfaceNames != null) {
this.interfaceNames.remove(interfaceName);
}
}
public int getAutoExport() {
return this.autoExport;
}
public void setAutoExport(int autoExport) {
this.autoExport = autoExport;
}
public List<MapEntry> getServiceProperties() {
if (this.serviceProperties == null) {
return Collections.emptyList();
} else {
return Collections.unmodifiableList(this.serviceProperties);
}
}
public void setServiceProperties(List<MapEntry> serviceProperties) {
this.serviceProperties = serviceProperties != null ? new ArrayList<MapEntry>(serviceProperties) : null;
}
public void addServiceProperty(MapEntry serviceProperty) {
if (this.serviceProperties == null) {
this.serviceProperties = new ArrayList<MapEntry>();
}
this.serviceProperties.add(serviceProperty);
}
public MapEntry addServiceProperty(NonNullMetadata key, Metadata value) {
MapEntry serviceProperty = new MapEntryImpl(key, value);
addServiceProperty(serviceProperty);
return serviceProperty;
}
public void removeServiceProperty(MapEntry serviceProperty) {
if (this.serviceProperties != null) {
this.serviceProperties.remove(serviceProperty);
}
}
public int getRanking() {
return ranking;
}
public void setRanking(int ranking) {
this.ranking = ranking;
}
public Collection<RegistrationListener> getRegistrationListeners() {
if (this.registrationListeners == null) {
return Collections.emptySet();
} else {
return Collections.unmodifiableCollection(this.registrationListeners);
}
}
public void setRegistrationListeners(Collection<RegistrationListener> registrationListeners) {
this.registrationListeners = registrationListeners;
}
public void addRegistrationListener(RegistrationListener registrationListenerMetadata) {
if (this.registrationListeners == null) {
this.registrationListeners = new ArrayList<RegistrationListener>();
}
this.registrationListeners.add(registrationListenerMetadata);
}
public RegistrationListener addRegistrationListener(Target listenerComponent, String registrationMethodName, String unregistrationMethodName) {
RegistrationListener listener = new RegistrationListenerImpl(listenerComponent, registrationMethodName, unregistrationMethodName);
addRegistrationListener(listener);
return listener;
}
public void removeRegistrationListener(RegistrationListener listener) {
if (this.registrationListeners != null) {
this.registrationListeners.remove(listener);
}
}
@Override
public String toString() {
return "ServiceMetadata[" +
"id='" + id + '\'' +
", activation=" + activation +
", dependsOn=" + dependsOn +
", exportedComponent=" + serviceComponent +
", interfaces=" + interfaceNames +
", autoExportMode=" + autoExport +
", serviceProperties=" + serviceProperties +
", ranking=" + ranking +
", registrationListeners=" + registrationListeners +
']';
}
}
| 9,594 |
0 | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint/reflect/BeanArgumentImpl.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.blueprint.reflect;
import org.apache.aries.blueprint.mutable.MutableBeanArgument;
import org.osgi.service.blueprint.reflect.BeanArgument;
import org.osgi.service.blueprint.reflect.Metadata;
/**
* Implementation of BeanArgument
*
* @version $Rev$, $Date$
*/
public class BeanArgumentImpl implements MutableBeanArgument {
private Metadata value;
private String valueType;
private int index = -1;
public BeanArgumentImpl() {
}
public BeanArgumentImpl(Metadata value, String valueType, int index) {
this.value = value;
this.valueType = valueType;
this.index = index;
}
public BeanArgumentImpl(BeanArgument source) {
value = MetadataUtil.cloneMetadata(source.getValue());
valueType = source.getValueType();
index = source.getIndex();
}
public Metadata getValue() {
return value;
}
public void setValue(Metadata value) {
this.value = value;
}
public String getValueType() {
return valueType;
}
public void setValueType(String valueType) {
this.valueType = valueType;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
@Override
public String toString() {
return "BeanArgument[" +
"value=" + value +
", valueType='" + valueType + '\'' +
", index=" + index +
']';
}
}
| 9,595 |
0 | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint/reflect/BeanPropertyImpl.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.blueprint.reflect;
import org.apache.aries.blueprint.mutable.MutableBeanProperty;
import org.osgi.service.blueprint.reflect.BeanProperty;
import org.osgi.service.blueprint.reflect.Metadata;
/**
* Implementation of BeanProperty
*
* @version $Rev$, $Date$
*/
public class BeanPropertyImpl implements MutableBeanProperty {
private String name;
private Metadata value;
public BeanPropertyImpl() {
}
public BeanPropertyImpl(String name, Metadata value) {
this.name = name;
this.value = value;
}
public BeanPropertyImpl(BeanProperty source) {
this.name = source.getName();
this.value = MetadataUtil.cloneMetadata(source.getValue());
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Metadata getValue() {
return value;
}
public void setValue(Metadata value) {
this.value = value;
}
@Override
public String toString() {
return "BeanProperty[" +
"name='" + name + '\'' +
", value=" + value +
']';
}
} | 9,596 |
0 | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint/reflect/MetadataUtil.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.blueprint.reflect;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import org.apache.aries.blueprint.PassThroughMetadata;
import org.osgi.service.blueprint.reflect.BeanArgument;
import org.osgi.service.blueprint.reflect.BeanMetadata;
import org.osgi.service.blueprint.reflect.CollectionMetadata;
import org.osgi.service.blueprint.reflect.ComponentMetadata;
import org.osgi.service.blueprint.reflect.IdRefMetadata;
import org.osgi.service.blueprint.reflect.MapMetadata;
import org.osgi.service.blueprint.reflect.Metadata;
import org.osgi.service.blueprint.reflect.NullMetadata;
import org.osgi.service.blueprint.reflect.PropsMetadata;
import org.osgi.service.blueprint.reflect.ReferenceListMetadata;
import org.osgi.service.blueprint.reflect.RefMetadata;
import org.osgi.service.blueprint.reflect.ReferenceMetadata;
import org.osgi.service.blueprint.reflect.ServiceMetadata;
import org.osgi.service.blueprint.reflect.Target;
import org.osgi.service.blueprint.reflect.ValueMetadata;
/**
* A utility class that handles cloning various polymorphic
* bits of metadata into concrete class implementations.
*
* @version $Rev$, $Date$
*/
public class MetadataUtil {
public static final Comparator<BeanArgument> BEAN_COMPARATOR = new BeanArgumentComparator();
static public Metadata cloneMetadata(Metadata source) {
if (source == null) {
return null;
}
else if (source instanceof MapMetadata) {
return new MapMetadataImpl((MapMetadata)source);
}
else if (source instanceof NullMetadata) {
return NullMetadata.NULL;
}
else if (source instanceof PropsMetadata) {
return new PropsMetadataImpl((PropsMetadata)source);
}
else if (source instanceof RefMetadata) {
return new RefMetadataImpl((RefMetadata)source);
}
else if (source instanceof IdRefMetadata) {
return new IdRefMetadataImpl((IdRefMetadata)source);
}
else if (source instanceof ValueMetadata) {
return new ValueMetadataImpl((ValueMetadata)source);
}
else if (source instanceof BeanMetadata) {
return new BeanMetadataImpl((BeanMetadata)source);
}
else if (source instanceof ReferenceListMetadata) {
return new ReferenceListMetadataImpl((ReferenceListMetadata)source);
}
else if (source instanceof ServiceMetadata) {
return new ServiceMetadataImpl((ServiceMetadata)source);
}
else if (source instanceof ReferenceMetadata) {
return new ReferenceMetadataImpl((ReferenceMetadata)source);
}
else if (source instanceof CollectionMetadata) {
return new CollectionMetadataImpl((CollectionMetadata)source);
}
else if (source instanceof PassThroughMetadata) {
return new PassThroughMetadataImpl((PassThroughMetadata)source);
}
throw new RuntimeException("Unknown Metadata type received: " + source.getClass().getName());
}
/**
* Clone a component metadata item, returning a mutable
* instance.
*
* @param source The source metadata item.
*
* @return A mutable instance of this metadata item.
*/
static public ComponentMetadata cloneComponentMetadata(ComponentMetadata source) {
return (ComponentMetadata) cloneMetadata(source);
}
/**
* Clone a target item, returning a mutable
* instance.
*
* @param source The source target item.
*
* @return A mutable instance of this target item.
*/
static public Target cloneTarget(Target source) {
return (Target) cloneMetadata(source);
}
/**
* Create a new metadata instance of the given type
*
* @param type the class of the Metadata object to create
* @param <T>
* @return a new instance
*/
public static <T extends Metadata> T createMetadata(Class<T> type) {
if (MapMetadata.class.isAssignableFrom(type)) {
return type.cast(new MapMetadataImpl());
} else if (NullMetadata.class.isAssignableFrom(type)) {
return type.cast(NullMetadata.NULL);
} else if (PropsMetadata.class.isAssignableFrom(type)) {
return type.cast(new PropsMetadataImpl());
} else if (RefMetadata.class.isAssignableFrom(type)) {
return type.cast(new RefMetadataImpl());
} else if (IdRefMetadata.class.isAssignableFrom(type)) {
return type.cast(new IdRefMetadataImpl());
} else if (ValueMetadata.class.isAssignableFrom(type)) {
return type.cast(new ValueMetadataImpl());
} else if (BeanMetadata.class.isAssignableFrom(type)) {
return type.cast(new BeanMetadataImpl());
} else if (ReferenceListMetadata.class.isAssignableFrom(type)) {
return type.cast(new ReferenceListMetadataImpl());
} else if (ServiceMetadata.class.isAssignableFrom(type)) {
return type.cast(new ServiceMetadataImpl());
} else if (ReferenceMetadata.class.isAssignableFrom(type)) {
return type.cast(new ReferenceMetadataImpl());
} else if (CollectionMetadata.class.isAssignableFrom(type)) {
return type.cast(new CollectionMetadataImpl());
} else if (PassThroughMetadata.class.isAssignableFrom(type)) {
return type.cast(new PassThroughMetadataImpl());
} else {
throw new IllegalArgumentException("Unsupport metadata type: " + (type != null ? type.getName() : null));
}
}
public static List<BeanArgument> validateBeanArguments(List<BeanArgument> arguments) {
if (arguments == null || arguments.isEmpty()) {
return arguments;
}
// check if all or none arguments have index attribute
boolean hasIndexFirst = (arguments.get(0).getIndex() > -1);
for (int i = 1; i < arguments.size(); i++) {
boolean hasIndex = (arguments.get(i).getIndex() > -1);
if ( (hasIndexFirst && !hasIndex) ||
(!hasIndexFirst && hasIndex) ) {
throw new IllegalArgumentException("Index attribute must be specified either on all or none constructor arguments");
}
}
if (hasIndexFirst) {
// sort the arguments
List<BeanArgument> argumentsCopy = new ArrayList<BeanArgument>(arguments);
Collections.sort(argumentsCopy, MetadataUtil.BEAN_COMPARATOR);
arguments = argumentsCopy;
// check if the indexes are sequential
for (int i = 0; i < arguments.size(); i++) {
int index = arguments.get(i).getIndex();
if (index > i) {
throw new IllegalArgumentException("Missing attribute index");
} else if (index < i) {
throw new IllegalArgumentException("Duplicate attribute index");
} // must be the same
}
}
return arguments;
}
public static boolean isPrototypeScope(BeanMetadata metadata) {
return (BeanMetadata.SCOPE_PROTOTYPE.equals(metadata.getScope()) ||
(metadata.getScope() == null && metadata.getId() == null));
}
public static boolean isSingletonScope(BeanMetadata metadata) {
return (BeanMetadata.SCOPE_SINGLETON.equals(metadata.getScope()) ||
(metadata.getScope() == null && metadata.getId() != null));
}
public static boolean isCustomScope(BeanMetadata metadata) {
return (metadata.getScope() != null &&
!BeanMetadata.SCOPE_PROTOTYPE.equals(metadata.getScope()) &&
!BeanMetadata.SCOPE_SINGLETON.equals(metadata.getScope()));
}
private static class BeanArgumentComparator implements Comparator<BeanArgument>, Serializable {
public int compare(BeanArgument object1, BeanArgument object2) {
return object1.getIndex() - object2.getIndex();
}
}
}
| 9,597 |
0 | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint/reflect/ValueMetadataImpl.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.blueprint.reflect;
import org.apache.aries.blueprint.ExtendedValueMetadata;
import org.apache.aries.blueprint.mutable.MutableValueMetadata;
import org.osgi.service.blueprint.reflect.ValueMetadata;
/**
* Implementation of ValueMetadata
*
* @version $Rev$, $Date$
*/
public class ValueMetadataImpl implements MutableValueMetadata {
private String stringValue;
private String type;
private Object value;
public ValueMetadataImpl() {
}
public ValueMetadataImpl(String stringValue) {
this.stringValue = stringValue;
}
public ValueMetadataImpl(String stringValue, String type) {
this.stringValue = stringValue;
this.type = type;
}
public ValueMetadataImpl(Object value) {
this.value = value;
}
public ValueMetadataImpl(ValueMetadata source) {
this.stringValue = source.getStringValue();
this.type = source.getType();
if (source instanceof ExtendedValueMetadata) {
this.value = ((ExtendedValueMetadata) source).getValue();
}
}
public String getStringValue() {
return stringValue;
}
public void setStringValue(String stringValue) {
this.stringValue = stringValue;
}
public String getType() {
return type;
}
public void setType(String typeName) {
this.type = typeName;
}
public Object getValue() {
return value;
}
public void setValue(Object value) {
this.value = value;
}
@Override
public String toString() {
return "ValueMetadata[" +
"stringValue='" + stringValue + '\'' +
", type='" + type + '\'' +
", value='" + value + '\'' +
']';
}
}
| 9,598 |
0 | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint | Create_ds/aries/blueprint/blueprint-parser/src/main/java/org/apache/aries/blueprint/reflect/MapMetadataImpl.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.blueprint.reflect;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.apache.aries.blueprint.mutable.MutableMapMetadata;
import org.osgi.service.blueprint.reflect.MapEntry;
import org.osgi.service.blueprint.reflect.MapMetadata;
import org.osgi.service.blueprint.reflect.Metadata;
import org.osgi.service.blueprint.reflect.NonNullMetadata;
/**
* Implementation of MapMetadata
*
* @version $Rev$, $Date$
*/
public class MapMetadataImpl implements MutableMapMetadata {
private String keyType;
private String valueType;
private List<MapEntry> entries;
public MapMetadataImpl() {
}
public MapMetadataImpl(String keyType, String valueType, List<MapEntry> entries) {
this.keyType = keyType;
this.valueType = valueType;
this.entries = entries;
}
public MapMetadataImpl(MapMetadata source) {
this.valueType = source.getValueType();
this.keyType = source.getKeyType();
for (MapEntry entry : source.getEntries()) {
addEntry(new MapEntryImpl(entry));
}
}
public String getKeyType() {
return this.keyType;
}
public void setKeyType(String keyTypeName) {
this.keyType = keyTypeName;
}
public String getValueType() {
return this.valueType;
}
public void setValueType(String valueTypeName) {
this.valueType = valueTypeName;
}
public List<MapEntry> getEntries() {
if (this.entries == null) {
return Collections.emptyList();
} else {
return Collections.unmodifiableList(this.entries);
}
}
public void setEntries(List<MapEntry> entries) {
this.entries = entries != null ? new ArrayList<MapEntry>(entries) : null;
}
public void addEntry(MapEntry entry) {
if (this.entries == null) {
this.entries = new ArrayList<MapEntry>();
}
this.entries.add(entry);
}
public MapEntry addEntry(NonNullMetadata key, Metadata value) {
MapEntry entry = new MapEntryImpl(key, value);
addEntry(entry);
return entry;
}
public void removeEntry(MapEntry entry) {
if (this.entries != null) {
this.entries.remove(entry);
}
}
@Override
public String toString() {
return "MapMetadata[" +
"keyType='" + keyType + '\'' +
", valueType='" + valueType + '\'' +
", entries=" + entries +
']';
}
}
| 9,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.