Search in sources :

Example 81 with AnnotatedElement

use of java.lang.reflect.AnnotatedElement in project Payara by payara.

the class GenericCrudCommand method getInjectionResolver.

public InjectionResolver<Param> getInjectionResolver() {
    final InjectionResolver<Param> delegate = injector;
    return new InjectionResolver<Param>(Param.class) {

        @Override
        public <V> V getValue(Object component, AnnotatedElement annotated, Type genericType, Class<V> type) throws MultiException {
            if (type.isAssignableFrom(List.class)) {
                final List<ConfigBeanProxy> values;
                try {
                    if (annotated instanceof Method) {
                        values = (List<ConfigBeanProxy>) ((Method) annotated).invoke(component);
                    } else if (annotated instanceof Field) {
                        values = (List<ConfigBeanProxy>) ((Field) annotated).get(component);
                    } else {
                        String msg = LOCAL_STRINGS.getLocalString(GenericCrudCommand.class, "GenericCrudCommand.invalid_type", "Invalid annotated type {0} passed to InjectionResolver:getValue()", annotated.getClass().toString());
                        LOGGER.log(Level.SEVERE, ConfigApiLoggerInfo.INVALID_ANNO_TYPE, annotated.getClass().toString());
                        throw new MultiException(new IllegalArgumentException(msg));
                    }
                } catch (IllegalAccessException | InvocationTargetException e) {
                    String msg = LOCAL_STRINGS.getLocalString(GenericCrudCommand.class, "GenericCrudCommand.invocation_failure", "Failure {0} while getting List<?> values from component", e.getMessage());
                    LOGGER.log(Level.SEVERE, ConfigApiLoggerInfo.INVOKE_FAILURE);
                    throw new MultiException(new IllegalStateException(msg, e));
                }
                Object value = delegate.getValue(component, annotated, genericType, type);
                if (value == null) {
                    LOGGER.log(level, "Value of {0} is null", annotated);
                    return null;
                }
                Type genericReturnType = null;
                if (annotated instanceof Method) {
                    genericReturnType = ((Method) annotated).getGenericReturnType();
                } else if (annotated instanceof Field) {
                    genericReturnType = ((Field) annotated).getGenericType();
                }
                if (genericReturnType == null) {
                    throw new MultiException(new IllegalArgumentException("Cannot determine parametized type from " + annotated));
                }
                final Class<? extends ConfigBeanProxy> itemType = Types.erasure(Types.getTypeArgument(genericReturnType, 0));
                if (LOGGER.isLoggable(level)) {
                    LOGGER.log(level, "Found that List<?> really is a List<{0}>", itemType);
                }
                if (itemType == null) {
                    String msg = LOCAL_STRINGS.getLocalString(GenericCrudCommand.class, "GenericCrudCommand.nongeneric_type", "The List type returned by {0} must be a generic type", annotated.toString());
                    LOGGER.log(Level.SEVERE, ConfigApiLoggerInfo.LIST_NOT_GENERIC_TYPE, annotated.toString());
                    throw new MultiException(new IllegalArgumentException(msg));
                }
                if (!ConfigBeanProxy.class.isAssignableFrom(itemType)) {
                    String msg = LOCAL_STRINGS.getLocalString(GenericCrudCommand.class, "GenericCrudCommand.wrong_type", "The generic type {0} is not supported, only List<? extends ConfigBeanProxy> is", annotated.toString());
                    LOGGER.log(Level.SEVERE, ConfigApiLoggerInfo.GENERIC_TYPE_NOT_SUPPORTED, annotated.toString());
                    throw new MultiException(new IllegalArgumentException(msg));
                }
                Properties props = convertStringToProperties(value.toString(), ':');
                if (LOGGER.isLoggable(level)) {
                    for (Map.Entry<Object, Object> entry : props.entrySet()) {
                        LOGGER.log(level, "Subtype {0} key:{1} value:{2}", new Object[] { itemType, entry.getKey(), entry.getValue() });
                    }
                }
                final BeanInfo beanInfo;
                try {
                    beanInfo = Introspector.getBeanInfo(itemType);
                } catch (IntrospectionException e) {
                    String msg = LOCAL_STRINGS.getLocalString(GenericCrudCommand.class, "GenericCrudCommand.introspection_failure", "Failure {0} while instrospecting {1} to find all getters and setters", e.getMessage(), itemType.getName());
                    LogHelper.log(LOGGER, Level.SEVERE, ConfigApiLoggerInfo.INTROSPECTION_FAILED, e, itemType.getName());
                    throw new MultiException(new IllegalStateException(msg, e));
                }
                for (final Map.Entry<Object, Object> entry : props.entrySet()) {
                    ConfigBeanProxy child = (ConfigBeanProxy) component;
                    try {
                        ConfigBeanProxy cc = child.createChild(itemType);
                        new InjectionManager().inject(cc, itemType, new InjectionResolver<Attribute>(Attribute.class) {

                            @Override
                            public boolean isOptional(AnnotatedElement annotated, Attribute annotation) {
                                return true;
                            }

                            @Override
                            public Method getSetterMethod(Method annotated, Attribute annotation) {
                                // variant.
                                for (PropertyDescriptor pd : beanInfo.getPropertyDescriptors()) {
                                    if (pd.getReadMethod().equals(annotated)) {
                                        return pd.getWriteMethod();
                                    }
                                }
                                return annotated;
                            }

                            @Override
                            public <V> V getValue(Object component, AnnotatedElement annotated, Type genericType, Class<V> type) throws MultiException {
                                String name = annotated.getAnnotation(Attribute.class).value();
                                if ((name == null || name.length() == 0) && annotated instanceof Method) {
                                    // maybe there is a better way to do this...
                                    name = ((Method) annotated).getName().substring(3);
                                    if (name.equalsIgnoreCase("name") || name.equalsIgnoreCase("key")) {
                                        return type.cast(entry.getKey());
                                    }
                                    if (name.equalsIgnoreCase("value")) {
                                        return type.cast(entry.getValue());
                                    }
                                }
                                return null;
                            }
                        });
                        values.add(cc);
                    } catch (TransactionFailure transactionFailure) {
                        String msg = LOCAL_STRINGS.getLocalString(GenericCrudCommand.class, "GenericCrudCommand.transactionException", "Transaction exception {0} while injecting {1}", transactionFailure.getMessage(), itemType);
                        LogHelper.log(LOGGER, Level.SEVERE, ConfigApiLoggerInfo.TX_FAILED, transactionFailure, itemType);
                        throw new MultiException(new IllegalStateException(msg, transactionFailure));
                    }
                }
                return null;
            }
            return delegate.getValue(component, annotated, genericType, type);
        }

        @Override
        public boolean isOptional(AnnotatedElement annotated, Param annotation) {
            return annotation.optional();
        }
    };
}
Also used : TransactionFailure(org.jvnet.hk2.config.TransactionFailure) Attribute(org.jvnet.hk2.config.Attribute) BeanInfo(java.beans.BeanInfo) AnnotatedElement(java.lang.reflect.AnnotatedElement) IntrospectionException(java.beans.IntrospectionException) Properties(java.util.Properties) Field(java.lang.reflect.Field) ConfigBeanProxy(org.jvnet.hk2.config.ConfigBeanProxy) List(java.util.List) PropertyDescriptor(java.beans.PropertyDescriptor) GenerateServiceFromMethod(org.jvnet.hk2.config.GenerateServiceFromMethod) Method(java.lang.reflect.Method) InjectionResolver(org.jvnet.hk2.config.InjectionResolver) InvocationTargetException(java.lang.reflect.InvocationTargetException) Type(java.lang.reflect.Type) Param(org.glassfish.api.Param) MultiException(org.glassfish.hk2.api.MultiException) Map(java.util.Map) InjectionManager(org.jvnet.hk2.config.InjectionManager)

