Fixing issues on building migration tool

This commit is contained in:
Thomas Georgios Giannos 2023-12-12 18:06:30 +02:00
parent 9f781853a7
commit baae057c6a
22 changed files with 2 additions and 1370 deletions

View File

@ -1,55 +0,0 @@
package eu.old.eudat.controllers;
import eu.old.eudat.logic.managers.ContactEmailManager;
import eu.old.eudat.models.data.ContactEmail.ContactEmailModel;
import eu.old.eudat.models.data.ContactEmail.PublicContactEmailModel;
import eu.old.eudat.models.data.helpers.responses.ResponseItem;
import eu.old.eudat.models.data.security.Principal;
import eu.old.eudat.types.ApiMessageCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import jakarta.transaction.Transactional;
@RestController
@CrossOrigin
@RequestMapping(value = "api/contactEmail")
public class ContactEmail {
private static final Logger logger = LoggerFactory.getLogger(ContactEmail.class);
private ContactEmailManager contactEmailManager;
public ContactEmail(ContactEmailManager contactEmailManager) {
this.contactEmailManager = contactEmailManager;
}
@Transactional
@RequestMapping(method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity sendContactEmail(@RequestBody ContactEmailModel contactEmailModel, Principal principal) {
try {
this.contactEmailManager.emailValidation(contactEmailModel);
this.contactEmailManager.sendContactEmail(contactEmailModel, principal);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE));
} catch (Exception ex) {
logger.error(ex.getMessage(), ex);
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem().status(ApiMessageCode.ERROR_MESSAGE).message(ex.getMessage()));
}
}
@Transactional
@RequestMapping(method = RequestMethod.POST, path = "public", consumes = "application/x-www-form-urlencoded", produces = "application/json")
public @ResponseBody
ResponseEntity sendContactEmailNoAuth(@ModelAttribute PublicContactEmailModel contactEmailModel) {
try {
this.contactEmailManager.sendContactEmailNoAuth(contactEmailModel);
return ResponseEntity.status(HttpStatus.NO_CONTENT).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE));
} catch (Exception ex) {
logger.error(ex.getMessage(), ex);
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem().status(ApiMessageCode.ERROR_MESSAGE).message(ex.getMessage()));
}
}
}

View File

@ -1,59 +0,0 @@
package eu.old.eudat.controllers;
import eu.old.eudat.exceptions.emailconfirmation.HasConfirmedEmailException;
import eu.old.eudat.exceptions.emailconfirmation.TokenExpiredException;
import eu.old.eudat.logic.managers.EmailConfirmationManager;
import eu.old.eudat.models.data.helpers.responses.ResponseItem;
import eu.old.eudat.models.data.security.Principal;
import eu.old.eudat.types.ApiMessageCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import jakarta.transaction.Transactional;
@RestController
@CrossOrigin
@RequestMapping(value = "api/emailConfirmation")
public class EmailConfirmation {
private EmailConfirmationManager emailConfirmationManager;
@Autowired
public EmailConfirmation(EmailConfirmationManager emailConfirmationManager) {
this.emailConfirmationManager = emailConfirmationManager;
}
@Transactional
@RequestMapping(method = RequestMethod.GET, value = {"/{emailToken}"})
public @ResponseBody
ResponseEntity<ResponseItem> emailConfirmation(@PathVariable(value = "emailToken") String token) {
try {
this.emailConfirmationManager.confirmEmail(token);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE));
} catch
(HasConfirmedEmailException | TokenExpiredException ex) {
if (ex instanceof TokenExpiredException) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem().status(ApiMessageCode.NO_MESSAGE));
} else {
return ResponseEntity.status(HttpStatus.FOUND).body(new ResponseItem().status(ApiMessageCode.WARN_MESSAGE));
}
}
}
@Transactional
@RequestMapping(method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity sendConfirmatioEmail(@RequestBody String email, Principal principal) {
try {
this.emailConfirmationManager.sendConfirmationEmail(email, principal);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE));
} catch (Exception ex) {
if (ex instanceof HasConfirmedEmailException) {
return ResponseEntity.status(HttpStatus.FOUND).body(new ResponseItem().status(ApiMessageCode.WARN_MESSAGE));
}
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem().status(ApiMessageCode.NO_MESSAGE));
}
}
}

View File

@ -1,60 +0,0 @@
package eu.old.eudat.controllers;
import eu.old.eudat.exceptions.emailconfirmation.HasConfirmedEmailException;
import eu.old.eudat.exceptions.emailconfirmation.TokenExpiredException;
import eu.old.eudat.logic.managers.MergeEmailConfirmationManager;
import eu.old.eudat.models.data.helpers.responses.ResponseItem;
import eu.old.eudat.models.data.security.Principal;
import eu.old.eudat.models.data.userinfo.UserMergeRequestModel;
import eu.old.eudat.types.ApiMessageCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import jakarta.transaction.Transactional;
@RestController
@CrossOrigin
@RequestMapping(value = "api/emailMergeConfirmation")
public class EmailMergeConfirmation {
private MergeEmailConfirmationManager emailConfirmationManager;
@Autowired
public EmailMergeConfirmation(MergeEmailConfirmationManager emailConfirmationManager) {
this.emailConfirmationManager = emailConfirmationManager;
}
@Transactional
@RequestMapping(method = RequestMethod.GET, value = {"/{emailToken}"})
public @ResponseBody
ResponseEntity<ResponseItem<String>> emailConfirmation(@PathVariable(value = "emailToken") String token) {
try {
String emailToBeMerged = this.emailConfirmationManager.confirmEmail(token);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<String>().payload(emailToBeMerged).status(ApiMessageCode.SUCCESS_MESSAGE));
} catch
(HasConfirmedEmailException | TokenExpiredException ex) {
if (ex instanceof TokenExpiredException) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem<String>().status(ApiMessageCode.NO_MESSAGE));
} else {
return ResponseEntity.status(HttpStatus.FOUND).body(new ResponseItem<String>().status(ApiMessageCode.WARN_MESSAGE));
}
}
}
@Transactional
@RequestMapping(method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity sendConfirmatioEmail(@RequestBody UserMergeRequestModel requestModel, Principal principal) {
try {
this.emailConfirmationManager.sendConfirmationEmail(requestModel.getEmail(), principal, requestModel.getUserId(), requestModel.getProvider());
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE));
} catch (Exception ex) {
if (ex instanceof HasConfirmedEmailException) {
return ResponseEntity.status(HttpStatus.FOUND).body(new ResponseItem().status(ApiMessageCode.WARN_MESSAGE));
}
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem().status(ApiMessageCode.NO_MESSAGE));
}
}
}

View File

