Search in sources :

Example 21 with ClassDescriptor

use of jodd.introspector.ClassDescriptor in project jodd by oblac.

the class JoinHintResolver method join.

/**
	 * Joins entity array using provided string hints.
	 */
public Object[] join(Object[] data, String[] hints) {
    if (hints == null) {
        return data;
    }
    // build context
    Map<String, Object> context = new HashMap<>(hints.length);
    for (int i = 0; i < hints.length; i++) {
        hints[i] = hints[i].trim();
        String hint = hints[i];
        if (hint.indexOf('.') == -1) {
            context.put(hint, data[i]);
        }
    }
    // no joining hints found
    if (context.size() == data.length) {
        return data;
    }
    // joining
    Object[] result = new Object[context.size()];
    int count = 0;
    for (int i = 0; i < hints.length; i++) {
        String hint = hints[i];
        int ndx = hint.indexOf('.');
        if (ndx != -1) {
            String key = hint.substring(0, ndx);
            Object value = context.get(key);
            if (value == null) {
                throw new DbOomException("Hint value missing: " + key);
            }
            // don't merge nulls
            if (data[i] == null) {
                continue;
            }
            String hintPropertyName = hint.substring(ndx + 1);
            Class hintPropertyType = BeanUtil.pojo.getPropertyType(value, hintPropertyName);
            if (hintPropertyType != null) {
                ClassDescriptor cd = ClassIntrospector.lookup(hintPropertyType);
                if (cd.isCollection()) {
                    // add element to collection
                    try {
                        Collection collection = BeanUtil.declared.getProperty(value, hintPropertyName);
                        if (collection == null) {
                            collection = (Collection) ReflectUtil.newInstance(hintPropertyType);
                            BeanUtil.declaredSilent.setProperty(value, hintPropertyName, collection);
                        }
                        collection.add(data[i]);
                    } catch (Exception ex) {
                        throw new DbOomException(ex);
                    }
                } else if (cd.isArray()) {
                    // add element to array
                    try {
                        Object[] array = BeanUtil.declared.getProperty(value, hintPropertyName);
                        if (array == null) {
                            array = (Object[]) Array.newInstance(hintPropertyType.getComponentType(), 1);
                            BeanUtil.declaredSilent.setProperty(value, hintPropertyName, array);
                            array[0] = data[i];
                        } else {
                            Object[] newArray = ArraysUtil.append(array, data[i]);
                            if (newArray != array) {
                                BeanUtil.declaredSilent.setProperty(value, hintPropertyName, newArray);
                            }
                        }
                    } catch (Exception ex) {
                        throw new DbOomException(ex);
                    }
                } else {
                    // set value
                    BeanUtil.declaredSilent.setProperty(value, hintPropertyName, data[i]);
                }
            } else {
                // special case - the property probably contains the collection in the way
                int lastNdx = hintPropertyName.lastIndexOf('.');
                String name = hintPropertyName.substring(0, lastNdx);
                Object target = resolveValueInSpecialCase(value, name);
                if (target != null) {
                    String targetSimpleName = hintPropertyName.substring(lastNdx + 1);
                    BeanUtil.declaredForcedSilent.setProperty(target, targetSimpleName, data[i]);
                }
            }
        } else {
            result[count] = data[i];
            count++;
        }
    }
    return result;
}
Also used : ClassDescriptor(jodd.introspector.ClassDescriptor) HashMap(java.util.HashMap) Collection(java.util.Collection)

Example 22 with ClassDescriptor

use of jodd.introspector.ClassDescriptor in project jodd by oblac.

the class BigClassTest method testAllFeatures.

