@Override public boolean hasPermission(@NotNull Authentication authentication, @NotNull Serializable serializable, @NotNull String className, @NotNull Object permissions) { boolean result = false; CrudRepository<Object, Serializable> repository = repositoryFinder.find(className); if (repository != null) { Object targetDomainObject = repository.findOne(serializable); if (targetDomainObject instanceof CreatorAware) { result = hasPermission(authentication, targetDomainObject, permissions); } else if (targetDomainObject == null) { result = true; } } return result; }
@Then("^the database will be empty$") public void the_database_will_be_empty() throws Throwable { ClosureService closureService = getBean(ClosureService.class); Map<String, CrudRepository> crudRepositories = getBeansOfType(CrudRepository.class); for (final Map.Entry<String, CrudRepository> repository : crudRepositories.entrySet()) { Closure checkEmpty = new Closure() { @Override public void execute() throws Exception { long entityCount = repository.getValue().count(); String message = format("%s must be empty but is %s", repository.getKey(), entityCount); assertThat(message, entityCount, is(EMPTY)); } }; closureService.execute(checkEmpty); } }
public void setUpDomainClassAnalyzer(CrudRepository crudRepository, User user) throws ReflectiveOperationException { Map<String, DomainClass> domainMap = new HashMap<>(); List<String> tablesExpected = new ArrayList<>(); tablesExpected.add("user"); DomainClass domainClass = new DomainClass(); domainClass.setDomainClass(User.class); domainClass.setCrudRepository(crudRepository); OneToOneRequester cartSQLRequester = new OneToOneRequester(); cartSQLRequester.setAssociatedField(User.class.getDeclaredField("cart")); Map<String, SQLRequester> sqlRequesterMap = new HashMap<>(); sqlRequesterMap.put("cart", cartSQLRequester); domainClass.setSqlRequesters(sqlRequesterMap); domainMap.put("user", domainClass); when(domainClassAnalyzer.getDomainClassMap()).thenReturn(domainMap); when(domainClassAnalyzer.getMappingTablesExpected()).thenReturn(tablesExpected); doReturn(user).when(domainClassAnalyzer).generateInstanceFromName("user"); }
public RichObjectRepositoryImpl( Class<RichObjectType> domainClass, Class<RichObjectImplementation> implementationClass, Class<EntityType> entityType, CrudRepository<EntityType, ID> entityRepository, final ApplicationContext applicationContext) { this.domainClass = domainClass; this.entityRepository = entityRepository; this.applicationContext = applicationContext; try { entityField = findEntityField(implementationClass, entityType); } catch (NoSuchFieldException | IllegalAccessException e) { throw propagate(e); } }
public CrudRepository<Object, Serializable> find(@NotNull String domainClassName) { try { return this.find(Class.forName(domainClassName)); } catch (ClassNotFoundException e) { throw new RepositoryCouldNotBeFoundException("Could not find a Repository for Domain class: " + domainClassName); } }
@SuppressWarnings(value = "unchecked") public CrudRepository<Object, Serializable> find(@NotNull Class<?> domainClass) { Repositories repositories = new Repositories(listableBeanFactory); Iterator<Class<?>> it = repositories.iterator(); while (it.hasNext()) { Object repository = repositories.getRepositoryFor(domainClass); if (repository != null && repository instanceof CrudRepository) { return (CrudRepository<Object, Serializable>)repository; } } return null; }
@Override protected void doInitTestData(CrudRepository<Product, String> repository) { Product playstation = Product.builder().id("id-1").name("Playstation") .description("The Sony playstation was the top selling gaming system in 1994.").popularity(5).build(); Product playstation2 = Product.builder().id("id-2").name("Playstation Two") .description("Playstation two is the successor of playstation in 2000.").build(); Product superNES = Product.builder().id("id-3").name("Super Nintendo").popularity(3).build(); Product nintendo64 = Product.builder().id("id-4").name("N64").description("Nintendo 64").popularity(2).build(); repository.save(Arrays.asList(playstation, playstation2, superNES, nintendo64)); }
@Override public void run(String... arg0) throws Exception { for (final CrudRepository cr : repositories) { System.err.println(getRepositoryName(cr.getClass()) + " has " + cr.count() + ". <<DBCountRunner>>"); } }
@Override public void dataImport(ApplicationContext applicationContext, Map<String, List<Serializable>> importData) { for (Entry<String, List<Serializable>> entry : importData.entrySet()) { @SuppressWarnings("unchecked") CrudRepository<Serializable, Serializable> crudDao = applicationContext.getBean(entry.getKey(), CrudRepository.class); crudDao.save(entry.getValue()); } }
@Test public void shouldCreate() throws Exception { CrudRepository<T, UUID> repository = this.getRepository(); T instance = this.generateInstance(); Assert.assertNull(instance.getId()); instance = repository.save(instance); assertInstance(instance); Assert.assertTrue(repository.exists(instance.getId())); }
@Test public void shouldFindOne() throws Exception { CrudRepository<T, UUID> repository = this.getRepository(); T instance = this.generateInstance(); instance = repository.save(instance); assertInstance(instance); UUID id = instance.getId(); instance = repository.findOne(id); assertInstance(instance); Assert.assertEquals(id, instance.getId()); }
@Test public void shouldDelete() throws Exception { CrudRepository<T, UUID> repository = this.getRepository(); T instance = this.generateInstance(); assertNotNull(instance); instance = repository.save(instance); assertInstance(instance); UUID id = instance.getId(); repository.delete(id); Assert.assertFalse(repository.exists(id)); }
/** * This method is part of CommandLineRunner and is called automatically by Spring. * @param args Main method arguments. */ public void run(String... args) { //Get all JaVers repositories. Map<String,Object> repositoryMap = applicationContext.getBeansWithAnnotation(JaversSpringDataAuditable.class); //For each one... for (Object object : repositoryMap.values()) { if (object instanceof PagingAndSortingRepository) { createSnapshots((PagingAndSortingRepository<?, ?>) object); } else if (object instanceof CrudRepository) { createSnapshots((CrudRepository<?, ?>) object); } } }
private <T extends ContentEntity> T safeGet(ContentDto s, CrudRepository<? extends T, UUID> repo, T newEntity) { try { T entity = repo.findOne(s.getId()); return entity; } catch (Exception e) { return newEntity; } }
private <T extends BaseEntity, U> void updateCollection(Collection<T> currentValues, Collection<U> updatedValues, Supplier<T> newInstance, Function<U, String> idFun, Function<U, Function<T, T>> updateFunctionSupplier, CrudRepository<T, String> repository) { Map<String, List<T>> valuesMap = currentValues.stream() .collect(Collectors.groupingBy(T::getId)); List<String> newIds = updatedValues .stream() .map(newCollectionItem -> { Optional<T> existingItem = ofNullable(valuesMap.get(idFun.apply(newCollectionItem))) .flatMap(toFirst()); if (existingItem.isPresent()) { return repository.save(updateFunctionSupplier.apply(newCollectionItem).apply(existingItem.get())); } else { T newItem = newInstance.get(); repository.save(updateFunctionSupplier.apply(newCollectionItem).apply(newItem)); currentValues.add(newItem); return newItem; } }) .map(T::getId) .collect(Collectors.toList()); currentValues .stream() .filter(notIn(newIds)) .collect(Collectors.toList()) .forEach(removeFrom(currentValues, repository)); }
@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); }
@SuppressWarnings("unchecked") public static <T, ID extends Serializable> void setUpRepositoryMock(CrudRepository<T, ID> mockRepository) { // save should not return null but the saved entity when(mockRepository.save(Matchers.<T> any())).thenAnswer(new Answer<T>() { @Override public T answer(InvocationOnMock invocation) throws Throwable { Object[] args = invocation.getArguments(); return (T) args[0]; } }); }
@Override public void handleBeanEntry(Object bean, String documentType) { log.info("Mapping '" + documentType + "' to bean '" + bean.getClass().getCanonicalName() + "'"); if (bean instanceof CrudRepository) { crudRepositoryRegistry.put(documentType, (CrudRepository<? extends BaseDocument, String>) bean); } else if (bean instanceof CrudService) { crudServiceRegistry.put(documentType, (CrudService<? extends BaseDocument>) bean); } else if (bean instanceof PersistenceListenerManager) { persistenceListenerManagerRegistry.put(documentType, (PersistenceListenerManager<? extends BaseDocument>) bean); } }
public CrudRepository<? extends BaseDocument, String> getCrudRepository(Class clazz) { String documentType = getDocumentType(clazz); if (clazz != null) { return getCrudRepository(documentType); } else return null; }
@PostConstruct public void init() { String documentType = applicationRegistry.getDocumentType((Class) type); this.repository = (CrudRepository<T, String>) applicationRegistry.getCrudRepository((Class) type); this.service = (CrudService<T>) applicationRegistry.getCrudService((Class) type); this.documentProvider = (DocumentProvider<T>) testRegistry.getDocumentBuilder(documentType); log.info("Initializing TimeProvider mocks..."); EasyMock.resetToNice(service.getTimeProvider()); EasyMock.expect(service.getTimeProvider().getSystemTimeMillis()).andStubReturn(1000L); }
private Class getEntityClassForRepository(CrudRepository repo) { Class<?> originalInterface = repo.getClass().getInterfaces()[0]; EntityType annotation = originalInterface.getAnnotation(EntityType.class); if (annotation == null) { throw new IllegalStateException("Entity class is not specified for repository: " + originalInterface.getSimpleName()); } return annotation.entityClass(); }
@Override public void onApplicationEvent(ContextRefreshedEvent event) { if (event.getApplicationContext().equals(applicationContext)) { CrudRepository albumRepository = BeanFactoryUtils.beanOfTypeIncludingAncestors(applicationContext, CrudRepository.class); if (albumRepository != null && albumRepository.count() == 0) { populate(albumRepository); } } }
@SuppressWarnings("unchecked") public void populate(CrudRepository repository) { Object entity = getEntityFromResource(sourceData); if (entity instanceof Collection) { for (Album album : (Collection<Album>) entity) { if (album != null) { repository.save(album); } } } else { repository.save(entity); } }
private Optional<Class> getRepositoryInterface(JoinPoint pjp) { for (Class i : pjp.getTarget().getClass().getInterfaces()) { if (i.isAnnotationPresent(JaversSpringDataAuditable.class) && CrudRepository.class.isAssignableFrom(i)) { return Optional.of(i); } } return Optional.empty(); }
public static void registerRepository(String name, CrudRepository repository) { if (repositoryMap == null) { throw new IllegalStateException("Repository registry was not initialized."); } repositoryMap.putIfAbsent(name, repository); }
public static CrudRepository getRepositoryByEntityName(String entitiyName) { if (repositoryMap == null) { throw new IllegalStateException("Repository registry was not initialized."); } return repositoryMap.get(entitiyName); }
@Override protected CrudRepository<Cliente, Long> getCrudRepository() { return clienteRepository; }
@Override protected CrudRepository<Pedido, Long> getCrudRepository() { return pedidoRepository; }
@Override protected CrudRepository<Produto, Long> getCrudRepository() { return produtoRepository; }
protected void doInitTestData(CrudRepository<Product, String> repository) { IntStream.range(0, 100) .forEach(index -> repository.save(Product.builder().id("p-" + index).name("foobar").build())); }
@Override public CrudRepository<Product, String> getRepository() { return this.productRepository; }
@Override public CrudRepository<User, String> getRepository() { return this.userRepository; }
@Override public CrudRepository<Rating, Long> getRepository() { return this.ratingRepository; }
@Override protected CrudRepository<CustomerEntity, String> getCrudRepository() { return customerRepository; }
@Override protected CrudRepository<PluginMetaDataEntity, String> getCrudRepository() { return pluginMetaDataRepository; }
@Override protected CrudRepository<DashboardEntity, String> getCrudRepository() { return dashboardRepository; }
@Override protected CrudRepository getCrudRepository() { return dashboardInfoRepository; }
@Override protected CrudRepository<DeviceCredentialsEntity, String> getCrudRepository() { return deviceCredentialsRepository; }
@Override protected CrudRepository<DeviceEntity, String> getCrudRepository() { return deviceRepository; }
@Override protected CrudRepository<UserCredentialsEntity, String> getCrudRepository() { return userCredentialsRepository; }