@ -1,57 +0,0 @@
package eu.old.eudat.controllers;
import eu.old.eudat.exceptions.emailconfirmation.HasConfirmedEmailException;
import eu.old.eudat.exceptions.emailconfirmation.TokenExpiredException;
import eu.old.eudat.logic.managers.UnlinkEmailConfirmationManager;
import eu.old.eudat.models.data.helpers.responses.ResponseItem;
import eu.old.eudat.models.data.security.Principal;
import eu.old.eudat.models.data.userinfo.UserUnlinkRequestModel;
import eu.old.eudat.types.ApiMessageCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import jakarta.transaction.Transactional;
@RestController
@CrossOrigin
@RequestMapping(value = "api/emailUnlinkConfirmation")
public class EmailUnlinkConfirmation {
private UnlinkEmailConfirmationManager unlinkEmailConfirmationManager;
@Autowired
public EmailUnlinkConfirmation(UnlinkEmailConfirmationManager unlinkEmailConfirmationManager){
this.unlinkEmailConfirmationManager = unlinkEmailConfirmationManager;
}
@Transactional
@RequestMapping(method = RequestMethod.GET, value = {"/{emailToken}"})
public @ResponseBody
ResponseEntity<ResponseItem> emailConfirmation(@PathVariable(value = "emailToken") String token) {
try {
this.unlinkEmailConfirmationManager.confirmEmail(token);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE));
} catch (TokenExpiredException | HasConfirmedEmailException ex) {
if (ex instanceof TokenExpiredException) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem().status(ApiMessageCode.NO_MESSAGE));
}
else {
return ResponseEntity.status(HttpStatus.FOUND).body(new ResponseItem().status(ApiMessageCode.WARN_MESSAGE));
}
}
}
@Transactional
@RequestMapping(method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem> sendUnlinkConfirmationEmail(@RequestBody UserUnlinkRequestModel requestModel, Principal principal) {
try {
this.unlinkEmailConfirmationManager.sendConfirmationEmail(requestModel.getEmail(), principal, requestModel.getUserId(), requestModel.getProvider());
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE));
} catch (Exception ex) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem().status(ApiMessageCode.NO_MESSAGE).message("Could not send unlink email."));
}
}
}

View File

@ -1,59 +0,0 @@
package eu.old.eudat.controllers;
import eu.old.eudat.data.query.items.item.userinfo.UserInfoRequestItem;
import eu.old.eudat.logic.managers.InvitationsManager;
import eu.old.eudat.logic.services.ApiContext;
import eu.old.eudat.models.data.helpers.responses.ResponseItem;
import eu.old.eudat.models.data.invitation.Invitation;
import eu.old.eudat.models.data.security.Principal;
import eu.old.eudat.models.data.userinfo.UserInfoInvitationModel;
import eu.old.eudat.types.ApiMessageCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import jakarta.xml.bind.JAXBException;
import java.io.IOException;
import java.util.List;
import java.util.UUID;
@RequestMapping("api/invite/")
@RestController
@CrossOrigin
public class UserInvitationController extends BaseController {
private InvitationsManager invitationsManager;
@Autowired
public UserInvitationController(ApiContext apiContext, InvitationsManager invitationsManager) {
super(apiContext);
this.invitationsManager = invitationsManager;
}
@Transactional
@RequestMapping(method = RequestMethod.POST, value = {"/users"}, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<Invitation>> users(@RequestBody Invitation invitation, Principal principal) throws Exception {
this.invitationsManager.inviteUsers(invitation, principal);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<Invitation>().status(ApiMessageCode.SUCCESS_MESSAGE).message("Users have beeen invited"));
}
@Transactional
@RequestMapping(method = RequestMethod.GET, value = {"/exchange/{invitationID}"}, produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<UUID>> exchange(@PathVariable UUID invitationID, Principal principal) throws JAXBException, IOException {
UUID dmpId = invitationsManager.assignUserAcceptedInvitation(invitationID, principal);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<UUID>().status(ApiMessageCode.SUCCESS_MESSAGE).payload(dmpId));
}
@RequestMapping(method = RequestMethod.POST, value = {"/getUsers"}, consumes = "application/json", produces = "application/json")
public @ResponseBody
// ResponseEntity<ResponseItem<List<UserInfoInvitationModel>>> getUsers(Principal principal) throws IllegalAccessException, InstantiationException {
ResponseEntity<ResponseItem<List<UserInfoInvitationModel>>> getUsers(Principal principal, @RequestBody UserInfoRequestItem userInfoRequestItem) throws IllegalAccessException, InstantiationException {
// List<UserInfoInvitationModel> users = invitationsManager.getUsers(principal);
List<UserInfoInvitationModel> users = invitationsManager.getUsersWithCriteria(principal, userInfoRequestItem);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List<UserInfoInvitationModel>>().status(ApiMessageCode.SUCCESS_MESSAGE).payload(users));
}
}

View File

@ -1,58 +0,0 @@
package eu.old.eudat.logic.managers;
import eu.old.eudat.data.entities.UserInfo;
import eu.old.eudat.logic.services.ApiContext;
import eu.old.eudat.models.data.ContactEmail.ContactEmailModel;
import eu.old.eudat.models.data.ContactEmail.PublicContactEmailModel;
import eu.old.eudat.models.data.security.Principal;
import eu.eudat.service.mail.SimpleMail;
import org.springframework.core.env.Environment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import jakarta.mail.MessagingException;
@Component
public class ContactEmailManager {
private ApiContext apiContext;
private Environment environment;
@Autowired
public ContactEmailManager(ApiContext apiContext, Environment environment) {
this.apiContext = apiContext;
this.environment = environment;
}
public void sendContactEmail(ContactEmailModel contactEmailModel, Principal principal) throws MessagingException {
UserInfo user = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(principal.getId());
SimpleMail mail = new SimpleMail();
String enrichedMail = contactEmailModel.getDescription() + "\n\n" + "Send by user: " + user.getEmail() ;
mail.setSubject(contactEmailModel.getSubject());
mail.setTo(environment.getProperty("contact_email.mail"));
mail.setContent(enrichedMail);
mail.setFrom(user.getEmail());
apiContext.getUtilitiesService().getMailService().sendSimpleMail(mail);
}
public void sendContactEmailNoAuth(PublicContactEmailModel contactEmailModel) throws MessagingException {
SimpleMail mail = new SimpleMail();
String enrichedMail = contactEmailModel.getMessage() + "\n\n" + "Send by user: " + contactEmailModel.getEmail() ;
mail.setSubject(contactEmailModel.getAffiliation());
mail.setTo(environment.getProperty("contact_email.mail"));
mail.setContent(enrichedMail);
mail.setFrom(contactEmailModel.getEmail());
apiContext.getUtilitiesService().getMailService().sendSimpleMail(mail);
}
public void emailValidation(ContactEmailModel contactEmailModel) throws Exception {
if (contactEmailModel.getSubject() == null || contactEmailModel.getSubject().trim().isEmpty()) {
throw new Exception("Subject is empty");
}
if (contactEmailModel.getDescription() == null || contactEmailModel.getDescription().trim().isEmpty()) {
throw new Exception("Description is empty");
}
}
}

View File