@Test
public void testAllFeatures() throws IOException, IllegalAccessException, InstantiationException {
    StatCounter.counter = 0;
    final MutableBoolean firstTime = new MutableBoolean(true);
    ProxyAspect aspect = new ProxyAspect(StatCounterAdvice.class, new ProxyPointcutSupport() {

        public boolean apply(MethodInfo mi) {
            if (firstTime.value) {
                firstTime.value = false;
                ClassInfo ci = mi.getClassInfo();
                assertEquals("BigFatJoe", ci.getClassname());
                assertEquals(BigFatJoe.class.getPackage().getName(), ci.getPackage());
                assertEquals("jodd/proxetta/data/BigFatJoe", ci.getReference());
                assertEquals("jodd/proxetta/data/SmallSkinnyZoe", ci.getSuperName());
                AnnotationInfo[] anns = ci.getAnnotations();
                assertNotNull(anns);
                assertEquals(3, anns.length);
                AnnotationInfo ai = anns[0];
                assertSame(ai, getAnnotation(ci, MadvocAction.class));
                assertEquals(MadvocAction.class.getName(), ai.getAnnotationClassname());
                assertEquals("L" + MadvocAction.class.getName().replace('.', '/') + ";", ai.getAnnotationSignature());
                assertEquals("madvocAction", ai.getElement("value"));
                ai = anns[1];
                assertSame(ai, getAnnotation(ci, PetiteBean.class));
                assertEquals(PetiteBean.class.getName(), ai.getAnnotationClassname());
                assertEquals("L" + PetiteBean.class.getName().replace('.', '/') + ";", ai.getAnnotationSignature());
                ai = anns[2];
                assertSame(ai, getAnnotation(ci, InterceptedBy.class));
                assertEquals(InterceptedBy.class.getName(), ai.getAnnotationClassname());
                assertEquals("L" + InterceptedBy.class.getName().replace('.', '/') + ";", ai.getAnnotationSignature());
                assertTrue(ai.getElement("value") instanceof Object[]);
                assertFalse(ai.getElement("value") instanceof String[]);
                Object c1 = ((Object[]) ai.getElement("value"))[0];
                assertEquals("Ljodd/proxetta/data/Str;", ((Type) c1).getDescriptor());
            }
            if (mi.getMethodName().equals("publicMethod")) {
                AnnotationInfo[] anns = mi.getAnnotations();
                assertNotNull(anns);
                assertEquals(3, anns.length);
                AnnotationInfo ai = anns[0];
                assertSame(ai, getAnnotation(mi, Action.class));
                assertEquals(Action.class.getName(), ai.getAnnotationClassname());
                assertEquals("value", ai.getElement("value"));
                assertEquals("alias", ai.getElement("alias"));
                ai = anns[1];
                assertSame(ai, getAnnotation(mi, PetiteInject.class));
                assertEquals(PetiteInject.class.getName(), ai.getAnnotationClassname());
                assertEquals(0, ai.getElementNames().size());
                ai = anns[2];
                assertSame(ai, getAnnotation(mi, Transaction.class));
                assertEquals(Transaction.class.getName(), ai.getAnnotationClassname());
                assertEquals(2, ai.getElementNames().size());
                String s = (String) ai.getElement("propagation");
                assertEquals("PROPAGATION_REQUIRES_NEW", s);
            }
            if (mi.getMethodName().equals("superPublicMethod")) {
                AnnotationInfo[] anns = mi.getAnnotations();
                assertNotNull(anns);
                assertEquals(3, anns.length);
                AnnotationInfo ai = anns[0];
                assertSame(ai, getAnnotation(mi, Action.class));
                assertEquals(Action.class.getName(), ai.getAnnotationClassname());
                assertEquals(0, ai.getElementNames().size());
                ai = anns[1];
                assertSame(ai, getAnnotation(mi, PetiteInject.class));
                assertEquals(PetiteInject.class.getName(), ai.getAnnotationClassname());
                assertEquals(0, ai.getElementNames().size());
                ai = anns[2];
                assertSame(ai, getAnnotation(mi, Transaction.class));
                assertEquals(Transaction.class.getName(), ai.getAnnotationClassname());
                assertEquals(0, ai.getElementNames().size());
            }
            //System.out.println(!isRootMethod(mi) + " " + mi.getDeclaredClassName() + '#' + mi.getMethodName());
            return !isRootMethod(mi);
        }
    });
    byte[] classBytes = ProxyProxetta.withAspects(aspect).builder(BigFatJoe.class).create();
    //		URL resource = BigFatJoe.class.getResource("/" + BigFatJoe.class.getName().replace(".", "/") + ".class");
    //		jodd.io.FileUtil.copy(FileUtil.toFile(resource), new java.io.File(SystemUtil.getUserHome(), "jo.class"));
    //		jodd.io.FileUtil.writeBytes(new java.io.File(SystemUtil.getUserHome(), "joe.class"), classBytes);
    Class clazz = ClassLoaderUtil.defineClass(null, classBytes);
    BigFatJoe bigFatJoe = (BigFatJoe) clazz.newInstance();
    assertEquals(BigFatJoe.class.getName() + "$$Proxetta", bigFatJoe.getClass().getName());
    assertEquals(BigFatJoe.class, ProxettaUtil.getTargetClass(bigFatJoe.getClass()));
    // test invocation
    // 2 x static + 1 x instance
    assertEquals(3, StatCounter.counter);
    bigFatJoe.publicMethod();
    assertEquals(4, StatCounter.counter);
    bigFatJoe.callInnerMethods();
    // private method is not overridden
    assertEquals(7, StatCounter.counter);
    bigFatJoe.superPublicMethod();
    assertEquals(8, StatCounter.counter);
    bigFatJoe.callInnerMethods2();
    // only public super methods are overridden
    assertEquals(9, StatCounter.counter);
    // test class annotation
    MadvocAction ma = (MadvocAction) clazz.getAnnotation(MadvocAction.class);
    assertEquals("madvocAction", ma.value());
    InterceptedBy ib = (InterceptedBy) clazz.getAnnotation(InterceptedBy.class);
    assertNotNull(ib.value());
    assertEquals(2, ib.value().length);
    // test method annotation
    ClassDescriptor cd = ClassIntrospector.lookup(clazz);
    Method m = cd.getMethodDescriptor("publicMethod", false).getMethod();
    assertNotNull(m);
    Annotation[] aa = m.getAnnotations();
    assertEquals(3, aa.length);
    Action a = (Action) aa[0];
    assertEquals("alias", a.alias());
    assertEquals("extension", a.extension());
    assertEquals("method", a.method());
    assertEquals("value", a.value());
    PetiteInject pi = (PetiteInject) aa[1];
    assertEquals("", pi.value());
    Transaction tx = (Transaction) aa[2];
    assertTrue(tx.readOnly());
    assertEquals(1000, tx.timeout());
    assertEquals("PROPAGATION_REQUIRES_NEW", tx.propagation());
    bigFatJoe.runInnerClass();
    // proxy + call
    assertEquals(11, StatCounter.counter);
}
Also used : ClassDescriptor(jodd.introspector.ClassDescriptor) MutableBoolean(jodd.mutable.MutableBoolean) Method(java.lang.reflect.Method) Annotation(java.lang.annotation.Annotation) Type(jodd.asm5.Type) ProxyPointcutSupport(jodd.proxetta.pointcuts.ProxyPointcutSupport) Test(org.junit.Test)

