Search in sources :

Example 76 with Member

use of java.lang.reflect.Member in project mvel by mvel.

the class ReflectiveAccessorOptimizer method getBeanProperty.

private Object getBeanProperty(Object ctx, String property) throws Exception {
    if ((pCtx == null ? currType : pCtx.getVarOrInputTypeOrNull(property)) == Object.class && !pCtx.isStrongTyping()) {
        currType = null;
    }
    if (first) {
        if ("this".equals(property)) {
            addAccessorNode(new ThisValueAccessor());
            return this.thisRef;
        } else if (variableFactory != null && variableFactory.isResolveable(property)) {
            if (variableFactory.isIndexedFactory() && variableFactory.isTarget(property)) {
                int idx;
                addAccessorNode(new IndexedVariableAccessor(idx = variableFactory.variableIndexOf(property)));
                VariableResolver vr = variableFactory.getIndexedVariableResolver(idx);
                if (vr == null) {
                    variableFactory.setIndexedVariableResolver(idx, variableFactory.getVariableResolver(property));
                }
                return variableFactory.getIndexedVariableResolver(idx).getValue();
            } else {
                addAccessorNode(new VariableAccessor(property));
                return variableFactory.getVariableResolver(property).getValue();
            }
        }
    }
    boolean classRef = false;
    Class<?> cls;
    if (ctx instanceof Class) {
        if (MVEL.COMPILER_OPT_SUPPORT_JAVA_STYLE_CLASS_LITERALS && "class".equals(property)) {
            return ctx;
        }
        cls = (Class<?>) ctx;
        classRef = true;
    } else if (ctx != null) {
        cls = ctx.getClass();
    } else {
        cls = currType;
    }
    if (hasPropertyHandler(cls)) {
        PropertyHandlerAccessor acc = new PropertyHandlerAccessor(property, cls, getPropertyHandler(cls));
        addAccessorNode(acc);
        return acc.getValue(ctx, thisRef, variableFactory);
    }
    Member member = cls != null ? getFieldOrAccessor(cls, property) : null;
    if (member != null && classRef && (member.getModifiers() & Modifier.STATIC) == 0) {
        member = null;
    }
    Object o;
    if (member instanceof Method) {
        try {
            o = ctx != null ? ((Method) member).invoke(ctx, EMPTYARG) : null;
            if (hasNullPropertyHandler()) {
                addAccessorNode(new GetterAccessorNH((Method) member, getNullPropertyHandler()));
                if (o == null)
                    o = getNullPropertyHandler().getProperty(member.getName(), ctx, variableFactory);
            } else {
                addAccessorNode(new GetterAccessor((Method) member));
            }
        } catch (IllegalAccessException e) {
            Method iFaceMeth = determineActualTargetMethod((Method) member);
            if (iFaceMeth == null)
                throw new PropertyAccessException("could not access field: " + cls.getName() + "." + property, this.expr, this.start, pCtx);
            o = iFaceMeth.invoke(ctx, EMPTYARG);
            if (hasNullPropertyHandler()) {
                addAccessorNode(new GetterAccessorNH((Method) member, getNullMethodHandler()));
                if (o == null)
                    o = getNullMethodHandler().getProperty(member.getName(), ctx, variableFactory);
            } else {
                addAccessorNode(new GetterAccessor(iFaceMeth));
            }
        } catch (IllegalArgumentException e) {
            if (member.getDeclaringClass().equals(ctx)) {
                try {
                    Class c = Class.forName(member.getDeclaringClass().getName() + "$" + property);
                    throw new CompileException("name collision between innerclass: " + c.getCanonicalName() + "; and bean accessor: " + property + " (" + member.toString() + ")", expr, tkStart);
                } catch (ClassNotFoundException e2) {
                // fallthru
                }
            }
            throw e;
        }
        currType = toNonPrimitiveType(((Method) member).getReturnType());
        return o;
    } else if (member != null) {
        Field f = (Field) member;
        if ((f.getModifiers() & Modifier.STATIC) != 0) {
            o = f.get(null);
            if (hasNullPropertyHandler()) {
                addAccessorNode(new StaticVarAccessorNH((Field) member, getNullMethodHandler()));
                if (o == null)
                    o = getNullMethodHandler().getProperty(member.getName(), ctx, variableFactory);
            } else {
                addAccessorNode(new StaticVarAccessor((Field) member));
            }
        } else {
            o = ctx != null ? f.get(ctx) : null;
            if (hasNullPropertyHandler()) {
                addAccessorNode(new FieldAccessorNH((Field) member, getNullMethodHandler()));
                if (o == null)
                    o = getNullMethodHandler().getProperty(member.getName(), ctx, variableFactory);
            } else {
                addAccessorNode(new FieldAccessor((Field) member));
            }
        }
        currType = toNonPrimitiveType(f.getType());
        return o;
    } else if (ctx instanceof Map && (((Map) ctx).containsKey(property) || nullSafe)) {
        addAccessorNode(new MapAccessor(property));
        return ((Map) ctx).get(property);
    } else if (ctx != null && "length".equals(property) && ctx.getClass().isArray()) {
        addAccessorNode(new ArrayLength());
        return getLength(ctx);
    } else if (LITERALS.containsKey(property)) {
        addAccessorNode(new StaticReferenceAccessor(ctx = LITERALS.get(property)));
        return ctx;
    } else {
        Object tryStaticMethodRef = tryStaticAccess();
        staticAccess = true;
        if (tryStaticMethodRef != null) {
            if (tryStaticMethodRef instanceof Class) {
                addAccessorNode(new StaticReferenceAccessor(tryStaticMethodRef));
                return tryStaticMethodRef;
            } else if (tryStaticMethodRef instanceof Field) {
                addAccessorNode(new StaticVarAccessor((Field) tryStaticMethodRef));
                return ((Field) tryStaticMethodRef).get(null);
            } else {
                addAccessorNode(new StaticReferenceAccessor(tryStaticMethodRef));
                return tryStaticMethodRef;
            }
        } else if (ctx instanceof Class) {
            Class c = (Class) ctx;
            for (Method m : c.getMethods()) {
                if (property.equals(m.getName())) {
                    if (pCtx != null && pCtx.getParserConfiguration() != null ? pCtx.getParserConfiguration().isAllowNakedMethCall() : MVEL.COMPILER_OPT_ALLOW_NAKED_METH_CALL) {
                        o = m.invoke(null, EMPTY_OBJ_ARR);
                        if (hasNullMethodHandler()) {
                            addAccessorNode(new MethodAccessorNH(m, new ExecutableStatement[0], getNullMethodHandler()));
                            if (o == null)
                                o = getNullMethodHandler().getProperty(m.getName(), ctx, variableFactory);
                        } else {
                            addAccessorNode(new MethodAccessor(m, new ExecutableStatement[0]));
                        }
                        return o;
                    } else {
                        addAccessorNode(new StaticReferenceAccessor(m));
                        return m;
                    }
                }
            }
            try {
                Class subClass = findClass(variableFactory, c.getName() + "$" + property, pCtx);
                addAccessorNode(new StaticReferenceAccessor(subClass));
                return subClass;
            } catch (ClassNotFoundException cnfe) {
            // fall through.
            }
        } else if (pCtx != null && pCtx.getParserConfiguration() != null ? pCtx.getParserConfiguration().isAllowNakedMethCall() : MVEL.COMPILER_OPT_ALLOW_NAKED_METH_CALL) {
            return getMethod(ctx, property);
        }
        // if it is not already using this as context try to read the property value from this
        if (ctx != this.thisRef && this.thisRef != null) {
            addAccessorNode(new ThisValueAccessor());
            return getBeanProperty(this.thisRef, property);
        }
        if (ctx == null) {
            throw new PropertyAccessException("unresolvable property or identifier: " + property, expr, start, pCtx);
        } else {
            throw new PropertyAccessException("could not access: " + property + "; in class: " + ctx.getClass().getName(), expr, start, pCtx);
        }
    }
}
Also used : FieldAccessorNH(org.mvel2.optimizers.impl.refl.nodes.FieldAccessorNH) FieldAccessor(org.mvel2.optimizers.impl.refl.nodes.FieldAccessor) DynamicFieldAccessor(org.mvel2.optimizers.impl.refl.nodes.DynamicFieldAccessor) Field(java.lang.reflect.Field) GetterAccessorNH(org.mvel2.optimizers.impl.refl.nodes.GetterAccessorNH) ThisValueAccessor(org.mvel2.optimizers.impl.refl.nodes.ThisValueAccessor) StaticVarAccessorNH(org.mvel2.optimizers.impl.refl.nodes.StaticVarAccessorNH) CompileException(org.mvel2.CompileException) MapAccessor(org.mvel2.optimizers.impl.refl.nodes.MapAccessor) Member(java.lang.reflect.Member) GetterAccessor(org.mvel2.optimizers.impl.refl.nodes.GetterAccessor) IndexedVariableAccessor(org.mvel2.optimizers.impl.refl.nodes.IndexedVariableAccessor) VariableAccessor(org.mvel2.optimizers.impl.refl.nodes.VariableAccessor) MethodAccessor(org.mvel2.optimizers.impl.refl.nodes.MethodAccessor) PropertyAccessException(org.mvel2.PropertyAccessException) ArrayLength(org.mvel2.optimizers.impl.refl.nodes.ArrayLength) StaticVarAccessor(org.mvel2.optimizers.impl.refl.nodes.StaticVarAccessor) Method(java.lang.reflect.Method) PropertyHandlerAccessor(org.mvel2.optimizers.impl.refl.nodes.PropertyHandlerAccessor) StaticReferenceAccessor(org.mvel2.optimizers.impl.refl.nodes.StaticReferenceAccessor) MethodAccessorNH(org.mvel2.optimizers.impl.refl.nodes.MethodAccessorNH) IndexedVariableAccessor(org.mvel2.optimizers.impl.refl.nodes.IndexedVariableAccessor) VariableResolver(org.mvel2.integration.VariableResolver) Map(java.util.Map)

