@Override public void inject(Object result, Field field) { try { String datasourceName = field.getAnnotation(RepositoryInject.class).datasource(); EntityManagerFactory emf = provider.getProvider(datasourceName); if (emf == null) return; Object repository = Proxy.newProxyInstance(RepositoryInjectStrategy.class.getClassLoader(), new Class[]{field.getType(), Repository.class}, new RepositoryInvocationHandler(field.getType(), emf)); field.setAccessible(true); field.set(result, repository); } catch (Exception e) { log.error("Failed to create repository {}", field.getType(), e); } }
public static Repositories setUpRepositoryProviderMock(Map<Class<?>, Repository<?, ?>> repositoriesMap) { Repositories mockRepositories = Mockito.mock(Repositories.class); when(mockRepositories.getRepositoryFor(any())).thenAnswer(new Answer<Object>() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { Class<?> entityClass = (Class<?>) invocation.getArguments()[0]; Repository<?, ?> repository = repositoriesMap.get(entityClass); if (repository == null) { throw new IllegalArgumentException("Unsupported class: " + entityClass.getName()); } return repository; } }); RepositoryProvider.setRepositories(mockRepositories); return mockRepositories; }
@Override protected Map<Class<?>, Repository<?, ?>> getRepositories() { Map<Class<?>, Repository<?, ?>> repositoriesMap = new HashMap<>(); repositoriesMap.put(DeviceAnonymized.class, deviceAnonymizedRepository); repositoriesMap.put(UserDevice.class, userDeviceRepository); repositoriesMap.put(Activity.class, activityRepository); return repositoriesMap; }
@Override protected Map<Class<?>, Repository<?, ?>> getRepositories() { Map<Class<?>, Repository<?, ?>> repositoriesMap = new HashMap<>(); repositoriesMap.put(DeviceAnonymized.class, deviceAnonymizedRepository); repositoriesMap.put(BuddyAnonymized.class, buddyAnonymizedRepository); return repositoriesMap; }
@Override protected Map<Class<?>, Repository<?, ?>> getRepositories() { Map<Class<?>, Repository<?, ?>> repositoriesMap = new HashMap<>(); repositoriesMap.put(MessageSource.class, mockMessageSourceRepository); return repositoriesMap; }
@Override protected Map<Class<?>, Repository<?, ?>> getRepositories() { Map<Class<?>, Repository<?, ?>> repositoriesMap = new HashMap<>(); repositoriesMap.put(DeviceAnonymized.class, deviceAnonymizedRepository); repositoriesMap.put(BuddyAnonymized.class, buddyAnonymizedRepository); repositoriesMap.put(Message.class, mockMessageRepository); return repositoriesMap; }
@Before public final void setUpPerTestBase() { MockitoAnnotations.initMocks(this); Map<Class<?>, Repository<?, ?>> repositoriesMap = new HashMap<>(); repositoriesMap.put(User.class, userRepository); repositoriesMap.put(UserAnonymized.class, userAnonymizedRepository); repositoriesMap.putAll(getRepositories()); Set<CrudRepository<?, ?>> crudRepositories = filterForCrudRepositories(repositoriesMap.values()); crudRepositories.forEach(CrudRepository::deleteAll); crudRepositories.stream().filter(this::isMock).forEach(r -> JUnitUtil.setUpRepositoryMock(r)); JUnitUtil.setUpRepositoryProviderMock(repositoriesMap); }
private Object generateCustomImplementation() { EntityManagerFactory emf = context.getBean(entityManagerFactoryRef, EntityManagerFactory.class); for (Class<?> clz : repositoryInterface.getInterfaces()) { if (Repository.class.isAssignableFrom(clz)) { continue; } else if (clz.getAnnotation(RepositoryDefinition.class) != null) { continue; } String implementation=clz.getName() + StringUtils.trimToEmpty(repositoryImplementationPostfix); ClassEx implClz = ClassEx.forName(implementation); if (implClz == null) { log.error("Lack of implementation class: " + clz.getName()); throw new IllegalArgumentException("Lack of implementation class: " + implementation); } try { Object obj = implClz.newInstance(); for (FieldEx field : implClz.getDeclaredFields()) { if (field.getAnnotation(PersistenceContext.class) != null) { field.set(obj, QueryUtils.getEntityManager((JefEntityManagerFactory) emf)); } } if (obj instanceof ApplicationContextAware) { ((ApplicationContextAware) obj).setApplicationContext(context); } if (obj instanceof InitializingBean) { ((InitializingBean) obj).afterPropertiesSet(); } return obj; } catch (Exception ex) { log.error("", ex); return null; } } return null; }
/** * @param entityToRepositoryMapping * @param bfName * @param bf * @throws ClassNotFoundException */ private void mapEntityToRepository(Map<Class<?>, String> entityToRepositoryMapping, String bfName, BeanDefinition bf) throws ClassNotFoundException { // Determine the Entity Class associated with the Repo // String value = (String)bf.getPropertyValues().getPropertyValue("repositoryInterface").getValue(); Class<?> repoInterface = Class.forName(value); Class<?> entityType = null; for(Type type : repoInterface.getGenericInterfaces()) { if (type instanceof ParameterizedType) { ParameterizedType parmType = (ParameterizedType)type; if (Repository.class.isAssignableFrom((Class<?>)parmType.getRawType()) && parmType.getActualTypeArguments() != null && parmType.getActualTypeArguments().length > 0) { entityType = (Class<?>)parmType.getActualTypeArguments()[0]; break; } } } if (entityType == null) { throw new RuntimeException("Unable to determine Entity type for class " + repoInterface.getName()); } // Map Entity to the RepositoryFactoryBeanSupport bean // logger.debug("Mapped \"{}\" to repo \"{}\", beanId=\"{}\"", entityType.getName(), value, bfName); entityToRepositoryMapping.put(entityType, bfName); }
@Before public void setUp() { Map<Class<?>, Repository<?, ?>> repositoriesMap = new HashMap<>(); repositoriesMap.put(DayActivity.class, mockDayActivityRepository); JUnitUtil.setUpRepositoryProviderMock(repositoriesMap); // created 2 weeks ago gamblingGoal = BudgetGoal.createNoGoInstance(TimeUtil.utcNow().minusWeeks(2), ActivityCategory.createInstance(UUID.randomUUID(), usString("gambling"), false, new HashSet<>(Arrays.asList("poker", "lotto")), Collections.emptySet(), usString("Descr"))); newsGoal = BudgetGoal.createNoGoInstance(TimeUtil.utcNow(), ActivityCategory.createInstance(UUID.randomUUID(), usString("news"), false, new HashSet<>(Arrays.asList("refdag", "bbc")), Collections.emptySet(), usString("Descr"))); gamingGoal = BudgetGoal.createNoGoInstance(TimeUtil.utcNow(), ActivityCategory.createInstance(UUID.randomUUID(), usString("gaming"), false, new HashSet<>(Arrays.asList("games")), Collections.emptySet(), usString("Descr"))); socialGoal = TimeZoneGoal.createInstance(TimeUtil.utcNow(), ActivityCategory.createInstance(UUID.randomUUID(), usString("social"), false, new HashSet<>(Arrays.asList("social")), Collections.emptySet(), usString("Descr")), Collections.emptyList()); shoppingGoal = BudgetGoal.createInstance(TimeUtil.utcNow(), ActivityCategory.createInstance(UUID.randomUUID(), usString("shopping"), false, new HashSet<>(Arrays.asList("webshop")), Collections.emptySet(), usString("Descr")), 1); goalMap.put("gambling", gamblingGoal); goalMap.put("news", newsGoal); goalMap.put("gaming", gamingGoal); goalMap.put("social", socialGoal); goalMap.put("shopping", shoppingGoal); when(mockYonaProperties.getAnalysisService()).thenReturn(new AnalysisServiceProperties()); // Set up UserAnonymized instance. MessageDestination anonMessageDestinationEntity = MessageDestination .createInstance(PublicKeyUtil.generateKeyPair().getPublic()); Set<Goal> goals = new HashSet<>(Arrays.asList(gamblingGoal, gamingGoal, socialGoal, shoppingGoal)); deviceAnonEntity = DeviceAnonymized.createInstance(0, OperatingSystem.ANDROID, "Unknown"); userAnonEntity = UserAnonymized.createInstance(anonMessageDestinationEntity, goals); userAnonEntity.addDeviceAnonymized(deviceAnonEntity); UserAnonymizedDto userAnon = UserAnonymizedDto.createInstance(userAnonEntity); userAnonZone = userAnon.getTimeZone(); userAnonId = userAnon.getId(); userId = UUID.randomUUID(); // Stub the UserService to return our user anonymized ID. when(mockUserService.getUserAnonymizedId(userId)).thenReturn(userAnonId); // Stub the UserAnonymizedService to return our user. when(mockUserAnonymizedService.getUserAnonymized(userAnonId)).thenReturn(userAnon); when(mockUserAnonymizedService.getUserAnonymizedEntity(userAnonId)).thenReturn(userAnonEntity); // Stub the GoalService to return our goals. when(mockGoalService.getGoalEntityForUserAnonymizedId(userAnonId, gamblingGoal.getId())).thenReturn(gamblingGoal); when(mockGoalService.getGoalEntityForUserAnonymizedId(userAnonId, newsGoal.getId())).thenReturn(newsGoal); when(mockGoalService.getGoalEntityForUserAnonymizedId(userAnonId, gamingGoal.getId())).thenReturn(gamingGoal); when(mockGoalService.getGoalEntityForUserAnonymizedId(userAnonId, socialGoal.getId())).thenReturn(socialGoal); when(mockGoalService.getGoalEntityForUserAnonymizedId(userAnonId, shoppingGoal.getId())).thenReturn(shoppingGoal); }
private Set<CrudRepository<?, ?>> filterForCrudRepositories(Collection<Repository<?, ?>> values) { return values.stream().filter(r -> r instanceof CrudRepository).map(r -> (CrudRepository<?, ?>) r) .collect(Collectors.toSet()); }
@Before public void setUp() { this.factoryBean = new KeyValueRepositoryFactoryBean<Repository<Object, Object>, Object, Object>( SampleRepository.class); }
protected abstract Map<Class<?>, Repository<?, ?>> getRepositories();