Example 23 with ClassDescriptor

use of jodd.introspector.ClassDescriptor in project jodd by oblac.

the class MapToBean method map2bean.

/**
	 * Converts map to target type.
	 */
public Object map2bean(Map map, Class targetType) {
    Object target = null;
    // create targets type
    String className = (String) map.get(classMetadataName);
    if (className == null) {
        if (targetType == null) {
            // nothing to do, no information about target type found
            target = map;
        }
    } else {
        try {
            targetType = ClassLoaderUtil.loadClass(className);
        } catch (ClassNotFoundException cnfex) {
            throw new JsonException(cnfex);
        }
    }
    if (target == null) {
        target = jsonParser.newObjectInstance(targetType);
    }
    ClassDescriptor cd = ClassIntrospector.lookup(target.getClass());
    boolean targetIsMap = target instanceof Map;
    for (Object key : map.keySet()) {
        String keyName = key.toString();
        if (classMetadataName != null) {
            if (keyName.equals(classMetadataName)) {
                continue;
            }
        }
        PropertyDescriptor pd = cd.getPropertyDescriptor(keyName, declared);
        if (!targetIsMap && pd == null) {
            // target property does not exist, continue
            continue;
        }
        // value is one of JSON basic types, like Number, Map, List...
        Object value = map.get(key);
        Class propertyType = pd == null ? null : pd.getType();
        Class componentType = pd == null ? null : pd.resolveComponentType(true);
        if (value != null) {
            if (value instanceof List) {
                if (componentType != null && componentType != String.class) {
                    value = generifyList((List) value, componentType);
                }
            } else if (value instanceof Map) {
                // if the value we want to inject is a Map...
                if (!ReflectUtil.isTypeOf(propertyType, Map.class)) {
                    // ... and if target is NOT a map
                    value = map2bean((Map) value, propertyType);
                } else {
                    // target is also a Map, but we might need to generify it
                    Class keyType = pd == null ? null : pd.resolveKeyType(true);
                    if (keyType != String.class || componentType != String.class) {
                        // generify
                        value = generifyMap((Map) value, keyType, componentType);
                    }
                }
            }
        }
        if (targetIsMap) {
            ((Map) target).put(keyName, value);
        } else {
            try {
                setValue(target, pd, value);
            } catch (Exception ignore) {
                ignore.printStackTrace();
            }
        }
    }
    return target;
}
Also used : ClassDescriptor(jodd.introspector.ClassDescriptor) PropertyDescriptor(jodd.introspector.PropertyDescriptor) List(java.util.List) Map(java.util.Map) HashMap(java.util.HashMap) InvocationTargetException(java.lang.reflect.InvocationTargetException)

