Clover icon

sunshower-base

  1. Project Clover database Mon May 7 2018 22:12:38 UTC
  2. Package io.sunshower.test.persist

File AuthenticationTestExecutionListener.java

 

Coverage histogram

../../../../img/srcFileCovDistChart0.png
49% of files have more coverage

Code metrics

22
83
17
1
240
208
32
0.39
4.88
17
1.88

Classes

Class Line # Actions
AuthenticationTestExecutionListener 26 83 32
0.00%
 

Contributing tests

No tests hitting this source file were found.

Source view

1    package io.sunshower.test.persist;
2   
3    import static org.hamcrest.CoreMatchers.*;
4   
5    import java.lang.reflect.Field;
6    import java.lang.reflect.InvocationTargetException;
7    import java.lang.reflect.Method;
8    import java.lang.reflect.Parameter;
9    import java.util.*;
10    import javax.persistence.EntityManager;
11    import javax.persistence.EntityManagerFactory;
12    import javax.persistence.PersistenceContext;
13    import org.junit.Assert;
14    import org.springframework.aop.support.AopUtils;
15    import org.springframework.context.ApplicationContext;
16    import org.springframework.orm.jpa.EntityManagerHolder;
17    import org.springframework.security.core.GrantedAuthority;
18    import org.springframework.test.context.TestContext;
19    import org.springframework.test.context.support.AbstractTestExecutionListener;
20    import org.springframework.transaction.annotation.Isolation;
21    import org.springframework.transaction.annotation.Transactional;
22    import org.springframework.transaction.support.TransactionSynchronizationManager;
23   
24    @SuppressWarnings("all")
25    @Transactional(isolation = Isolation.READ_UNCOMMITTED)
 
