old code cleanup

This commit is contained in:
Efstratios Giannopoulos 2024-01-15 14:16:20 +02:00
parent 4da8c2a6a9
commit 9b079e4d4d
33 changed files with 25 additions and 1922 deletions

View File

@ -1,100 +0,0 @@
package eu.eudat.data.old;
import eu.eudat.data.converters.DateToUTCConverter;
import eu.eudat.data.old.queryableentity.DataEntity;
import jakarta.persistence.*;
import java.util.Date;
import java.util.List;
import java.util.UUID;
@Entity
@Table(name = "\"EmailConfirmation\"")
public class EmailConfirmation implements DataEntity<EmailConfirmation, UUID> {
@Id
@GeneratedValue
@Column(name = "\"ID\"", updatable = false, nullable = false)
private UUID id;
@Column(name = "\"email\"", nullable = false)
private String email;
@Column(name = "\"isConfirmed\"", nullable = false)
private boolean isConfirmed;
@Column(name = "\"token\"", updatable = false, nullable = false, columnDefinition = "BINARY(16)")
private UUID token;
@Column(name = "\"userId\"", nullable = false)
private UUID userId;
@Column(name = "\"data\"")
private String data;
@Column(name = "\"expiresAt\"", nullable = false)
@Convert(converter = DateToUTCConverter.class)
private Date expiresAt;
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public boolean getIsConfirmed() {
return isConfirmed;
}
public void setIsConfirmed(boolean confirmed) {
isConfirmed = confirmed;
}
public UUID getToken() {
return token;
}
public void setToken(UUID token) {
this.token = token;
}
public UUID getUserId() {
return userId;
}
public void setUserId(UUID userId) {
this.userId = userId;
}
public Date getExpiresAt() {
return expiresAt;
}
public void setExpiresAt(Date expiresAt) {
this.expiresAt = expiresAt;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
@Override
public void update(EmailConfirmation entity) {
}
@Override
public UUID getKeys() {
return null;
}
@Override
public EmailConfirmation buildFromTuple(List<Tuple> tuple, List<String> fields, String base) {
return null;
}
}

View File

@ -1,113 +0,0 @@
package eu.eudat.data.old;
import eu.eudat.data.UserEntity;
import eu.eudat.data.old.helpers.EntityBinder;
import eu.eudat.data.old.queryableentity.DataEntity;
import jakarta.persistence.*;
import java.util.List;
import java.util.UUID;
@Entity
@Table(name = "\"Invitation\"")
public class Invitation implements DataEntity<Invitation, UUID> {
@Id
@GeneratedValue
@Column(name = "\"Id\"", updatable = false, nullable = false)
private UUID id;
@Column(name = "\"InvitationEmail\"", nullable = false)
private String invitationEmail;
@OneToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "\"CreationUser\"", nullable = false)
private UserEntity user;
// @OneToOne(fetch = FetchType.EAGER)
// @JoinColumn(name = "\"Dmp\"", nullable = false)
// private DMP dmp;
@Column(name = "\"Token\"", updatable = false, nullable = false, columnDefinition = "BINARY(16)")
private UUID token;
@Column(name = "\"AcceptedInvitation\"", nullable = false)
private boolean acceptedInvitation;
@Column(name = "\"Properties\"", nullable = true)
private String properties;
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public String getInvitationEmail() {
return invitationEmail;
}
public void setInvitationEmail(String invitationEmail) {
this.invitationEmail = invitationEmail;
}
public UserEntity getUser() {
return user;
}
public void setUser(UserEntity user) {
this.user = user;
}
// public DMP getDmp() {
// return dmp;
// }
//
// public void setDmp(DMP dmp) {
// this.dmp = dmp;
// }
public UUID getToken() {
return token;
}
public void setToken(UUID token) {
this.token = token;
}
public String getProperties() {
return properties;
}
public void setProperties(String properties) {
this.properties = properties;
}
public boolean getAcceptedInvitation() {
return acceptedInvitation;
}
public void setAcceptedInvitation(boolean acceptedInvitation) {
this.acceptedInvitation = acceptedInvitation;
}
@Override
public void update(Invitation entity) {
}
@Override
public UUID getKeys() {
return this.id;
}
@Override
public Invitation buildFromTuple(List<Tuple> tuple, List<String> fields, String base) {
String currentBase = base.isEmpty() ? "" : base + ".";
if (fields.contains(currentBase + "id")) this.id = EntityBinder.fromTuple(tuple, currentBase + "id");
return this;
}
}

View File

@ -1,6 +0,0 @@
package eu.eudat.data.dao.criteria;
import eu.eudat.data.old.EmailConfirmation;
public class EmailConfirmationCriteria extends Criteria<EmailConfirmation>{
}

View File

@ -1,6 +0,0 @@
package eu.eudat.data.dao.criteria;
import eu.eudat.data.old.Invitation;
public class InvitationCriteria extends Criteria<Invitation> {
}

View File

@ -1,13 +0,0 @@
package eu.eudat.data.dao.entities;
import eu.eudat.data.dao.DatabaseAccessLayer;
import eu.eudat.data.dao.criteria.EmailConfirmationCriteria;
import eu.eudat.data.old.EmailConfirmation;
import eu.eudat.queryable.QueryableList;
import java.util.UUID;
public interface EmailConfirmationDao extends DatabaseAccessLayer<EmailConfirmation, UUID> {
QueryableList<EmailConfirmation> getWithCriteria(EmailConfirmationCriteria criteria);
}

View File

@ -1,57 +0,0 @@
package eu.eudat.data.dao.entities;
import eu.eudat.data.dao.DatabaseAccess;
import eu.eudat.data.dao.criteria.EmailConfirmationCriteria;
import eu.eudat.data.dao.databaselayer.service.DatabaseService;
import eu.eudat.data.old.EmailConfirmation;
import eu.eudat.queryable.QueryableList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.management.InvalidApplicationException;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
@Service("LoginConfirmationEmailDao")
public class EmailConfirmationDaoImpl extends DatabaseAccess<EmailConfirmation> implements EmailConfirmationDao {
@Autowired
public EmailConfirmationDaoImpl(DatabaseService<EmailConfirmation> databaseService) {
super(databaseService);
}
@Override
public QueryableList<EmailConfirmation> getWithCriteria(EmailConfirmationCriteria criteria) {
return null;
}
@Override
public EmailConfirmation createOrUpdate(EmailConfirmation item) {
return this.getDatabaseService().createOrUpdate(item, EmailConfirmation.class);
}
@Override
public CompletableFuture<EmailConfirmation> createOrUpdateAsync(EmailConfirmation item) {
return null;
}
@Override
public EmailConfirmation find(UUID id) throws InvalidApplicationException {
return this.getDatabaseService().getQueryable(EmailConfirmation.class).where((builder, root) -> builder.equal(root.get("id"), id)).getSingle();
}
@Override
public EmailConfirmation find(UUID id, String hint) {
throw new UnsupportedOperationException();
}
@Override
public void delete(EmailConfirmation item) {
throw new UnsupportedOperationException();
}
@Override
public QueryableList<EmailConfirmation> asQueryable() {
return this.getDatabaseService().getQueryable(EmailConfirmation.class);
}
}

View File

@ -1,15 +0,0 @@
package eu.eudat.data.dao.entities;
import eu.eudat.data.dao.DatabaseAccessLayer;
import eu.eudat.data.dao.criteria.InvitationCriteria;
import eu.eudat.data.old.Invitation;
import eu.eudat.queryable.QueryableList;
import java.util.UUID;
public interface InvitationDao extends DatabaseAccessLayer<Invitation, UUID> {
QueryableList<Invitation> getWithCriteria(InvitationCriteria criteria);
}

View File

