public
Created

  • Download Gist
RefreshEntityInterceptor.java
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
public class RefreshEntityInterceptor implements MethodInterceptor {
 
@Inject
private Provider<EntityManager> entityManagerProvider;
 
@Inject
protected Logger logger;
 
 
@SuppressWarnings("unchecked")
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
try {
Object result = methodInvocation.proceed();
List<Object> entities;
 
if(result == null) {
return result;
}
 
if(!Collection.class.isAssignableFrom(result.getClass())) {
entities = new ArrayList<Object>();
entities.add(result);
} else {
entities = new ArrayList<Object>((Collection)result);
}
 
EntityManager entityManager = entityManagerProvider.get();
for (Object entity : entities) {
if(entityManager.contains(entity)) {
clearAllCollections(entity);
entityManager.refresh(entity);
}
}
 
return result;
} catch (Throwable throwable) {
logger.error("Failed to refresh entity", throwable);
throw throwable;
}
}
 
private void clearAllCollections(Object entity) {
clearAllCollectionsOnMethods(entity);
clearAllCollectionsOnFields(entity);
}
 
private void clearAllCollectionsOnFields(Object entity) {
Field[] fields = entity.getClass().getDeclaredFields();
for (Field field : fields) {
if(field.isAnnotationPresent(OneToMany.class)) {
try {
field.setAccessible(true);
Object result = field.get(entity);
if(result != null) {
Collection collection = (Collection) result;
collection.clear();
}
} catch (IllegalAccessException e) {
logger.error("Could not clear entity collection before refreshing", e);
}
}
}
}
 
private void clearAllCollectionsOnMethods(Object entity) {
Method[] methods = entity.getClass().getMethods();
for (Method method : methods) {
if(method.isAnnotationPresent(OneToMany.class)) {
try {
method.setAccessible(true);
Object result = method.invoke(entity);
Collection collection = (Collection) result;
if(result != null) {
collection.clear();
}
} catch (IllegalAccessException e) {
logger.error("Could not clear entity collection before refreshing", e);
} catch (InvocationTargetException e) {
logger.error("Could not clear entity collection before refreshing", e);
}
}
}
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.