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; package eu.eudat.authorization;
public final class Permission { 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 //Language
public static String BrowseLanguage = "BrowseLanguage"; 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.QueryableList;
import eu.eudat.queryable.queryableentity.DataEntity; import eu.eudat.queryable.queryableentity.DataEntity;
import javax.management.InvalidApplicationException;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
public interface DatabaseAccessLayer<T extends DataEntity, I> { public interface DatabaseAccessLayer<T extends DataEntity, I> {
@ -11,9 +12,9 @@ public interface DatabaseAccessLayer<T extends DataEntity, I> {
CompletableFuture<T> createOrUpdateAsync(T item); 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); 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.scheduling.annotation.Async;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import javax.management.InvalidApplicationException;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
@ -34,7 +35,7 @@ public class ContentDaoImpl extends DatabaseAccess<Content> implements ContentDa
} }
@Override @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(); 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.scheduling.annotation.Async;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import javax.management.InvalidApplicationException;
import java.util.Arrays; import java.util.Arrays;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
@ -115,7 +116,7 @@ public class DMPDaoImpl extends DatabaseAccess<DMP> implements DMPDao {
} }
@Override @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(); 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.scheduling.annotation.Async;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import javax.management.InvalidApplicationException;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
@ -37,12 +38,12 @@ public class DMPProfileDaoImpl extends DatabaseAccess<DMPProfile> implements DMP
@Override @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(); return getDatabaseService().getQueryable(DMPProfile.class).where((builder, root) -> builder.equal((root.get("id")), id)).getSingle();
} }
@Override @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(); 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.scheduling.annotation.Async;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import javax.management.InvalidApplicationException;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
@ -33,7 +34,7 @@ public class DataRepositoryDaoImpl extends DatabaseAccess<DataRepository> implem
} }
@Override @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(); 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.data.old.UserInfo;
import eu.eudat.queryable.QueryableList; import eu.eudat.queryable.QueryableList;
import javax.management.InvalidApplicationException;
import java.util.List; import java.util.List;
import java.util.UUID; 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); 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.Join;
import jakarta.persistence.criteria.JoinType; import jakarta.persistence.criteria.JoinType;
import javax.management.InvalidApplicationException;
import java.util.Arrays; import java.util.Arrays;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
@ -102,19 +104,19 @@ public class DatasetDaoImpl extends DatabaseAccess<Dataset> implements DatasetDa
} }
@Override @Override
public Dataset find(UUID id) { public Dataset find(UUID id) throws InvalidApplicationException {
return getDatabaseService().getQueryable(Dataset.class) 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(); .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 @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) 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(); .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 @Override
public Dataset isPublicDataset(UUID id) { public Dataset isPublicDataset(UUID id) throws InvalidApplicationException {
QueryableList<Dataset> query = getDatabaseService().getQueryable(Dataset.getHints(), Dataset.class); QueryableList<Dataset> query = getDatabaseService().getQueryable(Dataset.getHints(), Dataset.class);
query.where(((builder, root) -> builder.equal(root.get("id"), id))); 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.scheduling.annotation.Async;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import javax.management.InvalidApplicationException;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
@ -34,7 +35,7 @@ public class DatasetExternalDatasetDaoImpl extends DatabaseAccess<DatasetExterna
@Override @Override
@Async @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(); 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.data.old.DescriptionTemplate;
import eu.eudat.queryable.QueryableList; import eu.eudat.queryable.QueryableList;
import javax.management.InvalidApplicationException;
import java.util.List; import java.util.List;
import java.util.UUID; 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); 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.Join;
import jakarta.persistence.criteria.JoinType; import jakarta.persistence.criteria.JoinType;
import javax.management.InvalidApplicationException;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
@ -78,7 +80,7 @@ public class DatasetProfileDaoImpl extends DatabaseAccess<DescriptionTemplate> i
} }
@Override @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(); 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 @Override
public List<DescriptionTemplate> getAllIds(){ public List<DescriptionTemplate> getAllIds() throws InvalidApplicationException {
return getDatabaseService().getQueryable(DescriptionTemplate.class).withFields(Collections.singletonList("id")).toList(); return getDatabaseService().getQueryable(DescriptionTemplate.class).withFields(Collections.singletonList("id")).toList();
} }
@ -128,7 +130,7 @@ public class DatasetProfileDaoImpl extends DatabaseAccess<DescriptionTemplate> i
} }
@Override @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(); 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.scheduling.annotation.Async;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import javax.management.InvalidApplicationException;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
@ -34,7 +35,7 @@ public class DatasetServiceDaoImpl extends DatabaseAccess<DatasetService> implem
} }
@Override @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(); 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.scheduling.annotation.Async;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import javax.management.InvalidApplicationException;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
@ -30,7 +31,7 @@ public class DmpDatasetProfileDaoImpl extends DatabaseAccess<DMPDatasetProfile>
} }
@Override @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(); 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.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import javax.management.InvalidApplicationException;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
@ -35,7 +36,7 @@ public class EmailConfirmationDaoImpl extends DatabaseAccess<EmailConfirmation>
} }
@Override @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(); 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.dao.DatabaseAccessLayer;
import eu.eudat.data.old.EntityDoi; import eu.eudat.data.old.EntityDoi;
import javax.management.InvalidApplicationException;
import java.util.UUID; import java.util.UUID;
public interface EntityDoiDao extends DatabaseAccessLayer<EntityDoi, 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.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import javax.management.InvalidApplicationException;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
@ -30,12 +31,12 @@ public class EntityDoiDaoImpl extends DatabaseAccess<EntityDoi> implements Entit
} }
@Override @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(); return this.getDatabaseService().getQueryable(EntityDoi.class).where((builder, root) -> builder.equal(root.get("id"), id)).getSingle();
} }
@Override @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(); 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.scheduling.annotation.Async;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import javax.management.InvalidApplicationException;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
@ -39,7 +40,7 @@ public class ExternalDatasetDaoImpl extends DatabaseAccess<ExternalDataset> impl
} }
@Override @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(); 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.dao.DatabaseAccessLayer;
import eu.eudat.data.old.FileUpload; import eu.eudat.data.old.FileUpload;
import javax.management.InvalidApplicationException;
import java.util.List; import java.util.List;
import java.util.UUID; import java.util.UUID;
public interface FileUploadDao extends DatabaseAccessLayer<FileUpload, 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.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import javax.management.InvalidApplicationException;
import java.util.List; import java.util.List;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
@ -30,12 +31,12 @@ public class FileUploadDaoImpl extends DatabaseAccess<FileUpload> implements Fil
} }
@Override @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(); return getDatabaseService().getQueryable(FileUpload.class).where((builder, root) -> builder.equal(root.get("id"), id)).getSingle();
} }
@Override @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(); 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.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import javax.management.InvalidApplicationException;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
@ -54,7 +55,7 @@ public class FunderDaoImpl extends DatabaseAccess<Funder> implements FunderDao {
} }
@Override @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(); 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 org.springframework.stereotype.Component;
import jakarta.persistence.criteria.JoinType; import jakarta.persistence.criteria.JoinType;
import javax.management.InvalidApplicationException;
import java.util.Date; import java.util.Date;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
@ -69,7 +71,7 @@ public class GrantDaoImpl extends DatabaseAccess<Grant> implements GrantDao {
} }
@Override @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(); 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.scheduling.annotation.Async;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import javax.management.InvalidApplicationException;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
@ -32,7 +33,7 @@ public class InvitationDaoImpl extends DatabaseAccess<Invitation> implements Inv
} }
@Override @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(); 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.scheduling.annotation.Async;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import javax.management.InvalidApplicationException;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
@ -44,7 +45,7 @@ public class LockDaoImpl extends DatabaseAccess<Lock> implements LockDao {
} }
@Override @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(); 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.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import javax.management.InvalidApplicationException;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
@ -39,7 +40,7 @@ public class NotificationDaoImpl extends DatabaseAccess<Notification> implements
} }
@Override @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(); 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 org.springframework.stereotype.Component;
import jakarta.persistence.criteria.JoinType; import jakarta.persistence.criteria.JoinType;
import javax.management.InvalidApplicationException;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
@ -52,7 +54,7 @@ public class OrganisationDaoImpl extends DatabaseAccess<Organisation> implements
} }
@Override @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(); 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 org.springframework.stereotype.Service;
import jakarta.persistence.criteria.JoinType; import jakarta.persistence.criteria.JoinType;
import javax.management.InvalidApplicationException;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
@ -52,7 +54,7 @@ public class ProjectDaoImpl extends DatabaseAccess<Project> implements ProjectDa
} }
@Override @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(); 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.scheduling.annotation.Async;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import javax.management.InvalidApplicationException;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
@ -39,7 +40,7 @@ public class RegistryDaoImpl extends DatabaseAccess<Registry> implements Registr
} }
@Override @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(); 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.scheduling.annotation.Async;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import javax.management.InvalidApplicationException;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
@ -40,7 +41,7 @@ public class ResearcherDaoImpl extends DatabaseAccess<Researcher> implements Res
} }
@Override @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(); 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.scheduling.annotation.Async;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import javax.management.InvalidApplicationException;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
@ -38,7 +39,7 @@ public class ServiceDaoImpl extends DatabaseAccess<Service> implements ServiceDa
} }
@Override @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(); 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.scheduling.annotation.Async;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import javax.management.InvalidApplicationException;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
@ -25,7 +26,7 @@ public class UserDatasetProfileDaoImpl extends DatabaseAccess<UserDatasetProfile
} }
@Override @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(); 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.scheduling.annotation.Async;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import javax.management.InvalidApplicationException;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
@ -28,7 +29,7 @@ public class UserDmpDaoImpl extends DatabaseAccess<UserDMP> implements UserDmpDa
} }
@Override @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(); 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.scheduling.annotation.Async;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import javax.management.InvalidApplicationException;
import java.util.Arrays; import java.util.Arrays;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
@ -54,7 +55,7 @@ public class UserInfoDaoImpl extends DatabaseAccess<UserInfo> implements UserInf
} }
@Override @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(); 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.data.old.UserRole;
import eu.eudat.queryable.QueryableList; import eu.eudat.queryable.QueryableList;
import javax.management.InvalidApplicationException;
import java.util.List; import java.util.List;
import java.util.UUID; import java.util.UUID;
@ -14,5 +15,5 @@ public interface UserRoleDao extends DatabaseAccessLayer<UserRole, UUID> {
QueryableList<UserRole> getWithCriteria(UserRoleCriteria criteria); 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.scheduling.annotation.Async;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import javax.management.InvalidApplicationException;
import java.util.List; import java.util.List;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
@ -29,12 +30,12 @@ public class UserRoleDaoImpl extends DatabaseAccess<UserRole> implements UserRol
} }
@Override @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(); return this.getDatabaseService().getQueryable(UserRole.class).where((builder, root) -> builder.equal(root.get("id"), id)).getSingleOrDefault();
} }
@Override @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(); 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.CredentialEntity;
import eu.eudat.data.dao.DatabaseAccessLayer; import eu.eudat.data.dao.DatabaseAccessLayer;
import javax.management.InvalidApplicationException;
import java.util.UUID; import java.util.UUID;
public interface CredentialDao extends DatabaseAccessLayer<CredentialEntity, 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.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import javax.management.InvalidApplicationException;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
@ -25,12 +26,12 @@ public class CredentialDaoImpl extends DatabaseAccess<CredentialEntity> implemen
} }
@Override @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(); return this.getDatabaseService().getQueryable(CredentialEntity.class).where((builder, root) -> builder.equal(root.get("id"), id)).getSingleOrDefault();
} }
@Override @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) -> return this.getDatabaseService().getQueryable(CredentialEntity.class).where(((builder, root) ->
builder.and( builder.and(
builder.equal(root.get("publicValue"), username), 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 eu.eudat.queryable.types.SelectionField;
import jakarta.persistence.criteria.Subquery; import jakarta.persistence.criteria.Subquery;
import javax.management.InvalidApplicationException;
import java.util.Arrays; import java.util.Arrays;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
@ -115,7 +117,7 @@ public class DMPQuery extends Query<DMP, UUID> {
this.datasetQuery = datasetQuery; this.datasetQuery = datasetQuery;
} }
public QueryableList<DMP> getQuery() { public QueryableList<DMP> getQuery() throws InvalidApplicationException {
QueryableList<DMP> query = this.databaseAccessLayer.asQueryable(); QueryableList<DMP> query = this.databaseAccessLayer.asQueryable();
if (this.id != null) { if (this.id != null) {
query.where((builder, root) -> builder.equal(root.get("id"), this.id)); 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 eu.eudat.queryable.types.SelectionField;
import jakarta.persistence.criteria.Subquery; import jakarta.persistence.criteria.Subquery;
import javax.management.InvalidApplicationException;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.UUID; import java.util.UUID;
@ -51,7 +53,7 @@ public class DatasetQuery extends Query<Dataset, UUID> {
} }
@Override @Override
public QueryableList<Dataset> getQuery() { public QueryableList<Dataset> getQuery() throws InvalidApplicationException {
QueryableList<Dataset> query = this.databaseAccessLayer.asQueryable(); QueryableList<Dataset> query = this.databaseAccessLayer.asQueryable();
if (this.id != null) { if (this.id != null) {
query.where((builder, root) -> builder.equal(root.get("id"), this.id)); 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 eu.eudat.queryable.types.SelectionField;
import jakarta.persistence.criteria.Subquery; import jakarta.persistence.criteria.Subquery;
import javax.management.InvalidApplicationException;
import java.util.Arrays; import java.util.Arrays;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
@ -88,7 +90,7 @@ public class GrantQuery extends Query<Grant, UUID> {
} }
@Override @Override
public QueryableList<Grant> getQuery() { public QueryableList<Grant> getQuery() throws InvalidApplicationException {
QueryableList<Grant> query = this.databaseAccessLayer.asQueryable(); QueryableList<Grant> query = this.databaseAccessLayer.asQueryable();
if (this.id != null) if (this.id != null)
query.where((builder, root) -> builder.equal(root.get("id"), this.id)); 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 eu.eudat.queryable.types.SelectionField;
import jakarta.persistence.criteria.Subquery; import jakarta.persistence.criteria.Subquery;
import javax.management.InvalidApplicationException;
import java.util.Arrays; import java.util.Arrays;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
@ -61,7 +63,7 @@ public class LockQuery extends Query<Lock, UUID> {
} }
@Override @Override
public QueryableList<Lock> getQuery() { public QueryableList<Lock> getQuery() throws InvalidApplicationException {
QueryableList<Lock> query = this.databaseAccessLayer.asQueryable(); QueryableList<Lock> query = this.databaseAccessLayer.asQueryable();
if (this.id != null) { if (this.id != null) {
query.where((builder, root) -> builder.equal(root.get("id"), this.id)); 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.QueryableList;
import eu.eudat.queryable.queryableentity.DataEntity; import eu.eudat.queryable.queryableentity.DataEntity;
import javax.management.InvalidApplicationException;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.List; import java.util.List;
@ -21,7 +22,7 @@ public abstract class Query<T extends DataEntity, K> {
this.databaseAccessLayer = databaseAccessLayer; this.databaseAccessLayer = databaseAccessLayer;
} }
public abstract QueryableList<T> getQuery(); public abstract QueryableList<T> getQuery() throws InvalidApplicationException;
protected List<String> getSelectionFields() { protected List<String> getSelectionFields() {
return selectionFields; return selectionFields;

View File

@ -7,6 +7,8 @@ import eu.eudat.queryable.types.SelectionField;
import jakarta.persistence.criteria.Join; import jakarta.persistence.criteria.Join;
import jakarta.persistence.criteria.JoinType; import jakarta.persistence.criteria.JoinType;
import jakarta.persistence.criteria.Subquery; import jakarta.persistence.criteria.Subquery;
import javax.management.InvalidApplicationException;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
@ -14,27 +16,27 @@ import java.util.concurrent.CompletableFuture;
public interface QueryableList<T extends DataEntity> { public interface QueryableList<T extends DataEntity> {
QueryableList<T> where(SinglePredicate<T> predicate); 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); QueryableList<T> withFields(List<String> fields);
List<Map> toListWithFields(); 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); QueryableList<T> skip(Integer offset);
@ -48,25 +50,25 @@ public interface QueryableList<T extends DataEntity> {
QueryableList<T> withHint(String hint); QueryableList<T> withHint(String hint);
Long count(); Long count() throws InvalidApplicationException;
QueryableList<T> where(NestedQuerySinglePredicate<T> predicate); 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<T> subQuery(NestedQuerySinglePredicate<T> predicate, List<SelectionField> fields);
Subquery<Long> subQueryCount(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> 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); <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.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async; import org.springframework.scheduling.annotation.Async;
import javax.management.InvalidApplicationException;
import java.util.*; import java.util.*;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@ -154,11 +155,11 @@ public class QueryableHibernateList<T extends DataEntity> implements QueryableLi
return this; 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()); 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())); 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; return this;
} }
public Long count() { public Long count() throws InvalidApplicationException {
CriteriaBuilder criteriaBuilder = this.manager.getCriteriaBuilder(); CriteriaBuilder criteriaBuilder = this.manager.getCriteriaBuilder();
CriteriaQuery<Long> criteriaQuery = criteriaBuilder.createQuery(Long.class); CriteriaQuery<Long> criteriaQuery = criteriaBuilder.createQuery(Long.class);
this.root = criteriaQuery.from(tClass); this.root = criteriaQuery.from(tClass);
@ -200,7 +201,7 @@ public class QueryableHibernateList<T extends DataEntity> implements QueryableLi
} }
@Async @Async
public CompletableFuture<Long> countAsync() { public CompletableFuture<Long> countAsync() throws InvalidApplicationException {
CriteriaBuilder criteriaBuilder = this.manager.getCriteriaBuilder(); CriteriaBuilder criteriaBuilder = this.manager.getCriteriaBuilder();
CriteriaQuery<Long> criteriaQuery = criteriaBuilder.createQuery(Long.class); CriteriaQuery<Long> criteriaQuery = criteriaBuilder.createQuery(Long.class);
this.root = criteriaQuery.from(tClass); 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<>(); List<Predicate> predicates = new LinkedList<>();
predicates.addAll(Arrays.asList(this.generateSingleWherePredicates(singlePredicates, root))); predicates.addAll(Arrays.asList(this.generateSingleWherePredicates(singlePredicates, root)));
predicates.addAll(Arrays.asList(this.generateNestedWherePredicates(nestedPredicates, root, nestedQueryRoot))); predicates.addAll(Arrays.asList(this.generateNestedWherePredicates(nestedPredicates, root, nestedQueryRoot)));
return predicates.toArray(new Predicate[predicates.size()]); 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<>(); List<Predicate> predicates = new LinkedList<>();
for (SinglePredicate<T> singlePredicate : singlePredicates) { for (SinglePredicate<T> singlePredicate : singlePredicates) {
predicates.add(singlePredicate.applyPredicate(this.manager.getCriteriaBuilder(), root)); 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()]); return predicates.toArray(new Expression[predicates.size()]);
} }
public List<T> toList() { public List<T> toList() throws InvalidApplicationException {
CriteriaBuilder builder = this.manager.getCriteriaBuilder(); CriteriaBuilder builder = this.manager.getCriteriaBuilder();
if (!this.fields.isEmpty()) if (!this.fields.isEmpty())
this.query = builder.createTupleQuery(); this.query = builder.createTupleQuery();
@ -310,7 +311,7 @@ public class QueryableHibernateList<T extends DataEntity> implements QueryableLi
} }
@Async @Async
public CompletableFuture<List<T>> toListAsync() { public CompletableFuture<List<T>> toListAsync() throws InvalidApplicationException {
CriteriaBuilder builder = this.manager.getCriteriaBuilder(); CriteriaBuilder builder = this.manager.getCriteriaBuilder();
if (!this.fields.isEmpty()) if (!this.fields.isEmpty())
this.query = builder.createTupleQuery(); 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(); CriteriaBuilder builder = this.manager.getCriteriaBuilder();
if (!this.fields.isEmpty()) if (!this.fields.isEmpty())
this.query = builder.createTupleQuery(); this.query = builder.createTupleQuery();
@ -381,7 +382,7 @@ public class QueryableHibernateList<T extends DataEntity> implements QueryableLi
} }
@Async @Async
public CompletableFuture<T> getSingleAsync() { public CompletableFuture<T> getSingleAsync() throws InvalidApplicationException {
CriteriaBuilder builder = this.manager.getCriteriaBuilder(); CriteriaBuilder builder = this.manager.getCriteriaBuilder();
if (!this.fields.isEmpty()) if (!this.fields.isEmpty())
this.query = builder.createTupleQuery(); this.query = builder.createTupleQuery();
@ -397,7 +398,7 @@ public class QueryableHibernateList<T extends DataEntity> implements QueryableLi
return CompletableFuture.supplyAsync(() -> typedQuery.getSingleResult()); return CompletableFuture.supplyAsync(() -> typedQuery.getSingleResult());
} }
public T getSingleOrDefault() { public T getSingleOrDefault() throws InvalidApplicationException {
CriteriaBuilder builder = this.manager.getCriteriaBuilder(); CriteriaBuilder builder = this.manager.getCriteriaBuilder();
if (!this.fields.isEmpty()) if (!this.fields.isEmpty())
this.query = builder.createTupleQuery(); this.query = builder.createTupleQuery();
@ -420,7 +421,7 @@ public class QueryableHibernateList<T extends DataEntity> implements QueryableLi
} }
@Async @Async
public CompletableFuture<T> getSingleOrDefaultAsync() { public CompletableFuture<T> getSingleOrDefaultAsync() throws InvalidApplicationException {
CriteriaBuilder builder = this.manager.getCriteriaBuilder(); CriteriaBuilder builder = this.manager.getCriteriaBuilder();
if (!this.fields.isEmpty()) if (!this.fields.isEmpty())
this.query = builder.createTupleQuery(); this.query = builder.createTupleQuery();
@ -460,7 +461,7 @@ public class QueryableHibernateList<T extends DataEntity> implements QueryableLi
} }
@Override @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); Subquery<T> subquery = this.manager.getCriteriaBuilder().createQuery().subquery(this.tClass);
this.nestedQueryRoot = subquery.from(this.tClass); this.nestedQueryRoot = subquery.from(this.tClass);
subquery.where(predicate.applyPredicate(this.manager.getCriteriaBuilder(), this.nestedQueryRoot)); subquery.where(predicate.applyPredicate(this.manager.getCriteriaBuilder(), this.nestedQueryRoot));
@ -486,7 +487,7 @@ public class QueryableHibernateList<T extends DataEntity> implements QueryableLi
} }
@Override @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); Subquery<Long> subquery = this.manager.getCriteriaBuilder().createQuery().subquery(Long.class);
this.nestedQueryRoot = subquery.from(this.tClass); this.nestedQueryRoot = subquery.from(this.tClass);
subquery.where(predicate.applyPredicate(this.manager.getCriteriaBuilder(), this.nestedQueryRoot)); subquery.where(predicate.applyPredicate(this.manager.getCriteriaBuilder(), this.nestedQueryRoot));
@ -504,7 +505,7 @@ public class QueryableHibernateList<T extends DataEntity> implements QueryableLi
} }
@Override @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); Subquery<U> subquery = this.manager.getCriteriaBuilder().createQuery().subquery(uClass);
this.nestedQueryRoot = subquery.from(this.tClass); this.nestedQueryRoot = subquery.from(this.tClass);
subquery.where(predicate.applyPredicate(this.manager.getCriteriaBuilder(), this.nestedQueryRoot)); subquery.where(predicate.applyPredicate(this.manager.getCriteriaBuilder(), this.nestedQueryRoot));
@ -537,7 +538,7 @@ public class QueryableHibernateList<T extends DataEntity> implements QueryableLi
} }
@Override @Override
public Subquery<T> query(List<SelectionField> fields) { public Subquery<T> query(List<SelectionField> fields) throws InvalidApplicationException {
CriteriaBuilder builder = this.manager.getCriteriaBuilder(); CriteriaBuilder builder = this.manager.getCriteriaBuilder();
Subquery<T> query = builder.createQuery().subquery(this.tClass); Subquery<T> query = builder.createQuery().subquery(this.tClass);
this.root = query.from(this.tClass); this.root = query.from(this.tClass);
@ -553,7 +554,7 @@ public class QueryableHibernateList<T extends DataEntity> implements QueryableLi
} }
@Override @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 CriteriaBuilder builder = this.manager
.getCriteriaBuilder(); .getCriteriaBuilder();
CriteriaUpdate<T> update = builder CriteriaUpdate<T> update = builder

View File

@ -4,6 +4,8 @@ import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.Predicate; import jakarta.persistence.criteria.Predicate;
import jakarta.persistence.criteria.Root; import jakarta.persistence.criteria.Root;
import javax.management.InvalidApplicationException;
public interface SinglePredicate<T> { 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; package eu.eudat.configurations;
import eu.eudat.commons.scope.user.UserScope;
import eu.eudat.interceptors.UserInterceptor; 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.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.annotation.EnableAsync;
@ -21,28 +16,15 @@ import java.util.List;
@EnableScheduling @EnableScheduling
public class WebMVCConfiguration implements WebMvcConfigurer { public class WebMVCConfiguration implements WebMvcConfigurer {
private ApiContext apiContext;
private AuthenticationService verifiedUserAuthenticationService;
private AuthenticationService nonVerifiedUserAuthenticationService;
private final UserInterceptor userInterceptor; private final UserInterceptor userInterceptor;
private final UserScope userScope;
private final CurrentPrincipalResolver currentPrincipalResolver;
@Autowired @Autowired
public WebMVCConfiguration(ApiContext apiContext, AuthenticationService verifiedUserAuthenticationService, AuthenticationService nonVerifiedUserAuthenticationService, UserInterceptor userInterceptor, UserScope userScope, CurrentPrincipalResolver currentPrincipalResolver) { public WebMVCConfiguration(UserInterceptor userInterceptor) {
this.apiContext = apiContext;
this.verifiedUserAuthenticationService = verifiedUserAuthenticationService;
this.nonVerifiedUserAuthenticationService = nonVerifiedUserAuthenticationService;
this.userInterceptor = userInterceptor; this.userInterceptor = userInterceptor;
this.userScope = userScope;
this.currentPrincipalResolver = currentPrincipalResolver;
} }
@Autowired @Autowired
@Override @Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) { public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
argumentResolvers.add(new PrincipalArgumentResolver(verifiedUserAuthenticationService, nonVerifiedUserAuthenticationService, userScope, currentPrincipalResolver));
} }
@Override @Override

View File

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

View File

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

View File

@ -1,6 +1,7 @@
package eu.eudat.controllers; package eu.eudat.controllers;
import eu.eudat.authorization.Permission;
import eu.eudat.configurations.dynamicgrant.DynamicGrantConfiguration; import eu.eudat.configurations.dynamicgrant.DynamicGrantConfiguration;
import eu.eudat.criteria.DMPCriteria; import eu.eudat.criteria.DMPCriteria;
import eu.eudat.data.dao.criteria.DynamicFieldsCriteria; 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.exceptions.security.UnauthorisedException;
import eu.eudat.logic.managers.DataManagementPlanManager; import eu.eudat.logic.managers.DataManagementPlanManager;
import eu.eudat.logic.proxy.config.configloaders.ConfigLoader; 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.ApiContext;
import eu.eudat.logic.services.operations.DatabaseRepository; import eu.eudat.logic.services.operations.DatabaseRepository;
import eu.eudat.logic.utilities.documents.helpers.FileEnvelope; 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.DataManagementPlanOverviewModel;
import eu.eudat.models.data.listingmodels.UserInfoListingModel; import eu.eudat.models.data.listingmodels.UserInfoListingModel;
import eu.eudat.models.data.listingmodels.VersionListingModel; import eu.eudat.models.data.listingmodels.VersionListingModel;
import eu.eudat.models.data.security.Principal;
import eu.eudat.query.DMPQuery; import eu.eudat.query.DMPQuery;
import eu.eudat.types.ApiMessageCode; import eu.eudat.types.ApiMessageCode;
import eu.eudat.types.Authorities; import eu.eudat.types.Authorities;
import gr.cite.commons.web.authz.service.AuthorizationService;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@ -47,6 +47,8 @@ import org.springframework.web.multipart.MultipartFile;
import jakarta.activation.MimetypesFileTypeMap; import jakarta.activation.MimetypesFileTypeMap;
import jakarta.validation.Valid; import jakarta.validation.Valid;
import javax.management.InvalidApplicationException;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.IOException; import java.io.IOException;
@ -69,15 +71,17 @@ public class DMPs extends BaseController {
private Environment environment; private Environment environment;
private DataManagementPlanManager dataManagementPlanManager; private DataManagementPlanManager dataManagementPlanManager;
private ConfigLoader configLoader; private ConfigLoader configLoader;
private final AuthorizationService authorizationService;
@Autowired @Autowired
public DMPs(ApiContext apiContext, DynamicGrantConfiguration dynamicGrantConfiguration, Environment environment, public DMPs(ApiContext apiContext, DynamicGrantConfiguration dynamicGrantConfiguration, Environment environment,
DataManagementPlanManager dataManagementPlanManager, ConfigLoader configLoader) { DataManagementPlanManager dataManagementPlanManager, ConfigLoader configLoader, AuthorizationService authorizationService) {
super(apiContext); super(apiContext);
this.dynamicGrantConfiguration = dynamicGrantConfiguration; this.dynamicGrantConfiguration = dynamicGrantConfiguration;
this.environment = environment; this.environment = environment;
this.dataManagementPlanManager = dataManagementPlanManager; this.dataManagementPlanManager = dataManagementPlanManager;
this.configLoader = configLoader; 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") @RequestMapping(method = RequestMethod.POST, value = {"/paged"}, consumes = "application/json", produces = "application/json")
public @ResponseBody public @ResponseBody
ResponseEntity<ResponseItem<DataTableData<DataManagementPlanListingModel>>> getPaged(@Valid @RequestBody DataManagementPlanTableRequest dataManagementPlanTableRequest, ResponseEntity<ResponseItem<DataTableData<DataManagementPlanListingModel>>> getPaged(@Valid @RequestBody DataManagementPlanTableRequest dataManagementPlanTableRequest,
@RequestParam String fieldsGroup, @RequestParam String fieldsGroup) throws Exception {
@ClaimedAuthorities(claims = {Authorities.ADMIN, Authorities.MANAGER, Authorities.USER, Authorities.ANONYMOUS}) Principal principal) throws Exception { this.authorizationService.authorizeForce(Permission.AdminRole, Permission.ManagerRole, Permission.UserRole, Permission.AnonymousRole);
DataTableData<DataManagementPlanListingModel> dataTable = this.dataManagementPlanManager.getPaged(dataManagementPlanTableRequest, principal, fieldsGroup);
DataTableData<DataManagementPlanListingModel> dataTable = this.dataManagementPlanManager.getPaged(dataManagementPlanTableRequest, fieldsGroup);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DataTableData<DataManagementPlanListingModel>>().status(ApiMessageCode.NO_MESSAGE).payload(dataTable)); return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DataTableData<DataManagementPlanListingModel>>().status(ApiMessageCode.NO_MESSAGE).payload(dataTable));
} }
@RequestMapping(method = RequestMethod.GET, value = {"{id}"}) @RequestMapping(method = RequestMethod.GET, value = {"{id}"})
public @ResponseBody public @ResponseBody
ResponseEntity getSingle(@PathVariable String id, @RequestHeader("Content-Type") String contentType, ResponseEntity getSingle(@PathVariable String id, @RequestHeader("Content-Type") String contentType) throws Exception {
@ClaimedAuthorities(claims = {Authorities.ADMIN, Authorities.MANAGER, Authorities.USER, Authorities.ANONYMOUS}) Principal principal) throws Exception { this.authorizationService.authorizeForce(Permission.AdminRole, Permission.ManagerRole, Permission.UserRole, Permission.AnonymousRole);
if (contentType.equals("application/xml") || contentType.equals("application/msword")) { 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 { } 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)); return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DataManagementPlan>().status(ApiMessageCode.NO_MESSAGE).payload(dataManagementPlan));
} }
} }
@RequestMapping(method = RequestMethod.GET, value = {"/plain/{id}"}) @RequestMapping(method = RequestMethod.GET, value = {"/plain/{id}"})
public @ResponseBody public @ResponseBody
ResponseEntity getSingleNoDatasets(@PathVariable String id, @RequestHeader("Content-Type") String contentType, ResponseEntity getSingleNoDatasets(@PathVariable String id, @RequestHeader("Content-Type") String contentType) throws Exception {
@ClaimedAuthorities(claims = {Authorities.ADMIN, Authorities.MANAGER, Authorities.USER, Authorities.ANONYMOUS}) Principal principal) 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)); 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") @RequestMapping(method = RequestMethod.POST, value = {"/datasetProfilesUsedByDmps/paged"}, produces = "application/json")
public @ResponseBody public @ResponseBody
ResponseEntity<ResponseItem<DataTableData<DatasetProfileListingModel>>> getUsingDatasetProfilesPaged(@RequestBody DatasetProfileTableRequestItem datasetProfileTableRequestItem, Principal principal) { ResponseEntity<ResponseItem<DataTableData<DatasetProfileListingModel>>> getUsingDatasetProfilesPaged(@RequestBody DatasetProfileTableRequestItem datasetProfileTableRequestItem) throws InvalidApplicationException {
DataTableData<DatasetProfileListingModel> datasetProfileTableData = this.dataManagementPlanManager.getDatasetProfilesUsedByDMP(datasetProfileTableRequestItem, principal); 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)); return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DataTableData<DatasetProfileListingModel>>().status(ApiMessageCode.NO_MESSAGE).payload(datasetProfileTableData));
} }
@RequestMapping(method = RequestMethod.GET, value = {"/overview/{id}"}) @RequestMapping(method = RequestMethod.GET, value = {"/overview/{id}"})
public @ResponseBody 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 { 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)); return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DataManagementPlanOverviewModel>().status(ApiMessageCode.NO_MESSAGE).payload(dataManagementPlan));
} catch (Exception e) { } catch (Exception e) {
if (e instanceof UnauthorisedException) { if (e instanceof UnauthorisedException) {
@ -139,9 +148,10 @@ public class DMPs extends BaseController {
@RequestMapping(method = RequestMethod.GET, value = {"/public/{id}"}) @RequestMapping(method = RequestMethod.GET, value = {"/public/{id}"})
public @ResponseBody public @ResponseBody
ResponseEntity getSinglePublic(@PathVariable String id, @ClaimedAuthorities(claims = {Authorities.ADMIN, Authorities.MANAGER, Authorities.USER, Authorities.ANONYMOUS}) Principal principal) throws Exception { ResponseEntity getSinglePublic(@PathVariable String id) throws Exception {
this.authorizationService.authorizeForce(Permission.AdminRole, Permission.ManagerRole, Permission.UserRole, Permission.AnonymousRole);
// try { // try {
eu.eudat.models.data.dmp.DataManagementPlan dataManagementPlan = this.dataManagementPlanManager.getSingle(id, principal, true, true); 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)); return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DataManagementPlan>().status(ApiMessageCode.NO_MESSAGE).payload(dataManagementPlan));
// } catch (Exception ex) { // } catch (Exception ex) {
// return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem<DataManagementPlan>().status(ApiMessageCode.NO_MESSAGE).message(ex.getMessage())); // 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}"}) @RequestMapping(method = RequestMethod.GET, value = {"/publicOverview/{id}"})
public @ResponseBody 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 { // 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)); return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DataManagementPlanOverviewModel>().status(ApiMessageCode.NO_MESSAGE).payload(dataManagementPlan));
// } catch (Exception ex) { // } catch (Exception ex) {
// return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem<DataManagementPlanOverviewModel>().status(ApiMessageCode.NO_MESSAGE).message(ex.getMessage())); // 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") @RequestMapping(method = RequestMethod.POST, value = {"/dynamic"}, consumes = "application/json", produces = "application/json")
public @ResponseBody 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()); 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)); 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") @RequestMapping(method = RequestMethod.GET, value = {"/versions/{id}"}, consumes = "application/json", produces = "application/json")
public @ResponseBody public @ResponseBody
ResponseEntity<ResponseItem<List<VersionListingModel>>> getVersions(@PathVariable(value= "id") String groupId, @RequestParam(value= "public") Boolean isPublic, ResponseEntity<ResponseItem<List<VersionListingModel>>> getVersions(@PathVariable(value= "id") String groupId, @RequestParam(value= "public") Boolean isPublic) throws Exception {
@ClaimedAuthorities(claims = {Authorities.ADMIN, Authorities.MANAGER, Authorities.USER, Authorities.ANONYMOUS}) Principal principal) throws Exception { this.authorizationService.authorizeForce(Permission.AdminRole, Permission.ManagerRole, Permission.UserRole, Permission.AnonymousRole);
List<VersionListingModel> versions = this.dataManagementPlanManager.getAllVersions(groupId, principal, isPublic); List<VersionListingModel> versions = this.dataManagementPlanManager.getAllVersions(groupId, isPublic);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List<VersionListingModel>>().status(ApiMessageCode.NO_MESSAGE).payload(versions)); 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}"}) @RequestMapping(method = RequestMethod.GET, value = {"rda/{id}"})
public @ResponseBody 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 { try {
FileEnvelope rdaJsonDocument = this.dataManagementPlanManager.getRDAJsonDocument(id, principal); FileEnvelope rdaJsonDocument = this.dataManagementPlanManager.getRDAJsonDocument(id);
HttpHeaders responseHeaders = new HttpHeaders(); HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentLength(rdaJsonDocument.getFile().length()); responseHeaders.setContentLength(rdaJsonDocument.getFile().length());
@ -204,9 +218,9 @@ public class DMPs extends BaseController {
@RequestMapping(method = RequestMethod.GET, value = {"/getPDF/{id}"}) @RequestMapping(method = RequestMethod.GET, value = {"/getPDF/{id}"})
public @ResponseBody public @ResponseBody
ResponseEntity<byte[]> getPDFDocument(@PathVariable String id, @RequestHeader("Content-Type") String contentType, ResponseEntity<byte[]> getPDFDocument(@PathVariable String id, @RequestHeader("Content-Type") String contentType) throws IllegalAccessException, IOException, InstantiationException, InterruptedException, InvalidApplicationException {
@ClaimedAuthorities(claims = {Authorities.ADMIN, Authorities.MANAGER, Authorities.USER, Authorities.ANONYMOUS}) Principal principal) throws IllegalAccessException, IOException, InstantiationException, InterruptedException { this.authorizationService.authorizeForce(Permission.AdminRole, Permission.ManagerRole, Permission.UserRole, Permission.AnonymousRole);
FileEnvelope file = this.dataManagementPlanManager.getWordDocument(id, principal, configLoader); FileEnvelope file = this.dataManagementPlanManager.getWordDocument(id, configLoader);
String name = file.getFilename().substring(0, file.getFilename().length() - 5).replace(" ", "_").replace(",", "_"); String name = file.getFilename().substring(0, file.getFilename().length() - 5).replace(" ", "_").replace(",", "_");
File pdffile = PDFUtils.convertToPDF(file, environment); File pdffile = PDFUtils.convertToPDF(file, environment);
InputStream resource = new FileInputStream(pdffile); InputStream resource = new FileInputStream(pdffile);
@ -233,24 +247,29 @@ public class DMPs extends BaseController {
@Transactional @Transactional
@RequestMapping(method = RequestMethod.POST, consumes = "application/json", produces = "application/json") @RequestMapping(method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
public @ResponseBody public @ResponseBody
ResponseEntity<ResponseItem<eu.eudat.models.data.dmp.DataManagementPlan>> createOrUpdate(@RequestBody eu.eudat.models.data.dmp.DataManagementPlanEditorModel dataManagementPlanEditorModel, Principal principal) throws Exception { ResponseEntity<ResponseItem<eu.eudat.models.data.dmp.DataManagementPlan>> createOrUpdate(@RequestBody eu.eudat.models.data.dmp.DataManagementPlanEditorModel dataManagementPlanEditorModel) throws Exception {
DMP dmp = this.dataManagementPlanManager.createOrUpdate(dataManagementPlanEditorModel, principal); 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))); 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 @Transactional
@RequestMapping(method = RequestMethod.POST, path = "full", consumes = "application/json", produces = "application/json") @RequestMapping(method = RequestMethod.POST, path = "full", consumes = "application/json", produces = "application/json")
public @ResponseBody public @ResponseBody
ResponseEntity<ResponseItem<UUID>> createOrUpdateWithDatasets(@RequestBody eu.eudat.models.data.dmp.DataManagementPlanEditorModel dataManagementPlanEditorModel, Principal principal) throws Exception { ResponseEntity<ResponseItem<UUID>> createOrUpdateWithDatasets(@RequestBody eu.eudat.models.data.dmp.DataManagementPlanEditorModel dataManagementPlanEditorModel) throws Exception {
DMP dmp = this.dataManagementPlanManager.createOrUpdateWithDatasets(dataManagementPlanEditorModel, principal); 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())); 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") @RequestMapping(method = RequestMethod.POST, value = {"/new/{id}"}, consumes = "application/json", produces = "application/json")
public @ResponseBody 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 { 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)); return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<UUID>().status(ApiMessageCode.NO_MESSAGE).payload(result));
} catch (DMPNewVersionException exception) { } catch (DMPNewVersionException exception) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem<UUID>().status(ApiMessageCode.ERROR_MESSAGE).message(exception.getMessage())); 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") @RequestMapping(method = RequestMethod.POST, value = {"/clone/{id}"}, consumes = "application/json", produces = "application/json")
public @ResponseBody public @ResponseBody
ResponseEntity<ResponseItem<UUID>> clone(@PathVariable UUID id, @RequestBody eu.eudat.models.data.dmp.DataManagementPlanNewVersionModel dataManagementPlan, Principal principal) throws Exception { ResponseEntity<ResponseItem<UUID>> clone(@PathVariable UUID id, @RequestBody eu.eudat.models.data.dmp.DataManagementPlanNewVersionModel dataManagementPlan) throws Exception {
UUID cloneId = this.dataManagementPlanManager.clone(id, dataManagementPlan, principal); 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)); 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") @RequestMapping(method = RequestMethod.DELETE, value = {"{id}"}, consumes = "application/json", produces = "application/json")
public @ResponseBody public @ResponseBody
ResponseEntity<ResponseItem<DMP>> delete(@PathVariable UUID id, Principal principal) { ResponseEntity<ResponseItem<DMP>> delete(@PathVariable UUID id) {
this.authorizationService.authorizeForce(Permission.AuthenticatedRole);
try { try {
this.dataManagementPlanManager.delete(id); this.dataManagementPlanManager.delete(id);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DMP>().status(ApiMessageCode.SUCCESS_MESSAGE).message("Successfully Deleted Datamanagement Plan")); 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())); return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem<DMP>().status(ApiMessageCode.ERROR_MESSAGE).message(exception.getMessage()));
} }
} }
@RequestMapping(method = RequestMethod.POST, value = {"/upload"}) @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())) { 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())) { } 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 { } else {
return ResponseEntity.badRequest().body(new ResponseItem().status(ApiMessageCode.ERROR_MESSAGE).message("File format is not supported")); 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}"}) @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 { 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.")); return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DMP>().status(ApiMessageCode.SUCCESS_MESSAGE).message("Successfully Data Datamanagement Plan made public."));
} catch (Exception e) { } catch (Exception e) {
logger.error(e.getMessage(), e); logger.error(e.getMessage(), e);
@ -300,9 +327,11 @@ public class DMPs extends BaseController {
} }
@RequestMapping(method = RequestMethod.POST, value = {"/finalize/{id}"}) @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 { 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.")); return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DMP>().status(ApiMessageCode.SUCCESS_MESSAGE).message("Successfully Data Datamanagement Plan made finalized."));
} catch (Exception e) { } catch (Exception e) {
logger.error(e.getMessage(), e); logger.error(e.getMessage(), e);
@ -311,9 +340,11 @@ public class DMPs extends BaseController {
} }
@RequestMapping(method = RequestMethod.POST, value = {"/unfinalize/{id}"}) @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 { 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.")); return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DMP>().status(ApiMessageCode.SUCCESS_MESSAGE).message("Successfully Data Datamanagement Plan made active."));
} catch (Exception e) { } catch (Exception e) {
logger.error(e.getMessage(), e); logger.error(e.getMessage(), e);
@ -323,9 +354,11 @@ public class DMPs extends BaseController {
@RequestMapping(method = RequestMethod.POST, value = {"/updateusers/{id}"}) @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 { 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.")); return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DMP>().status(ApiMessageCode.SUCCESS_MESSAGE).message("Successfully Updated Colaborators for Data Datamanagement Plan."));
} catch (Exception e) { } catch (Exception e) {
logger.error(e.getMessage(), e); logger.error(e.getMessage(), e);
@ -340,16 +373,20 @@ public class DMPs extends BaseController {
@Transactional @Transactional
@RequestMapping(method = RequestMethod.POST, value = {"/index"}) @RequestMapping(method = RequestMethod.POST, value = {"/index"})
public @ResponseBody public @ResponseBody
ResponseEntity<ResponseItem<Dataset>> generateIndex(Principal principal) throws Exception { ResponseEntity<ResponseItem<Dataset>> generateIndex() throws Exception {
this.dataManagementPlanManager.generateIndex(principal); 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)); return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<Dataset>().status(ApiMessageCode.SUCCESS_MESSAGE).message("Generated").payload(null));
} }
@Transactional @Transactional
@RequestMapping(method = RequestMethod.DELETE, value = {"/index"}) @RequestMapping(method = RequestMethod.DELETE, value = {"/index"})
public @ResponseBody public @ResponseBody
ResponseEntity<ResponseItem<Dataset>> clearIndex(Principal principal) throws Exception { ResponseEntity<ResponseItem<Dataset>> clearIndex() throws Exception {
this.dataManagementPlanManager.clearIndex(principal); 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)); 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") @RequestMapping(method = RequestMethod.POST, value = {"/test"}, consumes = "application/json", produces = "application/json")
public @ResponseBody 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(); DatabaseRepository dbRepo = this.getApiContext().getOperationsContext().getDatabaseRepository();
DMPQuery query = criteria.buildQuery(dbRepo); DMPQuery query = criteria.buildQuery(dbRepo);
@ -382,7 +421,7 @@ public class DMPs extends BaseController {
/*@Transactional /*@Transactional
@RequestMapping(method = RequestMethod.GET, value = {"{id}/unlock"}, produces = "application/json") @RequestMapping(method = RequestMethod.GET, value = {"{id}/unlock"}, produces = "application/json")
public @ResponseBody 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); this.dataManagementPlanManager.unlock(id);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DMP>().status(ApiMessageCode.SUCCESS_MESSAGE).message("Unlocked")); 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.authorization.Permission;
import eu.eudat.logic.managers.DashBoardManager; import eu.eudat.logic.managers.DashBoardManager;
import eu.eudat.logic.security.claims.ClaimedAuthorities;
import eu.eudat.logic.services.ApiContext; import eu.eudat.logic.services.ApiContext;
import eu.eudat.models.data.dashboard.recent.RecentActivity; import eu.eudat.models.data.dashboard.recent.RecentActivity;
import eu.eudat.models.data.dashboard.recent.model.RecentActivityModel; 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.searchbar.SearchBarItem;
import eu.eudat.models.data.dashboard.statistics.DashBoardStatistics; import eu.eudat.models.data.dashboard.statistics.DashBoardStatistics;
import eu.eudat.models.data.helpers.responses.ResponseItem; import eu.eudat.models.data.helpers.responses.ResponseItem;
import eu.eudat.models.data.security.Principal;
import eu.eudat.types.ApiMessageCode; import eu.eudat.types.ApiMessageCode;
import eu.eudat.types.Authorities; import eu.eudat.types.Authorities;
import gr.cite.commons.web.authz.service.AuthorizationService; import gr.cite.commons.web.authz.service.AuthorizationService;
@ -20,6 +18,8 @@ import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import jakarta.transaction.Transactional; import jakarta.transaction.Transactional;
import javax.management.InvalidApplicationException;
import java.io.IOException; import java.io.IOException;
import java.util.List; import java.util.List;
@ -38,15 +38,15 @@ public class DashBoardController extends BaseController {
} }
@RequestMapping(method = RequestMethod.GET, value = {"/dashboard/me/getStatistics"}, produces = "application/json") @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); 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)); 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") @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); this.authorizationService.authorizeForce(Permission.BrowsePublicStatistics);
DashBoardStatistics statistics = dashBoardManager.getStatistics(); DashBoardStatistics statistics = dashBoardManager.getStatistics();
@ -55,23 +55,28 @@ public class DashBoardController extends BaseController {
@RequestMapping(method = RequestMethod.POST, value = {"/dashboard/recentActivity"}, produces = "application/json") @RequestMapping(method = RequestMethod.POST, value = {"/dashboard/recentActivity"}, produces = "application/json")
@Transactional @Transactional
public ResponseEntity<ResponseItem<List<RecentActivityModel>>> getNewRecentActivity(@RequestBody RecentActivityTableRequest tableRequest, public ResponseEntity<ResponseItem<List<RecentActivityModel>>> getNewRecentActivity(@RequestBody RecentActivityTableRequest tableRequest) throws Exception {
@ClaimedAuthorities(claims = {Authorities.ADMIN, Authorities.MANAGER, Authorities.USER, Authorities.ANONYMOUS}) Principal principal) throws Exception { this.authorizationService.authorizeForce(Permission.AdminRole, Permission.ManagerRole, Permission.UserRole, Permission.AnonymousRole);
List<RecentActivityModel> statistics = dashBoardManager.getNewRecentActivity(tableRequest, principal);
List<RecentActivityModel> statistics = dashBoardManager.getNewRecentActivity(tableRequest);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List<RecentActivityModel>>().status(ApiMessageCode.NO_MESSAGE).payload(statistics)); return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List<RecentActivityModel>>().status(ApiMessageCode.NO_MESSAGE).payload(statistics));
} }
@Deprecated @Deprecated
@RequestMapping(method = RequestMethod.GET, value = {"/user/recentActivity"}, produces = "application/json") @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) { public ResponseEntity<ResponseItem<RecentActivity>> getRecentActivity(@RequestParam(name = "numOfActivities", required = false, defaultValue = "5") Integer numberOfActivities) throws InvalidApplicationException {
RecentActivity statistics = dashBoardManager.getRecentActivity(principal, numberOfActivities); 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)); 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") @RequestMapping(method = RequestMethod.GET, value = {"/dashboard/search"}, produces = "application/json")
public ResponseEntity<ResponseItem<List<SearchBarItem>>> search(@RequestParam(name = "like") String like, public ResponseEntity<ResponseItem<List<SearchBarItem>>> search(@RequestParam(name = "like") String like) throws InvalidApplicationException {
@ClaimedAuthorities(claims = {Authorities.ADMIN, Authorities.MANAGER, Authorities.USER, Authorities.ANONYMOUS}) Principal principal) { this.authorizationService.authorizeForce(Permission.AdminRole, Permission.ManagerRole, Permission.UserRole, Permission.AnonymousRole);
List<SearchBarItem> searchBarItemList = dashBoardManager.searchUserData(like, principal);
List<SearchBarItem> searchBarItemList = dashBoardManager.searchUserData(like);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List<SearchBarItem>>().status(ApiMessageCode.NO_MESSAGE).payload(searchBarItemList)); 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; package eu.eudat.controllers;
import eu.eudat.authorization.Permission;
import eu.eudat.data.old.DataRepository; import eu.eudat.data.old.DataRepository;
import eu.eudat.logic.managers.DataRepositoryManager; import eu.eudat.logic.managers.DataRepositoryManager;
import eu.eudat.logic.proxy.config.exceptions.HugeResultSet; 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.logic.services.ApiContext;
import eu.eudat.models.data.datarepository.DataRepositoryModel; import eu.eudat.models.data.datarepository.DataRepositoryModel;
import eu.eudat.models.data.helpers.responses.ResponseItem; import eu.eudat.models.data.helpers.responses.ResponseItem;
import eu.eudat.models.data.security.Principal;
import eu.eudat.types.ApiMessageCode; import eu.eudat.types.ApiMessageCode;
import gr.cite.commons.web.authz.service.AuthorizationService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import javax.management.InvalidApplicationException;
import java.util.List; import java.util.List;
@ -24,27 +26,33 @@ import java.util.List;
public class DataRepositories extends BaseController { public class DataRepositories extends BaseController {
private DataRepositoryManager dataRepositoryManager; private DataRepositoryManager dataRepositoryManager;
private final AuthorizationService authorizationService;
@Autowired @Autowired
public DataRepositories(ApiContext apiContext, DataRepositoryManager dataRepositoryManager) { public DataRepositories(ApiContext apiContext, DataRepositoryManager dataRepositoryManager, AuthorizationService authorizationService) {
super(apiContext); super(apiContext);
this.dataRepositoryManager = dataRepositoryManager; this.dataRepositoryManager = dataRepositoryManager;
this.authorizationService = authorizationService;
} }
@RequestMapping(method = RequestMethod.GET, produces = "application/json") @RequestMapping(method = RequestMethod.GET, produces = "application/json")
public @ResponseBody public @ResponseBody
ResponseEntity<ResponseItem<List<DataRepositoryModel>>> listExternalDataRepositories( ResponseEntity<ResponseItem<List<DataRepositoryModel>>> listExternalDataRepositories(
@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 { ) throws HugeResultSet, NoURLFound, InvalidApplicationException {
List<DataRepositoryModel> dataRepositoryModels = this.dataRepositoryManager.getDataRepositories(query, type, principal); 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)); return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List<DataRepositoryModel>>().status(ApiMessageCode.NO_MESSAGE).payload(dataRepositoryModels));
} }
@Transactional @Transactional
@RequestMapping(method = RequestMethod.POST, consumes = "application/json", produces = "application/json") @RequestMapping(method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
public @ResponseBody public @ResponseBody
ResponseEntity<ResponseItem<DataRepositoryModel>> create(@RequestBody eu.eudat.models.data.datarepository.DataRepositoryModel dataRepositoryModel, Principal principal) throws Exception { ResponseEntity<ResponseItem<DataRepositoryModel>> create(@RequestBody eu.eudat.models.data.datarepository.DataRepositoryModel dataRepositoryModel) throws Exception {
DataRepository dataRepository = this.dataRepositoryManager.create(dataRepositoryModel, principal); this.authorizationService.authorizeForce(Permission.AuthenticatedRole);
DataRepository dataRepository = this.dataRepositoryManager.create(dataRepositoryModel);
DataRepositoryModel dataRepositoryModel1 = new DataRepositoryModel().fromDataModel(dataRepository); DataRepositoryModel dataRepositoryModel1 = new DataRepositoryModel().fromDataModel(dataRepository);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DataRepositoryModel>().payload(dataRepositoryModel1).status(ApiMessageCode.SUCCESS_MESSAGE)); 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; package eu.eudat.controllers;
import eu.eudat.authorization.Permission;
import eu.eudat.data.dao.criteria.RequestItem; import eu.eudat.data.dao.criteria.RequestItem;
import eu.eudat.data.old.DescriptionTemplate; import eu.eudat.data.old.DescriptionTemplate;
import eu.eudat.logic.managers.AdminManager; import eu.eudat.logic.managers.AdminManager;
import eu.eudat.logic.managers.DatasetProfileManager; import eu.eudat.logic.managers.DatasetProfileManager;
import eu.eudat.logic.security.claims.ClaimedAuthorities;
import eu.eudat.logic.services.ApiContext; import eu.eudat.logic.services.ApiContext;
import eu.eudat.models.data.components.commons.datafield.AutoCompleteData; import eu.eudat.models.data.components.commons.datafield.AutoCompleteData;
import eu.eudat.models.data.externaldataset.ExternalAutocompleteFieldModel; import eu.eudat.models.data.externaldataset.ExternalAutocompleteFieldModel;
import eu.eudat.models.data.helpers.common.AutoCompleteLookupItem; import eu.eudat.models.data.helpers.common.AutoCompleteLookupItem;
import eu.eudat.models.data.helpers.common.AutoCompleteOptionsLookupItem; import eu.eudat.models.data.helpers.common.AutoCompleteOptionsLookupItem;
import eu.eudat.models.data.helpers.responses.ResponseItem; 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.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import javax.management.InvalidApplicationException;
import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathExpressionException;
import java.util.List; import java.util.List;
import java.util.UUID; import java.util.UUID;
@ -29,12 +30,14 @@ import static eu.eudat.types.Authorities.ADMIN;
@RequestMapping(value = {"/api"}) @RequestMapping(value = {"/api"})
public class DatasetProfileController extends BaseController { public class DatasetProfileController extends BaseController {
private DatasetProfileManager datasetProfileManager; private final DatasetProfileManager datasetProfileManager;
private final AuthorizationService authorizationService;
@Autowired @Autowired
public DatasetProfileController(ApiContext apiContext, DatasetProfileManager datasetProfileManager) { public DatasetProfileController(ApiContext apiContext, DatasetProfileManager datasetProfileManager, AuthorizationService authorizationService) {
super(apiContext); super(apiContext);
this.datasetProfileManager = datasetProfileManager; this.datasetProfileManager = datasetProfileManager;
this.authorizationService = authorizationService;
} }
/* @Transactional /* @Transactional
@ -52,7 +55,9 @@ public class DatasetProfileController extends BaseController {
@Transactional @Transactional
@RequestMapping(method = RequestMethod.POST, value = {"/datasetprofile/clone/{id}"}, consumes = "application/json", produces = "application/json") @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); DescriptionTemplate profile = this.datasetProfileManager.clone(id);
eu.eudat.models.data.admin.composite.DatasetProfile datasetprofile = AdminManager.generateDatasetProfileModel(profile); eu.eudat.models.data.admin.composite.DatasetProfile datasetprofile = AdminManager.generateDatasetProfileModel(profile);
datasetprofile.setLabel(profile.getLabel() + " new "); 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") @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())); 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()); eu.eudat.models.data.entities.xmlmodels.datasetprofiledefinition.Field modelfield = this.datasetProfileManager.queryForField(descriptionTemplate.getDefinition(), lookupItem.getCriteria().getFieldID());
AutoCompleteData data = (AutoCompleteData) modelfield.getData(); AutoCompleteData data = (AutoCompleteData) modelfield.getData();

View File

@ -13,6 +13,7 @@ import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import javax.management.InvalidApplicationException;
import java.util.List; import java.util.List;
@ -31,14 +32,14 @@ public class DatasetProfiles extends BaseController {
@RequestMapping(method = RequestMethod.POST, value = {"/dmps/datasetprofiles/get"}, produces = "application/json") @RequestMapping(method = RequestMethod.POST, value = {"/dmps/datasetprofiles/get"}, produces = "application/json")
public @ResponseBody 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); List<DatasetProfileAutocompleteItem> datasetProfileAutocompleteItems = this.datasetProfileManager.getWithCriteria(datasetProfileAutocompleteRequest);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List<DatasetProfileAutocompleteItem>>().status(ApiMessageCode.NO_MESSAGE).payload(datasetProfileAutocompleteItems)); 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") @RequestMapping(method = RequestMethod.POST, value = {"/datasetprofiles/getAll"}, produces = "application/json")
public @ResponseBody 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); List<DatasetProfileListingModel> datasetProfileTableData = this.datasetProfileManager.getAll(tableRequestItem);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List<DatasetProfileListingModel>>().status(ApiMessageCode.NO_MESSAGE).payload(datasetProfileTableData)); 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; 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.Dataset;
import eu.eudat.data.old.DescriptionTemplate; import eu.eudat.data.old.DescriptionTemplate;
import eu.eudat.data.query.items.item.dataset.DatasetWizardAutocompleteRequest; 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.FileManager;
import eu.eudat.logic.managers.UserManager; import eu.eudat.logic.managers.UserManager;
import eu.eudat.logic.proxy.config.configloaders.ConfigLoader; 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.ApiContext;
import eu.eudat.logic.services.forms.VisibilityRuleService; import eu.eudat.logic.services.forms.VisibilityRuleService;
import eu.eudat.logic.services.forms.VisibilityRuleServiceImpl; 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.helpers.responses.ResponseItem;
import eu.eudat.models.data.listingmodels.DataManagementPlanOverviewModel; import eu.eudat.models.data.listingmodels.DataManagementPlanOverviewModel;
import eu.eudat.models.data.listingmodels.DatasetListingModel; 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.models.data.user.composite.PagedDatasetProfile;
import eu.eudat.types.ApiMessageCode; 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.apache.poi.util.IOUtils;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -47,6 +47,8 @@ import org.springframework.web.multipart.MultipartFile;
import jakarta.persistence.NoResultException; import jakarta.persistence.NoResultException;
import jakarta.transaction.Transactional; import jakarta.transaction.Transactional;
import javax.management.InvalidApplicationException;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.IOException; import java.io.IOException;
@ -56,8 +58,6 @@ import java.util.List;
import java.util.Locale; import java.util.Locale;
import java.util.UUID; import java.util.UUID;
import static eu.eudat.types.Authorities.ANONYMOUS;
@RestController @RestController
@CrossOrigin @CrossOrigin
@ -70,16 +70,20 @@ public class Datasets extends BaseController {
private ConfigLoader configLoader; private ConfigLoader configLoader;
private UserManager userManager; private UserManager userManager;
private FileManager fileManager; private FileManager fileManager;
private final AuthorizationService authorizationService;
private final UserScope userScope;
@Autowired @Autowired
public Datasets(ApiContext apiContext, Environment environment, DatasetManager datasetManager, ConfigLoader configLoader, UserManager userManager, public Datasets(ApiContext apiContext, Environment environment, DatasetManager datasetManager, ConfigLoader configLoader, UserManager userManager,
FileManager fileManager) { FileManager fileManager, AuthorizationService authorizationService, UserScope userScope) {
super(apiContext); super(apiContext);
this.environment = environment; this.environment = environment;
this.datasetManager = datasetManager; this.datasetManager = datasetManager;
this.configLoader = configLoader; this.configLoader = configLoader;
this.userManager = userManager; this.userManager = userManager;
this.fileManager = fileManager; 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") @RequestMapping(method = RequestMethod.POST, value = {"paged"}, consumes = "application/json", produces = "application/json")
public @ResponseBody public @ResponseBody
ResponseEntity<ResponseItem<DataTableData<DatasetListingModel>>> getPaged(@RequestBody DatasetTableRequest datasetTableRequest, @ClaimedAuthorities(claims = {Authorities.ADMIN, Authorities.MANAGER, Authorities.USER, Authorities.ANONYMOUS}) Principal principal) throws Exception { ResponseEntity<ResponseItem<DataTableData<DatasetListingModel>>> getPaged(@RequestBody DatasetTableRequest datasetTableRequest) throws Exception {
DataTableData<DatasetListingModel> dataTable = this.datasetManager.getPaged(datasetTableRequest, principal); 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)); 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") @RequestMapping(method = RequestMethod.POST, value = {"/public/paged"}, consumes = "application/json", produces = "application/json")
public @ResponseBody public @ResponseBody
ResponseEntity<ResponseItem<DataTableData<DatasetListingModel>>> getPublicPaged(@RequestBody DatasetPublicTableRequest datasetTableRequest, ResponseEntity<ResponseItem<DataTableData<DatasetListingModel>>> getPublicPaged(@RequestBody DatasetPublicTableRequest datasetTableRequest) throws Exception {
@ClaimedAuthorities(claims = {Authorities.ADMIN, Authorities.MANAGER, Authorities.USER, Authorities.ANONYMOUS}) Principal principal) throws Exception { this.authorizationService.authorizeForce(Permission.AdminRole, Permission.ManagerRole, Permission.UserRole, Permission.AnonymousRole);
DataTableData<DatasetListingModel> dataTable = this.datasetManager.getPaged(datasetTableRequest, principal);
DataTableData<DatasetListingModel> dataTable = this.datasetManager.getPaged(datasetTableRequest);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DataTableData<DatasetListingModel>>().status(ApiMessageCode.NO_MESSAGE).payload(dataTable)); return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DataTableData<DatasetListingModel>>().status(ApiMessageCode.NO_MESSAGE).payload(dataTable));
} }
@RequestMapping(method = RequestMethod.GET, value = {"/overview/{id}"}) @RequestMapping(method = RequestMethod.GET, value = {"/overview/{id}"})
public @ResponseBody 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 { 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)); return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DatasetOverviewModel>().status(ApiMessageCode.NO_MESSAGE).payload(dataset));
} catch (Exception e) { } catch (Exception e) {
if (e instanceof UnauthorisedException) { if (e instanceof UnauthorisedException) {
@ -118,9 +127,11 @@ public class Datasets extends BaseController {
@RequestMapping(method = RequestMethod.GET, value = {"/publicOverview/{id}"}) @RequestMapping(method = RequestMethod.GET, value = {"/publicOverview/{id}"})
public @ResponseBody public @ResponseBody
ResponseEntity<ResponseItem<DatasetOverviewModel>> getOverviewSinglePublic(@PathVariable String id, @ClaimedAuthorities(claims = {Authorities.ADMIN, Authorities.MANAGER, Authorities.USER, Authorities.ANONYMOUS}) Principal principal) throws Exception { ResponseEntity<ResponseItem<DatasetOverviewModel>> getOverviewSinglePublic(@PathVariable String id) throws Exception {
this.authorizationService.authorizeForce(Permission.AdminRole, Permission.ManagerRole, Permission.UserRole, Permission.AnonymousRole);
// try { // try {
DatasetOverviewModel dataset = this.datasetManager.getOverviewSingle(id, principal, true); DatasetOverviewModel dataset = this.datasetManager.getOverviewSingle(id, true);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DatasetOverviewModel>().status(ApiMessageCode.NO_MESSAGE).payload(dataset)); return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DatasetOverviewModel>().status(ApiMessageCode.NO_MESSAGE).payload(dataset));
// } catch (Exception ex) { // } catch (Exception ex) {
// return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem<DataManagementPlanOverviewModel>().status(ApiMessageCode.NO_MESSAGE).message(ex.getMessage())); // 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 @Transactional
@RequestMapping(method = RequestMethod.GET, value = {"{id}"}, produces = "application/json") @RequestMapping(method = RequestMethod.GET, value = {"{id}"}, produces = "application/json")
public @ResponseBody 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 { try {
VisibilityRuleService visibilityRuleService = new VisibilityRuleServiceImpl(); VisibilityRuleService visibilityRuleService = new VisibilityRuleServiceImpl();
if (contentType.equals("application/xml")) { 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")) { } 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()); InputStream resource = new FileInputStream(file.getFile());
HttpHeaders responseHeaders = new HttpHeaders(); HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentLength(file.getFile().length()); responseHeaders.setContentLength(file.getFile().length());
@ -153,7 +166,7 @@ public class Datasets extends BaseController {
responseHeaders, responseHeaders,
HttpStatus.OK); HttpStatus.OK);
} else { } 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)); return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DatasetWizardModel>().status(ApiMessageCode.NO_MESSAGE).payload(dataset));
} }
} catch (Exception e) { } catch (Exception e) {
@ -170,21 +183,27 @@ public class Datasets extends BaseController {
@RequestMapping(method = RequestMethod.POST, value = {"/datasetProfilesUsedByDatasets/paged"}, produces = "application/json") @RequestMapping(method = RequestMethod.POST, value = {"/datasetProfilesUsedByDatasets/paged"}, produces = "application/json")
public @ResponseBody public @ResponseBody
ResponseEntity<ResponseItem<DataTableData<DatasetProfileListingModel>>> getUsingDatasetProfilesPaged(@RequestBody DatasetProfileTableRequestItem datasetProfileTableRequestItem, Principal principal) { ResponseEntity<ResponseItem<DataTableData<DatasetProfileListingModel>>> getUsingDatasetProfilesPaged(@RequestBody DatasetProfileTableRequestItem datasetProfileTableRequestItem) throws InvalidApplicationException {
DataTableData<DatasetProfileListingModel> datasetProfileTableData = this.datasetManager.getDatasetProfilesUsedByDatasets(datasetProfileTableRequestItem, principal); 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)); 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") @RequestMapping(method = RequestMethod.POST, value = {"/userDmps"}, produces = "application/json")
public @ResponseBody public @ResponseBody
ResponseEntity<ResponseItem<List<DataManagentPlanListingModel>>> getUserDmps(@RequestBody DatasetWizardAutocompleteRequest datasetWizardAutocompleteRequest, Principal principal) throws IllegalAccessException, InstantiationException { ResponseEntity<ResponseItem<List<DataManagentPlanListingModel>>> getUserDmps(@RequestBody DatasetWizardAutocompleteRequest datasetWizardAutocompleteRequest) throws IllegalAccessException, InstantiationException, InvalidApplicationException {
List<DataManagentPlanListingModel> dataManagementPlans = DatasetWizardManager.getUserDmps(this.getApiContext().getOperationsContext().getDatabaseRepository().getDmpDao(), datasetWizardAutocompleteRequest, principal); 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)); 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") @RequestMapping(method = RequestMethod.POST, value = {"/getAvailableProfiles"}, produces = "application/json")
public @ResponseBody 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); 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)); 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") @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)); DescriptionTemplate profile = this.getApiContext().getOperationsContext().getDatabaseRepository().getDatasetProfileDao().find(UUID.fromString(id));
eu.eudat.models.data.user.composite.DatasetProfile datasetprofile = userManager.generateDatasetProfileModel(profile); eu.eudat.models.data.user.composite.DatasetProfile datasetprofile = userManager.generateDatasetProfileModel(profile);
PagedDatasetProfile pagedDatasetProfile = new PagedDatasetProfile(); PagedDatasetProfile pagedDatasetProfile = new PagedDatasetProfile();
@ -212,7 +231,9 @@ public class Datasets extends BaseController {
@RequestMapping(method = RequestMethod.GET, value = {"profile/{id}"}, produces = "application/json") @RequestMapping(method = RequestMethod.GET, value = {"profile/{id}"}, produces = "application/json")
public @ResponseBody 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); DatasetWizardModel dataset = this.datasetManager.datasetUpdateProfile(id);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DatasetWizardModel>().status(ApiMessageCode.NO_MESSAGE).payload(dataset)); 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}"}) @RequestMapping(method = RequestMethod.GET, value = {"/getPDF/{id}"})
public @ResponseBody 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 { ResponseEntity<byte[]> getPDFDocument(@PathVariable String id) throws IOException, InvalidApplicationException {
FileEnvelope file = datasetManager.getWordDocumentFile(this.configLoader, id, new VisibilityRuleServiceImpl(), principal); 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(",", "_"); String fileName = file.getFilename().replace(" ", "_").replace(",", "_");
if (fileName.endsWith(".docx")){ if (fileName.endsWith(".docx")){
fileName = fileName.substring(0, fileName.length() - 5); fileName = fileName.substring(0, fileName.length() - 5);
@ -255,8 +278,10 @@ public class Datasets extends BaseController {
@Transactional @Transactional
@RequestMapping(method = RequestMethod.POST, consumes = "application/json", produces = "application/json") @RequestMapping(method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
public @ResponseBody public @ResponseBody
ResponseEntity<ResponseItem<DatasetWizardModel>> createOrUpdate(@RequestBody DatasetWizardModel profile, Principal principal) throws Exception { ResponseEntity<ResponseItem<DatasetWizardModel>> createOrUpdate(@RequestBody DatasetWizardModel profile) throws Exception {
DatasetWizardModel dataset = new DatasetWizardModel().fromDataModel(this.datasetManager.createOrUpdate(profile, principal)); this.authorizationService.authorizeForce(Permission.AuthenticatedRole);
DatasetWizardModel dataset = new DatasetWizardModel().fromDataModel(this.datasetManager.createOrUpdate(profile));
dataset.setTags(profile.getTags()); dataset.setTags(profile.getTags());
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DatasetWizardModel>().status(ApiMessageCode.SUCCESS_MESSAGE).message("Created").payload(dataset)); 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 @Transactional
@RequestMapping(method = RequestMethod.GET, value = {"/makepublic/{id}"}, produces = "application/json") @RequestMapping(method = RequestMethod.GET, value = {"/makepublic/{id}"}, produces = "application/json")
public @ResponseBody 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); 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))); 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 @Transactional
@RequestMapping(method = RequestMethod.DELETE, value = {"/delete/{id}"}, produces = "application/json") @RequestMapping(method = RequestMethod.DELETE, value = {"/delete/{id}"}, produces = "application/json")
public @ResponseBody 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); new DatasetWizardManager().delete(this.getApiContext(), id);
this.fileManager.markAllFilesOfEntityIdAsDeleted(id); this.fileManager.markAllFilesOfEntityIdAsDeleted(id);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<Dataset>().status(ApiMessageCode.SUCCESS_MESSAGE).message("Deleted")); 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 @Transactional
@RequestMapping(method = RequestMethod.GET, value = {"/{id}/unlock"}, produces = "application/json") @RequestMapping(method = RequestMethod.GET, value = {"/{id}/unlock"}, produces = "application/json")
public @ResponseBody 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 { try {
new DatasetWizardManager().unlock(this.getApiContext(), id); new DatasetWizardManager().unlock(this.getApiContext(), id);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<Dataset>().status(ApiMessageCode.SUCCESS_MESSAGE).message("Unlocked")); 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") @RequestMapping(method = RequestMethod.GET, value = {"/{id}/validate"}, produces = "application/json")
public @ResponseBody 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); Dataset dataset = datasetManager.getEntitySingle(id);
String failedField = datasetManager.checkDatasetValidation(dataset); String failedField = datasetManager.checkDatasetValidation(dataset);
if (failedField == null) { if (failedField == null) {
@ -307,9 +338,11 @@ public class Datasets extends BaseController {
* */ * */
@RequestMapping(method = RequestMethod.POST, value = {"/upload"}) @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 { try {
Dataset dataset = this.datasetManager.createDatasetFromXml(file, dmpId, datasetProfileId, principal); Dataset dataset = this.datasetManager.createDatasetFromXml(file, dmpId, datasetProfileId);
if (dataset != null){ if (dataset != null){
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE)); return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE));
} }
@ -329,16 +362,20 @@ public class Datasets extends BaseController {
@Transactional @Transactional
@RequestMapping(method = RequestMethod.POST, value = {"/index"}) @RequestMapping(method = RequestMethod.POST, value = {"/index"})
public @ResponseBody public @ResponseBody
ResponseEntity<ResponseItem<Dataset>> generateIndex(Principal principal) throws Exception { ResponseEntity<ResponseItem<Dataset>> generateIndex() throws Exception {
this.datasetManager.generateIndex(principal); 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)); return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<Dataset>().status(ApiMessageCode.SUCCESS_MESSAGE).message("Generated").payload(null));
} }
@Transactional @Transactional
@RequestMapping(method = RequestMethod.DELETE, value = {"/index"}) @RequestMapping(method = RequestMethod.DELETE, value = {"/index"})
public @ResponseBody public @ResponseBody
ResponseEntity<ResponseItem<Dataset>> clearIndex(Principal principal) throws Exception { ResponseEntity<ResponseItem<Dataset>> clearIndex() throws Exception {
this.datasetManager.clearIndex(principal); 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)); 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; package eu.eudat.controllers;
import eu.eudat.authorization.Permission;
import eu.eudat.logic.managers.DepositManager; import eu.eudat.logic.managers.DepositManager;
import eu.eudat.logic.security.claims.ClaimedAuthorities;
import eu.eudat.logic.services.ApiContext; import eu.eudat.logic.services.ApiContext;
import eu.eudat.models.data.doi.DepositCode; import eu.eudat.models.data.doi.DepositCode;
import eu.eudat.models.data.doi.DepositRequest; import eu.eudat.models.data.doi.DepositRequest;
import eu.eudat.models.data.doi.Doi; import eu.eudat.models.data.doi.Doi;
import eu.eudat.models.data.doi.RepositoryConfig; import eu.eudat.models.data.doi.RepositoryConfig;
import eu.eudat.models.data.helpers.responses.ResponseItem; import eu.eudat.models.data.helpers.responses.ResponseItem;
import eu.eudat.models.data.security.Principal;
import eu.eudat.types.ApiMessageCode; 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.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@ -26,33 +25,40 @@ import java.util.List;
public class DepositController extends BaseController { public class DepositController extends BaseController {
private static final Logger logger = LoggerFactory.getLogger(DepositController.class); private static final Logger logger = LoggerFactory.getLogger(DepositController.class);
private DepositManager depositManager; private final DepositManager depositManager;
private final AuthorizationService authorizationService;
@Autowired @Autowired
public DepositController(ApiContext apiContext, DepositManager depositManager){ public DepositController(ApiContext apiContext, DepositManager depositManager, AuthorizationService authorizationService){
super(apiContext); super(apiContext);
this.depositManager = depositManager; this.depositManager = depositManager;
this.authorizationService = authorizationService;
} }
@RequestMapping(method = RequestMethod.GET, value = {"/repos"}) @RequestMapping(method = RequestMethod.GET, value = {"/repos"})
public @ResponseBody 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(); List<RepositoryConfig> ids = this.depositManager.getAvailableRepos();
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List<RepositoryConfig>>().status(ApiMessageCode.NO_MESSAGE).payload(ids)); return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List<RepositoryConfig>>().status(ApiMessageCode.NO_MESSAGE).payload(ids));
} }
@RequestMapping(method = RequestMethod.POST, value = {"/getAccessToken"}) @RequestMapping(method = RequestMethod.POST, value = {"/getAccessToken"})
public @ResponseBody 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()); String accessToken = this.depositManager.authenticate(depositCode.getRepositoryId(), depositCode.getCode());
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<String>().status(ApiMessageCode.NO_MESSAGE).payload(accessToken)); return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<String>().status(ApiMessageCode.NO_MESSAGE).payload(accessToken));
} }
@RequestMapping(method = RequestMethod.POST, value = {"/createDoi"}) @RequestMapping(method = RequestMethod.POST, value = {"/createDoi"})
public @ResponseBody 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 { try {
Doi doi = this.depositManager.deposit(depositRequest, principal); Doi doi = this.depositManager.deposit(depositRequest);
if(doi != null){ 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)); 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}"}) @RequestMapping(method = RequestMethod.GET, value = {"/logo/{repositoryId}"})
public @ResponseBody 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 { try {
String encodedLogo = this.depositManager.getRepositoryLogo(repositoryId); String encodedLogo = this.depositManager.getRepositoryLogo(repositoryId);
if(encodedLogo != null){ if(encodedLogo != null){

View File

@ -1,11 +1,12 @@
package eu.eudat.controllers; package eu.eudat.controllers;
import eu.eudat.authorization.Permission;
import eu.eudat.exceptions.emailconfirmation.HasConfirmedEmailException; import eu.eudat.exceptions.emailconfirmation.HasConfirmedEmailException;
import eu.eudat.exceptions.emailconfirmation.TokenExpiredException; import eu.eudat.exceptions.emailconfirmation.TokenExpiredException;
import eu.eudat.logic.managers.EmailConfirmationManager; import eu.eudat.logic.managers.EmailConfirmationManager;
import eu.eudat.models.data.helpers.responses.ResponseItem; import eu.eudat.models.data.helpers.responses.ResponseItem;
import eu.eudat.models.data.security.Principal;
import eu.eudat.types.ApiMessageCode; import eu.eudat.types.ApiMessageCode;
import gr.cite.commons.web.authz.service.AuthorizationService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
@ -13,16 +14,20 @@ import org.springframework.web.bind.annotation.*;
import jakarta.transaction.Transactional; import jakarta.transaction.Transactional;
import javax.management.InvalidApplicationException;
@RestController @RestController
@CrossOrigin @CrossOrigin
@RequestMapping(value = "/api/emailConfirmation/") @RequestMapping(value = "/api/emailConfirmation/")
public class EmailConfirmation { public class EmailConfirmation {
private EmailConfirmationManager emailConfirmationManager; private EmailConfirmationManager emailConfirmationManager;
private final AuthorizationService authorizationService;
@Autowired @Autowired
public EmailConfirmation(EmailConfirmationManager emailConfirmationManager) { public EmailConfirmation(EmailConfirmationManager emailConfirmationManager, AuthorizationService authorizationService) {
this.emailConfirmationManager = emailConfirmationManager; this.emailConfirmationManager = emailConfirmationManager;
this.authorizationService = authorizationService;
} }
@Transactional @Transactional
@ -33,7 +38,7 @@ public class EmailConfirmation {
this.emailConfirmationManager.confirmEmail(token); this.emailConfirmationManager.confirmEmail(token);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE)); return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE));
} catch } catch
(HasConfirmedEmailException | TokenExpiredException ex) { (HasConfirmedEmailException | TokenExpiredException | InvalidApplicationException ex) {
if (ex instanceof TokenExpiredException) { if (ex instanceof TokenExpiredException) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem().status(ApiMessageCode.NO_MESSAGE)); return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem().status(ApiMessageCode.NO_MESSAGE));
} else { } else {
@ -45,9 +50,11 @@ public class EmailConfirmation {
@Transactional @Transactional
@RequestMapping(method = RequestMethod.POST, consumes = "application/json", produces = "application/json") @RequestMapping(method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
public @ResponseBody public @ResponseBody
ResponseEntity sendConfirmatioEmail(@RequestBody String email, Principal principal) { ResponseEntity sendConfirmatioEmail(@RequestBody String email) {
this.authorizationService.authorizeForce(Permission.AuthenticatedRole);
try { try {
this.emailConfirmationManager.sendConfirmationEmail(email, principal); this.emailConfirmationManager.sendConfirmationEmail(email);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE)); return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE));
} catch (Exception ex) { } catch (Exception ex) {
if (ex instanceof HasConfirmedEmailException) { if (ex instanceof HasConfirmedEmailException) {

View File

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

View File

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

View File

@ -1,5 +1,6 @@
package eu.eudat.controllers; package eu.eudat.controllers;
import eu.eudat.authorization.Permission;
import eu.eudat.data.old.ExternalDataset; import eu.eudat.data.old.ExternalDataset;
import eu.eudat.data.query.items.table.externaldataset.ExternalDatasetTableRequest; import eu.eudat.data.query.items.table.externaldataset.ExternalDatasetTableRequest;
import eu.eudat.logic.managers.ExternalDatasetManager; 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.externaldataset.ExternalDatasetListingModel;
import eu.eudat.models.data.helpers.common.DataTableData; import eu.eudat.models.data.helpers.common.DataTableData;
import eu.eudat.models.data.helpers.responses.ResponseItem; import eu.eudat.models.data.helpers.responses.ResponseItem;
import eu.eudat.models.data.security.Principal;
import eu.eudat.types.ApiMessageCode; import eu.eudat.types.ApiMessageCode;
import gr.cite.commons.web.authz.service.AuthorizationService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import javax.management.InvalidApplicationException;
import java.util.List; import java.util.List;
import java.util.UUID; import java.util.UUID;
@ -27,16 +29,20 @@ import java.util.UUID;
public class ExternalDatasets extends BaseController { public class ExternalDatasets extends BaseController {
private ExternalDatasetManager externalDatasetManager; private ExternalDatasetManager externalDatasetManager;
private final AuthorizationService authorizationService;
@Autowired @Autowired
public ExternalDatasets(ApiContext apiContext, ExternalDatasetManager externalDatasetManager) { public ExternalDatasets(ApiContext apiContext, ExternalDatasetManager externalDatasetManager, AuthorizationService authorizationService) {
super(apiContext); super(apiContext);
this.externalDatasetManager = externalDatasetManager; this.externalDatasetManager = externalDatasetManager;
this.authorizationService = authorizationService;
} }
@RequestMapping(method = RequestMethod.POST, value = {"/externaldatasets/getPaged"}, consumes = "application/json", produces = "application/json") @RequestMapping(method = RequestMethod.POST, value = {"/externaldatasets/getPaged"}, consumes = "application/json", produces = "application/json")
public @ResponseBody 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); DataTableData<ExternalDatasetListingModel> dataTable = externalDatasetManager.getPaged(datasetTableRequest);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DataTableData<ExternalDatasetListingModel>>().status(ApiMessageCode.NO_MESSAGE).payload(dataTable)); 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") @RequestMapping(method = RequestMethod.GET, value = {"/external/datasets"}, produces = "application/json")
public @ResponseBody public @ResponseBody
ResponseEntity<ResponseItem<List<ExternalDatasetListingModel>>> getWithExternal( ResponseEntity<ResponseItem<List<ExternalDatasetListingModel>>> getWithExternal(
@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 NoURLFound, InstantiationException, HugeResultSet, IllegalAccessException { ) throws NoURLFound, InstantiationException, HugeResultSet, IllegalAccessException, InvalidApplicationException {
List<ExternalDatasetListingModel> dataTable = externalDatasetManager.getWithExternal(query, type, principal); 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)); 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") @RequestMapping(method = RequestMethod.POST, value = {"/externaldatasets/getSingle/{id}"}, consumes = "application/json", produces = "application/json")
public @ResponseBody 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); ExternalDatasetListingModel externalDatasetModel = externalDatasetManager.getSingle(id);
return new ResponseItem<ExternalDatasetListingModel>().payload(externalDatasetModel).status(ApiMessageCode.NO_MESSAGE); return new ResponseItem<ExternalDatasetListingModel>().payload(externalDatasetModel).status(ApiMessageCode.NO_MESSAGE);
} }
@ -60,8 +70,10 @@ public class ExternalDatasets extends BaseController {
@Transactional @Transactional
@RequestMapping(method = RequestMethod.POST, value = {"/externaldatasets"}, consumes = "application/json", produces = "application/json") @RequestMapping(method = RequestMethod.POST, value = {"/externaldatasets"}, consumes = "application/json", produces = "application/json")
public @ResponseBody public @ResponseBody
ResponseEntity<ResponseItem<ExternalDatasetListingModel>> create(@RequestBody eu.eudat.models.data.externaldataset.ExternalDatasetModel externalDatasetModel, Principal principal) throws Exception { ResponseEntity<ResponseItem<ExternalDatasetListingModel>> create(@RequestBody eu.eudat.models.data.externaldataset.ExternalDatasetModel externalDatasetModel) throws Exception {
ExternalDataset externalDataset = this.externalDatasetManager.create(externalDatasetModel, principal); this.authorizationService.authorizeForce(Permission.AuthenticatedRole);
ExternalDataset externalDataset = this.externalDatasetManager.create(externalDatasetModel);
ExternalDatasetListingModel externalDatasetListingModel = new ExternalDatasetListingModel().fromDataModel(externalDataset); ExternalDatasetListingModel externalDatasetListingModel = new ExternalDatasetListingModel().fromDataModel(externalDataset);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<ExternalDatasetListingModel>().payload(externalDatasetListingModel).status(ApiMessageCode.SUCCESS_MESSAGE)); 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.annotation.JsonInclude;
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper; 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.Dataset;
import eu.eudat.data.old.FileUpload; import eu.eudat.data.old.FileUpload;
import eu.eudat.exceptions.security.UnauthorisedException; import eu.eudat.exceptions.security.UnauthorisedException;
import eu.eudat.logic.managers.DatasetProfileManager; import eu.eudat.logic.managers.DatasetProfileManager;
import eu.eudat.logic.security.claims.ClaimedAuthorities;
import eu.eudat.logic.services.ApiContext; import eu.eudat.logic.services.ApiContext;
import eu.eudat.logic.services.operations.DatabaseRepository; import eu.eudat.logic.services.operations.DatabaseRepository;
import eu.eudat.logic.utilities.documents.helpers.FileEnvelope; 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.HintedModelFactory;
import eu.eudat.models.data.datasetwizard.DatasetWizardModel; import eu.eudat.models.data.datasetwizard.DatasetWizardModel;
import eu.eudat.models.data.helpers.responses.ResponseItem; import eu.eudat.models.data.helpers.responses.ResponseItem;
import eu.eudat.models.data.security.Principal;
import eu.eudat.types.ApiMessageCode; 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.apache.poi.util.IOUtils;
import org.json.JSONArray; import org.json.JSONArray;
import org.json.JSONObject; import org.json.JSONObject;
@ -31,6 +31,8 @@ import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import jakarta.transaction.Transactional; import jakarta.transaction.Transactional;
import javax.management.InvalidApplicationException;
import java.io.*; import java.io.*;
import java.nio.file.Files; import java.nio.file.Files;
import java.util.*; import java.util.*;
@ -45,19 +47,24 @@ public class FileController {
private DatasetProfileManager datasetProfileManager; private DatasetProfileManager datasetProfileManager;
private final Environment environment; private final Environment environment;
private DatabaseRepository databaseRepository; private DatabaseRepository databaseRepository;
private final AuthorizationService authorizationService;
private final UserScope userScope;
@Autowired @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.datasetProfileManager = datasetProfileManager;
this.environment = environment; this.environment = environment;
this.databaseRepository = apiContext.getOperationsContext().getDatabaseRepository(); this.databaseRepository = apiContext.getOperationsContext().getDatabaseRepository();
this.authorizationService = authorizationService;
this.userScope = userScope;
} }
@RequestMapping(method = RequestMethod.POST, value = {"/upload"}) @RequestMapping(method = RequestMethod.POST, value = {"/upload"})
public ResponseEntity<ResponseItem<String>> upload( public ResponseEntity<ResponseItem<String>> upload(
@RequestParam("file") MultipartFile file, @RequestParam("datasetProfileId") String datasetProfileId, @RequestParam("fieldId") String fieldId, @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, InvalidApplicationException {
throws IllegalAccessException, IOException { this.authorizationService.authorizeForce(Permission.AdminRole, Permission.ManagerRole, Permission.UserRole);
String uuid = UUID.randomUUID().toString(); String uuid = UUID.randomUUID().toString();
eu.eudat.models.data.admin.composite.DatasetProfile datasetprofile = this.datasetProfileManager.getDatasetProfile(datasetProfileId); eu.eudat.models.data.admin.composite.DatasetProfile datasetprofile = this.datasetProfileManager.getDatasetProfile(datasetProfileId);
@ -135,9 +142,10 @@ public class FileController {
@Transactional @Transactional
@RequestMapping(method = RequestMethod.GET, value = {"{id}"}, produces = "application/json") @RequestMapping(method = RequestMethod.GET, value = {"{id}"}, produces = "application/json")
public @ResponseBody public @ResponseBody
ResponseEntity download(@PathVariable String id ResponseEntity download(@PathVariable String id) throws IOException, InvalidApplicationException {
,@ClaimedAuthorities(claims = {Authorities.ADMIN, Authorities.MANAGER, Authorities.USER, Authorities.ANONYMOUS}) Principal principal
) throws IOException { this.authorizationService.authorizeForce(Permission.AdminRole, Permission.ManagerRole, Permission.UserRole, Permission.AnonymousRole);
FileUpload fileUpload = databaseRepository.getFileUploadDao().find(UUID.fromString(id)); FileUpload fileUpload = databaseRepository.getFileUploadDao().find(UUID.fromString(id));
if(fileUpload == null) { if(fileUpload == null) {
throw new NoSuchElementException("File with id "+id+" not found"); 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); 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() 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) .collect(Collectors.toList()).size() == 0)
throw new UnauthorisedException(); throw new UnauthorisedException();
} }

View File

@ -1,5 +1,6 @@
package eu.eudat.controllers; package eu.eudat.controllers;
import eu.eudat.authorization.Permission;
import eu.eudat.data.query.items.item.funder.FunderCriteriaRequest; import eu.eudat.data.query.items.item.funder.FunderCriteriaRequest;
import eu.eudat.logic.managers.FunderManager; import eu.eudat.logic.managers.FunderManager;
import eu.eudat.logic.proxy.config.exceptions.HugeResultSet; 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.logic.services.ApiContext;
import eu.eudat.models.data.funder.Funder; import eu.eudat.models.data.funder.Funder;
import eu.eudat.models.data.helpers.responses.ResponseItem; import eu.eudat.models.data.helpers.responses.ResponseItem;
import eu.eudat.models.data.security.Principal;
import eu.eudat.types.ApiMessageCode; import eu.eudat.types.ApiMessageCode;
import gr.cite.commons.web.authz.service.AuthorizationService;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import javax.management.InvalidApplicationException;
import java.util.List; import java.util.List;
@RestController @RestController
@ -20,16 +22,20 @@ import java.util.List;
@RequestMapping(value = {"/api/funders/"}) @RequestMapping(value = {"/api/funders/"})
public class Funders extends BaseController { public class Funders extends BaseController {
private FunderManager funderManager; private FunderManager funderManager;
private final AuthorizationService authorizationService;
public Funders(ApiContext apiContext, FunderManager funderManager) { public Funders(ApiContext apiContext, FunderManager funderManager, AuthorizationService authorizationService) {
super(apiContext); super(apiContext);
this.funderManager = funderManager; this.funderManager = funderManager;
this.authorizationService = authorizationService;
} }
@RequestMapping(method = RequestMethod.POST, value = {"/external"}, consumes = "application/json", produces = "application/json") @RequestMapping(method = RequestMethod.POST, value = {"/external"}, consumes = "application/json", produces = "application/json")
public @ResponseBody public @ResponseBody
ResponseEntity<ResponseItem<List<Funder>>> getWithExternal(@RequestBody FunderCriteriaRequest funderCriteria, Principal principal) throws NoURLFound, InstantiationException, HugeResultSet, IllegalAccessException { ResponseEntity<ResponseItem<List<Funder>>> getWithExternal(@RequestBody FunderCriteriaRequest funderCriteria) throws NoURLFound, InstantiationException, HugeResultSet, IllegalAccessException, InvalidApplicationException {
List<Funder> dataTable = this.funderManager.getCriteriaWithExternal(funderCriteria, principal); 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)); 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; package eu.eudat.controllers;
import eu.eudat.authorization.Permission;
import eu.eudat.data.query.items.item.grant.GrantCriteriaRequest; import eu.eudat.data.query.items.item.grant.GrantCriteriaRequest;
import eu.eudat.data.query.items.table.grant.GrantTableRequest; import eu.eudat.data.query.items.table.grant.GrantTableRequest;
import eu.eudat.logic.managers.GrantManager; import eu.eudat.logic.managers.GrantManager;
import eu.eudat.logic.proxy.config.exceptions.HugeResultSet; import eu.eudat.logic.proxy.config.exceptions.HugeResultSet;
import eu.eudat.logic.proxy.config.exceptions.NoURLFound; import eu.eudat.logic.proxy.config.exceptions.NoURLFound;
import eu.eudat.logic.security.claims.ClaimedAuthorities;
import eu.eudat.logic.services.ApiContext; import eu.eudat.logic.services.ApiContext;
import eu.eudat.models.data.helpers.common.DataTableData; import eu.eudat.models.data.helpers.common.DataTableData;
import eu.eudat.models.data.helpers.responses.ResponseItem; import eu.eudat.models.data.helpers.responses.ResponseItem;
import eu.eudat.models.data.grant.GrantListingModel; import eu.eudat.models.data.grant.GrantListingModel;
import eu.eudat.models.data.security.Principal;
import eu.eudat.types.ApiMessageCode; import eu.eudat.types.ApiMessageCode;
import gr.cite.commons.web.authz.service.AuthorizationService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import jakarta.validation.Valid; import jakarta.validation.Valid;
import javax.management.InvalidApplicationException;
import java.util.List; import java.util.List;
import static eu.eudat.types.Authorities.ANONYMOUS;
@RestController @RestController
@ -29,17 +28,21 @@ import static eu.eudat.types.Authorities.ANONYMOUS;
@RequestMapping(value = {"/api/grants/"}) @RequestMapping(value = {"/api/grants/"})
public class Grants extends BaseController { public class Grants extends BaseController {
private GrantManager grantManager; private GrantManager grantManager;
private final AuthorizationService authorizationService;
@Autowired @Autowired
public Grants(ApiContext apiContext, GrantManager grantManager) { public Grants(ApiContext apiContext, GrantManager grantManager, AuthorizationService authorizationService) {
super(apiContext); super(apiContext);
this.grantManager = grantManager; this.grantManager = grantManager;
this.authorizationService = authorizationService;
} }
@RequestMapping(method = RequestMethod.POST, value = {"/paged"}, consumes = "application/json", produces = "application/json") @RequestMapping(method = RequestMethod.POST, value = {"/paged"}, consumes = "application/json", produces = "application/json")
public @ResponseBody public @ResponseBody
ResponseEntity<ResponseItem<DataTableData<GrantListingModel>>> getPaged(@Valid @RequestBody GrantTableRequest grantTableRequest, @RequestParam String fieldsGroup, Principal principal) throws Exception { ResponseEntity<ResponseItem<DataTableData<GrantListingModel>>> getPaged(@Valid @RequestBody GrantTableRequest grantTableRequest, @RequestParam String fieldsGroup) throws Exception {
DataTableData<eu.eudat.models.data.grant.GrantListingModel> dataTable = this.grantManager.getPaged(grantTableRequest, principal, fieldsGroup); 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)); 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") @RequestMapping(method = RequestMethod.GET, value = {"{id}"}, produces = "application/json")
public @ResponseBody 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); 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)); 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 /*@Transactional
@RequestMapping(method = RequestMethod.POST, consumes = "application/json", produces = "application/json") @RequestMapping(method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
public @ResponseBody 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); this.grantManager.createOrUpdate(grant, principal);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<eu.eudat.data.old.Grant>().status(ApiMessageCode.SUCCESS_MESSAGE).message("Created")); 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 /*@Transactional
@RequestMapping(method = RequestMethod.DELETE, value = {"{id}"}, consumes = "application/json", produces = "application/json") @RequestMapping(method = RequestMethod.DELETE, value = {"{id}"}, consumes = "application/json", produces = "application/json")
public @ResponseBody 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); this.grantManager.inactivate(id);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<eu.eudat.data.old.Grant>().status(ApiMessageCode.SUCCESS_MESSAGE)); 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") @RequestMapping(method = RequestMethod.POST, value = {"/external"}, consumes = "application/json", produces = "application/json")
public @ResponseBody public @ResponseBody
ResponseEntity<ResponseItem<List<eu.eudat.models.data.grant.Grant>>> getWithExternal(@RequestBody GrantCriteriaRequest grantCriteria, Principal principal) throws NoURLFound, InstantiationException, HugeResultSet, IllegalAccessException { ResponseEntity<ResponseItem<List<eu.eudat.models.data.grant.Grant>>> getWithExternal(@RequestBody GrantCriteriaRequest grantCriteria) throws NoURLFound, InstantiationException, HugeResultSet, IllegalAccessException, InvalidApplicationException {
List<eu.eudat.models.data.grant.Grant> dataTable = this.grantManager.getCriteriaWithExternal(grantCriteria, principal); 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)); 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") @RequestMapping(method = RequestMethod.POST, value = {"get"}, consumes = "application/json", produces = "application/json")
public @ResponseBody 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); 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)); 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; package eu.eudat.controllers;
import eu.eudat.authorization.Permission;
import eu.eudat.logic.managers.DataRepositoryManager; import eu.eudat.logic.managers.DataRepositoryManager;
import eu.eudat.logic.proxy.config.exceptions.HugeResultSet; import eu.eudat.logic.proxy.config.exceptions.HugeResultSet;
import eu.eudat.logic.proxy.config.exceptions.NoURLFound; import eu.eudat.logic.proxy.config.exceptions.NoURLFound;
import eu.eudat.logic.services.ApiContext; import eu.eudat.logic.services.ApiContext;
import eu.eudat.models.data.datarepository.DataRepositoryModel; import eu.eudat.models.data.datarepository.DataRepositoryModel;
import eu.eudat.models.data.helpers.responses.ResponseItem; import eu.eudat.models.data.helpers.responses.ResponseItem;
import eu.eudat.models.data.security.Principal;
import eu.eudat.types.ApiMessageCode; import eu.eudat.types.ApiMessageCode;
import gr.cite.commons.web.authz.service.AuthorizationService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import javax.management.InvalidApplicationException;
import java.util.List; import java.util.List;
@ -22,19 +24,23 @@ import java.util.List;
public class JournalsController extends BaseController { public class JournalsController extends BaseController {
private DataRepositoryManager dataRepositoryManager; private DataRepositoryManager dataRepositoryManager;
private final AuthorizationService authorizationService;
@Autowired @Autowired
public JournalsController(ApiContext apiContext, DataRepositoryManager dataRepositoryManager) { public JournalsController(ApiContext apiContext, DataRepositoryManager dataRepositoryManager, AuthorizationService authorizationService) {
super(apiContext); super(apiContext);
this.dataRepositoryManager = dataRepositoryManager; this.dataRepositoryManager = dataRepositoryManager;
this.authorizationService = authorizationService;
} }
@RequestMapping(method = RequestMethod.GET, produces = "application/json") @RequestMapping(method = RequestMethod.GET, produces = "application/json")
public @ResponseBody public @ResponseBody
ResponseEntity<ResponseItem<List<DataRepositoryModel>>> listExternalDataRepositories( ResponseEntity<ResponseItem<List<DataRepositoryModel>>> listExternalDataRepositories(
@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 { ) throws HugeResultSet, NoURLFound, InvalidApplicationException {
List<DataRepositoryModel> dataRepositoryModels = this.dataRepositoryManager.getJournals(query, type, principal); 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)); 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; package eu.eudat.controllers;
import eu.eudat.authorization.Permission; 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.helpers.responses.ResponseItem;
import eu.eudat.models.data.security.Principal;
import eu.eudat.types.ApiMessageCode; import eu.eudat.types.ApiMessageCode;
import eu.eudat.types.Authorities;
import gr.cite.commons.web.authz.service.AuthorizationService; import gr.cite.commons.web.authz.service.AuthorizationService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment; import org.springframework.core.env.Environment;

View File

@ -1,13 +1,14 @@
package eu.eudat.controllers; package eu.eudat.controllers;
import eu.eudat.authorization.Permission;
import eu.eudat.logic.managers.LicenseManager; import eu.eudat.logic.managers.LicenseManager;
import eu.eudat.logic.proxy.config.exceptions.HugeResultSet; import eu.eudat.logic.proxy.config.exceptions.HugeResultSet;
import eu.eudat.logic.proxy.config.exceptions.NoURLFound; import eu.eudat.logic.proxy.config.exceptions.NoURLFound;
import eu.eudat.logic.services.ApiContext; import eu.eudat.logic.services.ApiContext;
import eu.eudat.models.data.helpers.responses.ResponseItem; import eu.eudat.models.data.helpers.responses.ResponseItem;
import eu.eudat.models.data.license.LicenseModel; import eu.eudat.models.data.license.LicenseModel;
import eu.eudat.models.data.security.Principal;
import eu.eudat.types.ApiMessageCode; import eu.eudat.types.ApiMessageCode;
import gr.cite.commons.web.authz.service.AuthorizationService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
@ -22,18 +23,22 @@ import java.util.List;
public class Licenses extends BaseController { public class Licenses extends BaseController {
private LicenseManager licenseManager; private LicenseManager licenseManager;
private final AuthorizationService authorizationService;
@Autowired @Autowired
public Licenses(ApiContext apiContext, LicenseManager licenseManager) { public Licenses(ApiContext apiContext, LicenseManager licenseManager, AuthorizationService authorizationService) {
super(apiContext); super(apiContext);
this.licenseManager = licenseManager; this.licenseManager = licenseManager;
this.authorizationService = authorizationService;
} }
@RequestMapping(method = RequestMethod.GET, produces = "application/json") @RequestMapping(method = RequestMethod.GET, produces = "application/json")
public @ResponseBody public @ResponseBody
ResponseEntity<ResponseItem<List<LicenseModel>>> listExternalLicenses( 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 { ) throws HugeResultSet, NoURLFound {
this.authorizationService.authorizeForce(Permission.AuthenticatedRole);
List<LicenseModel> licenseModels = this.licenseManager.getLicenses(query, type); List<LicenseModel> licenseModels = this.licenseManager.getLicenses(query, type);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List<LicenseModel>>().status(ApiMessageCode.NO_MESSAGE).payload(licenseModels)); 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; package eu.eudat.controllers;
import eu.eudat.authorization.Permission;
import eu.eudat.logic.managers.LockManager; import eu.eudat.logic.managers.LockManager;
import eu.eudat.models.data.helpers.responses.ResponseItem; import eu.eudat.models.data.helpers.responses.ResponseItem;
import eu.eudat.models.data.lock.Lock; import eu.eudat.models.data.lock.Lock;
import eu.eudat.models.data.security.Principal;
import eu.eudat.types.ApiMessageCode; import eu.eudat.types.ApiMessageCode;
import gr.cite.commons.web.authz.service.AuthorizationService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
@ -19,36 +20,46 @@ import java.util.UUID;
public class LockController { public class LockController {
private LockManager lockManager; private LockManager lockManager;
private final AuthorizationService authorizationService;
@Autowired @Autowired
public LockController(LockManager lockManager) { public LockController(LockManager lockManager, AuthorizationService authorizationService) {
this.lockManager = lockManager; this.lockManager = lockManager;
this.authorizationService = authorizationService;
} }
@Transactional @Transactional
@RequestMapping(method = RequestMethod.GET, path = "target/status/{id}") @RequestMapping(method = RequestMethod.GET, path = "target/status/{id}")
public @ResponseBody ResponseEntity<ResponseItem<Boolean>> getLocked(@PathVariable String id, Principal principal) throws Exception { public @ResponseBody ResponseEntity<ResponseItem<Boolean>> getLocked(@PathVariable String id) throws Exception {
boolean locked = this.lockManager.isLocked(id, principal); 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)); return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<Boolean>().status(ApiMessageCode.SUCCESS_MESSAGE).message("locked").payload(locked));
} }
@Transactional @Transactional
@RequestMapping(method = RequestMethod.DELETE, path = "target/unlock/{id}") @RequestMapping(method = RequestMethod.DELETE, path = "target/unlock/{id}")
public @ResponseBody ResponseEntity<ResponseItem<String>> unlock(@PathVariable String id, Principal principal) throws Exception { public @ResponseBody ResponseEntity<ResponseItem<String>> unlock(@PathVariable String id) throws Exception {
this.lockManager.unlock(id, principal); 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")); return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<String>().status(ApiMessageCode.SUCCESS_MESSAGE).message("Created").payload("Lock Removed"));
} }
@Transactional @Transactional
@RequestMapping(method = RequestMethod.POST, consumes = "application/json", produces = "application/json") @RequestMapping(method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
public @ResponseBody ResponseEntity<ResponseItem<UUID>> createOrUpdate(@RequestBody Lock lock, Principal principal) throws Exception { public @ResponseBody ResponseEntity<ResponseItem<UUID>> createOrUpdate(@RequestBody Lock lock) throws Exception {
eu.eudat.data.old.Lock result = this.lockManager.createOrUpdate(lock, principal); 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())); 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}") @RequestMapping(method = RequestMethod.GET, path = "target/{id}")
public @ResponseBody ResponseEntity<ResponseItem<Lock>> getSingle(@PathVariable String id, Principal principal) throws Exception { public @ResponseBody ResponseEntity<ResponseItem<Lock>> getSingle(@PathVariable String id) throws Exception {
Lock lock = this.lockManager.getFromTarget(id, principal); 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)); 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; 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.managers.DatasetProfileManager;
import eu.eudat.logic.security.claims.ClaimedAuthorities;
import eu.eudat.logic.services.ApiContext; 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.helpers.responses.ResponseItem;
import eu.eudat.models.data.security.Principal;
import eu.eudat.types.ApiMessageCode; import eu.eudat.types.ApiMessageCode;
import gr.cite.commons.web.authz.service.AuthorizationService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
@ -22,17 +20,20 @@ import static eu.eudat.types.Authorities.ADMIN;
@RequestMapping(value = {"/api/management/"}) @RequestMapping(value = {"/api/management/"})
public class ManagementController extends BaseController { public class ManagementController extends BaseController {
private DatasetProfileManager datasetProfileManager; private final DatasetProfileManager datasetProfileManager;
private final AuthorizationService authorizationService;
@Autowired @Autowired
public ManagementController(ApiContext apiContext, DatasetProfileManager datasetProfileManager){ public ManagementController(ApiContext apiContext, DatasetProfileManager datasetProfileManager, AuthorizationService authorizationService){
super(apiContext); super(apiContext);
this.datasetProfileManager = datasetProfileManager; this.datasetProfileManager = datasetProfileManager;
this.authorizationService = authorizationService;
} }
@Transactional @Transactional
@RequestMapping(method = RequestMethod.POST, value = {"/addSemantics"}) @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 { try {
this.datasetProfileManager.addSemanticsInDatasetProfiles(); this.datasetProfileManager.addSemanticsInDatasetProfiles();
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<Void>().status(ApiMessageCode.SUCCESS_MESSAGE)); return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<Void>().status(ApiMessageCode.SUCCESS_MESSAGE));
@ -43,7 +44,8 @@ public class ManagementController extends BaseController {
@Transactional @Transactional
@RequestMapping(method = RequestMethod.POST, value = {"/addRdaInSemantics"}) @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 { try {
this.datasetProfileManager.addRdaInSemanticsInDatasetProfiles(); this.datasetProfileManager.addRdaInSemanticsInDatasetProfiles();
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<Void>().status(ApiMessageCode.SUCCESS_MESSAGE)); return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<Void>().status(ApiMessageCode.SUCCESS_MESSAGE));

View File

@ -1,5 +1,6 @@
package eu.eudat.controllers; package eu.eudat.controllers;
import eu.eudat.authorization.Permission;
import eu.eudat.data.query.items.table.organisations.OrganisationsTableRequest; import eu.eudat.data.query.items.table.organisations.OrganisationsTableRequest;
import eu.eudat.logic.managers.OrganisationsManager; import eu.eudat.logic.managers.OrganisationsManager;
import eu.eudat.logic.proxy.config.exceptions.HugeResultSet; 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.dmp.Organisation;
import eu.eudat.models.data.helpers.common.DataTableData; import eu.eudat.models.data.helpers.common.DataTableData;
import eu.eudat.models.data.helpers.responses.ResponseItem; import eu.eudat.models.data.helpers.responses.ResponseItem;
import eu.eudat.models.data.security.Principal;
import eu.eudat.types.ApiMessageCode; import eu.eudat.types.ApiMessageCode;
import gr.cite.commons.web.authz.service.AuthorizationService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
@ -25,12 +26,15 @@ import java.util.List;
public class Organisations extends BaseController { public class Organisations extends BaseController {
private OrganisationsManager organisationsManager; private OrganisationsManager organisationsManager;
private final AuthorizationService authorizationService;
private ApiContext apiContext; private ApiContext apiContext;
@Autowired @Autowired
public Organisations(ApiContext apiContext, OrganisationsManager organisationsManager) { public Organisations(ApiContext apiContext, OrganisationsManager organisationsManager, AuthorizationService authorizationService, ApiContext apiContext1) {
super(apiContext); super(apiContext);
this.organisationsManager = organisationsManager; this.organisationsManager = organisationsManager;
this.authorizationService = authorizationService;
this.apiContext = apiContext1;
} }
@RequestMapping(method = RequestMethod.GET, value = {"/external/organisations"}, produces = "application/json") @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") @RequestMapping(method = RequestMethod.POST, value = {"/general/organisations"}, produces = "application/json")
public @ResponseBody public @ResponseBody
ResponseEntity<ResponseItem<List<Organisation>>> listGeneralOrganisations(@RequestBody OrganisationsTableRequest organisationsTableRequest, Principal principal) throws Exception { ResponseEntity<ResponseItem<List<Organisation>>> listGeneralOrganisations(@RequestBody OrganisationsTableRequest organisationsTableRequest) throws Exception {
List<Organisation> organisations = organisationsManager.getWithExternal(organisationsTableRequest, principal); 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)); 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") @RequestMapping(method = RequestMethod.POST, value = {"/internal/organisations"}, produces = "application/json")
public @ResponseBody public @ResponseBody
ResponseEntity<ResponseItem<DataTableData<Organisation>>> getPaged(@Valid @RequestBody OrganisationsTableRequest organisationsTableRequest, Principal principal) throws Exception{ ResponseEntity<ResponseItem<DataTableData<Organisation>>> getPaged(@Valid @RequestBody OrganisationsTableRequest organisationsTableRequest) throws Exception{
DataTableData<Organisation> organisationDataTableData = this.organisationsManager.getPagedOrganisations(organisationsTableRequest, principal); 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)); 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; package eu.eudat.controllers;
import eu.eudat.authorization.Permission;
import eu.eudat.data.query.items.item.project.ProjectCriteriaRequest; import eu.eudat.data.query.items.item.project.ProjectCriteriaRequest;
import eu.eudat.logic.managers.ProjectManager; import eu.eudat.logic.managers.ProjectManager;
import eu.eudat.logic.proxy.config.exceptions.HugeResultSet; 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.logic.services.ApiContext;
import eu.eudat.models.data.helpers.responses.ResponseItem; import eu.eudat.models.data.helpers.responses.ResponseItem;
import eu.eudat.models.data.project.Project; import eu.eudat.models.data.project.Project;
import eu.eudat.models.data.security.Principal;
import eu.eudat.types.ApiMessageCode; import eu.eudat.types.ApiMessageCode;
import gr.cite.commons.web.authz.service.AuthorizationService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import javax.management.InvalidApplicationException;
import java.util.List; import java.util.List;
@RestController @RestController
@ -21,17 +23,21 @@ import java.util.List;
@RequestMapping(value = {"/api/projects/"}) @RequestMapping(value = {"/api/projects/"})
public class Projects extends BaseController { public class Projects extends BaseController {
private ProjectManager projectManager; private ProjectManager projectManager;
private final AuthorizationService authorizationService;
@Autowired @Autowired
public Projects(ApiContext apiContext, ProjectManager projectManager) { public Projects(ApiContext apiContext, ProjectManager projectManager, AuthorizationService authorizationService) {
super(apiContext); super(apiContext);
this.projectManager = projectManager; this.projectManager = projectManager;
this.authorizationService = authorizationService;
} }
@RequestMapping(method = RequestMethod.POST, value = {"/external"}, consumes = "application/json", produces = "application/json") @RequestMapping(method = RequestMethod.POST, value = {"/external"}, consumes = "application/json", produces = "application/json")
public @ResponseBody public @ResponseBody
ResponseEntity<ResponseItem<List<Project>>> getWithExternal(@RequestBody ProjectCriteriaRequest projectCriteria, Principal principal) throws NoURLFound, InstantiationException, HugeResultSet, IllegalAccessException { ResponseEntity<ResponseItem<List<Project>>> getWithExternal(@RequestBody ProjectCriteriaRequest projectCriteria) throws NoURLFound, InstantiationException, HugeResultSet, IllegalAccessException, InvalidApplicationException {
List<Project> dataTable = this.projectManager.getCriteriaWithExternal(projectCriteria, principal); 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)); 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; package eu.eudat.controllers;
import eu.eudat.authorization.Permission;
import eu.eudat.logic.managers.DataRepositoryManager; import eu.eudat.logic.managers.DataRepositoryManager;
import eu.eudat.logic.proxy.config.exceptions.HugeResultSet; import eu.eudat.logic.proxy.config.exceptions.HugeResultSet;
import eu.eudat.logic.proxy.config.exceptions.NoURLFound; import eu.eudat.logic.proxy.config.exceptions.NoURLFound;
import eu.eudat.logic.services.ApiContext; import eu.eudat.logic.services.ApiContext;
import eu.eudat.models.data.datarepository.DataRepositoryModel; import eu.eudat.models.data.datarepository.DataRepositoryModel;
import eu.eudat.models.data.helpers.responses.ResponseItem; import eu.eudat.models.data.helpers.responses.ResponseItem;
import eu.eudat.models.data.security.Principal;
import eu.eudat.types.ApiMessageCode; import eu.eudat.types.ApiMessageCode;
import gr.cite.commons.web.authz.service.AuthorizationService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import javax.management.InvalidApplicationException;
import java.util.List; import java.util.List;
@ -22,19 +24,23 @@ import java.util.List;
public class PubRepositoriesController extends BaseController { public class PubRepositoriesController extends BaseController {
private DataRepositoryManager dataRepositoryManager; private DataRepositoryManager dataRepositoryManager;
private final AuthorizationService authorizationService;
@Autowired @Autowired
public PubRepositoriesController(ApiContext apiContext, DataRepositoryManager dataRepositoryManager) { public PubRepositoriesController(ApiContext apiContext, DataRepositoryManager dataRepositoryManager, AuthorizationService authorizationService) {
super(apiContext); super(apiContext);
this.dataRepositoryManager = dataRepositoryManager; this.dataRepositoryManager = dataRepositoryManager;
this.authorizationService = authorizationService;
} }
@RequestMapping(method = RequestMethod.GET, produces = "application/json") @RequestMapping(method = RequestMethod.GET, produces = "application/json")
public @ResponseBody public @ResponseBody
ResponseEntity<ResponseItem<List<DataRepositoryModel>>> listExternalDataRepositories( ResponseEntity<ResponseItem<List<DataRepositoryModel>>> listExternalDataRepositories(
@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 { ) throws HugeResultSet, NoURLFound, InvalidApplicationException {
List<DataRepositoryModel> dataRepositoryModels = this.dataRepositoryManager.getPubRepositories(query, type, principal); 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)); 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; package eu.eudat.controllers;
import eu.eudat.authorization.Permission;
import eu.eudat.logic.managers.PublicationManager; import eu.eudat.logic.managers.PublicationManager;
import eu.eudat.logic.proxy.config.exceptions.HugeResultSet; import eu.eudat.logic.proxy.config.exceptions.HugeResultSet;
import eu.eudat.logic.proxy.config.exceptions.NoURLFound; import eu.eudat.logic.proxy.config.exceptions.NoURLFound;
import eu.eudat.logic.services.ApiContext; import eu.eudat.logic.services.ApiContext;
import eu.eudat.models.data.helpers.responses.ResponseItem; import eu.eudat.models.data.helpers.responses.ResponseItem;
import eu.eudat.models.data.publication.PublicationModel; import eu.eudat.models.data.publication.PublicationModel;
import eu.eudat.models.data.security.Principal;
import eu.eudat.types.ApiMessageCode; import eu.eudat.types.ApiMessageCode;
import gr.cite.commons.web.authz.service.AuthorizationService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
@ -22,18 +23,22 @@ import java.util.List;
public class PublicationsController extends BaseController { public class PublicationsController extends BaseController {
private PublicationManager publicationManager; private PublicationManager publicationManager;
private final AuthorizationService authorizationService;
@Autowired @Autowired
public PublicationsController(ApiContext apiContext, PublicationManager publicationManager) { public PublicationsController(ApiContext apiContext, PublicationManager publicationManager, AuthorizationService authorizationService) {
super(apiContext); super(apiContext);
this.publicationManager = publicationManager; this.publicationManager = publicationManager;
this.authorizationService = authorizationService;
} }
@RequestMapping(method = RequestMethod.GET, produces = "application/json") @RequestMapping(method = RequestMethod.GET, produces = "application/json")
public @ResponseBody public @ResponseBody
ResponseEntity<ResponseItem<List<PublicationModel>>> listExternalPublications( 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 { ) throws HugeResultSet, NoURLFound {
this.authorizationService.authorizeForce(Permission.AuthenticatedRole);
List<PublicationModel> publicationModels = this.publicationManager.getPublications(query, type); List<PublicationModel> publicationModels = this.publicationManager.getPublications(query, type);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List<PublicationModel>>().status(ApiMessageCode.NO_MESSAGE).payload(publicationModels)); 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; 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.DescriptionTemplate;
import eu.eudat.data.old.DMP; import eu.eudat.data.old.DMP;
import eu.eudat.data.old.Funder; 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.DatasetCreateWizardModel;
import eu.eudat.models.data.quickwizard.DatasetDescriptionQuickWizardModel; import eu.eudat.models.data.quickwizard.DatasetDescriptionQuickWizardModel;
import eu.eudat.models.data.quickwizard.QuickWizardModel; import eu.eudat.models.data.quickwizard.QuickWizardModel;
import eu.eudat.models.data.security.Principal;
import eu.eudat.types.ApiMessageCode; import eu.eudat.types.ApiMessageCode;
import gr.cite.commons.web.authz.service.AuthorizationService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
@ -32,18 +34,24 @@ public class QuickWizardController extends BaseController {
private QuickWizardManager quickWizardManager; private QuickWizardManager quickWizardManager;
private DatasetManager datasetManager; private DatasetManager datasetManager;
private final AuthorizationService authorizationService;
private final UserScope userScope;
@Autowired @Autowired
public QuickWizardController(ApiContext apiContext, QuickWizardManager quickWizardManager, DatasetManager datasetManager) { public QuickWizardController(ApiContext apiContext, QuickWizardManager quickWizardManager, DatasetManager datasetManager, AuthorizationService authorizationService, UserScope userScope) {
super(apiContext); super(apiContext);
this.quickWizardManager = quickWizardManager; this.quickWizardManager = quickWizardManager;
this.datasetManager = datasetManager; this.datasetManager = datasetManager;
this.authorizationService = authorizationService;
this.userScope = userScope;
} }
@Transactional @Transactional
@RequestMapping(method = RequestMethod.POST, consumes = "application/json", produces = "application/json") @RequestMapping(method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
public @ResponseBody 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; Funder funderEntity;
//Create Funder //Create Funder
@ -52,7 +60,7 @@ public class QuickWizardController extends BaseController {
} else if (quickWizard.getFunder().getExistFunder() == null && quickWizard.getFunder().getLabel() == null) { } else if (quickWizard.getFunder().getExistFunder() == null && quickWizard.getFunder().getLabel() == null) {
funderEntity = null; funderEntity = null;
} else if (quickWizard.getFunder().getExistFunder() == null && quickWizard.getFunder().getLabel() != 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 { } else {
funderEntity = quickWizard.getFunder().getExistFunder().toDataModel(); funderEntity = quickWizard.getFunder().getExistFunder().toDataModel();
} }
@ -64,7 +72,7 @@ public class QuickWizardController extends BaseController {
} else if (quickWizard.getGrant().getExistGrant() == null && quickWizard.getGrant().getLabel() == null) { } else if (quickWizard.getGrant().getExistGrant() == null && quickWizard.getGrant().getLabel() == null) {
grantEntity = null; grantEntity = null;
} else if (quickWizard.getGrant().getExistGrant() == null) { } else if (quickWizard.getGrant().getExistGrant() == null) {
grantEntity = this.quickWizardManager.createOrUpdate(quickWizard.getGrant().toDataGrant(), principal); grantEntity = this.quickWizardManager.createOrUpdate(quickWizard.getGrant().toDataGrant());
} else { } else {
grantEntity = quickWizard.getGrant().getExistGrant().toDataModel(); grantEntity = quickWizard.getGrant().getExistGrant().toDataModel();
} }
@ -75,22 +83,22 @@ public class QuickWizardController extends BaseController {
&& quickWizard.getProject().getLabel() == null) { && quickWizard.getProject().getLabel() == null) {
projectEntity = null; projectEntity = null;
} else if (quickWizard.getProject().getExistProject() == null && quickWizard.getProject().getLabel() != 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 { } else {
projectEntity = quickWizard.getProject().getExistProject().toDataModel(); projectEntity = quickWizard.getProject().getExistProject().toDataModel();
} }
//Create Dmp //Create Dmp
DataManagementPlan dataManagementPlan = quickWizard.getDmp().toDataDmp(grantEntity, projectEntity, principal); DataManagementPlan dataManagementPlan = quickWizard.getDmp().toDataDmp(grantEntity, projectEntity, userScope);
DMP dmpEntity = this.quickWizardManager.createOrUpdate(dataManagementPlan, funderEntity, principal); DMP dmpEntity = this.quickWizardManager.createOrUpdate(dataManagementPlan, funderEntity);
//Create Datasets //Create Datasets
quickWizard.getDmp().setId(dmpEntity.getId()); quickWizard.getDmp().setId(dmpEntity.getId());
for (DatasetDescriptionQuickWizardModel dataset : quickWizard.getDatasets().getDatasetsList()) { 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(); DescriptionTemplate profile = quickWizard.getDmp().getDatasetProfile();
DatasetWizardModel datasetWizardModel = dataset.toDataModel(dmp, profile); 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")); 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") @RequestMapping(method = RequestMethod.POST, value = {"/datasetcreate"}, consumes = "application/json", produces = "application/json")
public @ResponseBody 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()){ for(DatasetDescriptionQuickWizardModel dataset : datasetCreateWizardModel.getDatasets().getDatasetsList()){
DescriptionTemplate profile = new DescriptionTemplate(); DescriptionTemplate profile = new DescriptionTemplate();
profile.setId(datasetCreateWizardModel.getDmpMeta().getDatasetProfile().getId()); profile.setId(datasetCreateWizardModel.getDmpMeta().getDatasetProfile().getId());
profile.setLabel(datasetCreateWizardModel.getDmpMeta().getDatasetProfile().getLabel()); 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!")); 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; package eu.eudat.controllers;
import eu.eudat.authorization.Permission;
import eu.eudat.data.old.Registry; import eu.eudat.data.old.Registry;
import eu.eudat.logic.managers.RegistryManager; import eu.eudat.logic.managers.RegistryManager;
import eu.eudat.logic.proxy.config.exceptions.HugeResultSet; 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.logic.services.ApiContext;
import eu.eudat.models.data.helpers.responses.ResponseItem; import eu.eudat.models.data.helpers.responses.ResponseItem;
import eu.eudat.models.data.registries.RegistryModel; import eu.eudat.models.data.registries.RegistryModel;
import eu.eudat.models.data.security.Principal;
import eu.eudat.types.ApiMessageCode; import eu.eudat.types.ApiMessageCode;
import gr.cite.commons.web.authz.service.AuthorizationService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import javax.management.InvalidApplicationException;
import java.util.List; import java.util.List;
@ -24,26 +26,32 @@ import java.util.List;
public class Registries extends BaseController { public class Registries extends BaseController {
private RegistryManager registryManager; private RegistryManager registryManager;
private final AuthorizationService authorizationService;
@Autowired @Autowired
public Registries(ApiContext apiContext, RegistryManager registryManager) { public Registries(ApiContext apiContext, RegistryManager registryManager, AuthorizationService authorizationService) {
super(apiContext); super(apiContext);
this.registryManager = registryManager; this.registryManager = registryManager;
this.authorizationService = authorizationService;
} }
@RequestMapping(method = RequestMethod.GET, value = {"/external/registries"}, produces = "application/json") @RequestMapping(method = RequestMethod.GET, value = {"/external/registries"}, produces = "application/json")
public @ResponseBody public @ResponseBody
ResponseEntity<ResponseItem<List<RegistryModel>>> listExternalRegistries(@RequestParam(value = "query", required = false) String query ResponseEntity<ResponseItem<List<RegistryModel>>> listExternalRegistries(@RequestParam(value = "query", required = false) String query
, @RequestParam(value = "type", required = false) String type, Principal principal) throws HugeResultSet, NoURLFound { , @RequestParam(value = "type", required = false) String type) throws HugeResultSet, NoURLFound, InvalidApplicationException {
List<RegistryModel> registryModels = this.registryManager.getRegistries(query, type, principal); 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)); return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List<RegistryModel>>().payload(registryModels).status(ApiMessageCode.NO_MESSAGE));
} }
@Transactional @Transactional
@RequestMapping(method = RequestMethod.POST, value = {"/registries"}, consumes = "application/json", produces = "application/json") @RequestMapping(method = RequestMethod.POST, value = {"/registries"}, consumes = "application/json", produces = "application/json")
public @ResponseBody public @ResponseBody
ResponseEntity<ResponseItem<RegistryModel>> create(@RequestBody RegistryModel registryModel, Principal principal) throws Exception { ResponseEntity<ResponseItem<RegistryModel>> create(@RequestBody RegistryModel registryModel) throws Exception {
Registry registry = this.registryManager.create(registryModel, principal); this.authorizationService.authorizeForce(Permission.AuthenticatedRole);
Registry registry = this.registryManager.create(registryModel);
RegistryModel registryModel1 = new RegistryModel().fromDataModel(registry); RegistryModel registryModel1 = new RegistryModel().fromDataModel(registry);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<RegistryModel>().payload(registryModel1).status(ApiMessageCode.SUCCESS_MESSAGE)); 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; package eu.eudat.controllers;
import eu.eudat.authorization.Permission;
import eu.eudat.data.query.items.item.researcher.ResearcherCriteriaRequest; import eu.eudat.data.query.items.item.researcher.ResearcherCriteriaRequest;
import eu.eudat.logic.managers.ResearcherManager; import eu.eudat.logic.managers.ResearcherManager;
import eu.eudat.logic.proxy.config.exceptions.HugeResultSet; import eu.eudat.logic.proxy.config.exceptions.HugeResultSet;
import eu.eudat.logic.proxy.config.exceptions.NoURLFound; import eu.eudat.logic.proxy.config.exceptions.NoURLFound;
import eu.eudat.logic.services.ApiContext; import eu.eudat.logic.services.ApiContext;
import eu.eudat.models.data.dmp.Researcher; 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.helpers.responses.ResponseItem;
import eu.eudat.models.data.security.Principal;
import eu.eudat.types.ApiMessageCode; import eu.eudat.types.ApiMessageCode;
import gr.cite.commons.web.authz.service.AuthorizationService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import javax.management.InvalidApplicationException;
import java.util.List; import java.util.List;
import java.util.Map;
@RestController @RestController
@ -27,24 +27,30 @@ import java.util.Map;
public class Researchers extends BaseController { public class Researchers extends BaseController {
private ResearcherManager researcherManager; private ResearcherManager researcherManager;
private final AuthorizationService authorizationService;
@Autowired @Autowired
public Researchers(ApiContext apiContext, ResearcherManager researcherManager) { public Researchers(ApiContext apiContext, ResearcherManager researcherManager, AuthorizationService authorizationService) {
super(apiContext); super(apiContext);
this.researcherManager = researcherManager; this.researcherManager = researcherManager;
this.authorizationService = authorizationService;
} }
@RequestMapping(method = RequestMethod.POST, value = {"/getWithExternal"}, consumes = "application/json", produces = "application/json") @RequestMapping(method = RequestMethod.POST, value = {"/getWithExternal"}, consumes = "application/json", produces = "application/json")
public @ResponseBody public @ResponseBody
ResponseEntity<ResponseItem<List<eu.eudat.models.data.dmp.Researcher>>> getWithExternal(@RequestBody ResearcherCriteriaRequest researcherCriteriaRequest, Principal principal) throws HugeResultSet, NoURLFound { ResponseEntity<ResponseItem<List<eu.eudat.models.data.dmp.Researcher>>> getWithExternal(@RequestBody ResearcherCriteriaRequest researcherCriteriaRequest) throws HugeResultSet, NoURLFound, InvalidApplicationException {
List<eu.eudat.models.data.dmp.Researcher> dataTable = this.researcherManager.getCriteriaWithExternal(researcherCriteriaRequest, principal); 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)); return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List<eu.eudat.models.data.dmp.Researcher>>().payload(dataTable).status(ApiMessageCode.NO_MESSAGE));
} }
@Transactional @Transactional
@RequestMapping(method = RequestMethod.POST, consumes = "application/json", produces = "application/json") @RequestMapping(method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
public @ResponseBody public @ResponseBody
ResponseEntity<ResponseItem<Researcher>> create(@RequestBody eu.eudat.models.data.researcher.Researcher researcher, Principal principal) throws Exception { ResponseEntity<ResponseItem<Researcher>> create(@RequestBody eu.eudat.models.data.researcher.Researcher researcher) throws Exception {
this.researcherManager.create(researcher, principal); this.authorizationService.authorizeForce(Permission.AuthenticatedRole);
this.researcherManager.create(researcher);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<Researcher>().status(ApiMessageCode.SUCCESS_MESSAGE)); return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<Researcher>().status(ApiMessageCode.SUCCESS_MESSAGE));
} }

View File

@ -1,20 +1,22 @@
package eu.eudat.controllers; package eu.eudat.controllers;
import eu.eudat.authorization.Permission;
import eu.eudat.data.old.Service; import eu.eudat.data.old.Service;
import eu.eudat.logic.managers.ServiceManager; import eu.eudat.logic.managers.ServiceManager;
import eu.eudat.logic.proxy.config.exceptions.HugeResultSet; import eu.eudat.logic.proxy.config.exceptions.HugeResultSet;
import eu.eudat.logic.proxy.config.exceptions.NoURLFound; import eu.eudat.logic.proxy.config.exceptions.NoURLFound;
import eu.eudat.logic.services.ApiContext; import eu.eudat.logic.services.ApiContext;
import eu.eudat.models.data.helpers.responses.ResponseItem; 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.models.data.services.ServiceModel;
import eu.eudat.types.ApiMessageCode; import eu.eudat.types.ApiMessageCode;
import gr.cite.commons.web.authz.service.AuthorizationService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import javax.management.InvalidApplicationException;
import java.util.List; import java.util.List;
@ -24,27 +26,31 @@ import java.util.List;
public class Services extends BaseController { public class Services extends BaseController {
private ServiceManager serviceManager; private ServiceManager serviceManager;
private final AuthorizationService authorizationService;
@Autowired @Autowired
public Services(ApiContext apiContext, ServiceManager serviceManager) { public Services(ApiContext apiContext, ServiceManager serviceManager, AuthorizationService authorizationService) {
super(apiContext); super(apiContext);
this.serviceManager = serviceManager; this.serviceManager = serviceManager;
this.authorizationService = authorizationService;
} }
@RequestMapping(method = RequestMethod.GET, value = {"/external/services"}, produces = "application/json") @RequestMapping(method = RequestMethod.GET, value = {"/external/services"}, produces = "application/json")
public @ResponseBody public @ResponseBody
ResponseEntity<ResponseItem<List<ServiceModel>>> listExternalServices( ResponseEntity<ResponseItem<List<ServiceModel>>> listExternalServices(
@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 { ) throws HugeResultSet, NoURLFound, InvalidApplicationException {
List<ServiceModel> serviceModels = this.serviceManager.getServices(query, type, principal); 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)); return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List<ServiceModel>>().payload(serviceModels).status(ApiMessageCode.NO_MESSAGE));
} }
@Transactional @Transactional
@RequestMapping(method = RequestMethod.POST, value = {"/services"}, consumes = "application/json", produces = "application/json") @RequestMapping(method = RequestMethod.POST, value = {"/services"}, consumes = "application/json", produces = "application/json")
public @ResponseBody public @ResponseBody
ResponseEntity<ResponseItem<ServiceModel>> create(@RequestBody ServiceModel serviceModel, Principal principal) throws Exception { ResponseEntity<ResponseItem<ServiceModel>> create(@RequestBody ServiceModel serviceModel) throws Exception {
Service service = serviceManager.create(serviceModel, principal); this.authorizationService.authorizeForce(Permission.AuthenticatedRole);
Service service = serviceManager.create(serviceModel);
ServiceModel serviceModel1 = new ServiceModel().fromDataModel(service); ServiceModel serviceModel1 = new ServiceModel().fromDataModel(service);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<ServiceModel>().payload(serviceModel1).status(ApiMessageCode.SUCCESS_MESSAGE)); 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; package eu.eudat.controllers;
import eu.eudat.authorization.Permission;
import eu.eudat.logic.managers.TaxonomyManager; import eu.eudat.logic.managers.TaxonomyManager;
import eu.eudat.logic.proxy.config.exceptions.HugeResultSet; import eu.eudat.logic.proxy.config.exceptions.HugeResultSet;
import eu.eudat.logic.proxy.config.exceptions.NoURLFound; import eu.eudat.logic.proxy.config.exceptions.NoURLFound;
import eu.eudat.logic.services.ApiContext; import eu.eudat.logic.services.ApiContext;
import eu.eudat.models.data.helpers.responses.ResponseItem; 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.models.data.taxonomy.TaxonomyModel;
import eu.eudat.types.ApiMessageCode; import eu.eudat.types.ApiMessageCode;
import gr.cite.commons.web.authz.service.AuthorizationService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
@ -22,18 +23,22 @@ import java.util.List;
public class TaxonomiesController extends BaseController { public class TaxonomiesController extends BaseController {
private TaxonomyManager taxonomyManager; private TaxonomyManager taxonomyManager;
private final AuthorizationService authorizationService;
@Autowired @Autowired
public TaxonomiesController(ApiContext apiContext, TaxonomyManager taxonomyManager) { public TaxonomiesController(ApiContext apiContext, TaxonomyManager taxonomyManager, AuthorizationService authorizationService) {
super(apiContext); super(apiContext);
this.taxonomyManager = taxonomyManager; this.taxonomyManager = taxonomyManager;
this.authorizationService = authorizationService;
} }
@RequestMapping(method = RequestMethod.GET, produces = "application/json") @RequestMapping(method = RequestMethod.GET, produces = "application/json")
public @ResponseBody public @ResponseBody
ResponseEntity<ResponseItem<List<TaxonomyModel>>> listExternalPublications( 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 { ) throws HugeResultSet, NoURLFound {
this.authorizationService.authorizeForce(Permission.AuthenticatedRole);
List<TaxonomyModel> taxonomyModels = this.taxonomyManager.getTaxonomies(query, type); List<TaxonomyModel> taxonomyModels = this.taxonomyManager.getTaxonomies(query, type);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List<TaxonomyModel>>().status(ApiMessageCode.NO_MESSAGE).payload(taxonomyModels)); 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; package eu.eudat.controllers;
import eu.eudat.authorization.Permission;
import eu.eudat.data.query.items.item.userinfo.UserInfoRequestItem; import eu.eudat.data.query.items.item.userinfo.UserInfoRequestItem;
import eu.eudat.logic.managers.InvitationsManager; import eu.eudat.logic.managers.InvitationsManager;
import eu.eudat.logic.services.ApiContext; import eu.eudat.logic.services.ApiContext;
import eu.eudat.models.data.helpers.responses.ResponseItem; import eu.eudat.models.data.helpers.responses.ResponseItem;
import eu.eudat.models.data.invitation.Invitation; import eu.eudat.models.data.invitation.Invitation;
import eu.eudat.models.data.security.Principal;
import eu.eudat.models.data.userinfo.UserInfoInvitationModel; import eu.eudat.models.data.userinfo.UserInfoInvitationModel;
import eu.eudat.types.ApiMessageCode; import eu.eudat.types.ApiMessageCode;
import gr.cite.commons.web.authz.service.AuthorizationService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
@ -15,6 +16,8 @@ import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import jakarta.xml.bind.JAXBException; import jakarta.xml.bind.JAXBException;
import javax.management.InvalidApplicationException;
import java.io.IOException; import java.io.IOException;
import java.util.List; import java.util.List;
import java.util.UUID; import java.util.UUID;
@ -26,34 +29,42 @@ import java.util.UUID;
public class UserInvitationController extends BaseController { public class UserInvitationController extends BaseController {
private InvitationsManager invitationsManager; private InvitationsManager invitationsManager;
private final AuthorizationService authorizationService;
@Autowired @Autowired
public UserInvitationController(ApiContext apiContext, InvitationsManager invitationsManager) { public UserInvitationController(ApiContext apiContext, InvitationsManager invitationsManager, AuthorizationService authorizationService) {
super(apiContext); super(apiContext);
this.invitationsManager = invitationsManager; this.invitationsManager = invitationsManager;
this.authorizationService = authorizationService;
} }
@Transactional @Transactional
@RequestMapping(method = RequestMethod.POST, value = {"/users"}, consumes = "application/json", produces = "application/json") @RequestMapping(method = RequestMethod.POST, value = {"/users"}, consumes = "application/json", produces = "application/json")
public @ResponseBody public @ResponseBody
ResponseEntity<ResponseItem<Invitation>> users(@RequestBody Invitation invitation, Principal principal) throws Exception { ResponseEntity<ResponseItem<Invitation>> users(@RequestBody Invitation invitation) throws Exception {
this.invitationsManager.inviteUsers(invitation, principal); 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")); return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<Invitation>().status(ApiMessageCode.SUCCESS_MESSAGE).message("Users have beeen invited"));
} }
@Transactional @Transactional
@RequestMapping(method = RequestMethod.GET, value = {"/exchange/{invitationID}"}, produces = "application/json") @RequestMapping(method = RequestMethod.GET, value = {"/exchange/{invitationID}"}, produces = "application/json")
public @ResponseBody public @ResponseBody
ResponseEntity<ResponseItem<UUID>> exchange(@PathVariable UUID invitationID, Principal principal) throws JAXBException, IOException { ResponseEntity<ResponseItem<UUID>> exchange(@PathVariable UUID invitationID) throws JAXBException, IOException, InvalidApplicationException {
UUID dmpId = invitationsManager.assignUserAcceptedInvitation(invitationID, principal); 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)); 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") @RequestMapping(method = RequestMethod.POST, value = {"/getUsers"}, consumes = "application/json", produces = "application/json")
public @ResponseBody public @ResponseBody
// ResponseEntity<ResponseItem<List<UserInfoInvitationModel>>> getUsers(Principal principal) throws IllegalAccessException, InstantiationException { // ResponseEntity<ResponseItem<List<UserInfoInvitationModel>>> getUsers() throws IllegalAccessException, InstantiationException {
ResponseEntity<ResponseItem<List<UserInfoInvitationModel>>> getUsers(Principal principal, @RequestBody UserInfoRequestItem userInfoRequestItem) 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.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)); 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; 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.data.query.items.table.userinfo.UserInfoTableRequestItem;
import eu.eudat.logic.managers.UserManager; import eu.eudat.logic.managers.UserManager;
import eu.eudat.logic.security.claims.ClaimedAuthorities;
import eu.eudat.logic.services.ApiContext; import eu.eudat.logic.services.ApiContext;
import eu.eudat.models.data.helpers.common.DataTableData; import eu.eudat.models.data.helpers.common.DataTableData;
import eu.eudat.models.data.helpers.responses.ResponseItem; 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.UserCredential;
import eu.eudat.models.data.userinfo.UserListingModel; import eu.eudat.models.data.userinfo.UserListingModel;
import eu.eudat.models.data.userinfo.UserProfile; import eu.eudat.models.data.userinfo.UserProfile;
import eu.eudat.types.ApiMessageCode; import eu.eudat.types.ApiMessageCode;
import gr.cite.commons.web.authz.service.AuthorizationService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
@ -18,12 +19,13 @@ import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import jakarta.validation.Valid; import jakarta.validation.Valid;
import javax.management.InvalidApplicationException;
import java.io.IOException; import java.io.IOException;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.UUID; import java.util.UUID;
import static eu.eudat.types.Authorities.ADMIN;
@RestController @RestController
@ -32,15 +34,22 @@ import static eu.eudat.types.Authorities.ADMIN;
public class Users extends BaseController { public class Users extends BaseController {
private UserManager userManager; private UserManager userManager;
private final AuthorizationService authorizationService;
private final UserScope userScope;
@Autowired @Autowired
public Users(ApiContext apiContext, UserManager userManager) { public Users(ApiContext apiContext, UserManager userManager, AuthorizationService authorizationService, UserScope userScope) {
super(apiContext); super(apiContext);
this.userManager = userManager; this.userManager = userManager;
this.authorizationService = authorizationService;
this.userScope = userScope;
} }
@RequestMapping(method = RequestMethod.POST, value = {"/getPaged"}, consumes = "application/json", produces = "application/json") @RequestMapping(method = RequestMethod.POST, value = {"/getPaged"}, consumes = "application/json", produces = "application/json")
public @ResponseBody 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); DataTableData<UserListingModel> dataTable = userManager.getPaged(userInfoTableRequestItem);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DataTableData<UserListingModel>>().payload(dataTable).status(ApiMessageCode.NO_MESSAGE)); 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 @Transactional
@RequestMapping(method = RequestMethod.POST, value = {"/updateRoles"}, consumes = "application/json", produces = "application/json") @RequestMapping(method = RequestMethod.POST, value = {"/updateRoles"}, consumes = "application/json", produces = "application/json")
public @ResponseBody 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); userManager.editRoles(userListingModel);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<UserListingModel>().status(ApiMessageCode.NO_MESSAGE)); return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<UserListingModel>().status(ApiMessageCode.NO_MESSAGE));
} }
@RequestMapping(method = RequestMethod.GET, value = {"/{id}"}, produces = "application/json") @RequestMapping(method = RequestMethod.GET, value = {"/{id}"}, produces = "application/json")
public @ResponseBody public @ResponseBody
ResponseEntity<ResponseItem<UserProfile>> get(@PathVariable String id, Principal principal) throws Exception { ResponseEntity<ResponseItem<UserProfile>> get(@PathVariable String id) throws Exception {
UUID userId = id.equals("me") ? principal.getId() : UUID.fromString(id); this.authorizationService.authorizeForce(Permission.AuthenticatedRole);
UUID userId = id.equals("me") ? this.userScope.getUserId() : UUID.fromString(id);
UserProfile user = userManager.getSingle(userId); UserProfile user = userManager.getSingle(userId);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<UserProfile>().payload(user).status(ApiMessageCode.NO_MESSAGE)); 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") @RequestMapping(method = RequestMethod.GET, value = {"/{id}/emails"}, produces = "application/json")
public @ResponseBody public @ResponseBody
ResponseEntity<ResponseItem<List<UserCredential>>> getEmails(@PathVariable String id, Principal principal) throws Exception { ResponseEntity<ResponseItem<List<UserCredential>>> getEmails(@PathVariable String id) throws Exception {
UUID userId = id.equals("me") ? principal.getId() : UUID.fromString(id); this.authorizationService.authorizeForce(Permission.AuthenticatedRole);
UUID userId = id.equals("me") ? this.userScope.getUserId() : UUID.fromString(id);
List<UserCredential> user = userManager.getCredentials(userId); List<UserCredential> user = userManager.getCredentials(userId);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List<UserCredential>>().payload(user).status(ApiMessageCode.NO_MESSAGE)); 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 @Transactional
@RequestMapping(method = RequestMethod.POST, value = {"/settings"}, produces = "application/json") @RequestMapping(method = RequestMethod.POST, value = {"/settings"}, produces = "application/json")
public @ResponseBody public @ResponseBody
ResponseEntity<ResponseItem<UserProfile>> saveSettings(@RequestBody Map<String, Object> settings, Principal principal) throws IOException { ResponseEntity<ResponseItem<UserProfile>> saveSettings(@RequestBody Map<String, Object> settings) throws IOException, InvalidApplicationException {
userManager.updateSettings(settings, principal); this.authorizationService.authorizeForce(Permission.AuthenticatedRole);
userManager.updateSettings(settings);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<UserProfile>().status(ApiMessageCode.NO_MESSAGE)); 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") @RequestMapping(method = RequestMethod.POST, value = {"/getCollaboratorsPaged"}, consumes = "application/json", produces = "application/json")
public @ResponseBody public @ResponseBody
ResponseEntity<ResponseItem<DataTableData<UserListingModel>>> getCollaboratorsPaged(@Valid @RequestBody UserInfoTableRequestItem userInfoTableRequestItem, Principal principal) throws Exception { ResponseEntity<ResponseItem<DataTableData<UserListingModel>>> getCollaboratorsPaged(@Valid @RequestBody UserInfoTableRequestItem userInfoTableRequestItem) throws Exception {
DataTableData<UserListingModel> dataTable = userManager.getCollaboratorsPaged(userInfoTableRequestItem, principal); 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)); return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DataTableData<UserListingModel>>().payload(dataTable).status(ApiMessageCode.NO_MESSAGE));
} }
@RequestMapping(method = RequestMethod.GET, value = {"/getCsv"}) @RequestMapping(method = RequestMethod.GET, value = {"/getCsv"})
public @ResponseBody public @ResponseBody
ResponseEntity exportCsv(@ClaimedAuthorities(claims = {ADMIN}) Principal principal) throws Exception { ResponseEntity exportCsv() throws Exception {
return userManager.exportToCsv(principal); return userManager.exportToCsv();
} }
@RequestMapping(method = RequestMethod.POST, value = {"/find"}, consumes = "application/json", produces = "application/json") @RequestMapping(method = RequestMethod.POST, value = {"/find"}, consumes = "application/json", produces = "application/json")
public @ResponseBody public @ResponseBody
ResponseEntity<ResponseItem<UserProfile>> find(@Valid @RequestBody String email) throws Exception { ResponseEntity<ResponseItem<UserProfile>> find(@Valid @RequestBody String email) throws Exception {
this.authorizationService.authorizeForce(Permission.PublicRole);
UserProfile userProfile = userManager.getFromEmail(email); UserProfile userProfile = userManager.getFromEmail(email);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<UserProfile>().payload(userProfile).status(ApiMessageCode.NO_MESSAGE)); 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; package eu.eudat.controllers;
import eu.eudat.authorization.Permission;
import eu.eudat.logic.managers.ValidationManager; import eu.eudat.logic.managers.ValidationManager;
import eu.eudat.logic.proxy.config.exceptions.HugeResultSet; import eu.eudat.logic.proxy.config.exceptions.HugeResultSet;
import eu.eudat.logic.proxy.config.exceptions.NoURLFound; import eu.eudat.logic.proxy.config.exceptions.NoURLFound;
import eu.eudat.logic.services.ApiContext; import eu.eudat.logic.services.ApiContext;
import eu.eudat.models.data.helpers.responses.ResponseItem; import eu.eudat.models.data.helpers.responses.ResponseItem;
import eu.eudat.models.data.security.Principal;
import eu.eudat.types.ApiMessageCode; import eu.eudat.types.ApiMessageCode;
import gr.cite.commons.web.authz.service.AuthorizationService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
@ -18,19 +19,23 @@ import org.springframework.web.bind.annotation.*;
public class Validation extends BaseController { public class Validation extends BaseController {
private ValidationManager validationManager; private ValidationManager validationManager;
private final AuthorizationService authorizationService;
@Autowired @Autowired
public Validation(ApiContext apiContext, ValidationManager validationManager) { public Validation(ApiContext apiContext, ValidationManager validationManager, AuthorizationService authorizationService) {
super(apiContext); super(apiContext);
this.validationManager = validationManager; this.validationManager = validationManager;
this.authorizationService = authorizationService;
} }
@RequestMapping(method = RequestMethod.GET, value = {"/external/validation"}, produces = "application/json") @RequestMapping(method = RequestMethod.GET, value = {"/external/validation"}, produces = "application/json")
public @ResponseBody public @ResponseBody
ResponseEntity<ResponseItem<Boolean>> validate( 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 { ) 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)); 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; 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.helpers.responses.ResponseItem;
import eu.eudat.models.data.security.Principal;
import eu.eudat.types.ApiMessageCode; import eu.eudat.types.ApiMessageCode;
import eu.eudat.types.Authorities;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;

View File

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

View File

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

View File

@ -1,13 +1,13 @@
package eu.eudat.controllers.v2; package eu.eudat.controllers.v2;
import eu.eudat.authorization.Permission;
import eu.eudat.commons.enums.SupportiveMaterialFieldType; import eu.eudat.commons.enums.SupportiveMaterialFieldType;
import eu.eudat.logic.managers.MetricsManager; import eu.eudat.logic.managers.MetricsManager;
import eu.eudat.logic.security.claims.ClaimedAuthorities;
import eu.eudat.model.persist.UserGuidePersist; import eu.eudat.model.persist.UserGuidePersist;
import eu.eudat.models.data.helpers.responses.ResponseItem; import eu.eudat.models.data.helpers.responses.ResponseItem;
import eu.eudat.models.data.security.Principal;
import eu.eudat.service.supportivematerial.SupportiveMaterialService; import eu.eudat.service.supportivematerial.SupportiveMaterialService;
import eu.eudat.types.ApiMessageCode; import eu.eudat.types.ApiMessageCode;
import gr.cite.commons.web.authz.service.AuthorizationService;
import org.apache.commons.lang3.EnumUtils; import org.apache.commons.lang3.EnumUtils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment; import org.springframework.core.env.Environment;
@ -31,11 +31,13 @@ public class SupportiveMaterialController {
private Environment environment; private Environment environment;
private SupportiveMaterialService supportiveMaterialService; private SupportiveMaterialService supportiveMaterialService;
private final AuthorizationService authorizationService;
@Autowired @Autowired
public SupportiveMaterialController(Environment environment, SupportiveMaterialService supportiveMaterialService, MetricsManager metricsManager) { public SupportiveMaterialController(Environment environment, SupportiveMaterialService supportiveMaterialService, MetricsManager metricsManager, AuthorizationService authorizationService) {
this.environment = environment; this.environment = environment;
this.supportiveMaterialService = supportiveMaterialService; this.supportiveMaterialService = supportiveMaterialService;
this.authorizationService = authorizationService;
} }
@GetMapping("{lang}") @GetMapping("{lang}")
@ -50,7 +52,8 @@ public class SupportiveMaterialController {
@PostMapping("current") @PostMapping("current")
public @ResponseBody 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)){ if( !EnumUtils.isValidEnum(SupportiveMaterialFieldType.class, field)){
return new ResponseEntity<>(HttpStatus.NOT_FOUND); 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.Document;
import org.w3c.dom.Element; import org.w3c.dom.Element;
import javax.management.InvalidApplicationException;
import java.util.Date; import java.util.Date;
import java.util.UUID; 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(); eu.eudat.data.dao.criteria.DatasetCriteria datasetsForThatDatasetProfile = new eu.eudat.data.dao.criteria.DatasetCriteria();
datasetsForThatDatasetProfile.setProfileDatasetId(UUID.fromString(id)); datasetsForThatDatasetProfile.setProfileDatasetId(UUID.fromString(id));
if (datasetDao.getWithCriteria(datasetsForThatDatasetProfile).count() == 0) { if (datasetDao.getWithCriteria(datasetsForThatDatasetProfile).count() == 0) {

View File

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

View File

@ -1,5 +1,6 @@
package eu.eudat.logic.managers; 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.DataManagementPlanCriteria;
import eu.eudat.data.dao.criteria.DatasetCriteria; import eu.eudat.data.dao.criteria.DatasetCriteria;
import eu.eudat.data.dao.criteria.GrantCriteria; 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.helpers.common.DataTableData;
import eu.eudat.models.data.listingmodels.DataManagementPlanListingModel; import eu.eudat.models.data.listingmodels.DataManagementPlanListingModel;
import eu.eudat.models.data.listingmodels.DatasetListingModel; import eu.eudat.models.data.listingmodels.DatasetListingModel;
import eu.eudat.models.data.security.Principal;
import eu.eudat.types.searchbar.SearchBarItemType; import eu.eudat.types.searchbar.SearchBarItemType;
import gr.cite.commons.web.oidc.principal.CurrentPrincipalResolver;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import jakarta.transaction.Transactional; import jakarta.transaction.Transactional;
import javax.management.InvalidApplicationException;
import java.io.IOException; import java.io.IOException;
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.InvocationTargetException;
import java.util.*; import java.util.*;
@ -56,20 +59,24 @@ public class DashBoardManager {
{ "publishedAt", Comparator.comparing(o -> ((RecentActivityModel)o).getPublishedAt(), Comparator.nullsLast(Comparator.naturalOrder())).reversed()} { "publishedAt", Comparator.comparing(o -> ((RecentActivityModel)o).getPublishedAt(), Comparator.nullsLast(Comparator.naturalOrder())).reversed()}
}).collect(Collectors.toMap(data -> (String) data[0], data -> (Comparator<RecentActivityModel>)data[1])); }).collect(Collectors.toMap(data -> (String) data[0], data -> (Comparator<RecentActivityModel>)data[1]));
private ApiContext apiContext; private final ApiContext apiContext;
private DatabaseRepository databaseRepository; private final DatabaseRepository databaseRepository;
private final DataManagementPlanManager dataManagementPlanManager; private final DataManagementPlanManager dataManagementPlanManager;
private final DatasetManager datasetManager; private final DatasetManager datasetManager;
private final CurrentPrincipalResolver currentPrincipalResolver;
private final UserScope userScope;
@Autowired @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.apiContext = apiContext;
this.databaseRepository = apiContext.getOperationsContext().getDatabaseRepository(); this.databaseRepository = apiContext.getOperationsContext().getDatabaseRepository();
this.dataManagementPlanManager = dataManagementPlanManager; this.dataManagementPlanManager = dataManagementPlanManager;
this.datasetManager = datasetManager; this.datasetManager = datasetManager;
this.currentPrincipalResolver = currentPrincipalResolver;
this.userScope = userScope;
} }
public DashBoardStatistics getStatistics() { public DashBoardStatistics getStatistics() throws InvalidApplicationException {
DashBoardStatistics statistics = new DashBoardStatistics(); DashBoardStatistics statistics = new DashBoardStatistics();
DataManagementPlanCriteria publicCriteria = new DataManagementPlanCriteria(); DataManagementPlanCriteria publicCriteria = new DataManagementPlanCriteria();
@ -104,7 +111,7 @@ public class DashBoardManager {
return statistics; return statistics;
} }
public DashBoardStatistics getMeStatistics(Principal principal) throws IOException { public DashBoardStatistics getMeStatistics() throws IOException, InvalidApplicationException {
Long datasets = 0L; Long datasets = 0L;
Long dmps = 0L; Long dmps = 0L;
DashBoardStatistics statistics = new DashBoardStatistics(); DashBoardStatistics statistics = new DashBoardStatistics();
@ -113,14 +120,14 @@ public class DashBoardManager {
GrantDao grantRepository = databaseRepository.getGrantDao(); GrantDao grantRepository = databaseRepository.getGrantDao();
OrganisationDao organisationRepository = databaseRepository.getOrganisationDao(); OrganisationDao organisationRepository = databaseRepository.getOrganisationDao();
UserInfo user = new UserInfo(); UserInfo user = new UserInfo();
user.setId(principal.getId()); user.setId(this.userScope.getUserId());
DatasetCriteria datasetCriteria = new DatasetCriteria(); DatasetCriteria datasetCriteria = new DatasetCriteria();
if (apiContext.getOperationsContext().getElasticRepository().getDatasetRepository() != null) { if (apiContext.getOperationsContext().getElasticRepository().getDatasetRepository() != null) {
try { try {
eu.eudat.elastic.criteria.DatasetCriteria datasetElasticCriteria = new eu.eudat.elastic.criteria.DatasetCriteria(); eu.eudat.elastic.criteria.DatasetCriteria datasetElasticCriteria = new eu.eudat.elastic.criteria.DatasetCriteria();
datasetElasticCriteria.setAllowAllVersions(false); datasetElasticCriteria.setAllowAllVersions(false);
datasetElasticCriteria.setPublic(false); datasetElasticCriteria.setPublic(false);
datasetElasticCriteria.setCollaborators(Collections.singletonList(principal.getId())); datasetElasticCriteria.setCollaborators(Collections.singletonList(this.userScope.getUserId()));
datasets = apiContext.getOperationsContext().getElasticRepository().getDatasetRepository().count(datasetElasticCriteria); datasets = apiContext.getOperationsContext().getElasticRepository().getDatasetRepository().count(datasetElasticCriteria);
}catch (Exception e) { }catch (Exception e) {
logger.warn(e.getMessage(), 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(); eu.eudat.elastic.criteria.DmpCriteria dmpElasticCriteria = new eu.eudat.elastic.criteria.DmpCriteria();
dmpElasticCriteria.setAllowAllVersions(false); dmpElasticCriteria.setAllowAllVersions(false);
dmpElasticCriteria.setPublic(false); dmpElasticCriteria.setPublic(false);
dmpElasticCriteria.setCollaborators(Collections.singletonList(principal.getId())); dmpElasticCriteria.setCollaborators(Collections.singletonList(this.userScope.getUserId()));
dmps = apiContext.getOperationsContext().getElasticRepository().getDmpRepository().count(dmpElasticCriteria); dmps = apiContext.getOperationsContext().getElasticRepository().getDmpRepository().count(dmpElasticCriteria);
}catch (Exception e) { }catch (Exception e) {
logger.warn(e.getMessage(), e); logger.warn(e.getMessage(), e);
@ -154,7 +161,7 @@ public class DashBoardManager {
List<Integer> roles = new LinkedList<>(); List<Integer> roles = new LinkedList<>();
if ((dmps == null || dmps == 0L) && (datasets == null || datasets == 0L)) { 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)); .whenComplete((dmpsStats, throwable) -> statistics.setTotalDataManagementPlanCount(dmpsStats));
CompletableFuture datasetFuture = datasetRepository.getAuthenticated( datasetRepository.getWithCriteria(datasetCriteria), user, roles).distinct().countAsync() CompletableFuture datasetFuture = datasetRepository.getAuthenticated( datasetRepository.getWithCriteria(datasetCriteria), user, roles).distinct().countAsync()
.whenComplete((datasetsStats, throwable) -> statistics.setTotalDataSetCount(datasetsStats)); .whenComplete((datasetsStats, throwable) -> statistics.setTotalDataSetCount(datasetsStats));
@ -173,13 +180,13 @@ public class DashBoardManager {
} }
@Deprecated @Deprecated
public RecentActivity getRecentActivity(Principal principal, Integer numberofactivities) { public RecentActivity getRecentActivity(Integer numberofactivities) throws InvalidApplicationException {
RecentActivity activity = new RecentActivity(); RecentActivity activity = new RecentActivity();
DMPDao dataManagementPlanRepository = databaseRepository.getDmpDao(); DMPDao dataManagementPlanRepository = databaseRepository.getDmpDao();
DatasetDao datasetRepository = databaseRepository.getDatasetDao(); DatasetDao datasetRepository = databaseRepository.getDatasetDao();
GrantDao grantRepository = databaseRepository.getGrantDao(); GrantDao grantRepository = databaseRepository.getGrantDao();
UserInfo user = new UserInfo(); UserInfo user = new UserInfo();
user.setId(principal.getId()); user.setId(this.userScope.getUserId());
DatasetCriteria datasetCriteria = new DatasetCriteria(); DatasetCriteria datasetCriteria = new DatasetCriteria();
datasetCriteria.setAllVersions(false); datasetCriteria.setAllVersions(false);
DataManagementPlanCriteria dataManagementPlanCriteria = new DataManagementPlanCriteria(); DataManagementPlanCriteria dataManagementPlanCriteria = new DataManagementPlanCriteria();
@ -188,7 +195,7 @@ public class DashBoardManager {
RecentActivityDataBuilder recentActivityDataBuilder = apiContext.getOperationsContext().getBuilderFactory().getBuilder(RecentActivityDataBuilder.class); RecentActivityDataBuilder recentActivityDataBuilder = apiContext.getOperationsContext().getBuilderFactory().getBuilder(RecentActivityDataBuilder.class);
List<Integer> roles = new LinkedList<>(); 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") .withHint("dmpRecentActivity")
.orderBy((builder, root) -> builder.desc(root.get("modified"))) .orderBy((builder, root) -> builder.desc(root.get("modified")))
.take(numberofactivities) .take(numberofactivities)
@ -214,12 +221,12 @@ public class DashBoardManager {
} }
@Transactional @Transactional
public List<RecentActivityModel> getNewRecentActivity(RecentActivityTableRequest tableRequest, Principal principal) throws Exception { public List<RecentActivityModel> getNewRecentActivity(RecentActivityTableRequest tableRequest) throws Exception {
boolean isAuthenticated = principal.getId() != null; boolean isAuthenticated = this.currentPrincipalResolver.currentPrincipal().isAuthenticated();
List<RecentActivityModel> recentActivityModels = new ArrayList<>(); List<RecentActivityModel> recentActivityModels = new ArrayList<>();
UserInfo user = new UserInfo(); UserInfo user = new UserInfo();
if (isAuthenticated) { if (isAuthenticated) {
user.setId(principal.getId()); user.setId(userScope.getUserId());
} }
DatasetCriteria datasetCriteria = new DatasetCriteria(); DatasetCriteria datasetCriteria = new DatasetCriteria();
datasetCriteria.setLike(tableRequest.getCriteria().getLike()); datasetCriteria.setLike(tableRequest.getCriteria().getLike());
@ -243,7 +250,7 @@ public class DashBoardManager {
dataManagementPlanTableRequest.setOrderings(tableRequest.getOrderings()); dataManagementPlanTableRequest.setOrderings(tableRequest.getOrderings());
dataManagementPlanTableRequest.setLength(tableRequest.getLength()); dataManagementPlanTableRequest.setLength(tableRequest.getLength());
dataManagementPlanTableRequest.setOffset(tableRequest.getDmpOffset()); 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())); recentActivityModels.addAll(dmps.getData().stream().map(dataManagementPlanListingModel -> new RecentDmpModel().fromDataModel(dataManagementPlanListingModel.toDataModel())).collect(Collectors.toList()));
DatasetTableRequest datasetTableRequest = new DatasetTableRequest(); DatasetTableRequest datasetTableRequest = new DatasetTableRequest();
datasetCriteria.setCollaborators(new ArrayList<>()); datasetCriteria.setCollaborators(new ArrayList<>());
@ -253,7 +260,7 @@ public class DashBoardManager {
datasetTableRequest.getOrderings().getFields().removeIf(s -> s.contains("publishedAt") && !s.endsWith("|join|")); datasetTableRequest.getOrderings().getFields().removeIf(s -> s.contains("publishedAt") && !s.endsWith("|join|"));
datasetTableRequest.setLength(tableRequest.getLength()); datasetTableRequest.setLength(tableRequest.getLength());
datasetTableRequest.setOffset(tableRequest.getDatasetOffset()); 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())); 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 //GK: Shuffle the deck otherwise we will summon the DMPodia when sorting with status
@ -290,9 +297,9 @@ public class DashBoardManager {
return recentActivityModels; return recentActivityModels;
} }
public List<SearchBarItem> searchUserData(String like, Principal principal) { public List<SearchBarItem> searchUserData(String like) throws InvalidApplicationException {
UserInfo user = new UserInfo(); UserInfo user = new UserInfo();
user.setId(principal.getId()); user.setId(this.userScope.getUserIdSafe());
DMPDao dataManagementPlanRepository = databaseRepository.getDmpDao(); DMPDao dataManagementPlanRepository = databaseRepository.getDmpDao();
DatasetDao datasetRepository = databaseRepository.getDatasetDao(); DatasetDao datasetRepository = databaseRepository.getDatasetDao();
GrantDao grantRepository = databaseRepository.getGrantDao(); GrantDao grantRepository = databaseRepository.getGrantDao();
@ -316,8 +323,8 @@ public class DashBoardManager {
.selectAsync(item -> new SearchBarItem(item.getId().toString(), item.getLabel(), SearchBarItemType.DATASET.getValue(), true)) .selectAsync(item -> new SearchBarItem(item.getId().toString(), item.getLabel(), SearchBarItemType.DATASET.getValue(), true))
.whenComplete((dataSetItems, throwable) -> searchBarItems.addAll(dataSetItems)); .whenComplete((dataSetItems, throwable) -> searchBarItems.addAll(dataSetItems));
if (principal.getId() != null) { if (this.userScope.isSet()) {
CompletableFuture<List<SearchBarItem>> dmps = dataManagementPlanRepository.getAuthenticated(dataManagementPlanRepository.asQueryable(), principal.getId(), roles) CompletableFuture<List<SearchBarItem>> dmps = dataManagementPlanRepository.getAuthenticated(dataManagementPlanRepository.asQueryable(), this.userScope.getUserId(), roles)
.withHint("dmpRecentActivity") .withHint("dmpRecentActivity")
.where((builder, root) -> builder.like(builder.upper(root.get("label")), "%" + like.toUpperCase() + "%")) .where((builder, root) -> builder.like(builder.upper(root.get("label")), "%" + like.toUpperCase() + "%"))
.where((builder, root) -> builder.notEqual(root.get("status"), DMP.DMPStatus.DELETED.getValue())) .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.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper; 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.DynamicGrantConfiguration;
import eu.eudat.configurations.dynamicgrant.entities.Property; import eu.eudat.configurations.dynamicgrant.entities.Property;
import eu.eudat.data.dao.criteria.*; 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.helpers.common.DataTableData;
import eu.eudat.models.data.listingmodels.*; import eu.eudat.models.data.listingmodels.*;
import eu.eudat.models.data.project.ProjectDMPEditorModel; 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.user.composite.PagedDatasetProfile;
import eu.eudat.models.data.userinfo.UserListingModel; import eu.eudat.models.data.userinfo.UserListingModel;
import eu.eudat.queryable.QueryableList; import eu.eudat.queryable.QueryableList;
import eu.eudat.types.Authorities; import eu.eudat.types.Authorities;
import eu.eudat.types.MetricNames; 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.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph; import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun; import org.apache.poi.xwpf.usermodel.XWPFRun;
@ -86,6 +88,8 @@ import jakarta.transaction.Transactional;
import jakarta.xml.bind.JAXBContext; import jakarta.xml.bind.JAXBContext;
import jakarta.xml.bind.JAXBException; import jakarta.xml.bind.JAXBException;
import jakarta.xml.bind.Unmarshaller; import jakarta.xml.bind.Unmarshaller;
import javax.management.InvalidApplicationException;
import java.io.*; import java.io.*;
import java.math.BigInteger; import java.math.BigInteger;
import java.nio.file.Files; import java.nio.file.Files;
@ -120,10 +124,13 @@ public class DataManagementPlanManager {
private final MetricsManager metricsManager; private final MetricsManager metricsManager;
private final ConfigLoader configLoader; private final ConfigLoader configLoader;
private List<RepositoryDeposit> repositoriesDeposit; private List<RepositoryDeposit> repositoriesDeposit;
private final UserScope userScope;
private final AuthorizationService authorizationService;
@Autowired @Autowired
public DataManagementPlanManager(ApiContext apiContext, DatasetManager datasetManager, DataManagementProfileManager dataManagementProfileManager, Environment environment, RDAManager rdaManager, UserManager userManager, 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.apiContext = apiContext;
this.datasetManager = datasetManager; this.datasetManager = datasetManager;
this.dataManagementProfileManager = dataManagementProfileManager; this.dataManagementProfileManager = dataManagementProfileManager;
@ -133,6 +140,8 @@ public class DataManagementPlanManager {
this.userManager = userManager; this.userManager = userManager;
this.metricsManager = metricsManager; this.metricsManager = metricsManager;
this.configLoader = configLoader; this.configLoader = configLoader;
this.userScope = userScope;
this.authorizationService = authorizationService;
this.objectMapper = new ObjectMapper(); this.objectMapper = new ObjectMapper();
this.repositoriesDeposit = repositoriesDeposit; this.repositoriesDeposit = repositoriesDeposit;
} }
@ -141,8 +150,8 @@ public class DataManagementPlanManager {
* Data Retrieval * Data Retrieval
* */ * */
public DataTableData<DataManagementPlanListingModel> getPaged(DataManagementPlanTableRequest dataManagementPlanTableRequest, Principal principal, String fieldsGroup) throws Exception { public DataTableData<DataManagementPlanListingModel> getPaged(DataManagementPlanTableRequest dataManagementPlanTableRequest, String fieldsGroup) throws Exception {
UUID principalID = principal.getId(); UUID principalID = userScope.getUserIdSafe();
List<Dmp> dmps = null; List<Dmp> dmps = null;
QueryableList<DMP> items = null; QueryableList<DMP> items = null;
QueryableList<DMP> authItems = null; QueryableList<DMP> authItems = null;
@ -199,7 +208,11 @@ public class DataManagementPlanManager {
datasetCriteria.setAllVersions(dataManagementPlanTableRequest.getCriteria().getAllVersions()); datasetCriteria.setAllVersions(dataManagementPlanTableRequest.getCriteria().getAllVersions());
datasetCriteria.setIsPublic(dataManagementPlanTableRequest.getCriteria().getIsPublic()); datasetCriteria.setIsPublic(dataManagementPlanTableRequest.getCriteria().getIsPublic());
datasetCriteria.setGroupIds(Collections.singletonList(dmp.getGroupId())); datasetCriteria.setGroupIds(Collections.singletonList(dmp.getGroupId()));
try {
dmp.setDataset(retrieveRelevantDatasets(datasetCriteria, principalID)); dmp.setDataset(retrieveRelevantDatasets(datasetCriteria, principalID));
} catch (InvalidApplicationException e) {
throw new RuntimeException(e);
}
return new DataManagementPlanListingModel().fromDataModelDatasets(dmp); return new DataManagementPlanListingModel().fromDataModelDatasets(dmp);
@ -224,7 +237,11 @@ public class DataManagementPlanManager {
datasetCriteria.setIsPublic(true); datasetCriteria.setIsPublic(true);
datasetCriteria.setAllVersions(dataManagementPlanTableRequest.getCriteria().getAllVersions()); datasetCriteria.setAllVersions(dataManagementPlanTableRequest.getCriteria().getAllVersions());
datasetCriteria.setGroupIds(Collections.singletonList(dmp.getGroupId())); datasetCriteria.setGroupIds(Collections.singletonList(dmp.getGroupId()));
try {
dmp.setDataset(retrieveRelevantDatasets(datasetCriteria)); dmp.setDataset(retrieveRelevantDatasets(datasetCriteria));
} catch (InvalidApplicationException e) {
throw new RuntimeException(e);
}
return new DataManagementPlanListingModel().fromDataModelDatasets(dmp); return new DataManagementPlanListingModel().fromDataModelDatasets(dmp);
@ -253,11 +270,11 @@ public class DataManagementPlanManager {
return dataTable; return dataTable;
} }
private Set<Dataset> retrieveRelevantDatasets(DatasetCriteria datasetCriteria) { private Set<Dataset> retrieveRelevantDatasets(DatasetCriteria datasetCriteria) throws InvalidApplicationException {
return retrieveRelevantDatasets(datasetCriteria, null); 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) QueryableList<Dataset> datasetItems = apiContext.getOperationsContext().getDatabaseRepository().getDatasetDao().getWithCriteria(datasetCriteria)
.orderBy((builder, root) -> builder.desc(root.get("modified"))); .orderBy((builder, root) -> builder.desc(root.get("modified")));
if (principal != null) { if (principal != null) {
@ -288,12 +305,12 @@ public class DataManagementPlanManager {
return datasetsSet; 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(); eu.eudat.models.data.dmp.DataManagementPlan dataManagementPlan = new eu.eudat.models.data.dmp.DataManagementPlan();
DMP dataManagementPlanEntity = databaseRepository.getDmpDao().find(UUID.fromString(id)); DMP dataManagementPlanEntity = databaseRepository.getDmpDao().find(UUID.fromString(id));
if (!isPublic && principal == null) { if (!isPublic && !this.userScope.isSet()) {
throw new UnauthorisedException(); 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()) { if (!dataManagementPlanEntity.isPublic()) {
throw new UnauthorisedException(); throw new UnauthorisedException();
} }
@ -339,16 +356,16 @@ public class DataManagementPlanManager {
return dataManagementPlan; 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)); DMP dataManagementPlanEntity = databaseRepository.getDmpDao().find(UUID.fromString(id));
if (dataManagementPlanEntity.getStatus() == DMP.DMPStatus.DELETED.getValue()) { if (dataManagementPlanEntity.getStatus() == DMP.DMPStatus.DELETED.getValue()) {
throw new Exception("DMP is deleted."); throw new Exception("DMP is deleted.");
} }
if (!isPublic && principal == null) { if (!isPublic && !this.userScope.isSet()) {
throw new UnauthorisedException(); throw new UnauthorisedException();
} else } else
if (!isPublic && dataManagementPlanEntity.getUsers() if (!isPublic && dataManagementPlanEntity.getUsers()
.stream().noneMatch(userInfo -> userInfo.getUser().getId() == principal.getId())) { .stream().noneMatch(userInfo -> userInfo.getUser().getId() == this.userScope.getUserIdSafe())) {
throw new UnauthorisedException(); throw new UnauthorisedException();
} else if (isPublic && !dataManagementPlanEntity.isPublic()) { } else if (isPublic && !dataManagementPlanEntity.isPublic()) {
throw new ForbiddenException("Selected DMP is not public"); throw new ForbiddenException("Selected DMP is not public");
@ -406,9 +423,9 @@ public class DataManagementPlanManager {
return result; 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().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()); QueryableList<DescriptionTemplate> items = apiContext.getOperationsContext().getDatabaseRepository().getDatasetProfileDao().getWithCriteria(datasetProfileTableRequestItem.getCriteria());
List<DatasetProfileListingModel> listingModels = items.select(item -> new DatasetProfileListingModel().fromDataModel(item)); List<DatasetProfileListingModel> listingModels = items.select(item -> new DatasetProfileListingModel().fromDataModel(item));
@ -420,8 +437,8 @@ public class DataManagementPlanManager {
return data; return data;
} }
public List<VersionListingModel> getAllVersions(String groupId, Principal principal, Boolean isPublic) { public List<VersionListingModel> getAllVersions(String groupId, Boolean isPublic) throws InvalidApplicationException {
UUID principalId = principal != null ? principal.getId() : null; UUID principalId = this.userScope.getUserIdSafe();
List<VersionListingModel> versions = new ArrayList<>(); List<VersionListingModel> versions = new ArrayList<>();
QueryableList<DMP> items = null; QueryableList<DMP> items = null;
QueryableList<DMP> authItems = null; QueryableList<DMP> authItems = null;
@ -452,7 +469,7 @@ public class DataManagementPlanManager {
* */ * */
@Transactional @Transactional
public DMP createOrUpdate(DataManagementPlanEditorModel dataManagementPlan, Principal principal) throws Exception { public DMP createOrUpdate(DataManagementPlanEditorModel dataManagementPlan) throws Exception {
boolean setNotification = false; boolean setNotification = false;
if (dataManagementPlan.getId() != null) { if (dataManagementPlan.getId() != null) {
DMP dmp1 = apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().find(dataManagementPlan.getId()); 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 dbTime = Instant.ofEpochMilli(dmp1.getModified().getTime()).truncatedTo(ChronoUnit.SECONDS);
Instant modelTime = Instant.ofEpochMilli(dataManagementPlan.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."); throw new Exception("User not being the creator is not authorized to edit this DMP.");
} }
if (dbTime.toEpochMilli() != modelTime.toEpochMilli()) { if (dbTime.toEpochMilli() != modelTime.toEpochMilli()) {
@ -487,21 +504,21 @@ public class DataManagementPlanManager {
if (newDmp.getStatus() == (int) DMP.DMPStatus.FINALISED.getValue()) { if (newDmp.getStatus() == (int) DMP.DMPStatus.FINALISED.getValue()) {
checkDmpValidationRules(newDmp); checkDmpValidationRules(newDmp);
} }
UserInfo user = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(principal.getId()); UserInfo user = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(this.userScope.getUserId());
newDmp.setCreator(user); 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()); 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); 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()); 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()); 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())) { if (newDmp.getProject() != null && newDmp.getGrant() != null && (newDmp.getProject().getLabel() == null || newDmp.getProject().getLabel().trim().isEmpty())) {
newDmp.setProject(newDmp.getProject().projectFromGrant(newDmp.getGrant())); newDmp.setProject(newDmp.getProject().projectFromGrant(newDmp.getGrant()));
} }
@ -515,7 +532,7 @@ public class DataManagementPlanManager {
} else dmp = new DMP(); } else dmp = new DMP();
newDmp.setCreated(dmp.getCreated() == null ? new Date() : dmp.getCreated()); 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) { .collect(Collectors.toList()).size() == 0) {
List<UserDMP> userDMPList = new ArrayList<>(newDmp.getUsers()); List<UserDMP> userDMPList = new ArrayList<>(newDmp.getUsers());
for (UserInfoListingModel userInfoListingModel : dataManagementPlan.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())) { if (newDmp.getGrant() != null && newDmp.getGrant().getType().equals(Grant.GrantType.INTERNAL.getValue())) {
checkIfUserCanEditGrant(newDmp, user); checkIfUserCanEditGrant(newDmp, user);
} }
assignGrandUserIfInternal(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); assignFunderUserIfInternal(newDmp, user);
} }
if(this.dataManagementProfileManager.fieldInBlueprint(newDmp.getProfile(), SystemFieldType.PROJECT, principal)) { if(this.dataManagementProfileManager.fieldInBlueprint(newDmp.getProfile(), SystemFieldType.PROJECT)) {
assignProjectUserIfInternal(newDmp, user); 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) { if (newDmp.getGrant() != null) {
apiContext.getOperationsContext().getDatabaseRepository().getGrantDao().createOrUpdate(newDmp.getGrant()); apiContext.getOperationsContext().getDatabaseRepository().getGrantDao().createOrUpdate(newDmp.getGrant());
} }
@ -618,14 +635,14 @@ public class DataManagementPlanManager {
return newDmp; return newDmp;
} }
public DMP createOrUpdateWithDatasets(DataManagementPlanEditorModel dataManagementPlan, Principal principal) throws Exception { public DMP createOrUpdateWithDatasets(DataManagementPlanEditorModel dataManagementPlan) throws Exception {
if (dataManagementPlan.getId() != null) { if (dataManagementPlan.getId() != null) {
DMP dmp1 = apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().find(dataManagementPlan.getId()); DMP dmp1 = apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().find(dataManagementPlan.getId());
Instant dbTime = Instant.ofEpochMilli(dmp1.getModified().getTime()).truncatedTo(ChronoUnit.SECONDS); Instant dbTime = Instant.ofEpochMilli(dmp1.getModified().getTime()).truncatedTo(ChronoUnit.SECONDS);
Instant modelTime = Instant.ofEpochMilli(dataManagementPlan.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."); throw new Exception("User not being the creator is not authorized to edit this DMP.");
} }
if (dbTime.toEpochMilli() != modelTime.toEpochMilli()) { if (dbTime.toEpochMilli() != modelTime.toEpochMilli()) {
@ -645,25 +662,25 @@ public class DataManagementPlanManager {
if (tempDMP.getStatus() == (int) DMP.DMPStatus.FINALISED.getValue()) { if (tempDMP.getStatus() == (int) DMP.DMPStatus.FINALISED.getValue()) {
checkDmpValidationRules(tempDMP); checkDmpValidationRules(tempDMP);
} }
UserInfo user = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(principal.getId()); UserInfo user = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(this.userScope.getUserId());
if(this.dataManagementProfileManager.fieldInBlueprint(tempDMP.getProfile(), SystemFieldType.ORGANIZATIONS, principal)) { if(this.dataManagementProfileManager.fieldInBlueprint(tempDMP.getProfile(), SystemFieldType.ORGANIZATIONS)) {
createOrganisationsIfTheyDontExist(tempDMP, apiContext.getOperationsContext().getDatabaseRepository().getOrganisationDao()); 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); 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()); 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()); createGrantIfItDoesntExist(tempDMP, apiContext.getOperationsContext().getDatabaseRepository().getGrantDao());
} }
DMP result = createOrUpdate(dataManagementPlan, principal); DMP result = createOrUpdate(dataManagementPlan);
for (DatasetWizardModel datasetWizardModel: dataManagementPlan.getDatasets()) { for (DatasetWizardModel datasetWizardModel: dataManagementPlan.getDatasets()) {
datasetWizardModel.setDmp(new DataManagementPlan().fromDataModel(result)); datasetWizardModel.setDmp(new DataManagementPlan().fromDataModel(result));
Dataset dataset = datasetManager.createOrUpdate(datasetWizardModel, principal); Dataset dataset = datasetManager.createOrUpdate(datasetWizardModel);
datasets.add(dataset); datasets.add(dataset);
} }
@ -675,9 +692,9 @@ public class DataManagementPlanManager {
return result; 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); 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."); throw new Exception("User not being the creator is not authorized to perform this action.");
} }
DataManagementPlanCriteria criteria = new DataManagementPlanCriteria(); DataManagementPlanCriteria criteria = new DataManagementPlanCriteria();
@ -693,20 +710,20 @@ public class DataManagementPlanManager {
newDmp.setProfile(oldDmp.getProfile()); newDmp.setProfile(oldDmp.getProfile());
newDmp.setProperties(oldDmp.getProperties()); newDmp.setProperties(oldDmp.getProperties());
newDmp.setDmpProperties(oldDmp.getDmpProperties()); 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); newDmp.setCreator(user);
if(this.dataManagementProfileManager.fieldInBlueprint(newDmp.getProfile(), SystemFieldType.ORGANIZATIONS, principal)) { if(this.dataManagementProfileManager.fieldInBlueprint(newDmp.getProfile(), SystemFieldType.ORGANIZATIONS)) {
createOrganisationsIfTheyDontExist(newDmp, databaseRepository.getOrganisationDao()); 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); 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()); 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()); 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())) { if (newDmp.getProject() != null && newDmp.getGrant() != null && (newDmp.getProject().getLabel() == null || newDmp.getProject().getLabel().trim().isEmpty())) {
newDmp.setProject(newDmp.getProject().projectFromGrant(newDmp.getGrant())); newDmp.setProject(newDmp.getProject().projectFromGrant(newDmp.getGrant()));
} }
@ -718,19 +735,19 @@ public class DataManagementPlanManager {
newDmp.setVersion(oldDmp.getVersion() + 1); newDmp.setVersion(oldDmp.getVersion() + 1);
newDmp.setId(null); 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())) { if (newDmp.getGrant() != null && newDmp.getGrant().getType().equals(Grant.GrantType.INTERNAL.getValue())) {
checkIfUserCanEditGrant(newDmp, user); checkIfUserCanEditGrant(newDmp, user);
} }
assignGrandUserIfInternal(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); assignFunderUserIfInternal(newDmp, user);
} }
if(this.dataManagementProfileManager.fieldInBlueprint(newDmp.getProfile(), SystemFieldType.PROJECT, principal)) { if(this.dataManagementProfileManager.fieldInBlueprint(newDmp.getProfile(), SystemFieldType.PROJECT)) {
assignProjectUserIfInternal(newDmp, user); 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() != null) {
if (newDmp.getGrant().getStartdate() == null) { if (newDmp.getGrant().getStartdate() == null) {
newDmp.getGrant().setStartdate(new Date()); 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 oldDmp = databaseRepository.getDmpDao().find(uuid);
DMP newDmp = dataManagementPlan.toDataModel(); DMP newDmp = dataManagementPlan.toDataModel();
newDmp.setProfile(oldDmp.getProfile()); newDmp.setProfile(oldDmp.getProfile());
newDmp.setProperties(oldDmp.getProperties()); newDmp.setProperties(oldDmp.getProperties());
newDmp.setDmpProperties(oldDmp.getDmpProperties()); 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); newDmp.setCreator(user);
if(this.dataManagementProfileManager.fieldInBlueprint(newDmp.getProfile(), SystemFieldType.ORGANIZATIONS, principal)) { if(this.dataManagementProfileManager.fieldInBlueprint(newDmp.getProfile(), SystemFieldType.ORGANIZATIONS)) {
createOrganisationsIfTheyDontExist(newDmp, databaseRepository.getOrganisationDao()); 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); 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()); 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()); 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())) { if (newDmp.getProject() != null && newDmp.getGrant() != null && (newDmp.getProject().getLabel() == null || newDmp.getProject().getLabel().trim().isEmpty())) {
newDmp.setProject(newDmp.getProject().projectFromGrant(newDmp.getGrant())); newDmp.setProject(newDmp.getProject().projectFromGrant(newDmp.getGrant()));
} }
@ -807,19 +824,19 @@ public class DataManagementPlanManager {
newDmp.setVersion(0); newDmp.setVersion(0);
newDmp.setId(null); 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())) { if (newDmp.getGrant() != null && newDmp.getGrant().getType().equals(Grant.GrantType.INTERNAL.getValue())) {
checkIfUserCanEditGrant(newDmp, user); checkIfUserCanEditGrant(newDmp, user);
} }
assignGrandUserIfInternal(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); assignFunderUserIfInternal(newDmp, user);
} }
if(this.dataManagementProfileManager.fieldInBlueprint(newDmp.getProfile(), SystemFieldType.PROJECT, principal)) { if(this.dataManagementProfileManager.fieldInBlueprint(newDmp.getProfile(), SystemFieldType.PROJECT)) {
assignProjectUserIfInternal(newDmp, user); 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() != null) {
databaseRepository.getGrantDao().createOrUpdate(newDmp.getGrant()); databaseRepository.getGrantDao().createOrUpdate(newDmp.getGrant());
} }
@ -847,7 +864,7 @@ public class DataManagementPlanManager {
return newDmp.getId(); return newDmp.getId();
} }
public void delete(UUID uuid) throws DMPWithDatasetsDeleteException, IOException { public void delete(UUID uuid) throws DMPWithDatasetsDeleteException, IOException, InvalidApplicationException {
DatasetCriteria criteria = new DatasetCriteria(); DatasetCriteria criteria = new DatasetCriteria();
List<UUID> dmpIds = Collections.singletonList(uuid); List<UUID> dmpIds = Collections.singletonList(uuid);
criteria.setDmpIds(dmpIds); criteria.setDmpIds(dmpIds);
@ -881,7 +898,7 @@ public class DataManagementPlanManager {
UUID tdmpId = dmp.getId(); 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())); dmp.setUsers(new HashSet<>(apiContext.getOperationsContext().getDatabaseRepository().getUserDmpDao().asQueryable().where((builder, root) -> builder.equal(root.get("dmp").get("id"), tdmpId)).toList()));
this.updateIndex(dmp); this.updateIndex(dmp);
} catch (IOException e) { } catch (IOException | InvalidApplicationException e) {
logger.error(e.getMessage(), e); logger.error(e.getMessage(), e);
} }
for (Dataset dataset: dmp.getDataset()) { 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()) { if (newDmp.getResearchers() != null && !newDmp.getResearchers().isEmpty()) {
for (eu.eudat.data.old.Researcher researcher : newDmp.getResearchers()) { for (eu.eudat.data.old.Researcher researcher : newDmp.getResearchers()) {
ResearcherCriteria criteria = new ResearcherCriteria(); 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()) { if (newDmp.getOrganisations() != null && !newDmp.getOrganisations().isEmpty()) {
for (Organisation organisation : newDmp.getOrganisations()) { for (Organisation organisation : newDmp.getOrganisations()) {
boolean createNew = false; 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) { if (newDmp.getGrant() != null) {
Grant grant = newDmp.getGrant(); Grant grant = newDmp.getGrant();
GrantCriteria criteria = new GrantCriteria(); 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) { if (newDmp.getGrant() != null && newDmp.getGrant().getFunder() != null) {
Funder funder = newDmp.getGrant().getFunder(); Funder funder = newDmp.getGrant().getFunder();
FunderCriteria criteria = new FunderCriteria(); 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) { if (newDmp.getProject() != null) {
Project project = newDmp.getProject(); Project project = newDmp.getProject();
ProjectCriteria criteria = new ProjectCriteria(); ProjectCriteria criteria = new ProjectCriteria();
@ -1013,7 +1030,7 @@ public class DataManagementPlanManager {
metricsManager.increaseValue(MetricNames.PROJECT, 1, null); 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<>(); List<CompletableFuture<Dataset>> futures = new LinkedList<>();
for (Dataset dataset : newDmp.getDataset()) { for (Dataset dataset : newDmp.getDataset()) {
Dataset tempDataset = datasetDao.find(dataset.getId()); Dataset tempDataset = datasetDao.find(dataset.getId());
@ -1092,7 +1109,7 @@ public class DataManagementPlanManager {
datasetElastic.setStatus(dataset1.getStatus()); datasetElastic.setStatus(dataset1.getStatus());
datasetElastic.setDmp(dataset1.getDmp().getId()); datasetElastic.setDmp(dataset1.getDmp().getId());
datasetElastic.setGroup(dataset1.getDmp().getGroupId()); 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()); datasetElastic.setGrant(dataset1.getDmp().getGrant().getId());
} }
if (dataset1.getDmp().getUsers() != null) { if (dataset1.getDmp().getUsers() != null) {
@ -1115,7 +1132,7 @@ public class DataManagementPlanManager {
}).collect(Collectors.toList())); }).collect(Collectors.toList()));
} }
datasetElastic.setPublic(dataset1.getDmp().isPublic()); 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()); 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); DMP dmp = this.apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().find(id);
// Check if dmp is finalized and if user is owner. // 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."); throw new Exception("User does not have the privilege to do this action.");
if (!dmp.getStatus().equals(DMP.DMPStatus.FINALISED.getValue())) if (!dmp.getStatus().equals(DMP.DMPStatus.FINALISED.getValue()))
throw new Exception("DMP is not finalized"); 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); sendNotification(dmp, user, NotificationType.DMP_PUBLISH);
} }
@Transactional @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); 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."); throw new Exception("User does not have the privilege to do this action.");
if (dmp.getStatus().equals(DMP.DMPStatus.FINALISED.getValue())) if (dmp.getStatus().equals(DMP.DMPStatus.FINALISED.getValue()))
throw new Exception("DMP is already finalized"); throw new Exception("DMP is already finalized");
@ -1194,7 +1211,7 @@ public class DataManagementPlanManager {
wizardModel = wizardModel.fromDataModel(dataset); wizardModel = wizardModel.fromDataModel(dataset);
wizardModel.setDatasetProfileDefinition(this.datasetManager.getPagedProfile(wizardModel, dataset)); wizardModel.setDatasetProfileDefinition(this.datasetManager.getPagedProfile(wizardModel, dataset));
try { try {
datasetManager.createOrUpdate(wizardModel, principal); datasetManager.createOrUpdate(wizardModel);
} catch (Exception e) { } catch (Exception e) {
dataset.setStatus(status.getValue()); dataset.setStatus(status.getValue());
dataset.setFinalizedAt(finalizedDate); dataset.setFinalizedAt(finalizedDate);
@ -1247,7 +1264,7 @@ public class DataManagementPlanManager {
UUID dmpId = dmp.getId(); 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())); dmp.setUsers(new HashSet<>(apiContext.getOperationsContext().getDatabaseRepository().getUserDmpDao().asQueryable().where((builder, root) -> builder.equal(root.get("dmp").get("id"), dmpId)).toList()));
this.updateIndex(dmp); 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); sendNotification(dmp, user, NotificationType.DMP_FINALISED);
metricsManager.decreaseValue(MetricNames.DMP, 1, MetricNames.DRAFT); metricsManager.decreaseValue(MetricNames.DMP, 1, MetricNames.DRAFT);
metricsManager.increaseValue(MetricNames.DMP, 1, MetricNames.FINALIZED); metricsManager.increaseValue(MetricNames.DMP, 1, MetricNames.FINALIZED);
@ -1256,9 +1273,9 @@ public class DataManagementPlanManager {
metricsManager.increaseValue(MetricNames.DATASET, indexDatasets.size(), MetricNames.FINALIZED); 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); 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."); throw new Exception("User does not have the privilege to do this action.");
if (dmp.getStatus().equals(DMP.DMPStatus.ACTIVE.getValue())) if (dmp.getStatus().equals(DMP.DMPStatus.ACTIVE.getValue()))
throw new Exception("DMP is already Active"); throw new Exception("DMP is already Active");
@ -1275,9 +1292,9 @@ public class DataManagementPlanManager {
metricsManager.increaseValue(MetricNames.DMP, 1, MetricNames.DRAFT); 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); 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."); throw new Exception("User does not have the privilege to do this action.");
clearUsers(dmp); clearUsers(dmp);
for (UserInfoListingModel userListing : users) { for (UserInfoListingModel userListing : users) {
@ -1291,18 +1308,18 @@ public class DataManagementPlanManager {
* Export Data * Export Data
* */ * */
public FileEnvelope getWordDocument(String id, Principal principal, ConfigLoader configLoader) throws IOException { public FileEnvelope getWordDocument(String id, ConfigLoader configLoader) throws IOException, InvalidApplicationException {
return this.getWordDocument(id, principal, configLoader, true); 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); WordBuilder wordBuilder = new WordBuilder(this.environment, configLoader);
VisibilityRuleService visibilityRuleService = new VisibilityRuleServiceImpl(); VisibilityRuleService visibilityRuleService = new VisibilityRuleServiceImpl();
DatasetWizardModel dataset = new DatasetWizardModel(); DatasetWizardModel dataset = new DatasetWizardModel();
XWPFDocument document = configLoader.getDocument(); XWPFDocument document = configLoader.getDocument();
DMP dmpEntity = databaseRepository.getDmpDao().find(UUID.fromString(id)); 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(); throw new UnauthorisedException();
wordBuilder.fillFirstPage(dmpEntity, null, document, false); wordBuilder.fillFirstPage(dmpEntity, null, document, false);
@ -1678,11 +1695,11 @@ public class DataManagementPlanManager {
return exportEnvelope; 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(); ExportXmlBuilder xmlBuilder = new ExportXmlBuilder();
VisibilityRuleService visibilityRuleService = new VisibilityRuleServiceImpl(); VisibilityRuleService visibilityRuleService = new VisibilityRuleServiceImpl();
DMP dmp = databaseRepository.getDmpDao().find(UUID.fromString(id)); 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(); throw new UnauthorisedException();
final Boolean isFinalized = dmp.getStatus() == DMP.DMPStatus.FINALISED.getValue(); final Boolean isFinalized = dmp.getStatus() == DMP.DMPStatus.FINALISED.getValue();
final Boolean isPublic = dmp.isPublic(); final Boolean isPublic = dmp.isPublic();
@ -1772,7 +1789,7 @@ public class DataManagementPlanManager {
// Funder. // Funder.
Element funder = xmlDoc.createElement("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 funderLabel = xmlDoc.createElement("label");
Element funderId = xmlDoc.createElement("id"); Element funderId = xmlDoc.createElement("id");
funderLabel.setTextContent(dmp.getGrant().getFunder().getLabel()); funderLabel.setTextContent(dmp.getGrant().getFunder().getLabel());
@ -1790,7 +1807,7 @@ public class DataManagementPlanManager {
dmpElement.appendChild(funder); dmpElement.appendChild(funder);
// Grant. // Grant.
Element grant = xmlDoc.createElement("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 grantLabel = xmlDoc.createElement("label");
Element grantId = xmlDoc.createElement("id"); Element grantId = xmlDoc.createElement("id");
grantLabel.setTextContent(dmp.getGrant().getLabel()); grantLabel.setTextContent(dmp.getGrant().getLabel());
@ -1808,7 +1825,7 @@ public class DataManagementPlanManager {
dmpElement.appendChild(grant); dmpElement.appendChild(grant);
// Project. // Project.
Element project = xmlDoc.createElement("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 projectId = xmlDoc.createElement("id");
Element projectLabel = xmlDoc.createElement("label"); Element projectLabel = xmlDoc.createElement("label");
Element projectDescription = xmlDoc.createElement("description"); Element projectDescription = xmlDoc.createElement("description");
@ -1855,7 +1872,7 @@ public class DataManagementPlanManager {
Element extraFields = xmlDoc.createElement("extraFields"); Element extraFields = xmlDoc.createElement("extraFields");
Map<String, Object> dmpProperties = new ObjectMapper().readValue(dmp.getProperties(), new TypeReference<Map<String, Object>>() {}); 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 -> { blueprint.getSections().forEach(section -> {
section.getFields().forEach(fieldModel -> { section.getFields().forEach(fieldModel -> {
if (fieldModel.getCategory() == FieldCategory.EXTRA) { if (fieldModel.getCategory() == FieldCategory.EXTRA) {
@ -1958,9 +1975,9 @@ public class DataManagementPlanManager {
return fileEnvelope; 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)); 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(); throw new UnauthorisedException();
final boolean isFinalized = dmp.getStatus() == DMP.DMPStatus.FINALISED.getValue(); final boolean isFinalized = dmp.getStatus() == DMP.DMPStatus.FINALISED.getValue();
final boolean isPublic = dmp.isPublic(); final boolean isPublic = dmp.isPublic();
@ -1996,17 +2013,17 @@ public class DataManagementPlanManager {
return rdaJsonDocument; 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; FileEnvelope file;
switch (contentType) { switch (contentType) {
case "application/xml": case "application/xml":
file = getXmlDocument(id, principal); file = getXmlDocument(id);
break; break;
case "application/msword": case "application/msword":
file = getWordDocument(id, principal, configLoader); file = getWordDocument(id, configLoader);
break; break;
default: default:
file = getXmlDocument(id, principal); file = getXmlDocument(id);
} }
String fileName = file.getFilename().replace(" ", "_").replace(",", "_"); String fileName = file.getFilename().replace(" ", "_").replace(",", "_");
InputStream resource = new FileInputStream(file.getFile()); InputStream resource = new FileInputStream(file.getFile());
@ -2029,7 +2046,7 @@ public class DataManagementPlanManager {
* Data Import * 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<>(); List<DmpImportModel> dataManagementPlans = new ArrayList<>();
// Jaxb approach. // Jaxb approach.
JAXBContext jaxbContext; JAXBContext jaxbContext;
@ -2070,7 +2087,7 @@ public class DataManagementPlanManager {
} }
dm.setProperties(dmpPropertiesMap); 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(); eu.eudat.models.data.funder.Funder funder = new eu.eudat.models.data.funder.Funder();
FunderImportModels funderImport = dataManagementPlans.get(0).getFunderImportModels(); FunderImportModels funderImport = dataManagementPlans.get(0).getFunderImportModels();
funder.setId(funderImport.getId()); funder.setId(funderImport.getId());
@ -2081,7 +2098,7 @@ public class DataManagementPlanManager {
dm.setFunder(funderEditor); 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(); eu.eudat.models.data.grant.Grant grant = new eu.eudat.models.data.grant.Grant();
GrantImportModels grantImport = dataManagementPlans.get(0).getGrantImport(); GrantImportModels grantImport = dataManagementPlans.get(0).getGrantImport();
grant.setId(grantImport.getId()); grant.setId(grantImport.getId());
@ -2094,7 +2111,7 @@ public class DataManagementPlanManager {
dm.setGrant(grantEditor); 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(); eu.eudat.models.data.project.Project project = new eu.eudat.models.data.project.Project();
ProjectImportModels projectImport = dataManagementPlans.get(0).getProjectImportModels(); ProjectImportModels projectImport = dataManagementPlans.get(0).getProjectImportModels();
project.setId(projectImport.getId()); project.setId(projectImport.getId());
@ -2175,7 +2192,7 @@ public class DataManagementPlanManager {
dm.setExtraProperties(extraPropertiesMap); dm.setExtraProperties(extraPropertiesMap);
//createOrUpdate(apiContext, dm, principal); //createOrUpdate(apiContext, dm, principal);
DMP dmp = this.createOrUpdate(dm, principal); DMP dmp = this.createOrUpdate(dm);
if (dmp.getOrganisations() == null) { if (dmp.getOrganisations() == null) {
dmp.setOrganisations(new HashSet<>()); dmp.setOrganisations(new HashSet<>());
} }
@ -2212,7 +2229,7 @@ public class DataManagementPlanManager {
DatasetWizardModel datasetWizard = new DatasetWizardModel(); DatasetWizardModel datasetWizard = new DatasetWizardModel();
datasetWizard.setDatasetProfileDefinition(this.datasetManager.getPagedProfile(datasetWizard, dataset)); datasetWizard.setDatasetProfileDefinition(this.datasetManager.getPagedProfile(datasetWizard, dataset));
datasetWizard.fromDataModel(dataset); datasetWizard.fromDataModel(dataset);
this.datasetManager.createOrUpdate(datasetWizard, principal); this.datasetManager.createOrUpdate(datasetWizard);
// datasets.add(new DatasetListingModel().fromDataModel(dataset)); // datasets.add(new DatasetListingModel().fromDataModel(dataset));
} }
} }
@ -2220,15 +2237,15 @@ public class DataManagementPlanManager {
return dataManagementPlans; return dataManagementPlans;
} }
public List<DMP> createFromRDA(MultipartFile[] files, Principal principal, String[] profiles) throws IOException { public List<DMP> createFromRDA(MultipartFile[] files, String[] profiles) throws IOException, InvalidApplicationException {
if (principal.getId() == null) { if (!this.userScope.isSet()) {
throw new UnauthorisedException("No user is logged in"); throw new UnauthorisedException("No user is logged in");
} }
List<DMP> result = new ArrayList<>(); List<DMP> result = new ArrayList<>();
for (MultipartFile file: files) { for (MultipartFile file: files) {
DMP dmp = rdaManager.convertToEntity(new String(file.getBytes(), "UTF-8"), profiles); DMP dmp = rdaManager.convertToEntity(new String(file.getBytes(), "UTF-8"), profiles);
dmp.setLabel(file.getOriginalFilename()); 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.setModified(new Date());
dmp.setCreator(me); dmp.setCreator(me);
Map<String, String> extraProperties = objectMapper.readValue(dmp.getExtraProperties(), HashMap.class); Map<String, String> extraProperties = objectMapper.readValue(dmp.getExtraProperties(), HashMap.class);
@ -2269,7 +2286,11 @@ public class DataManagementPlanManager {
if (dmp.getResearchers() == null) { if (dmp.getResearchers() == null) {
dmp.setResearchers(new HashSet<>()); dmp.setResearchers(new HashSet<>());
} }
try {
dmp.setUsers(new HashSet<>(apiContext.getOperationsContext().getDatabaseRepository().getUserDmpDao().asQueryable().where((builder, root) -> builder.equal(root.get("dmp").get("id"), dmp.getId())).toList())); 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 { try {
List<Tag> tags = new ArrayList<>(); List<Tag> tags = new ArrayList<>();
eu.eudat.elastic.entities.Dataset elastic = apiContext.getOperationsContext().getElasticRepository().getDatasetRepository().findDocument(dataset.getId().toString()); 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); 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(); 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)); userDMPs.forEach(userDMP -> apiContext.getOperationsContext().getDatabaseRepository().getUserDmpDao().delete(userDMP));
} }
@ -2333,7 +2354,7 @@ public class DataManagementPlanManager {
* Data Index * Data Index
* */ * */
private void updateGroupIndex(UUID groupId) { private void updateGroupIndex(UUID groupId) throws InvalidApplicationException {
DataManagementPlanCriteria criteria = new DataManagementPlanCriteria(); DataManagementPlanCriteria criteria = new DataManagementPlanCriteria();
criteria.setGroupIds(Collections.singletonList(groupId)); criteria.setGroupIds(Collections.singletonList(groupId));
criteria.setAllVersions(true); 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())); dmp.setUsers(new HashSet<>(apiContext.getOperationsContext().getDatabaseRepository().getUserDmpDao().asQueryable().where((builder, root) -> builder.equal(root.get("dmp").get("id"), dmpId)).toList()));
} }
this.updateIndex(dmp); this.updateIndex(dmp);
} catch (IOException e) { } catch (IOException | InvalidApplicationException e) {
logger.error(e.getMessage(), 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); DmpMapper mapper = new DmpMapper(apiContext, datasetManager);
Dmp elastic = mapper.toElastic(dmp); Dmp elastic = mapper.toElastic(dmp);
apiContext.getOperationsContext().getElasticRepository().getDmpRepository().createOrUpdate(elastic); apiContext.getOperationsContext().getElasticRepository().getDmpRepository().createOrUpdate(elastic);
} }
public void generateIndex(Principal principal) { public void generateIndex() throws InvalidApplicationException {
if (principal.getAuthorities().contains(Authorities.ADMIN.getValue())) { if (this.authorizationService.authorize(Permission.AdminRole)) {
if (apiContext.getOperationsContext().getElasticRepository().getDmpRepository().createIndex()) { if (apiContext.getOperationsContext().getElasticRepository().getDmpRepository().createIndex()) {
List<DMP> dmps = apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().asQueryable().toList(); List<DMP> dmps = apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().asQueryable().toList();
dmps.forEach(dmp -> { dmps.forEach(dmp -> {
@ -2385,7 +2406,7 @@ public class DataManagementPlanManager {
UUID dmpId = dmp.getId(); 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())); dmp.setUsers(new HashSet<>(apiContext.getOperationsContext().getDatabaseRepository().getUserDmpDao().asQueryable().where((builder, root) -> builder.equal(root.get("dmp").get("id"), dmpId)).toList()));
this.updateIndex(dmp); this.updateIndex(dmp);
} catch (IOException e) { } catch (IOException | InvalidApplicationException e) {
logger.error(e.getMessage(), e); logger.error(e.getMessage(), e);
} }
}); });
@ -2393,8 +2414,8 @@ public class DataManagementPlanManager {
} }
} }
public void clearIndex(Principal principal) throws IOException { public void clearIndex() throws IOException {
if (principal.getAuthorities().contains(Authorities.ADMIN.getValue())) { if (this.authorizationService.authorize(Permission.AdminRole)) {
apiContext.getOperationsContext().getElasticRepository().getDmpRepository().clear(); apiContext.getOperationsContext().getElasticRepository().getDmpRepository().clear();
} }
} }
@ -2430,15 +2451,15 @@ public class DataManagementPlanManager {
} }
} }
private boolean isUserOwnerOfDmp(DMP dmp, Principal principal) { private boolean isUserOwnerOfDmp(DMP dmp) throws InvalidApplicationException {
return (dmp.getUsers().stream().filter(userDMP -> userDMP.getRole().equals(UserDMP.UserDMPRoles.OWNER.getValue())).map(userDMP -> userDMP.getUser().getId())).collect(Collectors.toList()).contains(principal.getId()); 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 * 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(); DataManagementPlanCriteria criteria = new DataManagementPlanCriteria();
List<UUID> groupIds = new ArrayList<>(); List<UUID> groupIds = new ArrayList<>();
groupIds.add(groupId); groupIds.add(groupId);
@ -2462,16 +2483,16 @@ public class DataManagementPlanManager {
return null; 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())); 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"); throw new Exception("User is not authorized to invoke this action");
if (!dmp.getStatus().equals(DMP.DMPStatus.FINALISED.getValue())) if (!dmp.getStatus().equals(DMP.DMPStatus.FINALISED.getValue()))
throw new Exception("DMP is not finalized"); throw new Exception("DMP is not finalized");
/*if (dmp.getDoi() != null) /*if (dmp.getDoi() != null)
throw new Exception("DMP already has a DOI");*/ 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(",", "_"); String name = file.getFilename().substring(0, file.getFilename().length() - 5).replaceAll("[^a-zA-Z0-9_+ ]", "").replace(" ", "_").replace(",", "_");
File pdfFile = PDFUtils.convertToPDF(file, environment); File pdfFile = PDFUtils.convertToPDF(file, environment);
eu.eudat.depositinterface.models.FileEnvelope pdfEnvelope = new eu.eudat.depositinterface.models.FileEnvelope(); eu.eudat.depositinterface.models.FileEnvelope pdfEnvelope = new eu.eudat.depositinterface.models.FileEnvelope();
@ -2479,7 +2500,7 @@ public class DataManagementPlanManager {
pdfEnvelope.setFilename(name + ".pdf"); pdfEnvelope.setFilename(name + ".pdf");
eu.eudat.depositinterface.models.FileEnvelope rdaJsonFile = new eu.eudat.depositinterface.models.FileEnvelope(); eu.eudat.depositinterface.models.FileEnvelope rdaJsonFile = new eu.eudat.depositinterface.models.FileEnvelope();
try { try {
FileEnvelope rdaJsonDocument = getRDAJsonDocument(depositRequest.getDmpId(), principal); FileEnvelope rdaJsonDocument = getRDAJsonDocument(depositRequest.getDmpId());
rdaJsonFile.setFile(rdaJsonDocument.getFile()); rdaJsonFile.setFile(rdaJsonDocument.getFile());
rdaJsonFile.setFilename(rdaJsonDocument.getFilename()); rdaJsonFile.setFilename(rdaJsonDocument.getFilename());
} catch (Exception e) { } 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"); FileOutputStream fout = new FileOutputStream(this.environment.getProperty("temp.temp") + "supportingFiles.zip");
ZipOutputStream zout = new ZipOutputStream(fout); ZipOutputStream zout = new ZipOutputStream(fout);
@ -2565,7 +2586,7 @@ public class DataManagementPlanManager {
* Misc * 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(); List<UserDMP> userDMPS = databaseRepository.getUserDmpDao().asQueryable().where(((builder, root) -> builder.equal(root.get("dmp").get("id"), dmp.getId()))).toList();
for (UserDMP userDMP : userDMPS) { for (UserDMP userDMP : userDMPS) {
if (!userDMP.getUser().getId().equals(user.getId())) { 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.helpers.common.DataTableData;
import eu.eudat.models.data.listingmodels.DataManagementPlanBlueprintListingModel; import eu.eudat.models.data.listingmodels.DataManagementPlanBlueprintListingModel;
import eu.eudat.models.data.listingmodels.DataManagementPlanProfileListingModel; import eu.eudat.models.data.listingmodels.DataManagementPlanProfileListingModel;
import eu.eudat.models.data.security.Principal;
import eu.eudat.queryable.QueryableList; import eu.eudat.queryable.QueryableList;
import eu.eudat.logic.services.ApiContext; import eu.eudat.logic.services.ApiContext;
import org.slf4j.Logger; import org.slf4j.Logger;
@ -33,6 +32,8 @@ import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import jakarta.activation.MimetypesFileTypeMap; import jakarta.activation.MimetypesFileTypeMap;
import javax.management.InvalidApplicationException;
import javax.xml.xpath.*; import javax.xml.xpath.*;
import java.io.*; import java.io.*;
import java.nio.file.Files; import java.nio.file.Files;
@ -63,7 +64,7 @@ public class DataManagementProfileManager {
this.environment = environment; 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> items = apiContext.getOperationsContext().getDatabaseRepository().getDmpProfileDao().getWithCriteria(dataManagementPlanProfileTableRequest.getCriteria());
QueryableList<DMPProfile> pagedItems = PaginationManager.applyPaging(items, dataManagementPlanProfileTableRequest); QueryableList<DMPProfile> pagedItems = PaginationManager.applyPaging(items, dataManagementPlanProfileTableRequest);
@ -82,7 +83,7 @@ public class DataManagementProfileManager {
return dataTable; 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> items = apiContext.getOperationsContext().getDatabaseRepository().getDmpProfileDao().getWithCriteriaBlueprint(dataManagementPlanBlueprintTableRequest.getCriteria());
QueryableList<DMPProfile> pagedItems = PaginationManager.applyPaging(items, dataManagementPlanBlueprintTableRequest); QueryableList<DMPProfile> pagedItems = PaginationManager.applyPaging(items, dataManagementPlanBlueprintTableRequest);
@ -96,26 +97,26 @@ public class DataManagementProfileManager {
return dataTable; 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)); DMPProfile dmpProfile = databaseRepository.getDmpProfileDao().find(UUID.fromString(id));
DataManagementPlanProfileListingModel dataManagementPlanProfileListingModel = new DataManagementPlanProfileListingModel(); DataManagementPlanProfileListingModel dataManagementPlanProfileListingModel = new DataManagementPlanProfileListingModel();
dataManagementPlanProfileListingModel.fromDataModel(dmpProfile); dataManagementPlanProfileListingModel.fromDataModel(dmpProfile);
return dataManagementPlanProfileListingModel; return dataManagementPlanProfileListingModel;
} }
public DataManagementPlanBlueprintListingModel getSingleBlueprint(String id, Principal principal) { public DataManagementPlanBlueprintListingModel getSingleBlueprint(String id) throws InvalidApplicationException {
DMPProfile dmpProfile = databaseRepository.getDmpProfileDao().find(UUID.fromString(id)); DMPProfile dmpProfile = databaseRepository.getDmpProfileDao().find(UUID.fromString(id));
DataManagementPlanBlueprintListingModel dataManagementPlanBlueprintListingModel = new DataManagementPlanBlueprintListingModel(); DataManagementPlanBlueprintListingModel dataManagementPlanBlueprintListingModel = new DataManagementPlanBlueprintListingModel();
dataManagementPlanBlueprintListingModel.fromDataModel(dmpProfile); dataManagementPlanBlueprintListingModel.fromDataModel(dmpProfile);
return dataManagementPlanBlueprintListingModel; 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)); 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(); DataManagementPlanBlueprintListingModel dmpBlueprint = new DataManagementPlanBlueprintListingModel();
dmpBlueprint.fromDataModel(dmpProfile); dmpBlueprint.fromDataModel(dmpProfile);
for(Section section: dmpBlueprint.getDefinition().getSections()){ for(Section section: dmpBlueprint.getDefinition().getSections()){
@ -131,23 +132,23 @@ public class DataManagementProfileManager {
return false; 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()); QueryableList<DMPProfile> items = databaseRepository.getDmpProfileDao().getWithCriteria(dataManagementPlanProfileCriteriaRequest.getCriteria());
List<DataManagementPlanProfileListingModel> datamanagementPlans = items.select(item -> new DataManagementPlanProfileListingModel().fromDataModel(item)); List<DataManagementPlanProfileListingModel> datamanagementPlans = items.select(item -> new DataManagementPlanProfileListingModel().fromDataModel(item));
return datamanagementPlans; return datamanagementPlans;
} }
public void createOrUpdate(DataManagementPlanProfileListingModel dataManagementPlanProfileListingModel, Principal principal) throws Exception { public void createOrUpdate(DataManagementPlanProfileListingModel dataManagementPlanProfileListingModel) throws Exception {
DMPProfile dmpProfile = dataManagementPlanProfileListingModel.toDataModel(); DMPProfile dmpProfile = dataManagementPlanProfileListingModel.toDataModel();
apiContext.getOperationsContext().getDatabaseRepository().getDmpProfileDao().createOrUpdate(dmpProfile); 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(); DMPProfile dmpProfile = dataManagementPlanBlueprintListingModel.toDataModel();
apiContext.getOperationsContext().getDatabaseRepository().getDmpProfileDao().createOrUpdate(dmpProfile); 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)); DMPProfile dmpProfile = databaseRepository.getDmpProfileDao().find(UUID.fromString(id));
DataManagementPlanCriteria dataManagementPlanCriteria = new DataManagementPlanCriteria(); DataManagementPlanCriteria dataManagementPlanCriteria = new DataManagementPlanCriteria();
dataManagementPlanCriteria.setProfile(dmpProfile); dataManagementPlanCriteria.setProfile(dmpProfile);
@ -208,7 +209,7 @@ public class DataManagementProfileManager {
return convFile; 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())); DMPProfile dmpProfile = this.apiContext.getOperationsContext().getDatabaseRepository().getDmpProfileDao().find(UUID.fromString(lookupItem.getCriteria().getProfileID()));
Field field = this.queryForField(dmpProfile.getDefinition(), lookupItem.getCriteria().getFieldID()); Field field = this.queryForField(dmpProfile.getDefinition(), lookupItem.getCriteria().getFieldID());
DmpProfileExternalAutoComplete data = field.getExternalAutocomplete(); 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.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import eu.eudat.commons.scope.user.UserScope;
import eu.eudat.data.dao.criteria.DataRepositoryCriteria; import eu.eudat.data.dao.criteria.DataRepositoryCriteria;
import eu.eudat.data.old.DataRepository; import eu.eudat.data.old.DataRepository;
import eu.eudat.logic.proxy.config.ExternalUrlCriteria; 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.proxy.config.exceptions.NoURLFound;
import eu.eudat.logic.services.ApiContext; import eu.eudat.logic.services.ApiContext;
import eu.eudat.models.data.datarepository.DataRepositoryModel; import eu.eudat.models.data.datarepository.DataRepositoryModel;
import eu.eudat.models.data.security.Principal;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import javax.management.InvalidApplicationException;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@ -24,25 +25,27 @@ import java.util.stream.Collectors;
@Component @Component
public class DataRepositoryManager { public class DataRepositoryManager {
private ApiContext apiContext; private ApiContext apiContext;
private UserScope userScope;
@Autowired @Autowired
public DataRepositoryManager(ApiContext apiContext) { public DataRepositoryManager(ApiContext apiContext, UserScope userScope) {
this.apiContext = apiContext; 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 dataRepository = dataRepositoryModel.toDataModel();
dataRepository.getCreationUser().setId(principal.getId()); dataRepository.getCreationUser().setId(userScope.getUserId());
return apiContext.getOperationsContext().getDatabaseRepository().getDataRepositoryDao().createOrUpdate(dataRepository); 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); ExternalUrlCriteria externalUrlCriteria = new ExternalUrlCriteria(query);
List<Map<String, String>> remoteRepos = this.apiContext.getOperationsContext().getRemoteFetcher().getRepositories(externalUrlCriteria, type); List<Map<String, String>> remoteRepos = this.apiContext.getOperationsContext().getRemoteFetcher().getRepositories(externalUrlCriteria, type);
DataRepositoryCriteria criteria = new DataRepositoryCriteria(); DataRepositoryCriteria criteria = new DataRepositoryCriteria();
if (!query.isEmpty()) criteria.setLike(query); if (!query.isEmpty()) criteria.setLike(query);
criteria.setCreationUserId(principal.getId()); criteria.setCreationUserId(userScope.getUserId());
List<DataRepositoryModel> dataRepositoryModels = new LinkedList<>(); List<DataRepositoryModel> dataRepositoryModels = new LinkedList<>();
if (type.equals("")) { if (type.equals("")) {
@ -55,13 +58,13 @@ public class DataRepositoryManager {
return dataRepositoryModels; 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); ExternalUrlCriteria externalUrlCriteria = new ExternalUrlCriteria(query);
List<Map<String, String>> remoteRepos = this.apiContext.getOperationsContext().getRemoteFetcher().getPubRepositories(externalUrlCriteria, type); List<Map<String, String>> remoteRepos = this.apiContext.getOperationsContext().getRemoteFetcher().getPubRepositories(externalUrlCriteria, type);
DataRepositoryCriteria criteria = new DataRepositoryCriteria(); DataRepositoryCriteria criteria = new DataRepositoryCriteria();
if (!query.isEmpty()) criteria.setLike(query); if (!query.isEmpty()) criteria.setLike(query);
criteria.setCreationUserId(principal.getId()); criteria.setCreationUserId(userScope.getUserId());
List<DataRepositoryModel> dataRepositoryModels = new LinkedList<>(); List<DataRepositoryModel> dataRepositoryModels = new LinkedList<>();
if (type.equals("")) { if (type.equals("")) {
@ -74,13 +77,13 @@ public class DataRepositoryManager {
return dataRepositoryModels; 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); ExternalUrlCriteria externalUrlCriteria = new ExternalUrlCriteria(query);
List<Map<String, String>> remoteRepos = this.apiContext.getOperationsContext().getRemoteFetcher().getJournals(externalUrlCriteria, type); List<Map<String, String>> remoteRepos = this.apiContext.getOperationsContext().getRemoteFetcher().getJournals(externalUrlCriteria, type);
DataRepositoryCriteria criteria = new DataRepositoryCriteria(); DataRepositoryCriteria criteria = new DataRepositoryCriteria();
if (!query.isEmpty()) criteria.setLike(query); if (!query.isEmpty()) criteria.setLike(query);
criteria.setCreationUserId(principal.getId()); criteria.setCreationUserId(userScope.getUserId());
List<DataRepositoryModel> dataRepositoryModels = new LinkedList<>(); List<DataRepositoryModel> dataRepositoryModels = new LinkedList<>();
if (type.equals("")) { 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.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper; 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.criteria.*;
import eu.eudat.data.dao.entities.DataRepositoryDao; import eu.eudat.data.dao.entities.DataRepositoryDao;
import eu.eudat.data.dao.entities.DatasetDao; 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.dmp.DataManagementPlan;
import eu.eudat.models.data.helpers.common.DataTableData; import eu.eudat.models.data.helpers.common.DataTableData;
import eu.eudat.models.data.listingmodels.DatasetListingModel; 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.models.data.user.composite.PagedDatasetProfile;
import eu.eudat.queryable.QueryableList; import eu.eudat.queryable.QueryableList;
import eu.eudat.types.Authorities; import eu.eudat.types.Authorities;
import eu.eudat.types.MetricNames; 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.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph; import org.apache.poi.xwpf.usermodel.XWPFParagraph;
@ -79,6 +81,8 @@ import jakarta.transaction.Transactional;
import jakarta.xml.bind.JAXBContext; import jakarta.xml.bind.JAXBContext;
import jakarta.xml.bind.JAXBException; import jakarta.xml.bind.JAXBException;
import jakarta.xml.bind.Unmarshaller; import jakarta.xml.bind.Unmarshaller;
import javax.management.InvalidApplicationException;
import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath; import javax.xml.xpath.XPath;
@ -111,10 +115,12 @@ public class DatasetManager {
private Environment environment; private Environment environment;
private final MetricsManager metricsManager; private final MetricsManager metricsManager;
private final FileManager fileManager; private final FileManager fileManager;
private final UserScope userScope;
private final AuthorizationService authorizationService;
@Autowired @Autowired
public DatasetManager(ApiContext apiContext, UserManager userManager, ConfigLoader configLoader, Environment environment, MetricsManager metricsManager, public DatasetManager(ApiContext apiContext, UserManager userManager, ConfigLoader configLoader, Environment environment, MetricsManager metricsManager,
FileManager fileManager) { FileManager fileManager, UserScope userScope, AuthorizationService authorizationService) {
this.apiContext = apiContext; this.apiContext = apiContext;
this.databaseRepository = apiContext.getOperationsContext().getDatabaseRepository(); this.databaseRepository = apiContext.getOperationsContext().getDatabaseRepository();
this.datasetRepository = apiContext.getOperationsContext().getElasticRepository().getDatasetRepository(); this.datasetRepository = apiContext.getOperationsContext().getElasticRepository().getDatasetRepository();
@ -124,9 +130,11 @@ public class DatasetManager {
this.environment = environment; this.environment = environment;
this.metricsManager = metricsManager; this.metricsManager = metricsManager;
this.fileManager = fileManager; 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 datasetCriteria = new DatasetCriteria();
datasetCriteria.setLike(datasetTableRequest.getCriteria().getLike()); datasetCriteria.setLike(datasetTableRequest.getCriteria().getLike());
datasetCriteria.setDatasetTemplates(datasetTableRequest.getCriteria().getDatasetTemplates()); datasetCriteria.setDatasetTemplates(datasetTableRequest.getCriteria().getDatasetTemplates());
@ -148,7 +156,7 @@ public class DatasetManager {
if (datasetCriteria.getCollaborators() == null) { if (datasetCriteria.getCollaborators() == null) {
datasetCriteria.setSortCriteria(new ArrayList<>()); datasetCriteria.setSortCriteria(new ArrayList<>());
} }
datasetCriteria.getCollaborators().add(principal.getId()); datasetCriteria.getCollaborators().add(this.userScope.getUserId());
} }
if (datasetTableRequest.getCriteria().getGrantStatus() != null) { if (datasetTableRequest.getCriteria().getGrantStatus() != null) {
datasetCriteria.setGrantStatus(datasetTableRequest.getCriteria().getGrantStatus()); datasetCriteria.setGrantStatus(datasetTableRequest.getCriteria().getGrantStatus());
@ -167,7 +175,7 @@ public class DatasetManager {
datasets = null; 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<eu.eudat.data.old.Dataset> items = databaseRepository.getDatasetDao().getWithCriteria(datasetTableRequest.getCriteria()).withHint(HintedModelFactory.getHint(DatasetListingModel.class));
QueryableList<Dataset> items; QueryableList<Dataset> items;
if (datasets != null) { if (datasets != null) {
@ -188,7 +196,7 @@ public class DatasetManager {
QueryableList<Dataset> pagedItems; QueryableList<Dataset> pagedItems;
QueryableList<Dataset> authItems; QueryableList<Dataset> authItems;
if (!datasetTableRequest.getCriteria().getIsPublic()) { if (!datasetTableRequest.getCriteria().getIsPublic()) {
if (principal.getId() == null) { if (this.userScope.getUserIdSafe() == null) {
throw new UnauthorisedException("You are not allowed to access those datasets"); throw new UnauthorisedException("You are not allowed to access those datasets");
} }
if (datasetTableRequest.getCriteria().getRole() != null) { if (datasetTableRequest.getCriteria().getRole() != null) {
@ -197,10 +205,10 @@ public class DatasetManager {
authItems = databaseRepository.getDatasetDao().getAuthenticated(items, userInfo, roles).distinct(); authItems = databaseRepository.getDatasetDao().getAuthenticated(items, userInfo, roles).distinct();
pagedItems = PaginationManager.applyPaging(authItems, datasetTableRequest); pagedItems = PaginationManager.applyPaging(authItems, datasetTableRequest);
} else { } else {
if (principal.getId() != null && datasetTableRequest.getCriteria().getRole() != null) { if (this.userScope.getUserIdSafe() != null && datasetTableRequest.getCriteria().getRole() != null) {
items.where((builder, root) -> { items.where((builder, root) -> {
Join userJoin = root.join("dmp", JoinType.LEFT).join("users", JoinType.LEFT); 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]; String[] strings = new String[1];
@ -220,7 +228,7 @@ public class DatasetManager {
return dataTable; return dataTable;
} }
public DataTableData<DatasetListingModel> getPaged(DatasetPublicTableRequest datasetTableRequest, Principal principal) throws Exception { public DataTableData<DatasetListingModel> getPaged(DatasetPublicTableRequest datasetTableRequest) throws Exception {
Long count = 0L; Long count = 0L;
DatasetCriteria datasetCriteria = new DatasetCriteria(); DatasetCriteria datasetCriteria = new DatasetCriteria();
datasetCriteria.setLike(datasetTableRequest.getCriteria().getLike()); datasetCriteria.setLike(datasetTableRequest.getCriteria().getLike());
@ -256,10 +264,10 @@ public class DatasetManager {
items = datasetTableRequest.applyCriteria(); items = datasetTableRequest.applyCriteria();
} }
if (principal.getId() != null && datasetTableRequest.getCriteria().getRole() != null) { if (this.userScope.isSet() && datasetTableRequest.getCriteria().getRole() != null) {
items.where((builder, root) -> { items.where((builder, root) -> {
Join userJoin = root.join("dmp", JoinType.LEFT).join("users", JoinType.LEFT); 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<>(); List<String> strings = new ArrayList<>();
@ -281,11 +289,11 @@ public class DatasetManager {
return dataTable; return dataTable;
} }
public DatasetWizardModel getSingle(String id, Principal principal) { public DatasetWizardModel getSingle(String id) throws InvalidApplicationException {
DatasetWizardModel dataset = new DatasetWizardModel(); DatasetWizardModel dataset = new DatasetWizardModel();
Dataset datasetEntity = databaseRepository.getDatasetDao().find(UUID.fromString(id), HintedModelFactory.getHint(DatasetWizardModel.class)); Dataset datasetEntity = databaseRepository.getDatasetDao().find(UUID.fromString(id), HintedModelFactory.getHint(DatasetWizardModel.class));
if (datasetEntity.getDmp().getUsers() 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()) .collect(Collectors.toList()).size() == 0 && !datasetEntity.getDmp().isPublic())
throw new UnauthorisedException(); throw new UnauthorisedException();
dataset.setDatasetProfileDefinition(getPagedProfile(dataset, datasetEntity)); 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)); Dataset datasetEntity = databaseRepository.getDatasetDao().find(UUID.fromString(id));
if (datasetEntity.getStatus() == Dataset.Status.DELETED.getValue()) { if (datasetEntity.getStatus() == Dataset.Status.DELETED.getValue()) {
throw new Exception("Dataset is deleted."); throw new Exception("Dataset is deleted.");
} }
if (!isPublic && principal == null) { if (!isPublic && !this.userScope.isSet()) {
throw new UnauthorisedException(); throw new UnauthorisedException();
} else } else
if (!isPublic && datasetEntity.getDmp().getUsers() 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(); throw new UnauthorisedException();
} else if (isPublic && !datasetEntity.getDmp().isPublic()) { } else if (isPublic && !datasetEntity.getDmp().isPublic()) {
throw new ForbiddenException("Selected Dataset is not public"); throw new ForbiddenException("Selected Dataset is not public");
@ -378,7 +386,7 @@ public class DatasetManager {
return dataset; return dataset;
} }
public Dataset getEntitySingle(UUID id) { public Dataset getEntitySingle(UUID id) throws InvalidApplicationException {
return databaseRepository.getDatasetDao().find(id); return databaseRepository.getDatasetDao().find(id);
} }
@ -395,14 +403,14 @@ public class DatasetManager {
return pagedDatasetProfile; 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); WordBuilder wordBuilder = new WordBuilder(this.environment, configLoader);
DatasetWizardModel dataset = new DatasetWizardModel(); DatasetWizardModel dataset = new DatasetWizardModel();
XWPFDocument document = configLoader.getDatasetDocument(); XWPFDocument document = configLoader.getDatasetDocument();
DMP dmpEntity = datasetEntity.getDmp(); 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(); throw new UnauthorisedException();
wordBuilder.fillFirstPage(dmpEntity, datasetEntity, document, true); wordBuilder.fillFirstPage(dmpEntity, datasetEntity, document, true);
@ -537,10 +545,10 @@ public class DatasetManager {
// return exportFile; // 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)); Dataset datasetEntity = databaseRepository.getDatasetDao().find(UUID.fromString(id), HintedModelFactory.getHint(DatasetWizardModel.class));
if (!datasetEntity.getDmp().isPublic() && datasetEntity.getDmp().getUsers() 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) .collect(Collectors.toList()).size() == 0)
throw new UnauthorisedException(); throw new UnauthorisedException();
String label = datasetEntity.getLabel().replaceAll("[^a-zA-Z0-9+ ]", ""); String label = datasetEntity.getLabel().replaceAll("[^a-zA-Z0-9+ ]", "");
@ -548,7 +556,7 @@ public class DatasetManager {
exportEnvelope.setFilename(label + ".docx"); exportEnvelope.setFilename(label + ".docx");
String uuid = UUID.randomUUID().toString(); String uuid = UUID.randomUUID().toString();
File exportFile = new File(this.environment.getProperty("temp.temp") + uuid + ".docx"); 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); FileOutputStream out = new FileOutputStream(exportFile);
document.write(out); document.write(out);
out.close(); out.close();
@ -564,12 +572,12 @@ public class DatasetManager {
return extractor.getText();/*.replaceAll("\n\\s*", " ");*/ 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(); ExportXmlBuilder xmlBuilder = new ExportXmlBuilder();
DatasetWizardModel dataset = new DatasetWizardModel(); DatasetWizardModel dataset = new DatasetWizardModel();
Dataset datasetEntity = databaseRepository.getDatasetDao().find(UUID.fromString(id), HintedModelFactory.getHint(DatasetWizardModel.class)); Dataset datasetEntity = databaseRepository.getDatasetDao().find(UUID.fromString(id), HintedModelFactory.getHint(DatasetWizardModel.class));
if (!datasetEntity.getDmp().isPublic() && datasetEntity.getDmp().getUsers() 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) .collect(Collectors.toList()).size() == 0)
throw new UnauthorisedException(); throw new UnauthorisedException();
Map<String, Object> properties = new HashMap<>(); Map<String, Object> properties = new HashMap<>();
@ -588,7 +596,7 @@ public class DatasetManager {
return fileEnvelope; return fileEnvelope;
} }
public Dataset createOrUpdate(DatasetWizardModel datasetWizardModel, Principal principal) throws Exception { public Dataset createOrUpdate(DatasetWizardModel datasetWizardModel) throws Exception {
Boolean sendNotification = false; Boolean sendNotification = false;
Dataset tempDataset = null; Dataset tempDataset = null;
DMP dmp = apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().find(datasetWizardModel.getDmp().getId()); 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."); 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); dataset.setCreator(userInfo);
createDataRepositoriesIfTheyDontExist(apiContext.getOperationsContext().getDatabaseRepository().getDataRepositoryDao(), dataset); createDataRepositoriesIfTheyDontExist(apiContext.getOperationsContext().getDatabaseRepository().getDataRepositoryDao(), dataset);
@ -651,7 +659,7 @@ public class DatasetManager {
return dataset1; 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 // Files in DB for this entityId which are NOT DELETED
List<FileUpload> fileUploads = fileManager.getCurrentFileUploadsForEntityId(datasetWizardModel.getId()); List<FileUpload> fileUploads = fileManager.getCurrentFileUploadsForEntityId(datasetWizardModel.getId());
List<String> fileUploadIds = fileUploads.stream().map(fileUpload -> fileUpload.getId().toString()).collect(Collectors.toList()); 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(); List<UserDMP> userDMPS = databaseRepository.getUserDmpDao().asQueryable().where(((builder, root) -> builder.equal(root.get("dmp").get("id"), dmp.getId()))).toList();
for (UserDMP userDMP : userDMPS) { for (UserDMP userDMP : userDMPS) {
if (!userDMP.getUser().getId().equals(user.getId())) { 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()) { if (dataset.getRegistries() != null && !dataset.getRegistries().isEmpty()) {
for (Registry registry : dataset.getRegistries()) { for (Registry registry : dataset.getRegistries()) {
RegistryCriteria criteria = new RegistryCriteria(); 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()) { if (dataset.getDatasetDataRepositories() != null && !dataset.getDatasetDataRepositories().isEmpty()) {
for (DatasetDataRepository datasetDataRepository : dataset.getDatasetDataRepositories()) { for (DatasetDataRepository datasetDataRepository : dataset.getDatasetDataRepositories()) {
DataRepositoryCriteria criteria = new DataRepositoryCriteria(); 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()) { if (dataset.getServices() != null && !dataset.getServices().isEmpty()) {
for (DatasetService service : dataset.getServices()) { for (DatasetService service : dataset.getServices()) {
ServiceCriteria criteria = new ServiceCriteria(); 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()) { if (dataset.getDatasetExternalDatasets() != null && !dataset.getDatasetExternalDatasets().isEmpty()) {
for (DatasetExternalDataset datasetExternalDataset : dataset.getDatasetExternalDatasets()) { for (DatasetExternalDataset datasetExternalDataset : dataset.getDatasetExternalDatasets()) {
ExternalDatasetCriteria criteria = new ExternalDatasetCriteria(); ExternalDatasetCriteria criteria = new ExternalDatasetCriteria();
@ -935,8 +943,8 @@ public class DatasetManager {
metricsManager.increaseValue(MetricNames.DATASET, 1, MetricNames.PUBLISHED); metricsManager.increaseValue(MetricNames.DATASET, 1, MetricNames.PUBLISHED);
} }
public ResponseEntity<byte[]> getDocument(String id, VisibilityRuleService visibilityRuleService, String contentType, Principal principal) throws IllegalAccessException, IOException, InstantiationException { public ResponseEntity<byte[]> getDocument(String id, VisibilityRuleService visibilityRuleService, String contentType) throws IllegalAccessException, IOException, InstantiationException, InvalidApplicationException {
FileEnvelope envelope = getXmlDocument(id, visibilityRuleService, principal); FileEnvelope envelope = getXmlDocument(id, visibilityRuleService);
InputStream resource = new FileInputStream(envelope.getFile()); InputStream resource = new FileInputStream(envelope.getFile());
logger.info("Mime Type of " + envelope.getFilename() + " is " + logger.info("Mime Type of " + envelope.getFilename() + " is " +
new MimetypesFileTypeMap().getContentType(envelope.getFile())); new MimetypesFileTypeMap().getContentType(envelope.getFile()));
@ -957,7 +965,7 @@ public class DatasetManager {
HttpStatus.OK); 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(); DatasetImportPagedDatasetProfile importModel = new DatasetImportPagedDatasetProfile();
JAXBContext jaxbContext; JAXBContext jaxbContext;
@ -1013,7 +1021,7 @@ public class DatasetManager {
profile.setId(UUID.fromString(datasetProfileId)); profile.setId(UUID.fromString(datasetProfileId));
entity.setProfile(profile); 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); entity.setCreator(userInfo);
updateTagsXmlImportDataset(apiContext.getOperationsContext().getElasticRepository().getDatasetRepository(), entity); updateTagsXmlImportDataset(apiContext.getOperationsContext().getElasticRepository().getDatasetRepository(), entity);
@ -1030,7 +1038,7 @@ public class DatasetManager {
// TODO: When tags functionality return. // TODO: When tags functionality return.
} }
public DatasetWizardModel datasetUpdateProfile(String id) { public DatasetWizardModel datasetUpdateProfile(String id) throws InvalidApplicationException {
DatasetWizardModel dataset = new DatasetWizardModel(); DatasetWizardModel dataset = new DatasetWizardModel();
Dataset datasetEntity = databaseRepository.getDatasetDao().find(UUID.fromString(id), HintedModelFactory.getHint(DatasetWizardModel.class)); Dataset datasetEntity = databaseRepository.getDatasetDao().find(UUID.fromString(id), HintedModelFactory.getHint(DatasetWizardModel.class));
dataset.setDatasetProfileDefinition(getPagedProfile(dataset, datasetEntity)); dataset.setDatasetProfileDefinition(getPagedProfile(dataset, datasetEntity));
@ -1083,9 +1091,9 @@ public class DatasetManager {
return pagedDatasetProfile; 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().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()); QueryableList<DescriptionTemplate> items = apiContext.getOperationsContext().getDatabaseRepository().getDatasetProfileDao().getWithCriteria(datasetProfileTableRequestItem.getCriteria());
List<DatasetProfileListingModel> listingModels = items.select(item -> new DatasetProfileListingModel().fromDataModel(item)); List<DatasetProfileListingModel> listingModels = items.select(item -> new DatasetProfileListingModel().fromDataModel(item));
@ -1097,8 +1105,8 @@ public class DatasetManager {
return data; return data;
} }
public void generateIndex(Principal principal) { public void generateIndex() throws InvalidApplicationException {
if (principal.getAuthorities().contains(Authorities.ADMIN.getValue())) { if (this.authorizationService.authorize(Permission.AdminRole)) {
this.apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().asQueryable().toList(); this.apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().asQueryable().toList();
List<Dataset> datasetEntities = new ArrayList<>(this.apiContext.getOperationsContext().getDatabaseRepository().getDatasetDao().asQueryable().toList()); List<Dataset> datasetEntities = new ArrayList<>(this.apiContext.getOperationsContext().getDatabaseRepository().getDatasetDao().asQueryable().toList());
datasetEntities.forEach(datasetEntity -> { datasetEntities.forEach(datasetEntity -> {
@ -1114,8 +1122,8 @@ public class DatasetManager {
} }
} }
public void clearIndex(Principal principal) { public void clearIndex() {
if (principal.getAuthorities().contains(Authorities.ADMIN.getValue())) { if (this.authorizationService.authorize(Permission.AdminRole)) {
try { try {
this.apiContext.getOperationsContext().getElasticRepository().getDatasetRepository().clear(); this.apiContext.getOperationsContext().getElasticRepository().getDatasetRepository().clear();
} catch (IOException e) { } 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())); dataset.setProfile(apiContext.getOperationsContext().getDatabaseRepository().getDatasetProfileDao().find(dataset.getProfile().getId()));
wizardModel.setDatasetProfileDefinition(this.getPagedProfile(wizardModel, dataset)); wizardModel.setDatasetProfileDefinition(this.getPagedProfile(wizardModel, dataset));
ObjectMapper mapper = new ObjectMapper(); ObjectMapper mapper = new ObjectMapper();

View File

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

View File

@ -1,5 +1,6 @@
package eu.eudat.logic.managers; package eu.eudat.logic.managers;
import eu.eudat.commons.scope.user.UserScope;
import eu.eudat.data.dao.criteria.DatasetProfileCriteria; import eu.eudat.data.dao.criteria.DatasetProfileCriteria;
import eu.eudat.data.dao.entities.DMPDao; import eu.eudat.data.dao.entities.DMPDao;
import eu.eudat.data.dao.entities.DatasetProfileDao; 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.datasetwizard.DataManagentPlanListingModel;
import eu.eudat.models.data.dmp.AssociatedProfile; import eu.eudat.models.data.dmp.AssociatedProfile;
import eu.eudat.models.data.dmp.DataManagementPlan; import eu.eudat.models.data.dmp.DataManagementPlan;
import eu.eudat.models.data.security.Principal;
import eu.eudat.queryable.QueryableList; import eu.eudat.queryable.QueryableList;
import javax.management.InvalidApplicationException;
import java.io.IOException; import java.io.IOException;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.List; import java.util.List;
@ -26,15 +27,15 @@ import java.util.stream.Collectors;
public class DatasetWizardManager { 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 userInfo = new UserInfo();
userInfo.setId(principal.getId()); userInfo.setId(userScope.getUserId());
QueryableList<DMP> items = dmpRepository.getUserDmps(datasetWizardAutocompleteRequest.getCriteria(), userInfo); QueryableList<DMP> items = dmpRepository.getUserDmps(datasetWizardAutocompleteRequest.getCriteria(), userInfo);
List<DataManagentPlanListingModel> dataManagementPlans = items.select(item -> new DataManagentPlanListingModel().fromDataModel(item)); List<DataManagentPlanListingModel> dataManagementPlans = items.select(item -> new DataManagentPlanListingModel().fromDataModel(item));
return dataManagementPlans; 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())); DataManagementPlan dataManagementPlan = new DataManagementPlan().fromDataModel(dmpRepository.find(datasetProfileWizardAutocompleteRequest.getCriteria().getId()));
if (dataManagementPlan.getProfiles() == null || dataManagementPlan.getProfiles().isEmpty()) { if (dataManagementPlan.getProfiles() == null || dataManagementPlan.getProfiles().isEmpty()) {
return new LinkedList<>(); return new LinkedList<>();
@ -49,7 +50,7 @@ public class DatasetWizardManager {
return profiles; 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); 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"); 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()); dataset.setStatus(Dataset.Status.SAVED.getValue());
@ -57,7 +58,7 @@ public class DatasetWizardManager {
return; 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); Dataset oldDataset = apiContext.getOperationsContext().getDatabaseRepository().getDatasetDao().find(uuid);
eu.eudat.elastic.entities.Dataset oldDatasetElasitc = apiContext.getOperationsContext().getElasticRepository().getDatasetRepository().findDocument(uuid.toString()); eu.eudat.elastic.entities.Dataset oldDatasetElasitc = apiContext.getOperationsContext().getElasticRepository().getDatasetRepository().findDocument(uuid.toString());
oldDataset.setStatus(Dataset.Status.DELETED.getValue()); 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.DepositRequest;
import eu.eudat.models.data.doi.Doi; import eu.eudat.models.data.doi.Doi;
import eu.eudat.models.data.doi.RepositoryConfig; import eu.eudat.models.data.doi.RepositoryConfig;
import eu.eudat.models.data.security.Principal;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@ -51,8 +50,8 @@ public class DepositManager {
return null; return null;
} }
public Doi deposit(DepositRequest depositRequest, Principal principal) throws Exception { public Doi deposit(DepositRequest depositRequest) throws Exception {
return this.dataManagementPlanManager.createDoi(depositRequest, principal); return this.dataManagementPlanManager.createDoi(depositRequest);
} }
public String getRepositoryLogo(String repositoryId){ public String getRepositoryLogo(String repositoryId){

View File

@ -1,5 +1,6 @@
package eu.eudat.logic.managers; package eu.eudat.logic.managers;
import eu.eudat.commons.scope.user.UserScope;
import eu.eudat.data.CredentialEntity; import eu.eudat.data.CredentialEntity;
import eu.eudat.data.old.EmailConfirmation; import eu.eudat.data.old.EmailConfirmation;
import eu.eudat.data.old.UserInfo; 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.exceptions.emailconfirmation.TokenExpiredException;
import eu.eudat.logic.services.ApiContext; import eu.eudat.logic.services.ApiContext;
import eu.eudat.logic.services.operations.DatabaseRepository; import eu.eudat.logic.services.operations.DatabaseRepository;
import eu.eudat.models.data.security.Principal;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import javax.management.InvalidApplicationException;
import java.util.Date; import java.util.Date;
import java.util.UUID; import java.util.UUID;
@ -18,14 +19,16 @@ import java.util.UUID;
public class EmailConfirmationManager { public class EmailConfirmationManager {
private ApiContext apiContext; private ApiContext apiContext;
private DatabaseRepository databaseRepository; private DatabaseRepository databaseRepository;
private final UserScope userScope;
@Autowired @Autowired
public EmailConfirmationManager(ApiContext apiContext) { public EmailConfirmationManager(ApiContext apiContext, UserScope userScope) {
this.apiContext = apiContext; this.apiContext = apiContext;
this.databaseRepository = apiContext.getOperationsContext().getDatabaseRepository(); 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() EmailConfirmation loginConfirmationEmail = apiContext.getOperationsContext()
.getDatabaseRepository().getLoginConfirmationEmailDao().asQueryable() .getDatabaseRepository().getLoginConfirmationEmailDao().asQueryable()
.where((builder, root) -> builder.equal(root.get("token"), UUID.fromString(token))).getSingle(); .where((builder, root) -> builder.equal(root.get("token"), UUID.fromString(token))).getSingle();
@ -65,8 +68,8 @@ public class EmailConfirmationManager {
databaseRepository.getLoginConfirmationEmailDao().createOrUpdate(loginConfirmationEmail); databaseRepository.getLoginConfirmationEmailDao().createOrUpdate(loginConfirmationEmail);
} }
public void sendConfirmationEmail(String email, Principal principal) throws HasConfirmedEmailException { public void sendConfirmationEmail(String email) throws HasConfirmedEmailException, InvalidApplicationException {
UserInfo user = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(principal.getId()); UserInfo user = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(this.userScope.getUserId());
if (user.getEmail() != null) if (user.getEmail() != null)
throw new HasConfirmedEmailException("User already has confirmed his Email."); throw new HasConfirmedEmailException("User already has confirmed his Email.");
@ -74,11 +77,11 @@ public class EmailConfirmationManager {
databaseRepository.getLoginConfirmationEmailDao(), databaseRepository.getLoginConfirmationEmailDao(),
apiContext.getUtilitiesService().getMailService(), apiContext.getUtilitiesService().getMailService(),
email, 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(); CredentialEntity credential = databaseRepository.getCredentialDao().asQueryable().where((builder, root) -> builder.equal(root.get("userId"), newUser.getId())).getSingle();
credential.setUserId(oldUser.getId()); credential.setUserId(oldUser.getId());
databaseRepository.getCredentialDao().createOrUpdate(credential); 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.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import eu.eudat.commons.scope.user.UserScope;
import eu.eudat.data.old.ExternalDataset; import eu.eudat.data.old.ExternalDataset;
import eu.eudat.logic.builders.model.criteria.ExternalDatasetCriteriaBuilder; import eu.eudat.logic.builders.model.criteria.ExternalDatasetCriteriaBuilder;
import eu.eudat.logic.builders.model.models.DataTableDataBuilder; 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.HugeResultSet;
import eu.eudat.logic.proxy.config.exceptions.NoURLFound; import eu.eudat.logic.proxy.config.exceptions.NoURLFound;
import eu.eudat.logic.proxy.fetching.RemoteFetcher; import eu.eudat.logic.proxy.fetching.RemoteFetcher;
import eu.eudat.models.data.security.Principal;
import eu.eudat.queryable.QueryableList; import eu.eudat.queryable.QueryableList;
import eu.eudat.logic.services.ApiContext; import eu.eudat.logic.services.ApiContext;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import javax.management.InvalidApplicationException;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@ -32,11 +33,13 @@ public class ExternalDatasetManager {
private ApiContext apiContext; private ApiContext apiContext;
private DatabaseRepository databaseRepository; private DatabaseRepository databaseRepository;
private RemoteFetcher remoteFetcher; private RemoteFetcher remoteFetcher;
private final UserScope userScope;
@Autowired @Autowired
public ExternalDatasetManager(ApiContext apiContext) { public ExternalDatasetManager(ApiContext apiContext, UserScope userScope) {
this.apiContext = apiContext; this.apiContext = apiContext;
this.databaseRepository = apiContext.getOperationsContext().getDatabaseRepository(); this.databaseRepository = apiContext.getOperationsContext().getDatabaseRepository();
this.remoteFetcher = apiContext.getOperationsContext().getRemoteFetcher(); this.remoteFetcher = apiContext.getOperationsContext().getRemoteFetcher();
this.userScope = userScope;
} }
public DataTableData<ExternalDatasetListingModel> getPaged(ExternalDatasetTableRequest externalDatasetTableRequest) throws Exception { 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(); 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. // Fetch the local saved external Datasets that belong to the user.
ExternalDatasetCriteria criteria = apiContext.getOperationsContext().getBuilderFactory().getBuilder(ExternalDatasetCriteriaBuilder.class).like(query).build(); 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); QueryableList<ExternalDataset> items = apiContext.getOperationsContext().getDatabaseRepository().getExternalDatasetDao().getWithCriteria(criteria);
// Fetch external Datasets from external sources. // Fetch external Datasets from external sources.
@ -69,16 +72,16 @@ public class ExternalDatasetManager {
return externalDatasets; 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); ExternalDataset externalDataset = databaseRepository.getExternalDatasetDao().find(id);
ExternalDatasetListingModel externalDatasetModel = new ExternalDatasetListingModel(); ExternalDatasetListingModel externalDatasetModel = new ExternalDatasetListingModel();
externalDatasetModel.fromDataModel(externalDataset); externalDatasetModel.fromDataModel(externalDataset);
return externalDatasetModel; 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 externalDataset = externalDatasetModel.toDataModel();
externalDataset.getCreationUser().setId(principal.getId()); externalDataset.getCreationUser().setId(this.userScope.getUserId());
return apiContext.getOperationsContext().getDatabaseRepository().getExternalDatasetDao().createOrUpdate(externalDataset); 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.core.env.Environment;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import javax.management.InvalidApplicationException;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.nio.file.Files; import java.nio.file.Files;
@ -59,19 +60,19 @@ public class FileManager {
databaseRepository.getFileUploadDao().createOrUpdate(fileUpload); databaseRepository.getFileUploadDao().createOrUpdate(fileUpload);
} }
public List<FileUpload> getFileUploadsForEntityId(String entityId) { public List<FileUpload> getFileUploadsForEntityId(String entityId) throws InvalidApplicationException {
return databaseRepository.getFileUploadDao().asQueryable() return databaseRepository.getFileUploadDao().asQueryable()
.where((builder, root) -> builder.equal(root.get("entityId"), entityId)).toList(); .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() return databaseRepository.getFileUploadDao().asQueryable()
.where((builder, root) -> builder.and( .where((builder, root) -> builder.and(
builder.equal(root.get("entityId"), entityId), builder.equal(root.get("entityId"), entityId),
builder.equal(root.get("isDeleted"), false))).toList(); 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); List<FileUpload> fileUploads = this.getCurrentFileUploadsForEntityId(entityId);
fileUploads.forEach(fileUpload -> { fileUploads.forEach(fileUpload -> {
this.markOldFileAsDeleted(fileUpload); this.markOldFileAsDeleted(fileUpload);

View File

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

View File

@ -1,5 +1,6 @@
package eu.eudat.logic.managers; package eu.eudat.logic.managers;
import eu.eudat.commons.scope.user.UserScope;
import eu.eudat.data.old.DMP; import eu.eudat.data.old.DMP;
import eu.eudat.data.old.UserDMP; import eu.eudat.data.old.UserDMP;
import eu.eudat.data.old.UserInfo; 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.logic.utilities.helpers.StreamDistinctBy;
import eu.eudat.models.data.invitation.Invitation; import eu.eudat.models.data.invitation.Invitation;
import eu.eudat.models.data.invitation.Properties; import eu.eudat.models.data.invitation.Properties;
import eu.eudat.models.data.security.Principal;
import eu.eudat.models.data.userinfo.UserInfoInvitationModel; import eu.eudat.models.data.userinfo.UserInfoInvitationModel;
import eu.eudat.queryable.QueryableList; import eu.eudat.queryable.QueryableList;
import org.springframework.beans.factory.annotation.Autowired; 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.JAXBContext;
import jakarta.xml.bind.JAXBException; import jakarta.xml.bind.JAXBException;
import jakarta.xml.bind.Unmarshaller; import jakarta.xml.bind.Unmarshaller;
import javax.management.InvalidApplicationException;
import java.io.IOException; import java.io.IOException;
import java.io.StringReader; import java.io.StringReader;
import java.util.*; import java.util.*;
@ -29,18 +31,25 @@ public class InvitationsManager {
private ApiContext apiContext; private ApiContext apiContext;
private DataManagementPlanManager dataManagementPlanManager; private DataManagementPlanManager dataManagementPlanManager;
private final UserScope userScope;
@Autowired @Autowired
public InvitationsManager(ApiContext apiContext, DataManagementPlanManager dataManagementPlanManager) { public InvitationsManager(ApiContext apiContext, DataManagementPlanManager dataManagementPlanManager, UserScope userScope) {
this.apiContext = apiContext; this.apiContext = apiContext;
this.dataManagementPlanManager = dataManagementPlanManager; 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(); UserInfo principalUser = new UserInfo();
principalUser.setId(principal.getId()); principalUser.setId(this.userScope.getUserIdSafe());
invitation.getUsers().stream().filter(item -> item.getId() == null).forEach(item -> { 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(); 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) { if (existingUser != null) {
item.setId(existingUser.getId()); item.setId(existingUser.getId());
} }
@ -65,7 +74,7 @@ public class InvitationsManager {
apiContext.getUtilitiesService().getInvitationService().assignToDmp(apiContext.getOperationsContext().getDatabaseRepository().getDmpDao(), userInfoToUserDmp, dataManagementPlan); 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()); /*UserInfo principalUser = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(principal.getId());
List<UserInfo> users = apiContext.getOperationsContext().getDatabaseRepository().getUserAssociationDao().getAssociated(principalUser).stream().map(userAssociation -> { List<UserInfo> users = apiContext.getOperationsContext().getDatabaseRepository().getUserAssociationDao().getAssociated(principalUser).stream().map(userAssociation -> {
if (userAssociation.getFirstUser().getId().equals(principal.getId())) { if (userAssociation.getFirstUser().getId().equals(principal.getId())) {
@ -76,20 +85,20 @@ public class InvitationsManager {
}).collect(Collectors.toList());*/ }).collect(Collectors.toList());*/
List<UserInfo> users = apiContext.getOperationsContext().getDatabaseRepository().getDmpDao() List<UserInfo> users = apiContext.getOperationsContext().getDatabaseRepository().getDmpDao()
.getAuthenticated(apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().asQueryable() .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) .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()); List<UserInfoInvitationModel> userModels = users.stream().map(userInfo -> new UserInfoInvitationModel().fromDataModel(userInfo)).collect(Collectors.toList());
return userModels; 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() List<UserInfo> users = apiContext.getOperationsContext().getDatabaseRepository().getDmpDao()
.getAuthenticated(apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().asQueryable() .getAuthenticated(apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().asQueryable()
.where(((builder, root) -> .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) .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 .filter(userInfo -> (userInfoRequestItem == null || userInfoRequestItem.getCriteria() == null || userInfoRequestItem.getCriteria().getLike() == null
|| userInfo.getName().toLowerCase().contains(userInfoRequestItem.getCriteria().getLike().toLowerCase()) || userInfo.getName().toLowerCase().contains(userInfoRequestItem.getCriteria().getLike().toLowerCase())
|| (userInfo.getEmail().toLowerCase().contains(userInfoRequestItem.getCriteria().getLike().toLowerCase())))) || (userInfo.getEmail().toLowerCase().contains(userInfoRequestItem.getCriteria().getLike().toLowerCase()))))
@ -100,7 +109,7 @@ public class InvitationsManager {
return userModels; 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); eu.eudat.data.old.Invitation invitation = apiContext.getOperationsContext().getDatabaseRepository().getInvitationDao().find(invitationID);
if (invitation == null) if (invitation == null)
throw new UnauthorisedException("There is no Data Management Plan assigned to this Link"); 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); JAXBContext context = JAXBContext.newInstance(Properties.class);
Unmarshaller unmarshaller = context.createUnmarshaller(); Unmarshaller unmarshaller = context.createUnmarshaller();
Properties properties = (Properties) unmarshaller.unmarshal(new StringReader(invitation.getProperties())); 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())))); 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(); UserDMP existingUserDMP = userDMPQueryableList.getSingleOrDefault();
if (existingUserDMP != null) { if (existingUserDMP != null) {

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