Created
August 10, 2012 19:33
-
-
Save jdewind/3317242 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment