Search in sources :

Example 11 with Recipe

use of org.apache.aries.blueprint.di.Recipe in project aries by apache.

the class BeanRecipe method setProperty.

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");
    }
}
Also used : PropertyDescriptor(org.apache.aries.blueprint.utils.ReflectionUtils.PropertyDescriptor) ComponentDefinitionException(org.osgi.service.blueprint.container.ComponentDefinitionException) Recipe(org.apache.aries.blueprint.di.Recipe) AbstractRecipe(org.apache.aries.blueprint.di.AbstractRecipe) ComponentDefinitionException(org.osgi.service.blueprint.container.ComponentDefinitionException) InvocationTargetException(java.lang.reflect.InvocationTargetException) UnableToProxyException(org.apache.aries.proxy.UnableToProxyException)

Example 12 with Recipe

use of org.apache.aries.blueprint.di.Recipe in project aries by apache.

the class BeanRecipe method getInstance.

private Object getInstance() throws ComponentDefinitionException {
    Object instance;
    // 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) {
        // look for instance method on factory object
        Object factoryObj = factory.create();
        /* BLUEPRINT-NOOSGI
            if (factoryObj instanceof ReferenceRecipe.ServiceProxyWrapper) {
                try {
                    factoryObj = ((ReferenceRecipe.ServiceProxyWrapper) factoryObj).convert(new ReifiedType(Object.class));
                } catch (Exception e) {
                    throw new ComponentDefinitionException("Error when instantiating bean " + getName() + " of class " + getType(), getRealCause(e));
                }
            } else*/
        if (factoryObj instanceof UnwrapperedBeanHolder) {
            factoryObj = wrap((UnwrapperedBeanHolder) factoryObj, Object.class);
        }
        // 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();
                instance = invoke(match.getKey(), factoryObj, match.getValue().toArray());
            } catch (Throwable e) {
                throw new ComponentDefinitionException("Error when instantiating bean " + getName() + " of class " + getType(), getRealCause(e));
            }
        } else if (matches.size() == 0) {
            throw new ComponentDefinitionException("Unable to find a matching factory method " + factoryMethod + " on class " + factoryObj.getClass().getName() + " for arguments " + args + " when instanciating bean " + getName());
        } else {
            throw new ComponentDefinitionException("Multiple matching factory methods " + factoryMethod + " found on class " + factoryObj.getClass().getName() + " for arguments " + args + " when instanciating bean " + getName() + ": " + matches.keySet());
        }
    } else if (factoryMethod != null) {
        // 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();
                instance = invoke(match.getKey(), null, match.getValue().toArray());
            } catch (Throwable e) {
                throw new ComponentDefinitionException("Error when instanciating bean " + getName() + " of class " + getType(), getRealCause(e));
            }
        } else if (matches.size() == 0) {
            throw new ComponentDefinitionException("Unable to find a matching factory method " + factoryMethod + " on class " + getType().getName() + " for arguments " + args + " when instanciating bean " + getName());
        } else {
            throw new ComponentDefinitionException("Multiple matching factory methods " + factoryMethod + " found on class " + getType().getName() + " for arguments " + args + " when instanciating bean " + getName() + ": " + matches.keySet());
        }
    } else {
        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();
                instance = newInstance(match.getKey(), match.getValue().toArray());
            } catch (Throwable e) {
                throw new ComponentDefinitionException("Error when instanciating bean " + getName() + " of class " + getType(), getRealCause(e));
            }
        } else if (matches.size() == 0) {
            throw new ComponentDefinitionException("Unable to find a matching constructor on class " + getType().getName() + " for arguments " + args + " when instanciating bean " + getName());
        } else {
            throw new ComponentDefinitionException("Multiple matching constructors found on class " + getType().getName() + " for arguments " + args + " when instanciating bean " + getName() + ": " + matches.keySet());
        }
    }
    return instance;
}
Also used : ComponentDefinitionException(org.osgi.service.blueprint.container.ComponentDefinitionException) Recipe(org.apache.aries.blueprint.di.Recipe) AbstractRecipe(org.apache.aries.blueprint.di.AbstractRecipe) ReifiedType(org.osgi.service.blueprint.container.ReifiedType) ArrayList(java.util.ArrayList) Method(java.lang.reflect.Method) ArrayList(java.util.ArrayList) List(java.util.List) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map)

Example 13 with Recipe

use of org.apache.aries.blueprint.di.Recipe in project aries by apache.

the class ReflectionUtilsTest method before.