Example 77 with Member

use of java.lang.reflect.Member in project mvel by mvel.

the class ReflectiveAccessorOptimizer method optimizeSetAccessor.

public Accessor optimizeSetAccessor(ParserContext pCtx, char[] property, int start, int offset, Object ctx, Object thisRef, VariableResolverFactory factory, boolean rootThisRef, Object value, Class ingressType) {
    this.rootNode = this.currNode = null;
    this.expr = property;
    this.start = start;
    this.first = true;
    this.length = start + offset;
    this.ctx = ctx;
    this.thisRef = thisRef;
    this.variableFactory = factory;
    this.ingressType = ingressType;
    char[] root = null;
    int split = findLastUnion();
    PropertyVerifier verifier = new PropertyVerifier(property, this.pCtx = pCtx);
    if (split != -1) {
        root = subset(property, 0, split++);
        // todo: must use the property verifier.
        property = subset(property, split, property.length - split);
    }
    if (root != null) {
        this.length = end = (this.expr = root).length;
        compileGetChain();
        ctx = this.val;
    }
    if (ctx == null) {
        throw new PropertyAccessException("could not access property: " + new String(property, this.start, Math.min(length, property.length)) + "; parent is null: " + new String(expr), expr, this.start, pCtx);
    }
    try {
        this.length = end = (this.expr = property).length;
        int st;
        this.cursor = st = 0;
        skipWhitespace();
        if (collection) {
            st = cursor;
            if (cursor == end)
                throw new PropertyAccessException("unterminated '['", expr, this.start, pCtx);
            if (scanTo(']'))
                throw new PropertyAccessException("unterminated '['", expr, this.start, pCtx);
            String ex = new String(property, st, cursor - st);
            if (ctx instanceof Map) {
                if (MVEL.COMPILER_OPT_ALLOW_OVERRIDE_ALL_PROPHANDLING && hasPropertyHandler(Map.class)) {
                    propHandlerSet(ex, ctx, Map.class, value);
                } else {
                    // noinspection unchecked
                    ((Map) ctx).put(eval(ex, ctx, variableFactory), convert(value, returnType = verifier.analyze()));
                    addAccessorNode(new MapAccessorNest(ex, returnType));
                }
                return rootNode;
            } else if (ctx instanceof List) {
                if (MVEL.COMPILER_OPT_ALLOW_OVERRIDE_ALL_PROPHANDLING && hasPropertyHandler(List.class)) {
                    propHandlerSet(ex, ctx, List.class, value);
                } else {
                    // noinspection unchecked
                    ((List) ctx).set(eval(ex, ctx, variableFactory, Integer.class), convert(value, returnType = verifier.analyze()));
                    addAccessorNode(new ListAccessorNest(ex, returnType));
                }
                return rootNode;
            } else if (MVEL.COMPILER_OPT_ALLOW_OVERRIDE_ALL_PROPHANDLING && hasPropertyHandler(ctx.getClass())) {
                propHandlerSet(ex, ctx, ctx.getClass(), value);
                return rootNode;
            } else if (ctx.getClass().isArray()) {
                if (MVEL.COMPILER_OPT_ALLOW_OVERRIDE_ALL_PROPHANDLING && hasPropertyHandler(Array.class)) {
                    propHandlerSet(ex, ctx, Array.class, value);
                } else {
                    // noinspection unchecked
                    Array.set(ctx, eval(ex, ctx, variableFactory, Integer.class), convert(value, getBaseComponentType(ctx.getClass())));
                    addAccessorNode(new ArrayAccessorNest(ex));
                }
                return rootNode;
            } else {
                throw new PropertyAccessException("cannot bind to collection property: " + new String(property) + ": not a recognized collection type: " + ctx.getClass(), expr, this.st, pCtx);
            }
        } else if (MVEL.COMPILER_OPT_ALLOW_OVERRIDE_ALL_PROPHANDLING && hasPropertyHandler(ctx.getClass())) {
            propHandlerSet(new String(property), ctx, ctx.getClass(), value);
            return rootNode;
        }
        String tk = new String(property, 0, length).trim();
        if (hasSetListeners()) {
            notifySetListeners(ctx, tk, variableFactory, value);
            addAccessorNode(new Notify(tk));
        }
        Member member = getFieldOrWriteAccessor(ctx.getClass(), tk, value == null ? null : ingressType);
        if (member instanceof Field) {
            Field fld = (Field) member;
            if (value != null && !fld.getType().isAssignableFrom(value.getClass())) {
                if (!canConvert(fld.getType(), value.getClass())) {
                    throw new CompileException("cannot convert type: " + value.getClass() + ": to " + fld.getType(), this.expr, this.start);
                }
                fld.set(ctx, convert(value, fld.getType()));
                addAccessorNode(new DynamicFieldAccessor(fld));
            } else if (value == null && fld.getType().isPrimitive()) {
                fld.set(ctx, PropertyTools.getPrimitiveInitialValue(fld.getType()));
                addAccessorNode(new FieldAccessor(fld));
            } else {
                fld.set(ctx, value);
                addAccessorNode(new FieldAccessor(fld));
            }
        } else if (member != null) {
            Method meth = (Method) member;
            if (value != null && !meth.getParameterTypes()[0].isAssignableFrom(value.getClass())) {
                if (!canConvert(meth.getParameterTypes()[0], value.getClass())) {
                    throw new CompileException("cannot convert type: " + value.getClass() + ": to " + meth.getParameterTypes()[0], this.expr, this.start);
                }
                meth.invoke(ctx, convert(value, meth.getParameterTypes()[0]));
            } else if (value == null && meth.getParameterTypes()[0].isPrimitive()) {
                meth.invoke(ctx, PropertyTools.getPrimitiveInitialValue(meth.getParameterTypes()[0]));
            } else {
                meth.invoke(ctx, value);
            }
            addAccessorNode(new SetterAccessor(meth));
        } else if (ctx instanceof Map) {
            // noinspection unchecked
            ((Map) ctx).put(tk, value);
            addAccessorNode(new MapAccessor(tk));
        } else {
            throw new PropertyAccessException("could not access property (" + tk + ") in: " + ingressType.getName(), this.expr, this.start, pCtx);
        }
    } catch (InvocationTargetException e) {
        throw new PropertyAccessException("could not access property: " + new String(property), this.expr, st, e, pCtx);
    } catch (IllegalAccessException e) {
        throw new PropertyAccessException("could not access property: " + new String(property), this.expr, st, e, pCtx);
    } catch (IllegalArgumentException e) {
        throw new PropertyAccessException("error binding property: " + new String(property) + " (value <<" + value + ">>::" + (value == null ? "null" : value.getClass().getCanonicalName()) + ")", this.expr, st, e, pCtx);
    }
    return rootNode;
}
Also used : PropertyVerifier(org.mvel2.compiler.PropertyVerifier) Notify(org.mvel2.optimizers.impl.refl.nodes.Notify) ArrayAccessorNest(org.mvel2.optimizers.impl.refl.nodes.ArrayAccessorNest) PropertyAccessException(org.mvel2.PropertyAccessException) Method(java.lang.reflect.Method) MapAccessorNest(org.mvel2.optimizers.impl.refl.nodes.MapAccessorNest) FieldAccessor(org.mvel2.optimizers.impl.refl.nodes.FieldAccessor) DynamicFieldAccessor(org.mvel2.optimizers.impl.refl.nodes.DynamicFieldAccessor) InvocationTargetException(java.lang.reflect.InvocationTargetException) Array(java.lang.reflect.Array) Field(java.lang.reflect.Field) SetterAccessor(org.mvel2.optimizers.impl.refl.nodes.SetterAccessor) ListAccessorNest(org.mvel2.optimizers.impl.refl.nodes.ListAccessorNest) CompileException(org.mvel2.CompileException) List(java.util.List) MapAccessor(org.mvel2.optimizers.impl.refl.nodes.MapAccessor) Map(java.util.Map) Member(java.lang.reflect.Member) DynamicFieldAccessor(org.mvel2.optimizers.impl.refl.nodes.DynamicFieldAccessor)