@ -28,7 +28,6 @@ import eu.old.eudat.models.data.listingmodels.UserInfoListingModel;
import eu.old.eudat.models.data.security.Principal;
import eu.old.eudat.models.data.admin.composite.DatasetProfile;
import eu.old.eudat.queryable.QueryableList;
import eu.eudat.service.mail.SimpleMail;
import eu.old.eudat.types.Authorities;
import eu.old.eudat.types.MetricNames;
import org.slf4j.Logger;
@ -322,14 +321,12 @@ public class DatasetProfileManager {
userDatasetProfile1.setUser(userInfo1);
userDatasetProfile1.setRole(1);
apiContext.getOperationsContext().getDatabaseRepository().getUserDatasetProfileDao().createOrUpdate(userDatasetProfile1);
sendJoinMail(userDatasetProfile1);
});
entity.getUsers().stream().filter(userDatasetProfile -> model.getUsers().stream()
.filter(userInfoListingModel -> userDatasetProfile.getUser().getId().equals(userInfoListingModel.getId())).count() > 0
&& userDatasetProfile.getRole() == 2).forEach(userDatasetProfile -> {
userDatasetProfile.setRole(1);
apiContext.getOperationsContext().getDatabaseRepository().getUserDatasetProfileDao().createOrUpdate(userDatasetProfile);
sendJoinMail(userDatasetProfile);
});
}
if (entity.getUsers() != null && !entity.getUsers().isEmpty()) {
@ -356,24 +353,6 @@ public class DatasetProfileManager {
}
}
private void sendJoinMail(UserDatasetProfile userDatasetProfile) {
SimpleMail mail = new SimpleMail();
mail.setSubject(environment.getProperty("admin.mail.subject").replace( "{templateName}", userDatasetProfile.getDatasetProfile().getLabel()));
String content = apiContext.getUtilitiesService().getMailService().getMailTemplateContent(environment.getProperty("email.dataset.template"));
content = content.replace("{recipient}", userDatasetProfile.getUser().getName());
content = content.replace("{templateName}", userDatasetProfile.getDatasetProfile().getLabel());
content = content.replace("{host}", this.environment.getProperty("dmp.domain"));
content = content.replace("{templateID}", userDatasetProfile.getDatasetProfile().getId().toString());
mail.setContent(content);
mail.setTo(userDatasetProfile.getUser().getEmail());
try {
apiContext.getUtilitiesService().getMailService().sendSimpleMail(mail);
} catch (Exception ex) {
logger.error(ex.getMessage(), ex);
}
}
public List<String> getSemantics(String query) {
List<Semantic> semantics = configLoader.getSemantics();
List<String> filteredSemantics = semantics.stream().map(Semantic::getName).collect(Collectors.toList());

View File

@ -66,19 +66,6 @@ public class EmailConfirmationManager {
databaseRepository.getLoginConfirmationEmailDao().createOrUpdate(loginConfirmationEmail);
}
public void sendConfirmationEmail(String email, Principal principal) throws HasConfirmedEmailException {
UserInfo user = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(principal.getId());
if (user.getEmail() != null)
throw new HasConfirmedEmailException("User already has confirmed his Email.");
apiContext.getUtilitiesService().getConfirmationEmailService().createConfirmationEmail(
databaseRepository.getLoginConfirmationEmailDao(),
apiContext.getUtilitiesService().getMailService(),
email,
principal.getId()
);
}
private void mergeNewUserToOld(UserInfo newUser, UserInfo oldUser) {
Credential credential = databaseRepository.getCredentialDao().asQueryable().where((builder, root) -> builder.equal(root.get("userInfo"), newUser)).getSingle();
credential.setUserInfo(oldUser);

View File

@ -1,153 +0,0 @@
package eu.old.eudat.logic.managers;
import eu.old.eudat.data.entities.DMP;
import eu.old.eudat.data.entities.UserDMP;
import eu.old.eudat.data.entities.UserInfo;
import eu.old.eudat.data.query.items.item.userinfo.UserInfoRequestItem;
import eu.old.eudat.exceptions.security.UnauthorisedException;
import eu.old.eudat.logic.services.ApiContext;
import eu.old.eudat.logic.utilities.helpers.StreamDistinctBy;
import eu.old.eudat.models.data.invitation.Invitation;
import eu.old.eudat.models.data.invitation.Properties;
import eu.old.eudat.models.data.security.Principal;
import eu.old.eudat.models.data.userinfo.UserInfoInvitationModel;
import eu.old.eudat.queryable.QueryableList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import jakarta.xml.bind.JAXBContext;
import jakarta.xml.bind.JAXBException;
import jakarta.xml.bind.Unmarshaller;
import java.io.IOException;
import java.io.StringReader;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@Component
public class InvitationsManager {
private ApiContext apiContext;
private DataManagementPlanManager dataManagementPlanManager;
@Autowired
public InvitationsManager(ApiContext apiContext, DataManagementPlanManager dataManagementPlanManager) {
this.apiContext = apiContext;
this.dataManagementPlanManager = dataManagementPlanManager;
}
public void inviteUsers(Invitation invitation, Principal principal) throws Exception {
UserInfo principalUser = new UserInfo();
principalUser.setId(principal.getId());
invitation.getUsers().stream().filter(item -> item.getId() == null).forEach(item -> {
UserInfo existingUser = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().asQueryable().where((builder, root) -> builder.equal(root.get("email"), item.getEmail())).getSingleOrDefault();
if (existingUser != null) {
item.setId(existingUser.getId());
}
});
List<UserInfoInvitationModel> alreadySignedInUsers = invitation.getUsers().stream().filter(item -> item.getId() != null).collect(Collectors.toList());
List<UserInfo> alreadySignedInUsersEntities = alreadySignedInUsers.stream().map(UserInfoInvitationModel::toDataModel).collect(Collectors.toList());
List<UserDMP> userInfoToUserDmp = new LinkedList<>();
for (UserInfo userInfo : alreadySignedInUsersEntities) {
UserDMP userDMP = new UserDMP();
userDMP.setUser(userInfo);
userDMP.setRole(invitation.getRole());
userInfoToUserDmp.add(userDMP);
/*if (!apiContext.getOperationsContext().getDatabaseRepository().getUserAssociationDao().areAssociated(principalUser, userInfo)) {
UserAssociation userAssociation = new UserAssociation();
userAssociation.setFirstUser(principalUser);
userAssociation.setSecondUser(userInfo);
apiContext.getOperationsContext().getDatabaseRepository().getUserAssociationDao().createOrUpdate(userAssociation);
}*/
}
DMP dataManagementPlan = apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().find(invitation.getDataManagementPlan());
apiContext.getUtilitiesService().getInvitationService().createInvitations(apiContext.getOperationsContext().getDatabaseRepository().getInvitationDao(), apiContext.getUtilitiesService().getMailService(), invitation.getUsers().stream().map(UserInfoInvitationModel::toDataModel).collect(Collectors.toList()), dataManagementPlan, invitation.getRole(), principalUser);
apiContext.getUtilitiesService().getInvitationService().assignToDmp(apiContext.getOperationsContext().getDatabaseRepository().getDmpDao(), userInfoToUserDmp, dataManagementPlan);
}
public List<UserInfoInvitationModel> getUsers(Principal principal) throws InstantiationException, IllegalAccessException {
/*UserInfo principalUser = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(principal.getId());
List<UserInfo> users = apiContext.getOperationsContext().getDatabaseRepository().getUserAssociationDao().getAssociated(principalUser).stream().map(userAssociation -> {
if (userAssociation.getFirstUser().getId().equals(principal.getId())) {
return userAssociation.getSecondUser();
} else {
return userAssociation.getFirstUser();
}
}).collect(Collectors.toList());*/
List<UserInfo> users = apiContext.getOperationsContext().getDatabaseRepository().getDmpDao()
.getAuthenticated(apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().asQueryable()
.where(((builder, root) -> builder.notEqual(root.get("status"), DMP.DMPStatus.DELETED.getValue()))), principal.getId(), Stream.of(0, 1).collect(Collectors.toList()))
.toList().stream().map(DMP::getUsers).flatMap(Collection::stream).map(UserDMP::getUser)
.filter(userInfo -> !userInfo.getId().equals(principal.getId())).filter(StreamDistinctBy.distinctByKey(UserInfo::getId)).collect(Collectors.toList());
List<UserInfoInvitationModel> userModels = users.stream().map(userInfo -> new UserInfoInvitationModel().fromDataModel(userInfo)).collect(Collectors.toList());
return userModels;
}
public List<UserInfoInvitationModel> getUsersWithCriteria(Principal principal, UserInfoRequestItem userInfoRequestItem) throws IllegalAccessException, InstantiationException {
List<UserInfo> users = apiContext.getOperationsContext().getDatabaseRepository().getDmpDao()
.getAuthenticated(apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().asQueryable()
.where(((builder, root) ->
builder.notEqual(root.get("status"), DMP.DMPStatus.DELETED.getValue()))), principal.getId(), Stream.of(0, 1).collect(Collectors.toList()))
.toList().stream().map(DMP::getUsers).flatMap(Collection::stream).map(UserDMP::getUser)
.filter(userInfo -> !userInfo.getId().equals(principal.getId())).filter(StreamDistinctBy.distinctByKey(UserInfo::getId))
.filter(userInfo -> (userInfoRequestItem == null || userInfoRequestItem.getCriteria() == null || userInfoRequestItem.getCriteria().getLike() == null
|| userInfo.getName().toLowerCase().contains(userInfoRequestItem.getCriteria().getLike().toLowerCase())
|| (userInfo.getEmail().toLowerCase().contains(userInfoRequestItem.getCriteria().getLike().toLowerCase()))))
.collect(Collectors.toList());
// .where((builder, root) -> builder.like(builder.upper(root.get("name")), "%" + userInfoRequestItem.getCriteria().getLike().toUpperCase() + "%"))
List<UserInfoInvitationModel> userModels = users.stream().map(userInfo -> new UserInfoInvitationModel().fromDataModel(userInfo)).collect(Collectors.toList());
return userModels;
}
public UUID assignUserAcceptedInvitation(UUID invitationID, Principal principal) throws UnauthorisedException, JAXBException, IOException {
eu.old.eudat.data.entities.Invitation invitation = apiContext.getOperationsContext().getDatabaseRepository().getInvitationDao().find(invitationID);
if (invitation == null)
throw new UnauthorisedException("There is no Data Management Plan assigned to this Link");
if (invitation.getAcceptedInvitation()) return invitation.getDmp().getId(); //throw new UnauthorisedException("This Url Has Expired");
JAXBContext context = JAXBContext.newInstance(eu.old.eudat.models.data.invitation.Properties.class);
Unmarshaller unmarshaller = context.createUnmarshaller();
eu.old.eudat.models.data.invitation.Properties properties = (Properties) unmarshaller.unmarshal(new StringReader(invitation.getProperties()));
UserInfo invitedUser = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(principal.getId());
QueryableList<UserDMP> userDMPQueryableList = apiContext.getOperationsContext().getDatabaseRepository().getUserDmpDao().asQueryable().where(((builder, root) -> builder.and(builder.equal(root.get("dmp").get("id"), invitation.getDmp().getId()), builder.equal(root.get("user").get("id"), invitedUser.getId()))));
UserDMP existingUserDMP = userDMPQueryableList.getSingleOrDefault();
if (existingUserDMP != null) {
if (properties.getRole() != null && existingUserDMP.getRole() > properties.getRole()) {
existingUserDMP.setRole(properties.getRole());
DMP datamanagementPlan = invitation.getDmp();
apiContext.getOperationsContext().getDatabaseRepository().getUserDmpDao().createOrUpdate(existingUserDMP);
apiContext.getUtilitiesService().getInvitationService().assignToDmp(apiContext.getOperationsContext().getDatabaseRepository().getDmpDao(), existingUserDMP, datamanagementPlan);
invitation.setAcceptedInvitation(true);
apiContext.getOperationsContext().getDatabaseRepository().getInvitationDao().createOrUpdate(invitation);
datamanagementPlan.setUsers(new HashSet<>(apiContext.getOperationsContext().getDatabaseRepository().getUserDmpDao().asQueryable().where((builder, root) -> builder.equal(root.get("dmp").get("id"), datamanagementPlan.getId())).toList()));
dataManagementPlanManager.updateIndex(datamanagementPlan);
return datamanagementPlan.getId();
}
} else {
UserDMP userDMP = new UserDMP();
userDMP.setUser(invitedUser);
userDMP.setDmp(invitation.getDmp());
if (properties.getRole() != null) {
userDMP.setRole(properties.getRole());
} else {
userDMP.setRole(UserDMP.UserDMPRoles.USER.getValue());
}
/*if (!apiContext.getOperationsContext().getDatabaseRepository().getUserAssociationDao().areAssociated(invitedUser, invitation.getUser())) {
UserAssociation userAssociation = new UserAssociation();
userAssociation.setFirstUser(invitedUser);
userAssociation.setSecondUser(invitation.getUser());
apiContext.getOperationsContext().getDatabaseRepository().getUserAssociationDao().createOrUpdate(userAssociation);
}*/
DMP datamanagementPlan = invitation.getDmp();
apiContext.getOperationsContext().getDatabaseRepository().getUserDmpDao().createOrUpdate(userDMP);
apiContext.getUtilitiesService().getInvitationService().assignToDmp(apiContext.getOperationsContext().getDatabaseRepository().getDmpDao(), userDMP, datamanagementPlan);
invitation.setAcceptedInvitation(true);
apiContext.getOperationsContext().getDatabaseRepository().getInvitationDao().createOrUpdate(invitation);
datamanagementPlan.setUsers(new HashSet<>(apiContext.getOperationsContext().getDatabaseRepository().getUserDmpDao().asQueryable().where((builder, root) -> builder.equal(root.get("dmp").get("id"), datamanagementPlan.getId())).toList()));
dataManagementPlanManager.updateIndex(datamanagementPlan);
return datamanagementPlan.getId();
}
return invitation.getDmp().getId();
}
}

View File

@ -1,149 +0,0 @@
package eu.old.eudat.logic.managers;
import eu.old.eudat.data.entities.Credential;
import eu.old.eudat.data.entities.EmailConfirmation;
import eu.old.eudat.data.entities.UserDMP;
import eu.old.eudat.data.entities.UserInfo;
import eu.old.eudat.data.entities.UserToken;
import eu.old.eudat.elastic.criteria.DmpCriteria;
import eu.old.eudat.elastic.entities.Collaborator;
import eu.old.eudat.elastic.entities.Dmp;
import eu.old.eudat.elastic.repository.DmpRepository;
import eu.old.eudat.exceptions.emailconfirmation.HasConfirmedEmailException;
import eu.old.eudat.exceptions.emailconfirmation.TokenExpiredException;
import eu.old.eudat.logic.services.ApiContext;
import eu.old.eudat.logic.services.operations.DatabaseRepository;
import eu.old.eudat.models.data.security.Principal;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.transaction.Transactional;
import java.io.IOException;
import java.util.*;
@Component
public class MergeEmailConfirmationManager {
private static Logger logger = LoggerFactory.getLogger(MergeEmailConfirmationManager.class);
private ApiContext apiContext;
private DatabaseRepository databaseRepository;
private DmpRepository dmpRepository;
@Autowired
public MergeEmailConfirmationManager(ApiContext apiContext) {
this.apiContext = apiContext;
this.databaseRepository = apiContext.getOperationsContext().getDatabaseRepository();
this.dmpRepository = apiContext.getOperationsContext().getElasticRepository().getDmpRepository();
}
@Transactional
public String confirmEmail(String token) throws TokenExpiredException, HasConfirmedEmailException {
EmailConfirmation loginConfirmationEmail = apiContext.getOperationsContext()
.getDatabaseRepository().getLoginConfirmationEmailDao().asQueryable()
.where((builder, root) -> builder.equal(root.get("token"), UUID.fromString(token))).getSingle();
if (loginConfirmationEmail.getExpiresAt().compareTo(new Date()) < 0)
throw new TokenExpiredException("Token has expired.");
UserInfo userToBeMerged = databaseRepository.getUserInfoDao().asQueryable()
.where((builder, root) -> builder.equal(root.get("id"), loginConfirmationEmail.getUserId())).getSingle();
String userToBeMergedEmail = userToBeMerged.getEmail();
try {
Map<String, Object> map = new ObjectMapper().readValue(loginConfirmationEmail.getData(), HashMap.class);
UUID otherUserId = UUID.fromString((String) map.get("userId"));
UserInfo user = databaseRepository.getUserInfoDao().asQueryable()
.where((builder, root) -> builder.equal(root.get("id"), otherUserId)).getSingle();
// Checks if mail is used by another user. If it is, merges the new the old.
mergeNewUserToOld(user, userToBeMerged, Integer.valueOf((String) map.get("provider")));
expireUserToken(userToBeMerged);
loginConfirmationEmail.setIsConfirmed(true);
databaseRepository.getLoginConfirmationEmailDao().createOrUpdate(loginConfirmationEmail);
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
return userToBeMergedEmail;
}
public void sendConfirmationEmail(String email, Principal principal, UUID userId, Integer provider) throws HasConfirmedEmailException {
UserInfo user = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(principal.getId());
if (user.getEmail() != null && !user.getEmail().equals(email)) {
apiContext.getUtilitiesService().getConfirmationEmailService().createMergeConfirmationEmail(
databaseRepository.getLoginConfirmationEmailDao(),
apiContext.getUtilitiesService().getMailService(),
email,
userId,
principal,
provider
);
}
}
@Transactional
private void mergeNewUserToOld(UserInfo newUser, UserInfo oldUser, Integer provider) {
Credential credential = databaseRepository.getCredentialDao().asQueryable().where((builder, root) -> builder.and(builder.equal(root.get("userInfo"), oldUser), builder.equal(root.get("provider"), provider))).getSingle();
credential.setUserInfo(newUser);
databaseRepository.getCredentialDao().createOrUpdate(credential);
List<UserDMP> userDmps = databaseRepository.getUserDmpDao().asQueryable().where((builder, root) -> builder.equal(root.get("user"), oldUser)).toList();
userDmps.forEach(userDmp -> {
userDmp.setUser(newUser);
databaseRepository.getUserDmpDao().createOrUpdate(userDmp);
});
try {
DmpCriteria dmpCriteria = new DmpCriteria();
dmpCriteria.setCollaborators(Collections.singletonList(oldUser.getId()));
List<Dmp> elasticDmpsIds = dmpRepository.query(dmpCriteria);
for(Dmp dmpId: elasticDmpsIds){
Dmp dmp = dmpRepository.findDocument(dmpId.getId().toString());
if(dmp.getDatasets() != null) {
dmp.getDatasets().forEach(dataset -> {
if(dataset.getCollaborators() != null) {
for (Collaborator collaborator : dataset.getCollaborators()) {
if (collaborator.getId().equals(oldUser.getId().toString())) {
collaborator.setId(newUser.getId().toString());
collaborator.setName(newUser.getName());
}
}
}
});
}
if(dmp.getCollaborators() != null) {
for (Collaborator collaborator : dmp.getCollaborators()) {
if (collaborator.getId().equals(oldUser.getId().toString())) {
collaborator.setId(newUser.getId().toString());
collaborator.setName(newUser.getName());
}
}
}
dmpRepository.createOrUpdate(dmp);
}
}
catch (IOException e){
logger.warn("Warning: Could not fetch dmps from elastic.", e);
}
oldUser.setUserStatus((short)1);
oldUser.setEmail(null);
List<Credential> credentials = databaseRepository.getCredentialDao().asQueryable().where((builder, root) -> builder.equal(root.get("userInfo"), oldUser)).toList();
credentials.forEach(cred -> {
if (cred.getId() != credential.getId()) {
databaseRepository.getCredentialDao().delete(cred);
}
});
databaseRepository.getUserInfoDao().createOrUpdate(oldUser);
}
private void expireUserToken(UserInfo user) {
UserToken userToken = databaseRepository.getUserTokenDao().asQueryable()
.where((builder, root) -> builder.equal(root.get("user"), user))
.orderBy((builder, root) -> builder.desc(root.get("issuedAt")))
.take(1).toList().get(0);
userToken.setExpiresAt(new Date());
databaseRepository.getUserTokenDao().createOrUpdate(userToken);
}
}

View File

@ -1,124 +0,0 @@
package eu.old.eudat.logic.managers;
import com.fasterxml.jackson.databind.ObjectMapper;
import eu.old.eudat.data.entities.Notification;
import eu.old.eudat.data.entities.UserInfo;
import eu.old.eudat.data.enumeration.notification.ActiveStatus;
import eu.old.eudat.data.enumeration.notification.NotifyState;
import eu.old.eudat.logic.services.ApiContext;
import eu.eudat.service.mail.MailService;
import eu.eudat.service.mail.SimpleMail;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import jakarta.mail.MessagingException;
import jakarta.transaction.Transactional;
import java.io.IOException;
import java.util.*;
@Component
public class NotificationManager {
private static final Logger logger = LoggerFactory.getLogger(NotificationManager.class);
private ApiContext apiContext;
private Environment environment;
private MailService mailService;
@Autowired
public NotificationManager(ApiContext apiContext, Environment environment, MailService mailService) {
this.apiContext = apiContext;
this.environment = environment;
this.mailService = mailService;
}
@Transactional
public void sendNotification(Notification notification) throws Exception {
if (notification.getNotifyState() == NotifyState.ERROR) {
if (notification.getRetryCount() == null) {
notification.setRetryCount(0);
}
notification.setRetryCount(notification.getRetryCount() + 1);
if (notification.getRetryCount() >= this.environment.getProperty("notification.maxRetries", Integer.class)) {
notification.setIsActive(ActiveStatus.INACTIVE);
notification.setUpdatedAt(new Date());
return;
}
}
notification.setNotifyState(NotifyState.PROCESSING);
notification.setNotifiedAt(new Date());
notification.setUpdatedAt(new Date());
try {
Map<String, String> data = new ObjectMapper().readValue(notification.getData(), HashMap.class);
UserInfo userInfo = this.apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(UUID.fromString(data.get("userId")));
String subjectTemplate = "";
String contentTemplate = "";
switch (notification.getType()) {
case DMP_MODIFIED:
case DATASET_MODIFIED:
subjectTemplate = this.environment.getProperty("notification.modified.subject");
contentTemplate = mailService.getMailTemplateContent(this.environment.getProperty("notification.modified.template"));
break;
case DMP_PUBLISH:
subjectTemplate = this.environment.getProperty("notification.publish.subject");
contentTemplate = mailService.getMailTemplateContent(this.environment.getProperty("notification.publish.template"));
break;
case DMP_FINALISED:
subjectTemplate = this.environment.getProperty("notification.finalised.subject");
contentTemplate = mailService.getMailTemplateContent(this.environment.getProperty("notification.finalised.template"));
break;
case DMP_MODIFIED_FINALISED:
case DATASET_MODIFIED_FINALISED:
subjectTemplate = this.environment.getProperty("notification.modifiedFinalised.subject");
contentTemplate = mailService.getMailTemplateContent(this.environment.getProperty("notification.modified_finalised.template"));
break;
}
switch (notification.getContactTypeHint()) {
case EMAIL:
this.sendEmailNotification(notification, userInfo, data, subjectTemplate, contentTemplate);
break;
}
}catch (Exception e) {
notification.setNotifyState(NotifyState.ERROR);
notification.setUpdatedAt(new Date());
logger.error(e.getMessage(), e);
}
}
private void sendEmailNotification(Notification notification, UserInfo userInfo, Map<String, String> data, String subjectTemplate, String contentTemplate) throws IOException {
SimpleMail simpleMail = new SimpleMail();
simpleMail.setFrom(this.environment.getProperty("mail.from"));
simpleMail.setSubject(makeSubject(data, subjectTemplate));
simpleMail.setTo(notification.getContactHint());
simpleMail.setContent(makeContent(data, notification, userInfo, contentTemplate));
try {
mailService.sendSimpleMail(simpleMail);
notification.setNotifyState(NotifyState.SUCCEEDED);
notification.setUpdatedAt(new Date());
} catch (MessagingException e) {
notification.setNotifyState(NotifyState.ERROR);
notification.setUpdatedAt(new Date());
logger.error(e.getMessage(), e);
}
}
private String makeSubject(Map<String, String> data, String subjectTemplate) {
return subjectTemplate.replace("{name}", data.get("name"));
}
private String makeContent(Map<String, String> data, Notification notification, UserInfo userInfo, String template) {
String content = template;
content = content.replace("{recipient}", userInfo.getName());
for (String key : data.keySet()) {
content = content.replace("{" + key +"}", data.get(key));
}
content = content.replace("{host}", this.environment.getProperty("dmp.domain"));
content = content.replace("{reasonName}", notification.getUserId().getName());
return content;
}
}

View File

@ -1,89 +0,0 @@
package eu.old.eudat.logic.managers;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import eu.old.eudat.data.entities.Credential;
import eu.old.eudat.data.entities.EmailConfirmation;
import eu.old.eudat.data.entities.UserInfo;
import eu.old.eudat.exceptions.emailconfirmation.HasConfirmedEmailException;
import eu.old.eudat.exceptions.emailconfirmation.TokenExpiredException;
import eu.old.eudat.logic.services.ApiContext;
import eu.old.eudat.logic.services.operations.DatabaseRepository;
import eu.old.eudat.models.data.security.Principal;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import jakarta.transaction.Transactional;
import java.util.*;
@Component
public class UnlinkEmailConfirmationManager {
private static Logger logger = LoggerFactory.getLogger(UnlinkEmailConfirmationManager.class);
private ApiContext apiContext;
private DatabaseRepository databaseRepository;
@Autowired
public UnlinkEmailConfirmationManager(ApiContext apiContext) {
this.apiContext = apiContext;
this.databaseRepository = apiContext.getOperationsContext().getDatabaseRepository();
}
@Transactional
public void confirmEmail(String token) throws TokenExpiredException, HasConfirmedEmailException {
EmailConfirmation loginConfirmationEmail = apiContext.getOperationsContext()
.getDatabaseRepository().getLoginConfirmationEmailDao().asQueryable()
.where((builder, root) -> builder.equal(root.get("token"), UUID.fromString(token))).getSingle();
if (loginConfirmationEmail.getExpiresAt().compareTo(new Date()) < 0)
throw new TokenExpiredException("Token has expired.");
if(loginConfirmationEmail.getIsConfirmed())
throw new HasConfirmedEmailException("Email is already confirmed.");
// UserInfo userAskingForUnlink = databaseRepository.getUserInfoDao().asQueryable()
// .where((builder, root) -> builder.equal(root.get("id"), loginConfirmationEmail.getUserId())).getSingle();
try {
Map<String, Object> map = new ObjectMapper().readValue(loginConfirmationEmail.getData(), new TypeReference<Map<String, Object>>() {});
String emailTobeUnlinked = (String) map.get("email");
Integer provider = Integer.valueOf((String) map.get("provider"));
unlinkUser(emailTobeUnlinked, provider);
loginConfirmationEmail.setIsConfirmed(true);
databaseRepository.getLoginConfirmationEmailDao().createOrUpdate(loginConfirmationEmail);
}
catch (Exception e) {
logger.error(e.getMessage(), e);
}
}
@Transactional
private void unlinkUser(String emailTobeUnlinked, Integer provider){
Credential credential = databaseRepository.getCredentialDao().asQueryable()
.where((builder, root) -> builder.and(builder.equal(root.get("email"), emailTobeUnlinked), builder.equal(root.get("provider"), provider))).getSingle();
if(credential != null) {
databaseRepository.getCredentialDao().delete(credential);
}
}
public void sendConfirmationEmail(String email, Principal principal, UUID userId, Integer provider) {
UserInfo user = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(principal.getId());
if (user.getEmail() != null && !user.getEmail().equals(email)) {
apiContext.getUtilitiesService().getConfirmationEmailService().createUnlinkConfirmationEmail(
databaseRepository.getLoginConfirmationEmailDao(),
apiContext.getUtilitiesService().getMailService(),
email,
userId,
principal,
provider
);
}
}
}

View File

@ -2,13 +2,10 @@ package eu.old.eudat.logic.services;
import eu.old.eudat.logic.services.helpers.HelpersService;
import eu.old.eudat.logic.services.operations.OperationsContext;
import eu.old.eudat.logic.services.utilities.UtilitiesService;
public interface ApiContext {
HelpersService getHelpersService();
OperationsContext getOperationsContext();
UtilitiesService getUtilitiesService();
}

View File

@ -2,7 +2,6 @@ package eu.old.eudat.logic.services;
import eu.old.eudat.logic.services.helpers.HelpersService;
import eu.old.eudat.logic.services.operations.OperationsContext;
import eu.old.eudat.logic.services.utilities.UtilitiesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@ -12,13 +11,11 @@ public class ApiContextImpl implements ApiContext {
private OperationsContext operationsContext;
private HelpersService helpersService;
private UtilitiesService utilitiesService;
@Autowired
public ApiContextImpl(OperationsContext operationsContext, HelpersService helpersService, UtilitiesService utilitiesService) {
public ApiContextImpl(OperationsContext operationsContext, HelpersService helpersService) {
this.operationsContext = operationsContext;
this.helpersService = helpersService;
this.utilitiesService = utilitiesService;
}
@Override
@ -30,9 +27,4 @@ public class ApiContextImpl implements ApiContext {
public HelpersService getHelpersService() {
return helpersService;
}
@Override
public UtilitiesService getUtilitiesService() {
return utilitiesService;
}
}

View File

@ -1,23 +0,0 @@
package eu.old.eudat.logic.services.utilities;
import eu.old.eudat.data.dao.entities.EmailConfirmationDao;
import eu.old.eudat.data.entities.EmailConfirmation;
import eu.old.eudat.models.data.security.Principal;
import eu.eudat.service.mail.MailService;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
public interface ConfirmationEmailService {
public void createConfirmationEmail(EmailConfirmationDao loginConfirmationEmailDao, MailService mailService, String email, UUID userId);
public void createMergeConfirmationEmail(EmailConfirmationDao loginConfirmationEmailDao, MailService mailService, String email, UUID userId, Principal principal, Integer provider);
public void createUnlinkConfirmationEmail(EmailConfirmationDao loginConfirmationEmailDao, MailService mailService, String email, UUID userId, Principal principal, Integer provider);
public CompletableFuture sentConfirmationEmail(EmailConfirmation confirmationEmail, MailService mailService);
public CompletableFuture sentMergeConfirmationEmail(EmailConfirmation confirmationEmail, MailService mailService, String userName);
public CompletableFuture sentUnlinkConfirmationEmail(EmailConfirmation confirmationEmail, MailService mailService);
}

View File

@ -1,193 +0,0 @@
package eu.old.eudat.logic.services.utilities;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import eu.old.eudat.data.dao.entities.EmailConfirmationDao;
import eu.old.eudat.data.entities.EmailConfirmation;
import eu.old.eudat.models.data.security.Principal;
import eu.eudat.service.mail.MailService;
import eu.eudat.service.mail.SimpleMail;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
@Service("ConfirmationEmailService")
public class ConfirmationEmailServiceImpl implements ConfirmationEmailService {
private static final Logger logger = LoggerFactory.getLogger(ConfirmationEmailServiceImpl.class);
//private Logger logger;
private Environment environment;
public ConfirmationEmailServiceImpl(/*Logger logger,*/ Environment environment) {
// this.logger = logger;
this.environment = environment;
}
@Override
public void createConfirmationEmail(EmailConfirmationDao loginConfirmationEmailDao, MailService mailService, String email, UUID userId) {
EmailConfirmation confirmationEmail = new EmailConfirmation();
confirmationEmail.setEmail(email);
confirmationEmail.setExpiresAt(Date
.from(new Date()
.toInstant()
.plusSeconds(Long.parseLong(this.environment.getProperty("conf_email.expiration_time_seconds")))
)
);
confirmationEmail.setUserId(userId);
confirmationEmail.setIsConfirmed(false);
confirmationEmail.setToken(UUID.randomUUID());
confirmationEmail = loginConfirmationEmailDao.createOrUpdate(confirmationEmail);
sentConfirmationEmail(confirmationEmail, mailService);
}
@Override
public CompletableFuture sentConfirmationEmail(EmailConfirmation confirmationEmail, MailService mailService) {
return CompletableFuture.runAsync(() -> {
SimpleMail mail = new SimpleMail();
mail.setSubject(environment.getProperty("conf_email.subject"));
mail.setContent(createContent(confirmationEmail.getToken(), mailService));
mail.setTo(confirmationEmail.getEmail());
try {
mailService.sendSimpleMail(mail);
} catch (Exception ex) {
logger.error(ex.getMessage(), ex);
}
});
}
private String createContent(UUID confirmationToken, MailService mailService) {
String content = mailService.getMailTemplateContent(this.environment.getProperty("email.confirmation"));
content = content.replace("{confirmationToken}", confirmationToken.toString());
content = content.replace("{expiration_time}", secondsToTime(Integer.parseInt(this.environment.getProperty("conf_email.expiration_time_seconds"))));
content = content.replace("{host}", this.environment.getProperty("dmp.domain"));
return content;
}
@Override
public CompletableFuture sentMergeConfirmationEmail(EmailConfirmation confirmationEmail, MailService mailService, String userName) {
return CompletableFuture.runAsync(() -> {
SimpleMail mail = new SimpleMail();
mail.setSubject(environment.getProperty("conf_email.subject"));
mail.setContent(createMergeContent(confirmationEmail.getToken(), mailService, userName));
mail.setTo(confirmationEmail.getEmail());
try {
mailService.sendSimpleMail(mail);
} catch (Exception ex) {
logger.error(ex.getMessage(), ex);
}
});
}
@Override
public CompletableFuture sentUnlinkConfirmationEmail(EmailConfirmation confirmationEmail, MailService mailService) {
String email = null;
try {
Map<String, Object> map = new ObjectMapper().readValue(confirmationEmail.getData(), new TypeReference<Map<String, Object>>() {});
email = (String) map.get("email");
}
catch (JsonProcessingException e){
logger.error(e.getMessage(), e);
}
String finalEmail = email;
return CompletableFuture.runAsync(() -> {
SimpleMail mail = new SimpleMail();
mail.setSubject(environment.getProperty("conf_email.subject"));
mail.setContent(createUnlinkContent(confirmationEmail.getToken(), mailService, finalEmail));
mail.setTo(confirmationEmail.getEmail());
try {
mailService.sendSimpleMail(mail);
} catch (Exception ex) {
logger.error(ex.getMessage(), ex);
}
});
}
private String createMergeContent(UUID confirmationToken, MailService mailService, String userName) {
String content = mailService.getMailTemplateContent(this.environment.getProperty("email.merge"));
content = content.replace("{userName}", userName);
content = content.replace("{confirmationToken}", confirmationToken.toString());
content = content.replace("{expiration_time}", secondsToTime(Integer.parseInt(this.environment.getProperty("conf_email.expiration_time_seconds"))));
content = content.replace("{host}", this.environment.getProperty("dmp.domain"));
return content;
}
private String createUnlinkContent(UUID confirmationToken, MailService mailService, String email) {
String content = mailService.getMailTemplateContent(this.environment.getProperty("email.unlink"));
content = content.replace("{confirmationToken}", confirmationToken.toString());
content = content.replace("{expiration_time}", secondsToTime(Integer.parseInt(this.environment.getProperty("conf_email.expiration_time_seconds"))));
content = content.replace("{host}", this.environment.getProperty("dmp.domain"));
content = content.replace("{email}", email);
return content;
}
private String secondsToTime(int seconds) {
int sec = seconds % 60;
int hour = seconds / 60;
int min = hour % 60;
hour = hour / 60;
return (hour + ":" + min + ":" + sec);
}
@Override
public void createMergeConfirmationEmail(EmailConfirmationDao loginConfirmationEmailDao, MailService mailService,
String email, UUID userId, Principal principal, Integer provider) {
EmailConfirmation confirmationEmail = new EmailConfirmation();
confirmationEmail.setEmail(email);
confirmationEmail.setExpiresAt(Date
.from(new Date()
.toInstant()
.plusSeconds(Long.parseLong(this.environment.getProperty("conf_email.expiration_time_seconds")))
)
);
confirmationEmail.setUserId(userId);
try {
Map<String, Object> map = new HashMap<>();
map.put("userId", principal.getId());
map.put("provider", provider.toString());
confirmationEmail.setData(new ObjectMapper().writeValueAsString(map));
} catch (JsonProcessingException e) {
logger.error(e.getMessage(), e);
}
confirmationEmail.setIsConfirmed(false);
confirmationEmail.setToken(UUID.randomUUID());
confirmationEmail = loginConfirmationEmailDao.createOrUpdate(confirmationEmail);
sentMergeConfirmationEmail(confirmationEmail, mailService, principal.getName());
}
@Override
public void createUnlinkConfirmationEmail(EmailConfirmationDao loginConfirmationEmailDao, MailService mailService,
String email, UUID userId, Principal principal, Integer provider) {
EmailConfirmation confirmationEmail = new EmailConfirmation();
confirmationEmail.setEmail(principal.getEmail());
confirmationEmail.setExpiresAt(Date
.from(new Date()
.toInstant()
.plusSeconds(Long.parseLong(this.environment.getProperty("conf_email.expiration_time_seconds")))
)
);
confirmationEmail.setUserId(userId);
try {
Map<String, Object> map = new HashMap<>();
map.put("email", email);
map.put("provider", provider.toString());
confirmationEmail.setData(new ObjectMapper().writeValueAsString(map));
} catch (JsonProcessingException e) {
logger.error(e.getMessage(), e);
}
confirmationEmail.setIsConfirmed(false);
confirmationEmail.setToken(UUID.randomUUID());
confirmationEmail = loginConfirmationEmailDao.createOrUpdate(confirmationEmail);
sentUnlinkConfirmationEmail(confirmationEmail, mailService);
}
}

View File

@ -1,25 +0,0 @@
package eu.old.eudat.logic.services.utilities;
import eu.old.eudat.data.dao.entities.DMPDao;
import eu.old.eudat.data.dao.entities.InvitationDao;
import eu.old.eudat.data.entities.DMP;
import eu.old.eudat.data.entities.Invitation;
import eu.eudat.service.mail.MailService;
import eu.old.eudat.data.entities.UserDMP;
import eu.old.eudat.data.entities.UserInfo;
import jakarta.mail.MessagingException;
import java.util.List;
import java.util.concurrent.CompletableFuture;
public interface InvitationService {
void assignToDmp(DMPDao dmpDao, List<UserDMP> users, DMP dmp);
void assignToDmp(DMPDao dmpDao, UserDMP user, DMP dmp);
void createInvitations(InvitationDao invitationDao, MailService mailService, List<UserInfo> users, DMP dmp, Integer role, UserInfo creator) throws MessagingException;
CompletableFuture sendInvitationAsync(DMP dmp, Invitation invitation, String recipient, MailService mailService, Integer role) throws MessagingException;
}

View File

@ -1,109 +0,0 @@
package eu.old.eudat.logic.services.utilities;
import eu.old.eudat.data.dao.entities.DMPDao;
import eu.old.eudat.data.dao.entities.InvitationDao;
import eu.old.eudat.data.entities.DMP;
import eu.old.eudat.data.entities.Invitation;
import eu.old.eudat.data.entities.UserDMP;
import eu.old.eudat.data.entities.UserInfo;
import eu.old.eudat.models.data.invitation.Properties;
import eu.eudat.service.mail.MailService;
import eu.eudat.service.mail.SimpleMail;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import jakarta.mail.MessagingException;
import jakarta.xml.bind.JAXBContext;
import jakarta.xml.bind.Marshaller;
import java.io.StringWriter;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
@Service("invitationService")
public class InvitationServiceImpl implements InvitationService {
private static final Logger logger = LoggerFactory.getLogger(InvitationServiceImpl.class);
private Environment environment;
@Autowired
public InvitationServiceImpl(Environment environment) {
this.environment = environment;
}
@Override
public void assignToDmp(DMPDao dmpDao, List<UserDMP> users, DMP dmp) {
for (UserDMP user : users) {
dmp.getUsers().add(user);
}
dmpDao.createOrUpdate(dmp);
}
@Override
public void assignToDmp(DMPDao dmpDao, UserDMP user, DMP dmp) {
if (!dmp.getUsers().stream().map(x -> x.getUser().getId()).collect(Collectors.toList()).contains(user.getId())) {
dmp.getUsers().add(user);
dmpDao.createOrUpdate(dmp);
}
}
@Override
public void createInvitations(InvitationDao invitationDao, MailService mailService, List<UserInfo> users, DMP dmp, Integer role, UserInfo creator) throws MessagingException {
for (UserInfo userInfo : users) {
Invitation invitation = new Invitation();
invitation.setDmp(dmp);
invitation.setInvitationEmail(userInfo.getEmail());
invitation.setUser(creator);
invitation.setToken(UUID.randomUUID());
invitation.setAcceptedInvitation(false);
Properties properties = new Properties();
properties.setRole(role);
try {
JAXBContext context = JAXBContext.newInstance(Properties.class);
Marshaller marshaller = context.createMarshaller();
StringWriter propertyWriter = new StringWriter();
marshaller.marshal(properties, propertyWriter);
invitation.setProperties(propertyWriter.toString());
}catch (Exception e) {
logger.error(e.getMessage(), e);
}
invitationDao.createOrUpdate(invitation);
sendInvitationAsync(dmp, invitation, userInfo.getName(), mailService, role);
}
}
@Override
public CompletableFuture sendInvitationAsync(DMP dmp, Invitation invitation, String recipient, MailService mailService, Integer role) {
return CompletableFuture.runAsync(() -> {
SimpleMail mail = new SimpleMail();
mail.setSubject(createSubject(dmp, mailService.getMailTemplateSubject()));
mail.setContent(createContent(invitation.getId(), dmp, recipient, mailService.getMailTemplateContent(this.environment.getProperty("email.invite")), role));
mail.setTo(invitation.getInvitationEmail());
try {
mailService.sendSimpleMail(mail);
} catch (Exception ex) {
logger.error(ex.getMessage(), ex);
}
});
}
private String createSubject(DMP dmp, String templateSubject) {
String subject = templateSubject.replace("{dmpname}", dmp.getLabel());
return subject;
}
private String createContent(UUID invitationID, DMP dmp, String recipient, String templateContent, Integer role) {
String content = templateContent.replace("{dmpname}", dmp.getLabel());
content = content.replace("{invitationID}", invitationID.toString());
content = content.replace("{recipient}", recipient);
content = content.replace("{host}", this.environment.getProperty("dmp.domain"));
content = content.replace("{dmprole}", UserDMP.UserDMPRoles.fromInteger(role).name());
return content;
}
}

View File

@ -1,15 +0,0 @@
package eu.old.eudat.logic.services.utilities;
import eu.eudat.service.mail.MailService;
/**
* Created by ikalyvas on 3/1/2018.
*/
public interface UtilitiesService {
InvitationService getInvitationService();
MailService getMailService();
ConfirmationEmailService getConfirmationEmailService();
}

View File

@ -1,38 +0,0 @@
package eu.old.eudat.logic.services.utilities;
import eu.eudat.service.mail.MailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* Created by ikalyvas on 3/1/2018.
*/
@Service("utilitiesService")
public class UtilitiesServiceImpl implements UtilitiesService {
private InvitationService invitationService;
private MailService mailService;
private ConfirmationEmailService confirmationEmailService;
@Autowired
public UtilitiesServiceImpl(InvitationService invitationService, MailService mailService, ConfirmationEmailService confirmationEmailService) {
this.invitationService = invitationService;
this.mailService = mailService;
this.confirmationEmailService = confirmationEmailService;
}
@Override
public ConfirmationEmailService getConfirmationEmailService() {
return confirmationEmailService;
}
@Override
public InvitationService getInvitationService() {
return invitationService;
}
@Override
public MailService getMailService() {
return mailService;
}
}

View File

@ -1,57 +0,0 @@
package eu.old.eudat.logic.utilities.schedule.notification;
import eu.old.eudat.data.entities.Notification;
import eu.old.eudat.data.enumeration.notification.ActiveStatus;
import eu.old.eudat.data.enumeration.notification.NotifyState;
import eu.old.eudat.logic.managers.NotificationManager;
import eu.old.eudat.logic.services.ApiContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import jakarta.transaction.Transactional;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
@Component
public class NotificationScheduleJob {
private static final Logger logger = LoggerFactory.getLogger(NotificationScheduleJob.class);
private ApiContext apiContext;
private NotificationManager notificationManager;
@Autowired
public NotificationScheduleJob(ApiContext apiContext, NotificationManager notificationManager) {
this.apiContext = apiContext;
this.notificationManager = notificationManager;
}
@Transactional
@Scheduled(fixedRateString = "${notification.rateInterval}")
public void sendNotifications() {
List<CompletableFuture<Notification>> futures = new LinkedList<>();
this.apiContext.getOperationsContext().getDatabaseRepository().getNotificationDao().asQueryable().where(((builder, root) ->
builder.and(
builder.or(
builder.equal(root.get("notifyState"), NotifyState.PENDING), builder.equal(root.get("notifyState"), NotifyState.ERROR))
, builder.equal(root.get("isActive"), ActiveStatus.ACTIVE)))).toListAsync().thenApplyAsync((notifications) -> {
if (!notifications.isEmpty()) {
notifications.forEach(notification -> {
try {
this.notificationManager.sendNotification(notification);
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
});
}
return notifications;
}).thenApplyAsync((notifications) -> {
notifications.forEach((notification) -> futures.add(this.apiContext.getOperationsContext().getDatabaseRepository().getNotificationDao().createOrUpdateAsync(notification)));
return futures;
}).join();
}
}

View File

@ -48,7 +48,7 @@ public class DmpUserMigrationService {
DmpUserEntity data = new DmpUserEntity();
data.setId(item.getId());
data.setDmp(item.getDmp().getId());
data.setDmpId(item.getDmp().getId());
data.setUserId(item.getUser().getId());
data.setRole(DmpUserRole.of(item.getRole().shortValue()));
data.setCreatedAt(item.getDmp().getCreated() != null ? item.getDmp().getCreated().toInstant() : Instant.now());