Search in sources :

Example 1 with ReifiedType

use of org.osgi.service.blueprint.container.ReifiedType in project aries by apache.

the class MapRecipe method internalCreate.

protected Object internalCreate() throws ComponentDefinitionException {
    Class<?> mapType = getMap(typeClass);
    if (!ReflectionUtils.hasDefaultConstructor(mapType)) {
        throw new ComponentDefinitionException("Type does not have a default constructor " + mapType.getName());
    }
    Object o;
    try {
        o = mapType.newInstance();
    } catch (Exception e) {
        throw new ComponentDefinitionException("Error while creating set instance: " + mapType.getName());
    }
    Map instance;
    if (o instanceof Map) {
        instance = (Map) o;
    } else if (o instanceof Dictionary) {
        instance = new DummyDictionaryAsMap((Dictionary) o);
    } else {
        throw new ComponentDefinitionException("Specified map type does not implement the Map interface: " + mapType.getName());
    }
    ReifiedType defaultConvertKeyType = getType(keyType);
    ReifiedType defaultConvertValueType = getType(valueType);
    // add map entries
    try {
        for (Recipe[] entry : entries) {
            ReifiedType convertKeyType = workOutConversionType(entry[0], defaultConvertKeyType);
            Object key = convert(entry[0].create(), convertKeyType);
            // Each entry may have its own types
            ReifiedType convertValueType = workOutConversionType(entry[1], defaultConvertValueType);
            Object value = entry[1] != null ? convert(entry[1].create(), convertValueType) : null;
            instance.put(key, value);
        }
    } catch (Exception e) {
        throw new ComponentDefinitionException(e);
    }
    return instance;
}
Also used : Dictionary(java.util.Dictionary) ComponentDefinitionException(org.osgi.service.blueprint.container.ComponentDefinitionException) ReifiedType(org.osgi.service.blueprint.container.ReifiedType) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ConcurrentMap(java.util.concurrent.ConcurrentMap) LinkedHashMap(java.util.LinkedHashMap) AbstractMap(java.util.AbstractMap) TreeMap(java.util.TreeMap) Map(java.util.Map) SortedMap(java.util.SortedMap) ComponentDefinitionException(org.osgi.service.blueprint.container.ComponentDefinitionException)

Example 2 with ReifiedType

use of org.osgi.service.blueprint.container.ReifiedType in project aries by apache.

the class AggregateConverter method convertToCollection.

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;
    }
}
Also used : ReifiedType(org.osgi.service.blueprint.container.ReifiedType) Collection(java.util.Collection)

Example 3 with ReifiedType

use of org.osgi.service.blueprint.container.ReifiedType in project aries by apache.

the class AggregateConverter method convertToDictionary.

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;
    }
}
Also used : Dictionary(java.util.Dictionary) Enumeration(java.util.Enumeration) Hashtable(java.util.Hashtable) ReifiedType(org.osgi.service.blueprint.container.ReifiedType) HashMap(java.util.HashMap) Map(java.util.Map)

Example 4 with ReifiedType

use of org.osgi.service.blueprint.container.ReifiedType in project aries by apache.

the class BeanRecipe method findMatchingConstructors.

private Map<Constructor, List<Object>> findMatchingConstructors(Class type, List<Object> args, List<ReifiedType> types) {
    Map<Constructor, List<Object>> matches = new HashMap<Constructor, List<Object>>();
    // Get constructors
    List<Constructor> constructors = new ArrayList<Constructor>(Arrays.asList(type.getConstructors()));
    // Discard any signature with wrong cardinality
    for (Iterator<Constructor> it = constructors.iterator(); it.hasNext(); ) {
        if (it.next().getParameterTypes().length != args.size()) {
            it.remove();
        }
    }
    // Find a direct match with assignment
    if (matches.size() != 1) {
        Map<Constructor, List<Object>> nmatches = new HashMap<Constructor, List<Object>>();
        for (Constructor cns : constructors) {
            boolean found = true;
            List<Object> match = new ArrayList<Object>();
            for (int i = 0; i < args.size(); i++) {
                ReifiedType argType = new GenericType(cns.getGenericParameterTypes()[i]);
                if (types.get(i) != null && !argType.getRawClass().equals(types.get(i).getRawClass())) {
                    found = false;
                    break;
                }
                //If the arg is an Unwrappered bean then we need to do the assignment check against the
                //unwrappered bean itself.
                Object arg = args.get(i);
                Object argToTest = arg;
                if (arg instanceof UnwrapperedBeanHolder)
                    argToTest = ((UnwrapperedBeanHolder) arg).unwrapperedBean;
                if (!AggregateConverter.isAssignable(argToTest, argType)) {
                    found = false;
                    break;
                }
                try {
                    match.add(convert(arg, cns.getGenericParameterTypes()[i]));
                } catch (Throwable t) {
                    found = false;
                    break;
                }
            }
            if (found) {
                nmatches.put(cns, match);
            }
        }
        if (nmatches.size() > 0) {
            matches = nmatches;
        }
    }
    // Find a direct match with conversion
    if (matches.size() != 1) {
        Map<Constructor, List<Object>> nmatches = new HashMap<Constructor, List<Object>>();
        for (Constructor cns : constructors) {
            boolean found = true;
            List<Object> match = new ArrayList<Object>();
            for (int i = 0; i < args.size(); i++) {
                ReifiedType argType = new GenericType(cns.getGenericParameterTypes()[i]);
                if (types.get(i) != null && !argType.getRawClass().equals(types.get(i).getRawClass())) {
                    found = false;
                    break;
                }
                try {
                    Object val = convert(args.get(i), argType);
                    match.add(val);
                } catch (Throwable t) {
                    found = false;
                    break;
                }
            }
            if (found) {
                nmatches.put(cns, match);
            }
        }
        if (nmatches.size() > 0) {
            matches = nmatches;
        }
    }
    // Start reordering with assignment
    if (matches.size() != 1 && reorderArguments && arguments.size() > 1) {
        Map<Constructor, List<Object>> nmatches = new HashMap<Constructor, List<Object>>();
        for (Constructor cns : constructors) {
            ArgumentMatcher matcher = new ArgumentMatcher(cns.getGenericParameterTypes(), false);
            List<Object> match = matcher.match(args, types);
            if (match != null) {
                nmatches.put(cns, match);
            }
        }
        if (nmatches.size() > 0) {
            matches = nmatches;
        }
    }
    // Start reordering with conversion
    if (matches.size() != 1 && reorderArguments && arguments.size() > 1) {
        Map<Constructor, List<Object>> nmatches = new HashMap<Constructor, List<Object>>();
        for (Constructor cns : constructors) {
            ArgumentMatcher matcher = new ArgumentMatcher(cns.getGenericParameterTypes(), true);
            List<Object> match = matcher.match(args, types);
            if (match != null) {
                nmatches.put(cns, match);
            }
        }
        if (nmatches.size() > 0) {
            matches = nmatches;
        }
    }
    return matches;
}
Also used : HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Constructor(java.lang.reflect.Constructor) ReifiedType(org.osgi.service.blueprint.container.ReifiedType) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List)

