dsSortBy = DataSourceSortMapper.map(Arrays.asList(StringUtils.split(sortBy, ",")));
- Sort sort = new Sort(Sort.Direction.fromString(order), dsSortBy);
- return new PageRequest(pageDTO.getPage() - 1, pageDTO.getPageSize(), sort);
+ String[] dsSortBy = DataSourceSortMapper.map(Arrays.asList(StringUtils.split(sortBy, ","))).stream().toArray(String[]::new);
+ Sort sort = Sort.by(Sort.Direction.fromString(order), dsSortBy);
+ return PageRequest.of(pageDTO.getPage() - 1, pageDTO.getPageSize(), sort);
}
@Override
diff --git a/src/main/java/com/odysseusinc/arachne/portal/service/impl/BasePaperServiceImpl.java b/src/main/java/com/odysseusinc/arachne/portal/service/impl/BasePaperServiceImpl.java
index 3fdb18e2d..5444bfa81 100644
--- a/src/main/java/com/odysseusinc/arachne/portal/service/impl/BasePaperServiceImpl.java
+++ b/src/main/java/com/odysseusinc/arachne/portal/service/impl/BasePaperServiceImpl.java
@@ -167,7 +167,7 @@ protected void beforePaperSave(P newPaper) {
public Page getPapersAccordingToCurrentUser(PS paperSearch, IUser user) {
final PaperSpecification
paperSpecification = new PaperSpecification<>(paperSearch, user);
- return paperRepository.findAll(paperSpecification, new PageRequest(paperSearch.getPage(), paperSearch.getPageSize()));
+ return paperRepository.findAll(paperSpecification, PageRequest.of(paperSearch.getPage(), paperSearch.getPageSize()));
}
@@ -179,7 +179,7 @@ public P get(Long id) {
private P getPaperByIdOrThrow(Long id) {
- return Optional.ofNullable(paperRepository.findOne(id))
+ return Optional.ofNullable(paperRepository.getOne(id))
.orElseThrow(() -> new NotExistException(Paper.class));
}
@@ -237,9 +237,7 @@ public void delete(Long id) throws FileNotFoundException {
}
}
);
- if (paperRepository.deleteById(id) == 0) {
- throw new NotExistException(Paper.class);
- }
+ paperRepository.deleteById(id);
}
@PreAuthorize("hasPermission(#paperId, 'Paper', "
@@ -329,13 +327,13 @@ public void deleteFile(Long paperId, String fileUuid, PaperFileType fileType) th
case PAPER: {
paperFile = paperPaperFileRepository.findByPaperIdAndUuid(paperId, fileUuid)
.orElseThrow(() -> new NotExistException(AbstractPaperFile.class));
- paperPaperFileRepository.delete(paperFile.getId());
+ paperPaperFileRepository.deleteById(paperFile.getId());
break;
}
case PROTOCOL: {
paperFile = paperProtocolFileRepository.findByPaperIdAndUuid(paperId, fileUuid)
.orElseThrow(() -> new NotExistException(AbstractPaperFile.class));
- paperProtocolFileRepository.delete(paperFile.getId());
+ paperProtocolFileRepository.deleteById(paperFile.getId());
break;
}
default: {
@@ -455,15 +453,15 @@ public void fullDelete(List
papers) {
for (P paper : papers) {
List paperPaperFiles = paper.getPapers();
- paperPaperFileRepository.delete(paperPaperFiles);
+ paperPaperFileRepository.deleteAll(paperPaperFiles);
fileService.delete(paperPaperFiles);
List protocolFiles = paper.getProtocols();
- paperProtocolFileRepository.delete(protocolFiles);
+ paperProtocolFileRepository.deleteAll(protocolFiles);
fileService.delete(protocolFiles);
}
- paperRepository.delete(papers);
+ paperRepository.deleteAll(papers);
}
@Override
@@ -505,7 +503,7 @@ public void processAntivirusResponse(AntivirusJobPaperProtocolFileResponseEvent
private void update(AntivirusJobResponseEventBase event, JpaRepository repository) {
final AntivirusJobResponse antivirusJobResponse = event.getAntivirusJobResponse();
- final AntivirusFile file = (AntivirusFile) repository.findOne(antivirusJobResponse.getFileId());
+ final AntivirusFile file = (AntivirusFile) repository.getOne(antivirusJobResponse.getFileId());
if (file != null) {
file.setAntivirusStatus(antivirusJobResponse.getStatus());
file.setAntivirusDescription(antivirusJobResponse.getDescription());
diff --git a/src/main/java/com/odysseusinc/arachne/portal/service/impl/BaseRoleServiceImpl.java b/src/main/java/com/odysseusinc/arachne/portal/service/impl/BaseRoleServiceImpl.java
index 37cc5773d..60e849a62 100644
--- a/src/main/java/com/odysseusinc/arachne/portal/service/impl/BaseRoleServiceImpl.java
+++ b/src/main/java/com/odysseusinc/arachne/portal/service/impl/BaseRoleServiceImpl.java
@@ -52,7 +52,7 @@ public R create(R role) throws NotUniqueException {
@Override
public R update(R role) throws NotUniqueException, NotExistException {
- if (!roleRepository.exists(role.getId())) {
+ if (!roleRepository.existsById(role.getId())) {
throw new NotExistException("update: role with id=" + role.getId() + " not exist", getType());
}
List roles = roleRepository.findByName(role.getName());
diff --git a/src/main/java/com/odysseusinc/arachne/portal/service/impl/BaseSkillServiceImpl.java b/src/main/java/com/odysseusinc/arachne/portal/service/impl/BaseSkillServiceImpl.java
index 302689890..0cde14eba 100644
--- a/src/main/java/com/odysseusinc/arachne/portal/service/impl/BaseSkillServiceImpl.java
+++ b/src/main/java/com/odysseusinc/arachne/portal/service/impl/BaseSkillServiceImpl.java
@@ -61,7 +61,7 @@ public S create(S skill) throws NotUniqueException {
@Override
public S update(S skill) throws NotUniqueException, NotExistException {
- if (!skillRepository.exists(skill.getId())) {
+ if (!skillRepository.existsById(skill.getId())) {
throw new NotExistException("update: skill with id=" + skill.getId() + " not exist", getType());
}
List skills = skillRepository.findByName(skill.getName());
diff --git a/src/main/java/com/odysseusinc/arachne/portal/service/impl/BaseStudyServiceImpl.java b/src/main/java/com/odysseusinc/arachne/portal/service/impl/BaseStudyServiceImpl.java
index 4217effdb..666533009 100644
--- a/src/main/java/com/odysseusinc/arachne/portal/service/impl/BaseStudyServiceImpl.java
+++ b/src/main/java/com/odysseusinc/arachne/portal/service/impl/BaseStudyServiceImpl.java
@@ -192,7 +192,7 @@ public abstract class BaseStudyServiceImpl<
private final Map studySortPaths = new HashMap<>();
protected final ApplicationEventPublisher eventPublisher;
private final BaseSolrService solrService;
-
+
public BaseStudyService proxy;
public BaseStudyServiceImpl(final UserStudyExtendedRepository userStudyExtendedRepository,
@@ -259,6 +259,7 @@ private void init() {
this.studySortPaths.put("leadList", new String[]{"firstLead.firstname", "firstLead.middlename", "firstLead.lastname"});
this.studySortPaths.put("role", new String[]{"role"});
this.studySortPaths.put("created", new String[]{"study.created"});
+ this.studySortPaths.put("updated", new String[]{"study.updated"});
this.studySortPaths.put("type", new String[]{"study.type.name"});
this.studySortPaths.put("status", new String[]{"study.status"});
@@ -330,10 +331,10 @@ public void delete(Long studyId) throws NotExistException {
if (studyId == null) {
throw new NotExistException("id is null", getType());
}
- if (!studyRepository.exists(studyId)) {
+ if (!studyRepository.existsById(studyId)) {
throw new NotExistException(getType());
}
- studyRepository.delete(studyId);
+ studyRepository.deleteById(studyId);
}
@Override
@@ -368,7 +369,7 @@ public T update(T study)
if (!byTitle.isEmpty()) {
throw new NotUniqueException("title", "not unique");
}
- T forUpdate = studyRepository.findOne(study.getId());
+ T forUpdate = studyRepository.getOne(study.getId());
if (forUpdate == null) {
throw new NotExistException(getType());
}
@@ -401,7 +402,7 @@ public T update(T study)
@Override
public void setFavourite(Long userId, Long studyId, Boolean isFavourite) throws NotExistException {
- Study study = studyRepository.findOne(studyId);
+ Study study = studyRepository.getOne(studyId);
if (study == null) {
throw new NotExistException("study not exist", Study.class);
}
@@ -421,7 +422,7 @@ public Page findStudies(final SS studySearch) {
Page resultPage = baseUserStudyLinkRepository.findAll(
studyFilteredListSpecification,
- new PageRequest(studySearch.getPage() - 1, studySearch.getPagesize(), sort));
+ PageRequest.of(studySearch.getPage() - 1, studySearch.getPagesize(), sort));
return resultPage.map(s -> (AbstractUserStudyListItem) s);
}
@@ -450,12 +451,12 @@ public SU getStudy(final IUser user, final Long studyId) {
userStudyItem.getStudy().setDataSources(dataSourceLinks);
return userStudyItem;
}
-
+
@Override
public StudyKind getEntityStudyKind(final EntityType type, final Long id) {
-
+
final Optional kind;
-
+
switch (type) {
case ANALYSIS:
kind = studyRepository.findStudyKindByAnalysisId(id);
@@ -478,7 +479,7 @@ public StudyKind getEntityStudyKind(final EntityType type, final Long id) {
default:
throw new IllegalArgumentException("Can't get study kind of entity with type = " + type);
}
-
+
return kind.orElseThrow(() -> new IllegalArgumentException(String.format("Study doesn't exist for %s entity with id %d", type, id)));
}
@@ -500,7 +501,7 @@ protected final Sort getSort(String sortBy, Boolean sortAsc) {
Arrays.asList(studySortPaths.getOrDefault(sortBy, new String[]{defaultSort})).forEach((param) ->
orders.add(new Sort.Order(sortDirection, param).ignoreCase()));
- return new Sort(orders);
+ return Sort.by(orders);
}
@@ -515,7 +516,7 @@ public UserStudy addParticipant(
String message
) throws NotExistException, AlreadyExistException {
- Study study = Optional.ofNullable(studyRepository.findOne(studyId))
+ Study study = Optional.ofNullable(studyRepository.getOne(studyId))
.orElseThrow(() -> new NotExistException(EX_STUDY_NOT_EXISTS, Study.class));
IUser participant = Optional.ofNullable(userService.findOne(participantId))
@@ -557,7 +558,7 @@ public UserStudy updateParticipantRole(Long studyId, Long participantId,
ParticipantRole role)
throws NotExistException, AlreadyExistException, ValidationException {
- Study study = Optional.ofNullable(studyRepository.findOne(studyId))
+ Study study = Optional.ofNullable(studyRepository.getOne(studyId))
.orElseThrow(() -> new NotExistException(EX_STUDY_NOT_EXISTS, Study.class));
IUser participant = Optional.ofNullable(userService.findOne(participantId))
.orElseThrow(() -> new NotExistException(EX_USER_NOT_EXISTS, User.class));
@@ -606,7 +607,7 @@ private void checkLastLeadInvestigator(UserStudy studyLink, Study study) throws
public String saveFile(MultipartFile multipartFile, Long studyId, String label, IUser user)
throws IOException {
- Study study = studyRepository.findOne(studyId);
+ Study study = studyRepository.getOne(studyId);
String fileNameLowerCase = UUID.randomUUID().toString();
try {
@@ -646,7 +647,7 @@ public String saveFile(MultipartFile multipartFile, Long studyId, String label,
+ "T(com.odysseusinc.arachne.portal.security.ArachnePermission).UPLOAD_FILES)")
public String saveFile(String link, Long studyId, String label, IUser user) throws IOException {
- Study study = studyRepository.findOne(studyId);
+ Study study = studyRepository.getOne(studyId);
String fileNameLowerCase = UUID.randomUUID().toString();
try {
@@ -732,7 +733,7 @@ public List listApprovedDataSources(Long studyId) {
public StudyDataSourceLink addDataSource(IUser createdBy, Long studyId, Long dataSourceId)
throws NotExistException, AlreadyExistException {
- T study = studyRepository.findOne(studyId);
+ T study = studyRepository.getOne(studyId);
if (study == null) {
throw new NotExistException("study not exist", Study.class);
}
@@ -773,7 +774,7 @@ public DS addVirtualDataSource(
throws NotExistException, AlreadyExistException, NoSuchFieldException, IOException, ValidationException,
FieldException, IllegalAccessException, SolrServerException {
- Study study = studyRepository.findOne(studyId);
+ Study study = studyRepository.getOne(studyId);
List dataNodeOwners = validateVirtualDataSourceOwners(study, dataOwnerIds);
@@ -837,7 +838,7 @@ public DS getStudyDataSource(IUser user, Long studyId, Long dataSourceId) {
+ "T(com.odysseusinc.arachne.portal.security.ArachnePermission).DELETE_DATASOURCE)")
public DS updateVirtualDataSource(IUser user, Long studyId, Long dataSourceId, String name, List dataOwnerIds) throws IllegalAccessException, IOException, NoSuchFieldException, SolrServerException, ValidationException {
- Study study = studyRepository.findOne(studyId);
+ Study study = studyRepository.getOne(studyId);
List dataOwners = validateVirtualDataSourceOwners(study, dataOwnerIds);
@@ -873,7 +874,7 @@ public void removeDataSourceUnsecured(Long studyId, Long dataSourceId) {
if (studyDataSourceLink == null) {
throw new NotExistException("studyDataSourceLink does not exist.", StudyDataSourceLink.class);
}
- studyDataSourceLinkRepository.delete(studyDataSourceLink.getId());
+ studyDataSourceLinkRepository.deleteById(studyDataSourceLink.getId());
}
@Override
@@ -926,15 +927,11 @@ public boolean fullDelete(List studies) {
List files = study.getFiles();
fileService.delete(files);
- studyFileRepository.delete(files);
-
- studyDataSourceLinkRepository.delete(study.getDataSources());
-
+ studyFileRepository.deleteAll(files);
+ studyDataSourceLinkRepository.deleteAll(study.getDataSources());
studyHelper.tryDeleteStudyFolder(study);
}
-
- studyRepository.delete(studies);
-
+ studyRepository.deleteAll(studies);
return Boolean.TRUE;
}
@@ -984,7 +981,7 @@ public Iterable suggestStudy(String query, IUser owner, Long id, SuggestSearc
+ "T(com.odysseusinc.arachne.portal.security.ArachnePermission).ACCESS_STUDY)")
public void getAllStudyFilesExceptLinks(Long studyId, String archiveName, OutputStream os) throws IOException {
- T study = studyRepository.findOne(studyId);
+ T study = studyRepository.getOne(studyId);
Path storeFilesPath = fileService.getPath(study);
List files = study.getFiles()
@@ -1017,7 +1014,7 @@ private Set updateDataNodeOwners(List dataOwners, DataNode
public void processAntivirusResponse(AntivirusJobStudyFileResponseEvent event) {
final AntivirusJobResponse antivirusJobResponse = event.getAntivirusJobResponse();
- final StudyFile studyFile = studyFileRepository.findOne(antivirusJobResponse.getFileId());
+ final StudyFile studyFile = studyFileRepository.getOne(antivirusJobResponse.getFileId());
if (studyFile != null) {
studyFile.setAntivirusStatus(antivirusJobResponse.getStatus());
studyFile.setAntivirusDescription(antivirusJobResponse.getDescription());
@@ -1061,7 +1058,7 @@ public T findByIdInAnyTenant(final Long studyId) {
public T findWorkspaceForUser(IUser user, Long userId) throws NotExistException {
final T workspace = studyRepository.findWorkspaceForUser(userId);
-
+
if (workspace == null) {
throw new NotExistException(getType());
}
@@ -1083,13 +1080,13 @@ public T findOrCreateWorkspaceForUser(IUser user, Long userId) {
}
protected BaseStudyService getProxy() {
-
+
return this.proxy;
}
-
+
@Override
public void setProxy(final Object proxy) {
-
+
this.proxy = (BaseStudyService)proxy;
}
}
diff --git a/src/main/java/com/odysseusinc/arachne/portal/service/impl/BaseUserServiceImpl.java b/src/main/java/com/odysseusinc/arachne/portal/service/impl/BaseUserServiceImpl.java
index 502f39d1a..da5c4169b 100644
--- a/src/main/java/com/odysseusinc/arachne/portal/service/impl/BaseUserServiceImpl.java
+++ b/src/main/java/com/odysseusinc/arachne/portal/service/impl/BaseUserServiceImpl.java
@@ -107,7 +107,7 @@
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
-import org.springframework.data.jpa.domain.Specifications;
+import org.springframework.data.jpa.domain.Specification;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.access.prepost.PreAuthorize;
@@ -147,7 +147,7 @@
import static com.odysseusinc.arachne.portal.service.RoleService.ROLE_ADMIN;
import static java.lang.Boolean.TRUE;
import static org.apache.commons.collections.CollectionUtils.isEmpty;
-import static org.springframework.data.jpa.domain.Specifications.where;
+import static org.springframework.data.jpa.domain.Specification.where;
public abstract class BaseUserServiceImpl<
@@ -328,12 +328,10 @@ public void remove(Long id) throws ValidationException, UserNotFoundException, N
if (id == null) {
throw new ValidationException("remove user: id must be not null");
}
- U user = rawUserRepository.findOne(id);
- if (user == null) {
- throw new UserNotFoundException("removeUser", "remove user: user not found");
- }
+ U user = rawUserRepository.findById(id).orElseThrow(()-> new UserNotFoundException("removeUser", "remove user: user not found"));
+
solrService.delete(user);
- rawUserRepository.delete(user.getId());
+ rawUserRepository.deleteById(user.getId());
}
@Override
@@ -480,20 +478,20 @@ public void resendActivationEmail(final U user) {
@Override
public U getByIdInAnyTenantAndInitializeCollections(Long id) {
- return initUserCollections(rawUserRepository.findOne(id));
+ return initUserCollections(rawUserRepository.getOne(id));
}
@Override
public U getByUuidInAnyTenantAndInitializeCollections(String uuid) {
final Long id = UserIdUtils.uuidToId(uuid);
- return initUserCollections(rawUserRepository.findOne(id));
+ return initUserCollections(rawUserRepository.findById(id).orElse(null));
}
@Override
public U getById(Long id) {
- return userRepository.findOne(id);
+ return userRepository.getOne(id);
}
private void afterUpdate(U savedUser) {
@@ -548,12 +546,12 @@ private U baseUpdate(U forUpdate, U user) {
forUpdate.setZipCode(user.getZipCode());
}
if (user.getCountry() != null) {
- Country country = user.getCountry().getId() != null ? countryRepository.findOne(user.getCountry().getId()) : null;
+ Country country = user.getCountry().getId() != null ? countryRepository.findById(user.getCountry().getId()).orElse(null) : null;
forUpdate.setCountry(country);
}
if (user.getStateProvince() != null) {
Long stateProvinceId = user.getStateProvince().getId();
- StateProvince stateProvince = stateProvinceId != null ? stateProvinceRepository.findOne(stateProvinceId) : null;
+ StateProvince stateProvince = stateProvinceId != null ? stateProvinceRepository.findById(stateProvinceId).orElse(null) : null;
forUpdate.setStateProvince(stateProvince);
}
if (user.getAffiliation() != null) {
@@ -576,7 +574,7 @@ private U baseUpdate(U forUpdate, U user) {
public U update(final U user)
throws IllegalAccessException, SolrServerException, IOException, NotExistException, NoSuchFieldException {
- U forUpdate = rawUserRepository.findOne(user.getId());
+ U forUpdate = rawUserRepository.findById(user.getId()).orElse(null);
forUpdate = baseUpdate(forUpdate, user);
U savedUser = rawUserRepository.saveAndFlush(forUpdate);
savedUser = initUserCollections(savedUser);
@@ -585,7 +583,7 @@ public U update(final U user)
}
@Override
- @PreAuthorize("T(String).CASE_INSENSITIVE_ORDER.compare(@rawUserRepository.findOne(#user.id)?.getUsername(), authentication.principal.username)==0 || hasRole('ROLE_ADMIN')")
+ @PreAuthorize("T(String).CASE_INSENSITIVE_ORDER.compare(@rawUserRepository.getOne(#user.id)?.getUsername(), authentication.principal.username)==0 || hasRole('ROLE_ADMIN')")
public U updateInAnyTenant(U user) throws NotExistException {
U forUpdate = getByIdInAnyTenant(user.getId());
forUpdate = baseUpdate(forUpdate, user);
@@ -619,7 +617,7 @@ public void saveUsers(List users, Set tenants, boolean emailConfirmat
public U getByUuid(String uuid) {
if (uuid != null && !uuid.isEmpty()) {
- return userRepository.findById(UserIdUtils.uuidToId(uuid));
+ return userRepository.getOne(UserIdUtils.uuidToId(uuid));
} else {
throw new IllegalArgumentException("Given uuid is blank");
}
@@ -685,9 +683,9 @@ public List getAllEnabledFromAllTenants() {
@Override
public Page getPage(final Pageable pageable, final UserSearch userSearch) {
- final Pageable pageableWithUpdatedOrder = new PageRequest(pageable.getPageNumber() - 1, pageable.getPageSize(), pageable.getSort());
+ final Pageable pageableWithUpdatedOrder = PageRequest.of(pageable.getPageNumber() - 1, pageable.getPageSize(), pageable.getSort());
- final Specifications spec = buildSpecification(userSearch);
+ final Specification spec = buildSpecification(userSearch);
final Page page = rawUserRepository.findAll(spec, pageableWithUpdatedOrder);
@@ -697,7 +695,7 @@ public Page getPage(final Pageable pageable, final UserSearch userSearch) {
@Override
public List getList(final UserSearch userSearch) {
- final Specifications spec = buildSpecification(userSearch);
+ final Specification spec = buildSpecification(userSearch);
return rawUserRepository.findAll(spec);
}
@@ -707,9 +705,9 @@ public List findUsersInAnyTenantByEmailIgnoreCaseIn(List emails) {
return rawUserRepository.findByEmailIgnoreCaseIn(emails);
}
- private Specifications buildSpecification(final UserSearch userSearch) {
+ private Specification buildSpecification(final UserSearch userSearch) {
- Specifications spec = where(UserSpecifications.hasEmail());
+ Specification spec = where(UserSpecifications.hasEmail());
if (userSearch.getEmailConfirmed() != null) {
spec = spec.and(emailConfirmed(userSearch.getEmailConfirmed()));
}
@@ -773,7 +771,7 @@ public void resetPassword(U user)
NoSuchFieldException, SolrServerException, IOException {
final Long id = user.getId();
- final U existingUser = rawUserRepository.findOne(id);
+ final U existingUser = rawUserRepository.findById(id).orElse(null);
if (existingUser == null) {
final String message = String.format("User with id='%s' does not exist", id);
throw new NotExistException(message, User.class);
@@ -791,7 +789,7 @@ public void resetPassword(U user)
public void updatePassword(U user, String oldPassword, String newPassword)
throws ValidationException, PasswordValidationException {
- U exists = userRepository.findOne(user.getId());
+ U exists = userRepository.getOne(user.getId());
if (!passwordEncoder.matches(oldPassword, user.getPassword())) {
throw new ValidationException(PASSWORD_NOT_MATCH_EXC);
@@ -805,7 +803,7 @@ public void updatePassword(U user, String oldPassword, String newPassword)
public U addSkillToUser(Long userId, Long skillId)
throws NotExistException, IllegalAccessException, SolrServerException, IOException, NoSuchFieldException {
- U forUpdate = userRepository.findOne(userId);
+ U forUpdate = userRepository.getOne(userId);
S skill = skillService.getById(skillId);
forUpdate.getSkills().add(skill);
U savedUser = initUserCollections(rawUserRepository.save(forUpdate));
@@ -818,7 +816,7 @@ public U addSkillToUser(Long userId, Long skillId)
public U removeSkillFromUser(Long userId, Long skillId)
throws NotExistException, IllegalAccessException, SolrServerException, IOException, NoSuchFieldException {
- U forUpdate = userRepository.findOne(userId);
+ U forUpdate = userRepository.getOne(userId);
Skill skill = skillService.getById(skillId);
forUpdate.getSkills().remove(skill);
U savedUser = initUserCollections(rawUserRepository.save(forUpdate));
@@ -831,7 +829,7 @@ public U removeSkillFromUser(Long userId, Long skillId)
public U addLinkToUser(Long userId, UserLink link)
throws NotExistException, NotUniqueException, PermissionDeniedException {
- U forUpdate = userRepository.findOne(userId);
+ U forUpdate = userRepository.getOne(userId);
link.setUser(forUpdate);
userLinkService.create(link);
return initUserCollections(forUpdate);
@@ -851,7 +849,7 @@ private U initUserCollections(U user) {
public U removeLinkFromUser(Long userId, Long linkId) throws NotExistException {
userLinkService.delete(linkId);
- U user = userRepository.findOne(userId);
+ U user = userRepository.getOne(userId);
user.getLinks().size();
return initUserCollections(user);
}
@@ -860,7 +858,7 @@ public U removeLinkFromUser(Long userId, Long linkId) throws NotExistException {
public U addPublicationToUser(Long userId, UserPublication publication)
throws NotExistException, NotUniqueException, PermissionDeniedException {
- U forUpdate = userRepository.findOne(userId);
+ U forUpdate = userRepository.getOne(userId);
publication.setUser(forUpdate);
UserPublication userPublication = userPublicationService.create(publication);
forUpdate.getPublications().add(userPublication);
@@ -871,7 +869,7 @@ public U addPublicationToUser(Long userId, UserPublication publication)
public U removePublicationFromUser(Long userId, Long publicationId) throws NotExistException {
userPublicationService.delete(publicationId);
- U user = userRepository.findOne(userId);
+ U user = userRepository.getOne(userId);
user.getPublications().size();
return (U) initUserCollections(user);
}
@@ -1136,9 +1134,9 @@ public List getAllAdmins(final String sortBy, final Boolean sortAsc) {
Sort.Direction direction = sortAsc != null && sortAsc ? Sort.Direction.ASC : Sort.Direction.DESC;
final Sort sort;
if (sortBy == null || sortBy.isEmpty() || sortBy.equals("name")) {
- sort = new Sort(direction, "firstname", "lastname", "middlename");
+ sort = Sort.by(direction, "firstname", "lastname", "middlename");
} else {
- sort = new Sort(direction, sortBy);
+ sort = Sort.by(direction, sortBy);
}
List admins = rawUserRepository.findByRoles_name(ROLE_ADMIN, sort);
return admins;
@@ -1147,7 +1145,7 @@ public List getAllAdmins(final String sortBy, final Boolean sortAsc) {
@Override
public void addUserToAdmins(Long id) {
- U user = rawUserRepository.findOne(id);
+ U user = rawUserRepository.getOne(id);
List roles = roleRepository.findByName(ROLE_ADMIN);
if (roles != null && !roles.isEmpty()) {
user.getRoles().add(roles.get(0));
@@ -1160,7 +1158,7 @@ public void addUserToAdmins(Long id) {
@Override
public void removeUserFromAdmins(Long id) {
- U user = rawUserRepository.findOne(id);
+ U user = rawUserRepository.getOne(id);
List roles = roleRepository.findByName(ROLE_ADMIN);
if (roles != null && !roles.isEmpty()) {
user.getRoles().remove(roles.get(0));
@@ -1185,7 +1183,7 @@ public List extends Invitationable> getUnlockAnalysisRequests(U user) {
@Override
public U findOne(Long participantId) {
- return userRepository.findOne(participantId);
+ return userRepository.getOne(participantId);
}
@Override
@@ -1256,7 +1254,7 @@ public void makeLinksWithStudiesDeleted(final Long tenantId, final Long userId)
@Override
public U getRawUser(final Long userId) {
- return rawUserRepository.findOne(userId);
+ return rawUserRepository.getOne(userId);
}
@Override
diff --git a/src/main/java/com/odysseusinc/arachne/portal/service/impl/BreadcrumbServiceImpl.java b/src/main/java/com/odysseusinc/arachne/portal/service/impl/BreadcrumbServiceImpl.java
index 1b330295b..66edf739b 100644
--- a/src/main/java/com/odysseusinc/arachne/portal/service/impl/BreadcrumbServiceImpl.java
+++ b/src/main/java/com/odysseusinc/arachne/portal/service/impl/BreadcrumbServiceImpl.java
@@ -84,7 +84,7 @@ private Breadcrumb getBreadcrumbByTypeAndId(EntityType type, Long id) throws Not
case ANALYSIS:
return analysisRepository.getOne(id);
case SUBMISSION_GROUP:
- return submissionGroupRepository.findOne(id);
+ return submissionGroupRepository.getOne(id);
case SUBMISSION:
return submissionRepository.getOne(id);
case INSIGHT:
@@ -94,7 +94,7 @@ private Breadcrumb getBreadcrumbByTypeAndId(EntityType type, Long id) throws Not
case DATA_SOURCE:
return dataSourceRepository.getOne(id);
case PAPER:
- return paperRepository.findOne(id);
+ return paperRepository.getOne(id);
}
return null;
}
diff --git a/src/main/java/com/odysseusinc/arachne/portal/service/impl/CRUDLServiceImpl.java b/src/main/java/com/odysseusinc/arachne/portal/service/impl/CRUDLServiceImpl.java
index efb72ec7e..2ef9c0a32 100644
--- a/src/main/java/com/odysseusinc/arachne/portal/service/impl/CRUDLServiceImpl.java
+++ b/src/main/java/com/odysseusinc/arachne/portal/service/impl/CRUDLServiceImpl.java
@@ -43,10 +43,8 @@ public T getById(Long id) throws NotExistException {
if (id == null) {
throw new NotExistException("id is null", getType());
}
- T entity = getRepository().findOne(id);
- if (entity == null) {
- throw new NotExistException(getType());
- }
+ T entity = getRepository().findById(id).orElseThrow(() -> new NotExistException(getType()));
+
return entity;
}
@@ -56,7 +54,7 @@ public void delete(Long id) throws NotExistException {
if (id == null) {
throw new NotExistException("id is null", getType());
}
- getRepository().delete(id);
+ getRepository().deleteById(id);
}
@Override
diff --git a/src/main/java/com/odysseusinc/arachne/portal/service/impl/CommentServiceImpl.java b/src/main/java/com/odysseusinc/arachne/portal/service/impl/CommentServiceImpl.java
index 10f593461..a25b20d61 100644
--- a/src/main/java/com/odysseusinc/arachne/portal/service/impl/CommentServiceImpl.java
+++ b/src/main/java/com/odysseusinc/arachne/portal/service/impl/CommentServiceImpl.java
@@ -80,7 +80,7 @@ public CommentTopic getTopic(Long id) throws NotExistException {
@Override
public Set list(Set topics, Integer size, Sort sort) {
- Pageable pageable = new PageRequest(0, size, sort);
+ Pageable pageable = PageRequest.of(0, size, sort);
final Page page = commentRepository.getAllByTopicIn(topics, pageable);
final List comments = page.getContent();
comments.forEach(comment -> connectToTopic(topics, comment));
@@ -110,7 +110,7 @@ public Comment addComment(Long topicId, Long parentId, Comment comment) {
final CommentTopic topic = commentTopicRepository.getOne(topicId);
comment.setTopic(topic);
if (parentId != null) {
- final Comment parent = commentRepository.findOne(parentId);
+ final Comment parent = commentRepository.findById(parentId).orElse(null);
comment.setParent(parent);
}
return commentRepository.save(comment);
@@ -130,7 +130,7 @@ public void deleteComment(Long topicId, Long commentId) throws NotExistException
@Override
public void deleteComments(List comments) {
- commentRepository.delete(comments);
+ commentRepository.deleteAll(comments);
}
@Override
diff --git a/src/main/java/com/odysseusinc/arachne/portal/service/impl/DataNodeStatusServiceImpl.java b/src/main/java/com/odysseusinc/arachne/portal/service/impl/DataNodeStatusServiceImpl.java
index 63454fb27..532e19933 100644
--- a/src/main/java/com/odysseusinc/arachne/portal/service/impl/DataNodeStatusServiceImpl.java
+++ b/src/main/java/com/odysseusinc/arachne/portal/service/impl/DataNodeStatusServiceImpl.java
@@ -55,14 +55,14 @@ public DataNodeStatus createUpdate(DataNodeStatus studyStatus) {
public Optional getById(Long id) {
checkNotNull(id, "getByIdAndInitializeCollections: dataNodeStatus with id=null not exist");
- return Optional.ofNullable(dataNodeStatusRepository.findOne(id));
+ return Optional.ofNullable(dataNodeStatusRepository.getOne(id));
}
@Override
public void delete(Long id) {
checkNotNull(id, "deleteComment: cannot deleteComment DataNodeStatus with id=null");
- dataNodeStatusRepository.delete(id);
+ dataNodeStatusRepository.deleteById(id);
}
@Override
diff --git a/src/main/java/com/odysseusinc/arachne/portal/service/impl/OrganizationServiceImpl.java b/src/main/java/com/odysseusinc/arachne/portal/service/impl/OrganizationServiceImpl.java
index 2b5fb6c3f..97d30e3e9 100644
--- a/src/main/java/com/odysseusinc/arachne/portal/service/impl/OrganizationServiceImpl.java
+++ b/src/main/java/com/odysseusinc/arachne/portal/service/impl/OrganizationServiceImpl.java
@@ -126,7 +126,7 @@ public Organization update(Organization organization) {
public void delete(Long id) {
final Organization exist = getById(id);
- organizationRepository.delete(id);
+ organizationRepository.deleteById(id);
logger.info("{} deleted", exist);
}
diff --git a/src/main/java/com/odysseusinc/arachne/portal/service/impl/ProfessionalTypeServiceImpl.java b/src/main/java/com/odysseusinc/arachne/portal/service/impl/ProfessionalTypeServiceImpl.java
index d1995cbe4..a8b83ea37 100644
--- a/src/main/java/com/odysseusinc/arachne/portal/service/impl/ProfessionalTypeServiceImpl.java
+++ b/src/main/java/com/odysseusinc/arachne/portal/service/impl/ProfessionalTypeServiceImpl.java
@@ -66,7 +66,7 @@ public CrudRepository getRepository() {
@Override
public ProfessionalType update(ProfessionalType professionalType) throws NotExistException, NotUniqueException {
- if (!professionalTypeRepository.exists(professionalType.getId())) {
+ if (!professionalTypeRepository.existsById(professionalType.getId())) {
throw new NotExistException("update: professionalType with id=" + professionalType.getId() + " not exist",
ProfessionalType.class);
}
diff --git a/src/main/java/com/odysseusinc/arachne/portal/service/impl/StudyStatusServiceImpl.java b/src/main/java/com/odysseusinc/arachne/portal/service/impl/StudyStatusServiceImpl.java
index a390b5668..d7c9bffa5 100644
--- a/src/main/java/com/odysseusinc/arachne/portal/service/impl/StudyStatusServiceImpl.java
+++ b/src/main/java/com/odysseusinc/arachne/portal/service/impl/StudyStatusServiceImpl.java
@@ -61,7 +61,7 @@ public StudyStatus create(StudyStatus studyStatus) throws NotUniqueException {
@Override
public StudyStatus update(StudyStatus studyStatus) throws NotUniqueException, NotExistException {
- if (!studyStatusRepository.exists(studyStatus.getId())) {
+ if (!studyStatusRepository.existsById(studyStatus.getId())) {
throw new NotExistException("update: studyStatus with id=" + studyStatus.getId() + " not exist", StudyStatus.class);
}
StudyStatus existStudyStatus = studyStatusRepository.findByName(studyStatus.getName());
diff --git a/src/main/java/com/odysseusinc/arachne/portal/service/impl/StudyTypeServiceImpl.java b/src/main/java/com/odysseusinc/arachne/portal/service/impl/StudyTypeServiceImpl.java
index eede774f1..5a7876750 100644
--- a/src/main/java/com/odysseusinc/arachne/portal/service/impl/StudyTypeServiceImpl.java
+++ b/src/main/java/com/odysseusinc/arachne/portal/service/impl/StudyTypeServiceImpl.java
@@ -61,7 +61,7 @@ public StudyType create(StudyType studyType) throws NotUniqueException {
@Override
public StudyType update(StudyType studyType) throws NotUniqueException, NotExistException {
- if (!studyTypeRepository.exists(studyType.getId())) {
+ if (!studyTypeRepository.existsById(studyType.getId())) {
throw new NotExistException("update: studyType with id=" + studyType.getId() + " not exist",
StudyType.class);
}
diff --git a/src/main/java/com/odysseusinc/arachne/portal/service/impl/UsersOperationsServiceImpl.java b/src/main/java/com/odysseusinc/arachne/portal/service/impl/UsersOperationsServiceImpl.java
index d16b8f18b..4798c998b 100644
--- a/src/main/java/com/odysseusinc/arachne/portal/service/impl/UsersOperationsServiceImpl.java
+++ b/src/main/java/com/odysseusinc/arachne/portal/service/impl/UsersOperationsServiceImpl.java
@@ -81,6 +81,6 @@ private void toggleFlag(
for (final IUser entity : entities) {
setter.accept(entity, !getter.apply(entity));
}
- baseRawUserRepository.save(entities);
+ baseRawUserRepository.saveAll(entities);
}
}
\ No newline at end of file
diff --git a/src/main/java/com/odysseusinc/arachne/portal/service/mail/ArachneMailSender.java b/src/main/java/com/odysseusinc/arachne/portal/service/mail/ArachneMailSender.java
index 373f5440f..37e4f94b0 100644
--- a/src/main/java/com/odysseusinc/arachne/portal/service/mail/ArachneMailSender.java
+++ b/src/main/java/com/odysseusinc/arachne/portal/service/mail/ArachneMailSender.java
@@ -22,89 +22,14 @@
package com.odysseusinc.arachne.portal.service.mail;
-import java.io.File;
-import java.net.URL;
-import java.util.Map;
-import javax.mail.internet.MimeMessage;
-import net.htmlparser.jericho.Source;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.beans.factory.annotation.Value;
-import org.springframework.mail.javamail.JavaMailSender;
-import org.springframework.mail.javamail.MimeMessageHelper;
-import org.springframework.scheduling.annotation.Async;
-import org.springframework.stereotype.Service;
-import org.thymeleaf.TemplateEngine;
-import org.thymeleaf.context.Context;
-
-@Service
-public class ArachneMailSender {
- private static final Logger LOG = LoggerFactory.getLogger(ArachneMailSender.class);
- private static final String SIGNATURE = "signature";
- private static final String PATH_TO_TEMPLATES = "/templates/";
- private static final String NAME = "_text";
- private static final String EXTENSION = ".txt";
-
- @Autowired
- private TemplateEngine templateEngine;
-
- private JavaMailSender mailSender;
-
- @Value("${arachne.mail.notifier}")
- private String from;
-
- @Value("${arachne.mail.signature}")
- private String signature;
- @Value("${arachne.mail.app-title}")
- private String appTitle;
-
- @Autowired
- public ArachneMailSender(JavaMailSender mailSender) {
-
- this.mailSender = mailSender;
- }
-
- public void send(ArachneMailMessage mailMessage) {
-
- try {
- MimeMessage message = mailSender.createMimeMessage();
- MimeMessageHelper helper;
- helper = new MimeMessageHelper(message, true);
- helper.setSubject(mailMessage.getSubject().replaceAll("\\$\\{app-title\\}", appTitle));
- helper.setFrom(from, mailMessage.getFromPersonal().replaceAll("\\$\\{app-title\\}", appTitle));
- helper.setTo(mailMessage.getUser().getEmail());
- URL templateUrl = this.getClass().getResource(PATH_TO_TEMPLATES + mailMessage.getTemplate() + NAME + EXTENSION);
- String htmlString = buildContent(mailMessage.getTemplate(), mailMessage.getParameters());
- if (templateUrl != null) {
- File textTemplate = new File(templateUrl.getPath());
- if (!textTemplate.isDirectory()) {
- helper.setText(buildContent(mailMessage.getTemplate() + NAME, mailMessage.getParameters()), htmlString);
- }
- } else {
- Source source = new Source(htmlString);
- String textString = source.getRenderer().toString();
- helper.setText(textString, htmlString);
- }
- mailSender.send(message);
-
- } catch (Exception e) {
- LOG.error(e.getMessage(), e);
- }
- }
+import java.util.Map;
- @Async
- public void asyncSend(ArachneMailMessage mailMessage) {
+public interface ArachneMailSender {
- send(mailMessage);
- }
+ void asyncSend(ArachneMailMessage mailMessage);
- public String buildContent(String templateName, Map parameters) {
+ String buildContent(String templateName, Map parameters);
- Context context = new Context();
- parameters.put(SIGNATURE, signature);
- context.setVariables(parameters);
- return templateEngine.process(templateName, context);
- }
+ void send(ArachneMailMessage mailMessage);
}
diff --git a/src/main/java/com/odysseusinc/arachne/portal/service/mail/ArachneMailSenderImpl.java b/src/main/java/com/odysseusinc/arachne/portal/service/mail/ArachneMailSenderImpl.java
new file mode 100644
index 000000000..a33cdfec2
--- /dev/null
+++ b/src/main/java/com/odysseusinc/arachne/portal/service/mail/ArachneMailSenderImpl.java
@@ -0,0 +1,114 @@
+/*
+ *
+ * Copyright 2021 Odysseus Data Services, inc.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * Company: Odysseus Data Services, Inc.
+ * Product Owner/Architecture: Gregory Klebanov
+ * Authors: Alexandr Cumarav
+ * Created: April 20, 2021
+ *
+ */
+
+package com.odysseusinc.arachne.portal.service.mail;
+
+import net.htmlparser.jericho.Source;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.mail.javamail.JavaMailSender;
+import org.springframework.mail.javamail.MimeMessageHelper;
+import org.springframework.scheduling.annotation.Async;
+import org.springframework.stereotype.Service;
+import org.thymeleaf.TemplateEngine;
+import org.thymeleaf.context.Context;
+
+import javax.mail.internet.MimeMessage;
+import java.io.File;
+import java.net.URL;
+import java.util.Map;
+
+@Service
+public class ArachneMailSenderImpl implements ArachneMailSender {
+ private static final Logger LOG = LoggerFactory.getLogger(ArachneMailSenderImpl.class);
+ private static final String SIGNATURE = "signature";
+ private static final String PATH_TO_TEMPLATES = "/templates/";
+ private static final String NAME = "_text";
+ private static final String EXTENSION = ".txt";
+
+ @Autowired
+ private TemplateEngine templateEngine;
+
+ private JavaMailSender mailSender;
+
+ @Value("${arachne.mail.notifier}")
+ private String from;
+
+ @Value("${arachne.mail.signature}")
+ private String signature;
+
+ @Value("${arachne.mail.app-title}")
+ private String appTitle;
+
+ @Autowired
+ public ArachneMailSenderImpl(JavaMailSender mailSender) {
+
+ this.mailSender = mailSender;
+ }
+
+ @Async
+ @Override
+ public void asyncSend(ArachneMailMessage mailMessage) {
+
+ send(mailMessage);
+ }
+
+ @Override
+ public String buildContent(String templateName, Map parameters) {
+
+ Context context = new Context();
+ parameters.put(SIGNATURE, signature);
+ context.setVariables(parameters);
+ return templateEngine.process(templateName, context);
+ }
+
+ @Override
+ public void send(ArachneMailMessage mailMessage) {
+
+ try {
+ MimeMessage message = mailSender.createMimeMessage();
+ MimeMessageHelper helper;
+ helper = new MimeMessageHelper(message, true);
+ helper.setSubject(mailMessage.getSubject().replaceAll("\\$\\{app-title\\}", appTitle));
+ helper.setFrom(from, mailMessage.getFromPersonal().replaceAll("\\$\\{app-title\\}", appTitle));
+ helper.setTo(mailMessage.getUser().getEmail());
+ URL templateUrl = this.getClass().getResource(PATH_TO_TEMPLATES + mailMessage.getTemplate() + NAME + EXTENSION);
+ String htmlString = buildContent(mailMessage.getTemplate(), mailMessage.getParameters());
+ if (templateUrl != null) {
+ File textTemplate = new File(templateUrl.getPath());
+ if (!textTemplate.isDirectory()) {
+ helper.setText(buildContent(mailMessage.getTemplate() + NAME, mailMessage.getParameters()), htmlString);
+ }
+ } else {
+ Source source = new Source(htmlString);
+ String textString = source.getRenderer().toString();
+ helper.setText(textString, htmlString);
+ }
+ mailSender.send(message);
+
+ } catch (Exception e) {
+ LOG.error(e.getMessage(), e);
+ }
+ }
+}
diff --git a/src/main/java/com/odysseusinc/arachne/portal/service/study/impl/AddDataSourceStrategyFactoryImpl.java b/src/main/java/com/odysseusinc/arachne/portal/service/study/impl/AddDataSourceStrategyFactoryImpl.java
index 0a0693f9d..cbdc0db52 100644
--- a/src/main/java/com/odysseusinc/arachne/portal/service/study/impl/AddDataSourceStrategyFactoryImpl.java
+++ b/src/main/java/com/odysseusinc/arachne/portal/service/study/impl/AddDataSourceStrategyFactoryImpl.java
@@ -22,29 +22,44 @@
package com.odysseusinc.arachne.portal.service.study.impl;
-import com.odysseusinc.arachne.portal.model.BaseDataSource;
-import com.odysseusinc.arachne.portal.model.DataSource;
+import com.odysseusinc.arachne.portal.model.IDataSource;
import com.odysseusinc.arachne.portal.service.study.AddDataSourceStrategy;
-import com.odysseusinc.arachne.portal.service.study.AddDataSourceStrategyFactory;
-import java.util.Objects;
import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
+import java.util.Objects;
+
@Service
-public class AddDataSourceStrategyFactoryImpl implements AddDataSourceStrategyFactory {
+@Primary
+public class AddDataSourceStrategyFactoryImpl extends BaseAddDataSourceStrategyFactory {
- private final AddPublicDataSourceStrategy addPublicDataSourceStrategy;
+ private final AddPublicDataSourceStrategy publicDataSourceStrategy;
+ private final AddRestrictedDataSourceStrategy rectrictedDataSourceStrategy;
@Autowired
- public AddDataSourceStrategyFactoryImpl(AddPublicDataSourceStrategy addPublicDataSourceStrategy) {
+ public AddDataSourceStrategyFactoryImpl(AddPublicDataSourceStrategy addPublicDataSourceStrategy,
+ AddRestrictedDataSourceStrategy rectrictedDataSourceStrategy) {
- this.addPublicDataSourceStrategy = addPublicDataSourceStrategy;
+ this.rectrictedDataSourceStrategy = rectrictedDataSourceStrategy;
+ publicDataSourceStrategy = addPublicDataSourceStrategy;
}
@Override
- public AddDataSourceStrategy getStrategy(DataSource dataSource) {
-
- Objects.requireNonNull(dataSource);
- return addPublicDataSourceStrategy;
+ public AddDataSourceStrategy getStrategy(IDataSource dataSource) {
+ // In case of virtual datasources we do not have access type
+ if (Objects.isNull(dataSource.getAccessType())) {
+ return publicDataSourceStrategy;
+ }
+ AddDataSourceStrategy strategy;
+ switch (dataSource.getAccessType()) {
+ case RESTRICTED:
+ strategy = rectrictedDataSourceStrategy;
+ break;
+ case PUBLIC:
+ default:
+ strategy = publicDataSourceStrategy;
+ }
+ return strategy;
}
}
diff --git a/src/main/java/com/odysseusinc/arachne/portal/service/study/impl/AddRestrictedDataSourceStrategy.java b/src/main/java/com/odysseusinc/arachne/portal/service/study/impl/AddRestrictedDataSourceStrategy.java
new file mode 100644
index 000000000..3326f82ec
--- /dev/null
+++ b/src/main/java/com/odysseusinc/arachne/portal/service/study/impl/AddRestrictedDataSourceStrategy.java
@@ -0,0 +1,77 @@
+/*
+ *
+ * Copyright 2018 Odysseus Data Services, inc.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * Company: Odysseus Data Services, Inc.
+ * Product Owner/Architecture: Gregory Klebanov
+ * Authors: Pavel Grafkin, Alexandr Ryabokon, Vitaly Koulakov, Anton Gackovka, Maria Pozhidaeva, Mikhail Mironov
+ * Created: September 08, 2017
+ *
+ */
+package com.odysseusinc.arachne.portal.service.study.impl;
+
+import com.odysseusinc.arachne.portal.api.v1.dto.UpdateNotificationDTO;
+import com.odysseusinc.arachne.portal.config.WebSecurityConfig;
+import com.odysseusinc.arachne.portal.model.DataNode;
+import com.odysseusinc.arachne.portal.model.IDataSource;
+import com.odysseusinc.arachne.portal.model.IUser;
+import com.odysseusinc.arachne.portal.model.StudyDataSourceLink;
+import com.odysseusinc.arachne.portal.repository.StudyDataSourceLinkRepository;
+import com.odysseusinc.arachne.portal.service.mail.ArachneMailSender;
+import com.odysseusinc.arachne.portal.service.mail.InvitationDataOwnerMailSender;
+import com.odysseusinc.arachne.portal.service.study.AddDataSourceStrategy;
+import com.odysseusinc.arachne.portal.util.DataNodeUtils;
+import org.springframework.messaging.simp.SimpMessagingTemplate;
+import org.springframework.stereotype.Service;
+
+import static com.odysseusinc.arachne.portal.model.DataSourceStatus.APPROVED;
+import static com.odysseusinc.arachne.portal.model.DataSourceStatus.PENDING;
+
+@Service
+public class AddRestrictedDataSourceStrategy extends AbstractAddDataSourceStrategy implements AddDataSourceStrategy {
+
+ private final ArachneMailSender arachneMailSender;
+ private final SimpMessagingTemplate wsTemplate;
+
+ public AddRestrictedDataSourceStrategy(StudyDataSourceLinkRepository studyDataSourceLinkRepository,
+ ArachneMailSender arachneMailSender,
+ SimpMessagingTemplate wsTemplate) {
+
+ super(studyDataSourceLinkRepository);
+ this.arachneMailSender = arachneMailSender;
+ this.wsTemplate = wsTemplate;
+ }
+
+ @Override
+ public void addDataSourceToStudy(IUser createdBy, IDataSource dataSource, StudyDataSourceLink link) {
+
+ DataNode dataNode = dataSource.getDataNode();
+ if (DataNodeUtils.isDataNodeOwner(dataNode, createdBy)) {
+ saveStudyDataSourceLinkWithStatus(link, APPROVED);
+ } else {
+ StudyDataSourceLink studyDataSourceLink
+ = saveStudyDataSourceLinkWithStatus(link, PENDING);
+ DataNodeUtils.getDataNodeOwners(dataNode).forEach(
+ user -> {
+ arachneMailSender.send(new InvitationDataOwnerMailSender(
+ WebSecurityConfig.getDefaultPortalURI(), user, studyDataSourceLink
+ )
+ );
+ wsTemplate.convertAndSendToUser(user.getUsername(), "/topic/invitations",
+ new UpdateNotificationDTO());
+ }
+ );
+ }
+ }
+}
diff --git a/src/main/java/com/odysseusinc/arachne/portal/service/submission/impl/BaseSubmissionInsightServiceImpl.java b/src/main/java/com/odysseusinc/arachne/portal/service/submission/impl/BaseSubmissionInsightServiceImpl.java
index 245696cab..db393a1e8 100644
--- a/src/main/java/com/odysseusinc/arachne/portal/service/submission/impl/BaseSubmissionInsightServiceImpl.java
+++ b/src/main/java/com/odysseusinc/arachne/portal/service/submission/impl/BaseSubmissionInsightServiceImpl.java
@@ -109,17 +109,17 @@ public SubmissionInsight createSubmissionInsight(Long submissionId, SubmissionIn
.stream()
.map(sf -> new SubmissionInsightSubmissionFile(savedInsight, sf, new CommentTopic()))
.collect(Collectors.toList());
- submissionInsightSubmissionFileRepository.save(submissionInsightSubmissionFiles);
+ submissionInsightSubmissionFileRepository.saveAll(submissionInsightSubmissionFiles);
final List resultFiles = submission.getResultFiles();
resultFiles.forEach(resultFile -> resultFile.setCommentTopic(new CommentTopic()));
- submissionResultFileRepository.save(resultFiles);
+ submissionResultFileRepository.saveAll(resultFiles);
return savedInsight;
}
@Override
public void deleteSubmissionInsightSubmissionFileLinks(List links) {
- submissionInsightSubmissionFileRepository.delete(links);
+ submissionInsightSubmissionFileRepository.deleteAll(links);
}
@Override
@@ -169,14 +169,14 @@ public void deleteSubmissionInsight(Long submissionId) throws NotExistException
throwNotExistExceptionIfNull(submission.getSubmissionInsight(), submissionId);
final List resultFiles = submission.getResultFiles();
resultFiles.forEach(resultFile -> resultFile.setCommentTopic(null));
- submissionResultFileRepository.save(resultFiles);
+ submissionResultFileRepository.saveAll(resultFiles);
submissionInsightRepository.deleteBySubmissionId(submissionId);
}
@Override
public void tryDeleteSubmissionInsight(Long submissionInsightId) {
- submissionInsightRepository.delete(submissionInsightId);
+ submissionInsightRepository.deleteById(submissionInsightId);
}
private void throwNotExistExceptionIfNull(Submission submission, Long submissionId) throws NotExistException {
diff --git a/src/main/java/com/odysseusinc/arachne/portal/service/submission/impl/BaseSubmissionServiceImpl.java b/src/main/java/com/odysseusinc/arachne/portal/service/submission/impl/BaseSubmissionServiceImpl.java
index 86f125807..b904e82aa 100644
--- a/src/main/java/com/odysseusinc/arachne/portal/service/submission/impl/BaseSubmissionServiceImpl.java
+++ b/src/main/java/com/odysseusinc/arachne/portal/service/submission/impl/BaseSubmissionServiceImpl.java
@@ -88,6 +88,7 @@
import net.lingala.zip4j.model.FileHeader;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
+import org.apache.commons.lang3.tuple.Triple;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
@@ -119,11 +120,13 @@
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
+import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
+import java.util.Queue;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;
@@ -205,7 +208,7 @@ protected BaseSubmissionServiceImpl(BaseSubmissionRepository submissionReposi
@Override
public T approveSubmissionResult(Long submissionId, ApproveDTO approveDTO, IUser user) {
- T submission = submissionRepository.findOne(submissionId);
+ T submission = submissionRepository.getOne(submissionId);
SubmissionStatus status = runApproveSubmissionProcess(submission,
beforeApproveSubmissionResult(submission, approveDTO), approveDTO);
List statusHistory = submission.getStatusHistory();
@@ -319,7 +322,7 @@ public T moveSubmissionToNewStatus(T submission, SubmissionStatus status, IUser
@Override
public T getSubmissionByIdUnsecured(Long id) throws NotExistException {
- T submission = submissionRepository.findOne(id);
+ T submission = submissionRepository.getOne(id);
throwNotExistExceptionIfNull(submission, id);
return submission;
}
@@ -336,7 +339,7 @@ public T getSubmissionById(Long id) throws NotExistException {
@Override
public T getSubmissionById(Long id, EntityGraph entityGraph) throws NotExistException {
- T submission = submissionRepository.findById(id, entityGraph);
+ T submission = submissionRepository.findById(id, entityGraph).orElse(null);
throwNotExistExceptionIfNull(submission, id);
return submission;
}
@@ -418,7 +421,7 @@ public SubmissionGroup createSubmissionGroup(IUser user, Analysis analysis) thro
}
files.add(submissionFile);
}
- submissionFileRepository.save(files);
+ submissionFileRepository.saveAll(files);
submissionGroup.setChecksum(calculateMD5Hash(submissionGroupFolder, files));
submissionGroupRepository.save(submissionGroup);
return submissionGroup;
@@ -432,7 +435,7 @@ public Page getSubmissionGroups(SubmissionGroupSearch submissoi
final SubmissionGroupSpecification submissionGroupSpecification = new SubmissionGroupSpecification(submissoinGroupSearch);
final Integer page = submissoinGroupSearch.getPage();
- final PageRequest pageRequest = new PageRequest(page == null ? 0 : page - 1, submissoinGroupSearch.getPageSize(), new Sort(Sort.Direction.DESC, "created"));
+ final PageRequest pageRequest = PageRequest.of(page == null ? 0 : page - 1, submissoinGroupSearch.getPageSize(), Sort.by(Sort.Direction.DESC, "created"));
final Page submissionGroups = submissionGroupRepository.findAll(submissionGroupSpecification, pageRequest);
final List content = submissionGroups.getContent();
final Map submissionGroupMap = content.stream().collect(Collectors.toMap(SubmissionGroup::getId, sg -> {
@@ -543,33 +546,64 @@ public T getSubmissionByIdAndToken(Long id, String token) throws NotExistExcepti
@Override
public void uploadCompressedResultsByDataOwner(Long submissionId, File compressedFile) throws IOException {
- Submission submission = submissionRepository.findById(submissionId);
+ Submission submission = submissionRepository.getOne(submissionId);
Objects.requireNonNull(submission);
UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
IUser user = userService.getByUsername(userDetails.getUsername());
Path unzipDir = Files.createTempDirectory(String.format("submission_%d_results", submissionId));
- ZipFile zipFile = new ZipFile(compressedFile);
- final List fileHeaders = zipFile.getFileHeaders().stream()
- .filter(fileHeader -> !fileHeader.isDirectory())
- .collect(Collectors.toList());
try {
- for (FileHeader fileHeader : fileHeaders) {
- String relativeFilePath = fileHeader.getFileName();
- String relativePath = FilenameUtils.getPath(relativeFilePath);
- if(isNotBlank(relativePath)){
- unzipDir.resolve(relativePath).toFile().mkdirs();
- }
- final File localFile = unzipDir.resolve(relativeFilePath).toFile();
- FileUtils.copyInputStreamToFile(zipFile.getInputStream(fileHeader), localFile);
- }
+ unzipWithNested(new ZipFile(compressedFile), unzipDir);
storeExtractedFiles(submission, unzipDir, user.getId());
} finally {
FileUtils.deleteDirectory(unzipDir.toFile());
}
}
+ private void unzipWithNested(final ZipFile zipFile, final Path unzipDir) throws IOException {
+ final Queue> queue = zipFile.getFileHeaders().stream()
+ .filter(fh -> !fh.isDirectory())
+ .map(fh -> Triple.of(unzipDir, zipFile, fh))
+ .collect(Collectors.toCollection(LinkedList::new));
+
+ final Set filesToDelete = new HashSet<>();
+
+ while (!queue.isEmpty()) {
+ final Triple element = queue.poll();
+
+ final Path unzipPath = element.getLeft();
+ final ZipFile zip = element.getMiddle();
+ final FileHeader fileHeader = element.getRight();
+
+ final String relativeFilePath = fileHeader.getFileName();
+ final String relativePath = FilenameUtils.getPath(relativeFilePath);
+ if (isNotBlank(relativePath)) {
+ unzipPath.resolve(relativePath).toFile().mkdirs();
+ }
+ final File localFile = unzipPath.resolve(relativeFilePath).toFile();
+ FileUtils.copyInputStreamToFile(zip.getInputStream(fileHeader), localFile);
+
+ if (relativeFilePath.endsWith(".zip")) {
+ final ZipFile innerZipFile = new ZipFile(localFile);
+ if (innerZipFile.isValidZipFile()) {
+ final String relativePathWithoutExtension = FilenameUtils.removeExtension(relativeFilePath);
+ final Path zipFileNamedDir = unzipPath.resolve(relativePathWithoutExtension);
+ queue.addAll(innerZipFile.getFileHeaders().stream()
+ .filter(fh -> !fh.isDirectory())
+ .map(fh -> Triple.of(zipFileNamedDir, innerZipFile, fh))
+ .collect(Collectors.toCollection(LinkedList::new)));
+ filesToDelete.add(localFile);
+ }
+ }
+ }
+
+ // delete unzipped zip files
+ for (final File file: filesToDelete) {
+ FileUtils.deleteQuietly(file);
+ }
+ }
+
@Override
public ResultFile uploadResultFileByDataOwner(Long submissionId, File localFile) throws IOException {
@@ -591,7 +625,7 @@ public ResultFile uploadResultFileByDataOwner(Long submissionId, File localFile)
List resultFiles = submission.getResultFiles();
resultFiles.add(resultFile);
submission.setUpdated(updated);
- submissionResultFileRepository.save(resultFiles);
+ submissionResultFileRepository.saveAll(resultFiles);
saveSubmission(submission);
return resultFile;
}
@@ -608,13 +642,13 @@ private void storeExtractedFiles(Submission submission, Path unzipDir, long uplo
resultFile.setPath(arachneFileMeta.getPath());
resultFiles.add(resultFile);
}
- submissionResultFileRepository.save(resultFiles);
+ submissionResultFileRepository.saveAll(resultFiles);
}
@Override
public void getSubmissionAllFiles(Long submissionGroupId, String archiveName, OutputStream os) throws IOException {
- SubmissionGroup submissionGroup = submissionGroupRepository.findOne(submissionGroupId);
+ SubmissionGroup submissionGroup = submissionGroupRepository.getOne(submissionGroupId);
Path storeFilesPath = analysisHelper.getSubmissionGroupFolder(submissionGroup);
try (ZipOutputStream zos = new ZipOutputStream(os)) {
for (SubmissionFile submissionFile : submissionGroup.getFiles()) {
@@ -663,19 +697,19 @@ public T approveSubmission(Long submissionId, Boolean isApproved, String comment
@Override
public SubmissionGroup getSubmissionGroupById(Long id) throws NotExistException {
- return submissionGroupRepository.findOne(id);
+ return submissionGroupRepository.getOne(id);
}
@Override
public void deleteSubmissionStatusHistory(List statusHistory) {
- submissionStatusHistoryRepository.delete(statusHistory);
+ submissionStatusHistoryRepository.deleteAll(statusHistory);
}
@Override
public SubmissionStatusHistoryElement getSubmissionStatusHistoryElementById(Long id) {
- return submissionStatusHistoryRepository.findOne(id);
+ return submissionStatusHistoryRepository.findById(id).orElse(null);
}
@Override
@@ -701,13 +735,13 @@ public T updateSubmission(T submission) {
@Override
public void deleteSubmissions(List submissions) {
- submissionRepository.delete(submissions);
+ submissionRepository.deleteAll(submissions);
}
@Override
public void deleteSubmissionGroups(List groups) {
- submissionGroupRepository.delete(groups);
+ submissionGroupRepository.deleteAll(groups);
}
@Override
@@ -769,7 +803,7 @@ public ResultFile createResultFile(
@Override
public List getResultFiles(IUser user, Long submissionId, ResultFileSearch resultFileSearch) throws PermissionDeniedException {
- Submission submission = submissionRepository.findById(submissionId, EntityUtils.fromAttributePaths("dataSource", "dataSource.dataNode"));
+ Submission submission = submissionRepository.findById(submissionId, EntityUtils.fromAttributePaths("dataSource", "dataSource.dataNode")).get();
checkSubmissionPermission(user, submission);
String resultFilesPath = contentStorageHelper.getResultFilesDir(submission, resultFileSearch.getPath());
@@ -806,7 +840,7 @@ public ResultFile getResultFileByPath(String path) {
public ResultFile getResultFileById(Long fileId) {
- return resultFileRepository.findById(fileId);
+ return resultFileRepository.findById(fileId).orElseThrow(IllegalArgumentException::new);
}
@Override
@@ -818,7 +852,7 @@ public void getSubmissionResultAllFiles(
OutputStream os) throws
IOException, PermissionDeniedException {
- Submission submission = submissionRepository.findOne(submissionId);
+ Submission submission = submissionRepository.getOne(submissionId);
checkSubmissionPermission(user, submission);
Path resultFilesPath = Paths.get(contentStorageHelper.getResultFilesDir(submission));
diff --git a/src/main/resources/application-base.yml b/src/main/resources/application-base.yml
index a4d6b4635..8478e82df 100644
--- a/src/main/resources/application-base.yml
+++ b/src/main/resources/application-base.yml
@@ -17,25 +17,24 @@ logging:
org.springframework.web.servlet.PageNotFound: ERROR
spring:
jpa:
- database: POSTGRESQL
+ show-sql: true
+ database-platform: org.hibernate.dialect.PostgreSQL95Dialect
properties:
- hibernate:
- jdbc:
- batch_size: 20
- dialect: org.hibernate.dialect.PostgreSQLDialect
- ddl-auto: none
- connection:
- CharSet: utf8
- characterEncoding: utf8
- useUnicode: true
- show-sql: false
+ hibernate.jdbc.batch_size: 20
+ hibernate.jdbc.lob.non_contextual_creation: true
+ hibernate.hbm2ddl.auto: none
datasource:
url: jdbc:postgresql://localhost:5434/arachne_portal
username: ohdsi
password: ENC(0Lpfvg9UPAyaaZpSIqwaDg==)
driver-class-name: org.postgresql.Driver
- max-active: 400
connection-test-query: select 1
+ pool-name: Central-Pool
+ flyway:
+ out-of-order: true
+ table: "schema_version"
+ ignore-missing-migrations: true
+ enabled: true
cache:
jcache:
config: classpath:ehcache.xml
@@ -57,7 +56,7 @@ spring:
throw-exception-if-no-handler-found: true
thymeleaf:
enabled: false
- http:
+ servlet:
multipart:
max-file-size: 1024MB
max-request-size: 1024MB
@@ -67,20 +66,18 @@ spring:
broker-url: vm://localhost?broker.persistent=true
packages:
trust-all: true
+ main:
+ allow-bean-definition-overriding: true
+management:
+ endpoint:
+ restart:
+ enabled: true
+ health:
+ ldap:
+ enabled: false
build:
number: @build.number@
id: @build.id@
-flyway:
- datasource:
- driverClassName: org.postgresql.Driver
- url: ${spring.datasource.url}
- username: ${spring.datasource.username}
- password: ${spring.datasource.password}
- baseline-on-migrate: true
- placeholderReplacement: false
- out-of-order: true
- validateOnMigrate: false
- #locations: db/migration,classpath:com.odysseusinc.arachne.portal.db.migration
arachne:
token:
secret: 129DF19C8A91AFD8375A2826A33539K01ACQ778QOJFAA9MGWLWH73PLXVFVHBR7860MTIE2O8EEVF9KCO77P6A7NUNX4XHAGCRFSBWG879XPDOIN6C2LFCKJI002OIABS4D6Q9VMJJIX8UCE48EF
@@ -136,7 +133,8 @@ datanode:
importTimeout: 60000
jasypt:
encryptor:
- password:
+ algorithm: PBEWITHMD5ANDDES
+ iv-generator-classname: org.jasypt.iv.NoIvGenerator
achilles:
executor:
corePoolSize: 4
diff --git a/src/main/resources/db/migration/V20210622115059__datasource_access_type.sql b/src/main/resources/db/migration/V20210622115059__datasource_access_type.sql
new file mode 100644
index 000000000..4ef57f38b
--- /dev/null
+++ b/src/main/resources/db/migration/V20210622115059__datasource_access_type.sql
@@ -0,0 +1,18 @@
+ALTER TABLE data_sources_data
+ ADD COLUMN IF NOT EXISTS access_type VARCHAR NULL DEFAULT 'PUBLIC';
+
+ALTER TABLE data_sources_data DROP CONSTRAINT data_sources_data_not_blank_fields_if_published;
+
+ALTER TABLE data_sources_data ADD CONSTRAINT data_sources_data_not_blank_fields_if_published
+ CHECK (published = FALSE OR (organization <> '' AND model_type <> '' AND access_type <> ''));
+
+CREATE OR REPLACE VIEW data_sources
+AS
+SELECT *
+FROM data_sources_data ds
+WHERE EXISTS(
+ SELECT 1
+ FROM tenants_data_sources tds
+ WHERE tds.data_source_id = ds.id AND tds.tenant_id = current_setting('app.tenant_id')::BIGINT
+ );
+
diff --git a/src/test/java/com/odysseusinc/arachne/portal/api/v1/controller/AchillesControllerTest.java b/src/test/java/com/odysseusinc/arachne/portal/api/v1/controller/AchillesControllerTest.java
index 6a26e2e9a..2026603c0 100644
--- a/src/test/java/com/odysseusinc/arachne/portal/api/v1/controller/AchillesControllerTest.java
+++ b/src/test/java/com/odysseusinc/arachne/portal/api/v1/controller/AchillesControllerTest.java
@@ -152,13 +152,13 @@ public void listReports() throws Exception {
public void getFile() throws Exception {
Bootstrap bootstrap = new Bootstrap();
- AchillesFile observationFile = achillesFileRepository.findOne(11L);
+ AchillesFile observationFile = achillesFileRepository.findById(11L).orElse(null);
assertThat(observationFile, is(notNullValue()));
observationFile.setData(bootstrap.observationJson());
- AchillesFile dashboardFile = achillesFileRepository.findOne(4L);
+ AchillesFile dashboardFile = achillesFileRepository.findById(4L).get();
assertThat(dashboardFile, is(notNullValue()));
dashboardFile.setData(bootstrap.dashboardJson());
- achillesFileRepository.save(Arrays.asList(observationFile, dashboardFile));
+ achillesFileRepository.saveAll(Arrays.asList(observationFile, dashboardFile));
mvc.perform(get(String.format(API_FILES, PUBLIC_DS, "dashboard.json"))
.accept(MediaType.APPLICATION_JSON_UTF8))
diff --git a/src/test/java/com/odysseusinc/arachne/portal/service/BaseDataSourceServiceTest.java b/src/test/java/com/odysseusinc/arachne/portal/service/BaseDataSourceServiceTest.java
index 8f9a00e2e..0baafd8ca 100644
--- a/src/test/java/com/odysseusinc/arachne/portal/service/BaseDataSourceServiceTest.java
+++ b/src/test/java/com/odysseusinc/arachne/portal/service/BaseDataSourceServiceTest.java
@@ -46,8 +46,8 @@ public static Collection