@ -1,60 +0,0 @@
package eu.eudat.data.dao.entities;
import eu.eudat.data.dao.DatabaseAccess;
import eu.eudat.data.dao.criteria.InvitationCriteria;
import eu.eudat.data.dao.databaselayer.service.DatabaseService;
import eu.eudat.data.old.Invitation;
import eu.eudat.queryable.QueryableList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import javax.management.InvalidApplicationException;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
@Service("invitationDao")
public class InvitationDaoImpl extends DatabaseAccess<Invitation> implements InvitationDao {
@Autowired
public InvitationDaoImpl(DatabaseService<Invitation> databaseService) {
super(databaseService);
}
@Override
public QueryableList<Invitation> getWithCriteria(InvitationCriteria criteria) {
return null;
}
@Override
public Invitation createOrUpdate(Invitation item) {
return this.getDatabaseService().createOrUpdate(item, Invitation.class);
}
@Override
public Invitation find(UUID id) throws InvalidApplicationException {
return this.getDatabaseService().getQueryable(Invitation.class).where((builder, root) -> builder.equal(root.get("id"), id)).getSingle();
}
@Override
public void delete(Invitation item) {
this.getDatabaseService().delete(item);
}
@Override
public QueryableList<Invitation> asQueryable() {
return this.getDatabaseService().getQueryable(Invitation.class);
}
@Async
@Override
public CompletableFuture<Invitation> createOrUpdateAsync(Invitation item) {
return CompletableFuture.supplyAsync(() -> this.createOrUpdate(item));
}
@Override
public Invitation find(UUID id, String hint) {
throw new UnsupportedOperationException();
}
}

View File