Example 82 with AnnotatedElement

use of java.lang.reflect.AnnotatedElement in project Payara by payara.

the class MapInjectionResolverTest method convertListToObjectTest.

@Test
public void convertListToObjectTest() throws Exception {
    DummyCommand dc = new DummyCommand();
    Class<?> cl = dc.getClass();
    AnnotatedElement target = (AnnotatedElement) cl.getDeclaredField("propm");
    List<String> paramValueList = new ArrayList<String>();
    paramValueList.add("prop1=valA");
    paramValueList.add("prop2=valB");
    paramValueList.add("prop3=valC");
    Object paramValActual = MapInjectionResolver.convertListToObject(target, Properties.class, paramValueList);
    Object paramValExpected = new Properties();
    ((Properties) paramValExpected).put("prop1", "valA");
    ((Properties) paramValExpected).put("prop2", "valB");
    ((Properties) paramValExpected).put("prop3", "valC");
    assertEquals("Properties type", paramValExpected, paramValActual);
    paramValueList.clear();
    paramValueList.add("server1");
    paramValueList.add("server2");
    paramValueList.add("server3");
    target = (AnnotatedElement) cl.getDeclaredField("lstrm");
    paramValActual = MapInjectionResolver.convertListToObject(target, List.class, paramValueList);
    assertEquals("List type", paramValueList, paramValActual);
    target = (AnnotatedElement) cl.getDeclaredField("astrm");
    paramValActual = MapInjectionResolver.convertListToObject(target, (new String[] {}).getClass(), paramValueList);
    String[] strArray = new String[3];
    strArray[0] = "server1";
    strArray[1] = "server2";
    strArray[2] = "server3";
    assertEquals("String Array type", strArray, (String[]) paramValActual);
}
Also used : AnnotatedElement(java.lang.reflect.AnnotatedElement) ArrayList(java.util.ArrayList) List(java.util.List) ArrayList(java.util.ArrayList) Properties(java.util.Properties) Test(org.junit.Test)