Example 78 with Member

use of java.lang.reflect.Member in project mvel by mvel.

the class PropertyVerifier method getBeanProperty.

/**
 * Process bean property
 *
 * @param ctx      - the ingress type
 * @param property - the property component
 * @return known egress type.
 */
private Class getBeanProperty(Class ctx, String property) {
    if (first) {
        if (pCtx.hasVarOrInput(property)) {
            if (pCtx.isStrictTypeEnforcement()) {
                recordTypeParmsForProperty(property);
            }
            return pCtx.getVarOrInputType(property);
        } else if (pCtx.hasImport(property)) {
            resolvedExternally = false;
            return pCtx.getImport(property);
        } else if (!pCtx.isStrongTyping()) {
            return Object.class;
        } else if (pCtx.hasVarOrInput("this")) {
            if (pCtx.isStrictTypeEnforcement()) {
                recordTypeParmsForProperty("this");
            }
            ctx = pCtx.getVarOrInputType("this");
            resolvedExternally = false;
        }
    }
    st = cursor;
    boolean switchStateReg;
    Member member = ctx != null ? getFieldOrAccessor(ctx, property) : null;
    if (MVEL.COMPILER_OPT_SUPPORT_JAVA_STYLE_CLASS_LITERALS) {
        if ("class".equals(property)) {
            return Class.class;
        }
    }
    if (member instanceof Field) {
        if (pCtx.isStrictTypeEnforcement()) {
            Field f = ((Field) member);
            if (f.getGenericType() != null) {
                if (f.getGenericType() instanceof ParameterizedType) {
                    ParameterizedType pt = (ParameterizedType) f.getGenericType();
                    pCtx.setLastTypeParameters(pt.getActualTypeArguments());
                    Type[] gpt = pt.getActualTypeArguments();
                    Type[] classArgs = type2Class(pt.getRawType()).getTypeParameters();
                    if (gpt.length > 0 && paramTypes == null)
                        paramTypes = new HashMap<String, Type>();
                    for (int i = 0; i < gpt.length; i++) {
                        paramTypes.put(classArgs[i].toString(), gpt[i]);
                    }
                } else if (f.getGenericType() instanceof TypeVariable) {
                    TypeVariable tv = (TypeVariable) f.getGenericType();
                    Type paramType = paramTypes.remove(tv.getName());
                    if (paramType != null && paramType instanceof Class) {
                        return (Class) paramType;
                    }
                }
            }
            return f.getType();
        } else {
            return ((Field) member).getType();
        }
    }
    if (member != null) {
        return getReturnType(ctx, (Method) member);
    }
    if (pCtx != null && first && pCtx.hasImport(property)) {
        Class<?> importedClass = pCtx.getImport(property);
        if (importedClass != null)
            return pCtx.getImport(property);
    }
    if (pCtx != null && pCtx.getLastTypeParameters() != null && pCtx.getLastTypeParameters().length != 0 && ((Collection.class.isAssignableFrom(ctx) && !(switchStateReg = false)) || (Map.class.isAssignableFrom(ctx) && (switchStateReg = true)))) {
        Type parm = pCtx.getLastTypeParameters()[switchStateReg ? 1 : 0];
        pCtx.setLastTypeParameters(null);
        return parm instanceof ParameterizedType ? Object.class : (Class) parm;
    }
    if (pCtx != null && "length".equals(property) && ctx.isArray()) {
        return Integer.class;
    }
    Object tryStaticMethodRef = tryStaticAccess();
    if (tryStaticMethodRef != null) {
        fqcn = true;
        resolvedExternally = false;
        if (tryStaticMethodRef instanceof Class) {
            classLiteral = !(MVEL.COMPILER_OPT_SUPPORT_JAVA_STYLE_CLASS_LITERALS && new String(expr, end - 6, 6).equals(".class"));
            return classLiteral ? (Class) tryStaticMethodRef : Class.class;
        } else if (tryStaticMethodRef instanceof Field) {
            try {
                return ((Field) tryStaticMethodRef).get(null).getClass();
            } catch (Exception e) {
                throw new CompileException("in verifier: ", expr, start, e);
            }
        } else {
            try {
                return ((Method) tryStaticMethodRef).getReturnType();
            } catch (Exception e) {
                throw new CompileException("in verifier: ", expr, start, e);
            }
        }
    }
    if (ctx != null) {
        try {
            return findClass(variableFactory, ctx.getName() + "$" + property, pCtx);
        } catch (ClassNotFoundException cnfe) {
        // fall through.
        }
    }
    if (pCtx != null && pCtx.getParserConfiguration() != null ? pCtx.getParserConfiguration().isAllowNakedMethCall() : MVEL.COMPILER_OPT_ALLOW_NAKED_METH_CALL) {
        Class cls = getMethod(ctx, property);
        if (cls != Object.class) {
            return cls;
        }
    }
    if (pCtx.isStrictTypeEnforcement()) {
        throw new CompileException("unqualified type in strict mode for: " + property, expr, tkStart);
    }
    return Object.class;
}
Also used : HashMap(java.util.HashMap) CompileException(org.mvel2.CompileException) ParameterizedType(java.lang.reflect.ParameterizedType) Field(java.lang.reflect.Field) ParameterizedType(java.lang.reflect.ParameterizedType) Type(java.lang.reflect.Type) NullType(org.mvel2.util.NullType) TypeVariable(java.lang.reflect.TypeVariable) Collection(java.util.Collection) CompileException(org.mvel2.CompileException) Member(java.lang.reflect.Member) HashMap(java.util.HashMap) Map(java.util.Map)