Example 24 with ClassDescriptor

use of jodd.introspector.ClassDescriptor in project jodd by oblac.

the class TypeJsonSerializerMap method _lookup.

protected TypeJsonSerializer _lookup(Class type) {
    synchronized (map) {
        TypeJsonSerializer tjs = lookupSerializer(type);
        if (tjs != null) {
            return tjs;
        }
        ClassDescriptor cd = ClassIntrospector.lookup(type);
        if (cd.isArray()) {
            return lookupSerializer(Arrays.class);
        }
        // now iterate interfaces
        Class[] interfaces = cd.getAllInterfaces();
        for (Class interfaze : interfaces) {
            tjs = lookupSerializer(interfaze);
            if (tjs != null) {
                return tjs;
            }
        }
        // now iterate all superclases
        Class[] superclasses = cd.getAllSuperclasses();
        for (Class clazz : superclasses) {
            tjs = lookupSerializer(clazz);
            if (tjs != null) {
                return tjs;
            }
        }
        return lookupSerializer(Object.class);
    }
}
Also used : ClassDescriptor(jodd.introspector.ClassDescriptor)

Example 25 with ClassDescriptor

use of jodd.introspector.ClassDescriptor in project jodd by oblac.

the class TypeJsonVisitor method visit.

/**
	 * Visits a type.
	 */
public void visit() {
    ClassDescriptor classDescriptor = ClassIntrospector.lookup(type);
    if (classMetadataName != null) {
        // process first 'meta' fields 'class'
        onProperty(classMetadataName, null, false);
    }
    PropertyDescriptor[] propertyDescriptors = classDescriptor.getAllPropertyDescriptors();
    for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
        Getter getter = propertyDescriptor.getGetter(declared);
        if (getter != null) {
            String propertyName = propertyDescriptor.getName();
            boolean isTransient = false;
            // check for transient flag
            FieldDescriptor fieldDescriptor = propertyDescriptor.getFieldDescriptor();
            if (fieldDescriptor != null) {
                isTransient = Modifier.isTransient(fieldDescriptor.getField().getModifiers());
            }
            onProperty(propertyName, propertyDescriptor, isTransient);
        }
    }
}
Also used : ClassDescriptor(jodd.introspector.ClassDescriptor) PropertyDescriptor(jodd.introspector.PropertyDescriptor) Getter(jodd.introspector.Getter) FieldDescriptor(jodd.introspector.FieldDescriptor)

Aggregations

ClassDescriptor (jodd.introspector.ClassDescriptor)33 PropertyDescriptor (jodd.introspector.PropertyDescriptor)16 MethodDescriptor (jodd.introspector.MethodDescriptor)15 ArrayList (java.util.ArrayList)10 Method (java.lang.reflect.Method)8 FieldDescriptor (jodd.introspector.FieldDescriptor)5 Test (org.junit.Test)5 HashMap (java.util.HashMap)4 PetiteInject (jodd.petite.meta.PetiteInject)4 Map (java.util.Map)3 CtorDescriptor (jodd.introspector.CtorDescriptor)3 PetiteException (jodd.petite.PetiteException)3 Annotation (java.lang.annotation.Annotation)2 Constructor (java.lang.reflect.Constructor)2 Collection (java.util.Collection)2 LifeBean (jodd.bean.data.LifeBean)2 CachingIntrospector (jodd.introspector.CachingIntrospector)2 Field (java.lang.reflect.Field)1 InvocationTargetException (java.lang.reflect.InvocationTargetException)1 List (java.util.List)1