Example 83 with AnnotatedElement

use of java.lang.reflect.AnnotatedElement in project Payara by payara.

the class MapInjectionResolverTest method getParamFieldTest.

@Test
public void getParamFieldTest() {
    try {
        DummyCommand dc = new DummyCommand();
        Class<?> cl = dc.getClass();
        AnnotatedElement ae = (AnnotatedElement) cl.getDeclaredField("hello");
        Object obj = MapInjectionResolver.getParamField(dc, ae);
        assertEquals("obj should be world", "world", (String) obj);
        ae = (AnnotatedElement) cl.getDeclaredField("prop");
        obj = MapInjectionResolver.getParamField(dc, ae);
        assertEquals("obj should be null", null, obj);
        ae = (AnnotatedElement) cl.getDeclaredField("dyn3");
        obj = MapInjectionResolver.getParamField(dc, ae);
        assertEquals("obj should be dynamic-default-value", "dynamic-default-value", (String) obj);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}
Also used : AnnotatedElement(java.lang.reflect.AnnotatedElement) Test(org.junit.Test)

Example 84 with AnnotatedElement

use of java.lang.reflect.AnnotatedElement in project Payara by payara.

the class MapInjectionResolverTest method convertStringToObjectTest.

@Test
public void convertStringToObjectTest() throws Exception {
    DummyCommand dc = new DummyCommand();
    Class<?> cl = dc.getClass();
    AnnotatedElement target = (AnnotatedElement) cl.getDeclaredField("foo");
    String paramValueStr = "prop1=valA:prop2=valB:prop3=valC";
    Object paramValActual = MapInjectionResolver.convertStringToObject(target, String.class, paramValueStr);
    Object paramValExpected = "prop1=valA:prop2=valB:prop3=valC";
    assertEquals("String type", paramValExpected, paramValActual);
    target = (AnnotatedElement) cl.getDeclaredField("prop");
    paramValActual = MapInjectionResolver.convertStringToObject(target, Properties.class, paramValueStr);
    paramValExpected = new Properties();
    ((Properties) paramValExpected).put("prop1", "valA");
    ((Properties) paramValExpected).put("prop2", "valB");
    ((Properties) paramValExpected).put("prop3", "valC");
    assertEquals("Properties type", paramValExpected, paramValActual);
    target = (AnnotatedElement) cl.getDeclaredField("portnum");
    paramValueStr = "8080";
    paramValActual = MapInjectionResolver.convertStringToObject(target, Integer.class, paramValueStr);
    paramValExpected = new Integer(8080);
    assertEquals("Integer type", paramValExpected, paramValActual);
    paramValueStr = "server1:server2:server3";
    target = (AnnotatedElement) cl.getDeclaredField("lstr");
    paramValActual = MapInjectionResolver.convertStringToObject(target, List.class, paramValueStr);
    List<String> paramValueList = new java.util.ArrayList();
    paramValueList.add("server1");
    paramValueList.add("server2");
    paramValueList.add("server3");
    assertEquals("List type", paramValueList, paramValActual);
    paramValueStr = "server1,server2,server3";
    target = (AnnotatedElement) cl.getDeclaredField("astr");
    paramValActual = MapInjectionResolver.convertStringToObject(target, (new String[] {}).getClass(), paramValueStr);
    String[] strArray = new String[3];
    strArray[0] = "server1";
    strArray[1] = "server2";
    strArray[2] = "server3";
    assertEquals("String Array type", strArray, (String[]) paramValActual);
}
Also used : AnnotatedElement(java.lang.reflect.AnnotatedElement) ArrayList(java.util.ArrayList) List(java.util.List) ArrayList(java.util.ArrayList) Properties(java.util.Properties) Test(org.junit.Test)

Example 85 with AnnotatedElement

use of java.lang.reflect.AnnotatedElement in project Payara by payara.

the class MapInjectionResolverTest method getParamValueStringTest.

@Test
public void getParamValueStringTest() {
    try {
        DummyCommand dc = new DummyCommand();
        Class<?> cl = dc.getClass();
        AnnotatedElement ae = (AnnotatedElement) cl.getDeclaredField("foo");
        Param param = ae.getAnnotation(Param.class);
        ParameterMap params = new ParameterMap();
        params.set("foo", "true");
        String val = MapInjectionResolver.getParamValueString(params, param, ae, null);
        assertEquals("val should be true", "true", val);
        ae = (AnnotatedElement) cl.getDeclaredField("bar");
        param = ae.getAnnotation(Param.class);
        val = MapInjectionResolver.getParamValueString(params, param, ae, null);
        assertEquals("val should be false", "false", val);
        ae = (AnnotatedElement) cl.getDeclaredField("hello");
        param = ae.getAnnotation(Param.class);
        val = MapInjectionResolver.getParamValueString(params, param, ae, null);
        assertEquals("val should be null", null, val);
        ae = (AnnotatedElement) cl.getDeclaredField("dyn");
        param = ae.getAnnotation(Param.class);
        val = MapInjectionResolver.getParamValueString(params, param, ae, null);
        assertEquals("val should be dynamic-default-value", "dynamic-default-value", val);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}
Also used : AnnotatedElement(java.lang.reflect.AnnotatedElement) Param(org.glassfish.api.Param) ParameterMap(org.glassfish.api.admin.ParameterMap) Test(org.junit.Test)

Aggregations

AnnotatedElement (java.lang.reflect.AnnotatedElement)106 Method (java.lang.reflect.Method)23 Annotation (java.lang.annotation.Annotation)17 Field (java.lang.reflect.Field)17 ArrayList (java.util.ArrayList)12 Test (org.junit.Test)11 HashMap (java.util.HashMap)9 Test (org.junit.jupiter.api.Test)8 Member (java.lang.reflect.Member)7 LinkedHashSet (java.util.LinkedHashSet)7 List (java.util.List)7 Constructor (java.lang.reflect.Constructor)6 Type (java.lang.reflect.Type)6 Map (java.util.Map)6 HashSet (java.util.HashSet)5 By (org.openqa.selenium.By)5 Statement (org.junit.runners.model.Statement)4 FindBy (org.openqa.selenium.support.FindBy)4 EntityType (com.querydsl.codegen.EntityType)3 Collection (java.util.Collection)3