Example 79 with Member

use of java.lang.reflect.Member in project act-eagle-allone by mailtous.

the class Method method attrName.

public String[] attrName(Member... member) {
    String[] cols = new String[member.length];
    int i = 0;
    for (Member fun : member) {
        cols[i++] = attrName(fun);
    }
    return cols;
}
Also used : Member(java.lang.reflect.Member)

Example 80 with Member

use of java.lang.reflect.Member in project felix by apache.

the class InstanceManagerTest method testConcurrencyOfMethodId.

@Test
public void testConcurrencyOfMethodId() throws InterruptedException, ConfigurationException, ClassNotFoundException {
    ExecutorService executor = Executors.newFixedThreadPool(CALLERS);
    final AtomicInteger counter = new AtomicInteger();
    final AtomicInteger error = new AtomicInteger();
    ComponentFactory factory = mock(ComponentFactory.class);
    when(factory.loadClass(anyString())).thenReturn(MyComponent.class);
    when(factory.getClassName()).thenReturn(MyComponent.class.getName());
    Bundle bundle = mock(Bundle.class);
    when(bundle.getHeaders()).thenReturn(new Hashtable<String, String>());
    BundleContext context = mock(BundleContext.class);
    when(context.getBundle()).thenReturn(bundle);
    InstanceManager manager = new InstanceManager(factory, context, new HandlerManager[0]);
    Element method1 = new Element("method", "");
    method1.addAttribute(new Attribute("name", "foo"));
    method1.addAttribute(new Attribute("arguments", "{java.lang.String}"));
    method1.addAttribute(new Attribute("names", "{name}"));
    Element method2 = new Element("method", "");
    method2.addAttribute(new Attribute("name", "bar"));
    method2.addAttribute(new Attribute("arguments", "{java.lang.String}"));
    method2.addAttribute(new Attribute("names", "{name}"));
    Element method3 = new Element("method", "");
    method3.addAttribute(new Attribute("name", "baz"));
    method3.addAttribute(new Attribute("arguments", "{java.lang.String}"));
    method3.addAttribute(new Attribute("names", "{name}"));
    final MethodMetadata metadata1 = new MethodMetadata(method1);
    final MethodInterceptor interceptor = new MethodInterceptor() {

        public void onEntry(Object pojo, Member method, Object[] args) {
            if (method != null) {
                counter.getAndIncrement();
            } else {
                System.out.println("No method object for " + args[0]);
                error.incrementAndGet();
            }
        }

        public void onExit(Object pojo, Member method, Object returnedObj) {
            if (method != null) {
                counter.getAndDecrement();
            } else {
                System.out.println("No method object");
                error.incrementAndGet();
            }
        }

        public void onError(Object pojo, Member method, Throwable throwable) {
        }

        public void onFinally(Object pojo, Member method) {
        }
    };
    manager.register(metadata1, interceptor);
    final MethodMetadata metadata2 = new MethodMetadata(method2);
    manager.register(metadata2, interceptor);
    final MethodMetadata metadata3 = new MethodMetadata(method3);
    manager.register(metadata3, interceptor);
    MyComponent component = new MyComponent();
    manager.start();
    manager.load();
    CountDownLatch startSignal = new CountDownLatch(1);
    CountDownLatch doneSignal = new CountDownLatch(CALLERS);
    for (int i = 1; i < CALLERS + 1; ++i) {
        // create and start threads
        executor.execute(new Caller(manager, component, metadata1.getMethodIdentifier(), startSignal, doneSignal, i));
        executor.execute(new Caller(manager, component, metadata2.getMethodIdentifier(), startSignal, doneSignal, i));
        executor.execute(new Caller(manager, component, metadata3.getMethodIdentifier(), startSignal, doneSignal, i));
    }
    // let all threads proceed
    startSignal.countDown();
    assertThat(doneSignal.await(1, TimeUnit.MINUTES)).isTrue();
    assertThat(error.get()).isEqualTo(0);
}
Also used : Attribute(org.apache.felix.ipojo.metadata.Attribute) Bundle(org.osgi.framework.Bundle) Element(org.apache.felix.ipojo.metadata.Element) Matchers.anyString(org.mockito.Matchers.anyString) CountDownLatch(java.util.concurrent.CountDownLatch) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ExecutorService(java.util.concurrent.ExecutorService) MethodMetadata(org.apache.felix.ipojo.parser.MethodMetadata) Member(java.lang.reflect.Member) BundleContext(org.osgi.framework.BundleContext) Test(org.junit.Test)

Aggregations

Member (java.lang.reflect.Member)135 Method (java.lang.reflect.Method)41 Field (java.lang.reflect.Field)30 ArrayList (java.util.ArrayList)13 AccessibleObject (java.lang.reflect.AccessibleObject)12 Type (java.lang.reflect.Type)12 Annotation (java.lang.annotation.Annotation)11 Constructor (java.lang.reflect.Constructor)10 TypeVariable (java.lang.reflect.TypeVariable)9 InvocationTargetException (java.lang.reflect.InvocationTargetException)8 ParameterizedType (java.lang.reflect.ParameterizedType)7 Map (java.util.Map)7 MetaInfo (org.qi4j.api.common.MetaInfo)7 InjectionPoint (com.google.inject.spi.InjectionPoint)6 AnnotatedElement (java.lang.reflect.AnnotatedElement)6 LinkedHashSet (java.util.LinkedHashSet)6 Optional (org.qi4j.api.common.Optional)6 ValueConstraintsInstance (org.qi4j.runtime.composite.ValueConstraintsInstance)6 ValueConstraintsModel (org.qi4j.runtime.composite.ValueConstraintsModel)6 HashSet (java.util.HashSet)5