class EntityManagerFactoryDecorator implements TestClassDecorator {

    @Override
    public void afterAll(final TestInvocation invocation) throws Exception {
        // if EntityManager has been configured for EXTENDED transaction mode, same instance is used
        // throughout all the tests/test steps. In that case we have to close it here, before the
        // EntityManagerFactory is closed.
        ExecutionContext context = invocation.getContext();
        final EntityManager em = (EntityManager) context.getData(Constants.KEY_ENTITY_MANAGER);
        context.storeData(Constants.KEY_ENTITY_MANAGER, null);
        if (em != null) {
            em.close();
        }

        final EntityManagerFactory emf = (EntityManagerFactory) context.getData(Constants.KEY_ENTITY_MANAGER_FACTORY);
        context.storeData(Constants.KEY_ENTITY_MANAGER_FACTORY, null);
        emf.close();
    }

}