PageRenderTime 17ms CodeModel.GetById 11ms app.highlight 4ms RepoModel.GetById 1ms app.codeStats 0ms

/sigmah/src/test/java/org/sigmah/MockDb.java

http://sigma-h.googlecode.com/
Java | 86 lines | 60 code | 22 blank | 4 comment | 13 complexity | 66ebfa6859be21bdcb2716a5e477e390 MD5 | raw file
 1/*
 2 * All Sigmah code is released under the GNU General Public License v3
 3 * See COPYRIGHT.txt and LICENSE.txt.
 4 */
 5
 6package org.sigmah;
 7
 8
 9
10import javax.persistence.Id;
11
12import org.sigmah.shared.dao.DAO;
13
14import java.lang.reflect.*;
15import java.util.ArrayList;
16import java.util.List;
17
18public class MockDb {
19
20    private List entities = new ArrayList(0);
21
22    public MockDb() {
23
24    }
25
26    public Object findById(Class entityClass, Object primaryKey) {
27        if (primaryKey == null) {
28            return null;
29        }
30
31        for (Object entity : entities) {
32            if (entity.getClass().equals(entityClass) && primaryKey.equals(getId(entity))) {
33                return entity;
34            }
35        }
36        return null;
37    }
38
39    public void persist(Object entity) {
40        entities.add(entity);
41    }
42
43    private Object getId(Object t) {
44        for (Method method : t.getClass().getMethods()) {
45            if (method.getAnnotation(Id.class) != null) {
46                try {
47                    return method.invoke(t);
48                } catch (Exception e) {
49                    throw new RuntimeException(e);
50                }
51            }
52        }
53        throw new RuntimeException("No @Id field!");
54    }
55
56    public <S extends DAO> S getDAO(Class<S> daoSubClass) {
57        ClassLoader cl = daoSubClass.getClassLoader();
58        Type daoClass = daoSubClass.getGenericInterfaces()[0];
59        Class persistentClass = (Class)((ParameterizedType) daoClass).getActualTypeArguments()[0];
60        return (S) Proxy.newProxyInstance(cl, new Class[]{daoSubClass}, new Handler(persistentClass));
61    }
62
63
64    public class Handler implements InvocationHandler {
65
66        private final Class persistentClass;
67
68        public Handler(Class persistentClass) {
69            this.persistentClass = persistentClass;
70        }
71
72        @Override
73        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
74
75            if (method.getName().equals("findById")) {
76                return findById(persistentClass, args[0]);
77            } else if (method.getName().equals("persist")) {
78                persist(args[0]);
79            } else if (method.getReturnType().equals(Boolean.TYPE)) {
80                return false;
81            }
82            return null;
83        }
84    }
85
86}