@ -9,7 +9,6 @@ import eu.eudat.exceptions.security.UnauthorisedException;
import eu.eudat.logic.managers.DatasetManager;
import eu.eudat.logic.managers.DatasetWizardManager;
import eu.eudat.logic.managers.FileManager;
import eu.eudat.logic.managers.UserManager;
import eu.eudat.logic.proxy.config.configloaders.ConfigLoader;
import eu.eudat.logic.services.ApiContext;
import eu.eudat.logic.services.forms.VisibilityRuleService;
@ -56,20 +55,18 @@ public class Datasets extends BaseController {
private Environment environment;
private DatasetManager datasetManager;
private ConfigLoader configLoader;
private UserManager userManager;
private FileManager fileManager;
private final AuthorizationService authorizationService;
private final UserScope userScope;
private final QueryFactory queryFactory;
@Autowired
public Datasets(ApiContext apiContext, Environment environment, DatasetManager datasetManager, ConfigLoader configLoader, UserManager userManager,
public Datasets(ApiContext apiContext, Environment environment, DatasetManager datasetManager, ConfigLoader configLoader,
FileManager fileManager, AuthorizationService authorizationService, UserScope userScope, QueryFactory queryFactory) {
super(apiContext);
this.environment = environment;
this.datasetManager = datasetManager;
this.configLoader = configLoader;
this.userManager = userManager;
this.fileManager = fileManager;
this.authorizationService = authorizationService;
this.userScope = userScope;

View File

@ -1,66 +0,0 @@
package eu.eudat.controllers;
import eu.eudat.authorization.Permission;
import eu.eudat.exceptions.emailconfirmation.HasConfirmedEmailException;
import eu.eudat.exceptions.emailconfirmation.TokenExpiredException;
import eu.eudat.logic.managers.EmailConfirmationManager;
import eu.eudat.models.data.helpers.responses.ResponseItem;
import eu.eudat.types.ApiMessageCode;
import gr.cite.commons.web.authz.service.AuthorizationService;
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;
import javax.management.InvalidApplicationException;
@RestController
@CrossOrigin
@RequestMapping(value = "/api/emailConfirmation/")
public class EmailConfirmation {
private EmailConfirmationManager emailConfirmationManager;
private final AuthorizationService authorizationService;
@Autowired
public EmailConfirmation(EmailConfirmationManager emailConfirmationManager, AuthorizationService authorizationService) {
this.emailConfirmationManager = emailConfirmationManager;
this.authorizationService = authorizationService;
}
@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 | InvalidApplicationException 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) {
this.authorizationService.authorizeForce(Permission.AuthenticatedRole);
try {
this.emailConfirmationManager.sendConfirmationEmail(email);
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,65 +0,0 @@
package eu.eudat.controllers;
import eu.eudat.authorization.Permission;
import eu.eudat.exceptions.emailconfirmation.HasConfirmedEmailException;
import eu.eudat.exceptions.emailconfirmation.TokenExpiredException;
import eu.eudat.logic.managers.MergeEmailConfirmationManager;
import eu.eudat.models.data.helpers.responses.ResponseItem;
import eu.eudat.types.ApiMessageCode;
import gr.cite.commons.web.authz.service.AuthorizationService;
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;
import javax.management.InvalidApplicationException;
@RestController
@CrossOrigin
@RequestMapping(value = "api/emailMergeConfirmation")
public class EmailMergeConfirmation {
private MergeEmailConfirmationManager emailConfirmationManager;
private final AuthorizationService authorizationService;
@Autowired
public EmailMergeConfirmation(MergeEmailConfirmationManager emailConfirmationManager, AuthorizationService authorizationService) {
this.emailConfirmationManager = emailConfirmationManager;
this.authorizationService = authorizationService;
}
@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 | InvalidApplicationException 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) {
// this.authorizationService.authorizeForce(Permission.AuthenticatedRole);
// try {
// this.emailConfirmationManager.sendConfirmationEmail(requestModel.getEmail(), 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,62 +0,0 @@
package eu.eudat.controllers;
import eu.eudat.authorization.Permission;
import eu.eudat.exceptions.emailconfirmation.HasConfirmedEmailException;
import eu.eudat.exceptions.emailconfirmation.TokenExpiredException;
import eu.eudat.logic.managers.UnlinkEmailConfirmationManager;
import eu.eudat.models.data.helpers.responses.ResponseItem;
import eu.eudat.types.ApiMessageCode;
import gr.cite.commons.web.authz.service.AuthorizationService;
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;
import javax.management.InvalidApplicationException;
@RestController
@CrossOrigin
@RequestMapping(value = "api/emailUnlinkConfirmation")
public class EmailUnlinkConfirmation {
private UnlinkEmailConfirmationManager unlinkEmailConfirmationManager;
private final AuthorizationService authorizationService;
@Autowired
public EmailUnlinkConfirmation(UnlinkEmailConfirmationManager unlinkEmailConfirmationManager, AuthorizationService authorizationService){
this.unlinkEmailConfirmationManager = unlinkEmailConfirmationManager;
this.authorizationService = authorizationService;
}
@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 | InvalidApplicationException 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) {
// this.authorizationService.authorizeForce(Permission.AuthenticatedRole);
// try {
// this.unlinkEmailConfirmationManager.sendConfirmationEmail(requestModel.getEmail(), 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,68 +0,0 @@
package eu.eudat.controllers;
import eu.eudat.authorization.Permission;
import eu.eudat.logic.managers.InvitationsManager;
import eu.eudat.logic.services.ApiContext;
import eu.eudat.models.data.helpers.responses.ResponseItem;
import eu.eudat.models.data.invitation.Invitation;
import eu.eudat.types.ApiMessageCode;
import gr.cite.commons.web.authz.service.AuthorizationService;
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 javax.management.InvalidApplicationException;
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;
private final AuthorizationService authorizationService;
@Autowired
public UserInvitationController(ApiContext apiContext, InvitationsManager invitationsManager, AuthorizationService authorizationService) {
super(apiContext);
this.invitationsManager = invitationsManager;
this.authorizationService = authorizationService;
}
@Transactional
@RequestMapping(method = RequestMethod.POST, value = {"/users"}, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<Invitation>> users(@RequestBody Invitation invitation) throws Exception {
this.authorizationService.authorizeForce(Permission.AuthenticatedRole);
this.invitationsManager.inviteUsers(invitation);
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) throws JAXBException, IOException, InvalidApplicationException {
this.authorizationService.authorizeForce(Permission.AuthenticatedRole);
UUID dmpId = invitationsManager.assignUserAcceptedInvitation(invitationID);
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() throws IllegalAccessException, InstantiationException {
// ResponseEntity<ResponseItem<List<UserInfoInvitationModel>>> getUsers(@RequestBody UserInfoRequestItem userInfoRequestItem) throws IllegalAccessException, InstantiationException, InvalidApplicationException {
//// List<UserInfoInvitationModel> users = invitationsManager.getUsers(principal);
// this.authorizationService.authorizeForce(Permission.AuthenticatedRole);
//
// List<UserInfoInvitationModel> users = invitationsManager.getUsersWithCriteria(userInfoRequestItem);
// return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List<UserInfoInvitationModel>>().status(ApiMessageCode.SUCCESS_MESSAGE).payload(users));
// }
}

View File

@ -102,7 +102,6 @@ public class DataManagementPlanManager {
private DatabaseRepository databaseRepository;
private Environment environment;
private RDAManager rdaManager;
private UserManager userManager;
private final MetricsManager metricsManager;
private final ConfigLoader configLoader;
private DepositService repositoriesDeposit;
@ -113,7 +112,7 @@ public class DataManagementPlanManager {
private final XmlHandlingService xmlHandlingService;
@Autowired
public DataManagementPlanManager(XmlHandlingService xmlHandlingService, ApiContext apiContext, DatasetManager datasetManager, Environment environment, RDAManager rdaManager, UserManager userManager,
public DataManagementPlanManager(XmlHandlingService xmlHandlingService, ApiContext apiContext, DatasetManager datasetManager, Environment environment, RDAManager rdaManager,
MetricsManager metricsManager, ConfigLoader configLoader, DepositService repositoriesDeposit, UserScope userScope, AuthorizationService authorizationService, DmpBlueprintService dmpBlueprintService, QueryFactory queryFactory) {
this.xmlHandlingService = xmlHandlingService;
this.apiContext = apiContext;
@ -121,7 +120,6 @@ public class DataManagementPlanManager {
this.databaseRepository = apiContext.getOperationsContext().getDatabaseRepository();
this.environment = environment;
this.rdaManager = rdaManager;
this.userManager = userManager;
this.metricsManager = metricsManager;
this.configLoader = configLoader;
this.userScope = userScope;

View File

@ -104,7 +104,6 @@ public class DatasetManager {
private DatabaseRepository databaseRepository;
// private DatasetRepository datasetRepository;
private BuilderFactory builderFactory;
private UserManager userManager;
private ConfigLoader configLoader;
private Environment environment;
private final MetricsManager metricsManager;
@ -114,13 +113,12 @@ public class DatasetManager {
private final QueryFactory queryFactory;
@Autowired
public DatasetManager(ApiContext apiContext, UserManager userManager, ConfigLoader configLoader, Environment environment, MetricsManager metricsManager,
public DatasetManager(ApiContext apiContext, ConfigLoader configLoader, Environment environment, MetricsManager metricsManager,
FileManager fileManager, UserScope userScope, AuthorizationService authorizationService, QueryFactory queryFactory) {
this.apiContext = apiContext;
this.databaseRepository = apiContext.getOperationsContext().getDatabaseRepository();
// this.datasetRepository = apiContext.getOperationsContext().getElasticRepository().getDatasetRepository();
this.builderFactory = apiContext.getOperationsContext().getBuilderFactory();
this.userManager = userManager;
this.configLoader = configLoader;
this.environment = environment;
this.metricsManager = metricsManager;
@ -400,15 +398,15 @@ public class DatasetManager {
}
public PagedDatasetProfile getPagedProfile(DatasetWizardModel dataset, DescriptionEntity descriptionEntityEntity) {
eu.eudat.models.data.user.composite.DatasetProfile datasetprofile = userManager.generateDatasetProfileModel(this.queryFactory.query(DescriptionTemplateQuery.class).ids(descriptionEntityEntity.getDescriptionTemplateId()).first());
datasetprofile.setStatus(dataset.getStatus().getValue());
if (descriptionEntityEntity.getProperties() != null) {
JSONObject jObject = new JSONObject(descriptionEntityEntity.getProperties());
Map<String, Object> properties = jObject.toMap();
datasetprofile.fromJsonObject(properties);
}
// eu.eudat.models.data.user.composite.DatasetProfile datasetprofile = userManager.generateDatasetProfileModel(this.queryFactory.query(DescriptionTemplateQuery.class).ids(descriptionEntityEntity.getDescriptionTemplateId()).first());
// datasetprofile.setStatus(dataset.getStatus().getValue());
// if (descriptionEntityEntity.getProperties() != null) {
// JSONObject jObject = new JSONObject(descriptionEntityEntity.getProperties());
// Map<String, Object> properties = jObject.toMap();
// datasetprofile.fromJsonObject(properties);
// }
PagedDatasetProfile pagedDatasetProfile = new PagedDatasetProfile();
pagedDatasetProfile.buildPagedDatasetProfile(datasetprofile);
// pagedDatasetProfile.buildPagedDatasetProfile(datasetprofile);
return pagedDatasetProfile;
}
@ -1069,18 +1067,18 @@ public class DatasetManager {
}
public PagedDatasetProfile getLatestDatasetProfile(DescriptionEntity descriptionEntityEntity, DescriptionTemplateEntity profile) {
eu.eudat.models.data.user.composite.DatasetProfile datasetprofile = userManager.generateDatasetProfileModel(profile);
datasetprofile.setStatus(descriptionEntityEntity.getStatus().getValue());
if (descriptionEntityEntity.getProperties() != null) {
JSONObject jobject = new JSONObject(descriptionEntityEntity.getProperties());
Map<String, Object> properties = jobject.toMap();
datasetprofile.fromJsonObject(properties);
}
PagedDatasetProfile pagedDatasetProfile = new PagedDatasetProfile();
pagedDatasetProfile.buildPagedDatasetProfile(datasetprofile);
return pagedDatasetProfile;
}
// public PagedDatasetProfile getLatestDatasetProfile(DescriptionEntity descriptionEntityEntity, DescriptionTemplateEntity profile) {
// eu.eudat.models.data.user.composite.DatasetProfile datasetprofile = userManager.generateDatasetProfileModel(profile);
// datasetprofile.setStatus(descriptionEntityEntity.getStatus().getValue());
// if (descriptionEntityEntity.getProperties() != null) {
// JSONObject jobject = new JSONObject(descriptionEntityEntity.getProperties());
// Map<String, Object> properties = jobject.toMap();
// datasetprofile.fromJsonObject(properties);
// }
// PagedDatasetProfile pagedDatasetProfile = new PagedDatasetProfile();
// pagedDatasetProfile.buildPagedDatasetProfile(datasetprofile);
// return pagedDatasetProfile;
// }
public DataTableData<DatasetProfileListingModel> getDatasetProfilesUsedByDatasets(DatasetProfileTableRequestItem datasetProfileTableRequestItem) throws InvalidApplicationException {
datasetProfileTableRequestItem.getCriteria().setFilter(DatasetProfileCriteria.DatasetProfileFilter.Datasets.getValue());

View File

@ -1,86 +0,0 @@
package eu.eudat.logic.managers;
import eu.eudat.commons.scope.user.UserScope;
import eu.eudat.data.old.EmailConfirmation;
import eu.eudat.data.UserEntity;
import eu.eudat.exceptions.emailconfirmation.HasConfirmedEmailException;
import eu.eudat.exceptions.emailconfirmation.TokenExpiredException;
import eu.eudat.logic.services.ApiContext;
import eu.eudat.logic.services.operations.DatabaseRepository;
import eu.eudat.query.UserQuery;
import gr.cite.tools.data.query.QueryFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.management.InvalidApplicationException;
import java.util.Date;
import java.util.UUID;
@Component
public class EmailConfirmationManager {
private ApiContext apiContext;
private DatabaseRepository databaseRepository;
private final UserScope userScope;
private final QueryFactory queryFactory;
@Autowired
public EmailConfirmationManager(ApiContext apiContext, UserScope userScope, QueryFactory queryFactory) {
this.apiContext = apiContext;
this.databaseRepository = apiContext.getOperationsContext().getDatabaseRepository();
this.userScope = userScope;
this.queryFactory = queryFactory;
}
public void confirmEmail(String token) throws TokenExpiredException, HasConfirmedEmailException, InvalidApplicationException {
EmailConfirmation loginConfirmationEmail = apiContext.getOperationsContext()
.getDatabaseRepository().getLoginConfirmationEmailDao().asQueryable()
.where((builder, root) -> builder.equal(root.get("token"), UUID.fromString(token))).getSingle();
UserEntity user = this.queryFactory.query(UserQuery.class).ids(loginConfirmationEmail.getUserId()).first();
// if (user.getEmail() != null) //TODO
// throw new HasConfirmedEmailException("User already has confirmed his Email.");
if (loginConfirmationEmail.getExpiresAt().compareTo(new Date()) < 0)
throw new TokenExpiredException("Token has expired.");
loginConfirmationEmail.setIsConfirmed(true);
// Checks if mail is used by another user. If it is, merges the new the old.
Long existingUsers = this.queryFactory.query(UserQuery.class).emails(loginConfirmationEmail.getEmail()).count();
if (existingUsers > 0) {
// UserCredentialEntity credential = databaseRepository.getCredentialDao().asQueryable().where((builder, root) -> builder.equal(root.get("userId"), user.getId())).getSingle();
// credential.setEmail(loginConfirmationEmail.getEmail()); //TODO
// databaseRepository.getCredentialDao().createOrUpdate(credential);
UserEntity oldUser = this.queryFactory.query(UserQuery.class).emails(loginConfirmationEmail.getEmail()).first();
mergeNewUserToOld(user, oldUser);
// expireUserToken(user); //TODO: Authn
databaseRepository.getLoginConfirmationEmailDao().createOrUpdate(loginConfirmationEmail);
return;
}
// user.setEmail(loginConfirmationEmail.getEmail()); //TODO
// databaseRepository.getUserInfoDao().createOrUpdate(user);
// UserCredentialEntity credential = databaseRepository.getCredentialDao().asQueryable()
// .where((builder, root) -> builder.equal(root.get("userId"), user.getId())).getSingle();
// if(credential.getEmail() == null){//TODO
// credential.setEmail(user.getEmail());
// databaseRepository.getCredentialDao().createOrUpdate(credential);
// }
databaseRepository.getLoginConfirmationEmailDao().createOrUpdate(loginConfirmationEmail);
}
public void sendConfirmationEmail(String email) throws HasConfirmedEmailException, InvalidApplicationException {
UserEntity user = this.queryFactory.query(UserQuery.class).ids(this.userScope.getUserId()).first();
// if (user.getEmail() != null) //TODO
// throw new HasConfirmedEmailException("User already has confirmed his Email.");
apiContext.getUtilitiesService().getConfirmationEmailService().sentConfirmationEmail(databaseRepository.getLoginConfirmationEmailDao(), email, user);
}
private void mergeNewUserToOld(UserEntity newUser, UserEntity oldUser) throws InvalidApplicationException {
// UserCredentialEntity credential = databaseRepository.getCredentialDao().asQueryable().where((builder, root) -> builder.equal(root.get("userId"), newUser.getId())).getSingle();
// credential.setUserId(oldUser.getId());
// databaseRepository.getCredentialDao().createOrUpdate(credential);
}
}

View File

@ -1,177 +0,0 @@
package eu.eudat.logic.managers;
import eu.eudat.commons.enums.DmpUserRole;
import eu.eudat.commons.scope.user.UserScope;
import eu.eudat.data.DmpEntity;
import eu.eudat.data.DmpUserEntity;
import eu.eudat.data.UserEntity;
import eu.eudat.exceptions.security.UnauthorisedException;
import eu.eudat.logic.services.ApiContext;
import eu.eudat.model.User;
import eu.eudat.models.data.invitation.Invitation;
import eu.eudat.query.DmpQuery;
import eu.eudat.query.UserQuery;
import gr.cite.tools.data.query.QueryFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import jakarta.xml.bind.JAXBException;
import javax.management.InvalidApplicationException;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;
@Component
public class InvitationsManager {
private ApiContext apiContext;
private DataManagementPlanManager dataManagementPlanManager;
private final UserScope userScope;
private final QueryFactory queryFactory;
@Autowired
public InvitationsManager(ApiContext apiContext, DataManagementPlanManager dataManagementPlanManager, UserScope userScope, QueryFactory queryFactory) {
this.apiContext = apiContext;
this.dataManagementPlanManager = dataManagementPlanManager;
this.userScope = userScope;
this.queryFactory = queryFactory;
}
public void inviteUsers(Invitation invitation) throws Exception {
UserEntity principalUser = new UserEntity();
principalUser.setId(this.userScope.getUserIdSafe());
invitation.getUsers().stream().filter(item -> item.getId() == null).forEach(item -> {
UserEntity existingUser = null;
// try {
// //TODO: email
// //existingUser = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().asQueryable().where((builder, root) -> builder.equal(root.get("email"), item.getEmail())).getSingleOrDefault();
// } catch (InvalidApplicationException e) {
// throw new RuntimeException(e);
// }
if (existingUser != null) {
item.setId(existingUser.getId());
}
});
List<User> alreadySignedInUsers = invitation.getUsers().stream().filter(item -> item.getId() != null).collect(Collectors.toList());
List<UserEntity> alreadySignedInUsersEntities = new ArrayList<>(); //alreadySignedInUsers.stream().map(User::toDataModel).collect(Collectors.toList());
List<DmpUserEntity> userInfoToUserDmp = new LinkedList<>();
for (UserEntity userInfo : alreadySignedInUsersEntities) {
DmpUserEntity userDMP = new DmpUserEntity();
userDMP.setUserId(userInfo.getId());
userDMP.setRole(DmpUserRole.of(invitation.getRole().shortValue()));
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);
}*/
}
DmpQuery dmpQuery = this.queryFactory.query(DmpQuery.class).ids(invitation.getDataManagementPlan());
if(dmpQuery != null){
// DmpEntity dataManagementPlan = apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().find(invitation.getDataManagementPlan());
DmpEntity dmpEntity = dmpQuery.first();
UserQuery userQuery = this.queryFactory.query(UserQuery.class).ids(invitation.getUsers().stream().map(user -> user.getId()).collect(Collectors.toList()));
if (userQuery != null){
List<UserEntity> userEntities = userQuery.collect();
// apiContext.getUtilitiesService().getInvitationService().createInvitations(apiContext.getOperationsContext().getDatabaseRepository().getInvitationDao(), invitation.getUsers().stream().map(UserInfoInvitationModel::toDataModel).collect(Collectors.toList()), dmpEntity, invitation.getRole(), principalUser);
apiContext.getUtilitiesService().getInvitationService().createInvitations(apiContext.getOperationsContext().getDatabaseRepository().getInvitationDao(), userEntities, dmpEntity, invitation.getRole(), principalUser);
apiContext.getUtilitiesService().getInvitationService().assignToDmp(apiContext.getOperationsContext().getDatabaseRepository().getDmpDao(), userInfoToUserDmp, dmpEntity);
}
}
}
public List<User> getUsers() throws InstantiationException, IllegalAccessException, InvalidApplicationException {
/*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<UserEntity> users = new ArrayList<>();
//TODO
// apiContext.getOperationsContext().getDatabaseRepository().getDmpDao()
// .getAuthenticated(apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().asQueryable()
// .where(((builder, root) -> builder.notEqual(root.get("isActive"), IsActive.Inactive))), this.userScope.getUserId(), Stream.of(0, 1).collect(Collectors.toList()))
// .toList().stream().map(DmpEntity::getUsers).flatMap(Collection::stream).map(DmpUser::getUser)
// .filter(userInfo -> !userInfo.getId().equals(this.userScope.getUserIdSafe())).filter(StreamDistinctBy.distinctByKey(UserInfo::getId)).collect(Collectors.toList());
List<User> userModels = new ArrayList<>(); //users.stream().map(userInfo -> new User().fromDataModel(userInfo)).collect(Collectors.toList());
return userModels;
}
// public List<UserInfoInvitationModel> getUsersWithCriteria(UserInfoRequestItem userInfoRequestItem) throws IllegalAccessException, InstantiationException, InvalidApplicationException {
// //TODO
//// 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()))), this.userScope.getUserId(), Stream.of(0, 1).collect(Collectors.toList()))
//// .toList().stream().map(DMP::getUsers).flatMap(Collection::stream).map(UserDMP::getUser)
//// .filter(userInfo -> !userInfo.getId().equals(this.userScope.getUserIdSafe())).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;
// return new ArrayList<>();
// }
public UUID assignUserAcceptedInvitation(UUID invitationID) throws UnauthorisedException, JAXBException, IOException, InvalidApplicationException {
//TODO
// eu.eudat.data.old.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(Properties.class);
// Unmarshaller unmarshaller = context.createUnmarshaller();
// Properties properties = (Properties) unmarshaller.unmarshal(new StringReader(invitation.getProperties()));
// UserInfo invitedUser = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(this.userScope.getUserId());
// 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); //TODO
// 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);
// }*/
// DmpEntity 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); //TODo
// return datamanagementPlan.getId();
// }
// return invitation.getDmp().getId();
return null;
}
}

View File

@ -1,144 +0,0 @@
package eu.eudat.logic.managers;
import eu.eudat.commons.enums.IsActive;
import eu.eudat.commons.scope.user.UserScope;
import eu.eudat.data.DmpUserEntity;
import eu.eudat.data.old.EmailConfirmation;
import eu.eudat.data.UserEntity;
import eu.eudat.exceptions.emailconfirmation.HasConfirmedEmailException;
import eu.eudat.exceptions.emailconfirmation.TokenExpiredException;
import eu.eudat.logic.services.ApiContext;
import eu.eudat.logic.services.operations.DatabaseRepository;
import eu.eudat.model.UserContactInfo;
import eu.eudat.query.UserContactInfoQuery;
import eu.eudat.query.UserQuery;
import gr.cite.tools.data.query.Ordering;
import gr.cite.tools.data.query.QueryFactory;
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 javax.management.InvalidApplicationException;
import java.util.*;
@Component
public class MergeEmailConfirmationManager {
private static Logger logger = LoggerFactory.getLogger(MergeEmailConfirmationManager.class);
private ApiContext apiContext;
private DatabaseRepository databaseRepository;
// private DmpRepository dmpRepository;
private final UserScope userScope;
private final QueryFactory queryFactory;
@Autowired
public MergeEmailConfirmationManager(ApiContext apiContext, UserScope userScope, QueryFactory queryFactory) {
this.apiContext = apiContext;
this.databaseRepository = apiContext.getOperationsContext().getDatabaseRepository();
// this.dmpRepository = apiContext.getOperationsContext().getElasticRepository().getDmpRepository();
this.userScope = userScope;
this.queryFactory = queryFactory;
}
@Transactional
public String confirmEmail(String token) throws TokenExpiredException, HasConfirmedEmailException, InvalidApplicationException {
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.");
UserEntity userToBeMerged = this.queryFactory.query(UserQuery.class).ids(loginConfirmationEmail.getUserId()).first();
String userToBeMergedEmail = ""; //TODO userToBeMerged.getEmail();
try {
Map<String, Object> map = new ObjectMapper().readValue(loginConfirmationEmail.getData(), HashMap.class);
UUID otherUserId = UUID.fromString((String) map.get("userId"));
UserEntity user = this.queryFactory.query(UserQuery.class).ids(otherUserId).first();
// 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); //TODO: Authn
loginConfirmationEmail.setIsConfirmed(true);
databaseRepository.getLoginConfirmationEmailDao().createOrUpdate(loginConfirmationEmail);
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
return userToBeMergedEmail;
}
public void sendMergeConfirmationEmail(String email, Integer provider) throws HasConfirmedEmailException, InvalidApplicationException {
UserEntity user = this.queryFactory.query(UserQuery.class).ids(this.userScope.getUserId()).first();
UserContactInfoQuery query = this.queryFactory.query(UserContactInfoQuery.class).userIds(user.getId());
query.setOrder(new Ordering().addAscending(UserContactInfo._ordinal));
if (query.first().getValue() != null && !query.first().getValue().equals(email)) {
apiContext.getUtilitiesService().getConfirmationEmailService().sentMergeConfirmationEmail(
databaseRepository.getLoginConfirmationEmailDao(),
email,
user,
provider
);
}
}
@Transactional
private void mergeNewUserToOld(UserEntity newUser, UserEntity oldUser, Integer provider) throws InvalidApplicationException {
// UserCredentialEntity credential = databaseRepository.getCredentialDao().asQueryable().where((builder, root) -> builder.and(builder.equal(root.get("userId"), oldUser.getId()), builder.equal(root.get("provider"), provider))).getSingle();
// credential.setUserId(newUser.getId());
// databaseRepository.getCredentialDao().createOrUpdate(credential);
// List<DmpUserEntity> userDmps = databaseRepository.getUserDmpDao().asQueryable().where((builder, root) -> builder.equal(root.get("user"), oldUser)).toList();
// userDmps.forEach(userDmp -> {
// userDmp.setUserId(newUser.getId());
// databaseRepository.getUserDmpDao().createOrUpdate(userDmp);
// });
//TODO
// 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.setIsActive(IsActive.Inactive);
//TODO oldUser.setEmail(null);
// List<UserCredentialEntity> credentials = databaseRepository.getCredentialDao().asQueryable().where((builder, root) -> builder.equal(root.get("userId"), oldUser.getId())).toList();
// credentials.forEach(cred -> {
// if (cred.getId() != credential.getId()) {
// databaseRepository.getCredentialDao().delete(cred);
// }
// });
// databaseRepository.getUserInfoDao().createOrUpdate(oldUser);
}
}

View File

@ -78,14 +78,12 @@ public class MetricsManager {
}
private final ApiContext apiContext;
private final UserManager userManager;
private final Environment environment;
private final QueryFactory queryFactory;
@Autowired
public MetricsManager(ApiContext apiContext, UserManager userManager, Environment environment, PrometheusMeterRegistry registry, QueryFactory queryFactory) {
public MetricsManager(ApiContext apiContext, Environment environment, PrometheusMeterRegistry registry, QueryFactory queryFactory) {
this.apiContext = apiContext;
this.userManager = userManager;
this.environment = environment;
this.queryFactory = queryFactory;
registry.clear();

View File

@ -1,115 +0,0 @@
package eu.eudat.logic.managers;
import eu.eudat.logic.services.ApiContext;
import gr.cite.tools.data.query.QueryFactory;
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;
@Component
public class NotificationManager {
private static final Logger logger = LoggerFactory.getLogger(NotificationManager.class);
private ApiContext apiContext;
private Environment environment;
private final QueryFactory queryFactory;
@Autowired
public NotificationManager(ApiContext apiContext, Environment environment,
// MailService mailService,
QueryFactory queryFactory) {
this.apiContext = apiContext;
this.environment = environment;
this.queryFactory = queryFactory;
}
// @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);
// UserEntity userInfo = this.queryFactory.query(UserQuery.class).ids(UUID.fromString(data.get("userId"))).first();
// 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, UserEntity 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, UserEntity 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,97 +0,0 @@
package eu.eudat.logic.managers;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import eu.eudat.commons.scope.user.UserScope;
import eu.eudat.data.old.EmailConfirmation;
import eu.eudat.data.UserEntity;
import eu.eudat.exceptions.emailconfirmation.HasConfirmedEmailException;
import eu.eudat.exceptions.emailconfirmation.TokenExpiredException;
import eu.eudat.logic.services.ApiContext;
import eu.eudat.logic.services.operations.DatabaseRepository;
import eu.eudat.model.UserContactInfo;
import eu.eudat.query.UserContactInfoQuery;
import eu.eudat.query.UserQuery;
import gr.cite.tools.data.query.Ordering;
import gr.cite.tools.data.query.QueryFactory;
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 javax.management.InvalidApplicationException;
import java.util.*;
@Component
public class UnlinkEmailConfirmationManager {
private static Logger logger = LoggerFactory.getLogger(UnlinkEmailConfirmationManager.class);
private ApiContext apiContext;
private DatabaseRepository databaseRepository;
private final QueryFactory queryFactory;
private final UserScope userScope;
@Autowired
public UnlinkEmailConfirmationManager(ApiContext apiContext, QueryFactory queryFactory, UserScope userScope) {
this.apiContext = apiContext;
this.databaseRepository = apiContext.getOperationsContext().getDatabaseRepository();
this.queryFactory = queryFactory;
this.userScope = userScope;
}
@Transactional
public void confirmEmail(String token) throws TokenExpiredException, HasConfirmedEmailException, InvalidApplicationException {
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) throws InvalidApplicationException {
// UserCredentialEntity 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 sendUnlinkConfirmationEmail(String email, Integer provider) throws InvalidApplicationException {
UserEntity user = this.queryFactory.query(UserQuery.class).ids(this.userScope.getUserId()).first();
UserContactInfoQuery query = this.queryFactory.query(UserContactInfoQuery.class).userIds(user.getId());
query.setOrder(new Ordering().addAscending(UserContactInfo._ordinal));
if (query.first().getValue() != null && !query.first().getValue().equals(email)) {
apiContext.getUtilitiesService().getConfirmationEmailService().sentUnlinkConfirmationEmail(
databaseRepository.getLoginConfirmationEmailDao(),
email,
user,
provider
);
}
}
}

View File

@ -1,177 +0,0 @@
package eu.eudat.logic.managers;
import eu.eudat.commons.scope.user.UserScope;
import eu.eudat.commons.types.descriptiontemplate.DefinitionEntity;
import eu.eudat.commons.types.xml.XmlBuilder;
import eu.eudat.data.DescriptionTemplateEntity;
import eu.eudat.data.UserCredentialEntity;
import eu.eudat.data.UserEntity;
import eu.eudat.logic.services.ApiContext;
import eu.eudat.query.UserCredentialQuery;
import gr.cite.commons.web.authz.service.AuthorizationService;
import gr.cite.tools.data.query.QueryFactory;
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 org.w3c.dom.Document;
import org.w3c.dom.Element;
import javax.management.InvalidApplicationException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
@Component
public class UserManager {
private static final Logger logger = LoggerFactory.getLogger(UserManager.class);
private final ApiContext apiContext;
private final Environment environment;
private final UserScope userScope;
private final QueryFactory queryFactory;
private final AuthorizationService authorizationService;
@Autowired
public UserManager(ApiContext apiContext, Environment environment, UserScope userScope, QueryFactory queryFactory, AuthorizationService authorizationService) {
this.apiContext = apiContext;
this.environment = environment;
this.userScope = userScope;
this.queryFactory = queryFactory;
this.authorizationService = authorizationService;
}
public eu.eudat.models.data.user.composite.DatasetProfile generateDatasetProfileModel(DescriptionTemplateEntity profile) {
Document viewStyleDoc = XmlBuilder.fromXml(profile.getDefinition());
Element root = (Element) viewStyleDoc.getDocumentElement();
DefinitionEntity viewstyle = new DefinitionEntity().fromXml(root);
eu.eudat.models.data.user.composite.DatasetProfile datasetprofile = new eu.eudat.models.data.user.composite.DatasetProfile();
datasetprofile.buildProfile(viewstyle);
return datasetprofile;
}
// public DataTableData<UserListingModel> getPaged(UserInfoTableRequestItem userInfoTableRequestItem) throws Exception {
// QueryableList<UserEntity> users = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().getWithCriteria(userInfoTableRequestItem.getCriteria()).withHint(HintedModelFactory.getHint(UserListingModel.class));
// QueryableList<UserEntity> pagedUsers = PaginationManager.applyPaging(users, userInfoTableRequestItem);
//
// List<UserListingModel> modelUsers = pagedUsers.select(item -> new UserListingModel().fromDataModel(item));
// return apiContext.getOperationsContext().getBuilderFactory().getBuilder(DataTableDataBuilder.class).totalCount(users.count()).data(modelUsers).build();
// }
// public List<UserCredential> getCredentials(UUID userId) throws InvalidApplicationException {
// List<UserCredential> results = new ArrayList<>();
// UserEntity user = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(userId);
// List<UserCredentialEntity> credentials = this.queryFactory.query(UserCredentialQuery.class).userIds(user.getId()).collect();
// credentials.forEach(credential -> {
// UserCredential userCredential = new UserCredential();
// results.add(userCredential);
// });
// return results;
// }
// public UserProfile getSingle(UUID userId) throws Exception {
// UserEntity user = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(userId);
// UserProfile profile = new UserProfile().fromDataModel(user);
// List<Integer> roles = new LinkedList<>();
// DataManagementPlanCriteria criteria = new DataManagementPlanCriteria();
// criteria.setAllVersions(false);
// QueryableList<DmpEntity> items = apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().getWithCriteria(criteria);
// List<DmpEntity> dmps = apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().getAuthenticated(items, userId, roles).take(5).toList();
// profile.setAssociatedDmps(dmps.stream().map(x -> new DataManagementPlan().fromDataModel(x)).collect(Collectors.toList()));
// return profile;
// }
// public void editRoles(UserListingModel user) throws InvalidApplicationException {
// UserEntity userInfo = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(user.getId());
// //userInfo.getUserRoles().stream().forEach(item -> apiContext.getOperationsContext().getDatabaseRepository().getUserRoleDao().delete(item)); //TODO
// for (String role : user.getAppRoles()) {
// UserRoleEntity userRole = apiContext.getOperationsContext().getBuilderFactory().getBuilder(UserRoleBuilder.class).role(role).userInfo(userInfo).build();
// apiContext.getOperationsContext().getDatabaseRepository().getUserRoleDao().createOrUpdate(userRole);
// }
// }
// public void updateSettings(Map<String, Object> settings) throws IOException, InvalidApplicationException {
// UserEntity userInfo = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(this.userScope.getUserId());
// apiContext.getOperationsContext().getDatabaseRepository().detachEntity(userInfo);
// HashMap<String, Object> result =
// new ObjectMapper().readValue(userInfo.getAdditionalInfo(), HashMap.class);
// userInfo.setName(settings.entrySet().stream().filter(entry -> entry.getKey().equals("name")).filter(Objects::nonNull).map(entry -> entry.getValue().toString()).findFirst().orElse(userInfo.getName()));
// settings.remove("name");
// result.putAll(settings);
// userInfo.setAdditionalInfo(new JSONObject(result).toString());
// apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao()
// .createOrUpdate(userInfo);
// }
//
// public DataTableData<UserListingModel> getCollaboratorsPaged(UserInfoTableRequestItem userInfoTableRequestItem) throws Exception {
// UserInfoDao userInfoDao = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao();
// QueryableList<UserEntity> users = userInfoDao.getWithCriteria(userInfoTableRequestItem.getCriteria());
//
// List<UserListingModel> colaborators = userInfoDao.getAuthenticated(users, this.userScope.getUserId())
// .withHint(HintedModelFactory.getHint(UserListingModel.class))
// .select(colaborator -> new UserListingModel().fromDataModel(colaborator));
//
// DataTableData<UserListingModel> dataTableData = new DataTableData<>();
// dataTableData.setData(colaborators);
// dataTableData.setTotalCount((long) colaborators.size());
// return dataTableData;
// }
//
// public ResponseEntity<byte[]> exportToCsv() throws IOException, InvalidApplicationException {
//
// this.authorizationService.authorizeForce(Permission.AdminRole);
//
// List<UserEntity> users = this.apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().asQueryable().toList();
// StringBuilder resultBuilder = new StringBuilder();
// resultBuilder.append("User Id").append(",").append("User Name").append(",").append("User Email").append("\n");
// users.stream().forEach(user -> resultBuilder.append(user.getId().toString()).append(",")
// .append(user.getName()).append(",")
////TODO .append(user.getEmail()).append("\n")
// );
// String result = resultBuilder.toString();
// String fileName = "Users_dump";//dmp.getLabel();
// fileName = fileName.replaceAll("[^a-zA-Z0-9+ ]", "");
// String uuid = UUID.randomUUID().toString();
// File file = new File(this.environment.getProperty("temp.temp") + uuid + ".csv");
// OutputStream output = new FileOutputStream(file);
// try {
//// mapper.writeValue(file, rdaExportModel);
// output.write(result.getBytes());
// output.flush();
// output.close();
// } catch (IOException e) {
// logger.error(e.getMessage(), e);
// }
//
// InputStream resource = new FileInputStream(file);
// HttpHeaders responseHeaders = new HttpHeaders();
// responseHeaders.setContentLength(file.length());
// responseHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
// responseHeaders.set("Content-Disposition", "attachment;filename=" + fileName + ".csv");
// responseHeaders.set("Access-Control-Expose-Headers", "Content-Disposition");
// responseHeaders.get("Access-Control-Expose-Headers").add("Content-Type");
//
// byte[] content = org.apache.poi.util.IOUtils.toByteArray(resource);
// resource.close();
// Files.deleteIfExists(file.toPath());
// return new ResponseEntity<>(content, responseHeaders, HttpStatus.OK);
// }
//
// public UserProfile getFromEmail(String email) throws InvalidApplicationException {
// UserEntity user = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().asQueryable().where((builder, root) -> builder.equal(root.get("email"), email)).getSingle();
// return new UserProfile().fromDataModel(user);
// }
//
// public Long countActiveUsers(){ //TODO: Authn
// return 0L;
// //return apiContext.getOperationsContext().getDatabaseRepository().getUserTokenDao().asQueryable().where(((builder, root) -> builder.greaterThan(root.get("expiresAt"), new Date()))).count();
// }
//
// public Long countAllUsers() throws InvalidApplicationException {
// return apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().asQueryable().count();
// }
}

View File

@ -2,7 +2,6 @@ package eu.eudat.logic.services;
import eu.eudat.logic.services.helpers.HelpersService;
import eu.eudat.logic.services.operations.OperationsContext;
import eu.eudat.logic.services.utilities.UtilitiesService;
public interface ApiContext {
@ -10,5 +9,4 @@ public interface ApiContext {
OperationsContext getOperationsContext();
UtilitiesService getUtilitiesService();
}

View File

@ -2,7 +2,6 @@ package eu.eudat.logic.services;
import eu.eudat.logic.services.helpers.HelpersService;
import eu.eudat.logic.services.operations.OperationsContext;
import eu.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
@ -31,8 +28,4 @@ public class ApiContextImpl implements ApiContext {
return helpersService;
}
@Override
public UtilitiesService getUtilitiesService() {
return utilitiesService;
}
}

View File

@ -12,10 +12,6 @@ public interface DatabaseRepository {
DMPDao getDmpDao();
InvitationDao getInvitationDao();
EmailConfirmationDao getLoginConfirmationEmailDao();
FileUploadDao getFileUploadDao();

View File

@ -15,11 +15,6 @@ public class DatabaseRepositoryImpl implements DatabaseRepository {
private DMPDao dmpDao;
private InvitationDao invitationDao;
private EmailConfirmationDao loginConfirmationEmailDao;
private FileUploadDao fileUploadDao;
@ -59,31 +54,11 @@ public class DatabaseRepositoryImpl implements DatabaseRepository {
}
@Override
public InvitationDao getInvitationDao() {
return invitationDao;
}
@Autowired
public void setInvitationDao(InvitationDao invitationDao) {
this.invitationDao = invitationDao;
}
@Autowired
public void setEntityManager(EntityManager entityManager) {
this.entityManager = entityManager;
}
@Override
public EmailConfirmationDao getLoginConfirmationEmailDao() {
return loginConfirmationEmailDao;
}
@Autowired
public void setLoginConfirmationEmailDao(EmailConfirmationDao loginConfirmationEmailDao) {
this.loginConfirmationEmailDao = loginConfirmationEmailDao;
}
@Override
public FileUploadDao getFileUploadDao() {

View File

@ -1,15 +0,0 @@
package eu.eudat.logic.services.utilities;
import eu.eudat.data.dao.entities.EmailConfirmationDao;
import eu.eudat.data.UserEntity;
import javax.management.InvalidApplicationException;
public interface ConfirmationEmailService {
public void sentConfirmationEmail(EmailConfirmationDao loginConfirmationEmailDao, String email, UserEntity user) throws InvalidApplicationException;
public void sentUnlinkConfirmationEmail(EmailConfirmationDao loginConfirmationEmailDao, String email, UserEntity user, Integer provider) throws InvalidApplicationException;
public void sentMergeConfirmationEmail(EmailConfirmationDao loginConfirmationEmailDao, String email, UserEntity user, Integer provider) throws InvalidApplicationException;
}

View File

@ -1,159 +0,0 @@
package eu.eudat.logic.services.utilities;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import eu.eudat.commons.JsonHandlingService;
import eu.eudat.commons.enums.ContactInfoType;
import eu.eudat.commons.enums.notification.NotificationContactType;
import eu.eudat.commons.scope.user.UserScope;
import eu.eudat.commons.types.notification.*;
import eu.eudat.configurations.notification.NotificationProperties;
import eu.eudat.data.dao.entities.EmailConfirmationDao;
import eu.eudat.data.old.EmailConfirmation;
import eu.eudat.data.UserEntity;
import eu.eudat.integrationevent.outbox.notification.NotificationIntegrationEvent;
import eu.eudat.integrationevent.outbox.notification.NotificationIntegrationEventHandler;
import eu.eudat.model.UserContactInfo;
import eu.eudat.query.UserContactInfoQuery;
import gr.cite.tools.data.query.Ordering;
import gr.cite.tools.data.query.QueryFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import javax.management.InvalidApplicationException;
import java.util.*;
@Service("ConfirmationEmailService")
public class ConfirmationEmailServiceImpl implements ConfirmationEmailService {
private static final Logger logger = LoggerFactory.getLogger(ConfirmationEmailServiceImpl.class);
//private Logger logger;
private final UserScope userScope;
private final QueryFactory queryFactory;
private final JsonHandlingService jsonHandlingService;
private final NotificationIntegrationEventHandler eventHandler;
private final NotificationProperties notificationProperties;
public ConfirmationEmailServiceImpl(/*Logger logger,*/ UserScope userScope, QueryFactory queryFactory, JsonHandlingService jsonHandlingService, NotificationIntegrationEventHandler eventHandler, NotificationProperties notificationProperties) {
// this.logger = logger;
this.userScope = userScope;
this.queryFactory = queryFactory;
this.jsonHandlingService = jsonHandlingService;
this.eventHandler = eventHandler;
this.notificationProperties = notificationProperties;
}
@Override
public void sentConfirmationEmail(EmailConfirmationDao loginConfirmationEmailDao, String email, UserEntity user) throws InvalidApplicationException {
EmailConfirmation confirmationEmail = new EmailConfirmation();
confirmationEmail.setEmail(email);
confirmationEmail.setExpiresAt(Date
.from(new Date()
.toInstant()
.plusSeconds(this.notificationProperties.getEmailExpirationTimeSeconds())
)
);
confirmationEmail.setUserId(user.getId());
confirmationEmail.setIsConfirmed(false);
confirmationEmail.setToken(UUID.randomUUID());
confirmationEmail = loginConfirmationEmailDao.createOrUpdate(confirmationEmail);
}
@Override
public void sentUnlinkConfirmationEmail(EmailConfirmationDao loginConfirmationEmailDao, String email, UserEntity user, Integer provider) throws InvalidApplicationException {
EmailConfirmation confirmationEmail = new EmailConfirmation();
UserContactInfoQuery query = this.queryFactory.query(UserContactInfoQuery.class).userIds(user.getId());
query.setOrder(new Ordering().addAscending(UserContactInfo._ordinal));
confirmationEmail.setEmail(query.first().getValue());
confirmationEmail.setExpiresAt(Date
.from(new Date()
.toInstant()
.plusSeconds(this.notificationProperties.getEmailExpirationTimeSeconds())
)
);
confirmationEmail.setUserId(user.getId());
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);
NotificationIntegrationEvent event = new NotificationIntegrationEvent();
event.setUserId(userScope.getUserIdSafe());
List<ContactPair> contactPairs = new ArrayList<>();
contactPairs.add(new ContactPair(ContactInfoType.Email, email));
NotificationContactData contactData = new NotificationContactData(contactPairs, null, null);
event.setContactHint(jsonHandlingService.toJsonSafe(contactData));
event.setContactTypeHint(NotificationContactType.EMAIL);
event.setNotificationType(notificationProperties.getRemoveCredentialConfirmationType());
NotificationFieldData data = new NotificationFieldData();
List<FieldInfo> fieldInfoList = new ArrayList<>();
fieldInfoList.add(new FieldInfo("{confirmationToken}", DataType.String, confirmationEmail.getToken().toString()));
fieldInfoList.add(new FieldInfo("{email}", DataType.String, email));
fieldInfoList.add(new FieldInfo("{expiration_time}", DataType.String, this.secondsToTime(this.notificationProperties.getEmailExpirationTimeSeconds())));
data.setFields(fieldInfoList);
event.setData(jsonHandlingService.toJsonSafe(data));
eventHandler.handle(event);
}
@Override
public void sentMergeConfirmationEmail(EmailConfirmationDao loginConfirmationEmailDao,
String email, UserEntity user, Integer provider) throws InvalidApplicationException {
EmailConfirmation confirmationEmail = new EmailConfirmation();
confirmationEmail.setEmail(email);
confirmationEmail.setExpiresAt(Date
.from(new Date()
.toInstant()
.plusSeconds(this.notificationProperties.getEmailExpirationTimeSeconds())
)
);
confirmationEmail.setUserId(user.getId());
try {
Map<String, Object> map = new HashMap<>();
map.put("userId", this.userScope.getUserId());
map.put("provider", provider.toString());
confirmationEmail.setData(new ObjectMapper().writeValueAsString(map));
} catch (JsonProcessingException | InvalidApplicationException e) {
logger.error(e.getMessage(), e);
}
confirmationEmail.setIsConfirmed(false);
confirmationEmail.setToken(UUID.randomUUID());
confirmationEmail = loginConfirmationEmailDao.createOrUpdate(confirmationEmail);
NotificationIntegrationEvent event = new NotificationIntegrationEvent();
event.setUserId(userScope.getUserIdSafe());
List<ContactPair> contactPairs = new ArrayList<>();
contactPairs.add(new ContactPair(ContactInfoType.Email, email));
NotificationContactData contactData = new NotificationContactData(contactPairs, null, null);
event.setContactHint(jsonHandlingService.toJsonSafe(contactData));
event.setContactTypeHint(NotificationContactType.EMAIL);
event.setNotificationType(notificationProperties.getMergeAccountConfirmationType());
NotificationFieldData data = new NotificationFieldData();
List<FieldInfo> fieldInfoList = new ArrayList<>();
fieldInfoList.add(new FieldInfo("{userName}", DataType.String, user.getName()));
fieldInfoList.add(new FieldInfo("{confirmationToken}", DataType.String, confirmationEmail.getToken().toString()));
fieldInfoList.add(new FieldInfo("{expiration_time}", DataType.String, this.secondsToTime(this.notificationProperties.getEmailExpirationTimeSeconds())));
data.setFields(fieldInfoList);
event.setData(jsonHandlingService.toJsonSafe(data));
eventHandler.handle(event);
}
private String secondsToTime(int seconds) {
int sec = seconds % 60;
int hour = seconds / 60;
int min = hour % 60;
hour = hour / 60;
return (hour + ":" + min + ":" + sec);
}
}

View File

@ -1,26 +0,0 @@
package eu.eudat.logic.services.utilities;
import eu.eudat.data.DmpEntity;
import eu.eudat.data.DmpUserEntity;
import eu.eudat.data.dao.entities.DMPDao;
import eu.eudat.data.dao.entities.InvitationDao;
import eu.eudat.data.old.Invitation;
import eu.eudat.data.UserEntity;
import jakarta.mail.MessagingException;
import javax.management.InvalidApplicationException;
import java.util.List;
import java.util.concurrent.CompletableFuture;
public interface InvitationService {
void assignToDmp(DMPDao dmpDao, List<DmpUserEntity> users, DmpEntity dmp);
void assignToDmp(DMPDao dmpDao, DmpUserEntity user, DmpEntity dmp);
void createInvitations(InvitationDao invitationDao, List<UserEntity> users, DmpEntity dmp, Integer role, UserEntity creator) throws MessagingException, InvalidApplicationException;
void sendInvitation(DmpEntity dmp, Invitation invitation, UserEntity user, Integer role) throws InvalidApplicationException;
}

View File

@ -1,129 +0,0 @@
package eu.eudat.logic.services.utilities;
import eu.eudat.commons.JsonHandlingService;
import eu.eudat.commons.enums.ContactInfoType;
import eu.eudat.commons.enums.DmpUserRole;
import eu.eudat.commons.enums.notification.NotificationContactType;
import eu.eudat.commons.scope.user.UserScope;
import eu.eudat.commons.types.notification.*;
import eu.eudat.configurations.notification.NotificationProperties;
import eu.eudat.data.DmpEntity;
import eu.eudat.data.DmpUserEntity;
import eu.eudat.data.dao.entities.DMPDao;
import eu.eudat.data.dao.entities.InvitationDao;
import eu.eudat.data.old.Invitation;
import eu.eudat.data.UserEntity;
import eu.eudat.integrationevent.outbox.notification.NotificationIntegrationEvent;
import eu.eudat.integrationevent.outbox.notification.NotificationIntegrationEventHandler;
import eu.eudat.model.UserContactInfo;
import eu.eudat.models.data.invitation.Properties;
import eu.eudat.query.UserContactInfoQuery;
import gr.cite.tools.data.query.Ordering;
import gr.cite.tools.data.query.QueryFactory;
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 javax.management.InvalidApplicationException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
@Service("invitationService")
public class InvitationServiceImpl implements InvitationService {
private static final Logger logger = LoggerFactory.getLogger(InvitationServiceImpl.class);
private Environment environment;
private final UserScope userScope;
private final NotificationIntegrationEventHandler eventHandler;
private final JsonHandlingService jsonHandlingService;
private final NotificationProperties notificationProperties;
@Autowired
public InvitationServiceImpl(Environment environment, UserScope userScope, NotificationIntegrationEventHandler eventHandler, JsonHandlingService jsonHandlingService, NotificationProperties notificationProperties, QueryFactory queryFactory) {
this.environment = environment;
this.userScope = userScope;
this.eventHandler = eventHandler;
this.jsonHandlingService = jsonHandlingService;
this.notificationProperties = notificationProperties;
this.queryFactory = queryFactory;
}
private final QueryFactory queryFactory;
@Override
public void assignToDmp(DMPDao dmpDao, List<DmpUserEntity> users, DmpEntity dmp) {
// for (DmpUserEntity user : users) {
// dmp.getUsers().add(user);
// } //TODO
dmpDao.createOrUpdate(dmp);
}
@Override
public void assignToDmp(DMPDao dmpDao, DmpUserEntity user, DmpEntity dmp) {
// if (!dmp.getUsers().stream().map(x -> x.getUser().getId()).collect(Collectors.toList()).contains(user.getId())) {
// dmp.getUsers().add(user);
// dmpDao.createOrUpdate(dmp);
// } //TODO
}
@Override
public void createInvitations(InvitationDao invitationDao, List<UserEntity> users, DmpEntity dmp, Integer role, UserEntity creator) throws MessagingException, InvalidApplicationException {
for (UserEntity user : users) {
Invitation invitation = new Invitation();
// invitation.setDmp(dmp); //TODO
UserContactInfoQuery query = this.queryFactory.query(UserContactInfoQuery.class).userIds(user.getId());
query.setOrder(new Ordering().addAscending(UserContactInfo._ordinal));
invitation.setInvitationEmail(query.first().getValue());
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);
this.sendInvitation(dmp, invitation, user, role);
}
}
@Override
public void sendInvitation(DmpEntity dmp, Invitation invitation, UserEntity user, Integer role) throws InvalidApplicationException {
NotificationIntegrationEvent event = new NotificationIntegrationEvent();
event.setUserId(user.getId());
UserContactInfoQuery query = this.queryFactory.query(UserContactInfoQuery.class).userIds(user.getId());
query.setOrder(new Ordering().addAscending(UserContactInfo._ordinal));
List<ContactPair> contactPairs = new ArrayList<>();
contactPairs.add(new ContactPair(ContactInfoType.Email, query.first().getValue()));
NotificationContactData contactData = new NotificationContactData(contactPairs, null, null);
event.setContactHint(jsonHandlingService.toJsonSafe(contactData));
event.setContactTypeHint(NotificationContactType.EMAIL);
event.setNotificationType(notificationProperties.getDmpInvitationExternalUserType());
NotificationFieldData data = new NotificationFieldData();
List<FieldInfo> fieldInfoList = new ArrayList<>();
fieldInfoList.add(new FieldInfo("{recipient}", DataType.String, user.getName()));
fieldInfoList.add(new FieldInfo("{invitationID}", DataType.String, invitation.getId().toString()));
fieldInfoList.add(new FieldInfo("{dmpname}", DataType.String, dmp.getLabel()));
fieldInfoList.add(new FieldInfo("{dmprole}", DataType.String, DmpUserRole.of(role.shortValue()).toString()));
data.setFields(fieldInfoList);
event.setData(jsonHandlingService.toJsonSafe(data));
eventHandler.handle(event);
}
}

View File

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

View File

@ -1,31 +0,0 @@
package eu.eudat.logic.services.utilities;
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 ConfirmationEmailService confirmationEmailService;
@Autowired
public UtilitiesServiceImpl(InvitationService invitationService, ConfirmationEmailService confirmationEmailService) {
this.invitationService = invitationService;
this.confirmationEmailService = confirmationEmailService;
}
@Override
public ConfirmationEmailService getConfirmationEmailService() {
return confirmationEmailService;
}
@Override
public InvitationService getInvitationService() {
return invitationService;
}
}

View File

@ -1,49 +0,0 @@
package eu.eudat.logic.utilities.schedule.notification;
import eu.eudat.logic.managers.NotificationManager;
import eu.eudat.logic.services.ApiContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@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 //TODO
// @Scheduled(fixedRateString = "${notification.rateInterval}")
// public void sendNotifications() throws InvalidApplicationException {
// 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();
//
// }
}