@BeforeClass
public static void before() throws ClassNotFoundException {
    mockBlueprint = EasyMock.createNiceMock(ExtendedBlueprintContainer.class);
    final Capture<String> nameCapture = new Capture<String>();
    EasyMock.expect(mockBlueprint.loadClass(EasyMock.capture(nameCapture))).andAnswer(new IAnswer<Class<?>>() {

        public Class<?> answer() throws Throwable {
            return Thread.currentThread().getContextClassLoader().loadClass(nameCapture.getValue());
        }
    });
    EasyMock.replay(mockBlueprint);
    ExecutionContext.Holder.setContext(new ExecutionContext() {

        public void addPartialObject(String name, Object object) {
        }

        public boolean containsObject(String name) {
            return false;
        }

        public Object convert(Object value, ReifiedType type) throws Exception {
            if (type.getRawClass().equals(Inconvertible.class))
                throw new Exception();
            else if (type.getRawClass().equals(String.class))
                return String.valueOf(value);
            else if (type.getRawClass().equals(List.class)) {
                if (value == null)
                    return null;
                else if (value instanceof Collection)
                    return new ArrayList((Collection) value);
                else
                    throw new Exception();
            } else if (value == null)
                return null;
            else if (type.getRawClass().isInstance(value))
                return value;
            else
                throw new Exception();
        }

        public boolean canConvert(Object value, ReifiedType type) {
            if (value instanceof Inconvertible)
                return false;
            else if (type.getRawClass().equals(String.class))
                return true;
            else if (type.getRawClass().equals(List.class) && (value == null || value instanceof Collection))
                return true;
            else
                return false;
        }

        public Object getObject(String name) {
            return null;
        }

        public Object getPartialObject(String name) {
            return null;
        }

        public Recipe getRecipe(String name) {
            return null;
        }

        public Class loadClass(String className) throws ClassNotFoundException {
            return null;
        }

        public Recipe pop() {
            return null;
        }

        public void push(Recipe recipe) throws CircularDependencyException {
        }

        public void removePartialObject(String name) {
        }

        public Future<Object> addFullObject(String name, Future<Object> object) {
            return null;
        }
    });
}
Also used : Recipe(org.apache.aries.blueprint.di.Recipe) ReifiedType(org.osgi.service.blueprint.container.ReifiedType) ArrayList(java.util.ArrayList) Capture(org.easymock.Capture) CircularDependencyException(org.apache.aries.blueprint.di.CircularDependencyException) ComponentDefinitionException(org.osgi.service.blueprint.container.ComponentDefinitionException) ExecutionContext(org.apache.aries.blueprint.di.ExecutionContext) Collection(java.util.Collection) Future(java.util.concurrent.Future) BeforeClass(org.junit.BeforeClass) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) List(java.util.List) ExtendedBlueprintContainer(org.apache.aries.blueprint.services.ExtendedBlueprintContainer) CircularDependencyException(org.apache.aries.blueprint.di.CircularDependencyException) BeforeClass(org.junit.BeforeClass)

Example 14 with Recipe

use of org.apache.aries.blueprint.di.Recipe in project aries by apache.

the class RecipeBuilder method createBeanRecipe.

private BeanRecipe createBeanRecipe(BeanMetadata beanMetadata) {
    BeanRecipe recipe = new BeanRecipe(getName(beanMetadata.getId()), blueprintContainer, getBeanClass(beanMetadata), allowsFieldInjection(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;
}
Also used : BeanArgument(org.osgi.service.blueprint.reflect.BeanArgument) DependentComponentFactoryRecipe(org.apache.aries.blueprint.di.DependentComponentFactoryRecipe) IdRefRecipe(org.apache.aries.blueprint.di.IdRefRecipe) ComponentFactoryRecipe(org.apache.aries.blueprint.di.ComponentFactoryRecipe) MapRecipe(org.apache.aries.blueprint.di.MapRecipe) Recipe(org.apache.aries.blueprint.di.Recipe) PassThroughRecipe(org.apache.aries.blueprint.di.PassThroughRecipe) CollectionRecipe(org.apache.aries.blueprint.di.CollectionRecipe) ArrayRecipe(org.apache.aries.blueprint.di.ArrayRecipe) RefRecipe(org.apache.aries.blueprint.di.RefRecipe) ValueRecipe(org.apache.aries.blueprint.di.ValueRecipe) ArrayList(java.util.ArrayList) BeanProperty(org.osgi.service.blueprint.reflect.BeanProperty)

Example 15 with Recipe

use of org.apache.aries.blueprint.di.Recipe in project aries by apache.

the class ReferenceListRecipe method internalCreate.

@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);
    }
}
Also used : ComponentDefinitionException(org.osgi.service.blueprint.container.ComponentDefinitionException) CollectionRecipe(org.apache.aries.blueprint.di.CollectionRecipe) ValueRecipe(org.apache.aries.blueprint.di.ValueRecipe) Recipe(org.apache.aries.blueprint.di.Recipe)

Aggregations

Recipe (org.apache.aries.blueprint.di.Recipe)21 RefRecipe (org.apache.aries.blueprint.di.RefRecipe)12 CollectionRecipe (org.apache.aries.blueprint.di.CollectionRecipe)11 ArrayList (java.util.ArrayList)10 IdRefRecipe (org.apache.aries.blueprint.di.IdRefRecipe)9 ValueRecipe (org.apache.aries.blueprint.di.ValueRecipe)6 ComponentDefinitionException (org.osgi.service.blueprint.container.ComponentDefinitionException)6 MapRecipe (org.apache.aries.blueprint.di.MapRecipe)5 ArrayRecipe (org.apache.aries.blueprint.di.ArrayRecipe)4 ComponentFactoryRecipe (org.apache.aries.blueprint.di.ComponentFactoryRecipe)4 DependentComponentFactoryRecipe (org.apache.aries.blueprint.di.DependentComponentFactoryRecipe)4 PassThroughRecipe (org.apache.aries.blueprint.di.PassThroughRecipe)4 ComponentMetadata (org.osgi.service.blueprint.reflect.ComponentMetadata)4 HashMap (java.util.HashMap)3 LinkedHashMap (java.util.LinkedHashMap)3 LinkedList (java.util.LinkedList)3 List (java.util.List)3 Map (java.util.Map)3 AbstractRecipe (org.apache.aries.blueprint.di.AbstractRecipe)3 CircularDependencyException (org.apache.aries.blueprint.di.CircularDependencyException)3