task #9088 Authorization model should be changed to be Permission based

This commit is contained in:
Efstratios Giannopoulos 2023-10-18 18:52:03 +03:00
parent 8574f33e56
commit 52e59ac11c
134 changed files with 1464 additions and 1237 deletions

View File

@ -1,6 +1,19 @@
package eu.eudat.authorization;
public final class Permission {
/////// Should Remove after Refactor
public static String AnonymousRole = "AnonymousRole";
public static String AdminRole = "AdminRole";
public static String ManagerRole = "ManagerRole";
public static String UserRole = "UserRole";
public static String AuthenticatedRole = "AuthenticatedRole";
public static String PublicRole = "PublicRole";
public static String DatasetProfileManagerRole = "DatasetProfileManagerRole";
/////
//Language
public static String BrowseLanguage = "BrowseLanguage";

View File

@ -4,6 +4,7 @@ package eu.eudat.data.dao;
import eu.eudat.queryable.QueryableList;
import eu.eudat.queryable.queryableentity.DataEntity;
import javax.management.InvalidApplicationException;
import java.util.concurrent.CompletableFuture;
public interface DatabaseAccessLayer<T extends DataEntity, I> {
@ -11,9 +12,9 @@ public interface DatabaseAccessLayer<T extends DataEntity, I> {
CompletableFuture<T> createOrUpdateAsync(T item);
T find(I id);
T find(I id) throws InvalidApplicationException;
T find(I id, String hint);
T find(I id, String hint) throws InvalidApplicationException;
void delete(T item);

View File

@ -8,6 +8,7 @@ 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;
@ -34,7 +35,7 @@ public class ContentDaoImpl extends DatabaseAccess<Content> implements ContentDa
}
@Override
public Content find(UUID id) {
public Content find(UUID id) throws InvalidApplicationException {
return this.getDatabaseService().getQueryable(Content.class).where((builder, root) -> builder.equal(root.get("id"), id)).getSingle();
}

View File

@ -17,6 +17,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import javax.management.InvalidApplicationException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
@ -115,7 +116,7 @@ public class DMPDaoImpl extends DatabaseAccess<DMP> implements DMPDao {
}
@Override
public DMP find(UUID id) {
public DMP find(UUID id) throws InvalidApplicationException {
return getDatabaseService().getQueryable(DMP.class).where((builder, root) -> builder.equal((root.get("id")), id)).getSingle();
}

View File

@ -10,6 +10,7 @@ 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;
@ -37,12 +38,12 @@ public class DMPProfileDaoImpl extends DatabaseAccess<DMPProfile> implements DMP
@Override
public DMPProfile find(UUID id) {
public DMPProfile find(UUID id) throws InvalidApplicationException {
return getDatabaseService().getQueryable(DMPProfile.class).where((builder, root) -> builder.equal((root.get("id")), id)).getSingle();
}
@Override
public DMPProfile find(UUID id, String hint) {
public DMPProfile find(UUID id, String hint) throws InvalidApplicationException {
return getDatabaseService().getQueryable(DMPProfile.class).where((builder, root) -> builder.equal((root.get("id")), id)).getSingle();
}

View File

@ -9,6 +9,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import javax.management.InvalidApplicationException;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
@ -33,7 +34,7 @@ public class DataRepositoryDaoImpl extends DatabaseAccess<DataRepository> implem
}
@Override
public DataRepository find(UUID id) {
public DataRepository find(UUID id) throws InvalidApplicationException {
return this.getDatabaseService().getQueryable(DataRepository.class).where((builder, root) -> builder.equal(root.get("id"), id)).getSingle();
}

View File

@ -6,6 +6,7 @@ import eu.eudat.data.old.Dataset;
import eu.eudat.data.old.UserInfo;
import eu.eudat.queryable.QueryableList;
import javax.management.InvalidApplicationException;
import java.util.List;
import java.util.UUID;
@ -17,6 +18,6 @@ public interface DatasetDao extends DatabaseAccessLayer<Dataset, UUID> {
QueryableList<Dataset> getAuthenticated(QueryableList<Dataset> query, UserInfo principal, List<Integer> roles);
Dataset isPublicDataset(UUID id);
Dataset isPublicDataset(UUID id) throws InvalidApplicationException;
}

View File

@ -16,6 +16,8 @@ import org.springframework.stereotype.Component;
import jakarta.persistence.criteria.Join;
import jakarta.persistence.criteria.JoinType;
import javax.management.InvalidApplicationException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
@ -102,19 +104,19 @@ public class DatasetDaoImpl extends DatabaseAccess<Dataset> implements DatasetDa
}
@Override
public Dataset find(UUID id) {
public Dataset find(UUID id) throws InvalidApplicationException {
return getDatabaseService().getQueryable(Dataset.class)
.where((builder, root) -> builder.and(builder.notEqual(root.get("status"),Dataset.Status.DELETED.getValue()), builder.notEqual(root.get("status"),Dataset.Status.CANCELED.getValue()), builder.equal((root.get("id")), id))).getSingle();
}
@Override
public Dataset find(UUID id, String hint) {
public Dataset find(UUID id, String hint) throws InvalidApplicationException {
return getDatabaseService().getQueryable(Dataset.getHints(), Dataset.class).withHint(hint)
.where((builder, root) -> builder.and(builder.notEqual(root.get("status"),Dataset.Status.DELETED.getValue()), builder.notEqual(root.get("status"),Dataset.Status.CANCELED.getValue()), builder.equal((root.get("id")), id))).getSingle();
}
@Override
public Dataset isPublicDataset(UUID id) {
public Dataset isPublicDataset(UUID id) throws InvalidApplicationException {
QueryableList<Dataset> query = getDatabaseService().getQueryable(Dataset.getHints(), Dataset.class);
query.where(((builder, root) -> builder.equal(root.get("id"), id)));

View File

@ -8,6 +8,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import javax.management.InvalidApplicationException;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
@ -34,7 +35,7 @@ public class DatasetExternalDatasetDaoImpl extends DatabaseAccess<DatasetExterna
@Override
@Async
public DatasetExternalDataset find(UUID id) {
public DatasetExternalDataset find(UUID id) throws InvalidApplicationException {
return getDatabaseService().getQueryable(DatasetExternalDataset.class).where((builder, root) -> builder.equal(root.get("id"), id)).getSingle();
}

View File

@ -6,6 +6,7 @@ import eu.eudat.data.dao.criteria.DatasetProfileCriteria;
import eu.eudat.data.old.DescriptionTemplate;
import eu.eudat.queryable.QueryableList;
import javax.management.InvalidApplicationException;
import java.util.List;
import java.util.UUID;
@ -17,8 +18,8 @@ public interface DatasetProfileDao extends DatabaseAccessLayer<DescriptionTempla
QueryableList<DescriptionTemplate> getAuthenticated(QueryableList<DescriptionTemplate> query, UUID principal, List<Integer> roles);
List<DescriptionTemplate> getAllIds();
List<DescriptionTemplate> getAllIds() throws InvalidApplicationException;
Long countWithType(DescriptionTemplateTypeEntity type);
Long countWithType(DescriptionTemplateTypeEntity type) throws InvalidApplicationException;
}

View File

@ -14,6 +14,8 @@ import org.springframework.stereotype.Component;
import jakarta.persistence.criteria.Join;
import jakarta.persistence.criteria.JoinType;
import javax.management.InvalidApplicationException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
@ -78,7 +80,7 @@ public class DatasetProfileDaoImpl extends DatabaseAccess<DescriptionTemplate> i
}
@Override
public DescriptionTemplate find(UUID id) {
public DescriptionTemplate find(UUID id) throws InvalidApplicationException {
return getDatabaseService().getQueryable(DescriptionTemplate.class).where((builder, root) -> builder.equal(root.get("id"), id)).getSingle();
}
@ -88,7 +90,7 @@ public class DatasetProfileDaoImpl extends DatabaseAccess<DescriptionTemplate> i
}
@Override
public List<DescriptionTemplate> getAllIds(){
public List<DescriptionTemplate> getAllIds() throws InvalidApplicationException {
return getDatabaseService().getQueryable(DescriptionTemplate.class).withFields(Collections.singletonList("id")).toList();
}
@ -128,7 +130,7 @@ public class DatasetProfileDaoImpl extends DatabaseAccess<DescriptionTemplate> i
}
@Override
public Long countWithType(DescriptionTemplateTypeEntity type) {
public Long countWithType(DescriptionTemplateTypeEntity type) throws InvalidApplicationException {
return this.getDatabaseService().getQueryable(DescriptionTemplate.class).where((builder, root) -> builder.equal(root.get("type"), type)).count();
}
}

View File

@ -8,6 +8,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import javax.management.InvalidApplicationException;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
@ -34,7 +35,7 @@ public class DatasetServiceDaoImpl extends DatabaseAccess<DatasetService> implem
}
@Override
public DatasetService find(UUID id) {
public DatasetService find(UUID id) throws InvalidApplicationException {
return getDatabaseService().getQueryable(DatasetService.class).where((builder, root) -> builder.equal(root.get("id"), id)).getSingle();
}

View File

@ -8,6 +8,7 @@ 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;
@ -30,7 +31,7 @@ public class DmpDatasetProfileDaoImpl extends DatabaseAccess<DMPDatasetProfile>
}
@Override
public DMPDatasetProfile find(UUID id) {
public DMPDatasetProfile find(UUID id) throws InvalidApplicationException {
return this.getDatabaseService().getQueryable(DMPDatasetProfile.class).where((builder, root) -> builder.equal(root.get("id"), id)).getSingle();
}

View File

@ -8,6 +8,7 @@ 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;
@ -35,7 +36,7 @@ public class EmailConfirmationDaoImpl extends DatabaseAccess<EmailConfirmation>
}
@Override
public EmailConfirmation find(UUID id) {
public EmailConfirmation find(UUID id) throws InvalidApplicationException {
return this.getDatabaseService().getQueryable(EmailConfirmation.class).where((builder, root) -> builder.equal(root.get("id"), id)).getSingle();
}

View File

@ -3,8 +3,9 @@ package eu.eudat.data.dao.entities;
import eu.eudat.data.dao.DatabaseAccessLayer;
import eu.eudat.data.old.EntityDoi;
import javax.management.InvalidApplicationException;
import java.util.UUID;
public interface EntityDoiDao extends DatabaseAccessLayer<EntityDoi, UUID> {
EntityDoi findFromDoi(String doi);
EntityDoi findFromDoi(String doi) throws InvalidApplicationException;
}

View File

@ -7,6 +7,7 @@ import eu.eudat.queryable.QueryableList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.management.InvalidApplicationException;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
@ -30,12 +31,12 @@ public class EntityDoiDaoImpl extends DatabaseAccess<EntityDoi> implements Entit
}
@Override
public EntityDoi find(UUID id) {
public EntityDoi find(UUID id) throws InvalidApplicationException {
return this.getDatabaseService().getQueryable(EntityDoi.class).where((builder, root) -> builder.equal(root.get("id"), id)).getSingle();
}
@Override
public EntityDoi findFromDoi(String doi) {
public EntityDoi findFromDoi(String doi) throws InvalidApplicationException {
return this.getDatabaseService().getQueryable(EntityDoi.class).where((builder, root) -> builder.equal(root.get("doi"), doi)).getSingle();
}

View File

@ -9,6 +9,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import javax.management.InvalidApplicationException;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
@ -39,7 +40,7 @@ public class ExternalDatasetDaoImpl extends DatabaseAccess<ExternalDataset> impl
}
@Override
public ExternalDataset find(UUID id) {
public ExternalDataset find(UUID id) throws InvalidApplicationException {
return this.getDatabaseService().getQueryable(ExternalDataset.class).where((builder, root) -> builder.equal(root.get("id"), id)).getSingle();
}

View File

@ -3,9 +3,10 @@ package eu.eudat.data.dao.entities;
import eu.eudat.data.dao.DatabaseAccessLayer;
import eu.eudat.data.old.FileUpload;
import javax.management.InvalidApplicationException;
import java.util.List;
import java.util.UUID;
public interface FileUploadDao extends DatabaseAccessLayer<FileUpload, UUID> {
List<FileUpload> getFileUploads(UUID entityId);
List<FileUpload> getFileUploads(UUID entityId) throws InvalidApplicationException;
}

View File

@ -7,6 +7,7 @@ import eu.eudat.queryable.QueryableList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.management.InvalidApplicationException;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
@ -30,12 +31,12 @@ public class FileUploadDaoImpl extends DatabaseAccess<FileUpload> implements Fil
}
@Override
public FileUpload find(UUID id) {
public FileUpload find(UUID id) throws InvalidApplicationException {
return getDatabaseService().getQueryable(FileUpload.class).where((builder, root) -> builder.equal(root.get("id"), id)).getSingle();
}
@Override
public List<FileUpload> getFileUploads(UUID entityId) {
public List<FileUpload> getFileUploads(UUID entityId) throws InvalidApplicationException {
return this.getDatabaseService().getQueryable(FileUpload.class).where((builder, root) -> builder.equal(root.get("entityId"), entityId)).toList();
}

View File

@ -9,6 +9,7 @@ import eu.eudat.queryable.QueryableList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.management.InvalidApplicationException;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
@ -54,7 +55,7 @@ public class FunderDaoImpl extends DatabaseAccess<Funder> implements FunderDao {
}
@Override
public Funder find(UUID id) {
public Funder find(UUID id) throws InvalidApplicationException {
return this.getDatabaseService().getQueryable(Funder.class).where((builder, root) -> builder.equal(root.get("id"), id)).getSingle();
}

View File

@ -13,6 +13,8 @@ import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import jakarta.persistence.criteria.JoinType;
import javax.management.InvalidApplicationException;
import java.util.Date;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
@ -69,7 +71,7 @@ public class GrantDaoImpl extends DatabaseAccess<Grant> implements GrantDao {
}
@Override
public Grant find(UUID id) {
public Grant find(UUID id) throws InvalidApplicationException {
return getDatabaseService().getQueryable(Grant.class).where((builder, root) -> builder.equal((root.get("id")), id)).getSingle();
}

View File

@ -9,6 +9,7 @@ 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;
@ -32,7 +33,7 @@ public class InvitationDaoImpl extends DatabaseAccess<Invitation> implements Inv
}
@Override
public Invitation find(UUID id) {
public Invitation find(UUID id) throws InvalidApplicationException {
return this.getDatabaseService().getQueryable(Invitation.class).where((builder, root) -> builder.equal(root.get("id"), id)).getSingle();
}

View File

@ -9,6 +9,7 @@ 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;
@ -44,7 +45,7 @@ public class LockDaoImpl extends DatabaseAccess<Lock> implements LockDao {
}
@Override
public Lock find(UUID id) {
public Lock find(UUID id) throws InvalidApplicationException {
return this.getDatabaseService().getQueryable(Lock.class).where(((builder, root) -> builder.equal(root.get("id"), id))).getSingle();
}

View File

@ -8,6 +8,7 @@ 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;
@ -39,7 +40,7 @@ public class NotificationDaoImpl extends DatabaseAccess<Notification> implements
}
@Override
public Notification find(UUID id) {
public Notification find(UUID id) throws InvalidApplicationException {
return this.getDatabaseService().getQueryable(Notification.class).where(((builder, root) -> builder.equal(root.get("id"), id))).getSingle();
}

View File

@ -12,6 +12,8 @@ import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import jakarta.persistence.criteria.JoinType;
import javax.management.InvalidApplicationException;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
@ -52,7 +54,7 @@ public class OrganisationDaoImpl extends DatabaseAccess<Organisation> implements
}
@Override
public Organisation find(UUID id) {
public Organisation find(UUID id) throws InvalidApplicationException {
return this.getDatabaseService().getQueryable(Organisation.class).where((builder, root) -> builder.equal(root.get("id"), id)).getSingle();
}

View File

@ -9,6 +9,8 @@ import eu.eudat.queryable.QueryableList;
import org.springframework.stereotype.Service;
import jakarta.persistence.criteria.JoinType;
import javax.management.InvalidApplicationException;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
@ -52,7 +54,7 @@ public class ProjectDaoImpl extends DatabaseAccess<Project> implements ProjectDa
}
@Override
public Project find(UUID id) {
public Project find(UUID id) throws InvalidApplicationException {
return this.getDatabaseService().getQueryable(Project.class).where((builder, root) -> builder.equal(root.get("id"), id)).getSingle();
}

View File

@ -9,6 +9,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import javax.management.InvalidApplicationException;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
@ -39,7 +40,7 @@ public class RegistryDaoImpl extends DatabaseAccess<Registry> implements Registr
}
@Override
public Registry find(UUID id) {
public Registry find(UUID id) throws InvalidApplicationException {
return this.getDatabaseService().getQueryable(Registry.class).where((builder, root) -> builder.equal(root.get("id"), id)).getSingle();
}

View File

@ -9,6 +9,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import javax.management.InvalidApplicationException;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
@ -40,7 +41,7 @@ public class ResearcherDaoImpl extends DatabaseAccess<Researcher> implements Res
}
@Override
public Researcher find(UUID id) {
public Researcher find(UUID id) throws InvalidApplicationException {
return this.getDatabaseService().getQueryable(Researcher.class).where((builder, root) -> builder.equal(root.get("id"), id)).getSingle();
}

View File

@ -9,6 +9,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import javax.management.InvalidApplicationException;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
@ -38,7 +39,7 @@ public class ServiceDaoImpl extends DatabaseAccess<Service> implements ServiceDa
}
@Override
public Service find(UUID id) {
public Service find(UUID id) throws InvalidApplicationException {
return this.getDatabaseService().getQueryable(Service.class).where((builder, root) -> builder.equal(root.get("id"), id)).getSingle();
}

View File

@ -8,6 +8,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import javax.management.InvalidApplicationException;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
@ -25,7 +26,7 @@ public class UserDatasetProfileDaoImpl extends DatabaseAccess<UserDatasetProfile
}
@Override
public UserDatasetProfile find(UUID id) {
public UserDatasetProfile find(UUID id) throws InvalidApplicationException {
return this.getDatabaseService().getQueryable(UserDatasetProfile.class).where((builder, root) -> builder.equal(root.get("id"), id)).getSingleOrDefault();
}

View File

@ -8,6 +8,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import javax.management.InvalidApplicationException;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
@ -28,7 +29,7 @@ public class UserDmpDaoImpl extends DatabaseAccess<UserDMP> implements UserDmpDa
}
@Override
public UserDMP find(UUID id) {
public UserDMP find(UUID id) throws InvalidApplicationException {
return this.getDatabaseService().getQueryable(UserDMP.class).where((builder, root) -> builder.equal(root.get("id"), id)).getSingleOrDefault();
}

View File

@ -11,6 +11,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import javax.management.InvalidApplicationException;
import java.util.Arrays;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
@ -54,7 +55,7 @@ public class UserInfoDaoImpl extends DatabaseAccess<UserInfo> implements UserInf
}
@Override
public UserInfo find(UUID id) {
public UserInfo find(UUID id) throws InvalidApplicationException {
return this.getDatabaseService().getQueryable(UserInfo.class).where((builder, root) -> builder.equal(root.get("id"), id)).getSingle();
}

View File

@ -6,6 +6,7 @@ import eu.eudat.data.old.UserInfo;
import eu.eudat.data.old.UserRole;
import eu.eudat.queryable.QueryableList;
import javax.management.InvalidApplicationException;
import java.util.List;
import java.util.UUID;
@ -14,5 +15,5 @@ public interface UserRoleDao extends DatabaseAccessLayer<UserRole, UUID> {
QueryableList<UserRole> getWithCriteria(UserRoleCriteria criteria);
List<UserRole> getUserRoles(UserInfo userInfo);
List<UserRole> getUserRoles(UserInfo userInfo) throws InvalidApplicationException;
}

View File

@ -10,6 +10,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import javax.management.InvalidApplicationException;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
@ -29,12 +30,12 @@ public class UserRoleDaoImpl extends DatabaseAccess<UserRole> implements UserRol
}
@Override
public UserRole find(UUID id) {
public UserRole find(UUID id) throws InvalidApplicationException {
return this.getDatabaseService().getQueryable(UserRole.class).where((builder, root) -> builder.equal(root.get("id"), id)).getSingleOrDefault();
}
@Override
public List<UserRole> getUserRoles(UserInfo userInfo) {
public List<UserRole> getUserRoles(UserInfo userInfo) throws InvalidApplicationException {
return this.getDatabaseService().getQueryable(UserRole.class).where((builder, root) -> builder.equal(root.get("userInfo"), userInfo)).toList();
}

View File

@ -3,10 +3,11 @@ package eu.eudat.data.dao.entities.security;
import eu.eudat.data.CredentialEntity;
import eu.eudat.data.dao.DatabaseAccessLayer;
import javax.management.InvalidApplicationException;
import java.util.UUID;
public interface CredentialDao extends DatabaseAccessLayer<CredentialEntity, UUID> {
CredentialEntity getLoggedInCredentials(String username, String secret, Integer provider);
CredentialEntity getLoggedInCredentials(String username, String secret, Integer provider) throws InvalidApplicationException;
}

View File

@ -7,6 +7,7 @@ import eu.eudat.queryable.QueryableList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.management.InvalidApplicationException;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
@ -25,12 +26,12 @@ public class CredentialDaoImpl extends DatabaseAccess<CredentialEntity> implemen
}
@Override
public CredentialEntity find(UUID id) {
public CredentialEntity find(UUID id) throws InvalidApplicationException {
return this.getDatabaseService().getQueryable(CredentialEntity.class).where((builder, root) -> builder.equal(root.get("id"), id)).getSingleOrDefault();
}
@Override
public CredentialEntity getLoggedInCredentials(String username, String secret, Integer provider) {
public CredentialEntity getLoggedInCredentials(String username, String secret, Integer provider) throws InvalidApplicationException {
return this.getDatabaseService().getQueryable(CredentialEntity.class).where(((builder, root) ->
builder.and(
builder.equal(root.get("publicValue"), username),

View File

@ -10,6 +10,8 @@ import eu.eudat.queryable.types.FieldSelectionType;
import eu.eudat.queryable.types.SelectionField;
import jakarta.persistence.criteria.Subquery;
import javax.management.InvalidApplicationException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
@ -115,7 +117,7 @@ public class DMPQuery extends Query<DMP, UUID> {
this.datasetQuery = datasetQuery;
}
public QueryableList<DMP> getQuery() {
public QueryableList<DMP> getQuery() throws InvalidApplicationException {
QueryableList<DMP> query = this.databaseAccessLayer.asQueryable();
if (this.id != null) {
query.where((builder, root) -> builder.equal(root.get("id"), this.id));

View File

@ -8,6 +8,8 @@ import eu.eudat.queryable.types.FieldSelectionType;
import eu.eudat.queryable.types.SelectionField;
import jakarta.persistence.criteria.Subquery;
import javax.management.InvalidApplicationException;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
@ -51,7 +53,7 @@ public class DatasetQuery extends Query<Dataset, UUID> {
}
@Override
public QueryableList<Dataset> getQuery() {
public QueryableList<Dataset> getQuery() throws InvalidApplicationException {
QueryableList<Dataset> query = this.databaseAccessLayer.asQueryable();
if (this.id != null) {
query.where((builder, root) -> builder.equal(root.get("id"), this.id));

View File

@ -8,6 +8,8 @@ import eu.eudat.queryable.types.FieldSelectionType;
import eu.eudat.queryable.types.SelectionField;
import jakarta.persistence.criteria.Subquery;
import javax.management.InvalidApplicationException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
@ -88,7 +90,7 @@ public class GrantQuery extends Query<Grant, UUID> {
}
@Override
public QueryableList<Grant> getQuery() {
public QueryableList<Grant> getQuery() throws InvalidApplicationException {
QueryableList<Grant> query = this.databaseAccessLayer.asQueryable();
if (this.id != null)
query.where((builder, root) -> builder.equal(root.get("id"), this.id));

View File

@ -8,6 +8,8 @@ import eu.eudat.queryable.types.FieldSelectionType;
import eu.eudat.queryable.types.SelectionField;
import jakarta.persistence.criteria.Subquery;
import javax.management.InvalidApplicationException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
@ -61,7 +63,7 @@ public class LockQuery extends Query<Lock, UUID> {
}
@Override
public QueryableList<Lock> getQuery() {
public QueryableList<Lock> getQuery() throws InvalidApplicationException {
QueryableList<Lock> query = this.databaseAccessLayer.asQueryable();
if (this.id != null) {
query.where((builder, root) -> builder.equal(root.get("id"), this.id));

View File

@ -4,6 +4,7 @@ import eu.eudat.data.dao.DatabaseAccessLayer;
import eu.eudat.queryable.QueryableList;
import eu.eudat.queryable.queryableentity.DataEntity;
import javax.management.InvalidApplicationException;
import java.util.LinkedList;
import java.util.List;
@ -21,7 +22,7 @@ public abstract class Query<T extends DataEntity, K> {
this.databaseAccessLayer = databaseAccessLayer;
}
public abstract QueryableList<T> getQuery();
public abstract QueryableList<T> getQuery() throws InvalidApplicationException;
protected List<String> getSelectionFields() {
return selectionFields;

View File

@ -7,6 +7,8 @@ import eu.eudat.queryable.types.SelectionField;
import jakarta.persistence.criteria.Join;
import jakarta.persistence.criteria.JoinType;
import jakarta.persistence.criteria.Subquery;
import javax.management.InvalidApplicationException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
@ -14,27 +16,27 @@ import java.util.concurrent.CompletableFuture;
public interface QueryableList<T extends DataEntity> {
QueryableList<T> where(SinglePredicate<T> predicate);
<R> List<R> select(SelectPredicate<T, R> predicate);
<R> List<R> select(SelectPredicate<T, R> predicate) throws InvalidApplicationException;
<R> CompletableFuture<List<R>> selectAsync(SelectPredicate<T, R> predicate);
<R> CompletableFuture<List<R>> selectAsync(SelectPredicate<T, R> predicate) throws InvalidApplicationException;
List<T> toList();
List<T> toList() throws InvalidApplicationException;
<V> void update(EntitySelectPredicate<T> selectPredicate, V value);
<V> void update(EntitySelectPredicate<T> selectPredicate, V value) throws InvalidApplicationException;
QueryableList<T> withFields(List<String> fields);
List<Map> toListWithFields();
CompletableFuture<List<T>> toListAsync();
CompletableFuture<List<T>> toListAsync() throws InvalidApplicationException;
T getSingle();
T getSingle() throws InvalidApplicationException;
CompletableFuture<T> getSingleAsync();
CompletableFuture<T> getSingleAsync() throws InvalidApplicationException;
T getSingleOrDefault();
T getSingleOrDefault() throws InvalidApplicationException;
CompletableFuture<T> getSingleOrDefaultAsync();
CompletableFuture<T> getSingleOrDefaultAsync() throws InvalidApplicationException;
QueryableList<T> skip(Integer offset);
@ -48,25 +50,25 @@ public interface QueryableList<T extends DataEntity> {
QueryableList<T> withHint(String hint);
Long count();
Long count() throws InvalidApplicationException;
QueryableList<T> where(NestedQuerySinglePredicate<T> predicate);
CompletableFuture<Long> countAsync();
CompletableFuture<Long> countAsync() throws InvalidApplicationException;
Subquery<T> query(List<SelectionField> fields);
Subquery<T> query(List<SelectionField> fields) throws InvalidApplicationException;
Subquery<T> subQuery(SinglePredicate<T> predicate, List<SelectionField> fields);
Subquery<T> subQuery(SinglePredicate<T> predicate, List<SelectionField> fields) throws InvalidApplicationException;
Subquery<T> subQuery(NestedQuerySinglePredicate<T> predicate, List<SelectionField> fields);
Subquery<Long> subQueryCount(NestedQuerySinglePredicate<T> predicate, List<SelectionField> fields);
Subquery<Long> subQueryCount(SinglePredicate<T> predicate, List<SelectionField> fields);
Subquery<Long> subQueryCount(SinglePredicate<T> predicate, List<SelectionField> fields) throws InvalidApplicationException;
<U> QueryableList<T> initSubQuery(Class<U> uClass);
<U extends Comparable> Subquery<U> subQueryMax(SinglePredicate<T> predicate, List<SelectionField> fields, Class<U> uClass);
<U extends Comparable> Subquery<U> subQueryMax(SinglePredicate<T> predicate, List<SelectionField> fields, Class<U> uClass) throws InvalidApplicationException;
<U extends Comparable> Subquery<U> subQueryMax(NestedQuerySinglePredicate<T> predicate, List<SelectionField> fields, Class<U> uClass);

View File

@ -16,6 +16,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import javax.management.InvalidApplicationException;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
@ -154,11 +155,11 @@ public class QueryableHibernateList<T extends DataEntity> implements QueryableLi
return this;
}
public <R> List<R> select(SelectPredicate<T, R> predicate) {
public <R> List<R> select(SelectPredicate<T, R> predicate) throws InvalidApplicationException {
return this.toList().stream().map(predicate::applySelection).collect(Collectors.toList());
}
public <R> CompletableFuture<List<R>> selectAsync(SelectPredicate<T, R> predicate) {
public <R> CompletableFuture<List<R>> selectAsync(SelectPredicate<T, R> predicate) throws InvalidApplicationException {
return this.toListAsync().thenApplyAsync(items -> items.stream().map(predicate::applySelection).collect(Collectors.toList()));
}
@ -177,7 +178,7 @@ public class QueryableHibernateList<T extends DataEntity> implements QueryableLi
return this;
}
public Long count() {
public Long count() throws InvalidApplicationException {
CriteriaBuilder criteriaBuilder = this.manager.getCriteriaBuilder();
CriteriaQuery<Long> criteriaQuery = criteriaBuilder.createQuery(Long.class);
this.root = criteriaQuery.from(tClass);
@ -200,7 +201,7 @@ public class QueryableHibernateList<T extends DataEntity> implements QueryableLi
}
@Async
public CompletableFuture<Long> countAsync() {
public CompletableFuture<Long> countAsync() throws InvalidApplicationException {
CriteriaBuilder criteriaBuilder = this.manager.getCriteriaBuilder();
CriteriaQuery<Long> criteriaQuery = criteriaBuilder.createQuery(Long.class);
this.root = criteriaQuery.from(tClass);
@ -221,14 +222,14 @@ public class QueryableHibernateList<T extends DataEntity> implements QueryableLi
});
}
private Predicate[] generateWherePredicates(List<SinglePredicate<T>> singlePredicates, Root<T> root, List<NestedQuerySinglePredicate<T>> nestedPredicates, Root<T> nestedQueryRoot) {
private Predicate[] generateWherePredicates(List<SinglePredicate<T>> singlePredicates, Root<T> root, List<NestedQuerySinglePredicate<T>> nestedPredicates, Root<T> nestedQueryRoot) throws InvalidApplicationException {
List<Predicate> predicates = new LinkedList<>();
predicates.addAll(Arrays.asList(this.generateSingleWherePredicates(singlePredicates, root)));
predicates.addAll(Arrays.asList(this.generateNestedWherePredicates(nestedPredicates, root, nestedQueryRoot)));
return predicates.toArray(new Predicate[predicates.size()]);
}
private Predicate[] generateSingleWherePredicates(List<SinglePredicate<T>> singlePredicates, Root<T> root) {
private Predicate[] generateSingleWherePredicates(List<SinglePredicate<T>> singlePredicates, Root<T> root) throws InvalidApplicationException {
List<Predicate> predicates = new LinkedList<>();
for (SinglePredicate<T> singlePredicate : singlePredicates) {
predicates.add(singlePredicate.applyPredicate(this.manager.getCriteriaBuilder(), root));
@ -260,7 +261,7 @@ public class QueryableHibernateList<T extends DataEntity> implements QueryableLi
return predicates.toArray(new Expression[predicates.size()]);
}
public List<T> toList() {
public List<T> toList() throws InvalidApplicationException {
CriteriaBuilder builder = this.manager.getCriteriaBuilder();
if (!this.fields.isEmpty())
this.query = builder.createTupleQuery();
@ -310,7 +311,7 @@ public class QueryableHibernateList<T extends DataEntity> implements QueryableLi
}
@Async
public CompletableFuture<List<T>> toListAsync() {
public CompletableFuture<List<T>> toListAsync() throws InvalidApplicationException {
CriteriaBuilder builder = this.manager.getCriteriaBuilder();
if (!this.fields.isEmpty())
this.query = builder.createTupleQuery();
@ -364,7 +365,7 @@ public class QueryableHibernateList<T extends DataEntity> implements QueryableLi
});
}
public T getSingle() {
public T getSingle() throws InvalidApplicationException {
CriteriaBuilder builder = this.manager.getCriteriaBuilder();
if (!this.fields.isEmpty())
this.query = builder.createTupleQuery();
@ -381,7 +382,7 @@ public class QueryableHibernateList<T extends DataEntity> implements QueryableLi
}
@Async
public CompletableFuture<T> getSingleAsync() {
public CompletableFuture<T> getSingleAsync() throws InvalidApplicationException {
CriteriaBuilder builder = this.manager.getCriteriaBuilder();
if (!this.fields.isEmpty())
this.query = builder.createTupleQuery();
@ -397,7 +398,7 @@ public class QueryableHibernateList<T extends DataEntity> implements QueryableLi
return CompletableFuture.supplyAsync(() -> typedQuery.getSingleResult());
}
public T getSingleOrDefault() {
public T getSingleOrDefault() throws InvalidApplicationException {
CriteriaBuilder builder = this.manager.getCriteriaBuilder();
if (!this.fields.isEmpty())
this.query = builder.createTupleQuery();
@ -420,7 +421,7 @@ public class QueryableHibernateList<T extends DataEntity> implements QueryableLi
}
@Async
public CompletableFuture<T> getSingleOrDefaultAsync() {
public CompletableFuture<T> getSingleOrDefaultAsync() throws InvalidApplicationException {
CriteriaBuilder builder = this.manager.getCriteriaBuilder();
if (!this.fields.isEmpty())
this.query = builder.createTupleQuery();
@ -460,7 +461,7 @@ public class QueryableHibernateList<T extends DataEntity> implements QueryableLi
}
@Override
public Subquery<T> subQuery(SinglePredicate<T> predicate, List<SelectionField> fields) {
public Subquery<T> subQuery(SinglePredicate<T> predicate, List<SelectionField> fields) throws InvalidApplicationException {
Subquery<T> subquery = this.manager.getCriteriaBuilder().createQuery().subquery(this.tClass);
this.nestedQueryRoot = subquery.from(this.tClass);
subquery.where(predicate.applyPredicate(this.manager.getCriteriaBuilder(), this.nestedQueryRoot));
@ -486,7 +487,7 @@ public class QueryableHibernateList<T extends DataEntity> implements QueryableLi
}
@Override
public Subquery<Long> subQueryCount(SinglePredicate<T> predicate, List<SelectionField> fields) {
public Subquery<Long> subQueryCount(SinglePredicate<T> predicate, List<SelectionField> fields) throws InvalidApplicationException {
Subquery<Long> subquery = this.manager.getCriteriaBuilder().createQuery().subquery(Long.class);
this.nestedQueryRoot = subquery.from(this.tClass);
subquery.where(predicate.applyPredicate(this.manager.getCriteriaBuilder(), this.nestedQueryRoot));
@ -504,7 +505,7 @@ public class QueryableHibernateList<T extends DataEntity> implements QueryableLi
}
@Override
public <U extends Comparable> Subquery<U> subQueryMax(SinglePredicate<T> predicate, List<SelectionField> fields, Class<U> uClass) {
public <U extends Comparable> Subquery<U> subQueryMax(SinglePredicate<T> predicate, List<SelectionField> fields, Class<U> uClass) throws InvalidApplicationException {
Subquery<U> subquery = this.manager.getCriteriaBuilder().createQuery().subquery(uClass);
this.nestedQueryRoot = subquery.from(this.tClass);
subquery.where(predicate.applyPredicate(this.manager.getCriteriaBuilder(), this.nestedQueryRoot));
@ -537,7 +538,7 @@ public class QueryableHibernateList<T extends DataEntity> implements QueryableLi
}
@Override
public Subquery<T> query(List<SelectionField> fields) {
public Subquery<T> query(List<SelectionField> fields) throws InvalidApplicationException {
CriteriaBuilder builder = this.manager.getCriteriaBuilder();
Subquery<T> query = builder.createQuery().subquery(this.tClass);
this.root = query.from(this.tClass);
@ -553,7 +554,7 @@ public class QueryableHibernateList<T extends DataEntity> implements QueryableLi
}
@Override
public <V> void update(EntitySelectPredicate<T> selectPredicate, V value) {
public <V> void update(EntitySelectPredicate<T> selectPredicate, V value) throws InvalidApplicationException {
CriteriaBuilder builder = this.manager
.getCriteriaBuilder();
CriteriaUpdate<T> update = builder

View File

@ -4,6 +4,8 @@ import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.Predicate;
import jakarta.persistence.criteria.Root;
import javax.management.InvalidApplicationException;
public interface SinglePredicate<T> {
Predicate applyPredicate(CriteriaBuilder builder, Root<T> root);
Predicate applyPredicate(CriteriaBuilder builder, Root<T> root) throws InvalidApplicationException;
}

View File

@ -1,11 +1,6 @@
package eu.eudat.configurations;
import eu.eudat.commons.scope.user.UserScope;
import eu.eudat.interceptors.UserInterceptor;
import eu.eudat.logic.handlers.PrincipalArgumentResolver;
import eu.eudat.logic.services.ApiContext;
import eu.eudat.logic.services.operations.authentication.AuthenticationService;
import gr.cite.commons.web.oidc.principal.CurrentPrincipalResolver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
@ -21,28 +16,15 @@ import java.util.List;
@EnableScheduling
public class WebMVCConfiguration implements WebMvcConfigurer {
private ApiContext apiContext;
private AuthenticationService verifiedUserAuthenticationService;
private AuthenticationService nonVerifiedUserAuthenticationService;
private final UserInterceptor userInterceptor;
private final UserScope userScope;
private final CurrentPrincipalResolver currentPrincipalResolver;
@Autowired
public WebMVCConfiguration(ApiContext apiContext, AuthenticationService verifiedUserAuthenticationService, AuthenticationService nonVerifiedUserAuthenticationService, UserInterceptor userInterceptor, UserScope userScope, CurrentPrincipalResolver currentPrincipalResolver) {
this.apiContext = apiContext;
this.verifiedUserAuthenticationService = verifiedUserAuthenticationService;
this.nonVerifiedUserAuthenticationService = nonVerifiedUserAuthenticationService;
public WebMVCConfiguration(UserInterceptor userInterceptor) {
this.userInterceptor = userInterceptor;
this.userScope = userScope;
this.currentPrincipalResolver = currentPrincipalResolver;
}
@Autowired
@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
argumentResolvers.add(new PrincipalArgumentResolver(verifiedUserAuthenticationService, nonVerifiedUserAuthenticationService, userScope, currentPrincipalResolver));
}
@Override

View File

@ -1,5 +1,7 @@
package eu.eudat.controllers;
import eu.eudat.authorization.Permission;
import eu.eudat.commons.scope.user.UserScope;
import eu.eudat.data.old.DescriptionTemplate;
import eu.eudat.data.old.UserDatasetProfile;
import eu.eudat.data.old.UserInfo;
@ -11,17 +13,16 @@ import eu.eudat.logic.managers.DatasetProfileManager;
import eu.eudat.logic.managers.MetricsManager;
import eu.eudat.logic.managers.UserManager;
import eu.eudat.logic.proxy.config.configloaders.ConfigLoader;
import eu.eudat.logic.security.claims.ClaimedAuthorities;
import eu.eudat.logic.services.ApiContext;
import eu.eudat.models.data.admin.composite.DatasetProfile;
import eu.eudat.models.data.datasetprofile.DatasetProfileListingModel;
import eu.eudat.models.data.helpers.common.DataTableData;
import eu.eudat.models.data.helpers.responses.ResponseItem;
import eu.eudat.models.data.security.Principal;
import eu.eudat.models.data.user.composite.PagedDatasetProfile;
import eu.eudat.service.DescriptionTemplateTypeService;
import eu.eudat.types.ApiMessageCode;
import eu.eudat.types.MetricNames;
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;
@ -30,6 +31,8 @@ import org.springframework.web.multipart.MultipartFile;
import jakarta.transaction.Transactional;
import jakarta.validation.Valid;
import javax.management.InvalidApplicationException;
import java.io.IOException;
import java.util.List;
import java.util.UUID;
@ -46,22 +49,28 @@ public class Admin extends BaseController {
private UserManager userManager;
private ConfigLoader configLoader;
private final MetricsManager metricsManager;
private final AuthorizationService authorizationService;
private final UserScope userScope;
private final DescriptionTemplateTypeService descriptionTemplateTypeService;
@Autowired
public Admin(ApiContext apiContext, DatasetProfileManager datasetProfileManager, UserManager userManager/*, Logger logger*/, ConfigLoader configLoader, MetricsManager metricsManager, DescriptionTemplateTypeService descriptionTemplateTypeService) {
public Admin(ApiContext apiContext, DatasetProfileManager datasetProfileManager, UserManager userManager/*, Logger logger*/, ConfigLoader configLoader, MetricsManager metricsManager, AuthorizationService authorizationService, UserScope userScope, DescriptionTemplateTypeService descriptionTemplateTypeService) {
super(apiContext);
this.datasetProfileManager = datasetProfileManager;
this.userManager = userManager;
this.configLoader = configLoader;
this.metricsManager = metricsManager;
this.authorizationService = authorizationService;
this.userScope = userScope;
this.descriptionTemplateTypeService = descriptionTemplateTypeService;
}
@Transactional
@RequestMapping(method = RequestMethod.POST, value = {"/addDmp"}, consumes = "application/json", produces = "application/json")
public ResponseEntity<Object> addDmp(@Valid @RequestBody DatasetProfile profile, @ClaimedAuthorities(claims = {ADMIN ,DATASET_PROFILE_MANAGER}) Principal principal) throws Exception {
public ResponseEntity<Object> addDmp(@Valid @RequestBody DatasetProfile profile) throws Exception {
this.authorizationService.authorizeForce(Permission.AdminRole, Permission.DatasetProfileManagerRole);
//this.getLoggerService().info(principal, "Admin Added Dataset Profile");
DatasetProfile shortenProfile = profile.toShort();
DescriptionTemplate modelDefinition = AdminManager.generateViewStyleDefinition(shortenProfile, getApiContext(), descriptionTemplateTypeService);
@ -73,7 +82,7 @@ public class Admin extends BaseController {
DescriptionTemplate descriptionTemplate = this.getApiContext().getOperationsContext().getDatabaseRepository().getDatasetProfileDao().createOrUpdate(modelDefinition);
UserDatasetProfile userDatasetProfile = new UserDatasetProfile();
userDatasetProfile.setDatasetProfile(descriptionTemplate);
UserInfo userInfo = getApiContext().getOperationsContext().getDatabaseRepository().getUserInfoDao().find(principal.getId());
UserInfo userInfo = getApiContext().getOperationsContext().getDatabaseRepository().getUserInfoDao().find(this.userScope.getUserId());
userDatasetProfile.setUser(userInfo);
userDatasetProfile.setRole(0);
getApiContext().getOperationsContext().getDatabaseRepository().getUserDatasetProfileDao().createOrUpdate(userDatasetProfile);
@ -85,7 +94,9 @@ public class Admin extends BaseController {
@Transactional
@RequestMapping(method = RequestMethod.POST, value = {"/addDmp/{id}"}, consumes = "application/json", produces = "application/json")
public ResponseEntity<ResponseItem<UUID>> updateDmp(@PathVariable String id, @RequestBody DatasetProfile profile, @ClaimedAuthorities(claims = {ADMIN, DATASET_PROFILE_MANAGER}) Principal principal) throws Exception {
public ResponseEntity<ResponseItem<UUID>> updateDmp(@PathVariable String id, @RequestBody DatasetProfile profile) throws Exception {
this.authorizationService.authorizeForce(Permission.AdminRole, Permission.DatasetProfileManagerRole);
DatasetProfile shortenProfile = profile.toShort();
DescriptionTemplate modelDefinition = AdminManager.generateViewStyleDefinition(shortenProfile, getApiContext(), descriptionTemplateTypeService);
DescriptionTemplate datasetprofile = this.getApiContext().getOperationsContext().getDatabaseRepository().getDatasetProfileDao().find(UUID.fromString(id));
@ -105,7 +116,9 @@ public class Admin extends BaseController {
@Transactional
@RequestMapping(method = RequestMethod.POST, value = {"/newVersion/{id}"}, produces = "application/json")
public ResponseEntity newVersionDatasetProfile(@PathVariable String id, @RequestBody DatasetProfile profile, @ClaimedAuthorities(claims = {ADMIN, DATASET_PROFILE_MANAGER}) Principal principal) throws Exception {
public ResponseEntity newVersionDatasetProfile(@PathVariable String id, @RequestBody DatasetProfile profile) throws Exception {
this.authorizationService.authorizeForce(Permission.AdminRole, Permission.DatasetProfileManagerRole);
try {
DescriptionTemplate modelDefinition = this.datasetProfileManager.createNewVersionDatasetProfile(id, profile);
return ResponseEntity.status(HttpStatus.OK).body(modelDefinition.getId());
@ -116,20 +129,26 @@ public class Admin extends BaseController {
@RequestMapping(method = RequestMethod.GET, value = {"/get/{id}"}, produces = "application/json")
@Transactional
public ResponseEntity<ResponseItem<DatasetProfile>> get(@PathVariable String id, @ClaimedAuthorities(claims = {ADMIN, DATASET_PROFILE_MANAGER}) Principal principal) {
public ResponseEntity<ResponseItem<DatasetProfile>> get(@PathVariable String id) throws InvalidApplicationException {
this.authorizationService.authorizeForce(Permission.AdminRole, Permission.DatasetProfileManagerRole);
eu.eudat.models.data.admin.composite.DatasetProfile datasetprofile = this.datasetProfileManager.getDatasetProfile(id);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DatasetProfile>().status(ApiMessageCode.NO_MESSAGE).payload(datasetprofile));
}
@RequestMapping(method = RequestMethod.POST, value = {"/datasetprofiles/getPaged"}, produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<DataTableData<DatasetProfileListingModel>>> getPaged(@RequestBody DatasetProfileTableRequestItem datasetProfileTableRequestItem, @ClaimedAuthorities(claims = {ADMIN, DATASET_PROFILE_MANAGER}) Principal principal) throws Exception {
DataTableData<DatasetProfileListingModel> datasetProfileTableData = this.datasetProfileManager.getPaged(datasetProfileTableRequestItem, principal);
ResponseEntity<ResponseItem<DataTableData<DatasetProfileListingModel>>> getPaged(@RequestBody DatasetProfileTableRequestItem datasetProfileTableRequestItem) throws Exception {
this.authorizationService.authorizeForce(Permission.AdminRole, Permission.DatasetProfileManagerRole);
DataTableData<DatasetProfileListingModel> datasetProfileTableData = this.datasetProfileManager.getPaged(datasetProfileTableRequestItem);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DataTableData<DatasetProfileListingModel>>().status(ApiMessageCode.NO_MESSAGE).payload(datasetProfileTableData));
}
@RequestMapping(method = RequestMethod.POST, value = {"/preview"}, consumes = "application/json", produces = "application/json")
public ResponseEntity<ResponseItem<PagedDatasetProfile>> getPreview(@RequestBody DatasetProfile profile, @ClaimedAuthorities(claims = {ADMIN, DATASET_PROFILE_MANAGER}) Principal principal) throws Exception {
public ResponseEntity<ResponseItem<PagedDatasetProfile>> getPreview(@RequestBody DatasetProfile profile) throws Exception {
this.authorizationService.authorizeForce(Permission.AdminRole, Permission.DatasetProfileManagerRole);
DescriptionTemplate modelDefinition = AdminManager.generateViewStyleDefinition(profile, getApiContext(), descriptionTemplateTypeService);
eu.eudat.models.data.user.composite.DatasetProfile datasetProfile = userManager.generateDatasetProfileModel(modelDefinition);
PagedDatasetProfile pagedDatasetProfile = new PagedDatasetProfile();
@ -139,7 +158,9 @@ public class Admin extends BaseController {
@Transactional
@RequestMapping(method = RequestMethod.POST, value = {"/datasetprofile/clone/{id}"}, consumes = "application/json", produces = "application/json")
public ResponseEntity<ResponseItem<eu.eudat.models.data.admin.composite.DatasetProfile>> clone(@PathVariable String id, @ClaimedAuthorities(claims = {ADMIN, DATASET_PROFILE_MANAGER}) Principal principal) {
public ResponseEntity<ResponseItem<eu.eudat.models.data.admin.composite.DatasetProfile>> clone(@PathVariable String id) throws InvalidApplicationException {
this.authorizationService.authorizeForce(Permission.AdminRole, Permission.DatasetProfileManagerRole);
eu.eudat.models.data.admin.composite.DatasetProfile datasetprofile = this.datasetProfileManager.getDatasetProfile(id);
datasetprofile.setLabel(datasetprofile.getLabel() + " new ");
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<eu.eudat.models.data.admin.composite.DatasetProfile>().payload(datasetprofile));
@ -148,18 +169,22 @@ public class Admin extends BaseController {
@Transactional
@RequestMapping(method = RequestMethod.DELETE, value = {"{id}"}, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<DatasetProfile>> inactivate(@PathVariable String id, @ClaimedAuthorities(claims = {ADMIN, DATASET_PROFILE_MANAGER}) Principal principal) {
ResponseEntity<ResponseItem<DatasetProfile>> inactivate(@PathVariable String id) {
this.authorizationService.authorizeForce(Permission.AdminRole, Permission.DatasetProfileManagerRole);
try {
DescriptionTemplate ret = AdminManager.inactivate(this.getApiContext().getOperationsContext().getDatabaseRepository().getDatasetProfileDao(), this.getApiContext().getOperationsContext().getDatabaseRepository().getDatasetDao(), id);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<eu.eudat.models.data.admin.composite.DatasetProfile>().status(ApiMessageCode.SUCCESS_MESSAGE));
} catch (DatasetProfileWithDatasetsExeption exception) {
} catch (DatasetProfileWithDatasetsExeption | InvalidApplicationException exception) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem<eu.eudat.models.data.admin.composite.DatasetProfile>().status(ApiMessageCode.UNSUCCESS_DELETE).message(exception.getMessage()));
}
}
@Transactional
@RequestMapping(method = RequestMethod.GET, value = {"/getXml/{id}"}, produces = "application/json")
public ResponseEntity getDatasetProfileXml(@PathVariable String id, @RequestHeader("Content-Type") String contentType, @ClaimedAuthorities(claims = {ADMIN, DATASET_PROFILE_MANAGER}) Principal principal) throws IllegalAccessException, IOException, InstantiationException {
public ResponseEntity getDatasetProfileXml(@PathVariable String id, @RequestHeader("Content-Type") String contentType) throws IllegalAccessException, IOException, InstantiationException, InvalidApplicationException {
this.authorizationService.authorizeForce(Permission.AdminRole, Permission.DatasetProfileManagerRole);
if (contentType.equals("application/xml")) {
DescriptionTemplate profile = this.getApiContext().getOperationsContext().getDatabaseRepository().getDatasetProfileDao().find(UUID.fromString(id));
eu.eudat.models.data.user.composite.DatasetProfile datasetProfile = userManager.generateDatasetProfileModel(profile);
@ -175,8 +200,9 @@ public class Admin extends BaseController {
@RequestMapping(method = RequestMethod.POST, value = {"/upload", "/upload/{id}"})
public ResponseEntity<Object> setDatasetProfileXml(@RequestParam("file") MultipartFile file,
@PathVariable(value = "id", required = false) String id,
@ClaimedAuthorities(claims = {ADMIN, DATASET_PROFILE_MANAGER}) Principal principal) throws Exception {
@PathVariable(value = "id", required = false) String id) throws Exception {
this.authorizationService.authorizeForce(Permission.AdminRole, Permission.DatasetProfileManagerRole);
eu.eudat.logic.utilities.documents.xml.datasetProfileXml.datasetProfileModel.DatasetProfile datasetProfileModel = this.datasetProfileManager.createDatasetProfileFromXml(file);
eu.eudat.models.data.admin.composite.DatasetProfile datasetProfileEntity = datasetProfileModel.toAdminCompositeModel(file.getOriginalFilename());
DescriptionTemplate modelDefinition;
@ -185,7 +211,7 @@ public class Admin extends BaseController {
DescriptionTemplate descriptionTemplate = this.getApiContext().getOperationsContext().getDatabaseRepository().getDatasetProfileDao().createOrUpdate(modelDefinition);
UserDatasetProfile userDatasetProfile = new UserDatasetProfile();
userDatasetProfile.setDatasetProfile(descriptionTemplate);
UserInfo userInfo = getApiContext().getOperationsContext().getDatabaseRepository().getUserInfoDao().find(principal.getId());
UserInfo userInfo = getApiContext().getOperationsContext().getDatabaseRepository().getUserInfoDao().find(userScope.getUserId());
userDatasetProfile.setUser(userInfo);
userDatasetProfile.setRole(0);
getApiContext().getOperationsContext().getDatabaseRepository().getUserDatasetProfileDao().createOrUpdate(userDatasetProfile);
@ -198,7 +224,9 @@ public class Admin extends BaseController {
@RequestMapping(method = RequestMethod.GET, value = {"/getSemantics"}, produces = "application/json")
public ResponseEntity<ResponseItem<List<String>>> getSemantics(@RequestParam(value = "query", required = false) String query, @ClaimedAuthorities(claims = {ADMIN, DATASET_PROFILE_MANAGER}) Principal principal) {
public ResponseEntity<ResponseItem<List<String>>> getSemantics(@RequestParam(value = "query", required = false) String query) {
this.authorizationService.authorizeForce(Permission.AdminRole, Permission.DatasetProfileManagerRole);
List<String> semantics = this.datasetProfileManager.getSemantics(query);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List<String>>().status(ApiMessageCode.SUCCESS_MESSAGE).payload(semantics));
}

View File

@ -1,11 +1,12 @@
package eu.eudat.controllers;
import eu.eudat.authorization.Permission;
import eu.eudat.logic.managers.ContactEmailManager;
import eu.eudat.models.data.ContactEmail.ContactEmailModel;
import eu.eudat.models.data.ContactEmail.PublicContactEmailModel;
import eu.eudat.models.data.helpers.responses.ResponseItem;
import eu.eudat.models.data.security.Principal;
import eu.eudat.types.ApiMessageCode;
import gr.cite.commons.web.authz.service.AuthorizationService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
@ -21,18 +22,22 @@ public class ContactEmail {
private static final Logger logger = LoggerFactory.getLogger(ContactEmail.class);
private ContactEmailManager contactEmailManager;
private final AuthorizationService authorizationService;
public ContactEmail(ContactEmailManager contactEmailManager) {
public ContactEmail(ContactEmailManager contactEmailManager, AuthorizationService authorizationService) {
this.contactEmailManager = contactEmailManager;
this.authorizationService = authorizationService;
}
@Transactional
@RequestMapping(method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity sendContactEmail(@RequestBody ContactEmailModel contactEmailModel, Principal principal) {
ResponseEntity sendContactEmail(@RequestBody ContactEmailModel contactEmailModel) {
this.authorizationService.authorizeForce(Permission.AuthenticatedRole);
try {
this.contactEmailManager.emailValidation(contactEmailModel);
this.contactEmailManager.sendContactEmail(contactEmailModel, principal);
this.contactEmailManager.sendContactEmail(contactEmailModel);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE));
} catch (Exception ex) {
logger.error(ex.getMessage(), ex);

View File

@ -1,5 +1,6 @@
package eu.eudat.controllers;
import eu.eudat.authorization.Permission;
import eu.eudat.data.dao.criteria.RequestItem;
import eu.eudat.data.old.DMPProfile;
import eu.eudat.data.old.DescriptionTemplate;
@ -7,7 +8,6 @@ import eu.eudat.data.query.items.dmpblueprint.DataManagementPlanBlueprintTableRe
import eu.eudat.data.query.items.table.dmpprofile.DataManagementPlanProfileTableRequest;
import eu.eudat.exceptions.dmpblueprint.DmpBlueprintUsedException;
import eu.eudat.logic.managers.DataManagementProfileManager;
import eu.eudat.logic.security.claims.ClaimedAuthorities;
import eu.eudat.logic.services.ApiContext;
import eu.eudat.models.data.helpermodels.Tuple;
import eu.eudat.models.data.helpers.common.AutoCompleteLookupItem;
@ -15,8 +15,8 @@ import eu.eudat.models.data.helpers.common.DataTableData;
import eu.eudat.models.data.helpers.responses.ResponseItem;
import eu.eudat.models.data.listingmodels.DataManagementPlanBlueprintListingModel;
import eu.eudat.models.data.listingmodels.DataManagementPlanProfileListingModel;
import eu.eudat.models.data.security.Principal;
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;
@ -25,6 +25,8 @@ import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import jakarta.validation.Valid;
import javax.management.InvalidApplicationException;
import javax.xml.xpath.XPathExpressionException;
import java.io.IOException;
import java.util.List;
@ -39,62 +41,78 @@ import static eu.eudat.types.Authorities.ADMIN;
@RequestMapping(value = {"/api/dmpprofile"})
public class DMPProfileController extends BaseController {
private DataManagementProfileManager dataManagementProfileManager;
private final DataManagementProfileManager dataManagementProfileManager;
private final AuthorizationService authorizationService;
@Autowired
public DMPProfileController(ApiContext apiContext, DataManagementProfileManager dataManagementProfileManager) {
public DMPProfileController(ApiContext apiContext, DataManagementProfileManager dataManagementProfileManager, AuthorizationService authorizationService) {
super(apiContext);
this.dataManagementProfileManager = dataManagementProfileManager;
this.authorizationService = authorizationService;
}
@Transactional
@RequestMapping(method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<DMPProfile>> createOrUpdate(@RequestBody DataManagementPlanProfileListingModel dataManagementPlan, @ClaimedAuthorities(claims = {ADMIN}) Principal principal) throws Exception {
this.dataManagementProfileManager.createOrUpdate(dataManagementPlan, principal);
ResponseEntity<ResponseItem<DMPProfile>> createOrUpdate(@RequestBody DataManagementPlanProfileListingModel dataManagementPlan) throws Exception {
this.authorizationService.authorizeForce(Permission.AdminRole);
this.dataManagementProfileManager.createOrUpdate(dataManagementPlan);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DMPProfile>().status(ApiMessageCode.SUCCESS_MESSAGE).message("Created"));
}
@Transactional
@RequestMapping(method = RequestMethod.POST, value = {"/blueprint"}, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<DMPProfile>> createOrUpdateBlueprint(@RequestBody DataManagementPlanBlueprintListingModel dataManagementPlan, @ClaimedAuthorities(claims = {ADMIN}) Principal principal) throws Exception {
this.dataManagementProfileManager.createOrUpdateBlueprint(dataManagementPlan, principal);
ResponseEntity<ResponseItem<DMPProfile>> createOrUpdateBlueprint(@RequestBody DataManagementPlanBlueprintListingModel dataManagementPlan) throws Exception {
this.authorizationService.authorizeForce(Permission.AdminRole);
this.dataManagementProfileManager.createOrUpdateBlueprint(dataManagementPlan);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DMPProfile>().status(ApiMessageCode.SUCCESS_MESSAGE).message("Created"));
}
@RequestMapping(method = RequestMethod.GET, value = {"/getSingle/{id}"}, produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<DataManagementPlanProfileListingModel>> getSingle(@PathVariable String id, Principal principal) throws IllegalAccessException, InstantiationException {
DataManagementPlanProfileListingModel dataManagementPlanProfileListingModel = this.dataManagementProfileManager.getSingle(id, principal);
ResponseEntity<ResponseItem<DataManagementPlanProfileListingModel>> getSingle(@PathVariable String id) throws IllegalAccessException, InstantiationException, InvalidApplicationException {
this.authorizationService.authorizeForce(Permission.AuthenticatedRole);
DataManagementPlanProfileListingModel dataManagementPlanProfileListingModel = this.dataManagementProfileManager.getSingle(id);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DataManagementPlanProfileListingModel>().status(ApiMessageCode.NO_MESSAGE).payload(dataManagementPlanProfileListingModel));
}
@RequestMapping(method = RequestMethod.GET, value = {"/getSingleBlueprint/{id}"}, produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<DataManagementPlanBlueprintListingModel>> getSingleBlueprint(@PathVariable String id, Principal principal) {
DataManagementPlanBlueprintListingModel dataManagementPlanBlueprintListingModel = this.dataManagementProfileManager.getSingleBlueprint(id, principal);
ResponseEntity<ResponseItem<DataManagementPlanBlueprintListingModel>> getSingleBlueprint(@PathVariable String id) throws InvalidApplicationException {
this.authorizationService.authorizeForce(Permission.AuthenticatedRole);
DataManagementPlanBlueprintListingModel dataManagementPlanBlueprintListingModel = this.dataManagementProfileManager.getSingleBlueprint(id);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DataManagementPlanBlueprintListingModel>().status(ApiMessageCode.NO_MESSAGE).payload(dataManagementPlanBlueprintListingModel));
}
@RequestMapping(method = RequestMethod.POST, value = {"/getPaged"}, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<DataTableData<DataManagementPlanProfileListingModel>>> getPaged(@Valid @RequestBody DataManagementPlanProfileTableRequest dataManagementPlanProfileTableRequest, Principal principal) throws Exception {
DataTableData<DataManagementPlanProfileListingModel> dataTable = this.dataManagementProfileManager.getPaged(dataManagementPlanProfileTableRequest, principal);
ResponseEntity<ResponseItem<DataTableData<DataManagementPlanProfileListingModel>>> getPaged(@Valid @RequestBody DataManagementPlanProfileTableRequest dataManagementPlanProfileTableRequest) throws Exception {
this.authorizationService.authorizeForce(Permission.AuthenticatedRole);
DataTableData<DataManagementPlanProfileListingModel> dataTable = this.dataManagementProfileManager.getPaged(dataManagementPlanProfileTableRequest);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DataTableData<DataManagementPlanProfileListingModel>>().status(ApiMessageCode.NO_MESSAGE).payload(dataTable));
}
@RequestMapping(method = RequestMethod.POST, value = {"/getPagedBlueprint"}, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<DataTableData<DataManagementPlanBlueprintListingModel>>> getPagedBlueprint(@Valid @RequestBody DataManagementPlanBlueprintTableRequest dataManagementPlanBlueprintTableRequest, Principal principal) throws Exception {
DataTableData<DataManagementPlanBlueprintListingModel> dataTable = this.dataManagementProfileManager.getPagedBlueprint(dataManagementPlanBlueprintTableRequest, principal);
ResponseEntity<ResponseItem<DataTableData<DataManagementPlanBlueprintListingModel>>> getPagedBlueprint(@Valid @RequestBody DataManagementPlanBlueprintTableRequest dataManagementPlanBlueprintTableRequest) throws Exception {
this.authorizationService.authorizeForce(Permission.AuthenticatedRole);
DataTableData<DataManagementPlanBlueprintListingModel> dataTable = this.dataManagementProfileManager.getPagedBlueprint(dataManagementPlanBlueprintTableRequest);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DataTableData<DataManagementPlanBlueprintListingModel>>().status(ApiMessageCode.NO_MESSAGE).payload(dataTable));
}
@Transactional
@RequestMapping(method = RequestMethod.POST, value = {"/clone/{id}"}, consumes = "application/json", produces = "application/json")
public ResponseEntity<ResponseItem<DataManagementPlanBlueprintListingModel>> clone(@PathVariable String id, @ClaimedAuthorities(claims = {ADMIN}) Principal principal) {
DataManagementPlanBlueprintListingModel dmpBlueprint = this.dataManagementProfileManager.getSingleBlueprint(id, principal);
public ResponseEntity<ResponseItem<DataManagementPlanBlueprintListingModel>> clone(@PathVariable String id) throws InvalidApplicationException {
this.authorizationService.authorizeForce(Permission.AdminRole);
DataManagementPlanBlueprintListingModel dmpBlueprint = this.dataManagementProfileManager.getSingleBlueprint(id);
dmpBlueprint.setLabel(dmpBlueprint.getLabel() + " new ");
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DataManagementPlanBlueprintListingModel>().payload(dmpBlueprint));
}
@ -102,20 +120,24 @@ public class DMPProfileController extends BaseController {
@Transactional
@RequestMapping(method = RequestMethod.DELETE, value = {"{id}"}, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<Void>> inactivate(@PathVariable String id, @ClaimedAuthorities(claims = {ADMIN}) Principal principal) {
ResponseEntity<ResponseItem<Void>> inactivate(@PathVariable String id) {
this.authorizationService.authorizeForce(Permission.AdminRole);
try {
this.dataManagementProfileManager.inactivate(id);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<Void>().status(ApiMessageCode.SUCCESS_MESSAGE));
} catch (DmpBlueprintUsedException exception) {
} catch (DmpBlueprintUsedException | InvalidApplicationException exception) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem<Void>().status(ApiMessageCode.UNSUCCESS_DELETE).message(exception.getMessage()));
}
}
@RequestMapping(method = RequestMethod.GET, value = {"/getXml/{id}"}, produces = "application/json")
public @ResponseBody
ResponseEntity getXml( @RequestHeader("Content-Type") String contentType, @PathVariable String id, Principal principal) throws IOException {
ResponseEntity getXml( @RequestHeader("Content-Type") String contentType, @PathVariable String id) throws IOException, InvalidApplicationException {
this.authorizationService.authorizeForce(Permission.AuthenticatedRole);
if (contentType.equals("application/xml")) {
DataManagementPlanBlueprintListingModel dataManagementPlanBlueprintListingModel = this.dataManagementProfileManager.getSingleBlueprint(id, principal);
DataManagementPlanBlueprintListingModel dataManagementPlanBlueprintListingModel = this.dataManagementProfileManager.getSingleBlueprint(id);
return this.dataManagementProfileManager.getDocument(dataManagementPlanBlueprintListingModel);
}else {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem<DataManagementPlanBlueprintListingModel>().status(ApiMessageCode.ERROR_MESSAGE).message("NOT AUTHORIZE"));
@ -123,17 +145,18 @@ public class DMPProfileController extends BaseController {
}
@RequestMapping(method = RequestMethod.POST, value = {"/upload"})
public ResponseEntity<Object> setDatasetProfileXml(@RequestParam("file") MultipartFile file,
@ClaimedAuthorities(claims = {ADMIN}) Principal principal) throws Exception {
public ResponseEntity<Object> setDatasetProfileXml(@RequestParam("file") MultipartFile file) throws Exception {
this.authorizationService.authorizeForce(Permission.AdminRole);
eu.eudat.logic.utilities.documents.xml.dmpXml.dmpBlueprintModel.DmpBlueprint dmpBlueprintModel = this.dataManagementProfileManager.createDmpProfileFromXml(file);
DataManagementPlanBlueprintListingModel dmpBlueprint = dmpBlueprintModel.toDmpProfileCompositeModel(file.getOriginalFilename());
this.dataManagementProfileManager.createOrUpdateBlueprint(dmpBlueprint, principal);
this.dataManagementProfileManager.createOrUpdateBlueprint(dmpBlueprint);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List<DescriptionTemplate>>()
.status(ApiMessageCode.SUCCESS_MESSAGE).message(""));
}
@RequestMapping(method = RequestMethod.POST, value = {"/search/autocomplete"})
public ResponseEntity<Object> getExternalAutocomplete(@RequestBody RequestItem<AutoCompleteLookupItem> lookupItem) throws XPathExpressionException {
public ResponseEntity<Object> getExternalAutocomplete(@RequestBody RequestItem<AutoCompleteLookupItem> lookupItem) throws XPathExpressionException, InvalidApplicationException {
List<Tuple<String, String>> items = this.dataManagementProfileManager.getExternalAutocomplete(lookupItem);
return ResponseEntity.status(HttpStatus.OK).body(items);
}

View File

@ -1,6 +1,7 @@
package eu.eudat.controllers;
import eu.eudat.authorization.Permission;
import eu.eudat.configurations.dynamicgrant.DynamicGrantConfiguration;
import eu.eudat.criteria.DMPCriteria;
import eu.eudat.data.dao.criteria.DynamicFieldsCriteria;
@ -14,7 +15,6 @@ import eu.eudat.exceptions.datamanagementplan.DMPWithDatasetsDeleteException;
import eu.eudat.exceptions.security.UnauthorisedException;
import eu.eudat.logic.managers.DataManagementPlanManager;
import eu.eudat.logic.proxy.config.configloaders.ConfigLoader;
import eu.eudat.logic.security.claims.ClaimedAuthorities;
import eu.eudat.logic.services.ApiContext;
import eu.eudat.logic.services.operations.DatabaseRepository;
import eu.eudat.logic.utilities.documents.helpers.FileEnvelope;
@ -29,10 +29,10 @@ import eu.eudat.models.data.listingmodels.DataManagementPlanListingModel;
import eu.eudat.models.data.listingmodels.DataManagementPlanOverviewModel;
import eu.eudat.models.data.listingmodels.UserInfoListingModel;
import eu.eudat.models.data.listingmodels.VersionListingModel;
import eu.eudat.models.data.security.Principal;
import eu.eudat.query.DMPQuery;
import eu.eudat.types.ApiMessageCode;
import eu.eudat.types.Authorities;
import gr.cite.commons.web.authz.service.AuthorizationService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
@ -47,6 +47,8 @@ import org.springframework.web.multipart.MultipartFile;
import jakarta.activation.MimetypesFileTypeMap;
import jakarta.validation.Valid;
import javax.management.InvalidApplicationException;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
@ -69,15 +71,17 @@ public class DMPs extends BaseController {
private Environment environment;
private DataManagementPlanManager dataManagementPlanManager;
private ConfigLoader configLoader;
private final AuthorizationService authorizationService;
@Autowired
public DMPs(ApiContext apiContext, DynamicGrantConfiguration dynamicGrantConfiguration, Environment environment,
DataManagementPlanManager dataManagementPlanManager, ConfigLoader configLoader) {
DataManagementPlanManager dataManagementPlanManager, ConfigLoader configLoader, AuthorizationService authorizationService) {
super(apiContext);
this.dynamicGrantConfiguration = dynamicGrantConfiguration;
this.environment = environment;
this.dataManagementPlanManager = dataManagementPlanManager;
this.configLoader = configLoader;
this.authorizationService = authorizationService;
}
/*
@ -87,46 +91,51 @@ public class DMPs extends BaseController {
@RequestMapping(method = RequestMethod.POST, value = {"/paged"}, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<DataTableData<DataManagementPlanListingModel>>> getPaged(@Valid @RequestBody DataManagementPlanTableRequest dataManagementPlanTableRequest,
@RequestParam String fieldsGroup,
@ClaimedAuthorities(claims = {Authorities.ADMIN, Authorities.MANAGER, Authorities.USER, Authorities.ANONYMOUS}) Principal principal) throws Exception {
DataTableData<DataManagementPlanListingModel> dataTable = this.dataManagementPlanManager.getPaged(dataManagementPlanTableRequest, principal, fieldsGroup);
@RequestParam String fieldsGroup) throws Exception {
this.authorizationService.authorizeForce(Permission.AdminRole, Permission.ManagerRole, Permission.UserRole, Permission.AnonymousRole);
DataTableData<DataManagementPlanListingModel> dataTable = this.dataManagementPlanManager.getPaged(dataManagementPlanTableRequest, fieldsGroup);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DataTableData<DataManagementPlanListingModel>>().status(ApiMessageCode.NO_MESSAGE).payload(dataTable));
}
@RequestMapping(method = RequestMethod.GET, value = {"{id}"})
public @ResponseBody
ResponseEntity getSingle(@PathVariable String id, @RequestHeader("Content-Type") String contentType,
@ClaimedAuthorities(claims = {Authorities.ADMIN, Authorities.MANAGER, Authorities.USER, Authorities.ANONYMOUS}) Principal principal) throws Exception {
ResponseEntity getSingle(@PathVariable String id, @RequestHeader("Content-Type") String contentType) throws Exception {
this.authorizationService.authorizeForce(Permission.AdminRole, Permission.ManagerRole, Permission.UserRole, Permission.AnonymousRole);
if (contentType.equals("application/xml") || contentType.equals("application/msword")) {
return this.dataManagementPlanManager.getDocument(id, contentType, principal, this.configLoader);
return this.dataManagementPlanManager.getDocument(id, contentType, this.configLoader);
} else {
eu.eudat.models.data.dmp.DataManagementPlan dataManagementPlan = this.dataManagementPlanManager.getSingle(id, principal, false, true);
eu.eudat.models.data.dmp.DataManagementPlan dataManagementPlan = this.dataManagementPlanManager.getSingle(id, false, true);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DataManagementPlan>().status(ApiMessageCode.NO_MESSAGE).payload(dataManagementPlan));
}
}
@RequestMapping(method = RequestMethod.GET, value = {"/plain/{id}"})
public @ResponseBody
ResponseEntity getSingleNoDatasets(@PathVariable String id, @RequestHeader("Content-Type") String contentType,
@ClaimedAuthorities(claims = {Authorities.ADMIN, Authorities.MANAGER, Authorities.USER, Authorities.ANONYMOUS}) Principal principal) throws Exception {
ResponseEntity getSingleNoDatasets(@PathVariable String id, @RequestHeader("Content-Type") String contentType) throws Exception {
this.authorizationService.authorizeForce(Permission.AdminRole, Permission.ManagerRole, Permission.UserRole, Permission.AnonymousRole);
eu.eudat.models.data.dmp.DataManagementPlan dataManagementPlan = this.dataManagementPlanManager.getSingle(id, principal, false, false);
eu.eudat.models.data.dmp.DataManagementPlan dataManagementPlan = this.dataManagementPlanManager.getSingle(id, false, false);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DataManagementPlan>().status(ApiMessageCode.NO_MESSAGE).payload(dataManagementPlan));
}
@RequestMapping(method = RequestMethod.POST, value = {"/datasetProfilesUsedByDmps/paged"}, produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<DataTableData<DatasetProfileListingModel>>> getUsingDatasetProfilesPaged(@RequestBody DatasetProfileTableRequestItem datasetProfileTableRequestItem, Principal principal) {
DataTableData<DatasetProfileListingModel> datasetProfileTableData = this.dataManagementPlanManager.getDatasetProfilesUsedByDMP(datasetProfileTableRequestItem, principal);
ResponseEntity<ResponseItem<DataTableData<DatasetProfileListingModel>>> getUsingDatasetProfilesPaged(@RequestBody DatasetProfileTableRequestItem datasetProfileTableRequestItem) throws InvalidApplicationException {
this.authorizationService.authorizeForce(Permission.AuthenticatedRole);
DataTableData<DatasetProfileListingModel> datasetProfileTableData = this.dataManagementPlanManager.getDatasetProfilesUsedByDMP(datasetProfileTableRequestItem);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DataTableData<DatasetProfileListingModel>>().status(ApiMessageCode.NO_MESSAGE).payload(datasetProfileTableData));
}
@RequestMapping(method = RequestMethod.GET, value = {"/overview/{id}"})
public @ResponseBody
ResponseEntity getOverviewSingle(@PathVariable String id,@ClaimedAuthorities(claims = {Authorities.ADMIN, Authorities.MANAGER, Authorities.USER, Authorities.ANONYMOUS}) Principal principal) {
ResponseEntity getOverviewSingle(@PathVariable String id) {
this.authorizationService.authorizeForce(Permission.AdminRole, Permission.ManagerRole, Permission.UserRole, Permission.AnonymousRole);
try {
DataManagementPlanOverviewModel dataManagementPlan = this.dataManagementPlanManager.getOverviewSingle(id, principal, false);
DataManagementPlanOverviewModel dataManagementPlan = this.dataManagementPlanManager.getOverviewSingle(id, false);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DataManagementPlanOverviewModel>().status(ApiMessageCode.NO_MESSAGE).payload(dataManagementPlan));
} catch (Exception e) {
if (e instanceof UnauthorisedException) {
@ -139,9 +148,10 @@ public class DMPs extends BaseController {
@RequestMapping(method = RequestMethod.GET, value = {"/public/{id}"})
public @ResponseBody
ResponseEntity getSinglePublic(@PathVariable String id, @ClaimedAuthorities(claims = {Authorities.ADMIN, Authorities.MANAGER, Authorities.USER, Authorities.ANONYMOUS}) Principal principal) throws Exception {
// try {
eu.eudat.models.data.dmp.DataManagementPlan dataManagementPlan = this.dataManagementPlanManager.getSingle(id, principal, true, true);
ResponseEntity getSinglePublic(@PathVariable String id) throws Exception {
this.authorizationService.authorizeForce(Permission.AdminRole, Permission.ManagerRole, Permission.UserRole, Permission.AnonymousRole);
// try {
eu.eudat.models.data.dmp.DataManagementPlan dataManagementPlan = this.dataManagementPlanManager.getSingle(id, true, true);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DataManagementPlan>().status(ApiMessageCode.NO_MESSAGE).payload(dataManagementPlan));
// } catch (Exception ex) {
// return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem<DataManagementPlan>().status(ApiMessageCode.NO_MESSAGE).message(ex.getMessage()));
@ -150,9 +160,10 @@ public class DMPs extends BaseController {
@RequestMapping(method = RequestMethod.GET, value = {"/publicOverview/{id}"})
public @ResponseBody
ResponseEntity<ResponseItem<DataManagementPlanOverviewModel>> getOverviewSinglePublic(@PathVariable String id, @ClaimedAuthorities(claims = {Authorities.ADMIN, Authorities.MANAGER, Authorities.USER, Authorities.ANONYMOUS}) Principal principal) throws Exception {
ResponseEntity<ResponseItem<DataManagementPlanOverviewModel>> getOverviewSinglePublic(@PathVariable String id) throws Exception {
this.authorizationService.authorizeForce(Permission.AdminRole, Permission.ManagerRole, Permission.UserRole, Permission.AnonymousRole);
// try {
DataManagementPlanOverviewModel dataManagementPlan = this.dataManagementPlanManager.getOverviewSingle(id, principal, true);
DataManagementPlanOverviewModel dataManagementPlan = this.dataManagementPlanManager.getOverviewSingle(id, true);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DataManagementPlanOverviewModel>().status(ApiMessageCode.NO_MESSAGE).payload(dataManagementPlan));
// } catch (Exception ex) {
// return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem<DataManagementPlanOverviewModel>().status(ApiMessageCode.NO_MESSAGE).message(ex.getMessage()));
@ -161,16 +172,18 @@ public class DMPs extends BaseController {
@RequestMapping(method = RequestMethod.POST, value = {"/dynamic"}, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<List<Tuple<String, String>>>> getWithCriteria(@RequestBody RequestItem<DynamicFieldsCriteria> criteriaRequestItem, Principal principal) throws InstantiationException, IllegalAccessException {
ResponseEntity<ResponseItem<List<Tuple<String, String>>>> getWithCriteria(@RequestBody RequestItem<DynamicFieldsCriteria> criteriaRequestItem) throws InstantiationException, IllegalAccessException {
this.authorizationService.authorizeForce(Permission.AuthenticatedRole);
List<Tuple<String, String>> dataTable = this.dataManagementPlanManager.getDynamicFields(criteriaRequestItem.getCriteria().getId(), this.dynamicGrantConfiguration, criteriaRequestItem.getCriteria());
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List<Tuple<String, String>>>().status(ApiMessageCode.NO_MESSAGE).payload(dataTable));
}
@RequestMapping(method = RequestMethod.GET, value = {"/versions/{id}"}, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<List<VersionListingModel>>> getVersions(@PathVariable(value= "id") String groupId, @RequestParam(value= "public") Boolean isPublic,
@ClaimedAuthorities(claims = {Authorities.ADMIN, Authorities.MANAGER, Authorities.USER, Authorities.ANONYMOUS}) Principal principal) throws Exception {
List<VersionListingModel> versions = this.dataManagementPlanManager.getAllVersions(groupId, principal, isPublic);
ResponseEntity<ResponseItem<List<VersionListingModel>>> getVersions(@PathVariable(value= "id") String groupId, @RequestParam(value= "public") Boolean isPublic) throws Exception {
this.authorizationService.authorizeForce(Permission.AdminRole, Permission.ManagerRole, Permission.UserRole, Permission.AnonymousRole);
List<VersionListingModel> versions = this.dataManagementPlanManager.getAllVersions(groupId, isPublic);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List<VersionListingModel>>().status(ApiMessageCode.NO_MESSAGE).payload(versions));
}
@ -180,9 +193,10 @@ public class DMPs extends BaseController {
@RequestMapping(method = RequestMethod.GET, value = {"rda/{id}"})
public @ResponseBody
ResponseEntity getRDAJsonDocument(@PathVariable String id, @ClaimedAuthorities(claims = {Authorities.ADMIN, Authorities.MANAGER, Authorities.USER, Authorities.ANONYMOUS}) Principal principal) {
ResponseEntity getRDAJsonDocument(@PathVariable String id) {
this.authorizationService.authorizeForce(Permission.AdminRole, Permission.ManagerRole, Permission.UserRole, Permission.AnonymousRole);
try {
FileEnvelope rdaJsonDocument = this.dataManagementPlanManager.getRDAJsonDocument(id, principal);
FileEnvelope rdaJsonDocument = this.dataManagementPlanManager.getRDAJsonDocument(id);
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentLength(rdaJsonDocument.getFile().length());
@ -204,9 +218,9 @@ public class DMPs extends BaseController {
@RequestMapping(method = RequestMethod.GET, value = {"/getPDF/{id}"})
public @ResponseBody
ResponseEntity<byte[]> getPDFDocument(@PathVariable String id, @RequestHeader("Content-Type") String contentType,
@ClaimedAuthorities(claims = {Authorities.ADMIN, Authorities.MANAGER, Authorities.USER, Authorities.ANONYMOUS}) Principal principal) throws IllegalAccessException, IOException, InstantiationException, InterruptedException {
FileEnvelope file = this.dataManagementPlanManager.getWordDocument(id, principal, configLoader);
ResponseEntity<byte[]> getPDFDocument(@PathVariable String id, @RequestHeader("Content-Type") String contentType) throws IllegalAccessException, IOException, InstantiationException, InterruptedException, InvalidApplicationException {
this.authorizationService.authorizeForce(Permission.AdminRole, Permission.ManagerRole, Permission.UserRole, Permission.AnonymousRole);
FileEnvelope file = this.dataManagementPlanManager.getWordDocument(id, configLoader);
String name = file.getFilename().substring(0, file.getFilename().length() - 5).replace(" ", "_").replace(",", "_");
File pdffile = PDFUtils.convertToPDF(file, environment);
InputStream resource = new FileInputStream(pdffile);
@ -233,24 +247,29 @@ public class DMPs extends BaseController {
@Transactional
@RequestMapping(method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<eu.eudat.models.data.dmp.DataManagementPlan>> createOrUpdate(@RequestBody eu.eudat.models.data.dmp.DataManagementPlanEditorModel dataManagementPlanEditorModel, Principal principal) throws Exception {
DMP dmp = this.dataManagementPlanManager.createOrUpdate(dataManagementPlanEditorModel, principal);
ResponseEntity<ResponseItem<eu.eudat.models.data.dmp.DataManagementPlan>> createOrUpdate(@RequestBody eu.eudat.models.data.dmp.DataManagementPlanEditorModel dataManagementPlanEditorModel) throws Exception {
this.authorizationService.authorizeForce(Permission.AuthenticatedRole);
DMP dmp = this.dataManagementPlanManager.createOrUpdate(dataManagementPlanEditorModel);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<eu.eudat.models.data.dmp.DataManagementPlan>().status(ApiMessageCode.SUCCESS_MESSAGE).message("Created").payload(new eu.eudat.models.data.dmp.DataManagementPlan().fromDataModel(dmp)));
}
@Transactional
@RequestMapping(method = RequestMethod.POST, path = "full", consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<UUID>> createOrUpdateWithDatasets(@RequestBody eu.eudat.models.data.dmp.DataManagementPlanEditorModel dataManagementPlanEditorModel, Principal principal) throws Exception {
DMP dmp = this.dataManagementPlanManager.createOrUpdateWithDatasets(dataManagementPlanEditorModel, principal);
ResponseEntity<ResponseItem<UUID>> createOrUpdateWithDatasets(@RequestBody eu.eudat.models.data.dmp.DataManagementPlanEditorModel dataManagementPlanEditorModel) throws Exception {
this.authorizationService.authorizeForce(Permission.AuthenticatedRole);
DMP dmp = this.dataManagementPlanManager.createOrUpdateWithDatasets(dataManagementPlanEditorModel);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<UUID>().status(ApiMessageCode.SUCCESS_MESSAGE).message("Created").payload(dmp.getId()));
}
@RequestMapping(method = RequestMethod.POST, value = {"/new/{id}"}, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<UUID>> newVersion(@PathVariable UUID id, @Valid @RequestBody eu.eudat.models.data.dmp.DataManagementPlanNewVersionModel dataManagementPlan, Principal principal) throws Exception {
ResponseEntity<ResponseItem<UUID>> newVersion(@PathVariable UUID id, @Valid @RequestBody eu.eudat.models.data.dmp.DataManagementPlanNewVersionModel dataManagementPlan) throws Exception {
this.authorizationService.authorizeForce(Permission.AuthenticatedRole);
try {
UUID result = this.dataManagementPlanManager.newVersion(id, dataManagementPlan, principal);
UUID result = this.dataManagementPlanManager.newVersion(id, dataManagementPlan);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<UUID>().status(ApiMessageCode.NO_MESSAGE).payload(result));
} catch (DMPNewVersionException exception) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem<UUID>().status(ApiMessageCode.ERROR_MESSAGE).message(exception.getMessage()));
@ -259,28 +278,34 @@ public class DMPs extends BaseController {
@RequestMapping(method = RequestMethod.POST, value = {"/clone/{id}"}, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<UUID>> clone(@PathVariable UUID id, @RequestBody eu.eudat.models.data.dmp.DataManagementPlanNewVersionModel dataManagementPlan, Principal principal) throws Exception {
UUID cloneId = this.dataManagementPlanManager.clone(id, dataManagementPlan, principal);
ResponseEntity<ResponseItem<UUID>> clone(@PathVariable UUID id, @RequestBody eu.eudat.models.data.dmp.DataManagementPlanNewVersionModel dataManagementPlan) throws Exception {
this.authorizationService.authorizeForce(Permission.AuthenticatedRole);
UUID cloneId = this.dataManagementPlanManager.clone(id, dataManagementPlan);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<UUID>().status(ApiMessageCode.SUCCESS_MESSAGE).payload(cloneId));
}
@RequestMapping(method = RequestMethod.DELETE, value = {"{id}"}, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<DMP>> delete(@PathVariable UUID id, Principal principal) {
ResponseEntity<ResponseItem<DMP>> delete(@PathVariable UUID id) {
this.authorizationService.authorizeForce(Permission.AuthenticatedRole);
try {
this.dataManagementPlanManager.delete(id);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DMP>().status(ApiMessageCode.SUCCESS_MESSAGE).message("Successfully Deleted Datamanagement Plan"));
} catch (DMPWithDatasetsDeleteException | IOException exception) {
} catch (DMPWithDatasetsDeleteException | IOException | InvalidApplicationException exception) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem<DMP>().status(ApiMessageCode.ERROR_MESSAGE).message(exception.getMessage()));
}
}
@RequestMapping(method = RequestMethod.POST, value = {"/upload"})
public ResponseEntity<ResponseItem> dmpUpload(@RequestParam("file") MultipartFile[] files, @RequestParam(name = "profiles", required = false)String[] profiles, Principal principal) throws Exception {
public ResponseEntity<ResponseItem> dmpUpload(@RequestParam("file") MultipartFile[] files, @RequestParam(name = "profiles", required = false)String[] profiles) throws Exception {
this.authorizationService.authorizeForce(Permission.AuthenticatedRole);
if (files[0].getContentType().equals(APPLICATION_JSON.toString())) {
this.dataManagementPlanManager.createFromRDA(files, principal, profiles);
this.dataManagementPlanManager.createFromRDA(files, profiles);
} else if (files[0].getContentType().equals(APPLICATION_ATOM_XML.toString()) || files[0].getContentType().equals(TEXT_XML.toString())) {
this.dataManagementPlanManager.createDmpFromXml(files, principal, profiles);
this.dataManagementPlanManager.createDmpFromXml(files, profiles);
} else {
return ResponseEntity.badRequest().body(new ResponseItem().status(ApiMessageCode.ERROR_MESSAGE).message("File format is not supported"));
}
@ -289,9 +314,11 @@ public class DMPs extends BaseController {
}
@RequestMapping(method = RequestMethod.GET, value = {"/makepublic/{id}"})
public ResponseEntity<ResponseItem<DMP>> makePublic(@PathVariable String id, Principal principal) {
public ResponseEntity<ResponseItem<DMP>> makePublic(@PathVariable String id) {
this.authorizationService.authorizeForce(Permission.AuthenticatedRole);
try {
this.dataManagementPlanManager.makePublic(UUID.fromString(id), principal);
this.dataManagementPlanManager.makePublic(UUID.fromString(id));
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DMP>().status(ApiMessageCode.SUCCESS_MESSAGE).message("Successfully Data Datamanagement Plan made public."));
} catch (Exception e) {
logger.error(e.getMessage(), e);
@ -300,9 +327,11 @@ public class DMPs extends BaseController {
}
@RequestMapping(method = RequestMethod.POST, value = {"/finalize/{id}"})
public ResponseEntity<ResponseItem<DMP>> makeFinalize(@PathVariable String id, Principal principal, @RequestBody DatasetsToBeFinalized datasetsToBeFinalized) {
public ResponseEntity<ResponseItem<DMP>> makeFinalize(@PathVariable String id, @RequestBody DatasetsToBeFinalized datasetsToBeFinalized) {
this.authorizationService.authorizeForce(Permission.AuthenticatedRole);
try {
this.dataManagementPlanManager.makeFinalize(UUID.fromString(id), principal, datasetsToBeFinalized);
this.dataManagementPlanManager.makeFinalize(UUID.fromString(id), datasetsToBeFinalized);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DMP>().status(ApiMessageCode.SUCCESS_MESSAGE).message("Successfully Data Datamanagement Plan made finalized."));
} catch (Exception e) {
logger.error(e.getMessage(), e);
@ -311,9 +340,11 @@ public class DMPs extends BaseController {
}
@RequestMapping(method = RequestMethod.POST, value = {"/unfinalize/{id}"})
public ResponseEntity<ResponseItem<DMP>> undoFinalize(@PathVariable String id, Principal principal) {
public ResponseEntity<ResponseItem<DMP>> undoFinalize(@PathVariable String id) {
this.authorizationService.authorizeForce(Permission.AuthenticatedRole);
try {
this.dataManagementPlanManager.undoFinalize(UUID.fromString(id), principal);
this.dataManagementPlanManager.undoFinalize(UUID.fromString(id));
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DMP>().status(ApiMessageCode.SUCCESS_MESSAGE).message("Successfully Data Datamanagement Plan made active."));
} catch (Exception e) {
logger.error(e.getMessage(), e);
@ -323,9 +354,11 @@ public class DMPs extends BaseController {
@RequestMapping(method = RequestMethod.POST, value = {"/updateusers/{id}"})
public ResponseEntity<ResponseItem<DMP>> updateUsers(@PathVariable String id, @RequestBody List<UserInfoListingModel> users, Principal principal) {
public ResponseEntity<ResponseItem<DMP>> updateUsers(@PathVariable String id, @RequestBody List<UserInfoListingModel> users) {
this.authorizationService.authorizeForce(Permission.AuthenticatedRole);
try {
this.dataManagementPlanManager.updateUsers(UUID.fromString(id), users, principal);
this.dataManagementPlanManager.updateUsers(UUID.fromString(id), users);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DMP>().status(ApiMessageCode.SUCCESS_MESSAGE).message("Successfully Updated Colaborators for Data Datamanagement Plan."));
} catch (Exception e) {
logger.error(e.getMessage(), e);
@ -340,16 +373,20 @@ public class DMPs extends BaseController {
@Transactional
@RequestMapping(method = RequestMethod.POST, value = {"/index"})
public @ResponseBody
ResponseEntity<ResponseItem<Dataset>> generateIndex(Principal principal) throws Exception {
this.dataManagementPlanManager.generateIndex(principal);
ResponseEntity<ResponseItem<Dataset>> generateIndex() throws Exception {
this.authorizationService.authorizeForce(Permission.AuthenticatedRole);
this.dataManagementPlanManager.generateIndex();
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<Dataset>().status(ApiMessageCode.SUCCESS_MESSAGE).message("Generated").payload(null));
}
@Transactional
@RequestMapping(method = RequestMethod.DELETE, value = {"/index"})
public @ResponseBody
ResponseEntity<ResponseItem<Dataset>> clearIndex(Principal principal) throws Exception {
this.dataManagementPlanManager.clearIndex(principal);
ResponseEntity<ResponseItem<Dataset>> clearIndex() throws Exception {
this.authorizationService.authorizeForce(Permission.AuthenticatedRole);
this.dataManagementPlanManager.clearIndex();
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<Dataset>().status(ApiMessageCode.SUCCESS_MESSAGE).message("Cleared").payload(null));
}
@ -359,7 +396,9 @@ public class DMPs extends BaseController {
@RequestMapping(method = RequestMethod.POST, value = {"/test"}, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<DataTableData<Map>>> test(@RequestBody DMPCriteria criteria, @ClaimedAuthorities(claims = {Authorities.ANONYMOUS}) Principal principal) throws Exception {
ResponseEntity<ResponseItem<DataTableData<Map>>> test(@RequestBody DMPCriteria criteria) throws Exception {
this.authorizationService.authorizeForce(Permission.AnonymousRole);
DatabaseRepository dbRepo = this.getApiContext().getOperationsContext().getDatabaseRepository();
DMPQuery query = criteria.buildQuery(dbRepo);
@ -382,7 +421,7 @@ public class DMPs extends BaseController {
/*@Transactional
@RequestMapping(method = RequestMethod.GET, value = {"{id}/unlock"}, produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<DMP>> unlock(@PathVariable(value = "id") UUID id, Principal principal) throws Exception {
ResponseEntity<ResponseItem<DMP>> unlock(@PathVariable(value = "id") UUID id) throws Exception {
this.dataManagementPlanManager.unlock(id);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DMP>().status(ApiMessageCode.SUCCESS_MESSAGE).message("Unlocked"));
}*/

View File

@ -2,7 +2,6 @@ package eu.eudat.controllers;
import eu.eudat.authorization.Permission;
import eu.eudat.logic.managers.DashBoardManager;
import eu.eudat.logic.security.claims.ClaimedAuthorities;
import eu.eudat.logic.services.ApiContext;
import eu.eudat.models.data.dashboard.recent.RecentActivity;
import eu.eudat.models.data.dashboard.recent.model.RecentActivityModel;
@ -10,7 +9,6 @@ import eu.eudat.models.data.dashboard.recent.tablerequest.RecentActivityTableReq
import eu.eudat.models.data.dashboard.searchbar.SearchBarItem;
import eu.eudat.models.data.dashboard.statistics.DashBoardStatistics;
import eu.eudat.models.data.helpers.responses.ResponseItem;
import eu.eudat.models.data.security.Principal;
import eu.eudat.types.ApiMessageCode;
import eu.eudat.types.Authorities;
import gr.cite.commons.web.authz.service.AuthorizationService;
@ -20,6 +18,8 @@ import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import jakarta.transaction.Transactional;
import javax.management.InvalidApplicationException;
import java.io.IOException;
import java.util.List;
@ -38,15 +38,15 @@ public class DashBoardController extends BaseController {
}
@RequestMapping(method = RequestMethod.GET, value = {"/dashboard/me/getStatistics"}, produces = "application/json")
public ResponseEntity<ResponseItem<DashBoardStatistics>> getStatistics(Principal principal) throws IOException {
public ResponseEntity<ResponseItem<DashBoardStatistics>> getMyStatistics() throws IOException, InvalidApplicationException {
this.authorizationService.authorizeForce(Permission.BrowseStatistics);
DashBoardStatistics statistics = dashBoardManager.getMeStatistics(principal);
DashBoardStatistics statistics = dashBoardManager.getMeStatistics();
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DashBoardStatistics>().status(ApiMessageCode.NO_MESSAGE).payload(statistics));
}
@RequestMapping(method = RequestMethod.GET, value = {"/dashboard/getStatistics"}, produces = "application/json")
public ResponseEntity<ResponseItem<DashBoardStatistics>> getStatistics() {
public ResponseEntity<ResponseItem<DashBoardStatistics>> getStatistics() throws InvalidApplicationException {
this.authorizationService.authorizeForce(Permission.BrowsePublicStatistics);
DashBoardStatistics statistics = dashBoardManager.getStatistics();
@ -55,23 +55,28 @@ public class DashBoardController extends BaseController {
@RequestMapping(method = RequestMethod.POST, value = {"/dashboard/recentActivity"}, produces = "application/json")
@Transactional
public ResponseEntity<ResponseItem<List<RecentActivityModel>>> getNewRecentActivity(@RequestBody RecentActivityTableRequest tableRequest,
@ClaimedAuthorities(claims = {Authorities.ADMIN, Authorities.MANAGER, Authorities.USER, Authorities.ANONYMOUS}) Principal principal) throws Exception {
List<RecentActivityModel> statistics = dashBoardManager.getNewRecentActivity(tableRequest, principal);
public ResponseEntity<ResponseItem<List<RecentActivityModel>>> getNewRecentActivity(@RequestBody RecentActivityTableRequest tableRequest) throws Exception {
this.authorizationService.authorizeForce(Permission.AdminRole, Permission.ManagerRole, Permission.UserRole, Permission.AnonymousRole);
List<RecentActivityModel> statistics = dashBoardManager.getNewRecentActivity(tableRequest);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List<RecentActivityModel>>().status(ApiMessageCode.NO_MESSAGE).payload(statistics));
}
@Deprecated
@RequestMapping(method = RequestMethod.GET, value = {"/user/recentActivity"}, produces = "application/json")
public ResponseEntity<ResponseItem<RecentActivity>> getRecentActivity(@RequestParam(name = "numOfActivities", required = false, defaultValue = "5") Integer numberOfActivities, Principal principal) {
RecentActivity statistics = dashBoardManager.getRecentActivity(principal, numberOfActivities);
public ResponseEntity<ResponseItem<RecentActivity>> getRecentActivity(@RequestParam(name = "numOfActivities", required = false, defaultValue = "5") Integer numberOfActivities) throws InvalidApplicationException {
this.authorizationService.authorizeForce(Permission.AuthenticatedRole);
RecentActivity statistics = dashBoardManager.getRecentActivity(numberOfActivities);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<RecentActivity>().status(ApiMessageCode.NO_MESSAGE).payload(statistics));
}
@RequestMapping(method = RequestMethod.GET, value = {"/dashboard/search"}, produces = "application/json")
public ResponseEntity<ResponseItem<List<SearchBarItem>>> search(@RequestParam(name = "like") String like,
@ClaimedAuthorities(claims = {Authorities.ADMIN, Authorities.MANAGER, Authorities.USER, Authorities.ANONYMOUS}) Principal principal) {
List<SearchBarItem> searchBarItemList = dashBoardManager.searchUserData(like, principal);
public ResponseEntity<ResponseItem<List<SearchBarItem>>> search(@RequestParam(name = "like") String like) throws InvalidApplicationException {
this.authorizationService.authorizeForce(Permission.AdminRole, Permission.ManagerRole, Permission.UserRole, Permission.AnonymousRole);
List<SearchBarItem> searchBarItemList = dashBoardManager.searchUserData(like);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List<SearchBarItem>>().status(ApiMessageCode.NO_MESSAGE).payload(searchBarItemList));
}
}

View File

@ -1,5 +1,6 @@
package eu.eudat.controllers;
import eu.eudat.authorization.Permission;
import eu.eudat.data.old.DataRepository;
import eu.eudat.logic.managers.DataRepositoryManager;
import eu.eudat.logic.proxy.config.exceptions.HugeResultSet;
@ -7,14 +8,15 @@ import eu.eudat.logic.proxy.config.exceptions.NoURLFound;
import eu.eudat.logic.services.ApiContext;
import eu.eudat.models.data.datarepository.DataRepositoryModel;
import eu.eudat.models.data.helpers.responses.ResponseItem;
import eu.eudat.models.data.security.Principal;
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 javax.management.InvalidApplicationException;
import java.util.List;
@ -24,27 +26,33 @@ import java.util.List;
public class DataRepositories extends BaseController {
private DataRepositoryManager dataRepositoryManager;
private final AuthorizationService authorizationService;
@Autowired
public DataRepositories(ApiContext apiContext, DataRepositoryManager dataRepositoryManager) {
public DataRepositories(ApiContext apiContext, DataRepositoryManager dataRepositoryManager, AuthorizationService authorizationService) {
super(apiContext);
this.dataRepositoryManager = dataRepositoryManager;
this.authorizationService = authorizationService;
}
@RequestMapping(method = RequestMethod.GET, produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<List<DataRepositoryModel>>> listExternalDataRepositories(
@RequestParam(value = "query", required = false) String query, @RequestParam(value = "type", required = false) String type, Principal principal
) throws HugeResultSet, NoURLFound {
List<DataRepositoryModel> dataRepositoryModels = this.dataRepositoryManager.getDataRepositories(query, type, principal);
@RequestParam(value = "query", required = false) String query, @RequestParam(value = "type", required = false) String type
) throws HugeResultSet, NoURLFound, InvalidApplicationException {
this.authorizationService.authorizeForce(Permission.AuthenticatedRole);
List<DataRepositoryModel> dataRepositoryModels = this.dataRepositoryManager.getDataRepositories(query, type);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List<DataRepositoryModel>>().status(ApiMessageCode.NO_MESSAGE).payload(dataRepositoryModels));
}
@Transactional
@RequestMapping(method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<DataRepositoryModel>> create(@RequestBody eu.eudat.models.data.datarepository.DataRepositoryModel dataRepositoryModel, Principal principal) throws Exception {
DataRepository dataRepository = this.dataRepositoryManager.create(dataRepositoryModel, principal);
ResponseEntity<ResponseItem<DataRepositoryModel>> create(@RequestBody eu.eudat.models.data.datarepository.DataRepositoryModel dataRepositoryModel) throws Exception {
this.authorizationService.authorizeForce(Permission.AuthenticatedRole);
DataRepository dataRepository = this.dataRepositoryManager.create(dataRepositoryModel);
DataRepositoryModel dataRepositoryModel1 = new DataRepositoryModel().fromDataModel(dataRepository);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DataRepositoryModel>().payload(dataRepositoryModel1).status(ApiMessageCode.SUCCESS_MESSAGE));
}

View File

@ -1,23 +1,24 @@
package eu.eudat.controllers;
import eu.eudat.authorization.Permission;
import eu.eudat.data.dao.criteria.RequestItem;
import eu.eudat.data.old.DescriptionTemplate;
import eu.eudat.logic.managers.AdminManager;
import eu.eudat.logic.managers.DatasetProfileManager;
import eu.eudat.logic.security.claims.ClaimedAuthorities;
import eu.eudat.logic.services.ApiContext;
import eu.eudat.models.data.components.commons.datafield.AutoCompleteData;
import eu.eudat.models.data.externaldataset.ExternalAutocompleteFieldModel;
import eu.eudat.models.data.helpers.common.AutoCompleteLookupItem;
import eu.eudat.models.data.helpers.common.AutoCompleteOptionsLookupItem;
import eu.eudat.models.data.helpers.responses.ResponseItem;
import eu.eudat.models.data.security.Principal;
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 javax.management.InvalidApplicationException;
import javax.xml.xpath.XPathExpressionException;
import java.util.List;
import java.util.UUID;
@ -29,12 +30,14 @@ import static eu.eudat.types.Authorities.ADMIN;
@RequestMapping(value = {"/api"})
public class DatasetProfileController extends BaseController {
private DatasetProfileManager datasetProfileManager;
private final DatasetProfileManager datasetProfileManager;
private final AuthorizationService authorizationService;
@Autowired
public DatasetProfileController(ApiContext apiContext, DatasetProfileManager datasetProfileManager) {
public DatasetProfileController(ApiContext apiContext, DatasetProfileManager datasetProfileManager, AuthorizationService authorizationService) {
super(apiContext);
this.datasetProfileManager = datasetProfileManager;
this.authorizationService = authorizationService;
}
/* @Transactional
@ -52,7 +55,9 @@ public class DatasetProfileController extends BaseController {
@Transactional
@RequestMapping(method = RequestMethod.POST, value = {"/datasetprofile/clone/{id}"}, consumes = "application/json", produces = "application/json")
public ResponseEntity<ResponseItem<eu.eudat.models.data.admin.composite.DatasetProfile>> clone(@PathVariable String id, @ClaimedAuthorities(claims = {ADMIN})Principal principal) {
public ResponseEntity<ResponseItem<eu.eudat.models.data.admin.composite.DatasetProfile>> clone(@PathVariable String id) throws InvalidApplicationException {
this.authorizationService.authorizeForce(Permission.AdminRole);
DescriptionTemplate profile = this.datasetProfileManager.clone(id);
eu.eudat.models.data.admin.composite.DatasetProfile datasetprofile = AdminManager.generateDatasetProfileModel(profile);
datasetprofile.setLabel(profile.getLabel() + " new ");
@ -60,7 +65,7 @@ public class DatasetProfileController extends BaseController {
}
@RequestMapping(method = RequestMethod.POST, value = {"/search/autocomplete"}, consumes = "application/json", produces = "application/json")
public ResponseEntity<Object> getDataForAutocomplete(@RequestBody RequestItem<AutoCompleteLookupItem> lookupItem) throws XPathExpressionException {
public ResponseEntity<Object> getDataForAutocomplete(@RequestBody RequestItem<AutoCompleteLookupItem> lookupItem) throws XPathExpressionException, InvalidApplicationException {
DescriptionTemplate descriptionTemplate = this.getApiContext().getOperationsContext().getDatabaseRepository().getDatasetProfileDao().find(UUID.fromString(lookupItem.getCriteria().getProfileID()));
eu.eudat.models.data.entities.xmlmodels.datasetprofiledefinition.Field modelfield = this.datasetProfileManager.queryForField(descriptionTemplate.getDefinition(), lookupItem.getCriteria().getFieldID());
AutoCompleteData data = (AutoCompleteData) modelfield.getData();

View File

@ -13,6 +13,7 @@ import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.management.InvalidApplicationException;
import java.util.List;
@ -31,14 +32,14 @@ public class DatasetProfiles extends BaseController {
@RequestMapping(method = RequestMethod.POST, value = {"/dmps/datasetprofiles/get"}, produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<List<DatasetProfileAutocompleteItem>>> get(@RequestBody DatasetProfileAutocompleteRequest datasetProfileAutocompleteRequest) throws InstantiationException, IllegalAccessException {
ResponseEntity<ResponseItem<List<DatasetProfileAutocompleteItem>>> get(@RequestBody DatasetProfileAutocompleteRequest datasetProfileAutocompleteRequest) throws InstantiationException, IllegalAccessException, InvalidApplicationException {
List<DatasetProfileAutocompleteItem> datasetProfileAutocompleteItems = this.datasetProfileManager.getWithCriteria(datasetProfileAutocompleteRequest);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List<DatasetProfileAutocompleteItem>>().status(ApiMessageCode.NO_MESSAGE).payload(datasetProfileAutocompleteItems));
}
@RequestMapping(method = RequestMethod.POST, value = {"/datasetprofiles/getAll"}, produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<List<DatasetProfileListingModel>>> getAll(@RequestBody DatasetProfileTableRequestItem tableRequestItem) throws InstantiationException, IllegalAccessException {
ResponseEntity<ResponseItem<List<DatasetProfileListingModel>>> getAll(@RequestBody DatasetProfileTableRequestItem tableRequestItem) throws InstantiationException, IllegalAccessException, InvalidApplicationException {
List<DatasetProfileListingModel> datasetProfileTableData = this.datasetProfileManager.getAll(tableRequestItem);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List<DatasetProfileListingModel>>().status(ApiMessageCode.NO_MESSAGE).payload(datasetProfileTableData));
}

View File

@ -1,5 +1,7 @@
package eu.eudat.controllers;
import eu.eudat.authorization.Permission;
import eu.eudat.commons.scope.user.UserScope;
import eu.eudat.data.old.Dataset;
import eu.eudat.data.old.DescriptionTemplate;
import eu.eudat.data.query.items.item.dataset.DatasetWizardAutocompleteRequest;
@ -14,7 +16,6 @@ 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.security.claims.ClaimedAuthorities;
import eu.eudat.logic.services.ApiContext;
import eu.eudat.logic.services.forms.VisibilityRuleService;
import eu.eudat.logic.services.forms.VisibilityRuleServiceImpl;
@ -29,10 +30,9 @@ import eu.eudat.models.data.helpers.common.DataTableData;
import eu.eudat.models.data.helpers.responses.ResponseItem;
import eu.eudat.models.data.listingmodels.DataManagementPlanOverviewModel;
import eu.eudat.models.data.listingmodels.DatasetListingModel;
import eu.eudat.models.data.security.Principal;
import eu.eudat.models.data.user.composite.PagedDatasetProfile;
import eu.eudat.types.ApiMessageCode;
import eu.eudat.types.Authorities;
import gr.cite.commons.web.authz.service.AuthorizationService;
import org.apache.poi.util.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -47,6 +47,8 @@ import org.springframework.web.multipart.MultipartFile;
import jakarta.persistence.NoResultException;
import jakarta.transaction.Transactional;
import javax.management.InvalidApplicationException;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
@ -56,8 +58,6 @@ import java.util.List;
import java.util.Locale;
import java.util.UUID;
import static eu.eudat.types.Authorities.ANONYMOUS;
@RestController
@CrossOrigin
@ -70,16 +70,20 @@ public class Datasets extends BaseController {
private ConfigLoader configLoader;
private UserManager userManager;
private FileManager fileManager;
private final AuthorizationService authorizationService;
private final UserScope userScope;
@Autowired
public Datasets(ApiContext apiContext, Environment environment, DatasetManager datasetManager, ConfigLoader configLoader, UserManager userManager,
FileManager fileManager) {
FileManager fileManager, AuthorizationService authorizationService, UserScope userScope) {
super(apiContext);
this.environment = environment;
this.datasetManager = datasetManager;
this.configLoader = configLoader;
this.userManager = userManager;
this.fileManager = fileManager;
this.authorizationService = authorizationService;
this.userScope = userScope;
}
/*
@ -88,24 +92,29 @@ public class Datasets extends BaseController {
@RequestMapping(method = RequestMethod.POST, value = {"paged"}, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<DataTableData<DatasetListingModel>>> getPaged(@RequestBody DatasetTableRequest datasetTableRequest, @ClaimedAuthorities(claims = {Authorities.ADMIN, Authorities.MANAGER, Authorities.USER, Authorities.ANONYMOUS}) Principal principal) throws Exception {
DataTableData<DatasetListingModel> dataTable = this.datasetManager.getPaged(datasetTableRequest, principal);
ResponseEntity<ResponseItem<DataTableData<DatasetListingModel>>> getPaged(@RequestBody DatasetTableRequest datasetTableRequest) throws Exception {
this.authorizationService.authorizeForce(Permission.AdminRole, Permission.ManagerRole, Permission.UserRole, Permission.AnonymousRole);
DataTableData<DatasetListingModel> dataTable = this.datasetManager.getPaged(datasetTableRequest);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DataTableData<DatasetListingModel>>().status(ApiMessageCode.NO_MESSAGE).payload(dataTable));
}
@RequestMapping(method = RequestMethod.POST, value = {"/public/paged"}, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<DataTableData<DatasetListingModel>>> getPublicPaged(@RequestBody DatasetPublicTableRequest datasetTableRequest,
@ClaimedAuthorities(claims = {Authorities.ADMIN, Authorities.MANAGER, Authorities.USER, Authorities.ANONYMOUS}) Principal principal) throws Exception {
DataTableData<DatasetListingModel> dataTable = this.datasetManager.getPaged(datasetTableRequest, principal);
ResponseEntity<ResponseItem<DataTableData<DatasetListingModel>>> getPublicPaged(@RequestBody DatasetPublicTableRequest datasetTableRequest) throws Exception {
this.authorizationService.authorizeForce(Permission.AdminRole, Permission.ManagerRole, Permission.UserRole, Permission.AnonymousRole);
DataTableData<DatasetListingModel> dataTable = this.datasetManager.getPaged(datasetTableRequest);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DataTableData<DatasetListingModel>>().status(ApiMessageCode.NO_MESSAGE).payload(dataTable));
}
@RequestMapping(method = RequestMethod.GET, value = {"/overview/{id}"})
public @ResponseBody
ResponseEntity getOverviewSingle(@PathVariable String id,@ClaimedAuthorities(claims = {Authorities.ADMIN, Authorities.MANAGER, Authorities.USER, Authorities.ANONYMOUS}) Principal principal) {
ResponseEntity getOverviewSingle(@PathVariable String id) {
this.authorizationService.authorizeForce(Permission.AdminRole, Permission.ManagerRole, Permission.UserRole, Permission.AnonymousRole);
try {
DatasetOverviewModel dataset = this.datasetManager.getOverviewSingle(id, principal, false);
DatasetOverviewModel dataset = this.datasetManager.getOverviewSingle(id, false);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DatasetOverviewModel>().status(ApiMessageCode.NO_MESSAGE).payload(dataset));
} catch (Exception e) {
if (e instanceof UnauthorisedException) {
@ -118,9 +127,11 @@ public class Datasets extends BaseController {
@RequestMapping(method = RequestMethod.GET, value = {"/publicOverview/{id}"})
public @ResponseBody
ResponseEntity<ResponseItem<DatasetOverviewModel>> getOverviewSinglePublic(@PathVariable String id, @ClaimedAuthorities(claims = {Authorities.ADMIN, Authorities.MANAGER, Authorities.USER, Authorities.ANONYMOUS}) Principal principal) throws Exception {
// try {
DatasetOverviewModel dataset = this.datasetManager.getOverviewSingle(id, principal, true);
ResponseEntity<ResponseItem<DatasetOverviewModel>> getOverviewSinglePublic(@PathVariable String id) throws Exception {
this.authorizationService.authorizeForce(Permission.AdminRole, Permission.ManagerRole, Permission.UserRole, Permission.AnonymousRole);
// try {
DatasetOverviewModel dataset = this.datasetManager.getOverviewSingle(id, true);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DatasetOverviewModel>().status(ApiMessageCode.NO_MESSAGE).payload(dataset));
// } catch (Exception ex) {
// return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem<DataManagementPlanOverviewModel>().status(ApiMessageCode.NO_MESSAGE).message(ex.getMessage()));
@ -130,13 +141,15 @@ public class Datasets extends BaseController {
@Transactional
@RequestMapping(method = RequestMethod.GET, value = {"{id}"}, produces = "application/json")
public @ResponseBody
ResponseEntity getSingle(@PathVariable String id, @RequestHeader("Content-Type") String contentType, @ClaimedAuthorities(claims = {Authorities.ADMIN, Authorities.MANAGER, Authorities.USER, Authorities.ANONYMOUS}) Principal principal) throws IllegalAccessException, IOException, InstantiationException {
ResponseEntity getSingle(@PathVariable String id, @RequestHeader("Content-Type") String contentType) throws IllegalAccessException, IOException, InstantiationException {
this.authorizationService.authorizeForce(Permission.AdminRole, Permission.ManagerRole, Permission.UserRole, Permission.AnonymousRole);
try {
VisibilityRuleService visibilityRuleService = new VisibilityRuleServiceImpl();
if (contentType.equals("application/xml")) {
return this.datasetManager.getDocument(id, visibilityRuleService, contentType, principal);
return this.datasetManager.getDocument(id, visibilityRuleService, contentType);
} else if (contentType.equals("application/msword")) {
FileEnvelope file = datasetManager.getWordDocumentFile(this.configLoader, id, visibilityRuleService, principal);
FileEnvelope file = datasetManager.getWordDocumentFile(this.configLoader, id, visibilityRuleService);
InputStream resource = new FileInputStream(file.getFile());
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentLength(file.getFile().length());
@ -153,7 +166,7 @@ public class Datasets extends BaseController {
responseHeaders,
HttpStatus.OK);
} else {
DatasetWizardModel dataset = this.datasetManager.getSingle(id, principal);
DatasetWizardModel dataset = this.datasetManager.getSingle(id);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DatasetWizardModel>().status(ApiMessageCode.NO_MESSAGE).payload(dataset));
}
} catch (Exception e) {
@ -170,21 +183,27 @@ public class Datasets extends BaseController {
@RequestMapping(method = RequestMethod.POST, value = {"/datasetProfilesUsedByDatasets/paged"}, produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<DataTableData<DatasetProfileListingModel>>> getUsingDatasetProfilesPaged(@RequestBody DatasetProfileTableRequestItem datasetProfileTableRequestItem, Principal principal) {
DataTableData<DatasetProfileListingModel> datasetProfileTableData = this.datasetManager.getDatasetProfilesUsedByDatasets(datasetProfileTableRequestItem, principal);
ResponseEntity<ResponseItem<DataTableData<DatasetProfileListingModel>>> getUsingDatasetProfilesPaged(@RequestBody DatasetProfileTableRequestItem datasetProfileTableRequestItem) throws InvalidApplicationException {
this.authorizationService.authorizeForce(Permission.AuthenticatedRole);
DataTableData<DatasetProfileListingModel> datasetProfileTableData = this.datasetManager.getDatasetProfilesUsedByDatasets(datasetProfileTableRequestItem);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DataTableData<DatasetProfileListingModel>>().status(ApiMessageCode.NO_MESSAGE).payload(datasetProfileTableData));
}
@RequestMapping(method = RequestMethod.POST, value = {"/userDmps"}, produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<List<DataManagentPlanListingModel>>> getUserDmps(@RequestBody DatasetWizardAutocompleteRequest datasetWizardAutocompleteRequest, Principal principal) throws IllegalAccessException, InstantiationException {
List<DataManagentPlanListingModel> dataManagementPlans = DatasetWizardManager.getUserDmps(this.getApiContext().getOperationsContext().getDatabaseRepository().getDmpDao(), datasetWizardAutocompleteRequest, principal);
ResponseEntity<ResponseItem<List<DataManagentPlanListingModel>>> getUserDmps(@RequestBody DatasetWizardAutocompleteRequest datasetWizardAutocompleteRequest) throws IllegalAccessException, InstantiationException, InvalidApplicationException {
this.authorizationService.authorizeForce(Permission.AuthenticatedRole);
List<DataManagentPlanListingModel> dataManagementPlans = DatasetWizardManager.getUserDmps(this.getApiContext().getOperationsContext().getDatabaseRepository().getDmpDao(), datasetWizardAutocompleteRequest, this.userScope);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List<DataManagentPlanListingModel>>().status(ApiMessageCode.NO_MESSAGE).payload(dataManagementPlans));
}
@RequestMapping(method = RequestMethod.POST, value = {"/getAvailableProfiles"}, produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<List<AssociatedProfile>>> getAvailableProfiles(@RequestBody DatasetProfileWizardAutocompleteRequest datasetProfileWizardAutocompleteRequest, @ClaimedAuthorities(claims = {ANONYMOUS}) Principal principal) throws IllegalAccessException, InstantiationException {
ResponseEntity<ResponseItem<List<AssociatedProfile>>> getAvailableProfiles(@RequestBody DatasetProfileWizardAutocompleteRequest datasetProfileWizardAutocompleteRequest) throws IllegalAccessException, InstantiationException, InvalidApplicationException {
this.authorizationService.authorizeForce(Permission.AnonymousRole);
List<AssociatedProfile> dataManagementPlans = DatasetWizardManager.getAvailableProfiles(this.getApiContext().getOperationsContext().getDatabaseRepository().getDmpDao(), this.getApiContext().getOperationsContext().getDatabaseRepository().getDatasetProfileDao(), datasetProfileWizardAutocompleteRequest);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List<AssociatedProfile>>().status(ApiMessageCode.NO_MESSAGE).payload(dataManagementPlans));
}
@ -202,7 +221,7 @@ public class Datasets extends BaseController {
}
@RequestMapping(method = RequestMethod.GET, value = {"/get/{id}"}, produces = "application/json")
public ResponseEntity<ResponseItem<PagedDatasetProfile>> getSingle(@PathVariable String id) {
public ResponseEntity<ResponseItem<PagedDatasetProfile>> getSingle(@PathVariable String id) throws InvalidApplicationException {
DescriptionTemplate profile = this.getApiContext().getOperationsContext().getDatabaseRepository().getDatasetProfileDao().find(UUID.fromString(id));
eu.eudat.models.data.user.composite.DatasetProfile datasetprofile = userManager.generateDatasetProfileModel(profile);
PagedDatasetProfile pagedDatasetProfile = new PagedDatasetProfile();
@ -212,7 +231,9 @@ public class Datasets extends BaseController {
@RequestMapping(method = RequestMethod.GET, value = {"profile/{id}"}, produces = "application/json")
public @ResponseBody
ResponseEntity getSingleProfileUpdate(@PathVariable String id, @ClaimedAuthorities(claims = {ANONYMOUS}) Principal principal) throws IllegalAccessException, IOException, InstantiationException {
ResponseEntity getSingleProfileUpdate(@PathVariable String id) throws IllegalAccessException, IOException, InstantiationException, InvalidApplicationException {
this.authorizationService.authorizeForce(Permission.AnonymousRole);
DatasetWizardModel dataset = this.datasetManager.datasetUpdateProfile(id);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DatasetWizardModel>().status(ApiMessageCode.NO_MESSAGE).payload(dataset));
}
@ -223,8 +244,10 @@ public class Datasets extends BaseController {
@RequestMapping(method = RequestMethod.GET, value = {"/getPDF/{id}"})
public @ResponseBody
ResponseEntity<byte[]> getPDFDocument(@PathVariable String id, @ClaimedAuthorities(claims = {Authorities.ADMIN, Authorities.MANAGER, Authorities.USER, Authorities.ANONYMOUS}) Principal principal) throws IllegalAccessException, IOException, InstantiationException, InterruptedException {
FileEnvelope file = datasetManager.getWordDocumentFile(this.configLoader, id, new VisibilityRuleServiceImpl(), principal);
ResponseEntity<byte[]> getPDFDocument(@PathVariable String id) throws IOException, InvalidApplicationException {
this.authorizationService.authorizeForce(Permission.AdminRole, Permission.ManagerRole, Permission.UserRole, Permission.AnonymousRole);
FileEnvelope file = datasetManager.getWordDocumentFile(this.configLoader, id, new VisibilityRuleServiceImpl());
String fileName = file.getFilename().replace(" ", "_").replace(",", "_");
if (fileName.endsWith(".docx")){
fileName = fileName.substring(0, fileName.length() - 5);
@ -255,8 +278,10 @@ public class Datasets extends BaseController {
@Transactional
@RequestMapping(method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<DatasetWizardModel>> createOrUpdate(@RequestBody DatasetWizardModel profile, Principal principal) throws Exception {
DatasetWizardModel dataset = new DatasetWizardModel().fromDataModel(this.datasetManager.createOrUpdate(profile, principal));
ResponseEntity<ResponseItem<DatasetWizardModel>> createOrUpdate(@RequestBody DatasetWizardModel profile) throws Exception {
this.authorizationService.authorizeForce(Permission.AuthenticatedRole);
DatasetWizardModel dataset = new DatasetWizardModel().fromDataModel(this.datasetManager.createOrUpdate(profile));
dataset.setTags(profile.getTags());
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DatasetWizardModel>().status(ApiMessageCode.SUCCESS_MESSAGE).message("Created").payload(dataset));
}
@ -264,7 +289,9 @@ public class Datasets extends BaseController {
@Transactional
@RequestMapping(method = RequestMethod.GET, value = {"/makepublic/{id}"}, produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<Dataset>> makePublic(@PathVariable UUID id, Principal principal, Locale locale) throws Exception {
ResponseEntity<ResponseItem<Dataset>> makePublic(@PathVariable UUID id, Locale locale) throws Exception {
this.authorizationService.authorizeForce(Permission.AuthenticatedRole);
this.datasetManager.makePublic(this.getApiContext().getOperationsContext().getDatabaseRepository().getDatasetDao(), id);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<Dataset>().status(ApiMessageCode.SUCCESS_MESSAGE).message(this.getApiContext().getHelpersService().getMessageSource().getMessage("dataset.public", new Object[]{}, locale)));
}
@ -272,7 +299,7 @@ public class Datasets extends BaseController {
@Transactional
@RequestMapping(method = RequestMethod.DELETE, value = {"/delete/{id}"}, produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<Dataset>> delete(@PathVariable(value = "id") UUID id, Principal principal) throws Exception {
ResponseEntity<ResponseItem<Dataset>> delete(@PathVariable(value = "id") UUID id) throws Exception {
new DatasetWizardManager().delete(this.getApiContext(), id);
this.fileManager.markAllFilesOfEntityIdAsDeleted(id);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<Dataset>().status(ApiMessageCode.SUCCESS_MESSAGE).message("Deleted"));
@ -281,7 +308,9 @@ public class Datasets extends BaseController {
@Transactional
@RequestMapping(method = RequestMethod.GET, value = {"/{id}/unlock"}, produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<Dataset>> unlock(@PathVariable(value = "id") UUID id, Principal principal) throws Exception {
ResponseEntity<ResponseItem<Dataset>> unlock(@PathVariable(value = "id") UUID id) throws Exception {
this.authorizationService.authorizeForce(Permission.AuthenticatedRole);
try {
new DatasetWizardManager().unlock(this.getApiContext(), id);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<Dataset>().status(ApiMessageCode.SUCCESS_MESSAGE).message("Unlocked"));
@ -292,7 +321,9 @@ public class Datasets extends BaseController {
@RequestMapping(method = RequestMethod.GET, value = {"/{id}/validate"}, produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<Boolean>> validate(@PathVariable(value = "id") UUID id, Principal principal) throws Exception {
ResponseEntity<ResponseItem<Boolean>> validate(@PathVariable(value = "id") UUID id) throws Exception {
this.authorizationService.authorizeForce(Permission.AuthenticatedRole);
Dataset dataset = datasetManager.getEntitySingle(id);
String failedField = datasetManager.checkDatasetValidation(dataset);
if (failedField == null) {
@ -307,9 +338,11 @@ public class Datasets extends BaseController {
* */
@RequestMapping(method = RequestMethod.POST, value = {"/upload"})
public ResponseEntity<ResponseItem> datasetXmlImport(@RequestParam("file") MultipartFile file, @RequestParam("dmpId") String dmpId, @RequestParam("datasetProfileId") String datasetProfileId, Principal principal) {
public ResponseEntity<ResponseItem> datasetXmlImport(@RequestParam("file") MultipartFile file, @RequestParam("dmpId") String dmpId, @RequestParam("datasetProfileId") String datasetProfileId) {
this.authorizationService.authorizeForce(Permission.AuthenticatedRole);
try {
Dataset dataset = this.datasetManager.createDatasetFromXml(file, dmpId, datasetProfileId, principal);
Dataset dataset = this.datasetManager.createDatasetFromXml(file, dmpId, datasetProfileId);
if (dataset != null){
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE));
}
@ -329,16 +362,20 @@ public class Datasets extends BaseController {
@Transactional
@RequestMapping(method = RequestMethod.POST, value = {"/index"})
public @ResponseBody
ResponseEntity<ResponseItem<Dataset>> generateIndex(Principal principal) throws Exception {
this.datasetManager.generateIndex(principal);
ResponseEntity<ResponseItem<Dataset>> generateIndex() throws Exception {
this.authorizationService.authorizeForce(Permission.AuthenticatedRole);
this.datasetManager.generateIndex();
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<Dataset>().status(ApiMessageCode.SUCCESS_MESSAGE).message("Generated").payload(null));
}
@Transactional
@RequestMapping(method = RequestMethod.DELETE, value = {"/index"})
public @ResponseBody
ResponseEntity<ResponseItem<Dataset>> clearIndex(Principal principal) throws Exception {
this.datasetManager.clearIndex(principal);
ResponseEntity<ResponseItem<Dataset>> clearIndex() throws Exception {
this.authorizationService.authorizeForce(Permission.AuthenticatedRole);
this.datasetManager.clearIndex();
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<Dataset>().status(ApiMessageCode.SUCCESS_MESSAGE).message("Cleared").payload(null));
}

View File

@ -1,16 +1,15 @@
package eu.eudat.controllers;
import eu.eudat.authorization.Permission;
import eu.eudat.logic.managers.DepositManager;
import eu.eudat.logic.security.claims.ClaimedAuthorities;
import eu.eudat.logic.services.ApiContext;
import eu.eudat.models.data.doi.DepositCode;
import eu.eudat.models.data.doi.DepositRequest;
import eu.eudat.models.data.doi.Doi;
import eu.eudat.models.data.doi.RepositoryConfig;
import eu.eudat.models.data.helpers.responses.ResponseItem;
import eu.eudat.models.data.security.Principal;
import eu.eudat.types.ApiMessageCode;
import eu.eudat.types.Authorities;
import gr.cite.commons.web.authz.service.AuthorizationService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
@ -26,33 +25,40 @@ import java.util.List;
public class DepositController extends BaseController {
private static final Logger logger = LoggerFactory.getLogger(DepositController.class);
private DepositManager depositManager;
private final DepositManager depositManager;
private final AuthorizationService authorizationService;
@Autowired
public DepositController(ApiContext apiContext, DepositManager depositManager){
public DepositController(ApiContext apiContext, DepositManager depositManager, AuthorizationService authorizationService){
super(apiContext);
this.depositManager = depositManager;
this.authorizationService = authorizationService;
}
@RequestMapping(method = RequestMethod.GET, value = {"/repos"})
public @ResponseBody
ResponseEntity<ResponseItem<List<RepositoryConfig>>> getAvailableRepos(@ClaimedAuthorities(claims = {Authorities.ADMIN, Authorities.MANAGER, Authorities.USER, Authorities.ANONYMOUS}) Principal principal) {
ResponseEntity<ResponseItem<List<RepositoryConfig>>> getAvailableRepos() {
this.authorizationService.authorizeForce(Permission.AdminRole, Permission.ManagerRole, Permission.UserRole, Permission.AnonymousRole);
List<RepositoryConfig> ids = this.depositManager.getAvailableRepos();
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List<RepositoryConfig>>().status(ApiMessageCode.NO_MESSAGE).payload(ids));
}
@RequestMapping(method = RequestMethod.POST, value = {"/getAccessToken"})
public @ResponseBody
ResponseEntity<ResponseItem<String>> getAccessToken(@RequestBody DepositCode depositCode, @ClaimedAuthorities(claims = {Authorities.ADMIN, Authorities.MANAGER, Authorities.USER, Authorities.ANONYMOUS}) Principal principal) throws Exception {
ResponseEntity<ResponseItem<String>> getAccessToken(@RequestBody DepositCode depositCode) throws Exception {
this.authorizationService.authorizeForce(Permission.AdminRole, Permission.ManagerRole, Permission.UserRole, Permission.AnonymousRole);
String accessToken = this.depositManager.authenticate(depositCode.getRepositoryId(), depositCode.getCode());
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<String>().status(ApiMessageCode.NO_MESSAGE).payload(accessToken));
}
@RequestMapping(method = RequestMethod.POST, value = {"/createDoi"})
public @ResponseBody
ResponseEntity<ResponseItem<Doi>> createDoi(@RequestBody DepositRequest depositRequest, @ClaimedAuthorities(claims = {Authorities.ADMIN, Authorities.MANAGER, Authorities.USER, Authorities.ANONYMOUS}) Principal principal) {
ResponseEntity<ResponseItem<Doi>> createDoi(@RequestBody DepositRequest depositRequest) {
this.authorizationService.authorizeForce(Permission.AdminRole, Permission.ManagerRole, Permission.UserRole, Permission.AnonymousRole);
try {
Doi doi = this.depositManager.deposit(depositRequest, principal);
Doi doi = this.depositManager.deposit(depositRequest);
if(doi != null){
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<Doi>().status(ApiMessageCode.SUCCESS_MESSAGE).message("Successfully created DOI for Data Datamanagement Plan in question.").payload(doi));
}
@ -67,7 +73,8 @@ public class DepositController extends BaseController {
@RequestMapping(method = RequestMethod.GET, value = {"/logo/{repositoryId}"})
public @ResponseBody
ResponseEntity<ResponseItem<String>> getLogo(@PathVariable("repositoryId") String repositoryId, @ClaimedAuthorities(claims = {Authorities.ADMIN, Authorities.MANAGER, Authorities.USER, Authorities.ANONYMOUS}) Principal principal) {
ResponseEntity<ResponseItem<String>> getLogo(@PathVariable("repositoryId") String repositoryId) {
this.authorizationService.authorizeForce(Permission.AdminRole, Permission.ManagerRole, Permission.UserRole, Permission.AnonymousRole);
try {
String encodedLogo = this.depositManager.getRepositoryLogo(repositoryId);
if(encodedLogo != null){

View File

@ -1,11 +1,12 @@
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.models.data.security.Principal;
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;
@ -13,16 +14,20 @@ 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) {
public EmailConfirmation(EmailConfirmationManager emailConfirmationManager, AuthorizationService authorizationService) {
this.emailConfirmationManager = emailConfirmationManager;
this.authorizationService = authorizationService;
}
@Transactional
@ -33,7 +38,7 @@ public class EmailConfirmation {
this.emailConfirmationManager.confirmEmail(token);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE));
} catch
(HasConfirmedEmailException | TokenExpiredException ex) {
(HasConfirmedEmailException | TokenExpiredException | InvalidApplicationException ex) {
if (ex instanceof TokenExpiredException) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem().status(ApiMessageCode.NO_MESSAGE));
} else {
@ -45,9 +50,11 @@ public class EmailConfirmation {
@Transactional
@RequestMapping(method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity sendConfirmatioEmail(@RequestBody String email, Principal principal) {
ResponseEntity sendConfirmatioEmail(@RequestBody String email) {
this.authorizationService.authorizeForce(Permission.AuthenticatedRole);
try {
this.emailConfirmationManager.sendConfirmationEmail(email, principal);
this.emailConfirmationManager.sendConfirmationEmail(email);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE));
} catch (Exception ex) {
if (ex instanceof HasConfirmedEmailException) {

View File

@ -14,6 +14,8 @@ import org.springframework.web.bind.annotation.*;
import jakarta.transaction.Transactional;
import javax.management.InvalidApplicationException;
@RestController
@CrossOrigin
@RequestMapping(value = "api/emailMergeConfirmation")
@ -34,7 +36,7 @@ public class EmailMergeConfirmation {
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) {
(HasConfirmedEmailException | TokenExpiredException | InvalidApplicationException ex) {
if (ex instanceof TokenExpiredException) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem<String>().status(ApiMessageCode.NO_MESSAGE));
} else {

View File

@ -14,6 +14,8 @@ import org.springframework.web.bind.annotation.*;
import jakarta.transaction.Transactional;
import javax.management.InvalidApplicationException;
@RestController
@CrossOrigin
@RequestMapping(value = "api/emailUnlinkConfirmation")
@ -33,7 +35,7 @@ public class EmailUnlinkConfirmation {
try {
this.unlinkEmailConfirmationManager.confirmEmail(token);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE));
} catch (TokenExpiredException | HasConfirmedEmailException ex) {
} catch (TokenExpiredException | HasConfirmedEmailException | InvalidApplicationException ex) {
if (ex instanceof TokenExpiredException) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem().status(ApiMessageCode.NO_MESSAGE));
}

View File

@ -1,5 +1,6 @@
package eu.eudat.controllers;
import eu.eudat.authorization.Permission;
import eu.eudat.data.old.ExternalDataset;
import eu.eudat.data.query.items.table.externaldataset.ExternalDatasetTableRequest;
import eu.eudat.logic.managers.ExternalDatasetManager;
@ -9,14 +10,15 @@ import eu.eudat.logic.services.ApiContext;
import eu.eudat.models.data.externaldataset.ExternalDatasetListingModel;
import eu.eudat.models.data.helpers.common.DataTableData;
import eu.eudat.models.data.helpers.responses.ResponseItem;
import eu.eudat.models.data.security.Principal;
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 javax.management.InvalidApplicationException;
import java.util.List;
import java.util.UUID;
@ -27,16 +29,20 @@ import java.util.UUID;
public class ExternalDatasets extends BaseController {
private ExternalDatasetManager externalDatasetManager;
private final AuthorizationService authorizationService;
@Autowired
public ExternalDatasets(ApiContext apiContext, ExternalDatasetManager externalDatasetManager) {
public ExternalDatasets(ApiContext apiContext, ExternalDatasetManager externalDatasetManager, AuthorizationService authorizationService) {
super(apiContext);
this.externalDatasetManager = externalDatasetManager;
this.authorizationService = authorizationService;
}
@RequestMapping(method = RequestMethod.POST, value = {"/externaldatasets/getPaged"}, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<DataTableData<ExternalDatasetListingModel>>> getPaged(@RequestBody ExternalDatasetTableRequest datasetTableRequest, Principal principal) throws Exception {
ResponseEntity<ResponseItem<DataTableData<ExternalDatasetListingModel>>> getPaged(@RequestBody ExternalDatasetTableRequest datasetTableRequest) throws Exception {
this.authorizationService.authorizeForce(Permission.AuthenticatedRole);
DataTableData<ExternalDatasetListingModel> dataTable = externalDatasetManager.getPaged(datasetTableRequest);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DataTableData<ExternalDatasetListingModel>>().status(ApiMessageCode.NO_MESSAGE).payload(dataTable));
}
@ -44,15 +50,19 @@ public class ExternalDatasets extends BaseController {
@RequestMapping(method = RequestMethod.GET, value = {"/external/datasets"}, produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<List<ExternalDatasetListingModel>>> getWithExternal(
@RequestParam(value = "query", required = false) String query, @RequestParam(value = "type", required = false) String type, Principal principal
) throws NoURLFound, InstantiationException, HugeResultSet, IllegalAccessException {
List<ExternalDatasetListingModel> dataTable = externalDatasetManager.getWithExternal(query, type, principal);
@RequestParam(value = "query", required = false) String query, @RequestParam(value = "type", required = false) String type
) throws NoURLFound, InstantiationException, HugeResultSet, IllegalAccessException, InvalidApplicationException {
this.authorizationService.authorizeForce(Permission.AuthenticatedRole);
List<ExternalDatasetListingModel> dataTable = externalDatasetManager.getWithExternal(query, type);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List<ExternalDatasetListingModel>>().payload(dataTable).status(ApiMessageCode.NO_MESSAGE));
}
@RequestMapping(method = RequestMethod.POST, value = {"/externaldatasets/getSingle/{id}"}, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseItem<ExternalDatasetListingModel> getWithExternal(@PathVariable UUID id, Principal principal) throws NoURLFound, InstantiationException, HugeResultSet, IllegalAccessException {
ResponseItem<ExternalDatasetListingModel> getWithExternal(@PathVariable UUID id) throws NoURLFound, InstantiationException, HugeResultSet, IllegalAccessException, InvalidApplicationException {
this.authorizationService.authorizeForce(Permission.AuthenticatedRole);
ExternalDatasetListingModel externalDatasetModel = externalDatasetManager.getSingle(id);
return new ResponseItem<ExternalDatasetListingModel>().payload(externalDatasetModel).status(ApiMessageCode.NO_MESSAGE);
}
@ -60,8 +70,10 @@ public class ExternalDatasets extends BaseController {
@Transactional
@RequestMapping(method = RequestMethod.POST, value = {"/externaldatasets"}, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<ExternalDatasetListingModel>> create(@RequestBody eu.eudat.models.data.externaldataset.ExternalDatasetModel externalDatasetModel, Principal principal) throws Exception {
ExternalDataset externalDataset = this.externalDatasetManager.create(externalDatasetModel, principal);
ResponseEntity<ResponseItem<ExternalDatasetListingModel>> create(@RequestBody eu.eudat.models.data.externaldataset.ExternalDatasetModel externalDatasetModel) throws Exception {
this.authorizationService.authorizeForce(Permission.AuthenticatedRole);
ExternalDataset externalDataset = this.externalDatasetManager.create(externalDatasetModel);
ExternalDatasetListingModel externalDatasetListingModel = new ExternalDatasetListingModel().fromDataModel(externalDataset);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<ExternalDatasetListingModel>().payload(externalDatasetListingModel).status(ApiMessageCode.SUCCESS_MESSAGE));
}

View File

@ -3,11 +3,12 @@ package eu.eudat.controllers;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import eu.eudat.authorization.Permission;
import eu.eudat.commons.scope.user.UserScope;
import eu.eudat.data.old.Dataset;
import eu.eudat.data.old.FileUpload;
import eu.eudat.exceptions.security.UnauthorisedException;
import eu.eudat.logic.managers.DatasetProfileManager;
import eu.eudat.logic.security.claims.ClaimedAuthorities;
import eu.eudat.logic.services.ApiContext;
import eu.eudat.logic.services.operations.DatabaseRepository;
import eu.eudat.logic.utilities.documents.helpers.FileEnvelope;
@ -15,9 +16,8 @@ import eu.eudat.logic.utilities.json.JsonSearcher;
import eu.eudat.models.HintedModelFactory;
import eu.eudat.models.data.datasetwizard.DatasetWizardModel;
import eu.eudat.models.data.helpers.responses.ResponseItem;
import eu.eudat.models.data.security.Principal;
import eu.eudat.types.ApiMessageCode;
import eu.eudat.types.Authorities;
import gr.cite.commons.web.authz.service.AuthorizationService;
import org.apache.poi.util.IOUtils;
import org.json.JSONArray;
import org.json.JSONObject;
@ -31,6 +31,8 @@ import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import jakarta.transaction.Transactional;
import javax.management.InvalidApplicationException;
import java.io.*;
import java.nio.file.Files;
import java.util.*;
@ -45,19 +47,24 @@ public class FileController {
private DatasetProfileManager datasetProfileManager;
private final Environment environment;
private DatabaseRepository databaseRepository;
private final AuthorizationService authorizationService;
private final UserScope userScope;
@Autowired
public FileController(DatasetProfileManager datasetProfileManager, Environment environment, ApiContext apiContext) {
public FileController(DatasetProfileManager datasetProfileManager, Environment environment, ApiContext apiContext, AuthorizationService authorizationService, UserScope userScope) {
this.datasetProfileManager = datasetProfileManager;
this.environment = environment;
this.databaseRepository = apiContext.getOperationsContext().getDatabaseRepository();
this.authorizationService = authorizationService;
this.userScope = userScope;
}
@RequestMapping(method = RequestMethod.POST, value = {"/upload"})
public ResponseEntity<ResponseItem<String>> upload(
@RequestParam("file") MultipartFile file, @RequestParam("datasetProfileId") String datasetProfileId, @RequestParam("fieldId") String fieldId,
@ClaimedAuthorities(claims = {Authorities.ADMIN, Authorities.MANAGER, Authorities.USER}) Principal principal)
throws IllegalAccessException, IOException {
@RequestParam("file") MultipartFile file, @RequestParam("datasetProfileId") String datasetProfileId, @RequestParam("fieldId") String fieldId)
throws IllegalAccessException, IOException, InvalidApplicationException {
this.authorizationService.authorizeForce(Permission.AdminRole, Permission.ManagerRole, Permission.UserRole);
String uuid = UUID.randomUUID().toString();
eu.eudat.models.data.admin.composite.DatasetProfile datasetprofile = this.datasetProfileManager.getDatasetProfile(datasetProfileId);
@ -135,9 +142,10 @@ public class FileController {
@Transactional
@RequestMapping(method = RequestMethod.GET, value = {"{id}"}, produces = "application/json")
public @ResponseBody
ResponseEntity download(@PathVariable String id
,@ClaimedAuthorities(claims = {Authorities.ADMIN, Authorities.MANAGER, Authorities.USER, Authorities.ANONYMOUS}) Principal principal
) throws IOException {
ResponseEntity download(@PathVariable String id) throws IOException, InvalidApplicationException {
this.authorizationService.authorizeForce(Permission.AdminRole, Permission.ManagerRole, Permission.UserRole, Permission.AnonymousRole);
FileUpload fileUpload = databaseRepository.getFileUploadDao().find(UUID.fromString(id));
if(fileUpload == null) {
throw new NoSuchElementException("File with id "+id+" not found");
@ -149,7 +157,7 @@ public class FileController {
throw new NoSuchElementException("No dataset with id " + fileUpload.getEntityId() + " found. This dataset was related to the file with id " + id);
}
if (!datasetEntity.getDmp().isPublic() && datasetEntity.getDmp().getUsers()
.stream().filter(userInfo -> userInfo.getUser().getId() == principal.getId())
.stream().filter(userInfo -> userInfo.getUser().getId() == this.userScope.getUserIdSafe())
.collect(Collectors.toList()).size() == 0)
throw new UnauthorisedException();
}

View File

@ -1,5 +1,6 @@
package eu.eudat.controllers;
import eu.eudat.authorization.Permission;
import eu.eudat.data.query.items.item.funder.FunderCriteriaRequest;
import eu.eudat.logic.managers.FunderManager;
import eu.eudat.logic.proxy.config.exceptions.HugeResultSet;
@ -7,12 +8,13 @@ import eu.eudat.logic.proxy.config.exceptions.NoURLFound;
import eu.eudat.logic.services.ApiContext;
import eu.eudat.models.data.funder.Funder;
import eu.eudat.models.data.helpers.responses.ResponseItem;
import eu.eudat.models.data.security.Principal;
import eu.eudat.types.ApiMessageCode;
import gr.cite.commons.web.authz.service.AuthorizationService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.management.InvalidApplicationException;
import java.util.List;
@RestController
@ -20,16 +22,20 @@ import java.util.List;
@RequestMapping(value = {"/api/funders/"})
public class Funders extends BaseController {
private FunderManager funderManager;
private final AuthorizationService authorizationService;
public Funders(ApiContext apiContext, FunderManager funderManager) {
public Funders(ApiContext apiContext, FunderManager funderManager, AuthorizationService authorizationService) {
super(apiContext);
this.funderManager = funderManager;
this.authorizationService = authorizationService;
}
@RequestMapping(method = RequestMethod.POST, value = {"/external"}, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<List<Funder>>> getWithExternal(@RequestBody FunderCriteriaRequest funderCriteria, Principal principal) throws NoURLFound, InstantiationException, HugeResultSet, IllegalAccessException {
List<Funder> dataTable = this.funderManager.getCriteriaWithExternal(funderCriteria, principal);
ResponseEntity<ResponseItem<List<Funder>>> getWithExternal(@RequestBody FunderCriteriaRequest funderCriteria) throws NoURLFound, InstantiationException, HugeResultSet, IllegalAccessException, InvalidApplicationException {
this.authorizationService.authorizeForce(Permission.AuthenticatedRole);
List<Funder> dataTable = this.funderManager.getCriteriaWithExternal(funderCriteria);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List<eu.eudat.models.data.funder.Funder>>().payload(dataTable).status(ApiMessageCode.NO_MESSAGE));
}
}

View File

@ -1,27 +1,26 @@
package eu.eudat.controllers;
import eu.eudat.authorization.Permission;
import eu.eudat.data.query.items.item.grant.GrantCriteriaRequest;
import eu.eudat.data.query.items.table.grant.GrantTableRequest;
import eu.eudat.logic.managers.GrantManager;
import eu.eudat.logic.proxy.config.exceptions.HugeResultSet;
import eu.eudat.logic.proxy.config.exceptions.NoURLFound;
import eu.eudat.logic.security.claims.ClaimedAuthorities;
import eu.eudat.logic.services.ApiContext;
import eu.eudat.models.data.helpers.common.DataTableData;
import eu.eudat.models.data.helpers.responses.ResponseItem;
import eu.eudat.models.data.grant.GrantListingModel;
import eu.eudat.models.data.security.Principal;
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.validation.Valid;
import javax.management.InvalidApplicationException;
import java.util.List;
import static eu.eudat.types.Authorities.ANONYMOUS;
@RestController
@ -29,17 +28,21 @@ import static eu.eudat.types.Authorities.ANONYMOUS;
@RequestMapping(value = {"/api/grants/"})
public class Grants extends BaseController {
private GrantManager grantManager;
private final AuthorizationService authorizationService;
@Autowired
public Grants(ApiContext apiContext, GrantManager grantManager) {
public Grants(ApiContext apiContext, GrantManager grantManager, AuthorizationService authorizationService) {
super(apiContext);
this.grantManager = grantManager;
this.authorizationService = authorizationService;
}
@RequestMapping(method = RequestMethod.POST, value = {"/paged"}, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<DataTableData<GrantListingModel>>> getPaged(@Valid @RequestBody GrantTableRequest grantTableRequest, @RequestParam String fieldsGroup, Principal principal) throws Exception {
DataTableData<eu.eudat.models.data.grant.GrantListingModel> dataTable = this.grantManager.getPaged(grantTableRequest, principal, fieldsGroup);
ResponseEntity<ResponseItem<DataTableData<GrantListingModel>>> getPaged(@Valid @RequestBody GrantTableRequest grantTableRequest, @RequestParam String fieldsGroup) throws Exception {
this.authorizationService.authorizeForce(Permission.AuthenticatedRole);
DataTableData<eu.eudat.models.data.grant.GrantListingModel> dataTable = this.grantManager.getPaged(grantTableRequest, fieldsGroup);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DataTableData<eu.eudat.models.data.grant.GrantListingModel>>().payload(dataTable).status(ApiMessageCode.NO_MESSAGE));
}
@ -52,7 +55,9 @@ public class Grants extends BaseController {
@RequestMapping(method = RequestMethod.GET, value = {"{id}"}, produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<eu.eudat.models.data.grant.Grant>> getSingle(@PathVariable String id, Principal principal) throws IllegalAccessException, InstantiationException {
ResponseEntity<ResponseItem<eu.eudat.models.data.grant.Grant>> getSingle(@PathVariable String id) throws IllegalAccessException, InstantiationException, InvalidApplicationException {
this.authorizationService.authorizeForce(Permission.AuthenticatedRole);
eu.eudat.models.data.grant.Grant grant = this.grantManager.getSingle(id);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<eu.eudat.models.data.grant.Grant>().payload(grant).status(ApiMessageCode.NO_MESSAGE));
}
@ -60,7 +65,7 @@ public class Grants extends BaseController {
/*@Transactional
@RequestMapping(method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<Grant>> addGrant(@Valid @RequestBody eu.eudat.models.data.grant.Grant grant, Principal principal) throws IOException, ParseException {
ResponseEntity<ResponseItem<Grant>> addGrant(@Valid @RequestBody eu.eudat.models.data.grant.Grant grant) throws IOException, ParseException {
this.grantManager.createOrUpdate(grant, principal);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<eu.eudat.data.old.Grant>().status(ApiMessageCode.SUCCESS_MESSAGE).message("Created"));
}*/
@ -68,21 +73,25 @@ public class Grants extends BaseController {
/*@Transactional
@RequestMapping(method = RequestMethod.DELETE, value = {"{id}"}, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<Grant>> inactivate(@PathVariable String id, Principal principal) throws IllegalAccessException, InstantiationException {
ResponseEntity<ResponseItem<Grant>> inactivate(@PathVariable String id) throws IllegalAccessException, InstantiationException {
this.grantManager.inactivate(id);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<eu.eudat.data.old.Grant>().status(ApiMessageCode.SUCCESS_MESSAGE));
}*/
@RequestMapping(method = RequestMethod.POST, value = {"/external"}, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<List<eu.eudat.models.data.grant.Grant>>> getWithExternal(@RequestBody GrantCriteriaRequest grantCriteria, Principal principal) throws NoURLFound, InstantiationException, HugeResultSet, IllegalAccessException {
List<eu.eudat.models.data.grant.Grant> dataTable = this.grantManager.getCriteriaWithExternal(grantCriteria, principal);
ResponseEntity<ResponseItem<List<eu.eudat.models.data.grant.Grant>>> getWithExternal(@RequestBody GrantCriteriaRequest grantCriteria) throws NoURLFound, InstantiationException, HugeResultSet, IllegalAccessException, InvalidApplicationException {
this.authorizationService.authorizeForce(Permission.AuthenticatedRole);
List<eu.eudat.models.data.grant.Grant> dataTable = this.grantManager.getCriteriaWithExternal(grantCriteria);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List<eu.eudat.models.data.grant.Grant>>().payload(dataTable).status(ApiMessageCode.NO_MESSAGE));
}
@RequestMapping(method = RequestMethod.POST, value = {"get"}, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<List<eu.eudat.models.data.grant.Grant>>> get(@RequestBody GrantCriteriaRequest grantCriteria, @ClaimedAuthorities(claims = {ANONYMOUS}) Principal principal) throws NoURLFound, InstantiationException, HugeResultSet, IllegalAccessException {
ResponseEntity<ResponseItem<List<eu.eudat.models.data.grant.Grant>>> get(@RequestBody GrantCriteriaRequest grantCriteria) throws NoURLFound, InstantiationException, HugeResultSet, IllegalAccessException, InvalidApplicationException {
this.authorizationService.authorizeForce(Permission.AnonymousRole);
List<eu.eudat.models.data.grant.Grant> dataTable = this.grantManager.getCriteria(grantCriteria);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List<eu.eudat.models.data.grant.Grant>>().payload(dataTable).status(ApiMessageCode.NO_MESSAGE));
}

View File

@ -1,18 +1,20 @@
package eu.eudat.controllers;
import eu.eudat.authorization.Permission;
import eu.eudat.logic.managers.DataRepositoryManager;
import eu.eudat.logic.proxy.config.exceptions.HugeResultSet;
import eu.eudat.logic.proxy.config.exceptions.NoURLFound;
import eu.eudat.logic.services.ApiContext;
import eu.eudat.models.data.datarepository.DataRepositoryModel;
import eu.eudat.models.data.helpers.responses.ResponseItem;
import eu.eudat.models.data.security.Principal;
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 javax.management.InvalidApplicationException;
import java.util.List;
@ -22,19 +24,23 @@ import java.util.List;
public class JournalsController extends BaseController {
private DataRepositoryManager dataRepositoryManager;
private final AuthorizationService authorizationService;
@Autowired
public JournalsController(ApiContext apiContext, DataRepositoryManager dataRepositoryManager) {
public JournalsController(ApiContext apiContext, DataRepositoryManager dataRepositoryManager, AuthorizationService authorizationService) {
super(apiContext);
this.dataRepositoryManager = dataRepositoryManager;
this.authorizationService = authorizationService;
}
@RequestMapping(method = RequestMethod.GET, produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<List<DataRepositoryModel>>> listExternalDataRepositories(
@RequestParam(value = "query", required = false) String query, @RequestParam(value = "type", required = false) String type, Principal principal
) throws HugeResultSet, NoURLFound {
List<DataRepositoryModel> dataRepositoryModels = this.dataRepositoryManager.getJournals(query, type, principal);
@RequestParam(value = "query", required = false) String query, @RequestParam(value = "type", required = false) String type
) throws HugeResultSet, NoURLFound, InvalidApplicationException {
this.authorizationService.authorizeForce(Permission.AuthenticatedRole);
List<DataRepositoryModel> dataRepositoryModels = this.dataRepositoryManager.getJournals(query, type);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List<DataRepositoryModel>>().status(ApiMessageCode.NO_MESSAGE).payload(dataRepositoryModels));
}

View File

@ -1,11 +1,8 @@
package eu.eudat.controllers;
import eu.eudat.authorization.Permission;
import eu.eudat.logic.security.claims.ClaimedAuthorities;
import eu.eudat.models.data.helpers.responses.ResponseItem;
import eu.eudat.models.data.security.Principal;
import eu.eudat.types.ApiMessageCode;
import eu.eudat.types.Authorities;
import gr.cite.commons.web.authz.service.AuthorizationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;

View File

@ -1,13 +1,14 @@
package eu.eudat.controllers;
import eu.eudat.authorization.Permission;
import eu.eudat.logic.managers.LicenseManager;
import eu.eudat.logic.proxy.config.exceptions.HugeResultSet;
import eu.eudat.logic.proxy.config.exceptions.NoURLFound;
import eu.eudat.logic.services.ApiContext;
import eu.eudat.models.data.helpers.responses.ResponseItem;
import eu.eudat.models.data.license.LicenseModel;
import eu.eudat.models.data.security.Principal;
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;
@ -22,18 +23,22 @@ import java.util.List;
public class Licenses extends BaseController {
private LicenseManager licenseManager;
private final AuthorizationService authorizationService;
@Autowired
public Licenses(ApiContext apiContext, LicenseManager licenseManager) {
public Licenses(ApiContext apiContext, LicenseManager licenseManager, AuthorizationService authorizationService) {
super(apiContext);
this.licenseManager = licenseManager;
this.authorizationService = authorizationService;
}
@RequestMapping(method = RequestMethod.GET, produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<List<LicenseModel>>> listExternalLicenses(
@RequestParam(value = "query", required = false) String query, @RequestParam(value = "type", required = false) String type, Principal principal
@RequestParam(value = "query", required = false) String query, @RequestParam(value = "type", required = false) String type
) throws HugeResultSet, NoURLFound {
this.authorizationService.authorizeForce(Permission.AuthenticatedRole);
List<LicenseModel> licenseModels = this.licenseManager.getLicenses(query, type);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List<LicenseModel>>().status(ApiMessageCode.NO_MESSAGE).payload(licenseModels));
}

View File

@ -1,10 +1,11 @@
package eu.eudat.controllers;
import eu.eudat.authorization.Permission;
import eu.eudat.logic.managers.LockManager;
import eu.eudat.models.data.helpers.responses.ResponseItem;
import eu.eudat.models.data.lock.Lock;
import eu.eudat.models.data.security.Principal;
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;
@ -19,36 +20,46 @@ import java.util.UUID;
public class LockController {
private LockManager lockManager;
private final AuthorizationService authorizationService;
@Autowired
public LockController(LockManager lockManager) {
public LockController(LockManager lockManager, AuthorizationService authorizationService) {
this.lockManager = lockManager;
this.authorizationService = authorizationService;
}
@Transactional
@RequestMapping(method = RequestMethod.GET, path = "target/status/{id}")
public @ResponseBody ResponseEntity<ResponseItem<Boolean>> getLocked(@PathVariable String id, Principal principal) throws Exception {
boolean locked = this.lockManager.isLocked(id, principal);
public @ResponseBody ResponseEntity<ResponseItem<Boolean>> getLocked(@PathVariable String id) throws Exception {
this.authorizationService.authorizeForce(Permission.AuthenticatedRole);
boolean locked = this.lockManager.isLocked(id);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<Boolean>().status(ApiMessageCode.SUCCESS_MESSAGE).message("locked").payload(locked));
}
@Transactional
@RequestMapping(method = RequestMethod.DELETE, path = "target/unlock/{id}")
public @ResponseBody ResponseEntity<ResponseItem<String>> unlock(@PathVariable String id, Principal principal) throws Exception {
this.lockManager.unlock(id, principal);
public @ResponseBody ResponseEntity<ResponseItem<String>> unlock(@PathVariable String id) throws Exception {
this.authorizationService.authorizeForce(Permission.AuthenticatedRole);
this.lockManager.unlock(id);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<String>().status(ApiMessageCode.SUCCESS_MESSAGE).message("Created").payload("Lock Removed"));
}
@Transactional
@RequestMapping(method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
public @ResponseBody ResponseEntity<ResponseItem<UUID>> createOrUpdate(@RequestBody Lock lock, Principal principal) throws Exception {
eu.eudat.data.old.Lock result = this.lockManager.createOrUpdate(lock, principal);
public @ResponseBody ResponseEntity<ResponseItem<UUID>> createOrUpdate(@RequestBody Lock lock) throws Exception {
this.authorizationService.authorizeForce(Permission.AuthenticatedRole);
eu.eudat.data.old.Lock result = this.lockManager.createOrUpdate(lock);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<UUID>().status(ApiMessageCode.SUCCESS_MESSAGE).message("Created").payload(result.getId()));
}
@RequestMapping(method = RequestMethod.GET, path = "target/{id}")
public @ResponseBody ResponseEntity<ResponseItem<Lock>> getSingle(@PathVariable String id, Principal principal) throws Exception {
Lock lock = this.lockManager.getFromTarget(id, principal);
public @ResponseBody ResponseEntity<ResponseItem<Lock>> getSingle(@PathVariable String id) throws Exception {
this.authorizationService.authorizeForce(Permission.AuthenticatedRole);
Lock lock = this.lockManager.getFromTarget(id);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<Lock>().status(ApiMessageCode.NO_MESSAGE).payload(lock));
}
}

View File

@ -1,13 +1,11 @@
package eu.eudat.controllers;
import eu.eudat.exceptions.datasetprofile.DatasetProfileNewVersionException;
import eu.eudat.authorization.Permission;
import eu.eudat.logic.managers.DatasetProfileManager;
import eu.eudat.logic.security.claims.ClaimedAuthorities;
import eu.eudat.logic.services.ApiContext;
import eu.eudat.models.data.admin.composite.DatasetProfile;
import eu.eudat.models.data.helpers.responses.ResponseItem;
import eu.eudat.models.data.security.Principal;
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;
@ -22,17 +20,20 @@ import static eu.eudat.types.Authorities.ADMIN;
@RequestMapping(value = {"/api/management/"})
public class ManagementController extends BaseController {
private DatasetProfileManager datasetProfileManager;
private final DatasetProfileManager datasetProfileManager;
private final AuthorizationService authorizationService;
@Autowired
public ManagementController(ApiContext apiContext, DatasetProfileManager datasetProfileManager){
public ManagementController(ApiContext apiContext, DatasetProfileManager datasetProfileManager, AuthorizationService authorizationService){
super(apiContext);
this.datasetProfileManager = datasetProfileManager;
this.authorizationService = authorizationService;
}
@Transactional
@RequestMapping(method = RequestMethod.POST, value = {"/addSemantics"})
public ResponseEntity addSemanticsInDatasetProfiles(@ClaimedAuthorities(claims = {ADMIN}) Principal principal) throws Exception {
public ResponseEntity addSemanticsInDatasetProfiles() throws Exception {
this.authorizationService.authorizeForce(Permission.AdminRole);
try {
this.datasetProfileManager.addSemanticsInDatasetProfiles();
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<Void>().status(ApiMessageCode.SUCCESS_MESSAGE));
@ -43,7 +44,8 @@ public class ManagementController extends BaseController {
@Transactional
@RequestMapping(method = RequestMethod.POST, value = {"/addRdaInSemantics"})
public ResponseEntity addRdaInSemanticsInDatasetProfiles(@ClaimedAuthorities(claims = {ADMIN}) Principal principal) throws Exception {
public ResponseEntity addRdaInSemanticsInDatasetProfiles() throws Exception {
this.authorizationService.authorizeForce(Permission.AdminRole);
try {
this.datasetProfileManager.addRdaInSemanticsInDatasetProfiles();
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<Void>().status(ApiMessageCode.SUCCESS_MESSAGE));

View File

@ -1,5 +1,6 @@
package eu.eudat.controllers;
import eu.eudat.authorization.Permission;
import eu.eudat.data.query.items.table.organisations.OrganisationsTableRequest;
import eu.eudat.logic.managers.OrganisationsManager;
import eu.eudat.logic.proxy.config.exceptions.HugeResultSet;
@ -8,8 +9,8 @@ import eu.eudat.logic.services.ApiContext;
import eu.eudat.models.data.dmp.Organisation;
import eu.eudat.models.data.helpers.common.DataTableData;
import eu.eudat.models.data.helpers.responses.ResponseItem;
import eu.eudat.models.data.security.Principal;
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;
@ -25,12 +26,15 @@ import java.util.List;
public class Organisations extends BaseController {
private OrganisationsManager organisationsManager;
private final AuthorizationService authorizationService;
private ApiContext apiContext;
@Autowired
public Organisations(ApiContext apiContext, OrganisationsManager organisationsManager) {
public Organisations(ApiContext apiContext, OrganisationsManager organisationsManager, AuthorizationService authorizationService, ApiContext apiContext1) {
super(apiContext);
this.organisationsManager = organisationsManager;
this.authorizationService = authorizationService;
this.apiContext = apiContext1;
}
@RequestMapping(method = RequestMethod.GET, value = {"/external/organisations"}, produces = "application/json")
@ -44,15 +48,19 @@ public class Organisations extends BaseController {
@RequestMapping(method = RequestMethod.POST, value = {"/general/organisations"}, produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<List<Organisation>>> listGeneralOrganisations(@RequestBody OrganisationsTableRequest organisationsTableRequest, Principal principal) throws Exception {
List<Organisation> organisations = organisationsManager.getWithExternal(organisationsTableRequest, principal);
ResponseEntity<ResponseItem<List<Organisation>>> listGeneralOrganisations(@RequestBody OrganisationsTableRequest organisationsTableRequest) throws Exception {
this.authorizationService.authorizeForce(Permission.AuthenticatedRole);
List<Organisation> organisations = organisationsManager.getWithExternal(organisationsTableRequest);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List<Organisation>>().payload(organisations).status(ApiMessageCode.NO_MESSAGE));
}
@RequestMapping(method = RequestMethod.POST, value = {"/internal/organisations"}, produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<DataTableData<Organisation>>> getPaged(@Valid @RequestBody OrganisationsTableRequest organisationsTableRequest, Principal principal) throws Exception{
DataTableData<Organisation> organisationDataTableData = this.organisationsManager.getPagedOrganisations(organisationsTableRequest, principal);
ResponseEntity<ResponseItem<DataTableData<Organisation>>> getPaged(@Valid @RequestBody OrganisationsTableRequest organisationsTableRequest) throws Exception{
this.authorizationService.authorizeForce(Permission.AuthenticatedRole);
DataTableData<Organisation> organisationDataTableData = this.organisationsManager.getPagedOrganisations(organisationsTableRequest);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DataTableData<Organisation>>().payload(organisationDataTableData).status(ApiMessageCode.NO_MESSAGE));
}

View File

@ -1,5 +1,6 @@
package eu.eudat.controllers;
import eu.eudat.authorization.Permission;
import eu.eudat.data.query.items.item.project.ProjectCriteriaRequest;
import eu.eudat.logic.managers.ProjectManager;
import eu.eudat.logic.proxy.config.exceptions.HugeResultSet;
@ -7,13 +8,14 @@ import eu.eudat.logic.proxy.config.exceptions.NoURLFound;
import eu.eudat.logic.services.ApiContext;
import eu.eudat.models.data.helpers.responses.ResponseItem;
import eu.eudat.models.data.project.Project;
import eu.eudat.models.data.security.Principal;
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 javax.management.InvalidApplicationException;
import java.util.List;
@RestController
@ -21,17 +23,21 @@ import java.util.List;
@RequestMapping(value = {"/api/projects/"})
public class Projects extends BaseController {
private ProjectManager projectManager;
private final AuthorizationService authorizationService;
@Autowired
public Projects(ApiContext apiContext, ProjectManager projectManager) {
public Projects(ApiContext apiContext, ProjectManager projectManager, AuthorizationService authorizationService) {
super(apiContext);
this.projectManager = projectManager;
this.authorizationService = authorizationService;
}
@RequestMapping(method = RequestMethod.POST, value = {"/external"}, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<List<Project>>> getWithExternal(@RequestBody ProjectCriteriaRequest projectCriteria, Principal principal) throws NoURLFound, InstantiationException, HugeResultSet, IllegalAccessException {
List<Project> dataTable = this.projectManager.getCriteriaWithExternal(projectCriteria, principal);
ResponseEntity<ResponseItem<List<Project>>> getWithExternal(@RequestBody ProjectCriteriaRequest projectCriteria) throws NoURLFound, InstantiationException, HugeResultSet, IllegalAccessException, InvalidApplicationException {
this.authorizationService.authorizeForce(Permission.AuthenticatedRole);
List<Project> dataTable = this.projectManager.getCriteriaWithExternal(projectCriteria);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List<eu.eudat.models.data.project.Project>>().payload(dataTable).status(ApiMessageCode.NO_MESSAGE));
}
}

View File

@ -1,18 +1,20 @@
package eu.eudat.controllers;
import eu.eudat.authorization.Permission;
import eu.eudat.logic.managers.DataRepositoryManager;
import eu.eudat.logic.proxy.config.exceptions.HugeResultSet;
import eu.eudat.logic.proxy.config.exceptions.NoURLFound;
import eu.eudat.logic.services.ApiContext;
import eu.eudat.models.data.datarepository.DataRepositoryModel;
import eu.eudat.models.data.helpers.responses.ResponseItem;
import eu.eudat.models.data.security.Principal;
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 javax.management.InvalidApplicationException;
import java.util.List;
@ -22,19 +24,23 @@ import java.util.List;
public class PubRepositoriesController extends BaseController {
private DataRepositoryManager dataRepositoryManager;
private final AuthorizationService authorizationService;
@Autowired
public PubRepositoriesController(ApiContext apiContext, DataRepositoryManager dataRepositoryManager) {
public PubRepositoriesController(ApiContext apiContext, DataRepositoryManager dataRepositoryManager, AuthorizationService authorizationService) {
super(apiContext);
this.dataRepositoryManager = dataRepositoryManager;
this.authorizationService = authorizationService;
}
@RequestMapping(method = RequestMethod.GET, produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<List<DataRepositoryModel>>> listExternalDataRepositories(
@RequestParam(value = "query", required = false) String query, @RequestParam(value = "type", required = false) String type, Principal principal
) throws HugeResultSet, NoURLFound {
List<DataRepositoryModel> dataRepositoryModels = this.dataRepositoryManager.getPubRepositories(query, type, principal);
@RequestParam(value = "query", required = false) String query, @RequestParam(value = "type", required = false) String type
) throws HugeResultSet, NoURLFound, InvalidApplicationException {
this.authorizationService.authorizeForce(Permission.AuthenticatedRole);
List<DataRepositoryModel> dataRepositoryModels = this.dataRepositoryManager.getPubRepositories(query, type);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List<DataRepositoryModel>>().status(ApiMessageCode.NO_MESSAGE).payload(dataRepositoryModels));
}

View File

@ -1,13 +1,14 @@
package eu.eudat.controllers;
import eu.eudat.authorization.Permission;
import eu.eudat.logic.managers.PublicationManager;
import eu.eudat.logic.proxy.config.exceptions.HugeResultSet;
import eu.eudat.logic.proxy.config.exceptions.NoURLFound;
import eu.eudat.logic.services.ApiContext;
import eu.eudat.models.data.helpers.responses.ResponseItem;
import eu.eudat.models.data.publication.PublicationModel;
import eu.eudat.models.data.security.Principal;
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;
@ -22,18 +23,22 @@ import java.util.List;
public class PublicationsController extends BaseController {
private PublicationManager publicationManager;
private final AuthorizationService authorizationService;
@Autowired
public PublicationsController(ApiContext apiContext, PublicationManager publicationManager) {
public PublicationsController(ApiContext apiContext, PublicationManager publicationManager, AuthorizationService authorizationService) {
super(apiContext);
this.publicationManager = publicationManager;
this.authorizationService = authorizationService;
}
@RequestMapping(method = RequestMethod.GET, produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<List<PublicationModel>>> listExternalPublications(
@RequestParam(value = "query", required = false) String query, @RequestParam(value = "type", required = false) String type, Principal principal
@RequestParam(value = "query", required = false) String query, @RequestParam(value = "type", required = false) String type
) throws HugeResultSet, NoURLFound {
this.authorizationService.authorizeForce(Permission.AuthenticatedRole);
List<PublicationModel> publicationModels = this.publicationManager.getPublications(query, type);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List<PublicationModel>>().status(ApiMessageCode.NO_MESSAGE).payload(publicationModels));
}

View File

@ -1,6 +1,8 @@
package eu.eudat.controllers;
import eu.eudat.authorization.Permission;
import eu.eudat.commons.scope.user.UserScope;
import eu.eudat.data.old.DescriptionTemplate;
import eu.eudat.data.old.DMP;
import eu.eudat.data.old.Funder;
@ -15,8 +17,8 @@ import eu.eudat.models.data.helpers.responses.ResponseItem;
import eu.eudat.models.data.quickwizard.DatasetCreateWizardModel;
import eu.eudat.models.data.quickwizard.DatasetDescriptionQuickWizardModel;
import eu.eudat.models.data.quickwizard.QuickWizardModel;
import eu.eudat.models.data.security.Principal;
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;
@ -32,18 +34,24 @@ public class QuickWizardController extends BaseController {
private QuickWizardManager quickWizardManager;
private DatasetManager datasetManager;
private final AuthorizationService authorizationService;
private final UserScope userScope;
@Autowired
public QuickWizardController(ApiContext apiContext, QuickWizardManager quickWizardManager, DatasetManager datasetManager) {
public QuickWizardController(ApiContext apiContext, QuickWizardManager quickWizardManager, DatasetManager datasetManager, AuthorizationService authorizationService, UserScope userScope) {
super(apiContext);
this.quickWizardManager = quickWizardManager;
this.datasetManager = datasetManager;
this.authorizationService = authorizationService;
this.userScope = userScope;
}
@Transactional
@RequestMapping(method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<QuickWizardModel>> addQuickWizardModel(@Valid @RequestBody QuickWizardModel quickWizard, Principal principal) throws Exception {
ResponseEntity<ResponseItem<QuickWizardModel>> addQuickWizardModel(@Valid @RequestBody QuickWizardModel quickWizard) throws Exception {
this.authorizationService.authorizeForce(Permission.AuthenticatedRole);
Funder funderEntity;
//Create Funder
@ -52,7 +60,7 @@ public class QuickWizardController extends BaseController {
} else if (quickWizard.getFunder().getExistFunder() == null && quickWizard.getFunder().getLabel() == null) {
funderEntity = null;
} else if (quickWizard.getFunder().getExistFunder() == null && quickWizard.getFunder().getLabel() != null) {
funderEntity = this.quickWizardManager.createOrUpdate(quickWizard.getFunder().toDataFunder(), principal);
funderEntity = this.quickWizardManager.createOrUpdate(quickWizard.getFunder().toDataFunder());
} else {
funderEntity = quickWizard.getFunder().getExistFunder().toDataModel();
}
@ -64,7 +72,7 @@ public class QuickWizardController extends BaseController {
} else if (quickWizard.getGrant().getExistGrant() == null && quickWizard.getGrant().getLabel() == null) {
grantEntity = null;
} else if (quickWizard.getGrant().getExistGrant() == null) {
grantEntity = this.quickWizardManager.createOrUpdate(quickWizard.getGrant().toDataGrant(), principal);
grantEntity = this.quickWizardManager.createOrUpdate(quickWizard.getGrant().toDataGrant());
} else {
grantEntity = quickWizard.getGrant().getExistGrant().toDataModel();
}
@ -75,22 +83,22 @@ public class QuickWizardController extends BaseController {
&& quickWizard.getProject().getLabel() == null) {
projectEntity = null;
} else if (quickWizard.getProject().getExistProject() == null && quickWizard.getProject().getLabel() != null) {
projectEntity = this.quickWizardManager.createOrUpdate(quickWizard.getProject().toDataProject(), principal);
projectEntity = this.quickWizardManager.createOrUpdate(quickWizard.getProject().toDataProject());
} else {
projectEntity = quickWizard.getProject().getExistProject().toDataModel();
}
//Create Dmp
DataManagementPlan dataManagementPlan = quickWizard.getDmp().toDataDmp(grantEntity, projectEntity, principal);
DMP dmpEntity = this.quickWizardManager.createOrUpdate(dataManagementPlan, funderEntity, principal);
DataManagementPlan dataManagementPlan = quickWizard.getDmp().toDataDmp(grantEntity, projectEntity, userScope);
DMP dmpEntity = this.quickWizardManager.createOrUpdate(dataManagementPlan, funderEntity);
//Create Datasets
quickWizard.getDmp().setId(dmpEntity.getId());
for (DatasetDescriptionQuickWizardModel dataset : quickWizard.getDatasets().getDatasetsList()) {
DataManagementPlan dmp = quickWizard.getDmp().toDataDmp(grantEntity, projectEntity, principal);
DataManagementPlan dmp = quickWizard.getDmp().toDataDmp(grantEntity, projectEntity, userScope);
DescriptionTemplate profile = quickWizard.getDmp().getDatasetProfile();
DatasetWizardModel datasetWizardModel = dataset.toDataModel(dmp, profile);
this.datasetManager.createOrUpdate(datasetWizardModel, principal);
this.datasetManager.createOrUpdate(datasetWizardModel);
}
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<QuickWizardModel>().status(ApiMessageCode.SUCCESS_MESSAGE).message("Created"));
@ -98,12 +106,14 @@ public class QuickWizardController extends BaseController {
@RequestMapping(method = RequestMethod.POST, value = {"/datasetcreate"}, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<DatasetCreateWizardModel>> addDatasetWizard(@RequestBody DatasetCreateWizardModel datasetCreateWizardModel, Principal principal) throws Exception{
ResponseEntity<ResponseItem<DatasetCreateWizardModel>> addDatasetWizard(@RequestBody DatasetCreateWizardModel datasetCreateWizardModel) throws Exception{
this.authorizationService.authorizeForce(Permission.AuthenticatedRole);
for(DatasetDescriptionQuickWizardModel dataset : datasetCreateWizardModel.getDatasets().getDatasetsList()){
DescriptionTemplate profile = new DescriptionTemplate();
profile.setId(datasetCreateWizardModel.getDmpMeta().getDatasetProfile().getId());
profile.setLabel(datasetCreateWizardModel.getDmpMeta().getDatasetProfile().getLabel());
this.datasetManager.createOrUpdate(dataset.toDataModel(datasetCreateWizardModel.getDmpMeta().getDmp(), profile), principal);
this.datasetManager.createOrUpdate(dataset.toDataModel(datasetCreateWizardModel.getDmpMeta().getDmp(), profile));
}
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DatasetCreateWizardModel>().status(ApiMessageCode.SUCCESS_MESSAGE).message("Dataset added!"));

View File

@ -1,5 +1,6 @@
package eu.eudat.controllers;
import eu.eudat.authorization.Permission;
import eu.eudat.data.old.Registry;
import eu.eudat.logic.managers.RegistryManager;
import eu.eudat.logic.proxy.config.exceptions.HugeResultSet;
@ -7,14 +8,15 @@ import eu.eudat.logic.proxy.config.exceptions.NoURLFound;
import eu.eudat.logic.services.ApiContext;
import eu.eudat.models.data.helpers.responses.ResponseItem;
import eu.eudat.models.data.registries.RegistryModel;
import eu.eudat.models.data.security.Principal;
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 javax.management.InvalidApplicationException;
import java.util.List;
@ -24,26 +26,32 @@ import java.util.List;
public class Registries extends BaseController {
private RegistryManager registryManager;
private final AuthorizationService authorizationService;
@Autowired
public Registries(ApiContext apiContext, RegistryManager registryManager) {
public Registries(ApiContext apiContext, RegistryManager registryManager, AuthorizationService authorizationService) {
super(apiContext);
this.registryManager = registryManager;
this.authorizationService = authorizationService;
}
@RequestMapping(method = RequestMethod.GET, value = {"/external/registries"}, produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<List<RegistryModel>>> listExternalRegistries(@RequestParam(value = "query", required = false) String query
, @RequestParam(value = "type", required = false) String type, Principal principal) throws HugeResultSet, NoURLFound {
List<RegistryModel> registryModels = this.registryManager.getRegistries(query, type, principal);
, @RequestParam(value = "type", required = false) String type) throws HugeResultSet, NoURLFound, InvalidApplicationException {
this.authorizationService.authorizeForce(Permission.AuthenticatedRole);
List<RegistryModel> registryModels = this.registryManager.getRegistries(query, type);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List<RegistryModel>>().payload(registryModels).status(ApiMessageCode.NO_MESSAGE));
}
@Transactional
@RequestMapping(method = RequestMethod.POST, value = {"/registries"}, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<RegistryModel>> create(@RequestBody RegistryModel registryModel, Principal principal) throws Exception {
Registry registry = this.registryManager.create(registryModel, principal);
ResponseEntity<ResponseItem<RegistryModel>> create(@RequestBody RegistryModel registryModel) throws Exception {
this.authorizationService.authorizeForce(Permission.AuthenticatedRole);
Registry registry = this.registryManager.create(registryModel);
RegistryModel registryModel1 = new RegistryModel().fromDataModel(registry);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<RegistryModel>().payload(registryModel1).status(ApiMessageCode.SUCCESS_MESSAGE));
}

View File

@ -1,23 +1,23 @@
package eu.eudat.controllers;
import eu.eudat.authorization.Permission;
import eu.eudat.data.query.items.item.researcher.ResearcherCriteriaRequest;
import eu.eudat.logic.managers.ResearcherManager;
import eu.eudat.logic.proxy.config.exceptions.HugeResultSet;
import eu.eudat.logic.proxy.config.exceptions.NoURLFound;
import eu.eudat.logic.services.ApiContext;
import eu.eudat.models.data.dmp.Researcher;
import eu.eudat.models.data.external.ResearchersExternalSourcesModel;
import eu.eudat.models.data.helpers.responses.ResponseItem;
import eu.eudat.models.data.security.Principal;
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 javax.management.InvalidApplicationException;
import java.util.List;
import java.util.Map;
@RestController
@ -27,24 +27,30 @@ import java.util.Map;
public class Researchers extends BaseController {
private ResearcherManager researcherManager;
private final AuthorizationService authorizationService;
@Autowired
public Researchers(ApiContext apiContext, ResearcherManager researcherManager) {
public Researchers(ApiContext apiContext, ResearcherManager researcherManager, AuthorizationService authorizationService) {
super(apiContext);
this.researcherManager = researcherManager;
this.authorizationService = authorizationService;
}
@RequestMapping(method = RequestMethod.POST, value = {"/getWithExternal"}, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<List<eu.eudat.models.data.dmp.Researcher>>> getWithExternal(@RequestBody ResearcherCriteriaRequest researcherCriteriaRequest, Principal principal) throws HugeResultSet, NoURLFound {
List<eu.eudat.models.data.dmp.Researcher> dataTable = this.researcherManager.getCriteriaWithExternal(researcherCriteriaRequest, principal);
ResponseEntity<ResponseItem<List<eu.eudat.models.data.dmp.Researcher>>> getWithExternal(@RequestBody ResearcherCriteriaRequest researcherCriteriaRequest) throws HugeResultSet, NoURLFound, InvalidApplicationException {
this.authorizationService.authorizeForce(Permission.AuthenticatedRole);
List<eu.eudat.models.data.dmp.Researcher> dataTable = this.researcherManager.getCriteriaWithExternal(researcherCriteriaRequest);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List<eu.eudat.models.data.dmp.Researcher>>().payload(dataTable).status(ApiMessageCode.NO_MESSAGE));
}
@Transactional
@RequestMapping(method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<Researcher>> create(@RequestBody eu.eudat.models.data.researcher.Researcher researcher, Principal principal) throws Exception {
this.researcherManager.create(researcher, principal);
ResponseEntity<ResponseItem<Researcher>> create(@RequestBody eu.eudat.models.data.researcher.Researcher researcher) throws Exception {
this.authorizationService.authorizeForce(Permission.AuthenticatedRole);
this.researcherManager.create(researcher);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<Researcher>().status(ApiMessageCode.SUCCESS_MESSAGE));
}

View File

@ -1,20 +1,22 @@
package eu.eudat.controllers;
import eu.eudat.authorization.Permission;
import eu.eudat.data.old.Service;
import eu.eudat.logic.managers.ServiceManager;
import eu.eudat.logic.proxy.config.exceptions.HugeResultSet;
import eu.eudat.logic.proxy.config.exceptions.NoURLFound;
import eu.eudat.logic.services.ApiContext;
import eu.eudat.models.data.helpers.responses.ResponseItem;
import eu.eudat.models.data.security.Principal;
import eu.eudat.models.data.services.ServiceModel;
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 javax.management.InvalidApplicationException;
import java.util.List;
@ -24,27 +26,31 @@ import java.util.List;
public class Services extends BaseController {
private ServiceManager serviceManager;
private final AuthorizationService authorizationService;
@Autowired
public Services(ApiContext apiContext, ServiceManager serviceManager) {
public Services(ApiContext apiContext, ServiceManager serviceManager, AuthorizationService authorizationService) {
super(apiContext);
this.serviceManager = serviceManager;
this.authorizationService = authorizationService;
}
@RequestMapping(method = RequestMethod.GET, value = {"/external/services"}, produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<List<ServiceModel>>> listExternalServices(
@RequestParam(value = "query", required = false) String query, @RequestParam(value = "type", required = false) String type, Principal principal
) throws HugeResultSet, NoURLFound {
List<ServiceModel> serviceModels = this.serviceManager.getServices(query, type, principal);
@RequestParam(value = "query", required = false) String query, @RequestParam(value = "type", required = false) String type
) throws HugeResultSet, NoURLFound, InvalidApplicationException {
this.authorizationService.authorizeForce(Permission.AuthenticatedRole);
List<ServiceModel> serviceModels = this.serviceManager.getServices(query, type);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List<ServiceModel>>().payload(serviceModels).status(ApiMessageCode.NO_MESSAGE));
}
@Transactional
@RequestMapping(method = RequestMethod.POST, value = {"/services"}, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<ServiceModel>> create(@RequestBody ServiceModel serviceModel, Principal principal) throws Exception {
Service service = serviceManager.create(serviceModel, principal);
ResponseEntity<ResponseItem<ServiceModel>> create(@RequestBody ServiceModel serviceModel) throws Exception {
this.authorizationService.authorizeForce(Permission.AuthenticatedRole);
Service service = serviceManager.create(serviceModel);
ServiceModel serviceModel1 = new ServiceModel().fromDataModel(service);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<ServiceModel>().payload(serviceModel1).status(ApiMessageCode.SUCCESS_MESSAGE));
}

View File

@ -1,13 +1,14 @@
package eu.eudat.controllers;
import eu.eudat.authorization.Permission;
import eu.eudat.logic.managers.TaxonomyManager;
import eu.eudat.logic.proxy.config.exceptions.HugeResultSet;
import eu.eudat.logic.proxy.config.exceptions.NoURLFound;
import eu.eudat.logic.services.ApiContext;
import eu.eudat.models.data.helpers.responses.ResponseItem;
import eu.eudat.models.data.security.Principal;
import eu.eudat.models.data.taxonomy.TaxonomyModel;
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;
@ -22,18 +23,22 @@ import java.util.List;
public class TaxonomiesController extends BaseController {
private TaxonomyManager taxonomyManager;
private final AuthorizationService authorizationService;
@Autowired
public TaxonomiesController(ApiContext apiContext, TaxonomyManager taxonomyManager) {
public TaxonomiesController(ApiContext apiContext, TaxonomyManager taxonomyManager, AuthorizationService authorizationService) {
super(apiContext);
this.taxonomyManager = taxonomyManager;
this.authorizationService = authorizationService;
}
@RequestMapping(method = RequestMethod.GET, produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<List<TaxonomyModel>>> listExternalPublications(
@RequestParam(value = "query", required = false) String query, @RequestParam(value = "type", required = false) String type, Principal principal
@RequestParam(value = "query", required = false) String query, @RequestParam(value = "type", required = false) String type
) throws HugeResultSet, NoURLFound {
this.authorizationService.authorizeForce(Permission.AuthenticatedRole);
List<TaxonomyModel> taxonomyModels = this.taxonomyManager.getTaxonomies(query, type);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List<TaxonomyModel>>().status(ApiMessageCode.NO_MESSAGE).payload(taxonomyModels));
}

View File

@ -1,13 +1,14 @@
package eu.eudat.controllers;
import eu.eudat.authorization.Permission;
import eu.eudat.data.query.items.item.userinfo.UserInfoRequestItem;
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.models.data.security.Principal;
import eu.eudat.models.data.userinfo.UserInfoInvitationModel;
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;
@ -15,6 +16,8 @@ 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;
@ -26,34 +29,42 @@ import java.util.UUID;
public class UserInvitationController extends BaseController {
private InvitationsManager invitationsManager;
private final AuthorizationService authorizationService;
@Autowired
public UserInvitationController(ApiContext apiContext, InvitationsManager invitationsManager) {
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, Principal principal) throws Exception {
this.invitationsManager.inviteUsers(invitation, principal);
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, Principal principal) throws JAXBException, IOException {
UUID dmpId = invitationsManager.assignUserAcceptedInvitation(invitationID, principal);
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(Principal principal) throws IllegalAccessException, InstantiationException {
ResponseEntity<ResponseItem<List<UserInfoInvitationModel>>> getUsers(Principal principal, @RequestBody UserInfoRequestItem userInfoRequestItem) throws IllegalAccessException, InstantiationException {
// 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);
List<UserInfoInvitationModel> users = invitationsManager.getUsersWithCriteria(principal, userInfoRequestItem);
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

@ -1,16 +1,17 @@
package eu.eudat.controllers;
import eu.eudat.authorization.Permission;
import eu.eudat.commons.scope.user.UserScope;
import eu.eudat.data.query.items.table.userinfo.UserInfoTableRequestItem;
import eu.eudat.logic.managers.UserManager;
import eu.eudat.logic.security.claims.ClaimedAuthorities;
import eu.eudat.logic.services.ApiContext;
import eu.eudat.models.data.helpers.common.DataTableData;
import eu.eudat.models.data.helpers.responses.ResponseItem;
import eu.eudat.models.data.security.Principal;
import eu.eudat.models.data.userinfo.UserCredential;
import eu.eudat.models.data.userinfo.UserListingModel;
import eu.eudat.models.data.userinfo.UserProfile;
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;
@ -18,12 +19,13 @@ import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import jakarta.validation.Valid;
import javax.management.InvalidApplicationException;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import static eu.eudat.types.Authorities.ADMIN;
@RestController
@ -32,15 +34,22 @@ import static eu.eudat.types.Authorities.ADMIN;
public class Users extends BaseController {
private UserManager userManager;
private final AuthorizationService authorizationService;
private final UserScope userScope;
@Autowired
public Users(ApiContext apiContext, UserManager userManager) {
public Users(ApiContext apiContext, UserManager userManager, AuthorizationService authorizationService, UserScope userScope) {
super(apiContext);
this.userManager = userManager;
this.authorizationService = authorizationService;
this.userScope = userScope;
}
@RequestMapping(method = RequestMethod.POST, value = {"/getPaged"}, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<DataTableData<UserListingModel>>> getPaged(@Valid @RequestBody UserInfoTableRequestItem userInfoTableRequestItem, @ClaimedAuthorities(claims = {ADMIN}) Principal principal) throws Exception {
ResponseEntity<ResponseItem<DataTableData<UserListingModel>>> getPaged(@Valid @RequestBody UserInfoTableRequestItem userInfoTableRequestItem) throws Exception {
this.authorizationService.authorizeForce(Permission.AdminRole);
DataTableData<UserListingModel> dataTable = userManager.getPaged(userInfoTableRequestItem);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DataTableData<UserListingModel>>().payload(dataTable).status(ApiMessageCode.NO_MESSAGE));
}
@ -48,23 +57,29 @@ public class Users extends BaseController {
@Transactional
@RequestMapping(method = RequestMethod.POST, value = {"/updateRoles"}, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<UserListingModel>> updateRoles(@Valid @RequestBody UserListingModel userListingModel, @ClaimedAuthorities(claims = {ADMIN}) Principal principal) {
ResponseEntity<ResponseItem<UserListingModel>> updateRoles(@Valid @RequestBody UserListingModel userListingModel) throws InvalidApplicationException {
this.authorizationService.authorizeForce(Permission.AdminRole);
userManager.editRoles(userListingModel);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<UserListingModel>().status(ApiMessageCode.NO_MESSAGE));
}
@RequestMapping(method = RequestMethod.GET, value = {"/{id}"}, produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<UserProfile>> get(@PathVariable String id, Principal principal) throws Exception {
UUID userId = id.equals("me") ? principal.getId() : UUID.fromString(id);
ResponseEntity<ResponseItem<UserProfile>> get(@PathVariable String id) throws Exception {
this.authorizationService.authorizeForce(Permission.AuthenticatedRole);
UUID userId = id.equals("me") ? this.userScope.getUserId() : UUID.fromString(id);
UserProfile user = userManager.getSingle(userId);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<UserProfile>().payload(user).status(ApiMessageCode.NO_MESSAGE));
}
@RequestMapping(method = RequestMethod.GET, value = {"/{id}/emails"}, produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<List<UserCredential>>> getEmails(@PathVariable String id, Principal principal) throws Exception {
UUID userId = id.equals("me") ? principal.getId() : UUID.fromString(id);
ResponseEntity<ResponseItem<List<UserCredential>>> getEmails(@PathVariable String id) throws Exception {
this.authorizationService.authorizeForce(Permission.AuthenticatedRole);
UUID userId = id.equals("me") ? this.userScope.getUserId() : UUID.fromString(id);
List<UserCredential> user = userManager.getCredentials(userId);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List<UserCredential>>().payload(user).status(ApiMessageCode.NO_MESSAGE));
}
@ -72,27 +87,32 @@ public class Users extends BaseController {
@Transactional
@RequestMapping(method = RequestMethod.POST, value = {"/settings"}, produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<UserProfile>> saveSettings(@RequestBody Map<String, Object> settings, Principal principal) throws IOException {
userManager.updateSettings(settings, principal);
ResponseEntity<ResponseItem<UserProfile>> saveSettings(@RequestBody Map<String, Object> settings) throws IOException, InvalidApplicationException {
this.authorizationService.authorizeForce(Permission.AuthenticatedRole);
userManager.updateSettings(settings);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<UserProfile>().status(ApiMessageCode.NO_MESSAGE));
}
@RequestMapping(method = RequestMethod.POST, value = {"/getCollaboratorsPaged"}, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<DataTableData<UserListingModel>>> getCollaboratorsPaged(@Valid @RequestBody UserInfoTableRequestItem userInfoTableRequestItem, Principal principal) throws Exception {
DataTableData<UserListingModel> dataTable = userManager.getCollaboratorsPaged(userInfoTableRequestItem, principal);
ResponseEntity<ResponseItem<DataTableData<UserListingModel>>> getCollaboratorsPaged(@Valid @RequestBody UserInfoTableRequestItem userInfoTableRequestItem) throws Exception {
this.authorizationService.authorizeForce(Permission.AuthenticatedRole);
DataTableData<UserListingModel> dataTable = userManager.getCollaboratorsPaged(userInfoTableRequestItem);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DataTableData<UserListingModel>>().payload(dataTable).status(ApiMessageCode.NO_MESSAGE));
}
@RequestMapping(method = RequestMethod.GET, value = {"/getCsv"})
public @ResponseBody
ResponseEntity exportCsv(@ClaimedAuthorities(claims = {ADMIN}) Principal principal) throws Exception {
return userManager.exportToCsv(principal);
ResponseEntity exportCsv() throws Exception {
return userManager.exportToCsv();
}
@RequestMapping(method = RequestMethod.POST, value = {"/find"}, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<UserProfile>> find(@Valid @RequestBody String email) throws Exception {
this.authorizationService.authorizeForce(Permission.PublicRole);
UserProfile userProfile = userManager.getFromEmail(email);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<UserProfile>().payload(userProfile).status(ApiMessageCode.NO_MESSAGE));
}

View File

@ -1,12 +1,13 @@
package eu.eudat.controllers;
import eu.eudat.authorization.Permission;
import eu.eudat.logic.managers.ValidationManager;
import eu.eudat.logic.proxy.config.exceptions.HugeResultSet;
import eu.eudat.logic.proxy.config.exceptions.NoURLFound;
import eu.eudat.logic.services.ApiContext;
import eu.eudat.models.data.helpers.responses.ResponseItem;
import eu.eudat.models.data.security.Principal;
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;
@ -18,19 +19,23 @@ import org.springframework.web.bind.annotation.*;
public class Validation extends BaseController {
private ValidationManager validationManager;
private final AuthorizationService authorizationService;
@Autowired
public Validation(ApiContext apiContext, ValidationManager validationManager) {
public Validation(ApiContext apiContext, ValidationManager validationManager, AuthorizationService authorizationService) {
super(apiContext);
this.validationManager = validationManager;
this.authorizationService = authorizationService;
}
@RequestMapping(method = RequestMethod.GET, value = {"/external/validation"}, produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<Boolean>> validate(
@RequestParam(value = "query", required = false) String query, @RequestParam(value = "type", required = false) String type, Principal principal
@RequestParam(value = "query", required = false) String query, @RequestParam(value = "type", required = false) String type
) throws HugeResultSet, NoURLFound {
Boolean isValid = this.validationManager.validateIdentifier(query, type, principal);
this.authorizationService.authorizeForce(Permission.AuthenticatedRole);
Boolean isValid = this.validationManager.validateIdentifier(query, type);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<Boolean>().payload(isValid).status(ApiMessageCode.NO_MESSAGE));
}
}

View File

@ -1,11 +1,8 @@
package eu.eudat.controllers.controllerhandler;
import eu.eudat.logic.security.claims.ClaimedAuthorities;
import eu.eudat.models.data.helpers.responses.ResponseItem;
import eu.eudat.models.data.security.Principal;
import eu.eudat.types.ApiMessageCode;
import eu.eudat.types.Authorities;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;

View File

@ -3,17 +3,14 @@ package eu.eudat.controllers.v2;
import eu.eudat.audit.AuditableAction;
import eu.eudat.authorization.AuthorizationFlags;
import eu.eudat.data.DescriptionTemplateTypeEntity;
import eu.eudat.logic.security.claims.ClaimedAuthorities;
import eu.eudat.model.DescriptionTemplateType;
import eu.eudat.model.builder.DescriptionTemplateTypeBuilder;
import eu.eudat.model.censorship.DescriptionTemplateTypeCensor;
import eu.eudat.model.persist.DescriptionTemplateTypePersist;
import eu.eudat.model.result.QueryResult;
import eu.eudat.models.data.security.Principal;
import eu.eudat.query.DescriptionTemplateTypeQuery;
import eu.eudat.query.lookup.DescriptionTemplateTypeLookup;
import eu.eudat.service.DescriptionTemplateTypeService;
import eu.eudat.types.Authorities;
import gr.cite.tools.auditing.AuditService;
import gr.cite.tools.data.builder.BuilderFactory;
import gr.cite.tools.data.censor.CensorFactory;
@ -25,19 +22,14 @@ import gr.cite.tools.fieldset.FieldSet;
import gr.cite.tools.logging.LoggerService;
import gr.cite.tools.logging.MapLogEntry;
import gr.cite.tools.validation.MyValidate;
import org.opensaml.xml.signature.Q;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import javax.management.InvalidApplicationException;
import java.io.IOException;
import java.util.*;
@RestController

View File

@ -18,6 +18,8 @@ import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import eu.eudat.models.v2.Account;
import javax.management.InvalidApplicationException;
@RestController
@CrossOrigin
@RequestMapping(value = { "/api/principal/" })
@ -39,7 +41,7 @@ public class PrincipalController {
}
@RequestMapping(path = "me", method = RequestMethod.GET )
public ResponseEntity<?> me(FieldSet fieldSet) {
public ResponseEntity<?> me(FieldSet fieldSet) throws InvalidApplicationException {
logger.debug("me");
if (fieldSet == null || fieldSet.isEmpty()) {

View File

@ -1,13 +1,13 @@
package eu.eudat.controllers.v2;
import eu.eudat.authorization.Permission;
import eu.eudat.commons.enums.SupportiveMaterialFieldType;
import eu.eudat.logic.managers.MetricsManager;
import eu.eudat.logic.security.claims.ClaimedAuthorities;
import eu.eudat.model.persist.UserGuidePersist;
import eu.eudat.models.data.helpers.responses.ResponseItem;
import eu.eudat.models.data.security.Principal;
import eu.eudat.service.supportivematerial.SupportiveMaterialService;
import eu.eudat.types.ApiMessageCode;
import gr.cite.commons.web.authz.service.AuthorizationService;
import org.apache.commons.lang3.EnumUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
@ -31,11 +31,13 @@ public class SupportiveMaterialController {
private Environment environment;
private SupportiveMaterialService supportiveMaterialService;
private final AuthorizationService authorizationService;
@Autowired
public SupportiveMaterialController(Environment environment, SupportiveMaterialService supportiveMaterialService, MetricsManager metricsManager) {
public SupportiveMaterialController(Environment environment, SupportiveMaterialService supportiveMaterialService, MetricsManager metricsManager, AuthorizationService authorizationService) {
this.environment = environment;
this.supportiveMaterialService = supportiveMaterialService;
this.authorizationService = authorizationService;
}
@GetMapping("{lang}")
@ -50,7 +52,8 @@ public class SupportiveMaterialController {
@PostMapping("current")
public @ResponseBody
ResponseEntity<ResponseItem<String>> persist(@RequestBody UserGuidePersist guide, String field, @ClaimedAuthorities(claims = {ADMIN}) Principal principal) throws IOException {
ResponseEntity<ResponseItem<String>> persist(@RequestBody UserGuidePersist guide, String field) throws IOException {
this.authorizationService.authorizeForce(Permission.AdminRole);
if( !EnumUtils.isValidEnum(SupportiveMaterialFieldType.class, field)){
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}

View File

@ -1,86 +0,0 @@
package eu.eudat.logic.handlers;
import eu.eudat.commons.scope.user.UserScope;
import eu.eudat.exceptions.security.UnauthorisedException;
import eu.eudat.logic.security.claims.ClaimedAuthorities;
import eu.eudat.logic.services.operations.authentication.AuthenticationService;
import eu.eudat.models.data.security.Principal;
import eu.eudat.types.Authorities;
import gr.cite.commons.web.oidc.principal.CurrentPrincipalResolver;
import gr.cite.commons.web.oidc.principal.MyPrincipal;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import javax.management.InvalidApplicationException;
import java.lang.annotation.Annotation;
import java.util.*;
public final class PrincipalArgumentResolver implements HandlerMethodArgumentResolver {
private AuthenticationService verifiedUserAuthenticationService;
private AuthenticationService nonVerifiedUserAuthenticationService;
private final UserScope userScope;
private final CurrentPrincipalResolver currentPrincipalResolver;
public PrincipalArgumentResolver(AuthenticationService verifiedUserAuthenticationService, AuthenticationService nonVerifiedUserAuthenticationService, UserScope userScope, CurrentPrincipalResolver currentPrincipalResolver) {
this.verifiedUserAuthenticationService = verifiedUserAuthenticationService;
this.nonVerifiedUserAuthenticationService = nonVerifiedUserAuthenticationService;
this.userScope = userScope;
this.currentPrincipalResolver = currentPrincipalResolver;
}
@Override
public boolean supportsParameter(MethodParameter methodParameter) {
return methodParameter.getParameterType().equals(Principal.class);
}
@Override
public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
MyPrincipal claimsPrincipal = this.currentPrincipalResolver.currentPrincipal();
boolean checkMailNull = ((ServletWebRequest) nativeWebRequest).getRequest().getRequestURI().startsWith("/api/emailConfirmation");
AuthenticationService authenticationService = checkMailNull ? this.nonVerifiedUserAuthenticationService : this.verifiedUserAuthenticationService;
Optional<Annotation> claimsAnnotation = Arrays.stream(methodParameter.getParameterAnnotations()).filter(annotation -> annotation.annotationType().equals(ClaimedAuthorities.class)).findAny();
List<Authorities> claimList = claimsAnnotation.map(annotation -> Arrays.asList(((ClaimedAuthorities) annotation).claims())).orElse(Authorities.all());
if (claimList.size() == 1 && claimList.get(0).equals(Authorities.ANONYMOUS)) {
return new Principal();
} else if (claimList.contains(Authorities.ANONYMOUS) && !claimsPrincipal.isAuthenticated()) {
return new Principal();
}
if (!claimsPrincipal.isAuthenticated()) throw new UnauthorisedException("Authentication Information Is Missing");
Principal principal;
if (checkMailNull){
principal = authenticationService.Touch(claimsPrincipal);
} else {
UUID userId;
try{
userId = checkMailNull ? null : this.userScope.getUserId();
} catch (InvalidApplicationException e) {
throw new UnauthorisedException("Authentication Information Is Missing");
}
principal = authenticationService.Touch(userId);
}
if (principal == null) throw new UnauthorisedException("Authentication Information Missing");
if (!claimList.contains(Authorities.ANONYMOUS) && !principal.isAuthorized(claimList))
throw new UnauthorisedException("You are not Authorized For this Action");
return principal;
}
private Date addADay(Date date) {
Date dt = new Date();
Calendar c = Calendar.getInstance();
c.setTime(dt);
c.add(Calendar.DATE, 1);
dt = c.getTime();
return dt;
}
}

View File

@ -15,6 +15,7 @@ import eu.eudat.service.DescriptionTemplateTypeService;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import javax.management.InvalidApplicationException;
import java.util.Date;
import java.util.UUID;
@ -72,7 +73,7 @@ public class AdminManager {
}
public static DescriptionTemplate inactivate(DatasetProfileDao datasetProfileRepository, DatasetDao datasetDao, String id) {
public static DescriptionTemplate inactivate(DatasetProfileDao datasetProfileRepository, DatasetDao datasetDao, String id) throws InvalidApplicationException {
eu.eudat.data.dao.criteria.DatasetCriteria datasetsForThatDatasetProfile = new eu.eudat.data.dao.criteria.DatasetCriteria();
datasetsForThatDatasetProfile.setProfileDatasetId(UUID.fromString(id));
if (datasetDao.getWithCriteria(datasetsForThatDatasetProfile).count() == 0) {

View File

@ -1,31 +1,34 @@
package eu.eudat.logic.managers;
import eu.eudat.commons.scope.user.UserScope;
import eu.eudat.data.old.UserInfo;
import eu.eudat.logic.services.ApiContext;
import eu.eudat.models.data.ContactEmail.ContactEmailModel;
import eu.eudat.models.data.ContactEmail.PublicContactEmailModel;
import eu.eudat.models.data.mail.SimpleMail;
import eu.eudat.models.data.security.Principal;
import org.springframework.core.env.Environment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import jakarta.mail.MessagingException;
import javax.management.InvalidApplicationException;
@Component
public class ContactEmailManager {
private ApiContext apiContext;
private Environment environment;
private final UserScope userScope;
@Autowired
public ContactEmailManager(ApiContext apiContext, Environment environment) {
public ContactEmailManager(ApiContext apiContext, Environment environment, UserScope userScope) {
this.apiContext = apiContext;
this.environment = environment;
this.userScope = userScope;
}
public void sendContactEmail(ContactEmailModel contactEmailModel, Principal principal) throws MessagingException {
UserInfo user = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(principal.getId());
public void sendContactEmail(ContactEmailModel contactEmailModel) throws MessagingException, InvalidApplicationException {
UserInfo user = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(this.userScope.getUserId());
SimpleMail mail = new SimpleMail();
String enrichedMail = contactEmailModel.getDescription() + "\n\n" + "Send by user: " + user.getEmail() ;
mail.setSubject(contactEmailModel.getSubject());

View File

@ -1,5 +1,6 @@
package eu.eudat.logic.managers;
import eu.eudat.commons.scope.user.UserScope;
import eu.eudat.data.dao.criteria.DataManagementPlanCriteria;
import eu.eudat.data.dao.criteria.DatasetCriteria;
import eu.eudat.data.dao.criteria.GrantCriteria;
@ -28,14 +29,16 @@ import eu.eudat.models.data.dashboard.statistics.DashBoardStatistics;
import eu.eudat.models.data.helpers.common.DataTableData;
import eu.eudat.models.data.listingmodels.DataManagementPlanListingModel;
import eu.eudat.models.data.listingmodels.DatasetListingModel;
import eu.eudat.models.data.security.Principal;
import eu.eudat.types.searchbar.SearchBarItemType;
import gr.cite.commons.web.oidc.principal.CurrentPrincipalResolver;
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.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
@ -56,20 +59,24 @@ public class DashBoardManager {
{ "publishedAt", Comparator.comparing(o -> ((RecentActivityModel)o).getPublishedAt(), Comparator.nullsLast(Comparator.naturalOrder())).reversed()}
}).collect(Collectors.toMap(data -> (String) data[0], data -> (Comparator<RecentActivityModel>)data[1]));
private ApiContext apiContext;
private DatabaseRepository databaseRepository;
private final ApiContext apiContext;
private final DatabaseRepository databaseRepository;
private final DataManagementPlanManager dataManagementPlanManager;
private final DatasetManager datasetManager;
private final CurrentPrincipalResolver currentPrincipalResolver;
private final UserScope userScope;
@Autowired
public DashBoardManager(ApiContext apiContext, DataManagementPlanManager dataManagementPlanManager, DatasetManager datasetManager) {
public DashBoardManager(ApiContext apiContext, DataManagementPlanManager dataManagementPlanManager, DatasetManager datasetManager, CurrentPrincipalResolver currentPrincipalResolver, UserScope userScope) {
this.apiContext = apiContext;
this.databaseRepository = apiContext.getOperationsContext().getDatabaseRepository();
this.dataManagementPlanManager = dataManagementPlanManager;
this.datasetManager = datasetManager;
this.currentPrincipalResolver = currentPrincipalResolver;
this.userScope = userScope;
}
public DashBoardStatistics getStatistics() {
public DashBoardStatistics getStatistics() throws InvalidApplicationException {
DashBoardStatistics statistics = new DashBoardStatistics();
DataManagementPlanCriteria publicCriteria = new DataManagementPlanCriteria();
@ -104,7 +111,7 @@ public class DashBoardManager {
return statistics;
}
public DashBoardStatistics getMeStatistics(Principal principal) throws IOException {
public DashBoardStatistics getMeStatistics() throws IOException, InvalidApplicationException {
Long datasets = 0L;
Long dmps = 0L;
DashBoardStatistics statistics = new DashBoardStatistics();
@ -113,14 +120,14 @@ public class DashBoardManager {
GrantDao grantRepository = databaseRepository.getGrantDao();
OrganisationDao organisationRepository = databaseRepository.getOrganisationDao();
UserInfo user = new UserInfo();
user.setId(principal.getId());
user.setId(this.userScope.getUserId());
DatasetCriteria datasetCriteria = new DatasetCriteria();
if (apiContext.getOperationsContext().getElasticRepository().getDatasetRepository() != null) {
try {
eu.eudat.elastic.criteria.DatasetCriteria datasetElasticCriteria = new eu.eudat.elastic.criteria.DatasetCriteria();
datasetElasticCriteria.setAllowAllVersions(false);
datasetElasticCriteria.setPublic(false);
datasetElasticCriteria.setCollaborators(Collections.singletonList(principal.getId()));
datasetElasticCriteria.setCollaborators(Collections.singletonList(this.userScope.getUserId()));
datasets = apiContext.getOperationsContext().getElasticRepository().getDatasetRepository().count(datasetElasticCriteria);
}catch (Exception e) {
logger.warn(e.getMessage(), e);
@ -135,7 +142,7 @@ public class DashBoardManager {
eu.eudat.elastic.criteria.DmpCriteria dmpElasticCriteria = new eu.eudat.elastic.criteria.DmpCriteria();
dmpElasticCriteria.setAllowAllVersions(false);
dmpElasticCriteria.setPublic(false);
dmpElasticCriteria.setCollaborators(Collections.singletonList(principal.getId()));
dmpElasticCriteria.setCollaborators(Collections.singletonList(this.userScope.getUserId()));
dmps = apiContext.getOperationsContext().getElasticRepository().getDmpRepository().count(dmpElasticCriteria);
}catch (Exception e) {
logger.warn(e.getMessage(), e);
@ -154,7 +161,7 @@ public class DashBoardManager {
List<Integer> roles = new LinkedList<>();
if ((dmps == null || dmps == 0L) && (datasets == null || datasets == 0L)) {
CompletableFuture dmpFuture = dataManagementPlanRepository.getAuthenticated(dataManagementPlanRepository.getWithCriteria(dataManagementPlanCriteria), principal.getId(), roles).distinct().countAsync()
CompletableFuture dmpFuture = dataManagementPlanRepository.getAuthenticated(dataManagementPlanRepository.getWithCriteria(dataManagementPlanCriteria), this.userScope.getUserId(), roles).distinct().countAsync()
.whenComplete((dmpsStats, throwable) -> statistics.setTotalDataManagementPlanCount(dmpsStats));
CompletableFuture datasetFuture = datasetRepository.getAuthenticated( datasetRepository.getWithCriteria(datasetCriteria), user, roles).distinct().countAsync()
.whenComplete((datasetsStats, throwable) -> statistics.setTotalDataSetCount(datasetsStats));
@ -173,13 +180,13 @@ public class DashBoardManager {
}
@Deprecated
public RecentActivity getRecentActivity(Principal principal, Integer numberofactivities) {
public RecentActivity getRecentActivity(Integer numberofactivities) throws InvalidApplicationException {
RecentActivity activity = new RecentActivity();
DMPDao dataManagementPlanRepository = databaseRepository.getDmpDao();
DatasetDao datasetRepository = databaseRepository.getDatasetDao();
GrantDao grantRepository = databaseRepository.getGrantDao();
UserInfo user = new UserInfo();
user.setId(principal.getId());
user.setId(this.userScope.getUserId());
DatasetCriteria datasetCriteria = new DatasetCriteria();
datasetCriteria.setAllVersions(false);
DataManagementPlanCriteria dataManagementPlanCriteria = new DataManagementPlanCriteria();
@ -188,7 +195,7 @@ public class DashBoardManager {
RecentActivityDataBuilder recentActivityDataBuilder = apiContext.getOperationsContext().getBuilderFactory().getBuilder(RecentActivityDataBuilder.class);
List<Integer> roles = new LinkedList<>();
CompletableFuture<List<RecentActivityData>> dmps = dataManagementPlanRepository.getAuthenticated(dataManagementPlanRepository.getWithCriteria(dataManagementPlanCriteria), principal.getId(), roles)
CompletableFuture<List<RecentActivityData>> dmps = dataManagementPlanRepository.getAuthenticated(dataManagementPlanRepository.getWithCriteria(dataManagementPlanCriteria), this.userScope.getUserId(), roles)
.withHint("dmpRecentActivity")
.orderBy((builder, root) -> builder.desc(root.get("modified")))
.take(numberofactivities)
@ -214,12 +221,12 @@ public class DashBoardManager {
}
@Transactional
public List<RecentActivityModel> getNewRecentActivity(RecentActivityTableRequest tableRequest, Principal principal) throws Exception {
boolean isAuthenticated = principal.getId() != null;
public List<RecentActivityModel> getNewRecentActivity(RecentActivityTableRequest tableRequest) throws Exception {
boolean isAuthenticated = this.currentPrincipalResolver.currentPrincipal().isAuthenticated();
List<RecentActivityModel> recentActivityModels = new ArrayList<>();
UserInfo user = new UserInfo();
if (isAuthenticated) {
user.setId(principal.getId());
user.setId(userScope.getUserId());
}
DatasetCriteria datasetCriteria = new DatasetCriteria();
datasetCriteria.setLike(tableRequest.getCriteria().getLike());
@ -243,7 +250,7 @@ public class DashBoardManager {
dataManagementPlanTableRequest.setOrderings(tableRequest.getOrderings());
dataManagementPlanTableRequest.setLength(tableRequest.getLength());
dataManagementPlanTableRequest.setOffset(tableRequest.getDmpOffset());
DataTableData<DataManagementPlanListingModel> dmps = this.dataManagementPlanManager.getPaged(dataManagementPlanTableRequest, principal, "listing");
DataTableData<DataManagementPlanListingModel> dmps = this.dataManagementPlanManager.getPaged(dataManagementPlanTableRequest, "listing");
recentActivityModels.addAll(dmps.getData().stream().map(dataManagementPlanListingModel -> new RecentDmpModel().fromDataModel(dataManagementPlanListingModel.toDataModel())).collect(Collectors.toList()));
DatasetTableRequest datasetTableRequest = new DatasetTableRequest();
datasetCriteria.setCollaborators(new ArrayList<>());
@ -253,7 +260,7 @@ public class DashBoardManager {
datasetTableRequest.getOrderings().getFields().removeIf(s -> s.contains("publishedAt") && !s.endsWith("|join|"));
datasetTableRequest.setLength(tableRequest.getLength());
datasetTableRequest.setOffset(tableRequest.getDatasetOffset());
DataTableData<DatasetListingModel> datasets = this.datasetManager.getPaged(datasetTableRequest, principal);
DataTableData<DatasetListingModel> datasets = this.datasetManager.getPaged(datasetTableRequest);
recentActivityModels.addAll(datasets.getData().stream().map(datasetListingModel -> new RecentDatasetModel().fromDataModel(datasetListingModel.toDataModel())).collect(Collectors.toList()));
//GK: Shuffle the deck otherwise we will summon the DMPodia when sorting with status
@ -290,9 +297,9 @@ public class DashBoardManager {
return recentActivityModels;
}
public List<SearchBarItem> searchUserData(String like, Principal principal) {
public List<SearchBarItem> searchUserData(String like) throws InvalidApplicationException {
UserInfo user = new UserInfo();
user.setId(principal.getId());
user.setId(this.userScope.getUserIdSafe());
DMPDao dataManagementPlanRepository = databaseRepository.getDmpDao();
DatasetDao datasetRepository = databaseRepository.getDatasetDao();
GrantDao grantRepository = databaseRepository.getGrantDao();
@ -316,8 +323,8 @@ public class DashBoardManager {
.selectAsync(item -> new SearchBarItem(item.getId().toString(), item.getLabel(), SearchBarItemType.DATASET.getValue(), true))
.whenComplete((dataSetItems, throwable) -> searchBarItems.addAll(dataSetItems));
if (principal.getId() != null) {
CompletableFuture<List<SearchBarItem>> dmps = dataManagementPlanRepository.getAuthenticated(dataManagementPlanRepository.asQueryable(), principal.getId(), roles)
if (this.userScope.isSet()) {
CompletableFuture<List<SearchBarItem>> dmps = dataManagementPlanRepository.getAuthenticated(dataManagementPlanRepository.asQueryable(), this.userScope.getUserId(), roles)
.withHint("dmpRecentActivity")
.where((builder, root) -> builder.like(builder.upper(root.get("label")), "%" + like.toUpperCase() + "%"))
.where((builder, root) -> builder.notEqual(root.get("status"), DMP.DMPStatus.DELETED.getValue()))

View File

@ -2,6 +2,8 @@ package eu.eudat.logic.managers;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import eu.eudat.authorization.Permission;
import eu.eudat.commons.scope.user.UserScope;
import eu.eudat.configurations.dynamicgrant.DynamicGrantConfiguration;
import eu.eudat.configurations.dynamicgrant.entities.Property;
import eu.eudat.data.dao.criteria.*;
@ -61,12 +63,12 @@ import eu.eudat.models.data.helpermodels.Tuple;
import eu.eudat.models.data.helpers.common.DataTableData;
import eu.eudat.models.data.listingmodels.*;
import eu.eudat.models.data.project.ProjectDMPEditorModel;
import eu.eudat.models.data.security.Principal;
import eu.eudat.models.data.user.composite.PagedDatasetProfile;
import eu.eudat.models.data.userinfo.UserListingModel;
import eu.eudat.queryable.QueryableList;
import eu.eudat.types.Authorities;
import eu.eudat.types.MetricNames;
import gr.cite.commons.web.authz.service.AuthorizationService;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
@ -86,6 +88,8 @@ import jakarta.transaction.Transactional;
import jakarta.xml.bind.JAXBContext;
import jakarta.xml.bind.JAXBException;
import jakarta.xml.bind.Unmarshaller;
import javax.management.InvalidApplicationException;
import java.io.*;
import java.math.BigInteger;
import java.nio.file.Files;
@ -120,10 +124,13 @@ public class DataManagementPlanManager {
private final MetricsManager metricsManager;
private final ConfigLoader configLoader;
private List<RepositoryDeposit> repositoriesDeposit;
private final UserScope userScope;
private final AuthorizationService authorizationService;
@Autowired
public DataManagementPlanManager(ApiContext apiContext, DatasetManager datasetManager, DataManagementProfileManager dataManagementProfileManager, Environment environment, RDAManager rdaManager, UserManager userManager,
MetricsManager metricsManager, ConfigLoader configLoader, List<RepositoryDeposit> repositoriesDeposit) {
MetricsManager metricsManager, ConfigLoader configLoader, List<RepositoryDeposit> repositoriesDeposit, UserScope userScope, AuthorizationService authorizationService) {
this.apiContext = apiContext;
this.datasetManager = datasetManager;
this.dataManagementProfileManager = dataManagementProfileManager;
@ -133,6 +140,8 @@ public class DataManagementPlanManager {
this.userManager = userManager;
this.metricsManager = metricsManager;
this.configLoader = configLoader;
this.userScope = userScope;
this.authorizationService = authorizationService;
this.objectMapper = new ObjectMapper();
this.repositoriesDeposit = repositoriesDeposit;
}
@ -141,8 +150,8 @@ public class DataManagementPlanManager {
* Data Retrieval
* */
public DataTableData<DataManagementPlanListingModel> getPaged(DataManagementPlanTableRequest dataManagementPlanTableRequest, Principal principal, String fieldsGroup) throws Exception {
UUID principalID = principal.getId();
public DataTableData<DataManagementPlanListingModel> getPaged(DataManagementPlanTableRequest dataManagementPlanTableRequest, String fieldsGroup) throws Exception {
UUID principalID = userScope.getUserIdSafe();
List<Dmp> dmps = null;
QueryableList<DMP> items = null;
QueryableList<DMP> authItems = null;
@ -199,7 +208,11 @@ public class DataManagementPlanManager {
datasetCriteria.setAllVersions(dataManagementPlanTableRequest.getCriteria().getAllVersions());
datasetCriteria.setIsPublic(dataManagementPlanTableRequest.getCriteria().getIsPublic());
datasetCriteria.setGroupIds(Collections.singletonList(dmp.getGroupId()));
dmp.setDataset(retrieveRelevantDatasets(datasetCriteria, principalID));
try {
dmp.setDataset(retrieveRelevantDatasets(datasetCriteria, principalID));
} catch (InvalidApplicationException e) {
throw new RuntimeException(e);
}
return new DataManagementPlanListingModel().fromDataModelDatasets(dmp);
@ -224,7 +237,11 @@ public class DataManagementPlanManager {
datasetCriteria.setIsPublic(true);
datasetCriteria.setAllVersions(dataManagementPlanTableRequest.getCriteria().getAllVersions());
datasetCriteria.setGroupIds(Collections.singletonList(dmp.getGroupId()));
dmp.setDataset(retrieveRelevantDatasets(datasetCriteria));
try {
dmp.setDataset(retrieveRelevantDatasets(datasetCriteria));
} catch (InvalidApplicationException e) {
throw new RuntimeException(e);
}
return new DataManagementPlanListingModel().fromDataModelDatasets(dmp);
@ -253,11 +270,11 @@ public class DataManagementPlanManager {
return dataTable;
}
private Set<Dataset> retrieveRelevantDatasets(DatasetCriteria datasetCriteria) {
private Set<Dataset> retrieveRelevantDatasets(DatasetCriteria datasetCriteria) throws InvalidApplicationException {
return retrieveRelevantDatasets(datasetCriteria, null);
}
private Set<Dataset> retrieveRelevantDatasets (DatasetCriteria datasetCriteria, UUID principal) {
private Set<Dataset> retrieveRelevantDatasets (DatasetCriteria datasetCriteria, UUID principal) throws InvalidApplicationException {
QueryableList<Dataset> datasetItems = apiContext.getOperationsContext().getDatabaseRepository().getDatasetDao().getWithCriteria(datasetCriteria)
.orderBy((builder, root) -> builder.desc(root.get("modified")));
if (principal != null) {
@ -288,12 +305,12 @@ public class DataManagementPlanManager {
return datasetsSet;
}
public eu.eudat.models.data.dmp.DataManagementPlan getSingle(String id, Principal principal, boolean isPublic, boolean includeDatasets) throws Exception {
public eu.eudat.models.data.dmp.DataManagementPlan getSingle(String id, boolean isPublic, boolean includeDatasets) throws Exception {
eu.eudat.models.data.dmp.DataManagementPlan dataManagementPlan = new eu.eudat.models.data.dmp.DataManagementPlan();
DMP dataManagementPlanEntity = databaseRepository.getDmpDao().find(UUID.fromString(id));
if (!isPublic && principal == null) {
if (!isPublic && !this.userScope.isSet()) {
throw new UnauthorisedException();
} else if (!isPublic && (dataManagementPlanEntity.getUsers().stream().noneMatch(userInfo -> userInfo.getUser().getId() == principal.getId()))) {
} else if (!isPublic && (dataManagementPlanEntity.getUsers().stream().noneMatch(userInfo -> userInfo.getUser().getId() == this.userScope.getUserIdSafe()))) {
if (!dataManagementPlanEntity.isPublic()) {
throw new UnauthorisedException();
}
@ -339,16 +356,16 @@ public class DataManagementPlanManager {
return dataManagementPlan;
}
public DataManagementPlanOverviewModel getOverviewSingle(String id, Principal principal, boolean isPublic) throws Exception {
public DataManagementPlanOverviewModel getOverviewSingle(String id, boolean isPublic) throws Exception {
DMP dataManagementPlanEntity = databaseRepository.getDmpDao().find(UUID.fromString(id));
if (dataManagementPlanEntity.getStatus() == DMP.DMPStatus.DELETED.getValue()) {
throw new Exception("DMP is deleted.");
}
if (!isPublic && principal == null) {
if (!isPublic && !this.userScope.isSet()) {
throw new UnauthorisedException();
} else
if (!isPublic && dataManagementPlanEntity.getUsers()
.stream().noneMatch(userInfo -> userInfo.getUser().getId() == principal.getId())) {
.stream().noneMatch(userInfo -> userInfo.getUser().getId() == this.userScope.getUserIdSafe())) {
throw new UnauthorisedException();
} else if (isPublic && !dataManagementPlanEntity.isPublic()) {
throw new ForbiddenException("Selected DMP is not public");
@ -406,9 +423,9 @@ public class DataManagementPlanManager {
return result;
}
public DataTableData<DatasetProfileListingModel> getDatasetProfilesUsedByDMP(DatasetProfileTableRequestItem datasetProfileTableRequestItem, Principal principal) {
public DataTableData<DatasetProfileListingModel> getDatasetProfilesUsedByDMP(DatasetProfileTableRequestItem datasetProfileTableRequestItem) throws InvalidApplicationException {
datasetProfileTableRequestItem.getCriteria().setFilter(DatasetProfileCriteria.DatasetProfileFilter.DMPs.getValue());
datasetProfileTableRequestItem.getCriteria().setUserId(principal.getId());
datasetProfileTableRequestItem.getCriteria().setUserId(this.userScope.getUserId());
QueryableList<DescriptionTemplate> items = apiContext.getOperationsContext().getDatabaseRepository().getDatasetProfileDao().getWithCriteria(datasetProfileTableRequestItem.getCriteria());
List<DatasetProfileListingModel> listingModels = items.select(item -> new DatasetProfileListingModel().fromDataModel(item));
@ -420,8 +437,8 @@ public class DataManagementPlanManager {
return data;
}
public List<VersionListingModel> getAllVersions(String groupId, Principal principal, Boolean isPublic) {
UUID principalId = principal != null ? principal.getId() : null;
public List<VersionListingModel> getAllVersions(String groupId, Boolean isPublic) throws InvalidApplicationException {
UUID principalId = this.userScope.getUserIdSafe();
List<VersionListingModel> versions = new ArrayList<>();
QueryableList<DMP> items = null;
QueryableList<DMP> authItems = null;
@ -452,7 +469,7 @@ public class DataManagementPlanManager {
* */
@Transactional
public DMP createOrUpdate(DataManagementPlanEditorModel dataManagementPlan, Principal principal) throws Exception {
public DMP createOrUpdate(DataManagementPlanEditorModel dataManagementPlan) throws Exception {
boolean setNotification = false;
if (dataManagementPlan.getId() != null) {
DMP dmp1 = apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().find(dataManagementPlan.getId());
@ -460,7 +477,7 @@ public class DataManagementPlanManager {
Instant dbTime = Instant.ofEpochMilli(dmp1.getModified().getTime()).truncatedTo(ChronoUnit.SECONDS);
Instant modelTime = Instant.ofEpochMilli(dataManagementPlan.getModified().getTime()).truncatedTo(ChronoUnit.SECONDS);
if (!isUserOwnerOfDmp(dmp1, principal)) {
if (!isUserOwnerOfDmp(dmp1)) {
throw new Exception("User not being the creator is not authorized to edit this DMP.");
}
if (dbTime.toEpochMilli() != modelTime.toEpochMilli()) {
@ -487,21 +504,21 @@ public class DataManagementPlanManager {
if (newDmp.getStatus() == (int) DMP.DMPStatus.FINALISED.getValue()) {
checkDmpValidationRules(newDmp);
}
UserInfo user = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(principal.getId());
UserInfo user = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(this.userScope.getUserId());
newDmp.setCreator(user);
if(this.dataManagementProfileManager.fieldInBlueprint(newDmp.getProfile(), SystemFieldType.ORGANIZATIONS, principal)) {
if(this.dataManagementProfileManager.fieldInBlueprint(newDmp.getProfile(), SystemFieldType.ORGANIZATIONS)) {
createOrganisationsIfTheyDontExist(newDmp, apiContext.getOperationsContext().getDatabaseRepository().getOrganisationDao());
}
if(this.dataManagementProfileManager.fieldInBlueprint(newDmp.getProfile(), SystemFieldType.RESEARCHERS, principal)) {
if(this.dataManagementProfileManager.fieldInBlueprint(newDmp.getProfile(), SystemFieldType.RESEARCHERS)) {
createResearchersIfTheyDontExist(newDmp, apiContext.getOperationsContext().getDatabaseRepository().getResearcherDao(), user);
}
if(this.dataManagementProfileManager.fieldInBlueprint(newDmp.getProfile(), SystemFieldType.FUNDER, principal)) {
if(this.dataManagementProfileManager.fieldInBlueprint(newDmp.getProfile(), SystemFieldType.FUNDER)) {
createFunderIfItDoesntExist(newDmp, apiContext.getOperationsContext().getDatabaseRepository().getFunderDao());
}
if(this.dataManagementProfileManager.fieldInBlueprint(newDmp.getProfile(), SystemFieldType.GRANT, principal)) {
if(this.dataManagementProfileManager.fieldInBlueprint(newDmp.getProfile(), SystemFieldType.GRANT)) {
createGrantIfItDoesntExist(newDmp, apiContext.getOperationsContext().getDatabaseRepository().getGrantDao());
if(this.dataManagementProfileManager.fieldInBlueprint(newDmp.getProfile(), SystemFieldType.PROJECT, principal)) {
if(this.dataManagementProfileManager.fieldInBlueprint(newDmp.getProfile(), SystemFieldType.PROJECT)) {
if (newDmp.getProject() != null && newDmp.getGrant() != null && (newDmp.getProject().getLabel() == null || newDmp.getProject().getLabel().trim().isEmpty())) {
newDmp.setProject(newDmp.getProject().projectFromGrant(newDmp.getGrant()));
}
@ -515,7 +532,7 @@ public class DataManagementPlanManager {
} else dmp = new DMP();
newDmp.setCreated(dmp.getCreated() == null ? new Date() : dmp.getCreated());
if (newDmp.getUsers()!= null && newDmp.getUsers().stream().filter(userInfo -> userInfo.getUser().getId() == principal.getId())
if (newDmp.getUsers()!= null && newDmp.getUsers().stream().filter(userInfo -> userInfo.getUser().getId() == this.userScope.getUserIdSafe())
.collect(Collectors.toList()).size() == 0) {
List<UserDMP> userDMPList = new ArrayList<>(newDmp.getUsers());
for (UserInfoListingModel userInfoListingModel : dataManagementPlan.getUsers()) {
@ -527,16 +544,16 @@ public class DataManagementPlanManager {
}
}
if(this.dataManagementProfileManager.fieldInBlueprint(newDmp.getProfile(), SystemFieldType.GRANT, principal)) {
if(this.dataManagementProfileManager.fieldInBlueprint(newDmp.getProfile(), SystemFieldType.GRANT)) {
if (newDmp.getGrant() != null && newDmp.getGrant().getType().equals(Grant.GrantType.INTERNAL.getValue())) {
checkIfUserCanEditGrant(newDmp, user);
}
assignGrandUserIfInternal(newDmp, user);
}
if(this.dataManagementProfileManager.fieldInBlueprint(newDmp.getProfile(), SystemFieldType.FUNDER, principal)) {
if(this.dataManagementProfileManager.fieldInBlueprint(newDmp.getProfile(), SystemFieldType.FUNDER)) {
assignFunderUserIfInternal(newDmp, user);
}
if(this.dataManagementProfileManager.fieldInBlueprint(newDmp.getProfile(), SystemFieldType.PROJECT, principal)) {
if(this.dataManagementProfileManager.fieldInBlueprint(newDmp.getProfile(), SystemFieldType.PROJECT)) {
assignProjectUserIfInternal(newDmp, user);
}
@ -546,7 +563,7 @@ public class DataManagementPlanManager {
}
}
if(this.dataManagementProfileManager.fieldInBlueprint(newDmp.getProfile(), SystemFieldType.GRANT, principal)) {
if(this.dataManagementProfileManager.fieldInBlueprint(newDmp.getProfile(), SystemFieldType.GRANT)) {
if (newDmp.getGrant() != null) {
apiContext.getOperationsContext().getDatabaseRepository().getGrantDao().createOrUpdate(newDmp.getGrant());
}
@ -618,14 +635,14 @@ public class DataManagementPlanManager {
return newDmp;
}
public DMP createOrUpdateWithDatasets(DataManagementPlanEditorModel dataManagementPlan, Principal principal) throws Exception {
public DMP createOrUpdateWithDatasets(DataManagementPlanEditorModel dataManagementPlan) throws Exception {
if (dataManagementPlan.getId() != null) {
DMP dmp1 = apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().find(dataManagementPlan.getId());
Instant dbTime = Instant.ofEpochMilli(dmp1.getModified().getTime()).truncatedTo(ChronoUnit.SECONDS);
Instant modelTime = Instant.ofEpochMilli(dataManagementPlan.getModified().getTime()).truncatedTo(ChronoUnit.SECONDS);
if (!isUserOwnerOfDmp(dmp1, principal)) {
if (!isUserOwnerOfDmp(dmp1)) {
throw new Exception("User not being the creator is not authorized to edit this DMP.");
}
if (dbTime.toEpochMilli() != modelTime.toEpochMilli()) {
@ -645,25 +662,25 @@ public class DataManagementPlanManager {
if (tempDMP.getStatus() == (int) DMP.DMPStatus.FINALISED.getValue()) {
checkDmpValidationRules(tempDMP);
}
UserInfo user = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(principal.getId());
if(this.dataManagementProfileManager.fieldInBlueprint(tempDMP.getProfile(), SystemFieldType.ORGANIZATIONS, principal)) {
UserInfo user = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(this.userScope.getUserId());
if(this.dataManagementProfileManager.fieldInBlueprint(tempDMP.getProfile(), SystemFieldType.ORGANIZATIONS)) {
createOrganisationsIfTheyDontExist(tempDMP, apiContext.getOperationsContext().getDatabaseRepository().getOrganisationDao());
}
if(this.dataManagementProfileManager.fieldInBlueprint(tempDMP.getProfile(), SystemFieldType.RESEARCHERS, principal)) {
if(this.dataManagementProfileManager.fieldInBlueprint(tempDMP.getProfile(), SystemFieldType.RESEARCHERS)) {
createResearchersIfTheyDontExist(tempDMP, apiContext.getOperationsContext().getDatabaseRepository().getResearcherDao(), user);
}
if(this.dataManagementProfileManager.fieldInBlueprint(tempDMP.getProfile(), SystemFieldType.FUNDER, principal)) {
if(this.dataManagementProfileManager.fieldInBlueprint(tempDMP.getProfile(), SystemFieldType.FUNDER)) {
createFunderIfItDoesntExist(tempDMP, apiContext.getOperationsContext().getDatabaseRepository().getFunderDao());
}
if(this.dataManagementProfileManager.fieldInBlueprint(tempDMP.getProfile(), SystemFieldType.GRANT, principal)) {
if(this.dataManagementProfileManager.fieldInBlueprint(tempDMP.getProfile(), SystemFieldType.GRANT)) {
createGrantIfItDoesntExist(tempDMP, apiContext.getOperationsContext().getDatabaseRepository().getGrantDao());
}
DMP result = createOrUpdate(dataManagementPlan, principal);
DMP result = createOrUpdate(dataManagementPlan);
for (DatasetWizardModel datasetWizardModel: dataManagementPlan.getDatasets()) {
datasetWizardModel.setDmp(new DataManagementPlan().fromDataModel(result));
Dataset dataset = datasetManager.createOrUpdate(datasetWizardModel, principal);
Dataset dataset = datasetManager.createOrUpdate(datasetWizardModel);
datasets.add(dataset);
}
@ -675,9 +692,9 @@ public class DataManagementPlanManager {
return result;
}
public UUID newVersion(UUID uuid, DataManagementPlanNewVersionModel dataManagementPlan, Principal principal) throws Exception {
public UUID newVersion(UUID uuid, DataManagementPlanNewVersionModel dataManagementPlan) throws Exception {
DMP oldDmp = databaseRepository.getDmpDao().find(uuid);
if (!isUserOwnerOfDmp(oldDmp, principal)) {
if (!isUserOwnerOfDmp(oldDmp)) {
throw new Exception("User not being the creator is not authorized to perform this action.");
}
DataManagementPlanCriteria criteria = new DataManagementPlanCriteria();
@ -693,20 +710,20 @@ public class DataManagementPlanManager {
newDmp.setProfile(oldDmp.getProfile());
newDmp.setProperties(oldDmp.getProperties());
newDmp.setDmpProperties(oldDmp.getDmpProperties());
UserInfo user = apiContext.getOperationsContext().getBuilderFactory().getBuilder(UserInfoBuilder.class).id(principal.getId()).build();
UserInfo user = apiContext.getOperationsContext().getBuilderFactory().getBuilder(UserInfoBuilder.class).id(this.userScope.getUserId()).build();
newDmp.setCreator(user);
if(this.dataManagementProfileManager.fieldInBlueprint(newDmp.getProfile(), SystemFieldType.ORGANIZATIONS, principal)) {
if(this.dataManagementProfileManager.fieldInBlueprint(newDmp.getProfile(), SystemFieldType.ORGANIZATIONS)) {
createOrganisationsIfTheyDontExist(newDmp, databaseRepository.getOrganisationDao());
}
if(this.dataManagementProfileManager.fieldInBlueprint(newDmp.getProfile(), SystemFieldType.RESEARCHERS, principal)) {
if(this.dataManagementProfileManager.fieldInBlueprint(newDmp.getProfile(), SystemFieldType.RESEARCHERS)) {
createResearchersIfTheyDontExist(newDmp, databaseRepository.getResearcherDao(), user);
}
if(this.dataManagementProfileManager.fieldInBlueprint(newDmp.getProfile(), SystemFieldType.FUNDER, principal)) {
if(this.dataManagementProfileManager.fieldInBlueprint(newDmp.getProfile(), SystemFieldType.FUNDER)) {
createFunderIfItDoesntExist(newDmp, databaseRepository.getFunderDao());
}
if(this.dataManagementProfileManager.fieldInBlueprint(newDmp.getProfile(), SystemFieldType.GRANT, principal)) {
if(this.dataManagementProfileManager.fieldInBlueprint(newDmp.getProfile(), SystemFieldType.GRANT)) {
createGrantIfItDoesntExist(newDmp, databaseRepository.getGrantDao());
if(this.dataManagementProfileManager.fieldInBlueprint(newDmp.getProfile(), SystemFieldType.PROJECT, principal)) {
if(this.dataManagementProfileManager.fieldInBlueprint(newDmp.getProfile(), SystemFieldType.PROJECT)) {
if (newDmp.getProject() != null && newDmp.getGrant() != null && (newDmp.getProject().getLabel() == null || newDmp.getProject().getLabel().trim().isEmpty())) {
newDmp.setProject(newDmp.getProject().projectFromGrant(newDmp.getGrant()));
}
@ -718,19 +735,19 @@ public class DataManagementPlanManager {
newDmp.setVersion(oldDmp.getVersion() + 1);
newDmp.setId(null);
if(this.dataManagementProfileManager.fieldInBlueprint(newDmp.getProfile(), SystemFieldType.GRANT, principal)) {
if(this.dataManagementProfileManager.fieldInBlueprint(newDmp.getProfile(), SystemFieldType.GRANT)) {
if (newDmp.getGrant() != null && newDmp.getGrant().getType().equals(Grant.GrantType.INTERNAL.getValue())) {
checkIfUserCanEditGrant(newDmp, user);
}
assignGrandUserIfInternal(newDmp, user);
}
if(this.dataManagementProfileManager.fieldInBlueprint(newDmp.getProfile(), SystemFieldType.FUNDER, principal)) {
if(this.dataManagementProfileManager.fieldInBlueprint(newDmp.getProfile(), SystemFieldType.FUNDER)) {
assignFunderUserIfInternal(newDmp, user);
}
if(this.dataManagementProfileManager.fieldInBlueprint(newDmp.getProfile(), SystemFieldType.PROJECT, principal)) {
if(this.dataManagementProfileManager.fieldInBlueprint(newDmp.getProfile(), SystemFieldType.PROJECT)) {
assignProjectUserIfInternal(newDmp, user);
}
if(this.dataManagementProfileManager.fieldInBlueprint(newDmp.getProfile(), SystemFieldType.GRANT, principal)) {
if(this.dataManagementProfileManager.fieldInBlueprint(newDmp.getProfile(), SystemFieldType.GRANT)) {
if (newDmp.getGrant() != null) {
if (newDmp.getGrant().getStartdate() == null) {
newDmp.getGrant().setStartdate(new Date());
@ -775,27 +792,27 @@ public class DataManagementPlanManager {
}
}
public UUID clone(UUID uuid, DataManagementPlanNewVersionModel dataManagementPlan, Principal principal) throws Exception {
public UUID clone(UUID uuid, DataManagementPlanNewVersionModel dataManagementPlan) throws Exception {
DMP oldDmp = databaseRepository.getDmpDao().find(uuid);
DMP newDmp = dataManagementPlan.toDataModel();
newDmp.setProfile(oldDmp.getProfile());
newDmp.setProperties(oldDmp.getProperties());
newDmp.setDmpProperties(oldDmp.getDmpProperties());
UserInfo user = apiContext.getOperationsContext().getBuilderFactory().getBuilder(UserInfoBuilder.class).id(principal.getId()).build();
UserInfo user = apiContext.getOperationsContext().getBuilderFactory().getBuilder(UserInfoBuilder.class).id(this.userScope.getUserId()).build();
newDmp.setCreator(user);
if(this.dataManagementProfileManager.fieldInBlueprint(newDmp.getProfile(), SystemFieldType.ORGANIZATIONS, principal)) {
if(this.dataManagementProfileManager.fieldInBlueprint(newDmp.getProfile(), SystemFieldType.ORGANIZATIONS)) {
createOrganisationsIfTheyDontExist(newDmp, databaseRepository.getOrganisationDao());
}
if(this.dataManagementProfileManager.fieldInBlueprint(newDmp.getProfile(), SystemFieldType.RESEARCHERS, principal)) {
if(this.dataManagementProfileManager.fieldInBlueprint(newDmp.getProfile(), SystemFieldType.RESEARCHERS)) {
createResearchersIfTheyDontExist(newDmp, databaseRepository.getResearcherDao(), user);
}
if(this.dataManagementProfileManager.fieldInBlueprint(newDmp.getProfile(), SystemFieldType.FUNDER, principal)) {
if(this.dataManagementProfileManager.fieldInBlueprint(newDmp.getProfile(), SystemFieldType.FUNDER)) {
createFunderIfItDoesntExist(newDmp, databaseRepository.getFunderDao());
}
if(this.dataManagementProfileManager.fieldInBlueprint(newDmp.getProfile(), SystemFieldType.GRANT, principal)) {
if(this.dataManagementProfileManager.fieldInBlueprint(newDmp.getProfile(), SystemFieldType.GRANT)) {
createGrantIfItDoesntExist(newDmp, databaseRepository.getGrantDao());
if(this.dataManagementProfileManager.fieldInBlueprint(newDmp.getProfile(), SystemFieldType.PROJECT, principal)) {
if(this.dataManagementProfileManager.fieldInBlueprint(newDmp.getProfile(), SystemFieldType.PROJECT)) {
if (newDmp.getProject() != null && newDmp.getGrant() != null && (newDmp.getProject().getLabel() == null || newDmp.getProject().getLabel().trim().isEmpty())) {
newDmp.setProject(newDmp.getProject().projectFromGrant(newDmp.getGrant()));
}
@ -807,19 +824,19 @@ public class DataManagementPlanManager {
newDmp.setVersion(0);
newDmp.setId(null);
if(this.dataManagementProfileManager.fieldInBlueprint(newDmp.getProfile(), SystemFieldType.GRANT, principal)) {
if(this.dataManagementProfileManager.fieldInBlueprint(newDmp.getProfile(), SystemFieldType.GRANT)) {
if (newDmp.getGrant() != null && newDmp.getGrant().getType().equals(Grant.GrantType.INTERNAL.getValue())) {
checkIfUserCanEditGrant(newDmp, user);
}
assignGrandUserIfInternal(newDmp, user);
}
if(this.dataManagementProfileManager.fieldInBlueprint(newDmp.getProfile(), SystemFieldType.FUNDER, principal)) {
if(this.dataManagementProfileManager.fieldInBlueprint(newDmp.getProfile(), SystemFieldType.FUNDER)) {
assignFunderUserIfInternal(newDmp, user);
}
if(this.dataManagementProfileManager.fieldInBlueprint(newDmp.getProfile(), SystemFieldType.PROJECT, principal)) {
if(this.dataManagementProfileManager.fieldInBlueprint(newDmp.getProfile(), SystemFieldType.PROJECT)) {
assignProjectUserIfInternal(newDmp, user);
}
if(this.dataManagementProfileManager.fieldInBlueprint(newDmp.getProfile(), SystemFieldType.GRANT, principal)) {
if(this.dataManagementProfileManager.fieldInBlueprint(newDmp.getProfile(), SystemFieldType.GRANT)) {
if (newDmp.getGrant() != null) {
databaseRepository.getGrantDao().createOrUpdate(newDmp.getGrant());
}
@ -847,7 +864,7 @@ public class DataManagementPlanManager {
return newDmp.getId();
}
public void delete(UUID uuid) throws DMPWithDatasetsDeleteException, IOException {
public void delete(UUID uuid) throws DMPWithDatasetsDeleteException, IOException, InvalidApplicationException {
DatasetCriteria criteria = new DatasetCriteria();
List<UUID> dmpIds = Collections.singletonList(uuid);
criteria.setDmpIds(dmpIds);
@ -881,7 +898,7 @@ public class DataManagementPlanManager {
UUID tdmpId = dmp.getId();
dmp.setUsers(new HashSet<>(apiContext.getOperationsContext().getDatabaseRepository().getUserDmpDao().asQueryable().where((builder, root) -> builder.equal(root.get("dmp").get("id"), tdmpId)).toList()));
this.updateIndex(dmp);
} catch (IOException e) {
} catch (IOException | InvalidApplicationException e) {
logger.error(e.getMessage(), e);
}
for (Dataset dataset: dmp.getDataset()) {
@ -900,7 +917,7 @@ public class DataManagementPlanManager {
});
}
private void createResearchersIfTheyDontExist(DMP newDmp, ResearcherDao researcherRepository, UserInfo user) {
private void createResearchersIfTheyDontExist(DMP newDmp, ResearcherDao researcherRepository, UserInfo user) throws InvalidApplicationException {
if (newDmp.getResearchers() != null && !newDmp.getResearchers().isEmpty()) {
for (eu.eudat.data.old.Researcher researcher : newDmp.getResearchers()) {
ResearcherCriteria criteria = new ResearcherCriteria();
@ -916,7 +933,7 @@ public class DataManagementPlanManager {
}
}
private void createOrganisationsIfTheyDontExist(DMP newDmp, OrganisationDao organisationRepository) {
private void createOrganisationsIfTheyDontExist(DMP newDmp, OrganisationDao organisationRepository) throws InvalidApplicationException {
if (newDmp.getOrganisations() != null && !newDmp.getOrganisations().isEmpty()) {
for (Organisation organisation : newDmp.getOrganisations()) {
boolean createNew = false;
@ -940,7 +957,7 @@ public class DataManagementPlanManager {
}
}
private void createGrantIfItDoesntExist(DMP newDmp, GrantDao grantDao) {
private void createGrantIfItDoesntExist(DMP newDmp, GrantDao grantDao) throws InvalidApplicationException {
if (newDmp.getGrant() != null) {
Grant grant = newDmp.getGrant();
GrantCriteria criteria = new GrantCriteria();
@ -968,7 +985,7 @@ public class DataManagementPlanManager {
}
}
private void createFunderIfItDoesntExist(DMP newDmp, FunderDao funderDao) {
private void createFunderIfItDoesntExist(DMP newDmp, FunderDao funderDao) throws InvalidApplicationException {
if (newDmp.getGrant() != null && newDmp.getGrant().getFunder() != null) {
Funder funder = newDmp.getGrant().getFunder();
FunderCriteria criteria = new FunderCriteria();
@ -986,7 +1003,7 @@ public class DataManagementPlanManager {
}
}
private void createProjectIfItDoesntExist(DMP newDmp, ProjectDao projectDao) {
private void createProjectIfItDoesntExist(DMP newDmp, ProjectDao projectDao) throws InvalidApplicationException {
if (newDmp.getProject() != null) {
Project project = newDmp.getProject();
ProjectCriteria criteria = new ProjectCriteria();
@ -1013,7 +1030,7 @@ public class DataManagementPlanManager {
metricsManager.increaseValue(MetricNames.PROJECT, 1, null);
}
private void copyDatasets(DMP newDmp, DatasetDao datasetDao) {
private void copyDatasets(DMP newDmp, DatasetDao datasetDao) throws InvalidApplicationException {
List<CompletableFuture<Dataset>> futures = new LinkedList<>();
for (Dataset dataset : newDmp.getDataset()) {
Dataset tempDataset = datasetDao.find(dataset.getId());
@ -1092,7 +1109,7 @@ public class DataManagementPlanManager {
datasetElastic.setStatus(dataset1.getStatus());
datasetElastic.setDmp(dataset1.getDmp().getId());
datasetElastic.setGroup(dataset1.getDmp().getGroupId());
if(this.dataManagementProfileManager.fieldInBlueprint(dataset1.getDmp().getProfile(), SystemFieldType.GRANT, null)) {
if(this.dataManagementProfileManager.fieldInBlueprint(dataset1.getDmp().getProfile(), SystemFieldType.GRANT)) {
datasetElastic.setGrant(dataset1.getDmp().getGrant().getId());
}
if (dataset1.getDmp().getUsers() != null) {
@ -1115,7 +1132,7 @@ public class DataManagementPlanManager {
}).collect(Collectors.toList()));
}
datasetElastic.setPublic(dataset1.getDmp().isPublic());
if(this.dataManagementProfileManager.fieldInBlueprint(dataset1.getDmp().getProfile(), SystemFieldType.GRANT, null)) {
if(this.dataManagementProfileManager.fieldInBlueprint(dataset1.getDmp().getProfile(), SystemFieldType.GRANT)) {
datasetElastic.setGrantStatus(dataset1.getDmp().getGrant().getStatus());
}
@ -1136,10 +1153,10 @@ public class DataManagementPlanManager {
}
}
public void makePublic(UUID id, Principal principal) throws Exception {
public void makePublic(UUID id) throws Exception {
DMP dmp = this.apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().find(id);
// Check if dmp is finalized and if user is owner.
if (!isUserOwnerOfDmp(dmp, principal))
if (!isUserOwnerOfDmp(dmp))
throw new Exception("User does not have the privilege to do this action.");
if (!dmp.getStatus().equals(DMP.DMPStatus.FINALISED.getValue()))
throw new Exception("DMP is not finalized");
@ -1169,14 +1186,14 @@ public class DataManagementPlanManager {
}
});
});
UserInfo user = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(principal.getId());
UserInfo user = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(this.userScope.getUserId());
sendNotification(dmp, user, NotificationType.DMP_PUBLISH);
}
@Transactional
public void makeFinalize(UUID id, Principal principal, DatasetsToBeFinalized datasetsToBeFinalized) throws Exception {
public void makeFinalize(UUID id, DatasetsToBeFinalized datasetsToBeFinalized) throws Exception {
DMP dmp = this.apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().find(id);
if (!isUserOwnerOfDmp(dmp, principal))
if (!isUserOwnerOfDmp(dmp))
throw new Exception("User does not have the privilege to do this action.");
if (dmp.getStatus().equals(DMP.DMPStatus.FINALISED.getValue()))
throw new Exception("DMP is already finalized");
@ -1194,7 +1211,7 @@ public class DataManagementPlanManager {
wizardModel = wizardModel.fromDataModel(dataset);
wizardModel.setDatasetProfileDefinition(this.datasetManager.getPagedProfile(wizardModel, dataset));
try {
datasetManager.createOrUpdate(wizardModel, principal);
datasetManager.createOrUpdate(wizardModel);
} catch (Exception e) {
dataset.setStatus(status.getValue());
dataset.setFinalizedAt(finalizedDate);
@ -1247,7 +1264,7 @@ public class DataManagementPlanManager {
UUID dmpId = dmp.getId();
dmp.setUsers(new HashSet<>(apiContext.getOperationsContext().getDatabaseRepository().getUserDmpDao().asQueryable().where((builder, root) -> builder.equal(root.get("dmp").get("id"), dmpId)).toList()));
this.updateIndex(dmp);
UserInfo user = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(principal.getId());
UserInfo user = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(this.userScope.getUserId());
sendNotification(dmp, user, NotificationType.DMP_FINALISED);
metricsManager.decreaseValue(MetricNames.DMP, 1, MetricNames.DRAFT);
metricsManager.increaseValue(MetricNames.DMP, 1, MetricNames.FINALIZED);
@ -1256,9 +1273,9 @@ public class DataManagementPlanManager {
metricsManager.increaseValue(MetricNames.DATASET, indexDatasets.size(), MetricNames.FINALIZED);
}
public void undoFinalize(UUID id, Principal principal) throws Exception {
public void undoFinalize(UUID id) throws Exception {
DMP dmp = this.apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().find(id);
if (!isUserOwnerOfDmp(dmp, principal))
if (!isUserOwnerOfDmp(dmp))
throw new Exception("User does not have the privilege to do this action.");
if (dmp.getStatus().equals(DMP.DMPStatus.ACTIVE.getValue()))
throw new Exception("DMP is already Active");
@ -1275,9 +1292,9 @@ public class DataManagementPlanManager {
metricsManager.increaseValue(MetricNames.DMP, 1, MetricNames.DRAFT);
}
public void updateUsers(UUID id, List<UserInfoListingModel> users, Principal principal) throws Exception {
public void updateUsers(UUID id, List<UserInfoListingModel> users) throws Exception {
DMP dmp = this.apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().find(id);
if (!isUserOwnerOfDmp(dmp, principal))
if (!isUserOwnerOfDmp(dmp))
throw new Exception("User does not have the privilege to do this action.");
clearUsers(dmp);
for (UserInfoListingModel userListing : users) {
@ -1291,18 +1308,18 @@ public class DataManagementPlanManager {
* Export Data
* */
public FileEnvelope getWordDocument(String id, Principal principal, ConfigLoader configLoader) throws IOException {
return this.getWordDocument(id, principal, configLoader, true);
public FileEnvelope getWordDocument(String id, ConfigLoader configLoader) throws IOException, InvalidApplicationException {
return this.getWordDocument(id, configLoader, true);
}
public FileEnvelope getWordDocument(String id, Principal principal, ConfigLoader configLoader, Boolean versioned) throws IOException {
public FileEnvelope getWordDocument(String id, ConfigLoader configLoader, Boolean versioned) throws IOException, InvalidApplicationException {
WordBuilder wordBuilder = new WordBuilder(this.environment, configLoader);
VisibilityRuleService visibilityRuleService = new VisibilityRuleServiceImpl();
DatasetWizardModel dataset = new DatasetWizardModel();
XWPFDocument document = configLoader.getDocument();
DMP dmpEntity = databaseRepository.getDmpDao().find(UUID.fromString(id));
if (!dmpEntity.isPublic() && dmpEntity.getUsers().stream().filter(userInfo -> userInfo.getUser().getId() == principal.getId()).collect(Collectors.toList()).size() == 0)
if (!dmpEntity.isPublic() && dmpEntity.getUsers().stream().filter(userInfo -> userInfo.getUser().getId() == this.userScope.getUserIdSafe()).collect(Collectors.toList()).size() == 0)
throw new UnauthorisedException();
wordBuilder.fillFirstPage(dmpEntity, null, document, false);
@ -1678,11 +1695,11 @@ public class DataManagementPlanManager {
return exportEnvelope;
}
private FileEnvelope getXmlDocument(String id, Principal principal) throws InstantiationException, IllegalAccessException, IOException {
private FileEnvelope getXmlDocument(String id) throws IOException, InvalidApplicationException {
ExportXmlBuilder xmlBuilder = new ExportXmlBuilder();
VisibilityRuleService visibilityRuleService = new VisibilityRuleServiceImpl();
DMP dmp = databaseRepository.getDmpDao().find(UUID.fromString(id));
if (!dmp.isPublic() && dmp.getUsers().stream().filter(userInfo -> userInfo.getUser().getId() == principal.getId()).collect(Collectors.toList()).size() == 0)
if (!dmp.isPublic() && dmp.getUsers().stream().filter(userInfo -> userInfo.getUser().getId() == this.userScope.getUserIdSafe()).collect(Collectors.toList()).size() == 0)
throw new UnauthorisedException();
final Boolean isFinalized = dmp.getStatus() == DMP.DMPStatus.FINALISED.getValue();
final Boolean isPublic = dmp.isPublic();
@ -1772,7 +1789,7 @@ public class DataManagementPlanManager {
// Funder.
Element funder = xmlDoc.createElement("funder");
if (this.dataManagementProfileManager.fieldInBlueprint(dmp.getProfile(), SystemFieldType.GRANT, principal) && this.dataManagementProfileManager.fieldInBlueprint(dmp.getProfile(), SystemFieldType.FUNDER, principal)) {
if (this.dataManagementProfileManager.fieldInBlueprint(dmp.getProfile(), SystemFieldType.GRANT) && this.dataManagementProfileManager.fieldInBlueprint(dmp.getProfile(), SystemFieldType.FUNDER)) {
Element funderLabel = xmlDoc.createElement("label");
Element funderId = xmlDoc.createElement("id");
funderLabel.setTextContent(dmp.getGrant().getFunder().getLabel());
@ -1790,7 +1807,7 @@ public class DataManagementPlanManager {
dmpElement.appendChild(funder);
// Grant.
Element grant = xmlDoc.createElement("grant");
if (this.dataManagementProfileManager.fieldInBlueprint(dmp.getProfile(), SystemFieldType.GRANT, principal)) {
if (this.dataManagementProfileManager.fieldInBlueprint(dmp.getProfile(), SystemFieldType.GRANT)) {
Element grantLabel = xmlDoc.createElement("label");
Element grantId = xmlDoc.createElement("id");
grantLabel.setTextContent(dmp.getGrant().getLabel());
@ -1808,7 +1825,7 @@ public class DataManagementPlanManager {
dmpElement.appendChild(grant);
// Project.
Element project = xmlDoc.createElement("project");
if (this.dataManagementProfileManager.fieldInBlueprint(dmp.getProfile(), SystemFieldType.PROJECT, principal)) {
if (this.dataManagementProfileManager.fieldInBlueprint(dmp.getProfile(), SystemFieldType.PROJECT)) {
Element projectId = xmlDoc.createElement("id");
Element projectLabel = xmlDoc.createElement("label");
Element projectDescription = xmlDoc.createElement("description");
@ -1855,7 +1872,7 @@ public class DataManagementPlanManager {
Element extraFields = xmlDoc.createElement("extraFields");
Map<String, Object> dmpProperties = new ObjectMapper().readValue(dmp.getProperties(), new TypeReference<Map<String, Object>>() {});
DataManagementPlanBlueprint blueprint = this.dataManagementProfileManager.getSingleBlueprint(dmp.getProfile().getId().toString(), principal).getDefinition();
DataManagementPlanBlueprint blueprint = this.dataManagementProfileManager.getSingleBlueprint(dmp.getProfile().getId().toString()).getDefinition();
blueprint.getSections().forEach(section -> {
section.getFields().forEach(fieldModel -> {
if (fieldModel.getCategory() == FieldCategory.EXTRA) {
@ -1958,9 +1975,9 @@ public class DataManagementPlanManager {
return fileEnvelope;
}
public FileEnvelope getRDAJsonDocument(String id, Principal principal) throws Exception {
public FileEnvelope getRDAJsonDocument(String id) throws Exception {
DMP dmp = databaseRepository.getDmpDao().find(UUID.fromString(id));
if (!dmp.isPublic() && dmp.getUsers().stream().noneMatch(userInfo -> userInfo.getUser().getId() == principal.getId()))
if (!dmp.isPublic() && dmp.getUsers().stream().noneMatch(userInfo -> userInfo.getUser().getId() == this.userScope.getUserIdSafe()))
throw new UnauthorisedException();
final boolean isFinalized = dmp.getStatus() == DMP.DMPStatus.FINALISED.getValue();
final boolean isPublic = dmp.isPublic();
@ -1996,17 +2013,17 @@ public class DataManagementPlanManager {
return rdaJsonDocument;
}
public ResponseEntity<byte[]> getDocument(String id, String contentType, Principal principal, ConfigLoader configLoader) throws InstantiationException, IllegalAccessException, IOException {
public ResponseEntity<byte[]> getDocument(String id, String contentType, ConfigLoader configLoader) throws InstantiationException, IllegalAccessException, IOException, InvalidApplicationException {
FileEnvelope file;
switch (contentType) {
case "application/xml":
file = getXmlDocument(id, principal);
file = getXmlDocument(id);
break;
case "application/msword":
file = getWordDocument(id, principal, configLoader);
file = getWordDocument(id, configLoader);
break;
default:
file = getXmlDocument(id, principal);
file = getXmlDocument(id);
}
String fileName = file.getFilename().replace(" ", "_").replace(",", "_");
InputStream resource = new FileInputStream(file.getFile());
@ -2029,7 +2046,7 @@ public class DataManagementPlanManager {
* Data Import
* */
public List<DmpImportModel> createDmpFromXml(MultipartFile[] files, Principal principal, String[] profiles) throws IOException, JAXBException, Exception {
public List<DmpImportModel> createDmpFromXml(MultipartFile[] files, String[] profiles) throws IOException, JAXBException, Exception {
List<DmpImportModel> dataManagementPlans = new ArrayList<>();
// Jaxb approach.
JAXBContext jaxbContext;
@ -2070,7 +2087,7 @@ public class DataManagementPlanManager {
}
dm.setProperties(dmpPropertiesMap);
if (this.dataManagementProfileManager.fieldInBlueprint(dmpProfileImportModel.getDmpProfileId().toString(), SystemFieldType.FUNDER, principal)) {
if (this.dataManagementProfileManager.fieldInBlueprint(dmpProfileImportModel.getDmpProfileId().toString(), SystemFieldType.FUNDER)) {
eu.eudat.models.data.funder.Funder funder = new eu.eudat.models.data.funder.Funder();
FunderImportModels funderImport = dataManagementPlans.get(0).getFunderImportModels();
funder.setId(funderImport.getId());
@ -2081,7 +2098,7 @@ public class DataManagementPlanManager {
dm.setFunder(funderEditor);
}
if (this.dataManagementProfileManager.fieldInBlueprint(dmpProfileImportModel.getDmpProfileId().toString(), SystemFieldType.GRANT, principal)) {
if (this.dataManagementProfileManager.fieldInBlueprint(dmpProfileImportModel.getDmpProfileId().toString(), SystemFieldType.GRANT)) {
eu.eudat.models.data.grant.Grant grant = new eu.eudat.models.data.grant.Grant();
GrantImportModels grantImport = dataManagementPlans.get(0).getGrantImport();
grant.setId(grantImport.getId());
@ -2094,7 +2111,7 @@ public class DataManagementPlanManager {
dm.setGrant(grantEditor);
}
if (this.dataManagementProfileManager.fieldInBlueprint(dmpProfileImportModel.getDmpProfileId().toString(), SystemFieldType.PROJECT, principal)) {
if (this.dataManagementProfileManager.fieldInBlueprint(dmpProfileImportModel.getDmpProfileId().toString(), SystemFieldType.PROJECT)) {
eu.eudat.models.data.project.Project project = new eu.eudat.models.data.project.Project();
ProjectImportModels projectImport = dataManagementPlans.get(0).getProjectImportModels();
project.setId(projectImport.getId());
@ -2175,7 +2192,7 @@ public class DataManagementPlanManager {
dm.setExtraProperties(extraPropertiesMap);
//createOrUpdate(apiContext, dm, principal);
DMP dmp = this.createOrUpdate(dm, principal);
DMP dmp = this.createOrUpdate(dm);
if (dmp.getOrganisations() == null) {
dmp.setOrganisations(new HashSet<>());
}
@ -2212,7 +2229,7 @@ public class DataManagementPlanManager {
DatasetWizardModel datasetWizard = new DatasetWizardModel();
datasetWizard.setDatasetProfileDefinition(this.datasetManager.getPagedProfile(datasetWizard, dataset));
datasetWizard.fromDataModel(dataset);
this.datasetManager.createOrUpdate(datasetWizard, principal);
this.datasetManager.createOrUpdate(datasetWizard);
// datasets.add(new DatasetListingModel().fromDataModel(dataset));
}
}
@ -2220,15 +2237,15 @@ public class DataManagementPlanManager {
return dataManagementPlans;
}
public List<DMP> createFromRDA(MultipartFile[] files, Principal principal, String[] profiles) throws IOException {
if (principal.getId() == null) {
public List<DMP> createFromRDA(MultipartFile[] files, String[] profiles) throws IOException, InvalidApplicationException {
if (!this.userScope.isSet()) {
throw new UnauthorisedException("No user is logged in");
}
List<DMP> result = new ArrayList<>();
for (MultipartFile file: files) {
DMP dmp = rdaManager.convertToEntity(new String(file.getBytes(), "UTF-8"), profiles);
dmp.setLabel(file.getOriginalFilename());
UserInfo me = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(principal.getId());
UserInfo me = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(this.userScope.getUserId());
dmp.setModified(new Date());
dmp.setCreator(me);
Map<String, String> extraProperties = objectMapper.readValue(dmp.getExtraProperties(), HashMap.class);
@ -2269,7 +2286,11 @@ public class DataManagementPlanManager {
if (dmp.getResearchers() == null) {
dmp.setResearchers(new HashSet<>());
}
dmp.setUsers(new HashSet<>(apiContext.getOperationsContext().getDatabaseRepository().getUserDmpDao().asQueryable().where((builder, root) -> builder.equal(root.get("dmp").get("id"), dmp.getId())).toList()));
try {
dmp.setUsers(new HashSet<>(apiContext.getOperationsContext().getDatabaseRepository().getUserDmpDao().asQueryable().where((builder, root) -> builder.equal(root.get("dmp").get("id"), dmp.getId())).toList()));
} catch (InvalidApplicationException e) {
throw new RuntimeException(e);
}
try {
List<Tag> tags = new ArrayList<>();
eu.eudat.elastic.entities.Dataset elastic = apiContext.getOperationsContext().getElasticRepository().getDatasetRepository().findDocument(dataset.getId().toString());
@ -2306,7 +2327,7 @@ public class DataManagementPlanManager {
databaseRepository.getUserDmpDao().createOrUpdate(userDMP);
}
private void clearUsers(DMP dmp) {
private void clearUsers(DMP dmp) throws InvalidApplicationException {
List<UserDMP> userDMPs = apiContext.getOperationsContext().getDatabaseRepository().getUserDmpDao().asQueryable().where(((builder, root) -> builder.equal(root.get("dmp").get("id"), dmp.getId()))).toList();
userDMPs.forEach(userDMP -> apiContext.getOperationsContext().getDatabaseRepository().getUserDmpDao().delete(userDMP));
}
@ -2333,7 +2354,7 @@ public class DataManagementPlanManager {
* Data Index
* */
private void updateGroupIndex(UUID groupId) {
private void updateGroupIndex(UUID groupId) throws InvalidApplicationException {
DataManagementPlanCriteria criteria = new DataManagementPlanCriteria();
criteria.setGroupIds(Collections.singletonList(groupId));
criteria.setAllVersions(true);
@ -2345,7 +2366,7 @@ public class DataManagementPlanManager {
dmp.setUsers(new HashSet<>(apiContext.getOperationsContext().getDatabaseRepository().getUserDmpDao().asQueryable().where((builder, root) -> builder.equal(root.get("dmp").get("id"), dmpId)).toList()));
}
this.updateIndex(dmp);
} catch (IOException e) {
} catch (IOException | InvalidApplicationException e) {
logger.error(e.getMessage(), e);
}
}
@ -2370,14 +2391,14 @@ public class DataManagementPlanManager {
});
}
public void updateIndex(DMP dmp) throws IOException {
public void updateIndex(DMP dmp) throws IOException, InvalidApplicationException {
DmpMapper mapper = new DmpMapper(apiContext, datasetManager);
Dmp elastic = mapper.toElastic(dmp);
apiContext.getOperationsContext().getElasticRepository().getDmpRepository().createOrUpdate(elastic);
}
public void generateIndex(Principal principal) {
if (principal.getAuthorities().contains(Authorities.ADMIN.getValue())) {
public void generateIndex() throws InvalidApplicationException {
if (this.authorizationService.authorize(Permission.AdminRole)) {
if (apiContext.getOperationsContext().getElasticRepository().getDmpRepository().createIndex()) {
List<DMP> dmps = apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().asQueryable().toList();
dmps.forEach(dmp -> {
@ -2385,7 +2406,7 @@ public class DataManagementPlanManager {
UUID dmpId = dmp.getId();
dmp.setUsers(new HashSet<>(apiContext.getOperationsContext().getDatabaseRepository().getUserDmpDao().asQueryable().where((builder, root) -> builder.equal(root.get("dmp").get("id"), dmpId)).toList()));
this.updateIndex(dmp);
} catch (IOException e) {
} catch (IOException | InvalidApplicationException e) {
logger.error(e.getMessage(), e);
}
});
@ -2393,8 +2414,8 @@ public class DataManagementPlanManager {
}
}
public void clearIndex(Principal principal) throws IOException {
if (principal.getAuthorities().contains(Authorities.ADMIN.getValue())) {
public void clearIndex() throws IOException {
if (this.authorizationService.authorize(Permission.AdminRole)) {
apiContext.getOperationsContext().getElasticRepository().getDmpRepository().clear();
}
}
@ -2430,15 +2451,15 @@ public class DataManagementPlanManager {
}
}
private boolean isUserOwnerOfDmp(DMP dmp, Principal principal) {
return (dmp.getUsers().stream().filter(userDMP -> userDMP.getRole().equals(UserDMP.UserDMPRoles.OWNER.getValue())).map(userDMP -> userDMP.getUser().getId())).collect(Collectors.toList()).contains(principal.getId());
private boolean isUserOwnerOfDmp(DMP dmp) throws InvalidApplicationException {
return this.userScope.isSet() && (dmp.getUsers().stream().filter(userDMP -> userDMP.getRole().equals(UserDMP.UserDMPRoles.OWNER.getValue())).map(userDMP -> userDMP.getUser().getId())).collect(Collectors.toList()).contains(this.userScope.getUserId());
}
/*
* DOI Generation
* */
private String getPreviousDOI(UUID groupId, UUID selfId, String repositoryId) {
private String getPreviousDOI(UUID groupId, UUID selfId, String repositoryId) throws InvalidApplicationException {
DataManagementPlanCriteria criteria = new DataManagementPlanCriteria();
List<UUID> groupIds = new ArrayList<>();
groupIds.add(groupId);
@ -2462,16 +2483,16 @@ public class DataManagementPlanManager {
return null;
}
public Doi createDoi(DepositRequest depositRequest, Principal principal) throws Exception {
public Doi createDoi(DepositRequest depositRequest) throws Exception {
DMP dmp = this.apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().find(UUID.fromString(depositRequest.getDmpId()));
if (!isUserOwnerOfDmp(dmp, principal))
if (!isUserOwnerOfDmp(dmp))
throw new Exception("User is not authorized to invoke this action");
if (!dmp.getStatus().equals(DMP.DMPStatus.FINALISED.getValue()))
throw new Exception("DMP is not finalized");
/*if (dmp.getDoi() != null)
throw new Exception("DMP already has a DOI");*/
FileEnvelope file = getWordDocument(depositRequest.getDmpId(), principal, configLoader);
FileEnvelope file = getWordDocument(depositRequest.getDmpId(), configLoader);
String name = file.getFilename().substring(0, file.getFilename().length() - 5).replaceAll("[^a-zA-Z0-9_+ ]", "").replace(" ", "_").replace(",", "_");
File pdfFile = PDFUtils.convertToPDF(file, environment);
eu.eudat.depositinterface.models.FileEnvelope pdfEnvelope = new eu.eudat.depositinterface.models.FileEnvelope();
@ -2479,7 +2500,7 @@ public class DataManagementPlanManager {
pdfEnvelope.setFilename(name + ".pdf");
eu.eudat.depositinterface.models.FileEnvelope rdaJsonFile = new eu.eudat.depositinterface.models.FileEnvelope();
try {
FileEnvelope rdaJsonDocument = getRDAJsonDocument(depositRequest.getDmpId(), principal);
FileEnvelope rdaJsonDocument = getRDAJsonDocument(depositRequest.getDmpId());
rdaJsonFile.setFile(rdaJsonDocument.getFile());
rdaJsonFile.setFilename(rdaJsonDocument.getFilename());
} catch (Exception e) {
@ -2533,7 +2554,7 @@ public class DataManagementPlanManager {
}
private File createSupportingFilesZip(DMP dmp) throws IOException {
private File createSupportingFilesZip(DMP dmp) throws IOException, InvalidApplicationException {
FileOutputStream fout = new FileOutputStream(this.environment.getProperty("temp.temp") + "supportingFiles.zip");
ZipOutputStream zout = new ZipOutputStream(fout);
@ -2565,7 +2586,7 @@ public class DataManagementPlanManager {
* Misc
* */
private void sendNotification(DMP dmp, UserInfo user, NotificationType notificationType) {
private void sendNotification(DMP dmp, UserInfo user, NotificationType notificationType) throws InvalidApplicationException {
List<UserDMP> userDMPS = databaseRepository.getUserDmpDao().asQueryable().where(((builder, root) -> builder.equal(root.get("dmp").get("id"), dmp.getId()))).toList();
for (UserDMP userDMP : userDMPS) {
if (!userDMP.getUser().getId().equals(user.getId())) {

View File

@ -22,7 +22,6 @@ import eu.eudat.models.data.helpers.common.AutoCompleteLookupItem;
import eu.eudat.models.data.helpers.common.DataTableData;
import eu.eudat.models.data.listingmodels.DataManagementPlanBlueprintListingModel;
import eu.eudat.models.data.listingmodels.DataManagementPlanProfileListingModel;
import eu.eudat.models.data.security.Principal;
import eu.eudat.queryable.QueryableList;
import eu.eudat.logic.services.ApiContext;
import org.slf4j.Logger;
@ -33,6 +32,8 @@ import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import jakarta.activation.MimetypesFileTypeMap;
import javax.management.InvalidApplicationException;
import javax.xml.xpath.*;
import java.io.*;
import java.nio.file.Files;
@ -63,7 +64,7 @@ public class DataManagementProfileManager {
this.environment = environment;
}
public DataTableData<DataManagementPlanProfileListingModel> getPaged(DataManagementPlanProfileTableRequest dataManagementPlanProfileTableRequest, Principal principal) throws Exception {
public DataTableData<DataManagementPlanProfileListingModel> getPaged(DataManagementPlanProfileTableRequest dataManagementPlanProfileTableRequest) throws Exception {
QueryableList<DMPProfile> items = apiContext.getOperationsContext().getDatabaseRepository().getDmpProfileDao().getWithCriteria(dataManagementPlanProfileTableRequest.getCriteria());
QueryableList<DMPProfile> pagedItems = PaginationManager.applyPaging(items, dataManagementPlanProfileTableRequest);
@ -82,7 +83,7 @@ public class DataManagementProfileManager {
return dataTable;
}
public DataTableData<DataManagementPlanBlueprintListingModel> getPagedBlueprint(DataManagementPlanBlueprintTableRequest dataManagementPlanBlueprintTableRequest, Principal principal) throws Exception {
public DataTableData<DataManagementPlanBlueprintListingModel> getPagedBlueprint(DataManagementPlanBlueprintTableRequest dataManagementPlanBlueprintTableRequest) throws Exception {
QueryableList<DMPProfile> items = apiContext.getOperationsContext().getDatabaseRepository().getDmpProfileDao().getWithCriteriaBlueprint(dataManagementPlanBlueprintTableRequest.getCriteria());
QueryableList<DMPProfile> pagedItems = PaginationManager.applyPaging(items, dataManagementPlanBlueprintTableRequest);
@ -96,26 +97,26 @@ public class DataManagementProfileManager {
return dataTable;
}
public DataManagementPlanProfileListingModel getSingle(String id, Principal principal) throws InstantiationException, IllegalAccessException {
public DataManagementPlanProfileListingModel getSingle(String id) throws InstantiationException, IllegalAccessException, InvalidApplicationException {
DMPProfile dmpProfile = databaseRepository.getDmpProfileDao().find(UUID.fromString(id));
DataManagementPlanProfileListingModel dataManagementPlanProfileListingModel = new DataManagementPlanProfileListingModel();
dataManagementPlanProfileListingModel.fromDataModel(dmpProfile);
return dataManagementPlanProfileListingModel;
}
public DataManagementPlanBlueprintListingModel getSingleBlueprint(String id, Principal principal) {
public DataManagementPlanBlueprintListingModel getSingleBlueprint(String id) throws InvalidApplicationException {
DMPProfile dmpProfile = databaseRepository.getDmpProfileDao().find(UUID.fromString(id));
DataManagementPlanBlueprintListingModel dataManagementPlanBlueprintListingModel = new DataManagementPlanBlueprintListingModel();
dataManagementPlanBlueprintListingModel.fromDataModel(dmpProfile);
return dataManagementPlanBlueprintListingModel;
}
public boolean fieldInBlueprint(String id, SystemFieldType type, Principal principal) {
public boolean fieldInBlueprint(String id, SystemFieldType type) throws InvalidApplicationException {
DMPProfile dmpProfile = databaseRepository.getDmpProfileDao().find(UUID.fromString(id));
return this.fieldInBlueprint(dmpProfile, type, principal);
return this.fieldInBlueprint(dmpProfile, type);
}
public boolean fieldInBlueprint(DMPProfile dmpProfile, SystemFieldType type, Principal principal) {
public boolean fieldInBlueprint(DMPProfile dmpProfile, SystemFieldType type) {
DataManagementPlanBlueprintListingModel dmpBlueprint = new DataManagementPlanBlueprintListingModel();
dmpBlueprint.fromDataModel(dmpProfile);
for(Section section: dmpBlueprint.getDefinition().getSections()){
@ -131,23 +132,23 @@ public class DataManagementProfileManager {
return false;
}
public List<DataManagementPlanProfileListingModel> getWithCriteria(DataManagementPlanProfileCriteriaRequest dataManagementPlanProfileCriteriaRequest) throws IllegalAccessException, InstantiationException {
public List<DataManagementPlanProfileListingModel> getWithCriteria(DataManagementPlanProfileCriteriaRequest dataManagementPlanProfileCriteriaRequest) throws IllegalAccessException, InstantiationException, InvalidApplicationException {
QueryableList<DMPProfile> items = databaseRepository.getDmpProfileDao().getWithCriteria(dataManagementPlanProfileCriteriaRequest.getCriteria());
List<DataManagementPlanProfileListingModel> datamanagementPlans = items.select(item -> new DataManagementPlanProfileListingModel().fromDataModel(item));
return datamanagementPlans;
}
public void createOrUpdate(DataManagementPlanProfileListingModel dataManagementPlanProfileListingModel, Principal principal) throws Exception {
public void createOrUpdate(DataManagementPlanProfileListingModel dataManagementPlanProfileListingModel) throws Exception {
DMPProfile dmpProfile = dataManagementPlanProfileListingModel.toDataModel();
apiContext.getOperationsContext().getDatabaseRepository().getDmpProfileDao().createOrUpdate(dmpProfile);
}
public void createOrUpdateBlueprint(DataManagementPlanBlueprintListingModel dataManagementPlanBlueprintListingModel, Principal principal) throws Exception {
public void createOrUpdateBlueprint(DataManagementPlanBlueprintListingModel dataManagementPlanBlueprintListingModel) throws Exception {
DMPProfile dmpProfile = dataManagementPlanBlueprintListingModel.toDataModel();
apiContext.getOperationsContext().getDatabaseRepository().getDmpProfileDao().createOrUpdate(dmpProfile);
}
public void inactivate(String id) {
public void inactivate(String id) throws InvalidApplicationException {
DMPProfile dmpProfile = databaseRepository.getDmpProfileDao().find(UUID.fromString(id));
DataManagementPlanCriteria dataManagementPlanCriteria = new DataManagementPlanCriteria();
dataManagementPlanCriteria.setProfile(dmpProfile);
@ -208,7 +209,7 @@ public class DataManagementProfileManager {
return convFile;
}
public List<Tuple<String, String>> getExternalAutocomplete(RequestItem<AutoCompleteLookupItem> lookupItem) throws XPathExpressionException {
public List<Tuple<String, String>> getExternalAutocomplete(RequestItem<AutoCompleteLookupItem> lookupItem) throws XPathExpressionException, InvalidApplicationException {
DMPProfile dmpProfile = this.apiContext.getOperationsContext().getDatabaseRepository().getDmpProfileDao().find(UUID.fromString(lookupItem.getCriteria().getProfileID()));
Field field = this.queryForField(dmpProfile.getDefinition(), lookupItem.getCriteria().getFieldID());
DmpProfileExternalAutoComplete data = field.getExternalAutocomplete();

View File

@ -2,6 +2,7 @@ package eu.eudat.logic.managers;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import eu.eudat.commons.scope.user.UserScope;
import eu.eudat.data.dao.criteria.DataRepositoryCriteria;
import eu.eudat.data.old.DataRepository;
import eu.eudat.logic.proxy.config.ExternalUrlCriteria;
@ -9,10 +10,10 @@ import eu.eudat.logic.proxy.config.exceptions.HugeResultSet;
import eu.eudat.logic.proxy.config.exceptions.NoURLFound;
import eu.eudat.logic.services.ApiContext;
import eu.eudat.models.data.datarepository.DataRepositoryModel;
import eu.eudat.models.data.security.Principal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.management.InvalidApplicationException;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
@ -24,25 +25,27 @@ import java.util.stream.Collectors;
@Component
public class DataRepositoryManager {
private ApiContext apiContext;
private UserScope userScope;
@Autowired
public DataRepositoryManager(ApiContext apiContext) {
public DataRepositoryManager(ApiContext apiContext, UserScope userScope) {
this.apiContext = apiContext;
this.userScope = userScope;
}
public DataRepository create(eu.eudat.models.data.datarepository.DataRepositoryModel dataRepositoryModel, Principal principal) throws Exception {
public DataRepository create(eu.eudat.models.data.datarepository.DataRepositoryModel dataRepositoryModel) throws Exception {
DataRepository dataRepository = dataRepositoryModel.toDataModel();
dataRepository.getCreationUser().setId(principal.getId());
dataRepository.getCreationUser().setId(userScope.getUserId());
return apiContext.getOperationsContext().getDatabaseRepository().getDataRepositoryDao().createOrUpdate(dataRepository);
}
public List<DataRepositoryModel> getDataRepositories(String query, String type, Principal principal) throws HugeResultSet, NoURLFound {
public List<DataRepositoryModel> getDataRepositories(String query, String type) throws HugeResultSet, NoURLFound, InvalidApplicationException {
ExternalUrlCriteria externalUrlCriteria = new ExternalUrlCriteria(query);
List<Map<String, String>> remoteRepos = this.apiContext.getOperationsContext().getRemoteFetcher().getRepositories(externalUrlCriteria, type);
DataRepositoryCriteria criteria = new DataRepositoryCriteria();
if (!query.isEmpty()) criteria.setLike(query);
criteria.setCreationUserId(principal.getId());
criteria.setCreationUserId(userScope.getUserId());
List<DataRepositoryModel> dataRepositoryModels = new LinkedList<>();
if (type.equals("")) {
@ -55,13 +58,13 @@ public class DataRepositoryManager {
return dataRepositoryModels;
}
public List<DataRepositoryModel> getPubRepositories(String query, String type, Principal principal) throws HugeResultSet, NoURLFound {
public List<DataRepositoryModel> getPubRepositories(String query, String type) throws HugeResultSet, NoURLFound, InvalidApplicationException {
ExternalUrlCriteria externalUrlCriteria = new ExternalUrlCriteria(query);
List<Map<String, String>> remoteRepos = this.apiContext.getOperationsContext().getRemoteFetcher().getPubRepositories(externalUrlCriteria, type);
DataRepositoryCriteria criteria = new DataRepositoryCriteria();
if (!query.isEmpty()) criteria.setLike(query);
criteria.setCreationUserId(principal.getId());
criteria.setCreationUserId(userScope.getUserId());
List<DataRepositoryModel> dataRepositoryModels = new LinkedList<>();
if (type.equals("")) {
@ -74,13 +77,13 @@ public class DataRepositoryManager {
return dataRepositoryModels;
}
public List<DataRepositoryModel> getJournals(String query, String type, Principal principal) throws HugeResultSet, NoURLFound {
public List<DataRepositoryModel> getJournals(String query, String type) throws HugeResultSet, NoURLFound, InvalidApplicationException {
ExternalUrlCriteria externalUrlCriteria = new ExternalUrlCriteria(query);
List<Map<String, String>> remoteRepos = this.apiContext.getOperationsContext().getRemoteFetcher().getJournals(externalUrlCriteria, type);
DataRepositoryCriteria criteria = new DataRepositoryCriteria();
if (!query.isEmpty()) criteria.setLike(query);
criteria.setCreationUserId(principal.getId());
criteria.setCreationUserId(userScope.getUserId());
List<DataRepositoryModel> dataRepositoryModels = new LinkedList<>();
if (type.equals("")) {

View File

@ -4,6 +4,8 @@ import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import eu.eudat.authorization.Permission;
import eu.eudat.commons.scope.user.UserScope;
import eu.eudat.data.dao.criteria.*;
import eu.eudat.data.dao.entities.DataRepositoryDao;
import eu.eudat.data.dao.entities.DatasetDao;
@ -47,11 +49,11 @@ import eu.eudat.models.data.dmp.AssociatedProfile;
import eu.eudat.models.data.dmp.DataManagementPlan;
import eu.eudat.models.data.helpers.common.DataTableData;
import eu.eudat.models.data.listingmodels.DatasetListingModel;
import eu.eudat.models.data.security.Principal;
import eu.eudat.models.data.user.composite.PagedDatasetProfile;
import eu.eudat.queryable.QueryableList;
import eu.eudat.types.Authorities;
import eu.eudat.types.MetricNames;
import gr.cite.commons.web.authz.service.AuthorizationService;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
@ -79,6 +81,8 @@ import jakarta.transaction.Transactional;
import jakarta.xml.bind.JAXBContext;
import jakarta.xml.bind.JAXBException;
import jakarta.xml.bind.Unmarshaller;
import javax.management.InvalidApplicationException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
@ -111,10 +115,12 @@ public class DatasetManager {
private Environment environment;
private final MetricsManager metricsManager;
private final FileManager fileManager;
private final UserScope userScope;
private final AuthorizationService authorizationService;
@Autowired
public DatasetManager(ApiContext apiContext, UserManager userManager, ConfigLoader configLoader, Environment environment, MetricsManager metricsManager,
FileManager fileManager) {
FileManager fileManager, UserScope userScope, AuthorizationService authorizationService) {
this.apiContext = apiContext;
this.databaseRepository = apiContext.getOperationsContext().getDatabaseRepository();
this.datasetRepository = apiContext.getOperationsContext().getElasticRepository().getDatasetRepository();
@ -124,9 +130,11 @@ public class DatasetManager {
this.environment = environment;
this.metricsManager = metricsManager;
this.fileManager = fileManager;
this.userScope = userScope;
this.authorizationService = authorizationService;
}
public DataTableData<DatasetListingModel> getPaged(DatasetTableRequest datasetTableRequest, Principal principal) throws Exception {
public DataTableData<DatasetListingModel> getPaged(DatasetTableRequest datasetTableRequest) throws Exception {
DatasetCriteria datasetCriteria = new DatasetCriteria();
datasetCriteria.setLike(datasetTableRequest.getCriteria().getLike());
datasetCriteria.setDatasetTemplates(datasetTableRequest.getCriteria().getDatasetTemplates());
@ -148,7 +156,7 @@ public class DatasetManager {
if (datasetCriteria.getCollaborators() == null) {
datasetCriteria.setSortCriteria(new ArrayList<>());
}
datasetCriteria.getCollaborators().add(principal.getId());
datasetCriteria.getCollaborators().add(this.userScope.getUserId());
}
if (datasetTableRequest.getCriteria().getGrantStatus() != null) {
datasetCriteria.setGrantStatus(datasetTableRequest.getCriteria().getGrantStatus());
@ -167,7 +175,7 @@ public class DatasetManager {
datasets = null;
}
UserInfo userInfo = builderFactory.getBuilder(UserInfoBuilder.class).id(principal.getId()).build();
UserInfo userInfo = builderFactory.getBuilder(UserInfoBuilder.class).id(this.userScope.getUserIdSafe()).build();
// QueryableList<eu.eudat.data.old.Dataset> items = databaseRepository.getDatasetDao().getWithCriteria(datasetTableRequest.getCriteria()).withHint(HintedModelFactory.getHint(DatasetListingModel.class));
QueryableList<Dataset> items;
if (datasets != null) {
@ -188,7 +196,7 @@ public class DatasetManager {
QueryableList<Dataset> pagedItems;
QueryableList<Dataset> authItems;
if (!datasetTableRequest.getCriteria().getIsPublic()) {
if (principal.getId() == null) {
if (this.userScope.getUserIdSafe() == null) {
throw new UnauthorisedException("You are not allowed to access those datasets");
}
if (datasetTableRequest.getCriteria().getRole() != null) {
@ -197,10 +205,10 @@ public class DatasetManager {
authItems = databaseRepository.getDatasetDao().getAuthenticated(items, userInfo, roles).distinct();
pagedItems = PaginationManager.applyPaging(authItems, datasetTableRequest);
} else {
if (principal.getId() != null && datasetTableRequest.getCriteria().getRole() != null) {
if (this.userScope.getUserIdSafe() != null && datasetTableRequest.getCriteria().getRole() != null) {
items.where((builder, root) -> {
Join userJoin = root.join("dmp", JoinType.LEFT).join("users", JoinType.LEFT);
return builder.and(builder.equal(userJoin.join("user", JoinType.LEFT).get("id"), principal.getId()), builder.equal(userJoin.get("role"), datasetTableRequest.getCriteria().getRole()));
return builder.and(builder.equal(userJoin.join("user", JoinType.LEFT).get("id"), this.userScope.getUserId()), builder.equal(userJoin.get("role"), datasetTableRequest.getCriteria().getRole()));
});
}
String[] strings = new String[1];
@ -220,7 +228,7 @@ public class DatasetManager {
return dataTable;
}
public DataTableData<DatasetListingModel> getPaged(DatasetPublicTableRequest datasetTableRequest, Principal principal) throws Exception {
public DataTableData<DatasetListingModel> getPaged(DatasetPublicTableRequest datasetTableRequest) throws Exception {
Long count = 0L;
DatasetCriteria datasetCriteria = new DatasetCriteria();
datasetCriteria.setLike(datasetTableRequest.getCriteria().getLike());
@ -256,10 +264,10 @@ public class DatasetManager {
items = datasetTableRequest.applyCriteria();
}
if (principal.getId() != null && datasetTableRequest.getCriteria().getRole() != null) {
if (this.userScope.isSet() && datasetTableRequest.getCriteria().getRole() != null) {
items.where((builder, root) -> {
Join userJoin = root.join("dmp", JoinType.LEFT).join("users", JoinType.LEFT);
return builder.and(builder.equal(userJoin.join("user", JoinType.LEFT).get("id"), principal.getId()), builder.equal(userJoin.get("role"), datasetTableRequest.getCriteria().getRole()));
return builder.and(builder.equal(userJoin.join("user", JoinType.LEFT).get("id"), this.userScope.getUserId()), builder.equal(userJoin.get("role"), datasetTableRequest.getCriteria().getRole()));
});
}
List<String> strings = new ArrayList<>();
@ -281,11 +289,11 @@ public class DatasetManager {
return dataTable;
}
public DatasetWizardModel getSingle(String id, Principal principal) {
public DatasetWizardModel getSingle(String id) throws InvalidApplicationException {
DatasetWizardModel dataset = new DatasetWizardModel();
Dataset datasetEntity = databaseRepository.getDatasetDao().find(UUID.fromString(id), HintedModelFactory.getHint(DatasetWizardModel.class));
if (datasetEntity.getDmp().getUsers()
.stream().filter(userInfo -> userInfo.getUser().getId() == principal.getId())
.stream().filter(userInfo -> userInfo.getUser().getId() == this.userScope.getUserIdSafe())
.collect(Collectors.toList()).size() == 0 && !datasetEntity.getDmp().isPublic())
throw new UnauthorisedException();
dataset.setDatasetProfileDefinition(getPagedProfile(dataset, datasetEntity));
@ -358,16 +366,16 @@ public class DatasetManager {
}
}
public DatasetOverviewModel getOverviewSingle(String id, Principal principal, boolean isPublic) throws Exception {
public DatasetOverviewModel getOverviewSingle(String id, boolean isPublic) throws Exception {
Dataset datasetEntity = databaseRepository.getDatasetDao().find(UUID.fromString(id));
if (datasetEntity.getStatus() == Dataset.Status.DELETED.getValue()) {
throw new Exception("Dataset is deleted.");
}
if (!isPublic && principal == null) {
if (!isPublic && !this.userScope.isSet()) {
throw new UnauthorisedException();
} else
if (!isPublic && datasetEntity.getDmp().getUsers()
.stream().noneMatch(userInfo -> userInfo.getUser().getId() == principal.getId())) {
.stream().noneMatch(userInfo -> userInfo.getUser().getId() == this.userScope.getUserIdSafe())) {
throw new UnauthorisedException();
} else if (isPublic && !datasetEntity.getDmp().isPublic()) {
throw new ForbiddenException("Selected Dataset is not public");
@ -378,7 +386,7 @@ public class DatasetManager {
return dataset;
}
public Dataset getEntitySingle(UUID id) {
public Dataset getEntitySingle(UUID id) throws InvalidApplicationException {
return databaseRepository.getDatasetDao().find(id);
}
@ -395,14 +403,14 @@ public class DatasetManager {
return pagedDatasetProfile;
}
private XWPFDocument getWordDocument(ConfigLoader configLoader, Dataset datasetEntity, VisibilityRuleService visibilityRuleService, Principal principal) throws IOException {
private XWPFDocument getWordDocument(ConfigLoader configLoader, Dataset datasetEntity, VisibilityRuleService visibilityRuleService) throws IOException {
WordBuilder wordBuilder = new WordBuilder(this.environment, configLoader);
DatasetWizardModel dataset = new DatasetWizardModel();
XWPFDocument document = configLoader.getDatasetDocument();
DMP dmpEntity = datasetEntity.getDmp();
if (!dmpEntity.isPublic() && dmpEntity.getUsers().stream().filter(userInfo -> userInfo.getUser().getId() == principal.getId()).collect(Collectors.toList()).size() == 0)
if (!dmpEntity.isPublic() && dmpEntity.getUsers().stream().filter(userInfo -> userInfo.getUser().getId() == this.userScope.getUserIdSafe()).collect(Collectors.toList()).size() == 0)
throw new UnauthorisedException();
wordBuilder.fillFirstPage(dmpEntity, datasetEntity, document, true);
@ -537,10 +545,10 @@ public class DatasetManager {
// return exportFile;
}
public FileEnvelope getWordDocumentFile(ConfigLoader configLoader, String id, VisibilityRuleService visibilityRuleService, Principal principal) throws IOException {
public FileEnvelope getWordDocumentFile(ConfigLoader configLoader, String id, VisibilityRuleService visibilityRuleService) throws IOException, InvalidApplicationException {
Dataset datasetEntity = databaseRepository.getDatasetDao().find(UUID.fromString(id), HintedModelFactory.getHint(DatasetWizardModel.class));
if (!datasetEntity.getDmp().isPublic() && datasetEntity.getDmp().getUsers()
.stream().filter(userInfo -> userInfo.getUser().getId() == principal.getId())
.stream().filter(userInfo -> userInfo.getUser().getId() == this.userScope.getUserIdSafe())
.collect(Collectors.toList()).size() == 0)
throw new UnauthorisedException();
String label = datasetEntity.getLabel().replaceAll("[^a-zA-Z0-9+ ]", "");
@ -548,7 +556,7 @@ public class DatasetManager {
exportEnvelope.setFilename(label + ".docx");
String uuid = UUID.randomUUID().toString();
File exportFile = new File(this.environment.getProperty("temp.temp") + uuid + ".docx");
XWPFDocument document = getWordDocument(configLoader, datasetEntity, visibilityRuleService, principal);
XWPFDocument document = getWordDocument(configLoader, datasetEntity, visibilityRuleService);
FileOutputStream out = new FileOutputStream(exportFile);
document.write(out);
out.close();
@ -564,12 +572,12 @@ public class DatasetManager {
return extractor.getText();/*.replaceAll("\n\\s*", " ");*/
}
public FileEnvelope getXmlDocument(String id, VisibilityRuleService visibilityRuleService, Principal principal) throws InstantiationException, IllegalAccessException, IOException {
public FileEnvelope getXmlDocument(String id, VisibilityRuleService visibilityRuleService) throws InstantiationException, IllegalAccessException, IOException, InvalidApplicationException {
ExportXmlBuilder xmlBuilder = new ExportXmlBuilder();
DatasetWizardModel dataset = new DatasetWizardModel();
Dataset datasetEntity = databaseRepository.getDatasetDao().find(UUID.fromString(id), HintedModelFactory.getHint(DatasetWizardModel.class));
if (!datasetEntity.getDmp().isPublic() && datasetEntity.getDmp().getUsers()
.stream().filter(userInfo -> userInfo.getUser().getId() == principal.getId())
.stream().filter(userInfo -> userInfo.getUser().getId() == this.userScope.getUserIdSafe())
.collect(Collectors.toList()).size() == 0)
throw new UnauthorisedException();
Map<String, Object> properties = new HashMap<>();
@ -588,7 +596,7 @@ public class DatasetManager {
return fileEnvelope;
}
public Dataset createOrUpdate(DatasetWizardModel datasetWizardModel, Principal principal) throws Exception {
public Dataset createOrUpdate(DatasetWizardModel datasetWizardModel) throws Exception {
Boolean sendNotification = false;
Dataset tempDataset = null;
DMP dmp = apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().find(datasetWizardModel.getDmp().getId());
@ -620,7 +628,7 @@ public class DatasetManager {
throw new Exception("Field value of " + failedField + " must be filled.");
}
}
UserInfo userInfo = apiContext.getOperationsContext().getBuilderFactory().getBuilder(UserInfoBuilder.class).id(principal.getId()).build();
UserInfo userInfo = apiContext.getOperationsContext().getBuilderFactory().getBuilder(UserInfoBuilder.class).id(this.userScope.getUserId()).build();
dataset.setCreator(userInfo);
createDataRepositoriesIfTheyDontExist(apiContext.getOperationsContext().getDatabaseRepository().getDataRepositoryDao(), dataset);
@ -651,7 +659,7 @@ public class DatasetManager {
return dataset1;
}
private void deleteOldFilesAndAddNew(DatasetWizardModel datasetWizardModel, UserInfo userInfo) throws JsonProcessingException {
private void deleteOldFilesAndAddNew(DatasetWizardModel datasetWizardModel, UserInfo userInfo) throws JsonProcessingException, InvalidApplicationException {
// Files in DB for this entityId which are NOT DELETED
List<FileUpload> fileUploads = fileManager.getCurrentFileUploadsForEntityId(datasetWizardModel.getId());
List<String> fileUploadIds = fileUploads.stream().map(fileUpload -> fileUpload.getId().toString()).collect(Collectors.toList());
@ -689,7 +697,7 @@ public class DatasetManager {
});
}
private void sendNotification(Dataset dataset, DMP dmp, UserInfo user, NotificationType notificationType) {
private void sendNotification(Dataset dataset, DMP dmp, UserInfo user, NotificationType notificationType) throws InvalidApplicationException {
List<UserDMP> userDMPS = databaseRepository.getUserDmpDao().asQueryable().where(((builder, root) -> builder.equal(root.get("dmp").get("id"), dmp.getId()))).toList();
for (UserDMP userDMP : userDMPS) {
if (!userDMP.getUser().getId().equals(user.getId())) {
@ -853,7 +861,7 @@ public class DatasetManager {
private void createRegistriesIfTheyDontExist(RegistryDao registryDao, Dataset dataset) {
private void createRegistriesIfTheyDontExist(RegistryDao registryDao, Dataset dataset) throws InvalidApplicationException {
if (dataset.getRegistries() != null && !dataset.getRegistries().isEmpty()) {
for (Registry registry : dataset.getRegistries()) {
RegistryCriteria criteria = new RegistryCriteria();
@ -868,7 +876,7 @@ public class DatasetManager {
}
}
private void createDataRepositoriesIfTheyDontExist(DataRepositoryDao dataRepositoryDao, Dataset dataset) {
private void createDataRepositoriesIfTheyDontExist(DataRepositoryDao dataRepositoryDao, Dataset dataset) throws InvalidApplicationException {
if (dataset.getDatasetDataRepositories() != null && !dataset.getDatasetDataRepositories().isEmpty()) {
for (DatasetDataRepository datasetDataRepository : dataset.getDatasetDataRepositories()) {
DataRepositoryCriteria criteria = new DataRepositoryCriteria();
@ -889,7 +897,7 @@ public class DatasetManager {
}
}
private void createServicesIfTheyDontExist(Dataset dataset) {
private void createServicesIfTheyDontExist(Dataset dataset) throws InvalidApplicationException {
if (dataset.getServices() != null && !dataset.getServices().isEmpty()) {
for (DatasetService service : dataset.getServices()) {
ServiceCriteria criteria = new ServiceCriteria();
@ -906,7 +914,7 @@ public class DatasetManager {
}
}
private void createExternalDatasetsIfTheyDontExist(Dataset dataset) {
private void createExternalDatasetsIfTheyDontExist(Dataset dataset) throws InvalidApplicationException {
if (dataset.getDatasetExternalDatasets() != null && !dataset.getDatasetExternalDatasets().isEmpty()) {
for (DatasetExternalDataset datasetExternalDataset : dataset.getDatasetExternalDatasets()) {
ExternalDatasetCriteria criteria = new ExternalDatasetCriteria();
@ -935,8 +943,8 @@ public class DatasetManager {
metricsManager.increaseValue(MetricNames.DATASET, 1, MetricNames.PUBLISHED);
}
public ResponseEntity<byte[]> getDocument(String id, VisibilityRuleService visibilityRuleService, String contentType, Principal principal) throws IllegalAccessException, IOException, InstantiationException {
FileEnvelope envelope = getXmlDocument(id, visibilityRuleService, principal);
public ResponseEntity<byte[]> getDocument(String id, VisibilityRuleService visibilityRuleService, String contentType) throws IllegalAccessException, IOException, InstantiationException, InvalidApplicationException {
FileEnvelope envelope = getXmlDocument(id, visibilityRuleService);
InputStream resource = new FileInputStream(envelope.getFile());
logger.info("Mime Type of " + envelope.getFilename() + " is " +
new MimetypesFileTypeMap().getContentType(envelope.getFile()));
@ -957,7 +965,7 @@ public class DatasetManager {
HttpStatus.OK);
}
public Dataset createDatasetFromXml(MultipartFile importFile, String dmpId, String datasetProfileId, Principal principal) throws JAXBException, IOException {
public Dataset createDatasetFromXml(MultipartFile importFile, String dmpId, String datasetProfileId) throws JAXBException, IOException, InvalidApplicationException {
DatasetImportPagedDatasetProfile importModel = new DatasetImportPagedDatasetProfile();
JAXBContext jaxbContext;
@ -1013,7 +1021,7 @@ public class DatasetManager {
profile.setId(UUID.fromString(datasetProfileId));
entity.setProfile(profile);
UserInfo userInfo = apiContext.getOperationsContext().getBuilderFactory().getBuilder(UserInfoBuilder.class).id(principal.getId()).build();
UserInfo userInfo = apiContext.getOperationsContext().getBuilderFactory().getBuilder(UserInfoBuilder.class).id(this.userScope.getUserId()).build();
entity.setCreator(userInfo);
updateTagsXmlImportDataset(apiContext.getOperationsContext().getElasticRepository().getDatasetRepository(), entity);
@ -1030,7 +1038,7 @@ public class DatasetManager {
// TODO: When tags functionality return.
}
public DatasetWizardModel datasetUpdateProfile(String id) {
public DatasetWizardModel datasetUpdateProfile(String id) throws InvalidApplicationException {
DatasetWizardModel dataset = new DatasetWizardModel();
Dataset datasetEntity = databaseRepository.getDatasetDao().find(UUID.fromString(id), HintedModelFactory.getHint(DatasetWizardModel.class));
dataset.setDatasetProfileDefinition(getPagedProfile(dataset, datasetEntity));
@ -1083,9 +1091,9 @@ public class DatasetManager {
return pagedDatasetProfile;
}
public DataTableData<DatasetProfileListingModel> getDatasetProfilesUsedByDatasets(DatasetProfileTableRequestItem datasetProfileTableRequestItem, Principal principal) {
public DataTableData<DatasetProfileListingModel> getDatasetProfilesUsedByDatasets(DatasetProfileTableRequestItem datasetProfileTableRequestItem) throws InvalidApplicationException {
datasetProfileTableRequestItem.getCriteria().setFilter(DatasetProfileCriteria.DatasetProfileFilter.Datasets.getValue());
datasetProfileTableRequestItem.getCriteria().setUserId(principal.getId());
datasetProfileTableRequestItem.getCriteria().setUserId(this.userScope.getUserId());
QueryableList<DescriptionTemplate> items = apiContext.getOperationsContext().getDatabaseRepository().getDatasetProfileDao().getWithCriteria(datasetProfileTableRequestItem.getCriteria());
List<DatasetProfileListingModel> listingModels = items.select(item -> new DatasetProfileListingModel().fromDataModel(item));
@ -1097,8 +1105,8 @@ public class DatasetManager {
return data;
}
public void generateIndex(Principal principal) {
if (principal.getAuthorities().contains(Authorities.ADMIN.getValue())) {
public void generateIndex() throws InvalidApplicationException {
if (this.authorizationService.authorize(Permission.AdminRole)) {
this.apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().asQueryable().toList();
List<Dataset> datasetEntities = new ArrayList<>(this.apiContext.getOperationsContext().getDatabaseRepository().getDatasetDao().asQueryable().toList());
datasetEntities.forEach(datasetEntity -> {
@ -1114,8 +1122,8 @@ public class DatasetManager {
}
}
public void clearIndex(Principal principal) {
if (principal.getAuthorities().contains(Authorities.ADMIN.getValue())) {
public void clearIndex() {
if (this.authorizationService.authorize(Permission.AdminRole)) {
try {
this.apiContext.getOperationsContext().getElasticRepository().getDatasetRepository().clear();
} catch (IOException e) {
@ -1124,7 +1132,7 @@ public class DatasetManager {
}
}
public void getTagsFromProfile(DatasetWizardModel wizardModel, Dataset dataset) throws IOException {
public void getTagsFromProfile(DatasetWizardModel wizardModel, Dataset dataset) throws IOException, InvalidApplicationException {
dataset.setProfile(apiContext.getOperationsContext().getDatabaseRepository().getDatasetProfileDao().find(dataset.getProfile().getId()));
wizardModel.setDatasetProfileDefinition(this.getPagedProfile(wizardModel, dataset));
ObjectMapper mapper = new ObjectMapper();

View File

@ -1,5 +1,7 @@
package eu.eudat.logic.managers;
import eu.eudat.authorization.Permission;
import eu.eudat.commons.scope.user.UserScope;
import eu.eudat.data.dao.criteria.DatasetProfileCriteria;
import eu.eudat.data.old.DescriptionTemplate;
import eu.eudat.data.old.UserDatasetProfile;
@ -26,11 +28,11 @@ import eu.eudat.models.data.externaldataset.ExternalAutocompleteFieldModel;
import eu.eudat.models.data.helpers.common.DataTableData;
import eu.eudat.models.data.listingmodels.UserInfoListingModel;
import eu.eudat.models.data.mail.SimpleMail;
import eu.eudat.models.data.security.Principal;
import eu.eudat.queryable.QueryableList;
import eu.eudat.service.DescriptionTemplateTypeService;
import eu.eudat.types.Authorities;
import eu.eudat.types.MetricNames;
import gr.cite.commons.web.authz.service.AuthorizationService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
@ -46,6 +48,7 @@ import org.w3c.dom.NodeList;
import jakarta.activation.MimetypesFileTypeMap;
import jakarta.transaction.Transactional;
import javax.management.InvalidApplicationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
@ -73,9 +76,11 @@ public class DatasetProfileManager {
private final MetricsManager metricsManager;
private final RemoteFetcher remoteFetcher;
private final DescriptionTemplateTypeService descriptionTemplateTypeService;
private final AuthorizationService authorizationService;
private final UserScope userScope;
@Autowired
public DatasetProfileManager(ApiContext apiContext, Environment environment, ConfigLoader configLoader, MetricsManager metricsManager, RemoteFetcher remoteFetcher, DescriptionTemplateTypeService descriptionTemplateTypeService) {
public DatasetProfileManager(ApiContext apiContext, Environment environment, ConfigLoader configLoader, MetricsManager metricsManager, RemoteFetcher remoteFetcher, DescriptionTemplateTypeService descriptionTemplateTypeService, AuthorizationService authorizationService, UserScope userScope) {
this.apiContext = apiContext;
this.databaseRepository = apiContext.getOperationsContext().getDatabaseRepository();
this.environment = environment;
@ -83,10 +88,12 @@ public class DatasetProfileManager {
this.metricsManager = metricsManager;
this.descriptionTemplateTypeService = descriptionTemplateTypeService;
this.remoteFetcher = remoteFetcher;
this.authorizationService = authorizationService;
this.userScope = userScope;
}
@Transactional
public eu.eudat.models.data.admin.composite.DatasetProfile getDatasetProfile(String id) {
public eu.eudat.models.data.admin.composite.DatasetProfile getDatasetProfile(String id) throws InvalidApplicationException {
DescriptionTemplate profile = apiContext.getOperationsContext().getDatabaseRepository().getDatasetProfileDao().find(UUID.fromString(id));
eu.eudat.models.data.admin.composite.DatasetProfile datasetprofile = AdminManager.generateDatasetProfileModel(profile);
datasetprofile.setLabel(profile.getLabel());
@ -99,35 +106,35 @@ public class DatasetProfileManager {
return datasetprofile;
}
public List<DatasetProfileAutocompleteItem> getWithCriteria(DatasetProfileAutocompleteRequest datasetProfileAutocompleteRequest) throws IllegalAccessException, InstantiationException {
public List<DatasetProfileAutocompleteItem> getWithCriteria(DatasetProfileAutocompleteRequest datasetProfileAutocompleteRequest) throws IllegalAccessException, InstantiationException, InvalidApplicationException {
QueryableList<DescriptionTemplate> items = databaseRepository.getDatasetProfileDao().getWithCriteria(datasetProfileAutocompleteRequest.getCriteria());
QueryableList<DescriptionTemplate> pagedItems = datasetProfileAutocompleteRequest.applyPaging(items);
List<DatasetProfileAutocompleteItem> datasetProfiles = pagedItems.select(item -> new DatasetProfileAutocompleteItem().fromDataModel(item));
return datasetProfiles;
}
public DescriptionTemplate clone(String id) {
public DescriptionTemplate clone(String id) throws InvalidApplicationException {
DescriptionTemplate profile = apiContext.getOperationsContext().getDatabaseRepository().getDatasetProfileDao().find(UUID.fromString(id));
apiContext.getOperationsContext().getDatabaseRepository().detachEntity(profile);
profile.setId(null);
return profile;
}
public DataTableData<DatasetProfileListingModel> getPaged(DatasetProfileTableRequestItem datasetProfileTableRequestItem, Principal principal) throws Exception {
public DataTableData<DatasetProfileListingModel> getPaged(DatasetProfileTableRequestItem datasetProfileTableRequestItem) throws Exception {
QueryableList<DescriptionTemplate> items = apiContext.getOperationsContext().getDatabaseRepository().getDatasetProfileDao().getWithCriteria(datasetProfileTableRequestItem.getCriteria());
QueryableList<DescriptionTemplate> authItems = null;
if (principal.getAuthz().contains(Authorities.ADMIN)) {
if (this.authorizationService.authorize(Permission.AdminRole)) {
authItems = items;
} else if (principal.getAuthz().contains(Authorities.DATASET_PROFILE_MANAGER)) {
} else if (this.authorizationService.authorize(Permission.DatasetProfileManagerRole)) {
List<Integer> roles = Arrays.asList(0, 1);
authItems = apiContext.getOperationsContext().getDatabaseRepository().getDatasetProfileDao().getAuthenticated(items, principal.getId(), roles);
authItems = apiContext.getOperationsContext().getDatabaseRepository().getDatasetProfileDao().getAuthenticated(items, this.userScope.getUserId(), roles);
}
QueryableList<DescriptionTemplate> pagedItems = PaginationManager.applyPaging(authItems, datasetProfileTableRequestItem);
List<DatasetProfileListingModel> datasetProfiles = pagedItems.select(item -> new DatasetProfileListingModel().fromDataModel(item));
return apiContext.getOperationsContext().getBuilderFactory().getBuilder(DataTableDataBuilder.class).data(datasetProfiles).totalCount(items.count()).build();
}
public List<DatasetProfileListingModel> getAll(DatasetProfileTableRequestItem tableRequestItem) throws IllegalAccessException, InstantiationException {
public List<DatasetProfileListingModel> getAll(DatasetProfileTableRequestItem tableRequestItem) throws IllegalAccessException, InstantiationException, InvalidApplicationException {
QueryableList<DescriptionTemplate> items = databaseRepository.getDatasetProfileDao().getWithCriteria(tableRequestItem.getCriteria());
List<DatasetProfileListingModel> datasetProfiles = items.select(item -> new DatasetProfileListingModel().fromDataModel(item));
@ -385,8 +392,13 @@ public class DatasetProfileManager {
.forEach(userInfoListingModel -> {
UserDatasetProfile userDatasetProfile1 = new UserDatasetProfile();
userDatasetProfile1.setDatasetProfile(entity);
UserInfo userInfo1 = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(userInfoListingModel.getId());
userDatasetProfile1.setUser(userInfo1);
UserInfo userInfo1 = null;
try {
userInfo1 = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(userInfoListingModel.getId());
} catch (InvalidApplicationException e) {
throw new RuntimeException(e);
}
userDatasetProfile1.setUser(userInfo1);
userDatasetProfile1.setRole(1);
apiContext.getOperationsContext().getDatabaseRepository().getUserDatasetProfileDao().createOrUpdate(userDatasetProfile1);
sendJoinMail(userDatasetProfile1);
@ -450,7 +462,7 @@ public class DatasetProfileManager {
return filteredSemantics;
}
public void addSemanticsInDatasetProfiles() throws XPathExpressionException {
public void addSemanticsInDatasetProfiles() throws XPathExpressionException, InvalidApplicationException {
List<DescriptionTemplate> ids = this.databaseRepository.getDatasetProfileDao().getAllIds();
for(DescriptionTemplate dp: ids){
DescriptionTemplate descriptionTemplate = this.databaseRepository.getDatasetProfileDao().find(dp.getId());
@ -476,7 +488,7 @@ public class DatasetProfileManager {
}
}
public void addRdaInSemanticsInDatasetProfiles() throws XPathExpressionException {
public void addRdaInSemanticsInDatasetProfiles() throws XPathExpressionException, InvalidApplicationException {
List<DescriptionTemplate> ids = this.databaseRepository.getDatasetProfileDao().getAllIds();
for(DescriptionTemplate dp: ids){
DescriptionTemplate descriptionTemplate = this.databaseRepository.getDatasetProfileDao().find(dp.getId());

View File

@ -1,5 +1,6 @@
package eu.eudat.logic.managers;
import eu.eudat.commons.scope.user.UserScope;
import eu.eudat.data.dao.criteria.DatasetProfileCriteria;
import eu.eudat.data.dao.entities.DMPDao;
import eu.eudat.data.dao.entities.DatasetProfileDao;
@ -14,9 +15,9 @@ import eu.eudat.logic.services.ApiContext;
import eu.eudat.models.data.datasetwizard.DataManagentPlanListingModel;
import eu.eudat.models.data.dmp.AssociatedProfile;
import eu.eudat.models.data.dmp.DataManagementPlan;
import eu.eudat.models.data.security.Principal;
import eu.eudat.queryable.QueryableList;
import javax.management.InvalidApplicationException;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
@ -26,15 +27,15 @@ import java.util.stream.Collectors;
public class DatasetWizardManager {
public static List<DataManagentPlanListingModel> getUserDmps(DMPDao dmpRepository, DatasetWizardAutocompleteRequest datasetWizardAutocompleteRequest, Principal principal) throws InstantiationException, IllegalAccessException {
public static List<DataManagentPlanListingModel> getUserDmps(DMPDao dmpRepository, DatasetWizardAutocompleteRequest datasetWizardAutocompleteRequest, UserScope userScope) throws InstantiationException, IllegalAccessException, InvalidApplicationException {
UserInfo userInfo = new UserInfo();
userInfo.setId(principal.getId());
userInfo.setId(userScope.getUserId());
QueryableList<DMP> items = dmpRepository.getUserDmps(datasetWizardAutocompleteRequest.getCriteria(), userInfo);
List<DataManagentPlanListingModel> dataManagementPlans = items.select(item -> new DataManagentPlanListingModel().fromDataModel(item));
return dataManagementPlans;
}
public static List<AssociatedProfile> getAvailableProfiles(DMPDao dmpRepository, DatasetProfileDao profileDao, DatasetProfileWizardAutocompleteRequest datasetProfileWizardAutocompleteRequest) throws InstantiationException, IllegalAccessException {
public static List<AssociatedProfile> getAvailableProfiles(DMPDao dmpRepository, DatasetProfileDao profileDao, DatasetProfileWizardAutocompleteRequest datasetProfileWizardAutocompleteRequest) throws InstantiationException, IllegalAccessException, InvalidApplicationException {
DataManagementPlan dataManagementPlan = new DataManagementPlan().fromDataModel(dmpRepository.find(datasetProfileWizardAutocompleteRequest.getCriteria().getId()));
if (dataManagementPlan.getProfiles() == null || dataManagementPlan.getProfiles().isEmpty()) {
return new LinkedList<>();
@ -49,7 +50,7 @@ public class DatasetWizardManager {
return profiles;
}
public void unlock(ApiContext apiContext, UUID uuid) throws DatasetWizardCannotUnlockException {
public void unlock(ApiContext apiContext, UUID uuid) throws DatasetWizardCannotUnlockException, InvalidApplicationException {
Dataset dataset = apiContext.getOperationsContext().getDatabaseRepository().getDatasetDao().find(uuid);
if(dataset.getDmp().getStatus() == DMP.DMPStatus.FINALISED.getValue()) throw new DatasetWizardCannotUnlockException("To perform this action you will need to revert DMP's finalisation");
dataset.setStatus(Dataset.Status.SAVED.getValue());
@ -57,7 +58,7 @@ public class DatasetWizardManager {
return;
}
public void delete(ApiContext apiContext, UUID uuid) throws IOException {
public void delete(ApiContext apiContext, UUID uuid) throws IOException, InvalidApplicationException {
Dataset oldDataset = apiContext.getOperationsContext().getDatabaseRepository().getDatasetDao().find(uuid);
eu.eudat.elastic.entities.Dataset oldDatasetElasitc = apiContext.getOperationsContext().getElasticRepository().getDatasetRepository().findDocument(uuid.toString());
oldDataset.setStatus(Dataset.Status.DELETED.getValue());

View File

@ -5,7 +5,6 @@ import eu.eudat.depositinterface.repository.RepositoryDepositConfiguration;
import eu.eudat.models.data.doi.DepositRequest;
import eu.eudat.models.data.doi.Doi;
import eu.eudat.models.data.doi.RepositoryConfig;
import eu.eudat.models.data.security.Principal;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
@ -51,8 +50,8 @@ public class DepositManager {
return null;
}
public Doi deposit(DepositRequest depositRequest, Principal principal) throws Exception {
return this.dataManagementPlanManager.createDoi(depositRequest, principal);
public Doi deposit(DepositRequest depositRequest) throws Exception {
return this.dataManagementPlanManager.createDoi(depositRequest);
}
public String getRepositoryLogo(String repositoryId){

View File

@ -1,5 +1,6 @@
package eu.eudat.logic.managers;
import eu.eudat.commons.scope.user.UserScope;
import eu.eudat.data.CredentialEntity;
import eu.eudat.data.old.EmailConfirmation;
import eu.eudat.data.old.UserInfo;
@ -7,10 +8,10 @@ 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.models.data.security.Principal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.management.InvalidApplicationException;
import java.util.Date;
import java.util.UUID;
@ -18,14 +19,16 @@ import java.util.UUID;
public class EmailConfirmationManager {
private ApiContext apiContext;
private DatabaseRepository databaseRepository;
private final UserScope userScope;
@Autowired
public EmailConfirmationManager(ApiContext apiContext) {
public EmailConfirmationManager(ApiContext apiContext, UserScope userScope) {
this.apiContext = apiContext;
this.databaseRepository = apiContext.getOperationsContext().getDatabaseRepository();
this.userScope = userScope;
}
public void confirmEmail(String token) throws TokenExpiredException, HasConfirmedEmailException {
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();
@ -65,8 +68,8 @@ 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());
public void sendConfirmationEmail(String email) throws HasConfirmedEmailException, InvalidApplicationException {
UserInfo user = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(this.userScope.getUserId());
if (user.getEmail() != null)
throw new HasConfirmedEmailException("User already has confirmed his Email.");
@ -74,11 +77,11 @@ public class EmailConfirmationManager {
databaseRepository.getLoginConfirmationEmailDao(),
apiContext.getUtilitiesService().getMailService(),
email,
principal.getId()
this.userScope.getUserId()
);
}
private void mergeNewUserToOld(UserInfo newUser, UserInfo oldUser) {
private void mergeNewUserToOld(UserInfo newUser, UserInfo oldUser) throws InvalidApplicationException {
CredentialEntity 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

@ -2,6 +2,7 @@ package eu.eudat.logic.managers;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import eu.eudat.commons.scope.user.UserScope;
import eu.eudat.data.old.ExternalDataset;
import eu.eudat.logic.builders.model.criteria.ExternalDatasetCriteriaBuilder;
import eu.eudat.logic.builders.model.models.DataTableDataBuilder;
@ -14,12 +15,12 @@ import eu.eudat.models.data.helpers.common.DataTableData;
import eu.eudat.logic.proxy.config.exceptions.HugeResultSet;
import eu.eudat.logic.proxy.config.exceptions.NoURLFound;
import eu.eudat.logic.proxy.fetching.RemoteFetcher;
import eu.eudat.models.data.security.Principal;
import eu.eudat.queryable.QueryableList;
import eu.eudat.logic.services.ApiContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.management.InvalidApplicationException;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
@ -32,11 +33,13 @@ public class ExternalDatasetManager {
private ApiContext apiContext;
private DatabaseRepository databaseRepository;
private RemoteFetcher remoteFetcher;
private final UserScope userScope;
@Autowired
public ExternalDatasetManager(ApiContext apiContext) {
public ExternalDatasetManager(ApiContext apiContext, UserScope userScope) {
this.apiContext = apiContext;
this.databaseRepository = apiContext.getOperationsContext().getDatabaseRepository();
this.remoteFetcher = apiContext.getOperationsContext().getRemoteFetcher();
this.userScope = userScope;
}
public DataTableData<ExternalDatasetListingModel> getPaged(ExternalDatasetTableRequest externalDatasetTableRequest) throws Exception {
@ -46,10 +49,10 @@ public class ExternalDatasetManager {
return apiContext.getOperationsContext().getBuilderFactory().getBuilder(DataTableDataBuilder.class).data(externalDatasetListingmodels).totalCount(items.count()).build();
}
public List<ExternalDatasetListingModel> getWithExternal(String query, String type, Principal principal) throws HugeResultSet, NoURLFound {
public List<ExternalDatasetListingModel> getWithExternal(String query, String type) throws HugeResultSet, NoURLFound, InvalidApplicationException {
// Fetch the local saved external Datasets that belong to the user.
ExternalDatasetCriteria criteria = apiContext.getOperationsContext().getBuilderFactory().getBuilder(ExternalDatasetCriteriaBuilder.class).like(query).build();
criteria.setCreationUserId(principal.getId());
criteria.setCreationUserId(this.userScope.getUserId());
QueryableList<ExternalDataset> items = apiContext.getOperationsContext().getDatabaseRepository().getExternalDatasetDao().getWithCriteria(criteria);
// Fetch external Datasets from external sources.
@ -69,16 +72,16 @@ public class ExternalDatasetManager {
return externalDatasets;
}
public ExternalDatasetListingModel getSingle(UUID id) throws HugeResultSet, NoURLFound, InstantiationException, IllegalAccessException {
public ExternalDatasetListingModel getSingle(UUID id) throws HugeResultSet, NoURLFound, InstantiationException, IllegalAccessException, InvalidApplicationException {
ExternalDataset externalDataset = databaseRepository.getExternalDatasetDao().find(id);
ExternalDatasetListingModel externalDatasetModel = new ExternalDatasetListingModel();
externalDatasetModel.fromDataModel(externalDataset);
return externalDatasetModel;
}
public ExternalDataset create(eu.eudat.models.data.externaldataset.ExternalDatasetModel externalDatasetModel, Principal principal) throws Exception {
public ExternalDataset create(eu.eudat.models.data.externaldataset.ExternalDatasetModel externalDatasetModel) throws Exception {
ExternalDataset externalDataset = externalDatasetModel.toDataModel();
externalDataset.getCreationUser().setId(principal.getId());
externalDataset.getCreationUser().setId(this.userScope.getUserId());
return apiContext.getOperationsContext().getDatabaseRepository().getExternalDatasetDao().createOrUpdate(externalDataset);
}
}

View File

@ -10,6 +10,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import javax.management.InvalidApplicationException;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
@ -59,19 +60,19 @@ public class FileManager {
databaseRepository.getFileUploadDao().createOrUpdate(fileUpload);
}
public List<FileUpload> getFileUploadsForEntityId(String entityId) {
public List<FileUpload> getFileUploadsForEntityId(String entityId) throws InvalidApplicationException {
return databaseRepository.getFileUploadDao().asQueryable()
.where((builder, root) -> builder.equal(root.get("entityId"), entityId)).toList();
}
public List<FileUpload> getCurrentFileUploadsForEntityId(UUID entityId) {
public List<FileUpload> getCurrentFileUploadsForEntityId(UUID entityId) throws InvalidApplicationException {
return databaseRepository.getFileUploadDao().asQueryable()
.where((builder, root) -> builder.and(
builder.equal(root.get("entityId"), entityId),
builder.equal(root.get("isDeleted"), false))).toList();
}
public void markAllFilesOfEntityIdAsDeleted(UUID entityId) {
public void markAllFilesOfEntityIdAsDeleted(UUID entityId) throws InvalidApplicationException {
List<FileUpload> fileUploads = this.getCurrentFileUploadsForEntityId(entityId);
fileUploads.forEach(fileUpload -> {
this.markOldFileAsDeleted(fileUpload);

View File

@ -1,5 +1,6 @@
package eu.eudat.logic.managers;
import eu.eudat.commons.scope.user.UserScope;
import eu.eudat.data.old.UserInfo;
import eu.eudat.data.query.items.item.funder.FunderCriteriaRequest;
import eu.eudat.logic.builders.model.models.FunderBuilder;
@ -12,10 +13,10 @@ import eu.eudat.logic.utilities.helpers.ListHelper;
import eu.eudat.models.data.external.ExternalSourcesItemModel;
import eu.eudat.models.data.external.FundersExternalSourcesModel;
import eu.eudat.models.data.funder.Funder;
import eu.eudat.models.data.security.Principal;
import eu.eudat.queryable.QueryableList;
import org.springframework.stereotype.Component;
import javax.management.InvalidApplicationException;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
@ -27,16 +28,18 @@ public class FunderManager {
private ApiContext apiContext;
private RemoteFetcher remoteFetcher;
private ListHelper listHelper;
private final UserScope userScope;
public FunderManager(ApiContext apiContext, RemoteFetcher remoteFetcher, ListHelper listHelper) {
public FunderManager(ApiContext apiContext, RemoteFetcher remoteFetcher, ListHelper listHelper, UserScope userScope) {
this.apiContext = apiContext;
this.remoteFetcher = remoteFetcher;
this.listHelper = listHelper;
this.userScope = userScope;
}
public List<Funder> getCriteriaWithExternal(FunderCriteriaRequest funderCriteria, Principal principal) throws HugeResultSet, NoURLFound {
public List<Funder> getCriteriaWithExternal(FunderCriteriaRequest funderCriteria) throws HugeResultSet, NoURLFound, InvalidApplicationException {
UserInfo userInfo = new UserInfo();
userInfo.setId(principal.getId());
userInfo.setId(this.userScope.getUserId());
funderCriteria.getCriteria().setReference("dmp:");
QueryableList<eu.eudat.data.old.Funder> items = apiContext.getOperationsContext().getDatabaseRepository().getFunderDao().getWithCritetia(funderCriteria.getCriteria());
QueryableList<eu.eudat.data.old.Funder> authItems = apiContext.getOperationsContext().getDatabaseRepository().getFunderDao().getAuthenticated(items, userInfo);

View File

@ -1,5 +1,6 @@
package eu.eudat.logic.managers;
import eu.eudat.commons.scope.user.UserScope;
import eu.eudat.data.old.UserInfo;
import eu.eudat.data.query.items.table.grant.GrantTableRequest;
import eu.eudat.exceptions.grant.GrantWithDMPsDeleteException;
@ -15,7 +16,6 @@ import eu.eudat.models.data.grant.Grant;
import eu.eudat.models.data.helpers.common.DataTableData;
import eu.eudat.data.query.items.item.grant.GrantCriteriaRequest;
import eu.eudat.models.data.grant.GrantListingModel;
import eu.eudat.models.data.security.Principal;
import eu.eudat.logic.proxy.config.exceptions.HugeResultSet;
import eu.eudat.logic.proxy.config.exceptions.NoURLFound;
import eu.eudat.logic.proxy.fetching.RemoteFetcher;
@ -23,6 +23,7 @@ import eu.eudat.queryable.QueryableList;
import eu.eudat.logic.services.ApiContext;
import org.springframework.stereotype.Component;
import javax.management.InvalidApplicationException;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
@ -38,18 +39,20 @@ public class GrantManager {
// private FileStorageService fileStorageService;
private RemoteFetcher remoteFetcher;
private ListHelper listHelper;
private final UserScope userScope;
public GrantManager(ApiContext apiContext, ListHelper listHelper) {
public GrantManager(ApiContext apiContext, ListHelper listHelper, UserScope userScope) {
this.apiContext = apiContext;
this.databaseRepository = apiContext.getOperationsContext().getDatabaseRepository();
// this.fileStorageService = apiContext.getOperationsContext().getFileStorageService();
this.remoteFetcher = apiContext.getOperationsContext().getRemoteFetcher();
this.listHelper = listHelper;
this.userScope = userScope;
}
public DataTableData<eu.eudat.models.data.grant.GrantListingModel> getPaged(GrantTableRequest grantTableRequest, Principal principal, String fieldsGroup) throws Exception {
public DataTableData<eu.eudat.models.data.grant.GrantListingModel> getPaged(GrantTableRequest grantTableRequest, String fieldsGroup) throws Exception {
UserInfo userInfo = new UserInfo();
userInfo.setId(principal.getId());
userInfo.setId(this.userScope.getUserId());
GrantDao grantRepository = databaseRepository.getGrantDao();
QueryableList<eu.eudat.data.old.Grant> items = grantRepository.getWithCriteria(grantTableRequest.getCriteria());
QueryableList<eu.eudat.data.old.Grant> authItems = grantRepository.getAuthenticated(items, userInfo);
@ -90,7 +93,7 @@ public class GrantManager {
return dataTable;
}
public eu.eudat.models.data.grant.Grant getSingle(String id) throws InstantiationException, IllegalAccessException {
public eu.eudat.models.data.grant.Grant getSingle(String id) throws InstantiationException, IllegalAccessException, InvalidApplicationException {
eu.eudat.models.data.grant.Grant grant = new eu.eudat.models.data.grant.Grant();
grant.fromDataModel(databaseRepository.getGrantDao().find(UUID.fromString(id)));
return grant;
@ -104,9 +107,9 @@ public class GrantManager {
return grant;
}*/
public List<eu.eudat.models.data.grant.Grant> getCriteriaWithExternal(GrantCriteriaRequest grantCriteria, Principal principal) throws HugeResultSet, NoURLFound {
public List<eu.eudat.models.data.grant.Grant> getCriteriaWithExternal(GrantCriteriaRequest grantCriteria) throws HugeResultSet, NoURLFound, InvalidApplicationException {
UserInfo userInfo = new UserInfo();
userInfo.setId(principal.getId());
userInfo.setId(this.userScope.getUserId());
/*if (grantCriteria.getCriteria().getFunderReference() != null && !grantCriteria.getCriteria().getFunderReference().trim().isEmpty()) {
FunderCriteria funderCriteria = new FunderCriteria();
funderCriteria.setReference(grantCriteria.getCriteria().getFunderReference());
@ -144,7 +147,7 @@ public class GrantManager {
return grants;
}
public List<eu.eudat.models.data.grant.Grant> getCriteria(GrantCriteriaRequest grantCriteria) throws IllegalAccessException, InstantiationException, HugeResultSet, NoURLFound {
public List<eu.eudat.models.data.grant.Grant> getCriteria(GrantCriteriaRequest grantCriteria) throws IllegalAccessException, InstantiationException, HugeResultSet, NoURLFound, InvalidApplicationException {
GrantDao grantRepository = databaseRepository.getGrantDao();
QueryableList<eu.eudat.data.old.Grant> items = grantRepository.getWithCriteria(grantCriteria.getCriteria());
if (grantCriteria.getLength() != null) items.take(grantCriteria.getLength());
@ -175,7 +178,7 @@ public class GrantManager {
databaseRepository.getGrantDao().createOrUpdate(grantEntity);
}*/
public void delete(UUID uuid) {
public void delete(UUID uuid) throws InvalidApplicationException {
eu.eudat.data.old.Grant oldGrant = apiContext.getOperationsContext().getDatabaseRepository().getGrantDao().find(uuid);
if (oldGrant.getDmps().size() > 0)
throw new GrantWithDMPsDeleteException("You cannot Remove Grants with DMPs");

View File

@ -1,5 +1,6 @@
package eu.eudat.logic.managers;
import eu.eudat.commons.scope.user.UserScope;
import eu.eudat.data.old.DMP;
import eu.eudat.data.old.UserDMP;
import eu.eudat.data.old.UserInfo;
@ -9,7 +10,6 @@ import eu.eudat.logic.services.ApiContext;
import eu.eudat.logic.utilities.helpers.StreamDistinctBy;
import eu.eudat.models.data.invitation.Invitation;
import eu.eudat.models.data.invitation.Properties;
import eu.eudat.models.data.security.Principal;
import eu.eudat.models.data.userinfo.UserInfoInvitationModel;
import eu.eudat.queryable.QueryableList;
import org.springframework.beans.factory.annotation.Autowired;
@ -18,6 +18,8 @@ import org.springframework.stereotype.Component;
import jakarta.xml.bind.JAXBContext;
import jakarta.xml.bind.JAXBException;
import jakarta.xml.bind.Unmarshaller;
import javax.management.InvalidApplicationException;
import java.io.IOException;
import java.io.StringReader;
import java.util.*;
@ -29,19 +31,26 @@ public class InvitationsManager {
private ApiContext apiContext;
private DataManagementPlanManager dataManagementPlanManager;
private final UserScope userScope;
@Autowired
public InvitationsManager(ApiContext apiContext, DataManagementPlanManager dataManagementPlanManager) {
public InvitationsManager(ApiContext apiContext, DataManagementPlanManager dataManagementPlanManager, UserScope userScope) {
this.apiContext = apiContext;
this.dataManagementPlanManager = dataManagementPlanManager;
this.userScope = userScope;
}
public void inviteUsers(Invitation invitation, Principal principal) throws Exception {
public void inviteUsers(Invitation invitation) throws Exception {
UserInfo principalUser = new UserInfo();
principalUser.setId(principal.getId());
principalUser.setId(this.userScope.getUserIdSafe());
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) {
UserInfo existingUser = null;
try {
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());
}
});
@ -65,7 +74,7 @@ public class InvitationsManager {
apiContext.getUtilitiesService().getInvitationService().assignToDmp(apiContext.getOperationsContext().getDatabaseRepository().getDmpDao(), userInfoToUserDmp, dataManagementPlan);
}
public List<UserInfoInvitationModel> getUsers(Principal principal) throws InstantiationException, IllegalAccessException {
public List<UserInfoInvitationModel> 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())) {
@ -76,20 +85,20 @@ public class InvitationsManager {
}).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()))
.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(principal.getId())).filter(StreamDistinctBy.distinctByKey(UserInfo::getId)).collect(Collectors.toList());
.filter(userInfo -> !userInfo.getId().equals(this.userScope.getUserIdSafe())).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 {
public List<UserInfoInvitationModel> getUsersWithCriteria(UserInfoRequestItem userInfoRequestItem) throws IllegalAccessException, InstantiationException, InvalidApplicationException {
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()))
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(principal.getId())).filter(StreamDistinctBy.distinctByKey(UserInfo::getId))
.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()))))
@ -100,7 +109,7 @@ public class InvitationsManager {
return userModels;
}
public UUID assignUserAcceptedInvitation(UUID invitationID, Principal principal) throws UnauthorisedException, JAXBException, IOException {
public UUID assignUserAcceptedInvitation(UUID invitationID) throws UnauthorisedException, JAXBException, IOException, InvalidApplicationException {
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");
@ -108,7 +117,7 @@ public class InvitationsManager {
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(principal.getId());
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) {

Some files were not shown because too many files have changed in this diff Show More