Example 5 with ReifiedType

use of org.osgi.service.blueprint.container.ReifiedType in project aries by apache.

the class CmManagedProperties method inject.

private void inject(Object bean, boolean initial) {
    LOGGER.debug("Injecting bean for bean={} / pid={}", beanName, persistentId);
    LOGGER.debug("Configuration: {}", properties);
    if (initial || "container-managed".equals(updateStrategy)) {
        if (properties != null) {
            for (Enumeration<String> e = properties.keys(); e.hasMoreElements(); ) {
                String key = e.nextElement();
                Object val = properties.get(key);
                String setterName = "set" + Character.toUpperCase(key.charAt(0));
                if (key.length() > 0) {
                    setterName += key.substring(1);
                }
                Set<Method> validSetters = new LinkedHashSet<Method>();
                List<Method> methods = new ArrayList<Method>(Arrays.asList(bean.getClass().getMethods()));
                methods.addAll(Arrays.asList(bean.getClass().getDeclaredMethods()));
                for (Method method : methods) {
                    if (method.getName().equals(setterName)) {
                        if (shouldSkip(method)) {
                            continue;
                        }
                        Class methodParameterType = method.getParameterTypes()[0];
                        Object propertyValue;
                        try {
                            propertyValue = blueprintContainer.getConverter().convert(val, new ReifiedType(methodParameterType));
                        } catch (Throwable t) {
                            LOGGER.debug("Unable to convert value for setter: " + method, t);
                            continue;
                        }
                        if (methodParameterType.isPrimitive() && propertyValue == null) {
                            LOGGER.debug("Null can not be assigned to {}: {}", methodParameterType.getName(), method);
                            continue;
                        }
                        if (validSetters.add(method)) {
                            try {
                                method.invoke(bean, propertyValue);
                            } catch (Exception t) {
                                LOGGER.debug("Setter can not be invoked: " + method, getRealCause(t));
                            }
                        }
                    }
                }
                if (validSetters.isEmpty()) {
                    LOGGER.debug("Unable to find a valid setter method for property {} and value {}", key, val);
                }
            }
        }
    } else if ("component-managed".equals(updateStrategy) && updateMethod != null) {
        List<Method> methods = ReflectionUtils.findCompatibleMethods(bean.getClass(), updateMethod, new Class[] { Map.class });
        Map map = null;
        if (properties != null) {
            map = new HashMap();
            for (Enumeration<String> e = properties.keys(); e.hasMoreElements(); ) {
                String key = e.nextElement();
                Object val = properties.get(key);
                map.put(key, val);
            }
        }
        for (Method method : methods) {
            try {
                method.invoke(bean, map);
            } catch (Throwable t) {
                LOGGER.warn("Unable to call method " + method + " on bean " + beanName, getRealCause(t));
            }
        }
    }
}
Also used : LinkedHashSet(java.util.LinkedHashSet) Enumeration(java.util.Enumeration) HashMap(java.util.HashMap) ReifiedType(org.osgi.service.blueprint.container.ReifiedType) ArrayList(java.util.ArrayList) Method(java.lang.reflect.Method) InvocationTargetException(java.lang.reflect.InvocationTargetException) ArrayList(java.util.ArrayList) List(java.util.List) HashMap(java.util.HashMap) Map(java.util.Map)

Aggregations

ReifiedType (org.osgi.service.blueprint.container.ReifiedType)16 HashMap (java.util.HashMap)6 ComponentDefinitionException (org.osgi.service.blueprint.container.ComponentDefinitionException)6 ArrayList (java.util.ArrayList)5 Collection (java.util.Collection)5 List (java.util.List)5 Map (java.util.Map)5 LinkedHashMap (java.util.LinkedHashMap)4 Method (java.lang.reflect.Method)3 Dictionary (java.util.Dictionary)3 Enumeration (java.util.Enumeration)3 Type (java.lang.reflect.Type)2 ExecutionContext (org.apache.aries.blueprint.di.ExecutionContext)2 Recipe (org.apache.aries.blueprint.di.Recipe)2 Constructor (java.lang.reflect.Constructor)1 InvocationTargetException (java.lang.reflect.InvocationTargetException)1 ParameterizedType (java.lang.reflect.ParameterizedType)1 AbstractMap (java.util.AbstractMap)1 Hashtable (java.util.Hashtable)1 LinkedHashSet (java.util.LinkedHashSet)1