26    public class AuthenticationTestExecutionListener extends AbstractTestExecutionListener {
27   
28    @PersistenceContext private EntityManager entityManager;
29   
30    final Map<String, Object> userCache = new HashMap<>();
31   
 
32  0 toggle public void beforeTestClass(TestContext ctx) {
33  0 ctx.getApplicationContext().getAutowireCapableBeanFactory().autowireBean(this);
34    }
35   
 
36  0 toggle @Override
37    public int getOrder() {
38  0 return 9999;
39    }
40   
 
41  0 toggle @Override
42    public void beforeTestMethod(TestContext testContext) throws Exception {
43  0 Assert.assertThat(entityManager, is(not(nullValue())));
44  0 Map<String, GrantedAuthority> authorities =
45    collectRoles(
46    entityManager,
47    testContext.getTestClass(),
48    testContext.getTestInstance(),
49    testContext.getApplicationContext());
50   
51  0 saveAuthorities(authorities);
52  0 saveFields(testContext.getTestClass(), testContext.getTestInstance(), authorities);
53   
54  0 saveMethods(testContext.getTestClass(), testContext.getTestInstance(), authorities);
55    }
56   
 
57  0 toggle private void resolveEntityManager(TestContext testContext) {
58  0 EntityManagerFactory emf =
59    testContext.getApplicationContext().getBean(EntityManagerFactory.class);
60  0 EntityManagerHolder holder =
61    (EntityManagerHolder) TransactionSynchronizationManager.getResource(emf);
62  0 this.entityManager = holder.getEntityManager();
63    }
64   
 
65  0 toggle private void saveAuthorities(Map<String, GrantedAuthority> authorities) {
66  0 for (GrantedAuthority authority : authorities.values()) {
67  0 entityManager.persist(authority);
68    }
69  0 entityManager.flush();
70    }
71   
 
72  0 toggle private Map<String, GrantedAuthority> collectRoles(
73    EntityManager bean,
74    Class<?> testClass,
75    Object testInstance,
76    ApplicationContext applicationContext) {
77   
78  0 final Map<String, GrantedAuthority> authorities = new HashMap<>();
79   
80  0 try {
81  0 collectRolesOnMethods(bean, testClass, testInstance, authorities);
82    } catch (Exception e) {
83  0 throw new RuntimeException(e);
84    }
85  0 return authorities;
86    }
87   
 
88  0 toggle private void collectRolesOnMethods(
89    EntityManager bean,
90    Class<?> testClass,
91    Object testInstance,
92    Map<String, GrantedAuthority> authorities)
93    throws InvocationTargetException, IllegalAccessException {
94   
95  0 for (Class<?> current = testClass; current != null; current = current.getSuperclass()) {
96  0 for (Method m : current.getDeclaredMethods()) {
97  0 if (m.isAnnotationPresent(Authority.class)) {
98  0 if (m.getParameterCount() == 0) {
99  0 Class<?> type = m.getReturnType();
100  0 checkType(current, m, type);
101  0 m.setAccessible(true);
102  0 GrantedAuthority authority = (GrantedAuthority) m.invoke(testInstance);
103  0 final String name = authority.getAuthority();
104  0 authorities.put(name, authority);
105    } else {
106  0 throw new InvalidTestException(
107    String.format(
108    "Method '%s' on type '%s' has " + "more than zero arguments", m, current));
109    }
110    }
111    }
112    }
113    }
114   
 
115  0 toggle private void checkType(Class<?> current, Method m, Class<?> type) {
116  0 if (!GrantedAuthority.class.isAssignableFrom(type)) {
117  0 throw new InvalidTestException(
118    String.format(
119    "Method '%s' on type '%s' has "
120    + "return type '%s', which is not "
121    + "assignable from GrantedAuthority",
122    m, current, type));
123    }
124    }
125   
 
126  0 toggle private void collectRolesOnFields(
127    EntityManagerFactory bean,
128    Class<?> testClass,
129    Object testInstance,
130    Map<String, GrantedAuthority> repository) {}
131   
 
132  0 toggle private void saveMethods(
133    Class<?> testClass, Object testInstance, Map<String, GrantedAuthority> authorities) {
134  0 Set<Object> users = usersFromMethods(testClass, testInstance, authorities);
135  0 saveAll(users, testClass);
136    }
137   
 
138  0 toggle private void saveFields(
139    Class<?> testClass, Object instance, Map<String, GrantedAuthority> authorities) {
140  0 Set<Object> users = collectUsers(testClass, instance);
141  0 saveAll(users, testClass);
142    }
143   
 
144  0 toggle private Set<Object> usersFromMethods(
145    Class<?> testClass, Object testInstance, Map<String, GrantedAuthority> authorities) {
146   
147  0 Set<Object> users = new HashSet<>();
148  0 for (Class<?> type = testClass; type != null; type = type.getSuperclass()) {
149  0 for (Method f : type.getDeclaredMethods()) {
150  0 if (f.isAnnotationPresent(Principal.class)) {
151  0 f.setAccessible(true);
152  0 GrantedAuthority[] arguments = resolveAuthorities(f, authorities);
153  0 try {
154  0 Object user = f.invoke(testInstance, (Object[]) arguments);
155  0 users.add(user);
156    } catch (Exception e) {
157  0 throw new IllegalStateException(e);
158    }
159    }
160    }
161    }
162  0 return users;
163    }
164   
 
165  0 toggle private GrantedAuthority[] resolveAuthorities(
166    Method f, Map<String, GrantedAuthority> authorities) {
167  0 Parameter[] parameters = f.getParameters();
168  0 GrantedAuthority[] results = new GrantedAuthority[parameters.length];
169  0 for (int i = 0; i < parameters.length; i++) {
170  0 Parameter p = parameters[i];
171  0 Authority a = p.getAnnotation(Authority.class);
172   
173  0 GrantedAuthority o = findAuthority(a, authorities);
174  0 results[i] = o;
175    }
176  0 return results;
177    }
178   
 
179  0 toggle private GrantedAuthority findAuthority(Authority a, Map<String, GrantedAuthority> authorities) {
180  0 GrantedAuthority authority = authorities.get(a.value());
181  0 if (authority == null) {
182  0 throw new IllegalStateException("Dunno what's up with this");
183    }
184  0 final Class<GrantedAuthority> type =
185    (Class<GrantedAuthority>) AopUtils.getTargetClass(authority);
186  0 final String simpleName = type.getSimpleName();
187  0 final String query =
188    String.format("select a " + "from %s as a where " + "a.authority = :authority", simpleName);
189  0 final List<GrantedAuthority> result =
190    entityManager.createQuery(query, type).setParameter("authority", a.value()).getResultList();
191  0 if (result.isEmpty()) {
192  0 throw new NoSuchElementException(
193    String.format(
194    "No authority named '%s' "
195    + "found--did you created it with an @Authority "
196    + "annotation somewhere in your test context?",
197    a.value()));
198    }
199  0 return result.get(0);
200    }
201   
 
202  0 toggle private synchronized void saveAll(Set<Object> users, Class<?> testClass) {
203  0 for (Object user : users) {
204  0 String id = id(user);
205  0 entityManager.persist(user);
206    }
207  0 entityManager.flush();
208    }
209   
210    // Meh. Don't clutter the classpath with api
211   
 
212  0 toggle private String id(Object o) {
213  0 try {
214  0 Field id = o.getClass().getDeclaredField("username");
215  0 id.setAccessible(true);
216  0 return (String) id.get(o);
217   
218    } catch (Exception e) {
219  0 throw new IllegalStateException();
220    }
221    }
222   
 
223  0 toggle private Set<Object> collectUsers(Class<?> testClass, Object instance) {
224  0 final Set<Object> users = new HashSet<>();
225  0 for (Class<?> type = testClass; type != null; type = type.getSuperclass()) {
226  0 for (Field f : type.getDeclaredFields()) {
227  0 if (f.isAnnotationPresent(Principal.class)) {
228  0 f.setAccessible(true);
229  0 try {
230  0 Object user = f.get(instance);
231  0 users.add(user);
232    } catch (IllegalAccessException e) {
233  0 throw new IllegalStateException(e);
234    }
235    }
236    }
237    }
238  0 return users;
239    }
240    }