Merge branch 'ui-redesign' into Development

# Conflicts:
#	dmp-backend/web/src/main/java/eu/eudat/logic/proxy/fetching/RemoteFetcher.java
#	dmp-backend/web/src/main/java/eu/eudat/models/data/external/ResearchersExternalSourcesModel.java
#	dmp-backend/web/src/main/resources/externalUrls/ExternalUrls.xml
This commit is contained in:
Diamantis Tziotzios 2020-10-06 16:43:20 +03:00
commit e65bce0f5a
447 changed files with 90567 additions and 48762 deletions

66
Jenkinsfile vendored Normal file
View File

@ -0,0 +1,66 @@
def pipelineContext = [:]
pipeline {
agent any
options {
skipDefaultCheckout(true)
}
stages {
stage('Checkout') {
steps {
checkout scm
}
}
stage('Build API') {
steps {
script {
pipelineContext.apiImage = docker.build("open-dmp-api:${env.BUILD_ID}", "-f dmp-backend/Dockerfile.CI dmp-backend/")
}
}
}
stage('Build WebApp') {
steps {
script {
pipelineContext.webappImage = docker.build("open-dmp-webapp:${env.BUILD_ID}", "-f dmp-frontend/Dockerfile.CI dmp-frontend/")
}
}
}
//stage('SonarQube analysis') {
// steps {
// script {
// def scannerHome = tool 'SonarQube Scanner 4.3';
// withSonarQubeEnv('SonarQube') { // If you have configured more than one global server connection, you can specify its name
// sh "${scannerHome}/bin/sonar-scanner"
// }
// }
// }
//}
//// waiting for sonar results based into the configured web hook in Sonar server which push the status back to jenkins
//stage('SonarQube scan result check') {
// steps {
// timeout(time: 2, unit: 'MINUTES') {
// retry(3) {
// script {
// def qg = waitForQualityGate()
// if (qg.status != 'OK') {
// error "Pipeline aborted due to quality gate failure: ${qg.status}"
// }
// }
// }
// }
// }
//}
stage('Pushing to Docker Registry') {
steps {
script {
docker.withRegistry('http://drepo.local.cite.gr', 'b2c651c1-9a3b-4a98-a6da-e1dd7a20f512') {
pipelineContext.apiImage.push()
pipelineContext.webappImage.push()
}
}
}
}
}
}

15
dmp-backend/Dockerfile.CI Normal file
View File

@ -0,0 +1,15 @@
FROM maven:3-jdk-8-alpine AS MAVEN_BUILD
COPY pom.xml /build/
COPY data /build/data/
COPY elastic /build/elastic/
COPY queryable /build/queryable/
COPY web /build/web/
WORKDIR /build/
RUN mvn package
FROM openjdk:8-jre-alpine
WORKDIR /app
COPY --from=MAVEN_BUILD /build/web/target/web-1.0-SNAPSHOT.jar /app/app.jar
ENTRYPOINT ["java","-Djava.security.egd=file:/dev/./urandom" ,"-Dspring.profiles.active=${PROF}","-jar","/app.jar"]

View File

@ -52,13 +52,12 @@ public class DMPDaoImpl extends DatabaseAccess<DMP> implements DMPDao {
query.where((builder, root) -> root.get("groupId").in(criteria.getGroupIds())); query.where((builder, root) -> root.get("groupId").in(criteria.getGroupIds()));
if (criteria.getStatus() != null) { if (criteria.getStatus() != null) {
if (criteria.getStatus() == DMP.DMPStatus.FINALISED.getValue()) { if (criteria.getStatus() == DMP.DMPStatus.FINALISED.getValue()) {
query.where((builder, root) -> builder.and(builder.equal(root.get("status"), DMP.DMPStatus.FINALISED.getValue()), builder.notEqual(root.get("isPublic"), true))); query.where((builder, root) -> builder.equal(root.get("status"), DMP.DMPStatus.FINALISED.getValue()));
} else if (criteria.getStatus() == DMP.DMPStatus.ACTIVE.getValue()) { } else if (criteria.getStatus() == DMP.DMPStatus.ACTIVE.getValue()) {
query.where((builder, root) -> builder.equal(root.get("status"), DMP.DMPStatus.ACTIVE.getValue())); query.where((builder, root) -> builder.equal(root.get("status"), DMP.DMPStatus.ACTIVE.getValue()));
} }
} }
if (criteria.getIsPublic()) query.where(((builder, root) -> builder.equal(root.get("isPublic"), criteria.getIsPublic())));
query.where(((builder, root) -> builder.equal(root.get("isPublic"), true)));
/*if (criteria.getRole() != null) { /*if (criteria.getRole() != null) {
if (criteria.getRole().equals(UserDMP.UserDMPRoles.OWNER.getValue())) { if (criteria.getRole().equals(UserDMP.UserDMPRoles.OWNER.getValue())) {
query.where((builder, root) -> builder.equal(root.join("users", JoinType.LEFT).get("role"), UserDMP.UserDMPRoles.OWNER.getValue())); query.where((builder, root) -> builder.equal(root.join("users", JoinType.LEFT).get("role"), UserDMP.UserDMPRoles.OWNER.getValue()));

View File

@ -29,7 +29,21 @@ import java.util.stream.Collectors;
@NamedEntityGraph( @NamedEntityGraph(
name = "dmpRecentActivity", name = "dmpRecentActivity",
attributeNodes = { attributeNodes = {
@NamedAttributeNode("users"), @NamedAttributeNode("creator")}) @NamedAttributeNode("users"), @NamedAttributeNode("creator")}),
@NamedEntityGraph(
name = "recentDmpModel",
attributeNodes = {@NamedAttributeNode("organisations"), @NamedAttributeNode("researchers"), @NamedAttributeNode("associatedDmps"),
@NamedAttributeNode("grant"), @NamedAttributeNode(value = "users", subgraph = "users"), @NamedAttributeNode("creator"), @NamedAttributeNode("profile"), @NamedAttributeNode(value = "dataset", subgraph = "dataset")},
subgraphs = {
@NamedSubgraph(name = "users", attributeNodes = {@NamedAttributeNode("user")}),
@NamedSubgraph(name = "dataset", attributeNodes = {@NamedAttributeNode("id"), @NamedAttributeNode("label")})
}
),
@NamedEntityGraph(
name = "versionListingModel",
attributeNodes = {@NamedAttributeNode("id"), @NamedAttributeNode("groupId"), @NamedAttributeNode("version")}
)
}) })
public class DMP implements DataEntity<DMP, UUID> { public class DMP implements DataEntity<DMP, UUID> {

View File

@ -36,7 +36,17 @@ import java.util.stream.Collectors;
@NamedEntityGraph( @NamedEntityGraph(
name = "datasetDataRepositories", name = "datasetDataRepositories",
attributeNodes = {@NamedAttributeNode(value = "dmp", subgraph = "dmp"), @NamedAttributeNode("creator")}, attributeNodes = {@NamedAttributeNode(value = "dmp", subgraph = "dmp"), @NamedAttributeNode("creator")},
subgraphs = @NamedSubgraph(name = "dmp", attributeNodes = {@NamedAttributeNode("creator"), @NamedAttributeNode("users")})) subgraphs = @NamedSubgraph(name = "dmp", attributeNodes = {@NamedAttributeNode("creator"), @NamedAttributeNode("users")})),
@NamedEntityGraph(
name = "recentDatasetModel",
attributeNodes = {@NamedAttributeNode("services"), @NamedAttributeNode(value = "datasetDataRepositories", subgraph = "datasetDataRepositories"),
@NamedAttributeNode(value = "datasetExternalDatasets", subgraph = "datasetExternalDatasets"), @NamedAttributeNode("registries"),
@NamedAttributeNode(value = "dmp", subgraph = "dmp"), @NamedAttributeNode("profile"), @NamedAttributeNode("creator")},
subgraphs = {
@NamedSubgraph(name = "dmp", attributeNodes = {@NamedAttributeNode("creator"), @NamedAttributeNode("users"), @NamedAttributeNode("grant"), @NamedAttributeNode("organisations")}),
@NamedSubgraph(name = "datasetDataRepositories", attributeNodes = {@NamedAttributeNode("dataRepository")}),
@NamedSubgraph(name = "datasetExternalDatasets", attributeNodes = {@NamedAttributeNode("externalDataset")})
})
}) })
public class Dataset implements DataEntity<Dataset, UUID> { public class Dataset implements DataEntity<Dataset, UUID> {

View File

@ -21,9 +21,12 @@ public class PaginationService {
items.withFields(Arrays.asList(tableRequest.getSelection().getFields())); items.withFields(Arrays.asList(tableRequest.getSelection().getFields()));
return items; return items;
} }
public static <T extends DataEntity> void applyOrder(QueryableList<T> items, TableQuery tableRequest) { public static <T extends DataEntity> void applyOrder(QueryableList<T> items, TableQuery tableRequest) {
ColumnOrderings columnOrderings = tableRequest.getOrderings(); applyOrder(items, tableRequest.getOrderings());
}
public static <T extends DataEntity> void applyOrder(QueryableList<T> items, ColumnOrderings columnOrderings) {
for (Ordering ordering : columnOrderings.getFieldOrderings()) { for (Ordering ordering : columnOrderings.getFieldOrderings()) {
if (ordering.getOrderByType() == Ordering.OrderByType.ASC) if (ordering.getOrderByType() == Ordering.OrderByType.ASC)
applyAscOrder(items, ordering); applyAscOrder(items, ordering);

View File

@ -13,6 +13,14 @@ public class Tag implements ElasticEntity {
private String id; private String id;
private String name; private String name;
public Tag() {
}
public Tag(String id, String name) {
this.id = id;
this.name = name;
}
public String getId() { public String getId() {
return id; return id;
} }

View File

@ -28,6 +28,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.DataManagementPlanListingModel; 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.VersionListingModel;
import eu.eudat.models.data.security.Principal; 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;
@ -55,8 +57,7 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.UUID; import java.util.UUID;
import static org.springframework.http.MediaType.APPLICATION_ATOM_XML; import static org.springframework.http.MediaType.*;
import static org.springframework.http.MediaType.APPLICATION_JSON;
@RestController @RestController
@ -158,14 +159,26 @@ public class DMPs extends BaseController {
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")
public @ResponseBody
ResponseEntity<ResponseItem<List<VersionListingModel>>> getVersions(@PathVariable(value= "id") String groupId,
@ClaimedAuthorities(claims = {Authorities.ADMIN, Authorities.MANAGER, Authorities.USER, Authorities.ANONYMOUS}) Principal principal) throws Exception {
List<VersionListingModel> versions = this.dataManagementPlanManager.getAllVersions(groupId, principal);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List<VersionListingModel>>().status(ApiMessageCode.NO_MESSAGE).payload(versions));
}
/* /*
* Data Export * Data Export
* */ * */
@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) throws IOException { ResponseEntity getRDAJsonDocument(@PathVariable String id, @ClaimedAuthorities(claims = {Authorities.ADMIN, Authorities.MANAGER, Authorities.USER, Authorities.ANONYMOUS}) Principal principal) {
try {
return this.dataManagementPlanManager.getRDAJsonDocument(id, datasetManager, principal); return this.dataManagementPlanManager.getRDAJsonDocument(id, datasetManager, principal);
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.EXPECTATION_FAILED).body(new ResponseItem<>().message(e.getMessage()).status(ApiMessageCode.ERROR_MESSAGE));
}
} }
@RequestMapping(method = RequestMethod.GET, value = {"/getPDF/{id}"}) @RequestMapping(method = RequestMethod.GET, value = {"/getPDF/{id}"})
@ -199,27 +212,35 @@ 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<UUID>> 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, Principal principal) throws Exception {
DMP dmp = this.dataManagementPlanManager.createOrUpdate(this.getApiContext(), dataManagementPlanEditorModel, principal); DMP dmp = this.dataManagementPlanManager.createOrUpdate(dataManagementPlanEditorModel, principal);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<eu.eudat.models.data.dmp.DataManagementPlan>().status(ApiMessageCode.SUCCESS_MESSAGE).message("Created").payload(new eu.eudat.models.data.dmp.DataManagementPlan().fromDataModel(dmp)));
}
@Transactional
@RequestMapping(method = RequestMethod.POST, path = "full", consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<UUID>> createOrUpdateWithDatasets(@RequestBody eu.eudat.models.data.dmp.DataManagementPlanEditorModel dataManagementPlanEditorModel, Principal principal) throws Exception {
DMP dmp = this.dataManagementPlanManager.createOrUpdateWithDatasets(dataManagementPlanEditorModel, principal);
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<DMP>> 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, Principal principal) throws Exception {
try { try {
this.dataManagementPlanManager.newVersion(id, dataManagementPlan, principal); UUID result = this.dataManagementPlanManager.newVersion(id, dataManagementPlan, principal);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DMP>().status(ApiMessageCode.NO_MESSAGE)); 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<DMP>().status(ApiMessageCode.ERROR_MESSAGE).message(exception.getMessage())); return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem<UUID>().status(ApiMessageCode.ERROR_MESSAGE).message(exception.getMessage()));
} }
} }
@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<DMP>> 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, Principal principal) throws Exception {
this.dataManagementPlanManager.clone(dataManagementPlan, principal); UUID cloneId = this.dataManagementPlanManager.clone(dataManagementPlan, principal);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DMP>().status(ApiMessageCode.SUCCESS_MESSAGE)); return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<UUID>().status(ApiMessageCode.SUCCESS_MESSAGE).payload(cloneId));
} }
@Transactional @Transactional
@ -238,8 +259,10 @@ public class DMPs extends BaseController {
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, Principal principal) throws Exception {
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, principal, profiles);
} else if (files[0].getContentType().equals(APPLICATION_ATOM_XML.toString())) { } else if (files[0].getContentType().equals(APPLICATION_ATOM_XML.toString()) || files[0].getContentType().equals(TEXT_XML.toString())) {
this.dataManagementPlanManager.createDmpFromXml(this.getApiContext(), files, principal); this.dataManagementPlanManager.createDmpFromXml(this.getApiContext(), files, principal);
} else {
return ResponseEntity.badRequest().body(new ResponseItem().status(ApiMessageCode.ERROR_MESSAGE).message("File format is not supported"));
} }
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List>() return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List>()
.status(ApiMessageCode.SUCCESS_MESSAGE)); .status(ApiMessageCode.SUCCESS_MESSAGE));
@ -251,7 +274,8 @@ public class DMPs extends BaseController {
this.dataManagementPlanManager.makePublic(UUID.fromString(id), principal); this.dataManagementPlanManager.makePublic(UUID.fromString(id), principal);
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) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem<DMP>().status(ApiMessageCode.ERROR_MESSAGE).message(e.getMessage())); logger.error(e.getMessage(), e);
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem<DMP>().status(ApiMessageCode.ERROR_MESSAGE).message("Failed to make Data Management Plan public."));
} }
} }
@ -262,7 +286,8 @@ public class DMPs extends BaseController {
this.dataManagementPlanManager.makeFinalize(UUID.fromString(id), principal, datasetsToBeFinalized); this.dataManagementPlanManager.makeFinalize(UUID.fromString(id), principal, 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) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem<DMP>().status(ApiMessageCode.ERROR_MESSAGE).message(e.getMessage())); logger.error(e.getMessage(), e);
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem<DMP>().status(ApiMessageCode.ERROR_MESSAGE).message("Failed to finalize Data Management Plan."));
} }
} }
@ -273,7 +298,21 @@ public class DMPs extends BaseController {
this.dataManagementPlanManager.undoFinalize(UUID.fromString(id), principal); this.dataManagementPlanManager.undoFinalize(UUID.fromString(id), principal);
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) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem<DMP>().status(ApiMessageCode.ERROR_MESSAGE).message(e.getMessage())); logger.error(e.getMessage(), e);
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem<DMP>().status(ApiMessageCode.ERROR_MESSAGE).message("Failed to unfinalize the Data Management Plan."));
}
}
@Transactional
@RequestMapping(method = RequestMethod.POST, value = {"/updateusers/{id}"})
public ResponseEntity<ResponseItem<DMP>> updateUsers(@PathVariable String id, @RequestBody List<UserInfoListingModel> users, Principal principal) {
try {
this.dataManagementPlanManager.updateUsers(UUID.fromString(id), users, principal);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DMP>().status(ApiMessageCode.SUCCESS_MESSAGE).message("Successfully Updated Colaborators for Data Datamanagement Plan."));
} catch (Exception e) {
logger.error(e.getMessage(), e);
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem<DMP>().status(ApiMessageCode.ERROR_MESSAGE).message("Failed to update the users of Data Management Plan."));
} }
} }
@ -289,7 +328,7 @@ public class DMPs extends BaseController {
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<String>().status(ApiMessageCode.SUCCESS_MESSAGE).message("Successfully created DOI for Data Datamanagement Plan in question.").payload(zenodoDOI)); return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<String>().status(ApiMessageCode.SUCCESS_MESSAGE).message("Successfully created DOI for Data Datamanagement Plan in question.").payload(zenodoDOI));
} catch (Exception e) { } catch (Exception e) {
logger.error(e.getMessage(), e); logger.error(e.getMessage(), e);
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem<String>().status(ApiMessageCode.ERROR_MESSAGE).message(e.getMessage())); return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem<String>().status(ApiMessageCode.ERROR_MESSAGE).message("Failed to create DOI for the Data Management Plan."));
} }
} }

View File

@ -1,9 +1,12 @@
package eu.eudat.controllers; package eu.eudat.controllers;
import eu.eudat.criteria.RecentActivityCriteria;
import eu.eudat.logic.managers.DashBoardManager; import eu.eudat.logic.managers.DashBoardManager;
import eu.eudat.logic.security.claims.ClaimedAuthorities; 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.tablerequest.RecentActivityTableRequest;
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;
@ -15,6 +18,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.transaction.Transactional;
import java.io.IOException; import java.io.IOException;
import java.util.List; import java.util.List;
@ -42,6 +46,14 @@ public class DashBoardController extends BaseController {
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.POST, value = {"/dashboard/recentActivity"}, produces = "application/json")
@Transactional
public ResponseEntity<ResponseItem<List<RecentActivityModel>>> getNewRecentActivity(@RequestBody RecentActivityTableRequest tableRequest,
@ClaimedAuthorities(claims = {Authorities.ADMIN, Authorities.MANAGER, Authorities.USER, Authorities.ANONYMOUS}) Principal principal) {
List<RecentActivityModel> statistics = dashBoardManager.getNewRecentActivity(tableRequest, principal);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List<RecentActivityModel>>().status(ApiMessageCode.NO_MESSAGE).payload(statistics));
}
@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, Principal principal) {
RecentActivity statistics = dashBoardManager.getRecentActivity(principal, numberOfActivities); RecentActivity statistics = dashBoardManager.getRecentActivity(principal, numberOfActivities);

View File

@ -1,224 +0,0 @@
package eu.eudat.controllers;
import eu.eudat.data.entities.Dataset;
import eu.eudat.data.query.items.item.dataset.DatasetWizardAutocompleteRequest;
import eu.eudat.data.query.items.item.datasetprofile.DatasetProfileWizardAutocompleteRequest;
import eu.eudat.exceptions.datasetwizard.DatasetWizardCannotUnlockException;
import eu.eudat.exceptions.security.UnauthorisedException;
import eu.eudat.logic.managers.DatasetManager;
import eu.eudat.logic.managers.DatasetWizardManager;
import eu.eudat.logic.managers.UserManager;
import eu.eudat.logic.proxy.config.configloaders.ConfigLoader;
import eu.eudat.logic.security.claims.ClaimedAuthorities;
import eu.eudat.logic.services.ApiContext;
import eu.eudat.logic.services.forms.VisibilityRuleService;
import eu.eudat.logic.utilities.documents.helpers.FileEnvelope;
import eu.eudat.models.data.datasetwizard.DataManagentPlanListingModel;
import eu.eudat.models.data.datasetwizard.DatasetWizardModel;
import eu.eudat.models.data.dmp.AssociatedProfile;
import eu.eudat.models.data.helpers.responses.ResponseItem;
import eu.eudat.models.data.listingmodels.DataManagementPlanOverviewModel;
import eu.eudat.models.data.security.Principal;
import eu.eudat.models.data.user.composite.PagedDatasetProfile;
import eu.eudat.types.ApiMessageCode;
import eu.eudat.types.Authorities;
import org.apache.poi.util.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.persistence.NoResultException;
import javax.transaction.Transactional;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.util.List;
import java.util.UUID;
import static eu.eudat.types.Authorities.ANONYMOUS;
@RestController
@CrossOrigin
@RequestMapping(value = {"api/datasetwizard"})
public class DatasetWizardController extends BaseController {
private static final Logger logger = LoggerFactory.getLogger(DatasetWizardController.class);
private Environment environment;
private DatasetManager datasetManager;
private UserManager userManager;
private ConfigLoader configLoader;
@Autowired
public DatasetWizardController(ApiContext apiContext, Environment environment, DatasetManager datasetManager, UserManager userManager, ConfigLoader configLoader) {
super(apiContext);
this.environment = environment;
this.datasetManager = datasetManager;
this.userManager = userManager;
this.configLoader = configLoader;
}
@RequestMapping(method = RequestMethod.POST, value = {"/userDmps"}, produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<List<DataManagentPlanListingModel>>> getUserDmps(@RequestBody DatasetWizardAutocompleteRequest datasetWizardAutocompleteRequest, Principal principal) throws IllegalAccessException, InstantiationException {
List<DataManagentPlanListingModel> dataManagementPlans = DatasetWizardManager.getUserDmps(this.getApiContext().getOperationsContext().getDatabaseRepository().getDmpDao(), datasetWizardAutocompleteRequest, principal);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List<DataManagentPlanListingModel>>().status(ApiMessageCode.NO_MESSAGE).payload(dataManagementPlans));
}
@RequestMapping(method = RequestMethod.POST, value = {"/getAvailableProfiles"}, produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<List<AssociatedProfile>>> getAvailableProfiles(@RequestBody DatasetProfileWizardAutocompleteRequest datasetProfileWizardAutocompleteRequest, @ClaimedAuthorities(claims = {ANONYMOUS}) Principal principal) throws IllegalAccessException, InstantiationException {
List<AssociatedProfile> dataManagementPlans = DatasetWizardManager.getAvailableProfiles(this.getApiContext().getOperationsContext().getDatabaseRepository().getDmpDao(), datasetProfileWizardAutocompleteRequest);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List<AssociatedProfile>>().status(ApiMessageCode.NO_MESSAGE).payload(dataManagementPlans));
}
@Transactional
@RequestMapping(method = RequestMethod.GET, value = {"{id}"}, produces = "application/json")
public @ResponseBody
ResponseEntity getSingle(@PathVariable String id, @RequestHeader("Content-Type") String contentType, @ClaimedAuthorities(claims = {Authorities.ADMIN, Authorities.MANAGER, Authorities.USER, Authorities.ANONYMOUS}) Principal principal) throws IllegalAccessException, IOException, InstantiationException {
try {
if (contentType.equals("application/xml")) {
VisibilityRuleService visibilityRuleService = this.getApiContext().getUtilitiesService().getVisibilityRuleService();
return this.datasetManager.getDocument(id, visibilityRuleService, contentType, principal);
} else if (contentType.equals("application/msword")) {
FileEnvelope file = datasetManager.getWordDocumentFile(this.configLoader, id, this.getApiContext().getUtilitiesService().getVisibilityRuleService(), principal);
InputStream resource = new FileInputStream(file.getFile());
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentLength(file.getFile().length());
responseHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
responseHeaders.set("Content-Disposition", "attachment;filename=" + file.getFilename());
responseHeaders.set("Access-Control-Expose-Headers", "Content-Disposition");
responseHeaders.get("Access-Control-Expose-Headers").add("Content-Type");
byte[] content = IOUtils.toByteArray(resource);
resource.close();
Files.deleteIfExists(file.getFile().toPath());
return new ResponseEntity<>(content,
responseHeaders,
HttpStatus.OK);
} else {
DatasetWizardModel dataset = this.datasetManager.getSingle(id, principal);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DatasetWizardModel>().status(ApiMessageCode.NO_MESSAGE).payload(dataset));
}
} catch (Exception e) {
if (e instanceof UnauthorisedException) {
if (e instanceof UnauthorisedException) {
return ResponseEntity.status(HttpStatus.FORBIDDEN).body(new ResponseItem<DataManagementPlanOverviewModel>().status(ApiMessageCode.ERROR_MESSAGE));
} else if (e instanceof NoResultException) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(new ResponseItem<DataManagementPlanOverviewModel>().status(ApiMessageCode.ERROR_MESSAGE));
} else {
throw e;
}
}
}
return null; // ????
}
@RequestMapping(method = RequestMethod.GET, value = {"/public/{id}"}, produces = "application/json")
public @ResponseBody
ResponseEntity getSinglePublic(@PathVariable String id) throws Exception {
try {
DatasetWizardModel dataset = this.datasetManager.getSinglePublic(id);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DatasetWizardModel>().status(ApiMessageCode.NO_MESSAGE).payload(dataset));
}
catch (Exception ex) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem<DatasetWizardModel>().status(ApiMessageCode.NO_MESSAGE).message(ex.getMessage()));
}
}
@Transactional
@RequestMapping(method = RequestMethod.DELETE, value = {"{id}"}, produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<Dataset>> delete(@PathVariable(value = "id") UUID id, Principal principal) throws Exception {
new DatasetWizardManager().delete(this.getApiContext(), id);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<Dataset>().status(ApiMessageCode.SUCCESS_MESSAGE).message("Deleted"));
}
@Transactional
@RequestMapping(method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<Dataset>> createOrUpdate(@RequestBody DatasetWizardModel profile, Principal principal) throws Exception {
this.datasetManager.createOrUpdate(profile, principal);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<eu.eudat.data.entities.Dataset>().status(ApiMessageCode.SUCCESS_MESSAGE).message("Created").payload(null));
}
@RequestMapping(method = RequestMethod.GET, value = {"/getPDF/{id}"})
public @ResponseBody
ResponseEntity<byte[]> getPDFDocument(@PathVariable String id, @ClaimedAuthorities(claims = {Authorities.ADMIN, Authorities.MANAGER, Authorities.USER, Authorities.ANONYMOUS}) Principal principal) throws IllegalAccessException, IOException, InstantiationException, InterruptedException {
FileEnvelope file = datasetManager.getWordDocumentFile(this.configLoader, id, this.getApiContext().getUtilitiesService().getVisibilityRuleService(), principal);
String fileName = file.getFilename();
if (fileName.endsWith(".docx")){
fileName = fileName.substring(0, fileName.length() - 5);
}
File pdffile = datasetManager.convertToPDF(file, environment);
InputStream resource = new FileInputStream(pdffile);
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentLength(pdffile.length());
responseHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
responseHeaders.set("Content-Disposition", "attachment;filename=" + fileName + ".pdf");
responseHeaders.set("Access-Control-Expose-Headers", "Content-Disposition");
responseHeaders.get("Access-Control-Expose-Headers").add("Content-Type");
byte[] content = IOUtils.toByteArray(resource);
resource.close();
Files.deleteIfExists(file.getFile().toPath());
Files.deleteIfExists(pdffile.toPath());
return new ResponseEntity<>(content,
responseHeaders,
HttpStatus.OK);
}
@RequestMapping(method = RequestMethod.GET, value = {"/get/{id}"}, produces = "application/json")
public ResponseEntity<ResponseItem<PagedDatasetProfile>> getSingle(@PathVariable String id) {
eu.eudat.data.entities.DatasetProfile profile = this.getApiContext().getOperationsContext().getDatabaseRepository().getDatasetProfileDao().find(UUID.fromString(id));
eu.eudat.models.data.user.composite.DatasetProfile datasetprofile = userManager.generateDatasetProfileModel(profile);
PagedDatasetProfile pagedDatasetProfile = new PagedDatasetProfile();
pagedDatasetProfile.buildPagedDatasetProfile(datasetprofile);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<PagedDatasetProfile>().status(ApiMessageCode.NO_MESSAGE).payload(pagedDatasetProfile));
}
@Transactional
@RequestMapping(method = RequestMethod.GET, value = {"/{id}/unlock"}, produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<Dataset>> unlock(@PathVariable(value = "id") UUID id, Principal principal) throws Exception {
try {
new DatasetWizardManager().unlock(this.getApiContext(), id);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<Dataset>().status(ApiMessageCode.SUCCESS_MESSAGE).message("Unlocked"));
} catch (DatasetWizardCannotUnlockException datasetWizardCannotUnlockException) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem<Dataset>().status(ApiMessageCode.ERROR_MESSAGE).message(datasetWizardCannotUnlockException.getMessage()));
}
}
@RequestMapping(method = RequestMethod.POST, value = {"/upload"})
public ResponseEntity<ResponseItem> datasetXmlImport(@RequestParam("file") MultipartFile file, @RequestParam("dmpId") String dmpId, @RequestParam("datasetProfileId") String datasetProfileId, Principal principal) {
try {
Dataset dataset = this.datasetManager.createDatasetFromXml(file, dmpId, datasetProfileId, principal);
if (dataset != null){
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE));
}
else {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem().status(ApiMessageCode.NO_MESSAGE).message("Import was unsuccessful."));
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem().status(ApiMessageCode.NO_MESSAGE).message("Import was unsuccessful."));
}
}
@RequestMapping(method = RequestMethod.GET, value = {"profile/{id}"}, produces = "application/json")
public @ResponseBody
ResponseEntity getSingleProfileUpdate(@PathVariable String id, @ClaimedAuthorities(claims = {ANONYMOUS}) Principal principal) throws IllegalAccessException, IOException, InstantiationException {
DatasetWizardModel dataset = this.datasetManager.datasetUpdateProfile(id);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DatasetWizardModel>().status(ApiMessageCode.NO_MESSAGE).payload(dataset));
}
}

View File

@ -1,42 +1,84 @@
package eu.eudat.controllers; package eu.eudat.controllers;
import eu.eudat.data.entities.Dataset; import eu.eudat.data.entities.Dataset;
import eu.eudat.data.query.items.item.dataset.DatasetWizardAutocompleteRequest;
import eu.eudat.data.query.items.item.datasetprofile.DatasetProfileWizardAutocompleteRequest;
import eu.eudat.data.query.items.table.dataset.DatasetPublicTableRequest; import eu.eudat.data.query.items.table.dataset.DatasetPublicTableRequest;
import eu.eudat.data.query.items.table.dataset.DatasetTableRequest; import eu.eudat.data.query.items.table.dataset.DatasetTableRequest;
import eu.eudat.data.query.items.table.datasetprofile.DatasetProfileTableRequestItem; import eu.eudat.data.query.items.table.datasetprofile.DatasetProfileTableRequestItem;
import eu.eudat.exceptions.datasetwizard.DatasetWizardCannotUnlockException;
import eu.eudat.exceptions.security.UnauthorisedException;
import eu.eudat.logic.managers.DatasetManager; import eu.eudat.logic.managers.DatasetManager;
import eu.eudat.logic.managers.DatasetWizardManager;
import eu.eudat.logic.managers.UserManager;
import eu.eudat.logic.proxy.config.configloaders.ConfigLoader;
import eu.eudat.logic.security.claims.ClaimedAuthorities; import eu.eudat.logic.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.utilities.documents.helpers.FileEnvelope;
import eu.eudat.models.data.dataset.DatasetOverviewModel;
import eu.eudat.models.data.datasetprofile.DatasetProfileListingModel; import eu.eudat.models.data.datasetprofile.DatasetProfileListingModel;
import eu.eudat.models.data.datasetwizard.DataManagentPlanListingModel;
import eu.eudat.models.data.datasetwizard.DatasetWizardModel;
import eu.eudat.models.data.dmp.AssociatedProfile;
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.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.security.Principal;
import eu.eudat.models.data.user.composite.PagedDatasetProfile;
import eu.eudat.types.ApiMessageCode; import eu.eudat.types.ApiMessageCode;
import eu.eudat.types.Authorities; import eu.eudat.types.Authorities;
import org.apache.poi.util.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
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 org.springframework.web.multipart.MultipartFile;
import javax.persistence.NoResultException;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
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
@RequestMapping(value = {"/api/datasets/"}) @RequestMapping(value = {"/api/datasets/"})
public class Datasets extends BaseController { public class Datasets extends BaseController {
private static final Logger logger = LoggerFactory.getLogger(Datasets.class);
private Environment environment;
private DatasetManager datasetManager; private DatasetManager datasetManager;
private ConfigLoader configLoader;
private UserManager userManager;
@Autowired @Autowired
public Datasets(ApiContext apiContext, DatasetManager datasetManager) { public Datasets(ApiContext apiContext, Environment environment, DatasetManager datasetManager, ConfigLoader configLoader, UserManager userManager) {
super(apiContext); super(apiContext);
this.environment = environment;
this.datasetManager = datasetManager; this.datasetManager = datasetManager;
this.configLoader = configLoader;
this.userManager = userManager;
} }
/*
* Data Retrieval
* */
@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, @ClaimedAuthorities(claims = {Authorities.ADMIN, Authorities.MANAGER, Authorities.USER, Authorities.ANONYMOUS}) Principal principal) throws Exception {
@ -52,12 +94,70 @@ public class Datasets extends BaseController {
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));
} }
@Transactional @RequestMapping(method = RequestMethod.GET, value = {"/overview/{id}"})
@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 getOverviewSingle(@PathVariable String id,@ClaimedAuthorities(claims = {Authorities.ADMIN, Authorities.MANAGER, Authorities.USER, Authorities.ANONYMOUS}) Principal principal) {
this.datasetManager.makePublic(this.getApiContext().getOperationsContext().getDatabaseRepository().getDatasetDao(), id); try {
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<Dataset>().status(ApiMessageCode.SUCCESS_MESSAGE).message(this.getApiContext().getHelpersService().getMessageSource().getMessage("dataset.public", new Object[]{}, locale))); DatasetOverviewModel dataset = this.datasetManager.getOverviewSingle(id, principal, false);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DatasetOverviewModel>().status(ApiMessageCode.NO_MESSAGE).payload(dataset));
} catch (Exception e) {
if (e instanceof UnauthorisedException) {
return ResponseEntity.status(HttpStatus.FORBIDDEN).body(new ResponseItem<DatasetOverviewModel>().status(ApiMessageCode.ERROR_MESSAGE));
} else {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(new ResponseItem<DatasetOverviewModel>().status(ApiMessageCode.ERROR_MESSAGE));
}
}
}
@RequestMapping(method = RequestMethod.GET, value = {"/publicOverview/{id}"})
public @ResponseBody
ResponseEntity getOverviewSinglePublic(@PathVariable String id, @ClaimedAuthorities(claims = {Authorities.ADMIN, Authorities.MANAGER, Authorities.USER, Authorities.ANONYMOUS}) Principal principal) throws Exception {
// try {
DatasetOverviewModel dataset = this.datasetManager.getOverviewSingle(id, principal, true);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DatasetOverviewModel>().status(ApiMessageCode.NO_MESSAGE).payload(dataset));
// } catch (Exception ex) {
// return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem<DataManagementPlanOverviewModel>().status(ApiMessageCode.NO_MESSAGE).message(ex.getMessage()));
// }
}
@javax.transaction.Transactional
@RequestMapping(method = RequestMethod.GET, value = {"{id}"}, produces = "application/json")
public @ResponseBody
ResponseEntity getSingle(@PathVariable String id, @RequestHeader("Content-Type") String contentType, @ClaimedAuthorities(claims = {Authorities.ADMIN, Authorities.MANAGER, Authorities.USER, Authorities.ANONYMOUS}) Principal principal) throws IllegalAccessException, IOException, InstantiationException {
try {
if (contentType.equals("application/xml")) {
VisibilityRuleService visibilityRuleService = this.getApiContext().getUtilitiesService().getVisibilityRuleService();
return this.datasetManager.getDocument(id, visibilityRuleService, contentType, principal);
} else if (contentType.equals("application/msword")) {
FileEnvelope file = datasetManager.getWordDocumentFile(this.configLoader, id, this.getApiContext().getUtilitiesService().getVisibilityRuleService(), principal);
InputStream resource = new FileInputStream(file.getFile());
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentLength(file.getFile().length());
responseHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
responseHeaders.set("Content-Disposition", "attachment;filename=" + file.getFilename());
responseHeaders.set("Access-Control-Expose-Headers", "Content-Disposition");
responseHeaders.get("Access-Control-Expose-Headers").add("Content-Type");
byte[] content = IOUtils.toByteArray(resource);
resource.close();
Files.deleteIfExists(file.getFile().toPath());
return new ResponseEntity<>(content,
responseHeaders,
HttpStatus.OK);
} else {
DatasetWizardModel dataset = this.datasetManager.getSingle(id, principal);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DatasetWizardModel>().status(ApiMessageCode.NO_MESSAGE).payload(dataset));
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
if (e instanceof UnauthorisedException) {
return ResponseEntity.status(HttpStatus.FORBIDDEN).body(new ResponseItem<DataManagementPlanOverviewModel>().status(ApiMessageCode.ERROR_MESSAGE));
} else if (e instanceof NoResultException) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(new ResponseItem<DataManagementPlanOverviewModel>().status(ApiMessageCode.ERROR_MESSAGE));
} else {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(new ResponseItem<DataManagementPlanOverviewModel>().status(ApiMessageCode.ERROR_MESSAGE));
}
}
} }
@RequestMapping(method = RequestMethod.POST, value = {"/datasetProfilesUsedByDatasets/paged"}, produces = "application/json") @RequestMapping(method = RequestMethod.POST, value = {"/datasetProfilesUsedByDatasets/paged"}, produces = "application/json")
@ -67,6 +167,143 @@ public class Datasets extends BaseController {
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")
public @ResponseBody
ResponseEntity<ResponseItem<List<DataManagentPlanListingModel>>> getUserDmps(@RequestBody DatasetWizardAutocompleteRequest datasetWizardAutocompleteRequest, Principal principal) throws IllegalAccessException, InstantiationException {
List<DataManagentPlanListingModel> dataManagementPlans = DatasetWizardManager.getUserDmps(this.getApiContext().getOperationsContext().getDatabaseRepository().getDmpDao(), datasetWizardAutocompleteRequest, principal);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List<DataManagentPlanListingModel>>().status(ApiMessageCode.NO_MESSAGE).payload(dataManagementPlans));
}
@RequestMapping(method = RequestMethod.POST, value = {"/getAvailableProfiles"}, produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<List<AssociatedProfile>>> getAvailableProfiles(@RequestBody DatasetProfileWizardAutocompleteRequest datasetProfileWizardAutocompleteRequest, @ClaimedAuthorities(claims = {ANONYMOUS}) Principal principal) throws IllegalAccessException, InstantiationException {
List<AssociatedProfile> dataManagementPlans = DatasetWizardManager.getAvailableProfiles(this.getApiContext().getOperationsContext().getDatabaseRepository().getDmpDao(), datasetProfileWizardAutocompleteRequest);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List<AssociatedProfile>>().status(ApiMessageCode.NO_MESSAGE).payload(dataManagementPlans));
}
@RequestMapping(method = RequestMethod.GET, value = {"/public/{id}"}, produces = "application/json")
public @ResponseBody
ResponseEntity getSinglePublic(@PathVariable String id) throws Exception {
try {
DatasetWizardModel dataset = this.datasetManager.getSinglePublic(id);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DatasetWizardModel>().status(ApiMessageCode.NO_MESSAGE).payload(dataset));
}
catch (Exception ex) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem<DatasetWizardModel>().status(ApiMessageCode.NO_MESSAGE).message(ex.getMessage()));
}
}
@RequestMapping(method = RequestMethod.GET, value = {"/get/{id}"}, produces = "application/json")
public ResponseEntity<ResponseItem<PagedDatasetProfile>> getSingle(@PathVariable String id) {
eu.eudat.data.entities.DatasetProfile profile = this.getApiContext().getOperationsContext().getDatabaseRepository().getDatasetProfileDao().find(UUID.fromString(id));
eu.eudat.models.data.user.composite.DatasetProfile datasetprofile = userManager.generateDatasetProfileModel(profile);
PagedDatasetProfile pagedDatasetProfile = new PagedDatasetProfile();
pagedDatasetProfile.buildPagedDatasetProfile(datasetprofile);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<PagedDatasetProfile>().status(ApiMessageCode.NO_MESSAGE).payload(pagedDatasetProfile));
}
@RequestMapping(method = RequestMethod.GET, value = {"profile/{id}"}, produces = "application/json")
public @ResponseBody
ResponseEntity getSingleProfileUpdate(@PathVariable String id, @ClaimedAuthorities(claims = {ANONYMOUS}) Principal principal) throws IllegalAccessException, IOException, InstantiationException {
DatasetWizardModel dataset = this.datasetManager.datasetUpdateProfile(id);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DatasetWizardModel>().status(ApiMessageCode.NO_MESSAGE).payload(dataset));
}
/*
* Data Export
* */
@RequestMapping(method = RequestMethod.GET, value = {"/getPDF/{id}"})
public @ResponseBody
ResponseEntity<byte[]> getPDFDocument(@PathVariable String id, @ClaimedAuthorities(claims = {Authorities.ADMIN, Authorities.MANAGER, Authorities.USER, Authorities.ANONYMOUS}) Principal principal) throws IllegalAccessException, IOException, InstantiationException, InterruptedException {
FileEnvelope file = datasetManager.getWordDocumentFile(this.configLoader, id, this.getApiContext().getUtilitiesService().getVisibilityRuleService(), principal);
String fileName = file.getFilename();
if (fileName.endsWith(".docx")){
fileName = fileName.substring(0, fileName.length() - 5);
}
File pdffile = datasetManager.convertToPDF(file, environment);
InputStream resource = new FileInputStream(pdffile);
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentLength(pdffile.length());
responseHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
responseHeaders.set("Content-Disposition", "attachment;filename=" + fileName + ".pdf");
responseHeaders.set("Access-Control-Expose-Headers", "Content-Disposition");
responseHeaders.get("Access-Control-Expose-Headers").add("Content-Type");
byte[] content = IOUtils.toByteArray(resource);
resource.close();
Files.deleteIfExists(file.getFile().toPath());
Files.deleteIfExists(pdffile.toPath());
return new ResponseEntity<>(content,
responseHeaders,
HttpStatus.OK);
}
/*
* Data Management
* */
@javax.transaction.Transactional
@RequestMapping(method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<UUID>> createOrUpdate(@RequestBody DatasetWizardModel profile, Principal principal) throws Exception {
Dataset dataset = this.datasetManager.createOrUpdate(profile, principal);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<UUID>().status(ApiMessageCode.SUCCESS_MESSAGE).message("Created").payload(dataset.getId()));
}
@Transactional
@RequestMapping(method = RequestMethod.GET, value = {"/makepublic/{id}"}, produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<Dataset>> makePublic(@PathVariable UUID id, Principal principal, Locale locale) throws Exception {
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)));
}
@javax.transaction.Transactional
@RequestMapping(method = RequestMethod.DELETE, value = {"/delete/{id}"}, produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<Dataset>> delete(@PathVariable(value = "id") UUID id, Principal principal) throws Exception {
new DatasetWizardManager().delete(this.getApiContext(), id);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<Dataset>().status(ApiMessageCode.SUCCESS_MESSAGE).message("Deleted"));
}
@javax.transaction.Transactional
@RequestMapping(method = RequestMethod.GET, value = {"/{id}/unlock"}, produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<Dataset>> unlock(@PathVariable(value = "id") UUID id, Principal principal) throws Exception {
try {
new DatasetWizardManager().unlock(this.getApiContext(), id);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<Dataset>().status(ApiMessageCode.SUCCESS_MESSAGE).message("Unlocked"));
} catch (DatasetWizardCannotUnlockException datasetWizardCannotUnlockException) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem<Dataset>().status(ApiMessageCode.ERROR_MESSAGE).message(datasetWizardCannotUnlockException.getMessage()));
}
}
/*
* Data Import
* */
@RequestMapping(method = RequestMethod.POST, value = {"/upload"})
public ResponseEntity<ResponseItem> datasetXmlImport(@RequestParam("file") MultipartFile file, @RequestParam("dmpId") String dmpId, @RequestParam("datasetProfileId") String datasetProfileId, Principal principal) {
try {
Dataset dataset = this.datasetManager.createDatasetFromXml(file, dmpId, datasetProfileId, principal);
if (dataset != null){
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE));
}
else {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem().status(ApiMessageCode.NO_MESSAGE).message("Import was unsuccessful."));
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem().status(ApiMessageCode.NO_MESSAGE).message("Import was unsuccessful."));
}
}
/*
* Data Index
* */
@javax.transaction.Transactional @javax.transaction.Transactional
@RequestMapping(method = RequestMethod.POST, value = {"/index"}) @RequestMapping(method = RequestMethod.POST, value = {"/index"})
public @ResponseBody public @ResponseBody
@ -82,5 +319,7 @@ public class Datasets extends BaseController {
this.datasetManager.clearIndex(principal); this.datasetManager.clearIndex(principal);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<eu.eudat.data.entities.Dataset>().status(ApiMessageCode.SUCCESS_MESSAGE).message("Cleared").payload(null)); return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<eu.eudat.data.entities.Dataset>().status(ApiMessageCode.SUCCESS_MESSAGE).message("Cleared").payload(null));
} }
} }

View File

@ -31,6 +31,7 @@ import eu.eudat.logic.services.operations.authentication.AuthenticationService;
import eu.eudat.models.data.helpers.responses.ResponseItem; import eu.eudat.models.data.helpers.responses.ResponseItem;
import eu.eudat.models.data.login.Credentials; import eu.eudat.models.data.login.Credentials;
import eu.eudat.models.data.login.LoginInfo; import eu.eudat.models.data.login.LoginInfo;
import eu.eudat.models.data.principal.PrincipalModel;
import eu.eudat.models.data.security.Principal; import eu.eudat.models.data.security.Principal;
import eu.eudat.types.ApiMessageCode; import eu.eudat.types.ApiMessageCode;
import org.slf4j.Logger; import org.slf4j.Logger;
@ -91,17 +92,17 @@ public class Login {
@Transactional @Transactional
@RequestMapping(method = RequestMethod.POST, value = {"/externallogin"}, consumes = "application/json", produces = "application/json") @RequestMapping(method = RequestMethod.POST, value = {"/externallogin"}, consumes = "application/json", produces = "application/json")
public @ResponseBody public @ResponseBody
ResponseEntity<ResponseItem<Principal>> externallogin(@RequestBody LoginInfo credentials) throws GeneralSecurityException, NullEmailException { ResponseEntity<ResponseItem<PrincipalModel>> externallogin(@RequestBody LoginInfo credentials) throws GeneralSecurityException, NullEmailException {
logger.info("Trying To Login With " + credentials.getProvider()); logger.info("Trying To Login With " + credentials.getProvider());
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<Principal>().payload(customAuthenticationProvider.authenticate(credentials)).status(ApiMessageCode.SUCCESS_MESSAGE)); return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<PrincipalModel>().payload(customAuthenticationProvider.authenticate(credentials)).status(ApiMessageCode.SUCCESS_MESSAGE));
} }
@Transactional @Transactional
@RequestMapping(method = RequestMethod.POST, value = {"/nativelogin"}, consumes = "application/json", produces = "application/json") @RequestMapping(method = RequestMethod.POST, value = {"/nativelogin"}, consumes = "application/json", produces = "application/json")
public @ResponseBody public @ResponseBody
ResponseEntity<ResponseItem<Principal>> nativelogin(@RequestBody Credentials credentials) throws NullEmailException { ResponseEntity<ResponseItem<PrincipalModel>> nativelogin(@RequestBody Credentials credentials) throws NullEmailException {
logger.info(credentials.getUsername() + " Trying To Login"); logger.info(credentials.getUsername() + " Trying To Login");
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<Principal>().payload(userManager.authenticate(this.nonVerifiedUserAuthenticationService, credentials)).status(ApiMessageCode.SUCCESS_MESSAGE)); return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<PrincipalModel>().payload(userManager.authenticate(this.nonVerifiedUserAuthenticationService, credentials)).status(ApiMessageCode.SUCCESS_MESSAGE));
} }
@RequestMapping(method = RequestMethod.GET, value = {"/twitterRequestToken"}, produces = "application/json") @RequestMapping(method = RequestMethod.GET, value = {"/twitterRequestToken"}, produces = "application/json")
@ -148,9 +149,11 @@ public class Login {
@RequestMapping(method = RequestMethod.POST, value = {"/me"}, consumes = "application/json", produces = "application/json") @RequestMapping(method = RequestMethod.POST, value = {"/me"}, consumes = "application/json", produces = "application/json")
public @ResponseBody public @ResponseBody
ResponseEntity<ResponseItem<Principal>> authMe(Principal principal) throws NullEmailException { ResponseEntity<ResponseItem<PrincipalModel>> authMe(Principal principal) throws NullEmailException {
logger.info(principal + " Getting Me"); logger.info(principal + " Getting Me");
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<Principal>().payload(this.nonVerifiedUserAuthenticationService.Touch(principal.getToken())).status(ApiMessageCode.NO_MESSAGE)); Principal principal1 = this.nonVerifiedUserAuthenticationService.Touch(principal.getToken());
PrincipalModel principalModel = PrincipalModel.fromEntity(principal1);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<PrincipalModel>().payload(principalModel).status(ApiMessageCode.NO_MESSAGE));
} }
@Transactional @Transactional

View File

@ -1,6 +1,8 @@
package eu.eudat.controllers; package eu.eudat.controllers;
import eu.eudat.data.entities.Dataset;
import eu.eudat.data.entities.DatasetProfile;
import eu.eudat.data.entities.Funder; import eu.eudat.data.entities.Funder;
import eu.eudat.data.entities.Project; import eu.eudat.data.entities.Project;
import eu.eudat.logic.managers.DatasetManager; import eu.eudat.logic.managers.DatasetManager;
@ -86,8 +88,8 @@ public class QuickWizardController extends BaseController {
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, principal);
UUID uuid = quickWizard.getDmp().getDatasetProfile().getId(); DatasetProfile profile = quickWizard.getDmp().getDatasetProfile();
DatasetWizardModel datasetWizardModel = dataset.toDataModel(dmp, uuid); DatasetWizardModel datasetWizardModel = dataset.toDataModel(dmp, profile);
this.datasetManager.createOrUpdate(datasetWizardModel, principal); this.datasetManager.createOrUpdate(datasetWizardModel, principal);
} }
@ -98,7 +100,10 @@ public class QuickWizardController extends BaseController {
public @ResponseBody public @ResponseBody
ResponseEntity<ResponseItem<DatasetCreateWizardModel>> addDatasetWizard(@RequestBody DatasetCreateWizardModel datasetCreateWizardModel, Principal principal) throws Exception{ ResponseEntity<ResponseItem<DatasetCreateWizardModel>> addDatasetWizard(@RequestBody DatasetCreateWizardModel datasetCreateWizardModel, Principal principal) throws Exception{
for(DatasetDescriptionQuickWizardModel dataset : datasetCreateWizardModel.getDatasets().getDatasetsList()){ for(DatasetDescriptionQuickWizardModel dataset : datasetCreateWizardModel.getDatasets().getDatasetsList()){
this.datasetManager.createOrUpdate(dataset.toDataModel(datasetCreateWizardModel.getDmpMeta().getDmp(), datasetCreateWizardModel.getDmpMeta().getDatasetProfile().getId()), principal); DatasetProfile profile = new DatasetProfile();
profile.setId(datasetCreateWizardModel.getDmpMeta().getDatasetProfile().getId());
profile.setLabel(datasetCreateWizardModel.getDmpMeta().getDatasetProfile().getLabel());
this.datasetManager.createOrUpdate(dataset.toDataModel(datasetCreateWizardModel.getDmpMeta().getDmp(), profile), principal);
} }
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

@ -48,8 +48,12 @@ public class TagController extends BaseController {
//ExternalUrlCriteria externalUrlCriteria = new ExternalUrlCriteria(query); //ExternalUrlCriteria externalUrlCriteria = new ExternalUrlCriteria(query);
/*List<Map<String, String>> remoteRepos = this.getApiContext().getOperationsContext().getRemoteFetcher().getTags(externalUrlCriteria, type); /*List<Map<String, String>> remoteRepos = this.getApiContext().getOperationsContext().getRemoteFetcher().getTags(externalUrlCriteria, type);
TagExternalSourcesModel researchersExternalSourcesModel = new TagExternalSourcesModel().fromExternalItem(remoteRepos);*/ TagExternalSourcesModel researchersExternalSourcesModel = new TagExternalSourcesModel().fromExternalItem(remoteRepos);*/
if (this.getApiContext().getOperationsContext().getElasticRepository().getDatasetRepository().exists()) {
List<Tag> tags = this.getApiContext().getOperationsContext().getElasticRepository().getDatasetRepository().query(new DatasetCriteria()).stream().map(Dataset::getTags).flatMap(Collection::stream).filter(StreamDistinctBy.distinctByKey(Tag::getId)).collect(Collectors.toList()); List<Tag> tags = this.getApiContext().getOperationsContext().getElasticRepository().getDatasetRepository().query(new DatasetCriteria()).stream().map(Dataset::getTags).flatMap(Collection::stream).filter(StreamDistinctBy.distinctByKey(Tag::getId)).collect(Collectors.toList());
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List<Tag>>().payload(tags).status(ApiMessageCode.NO_MESSAGE)); return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List<Tag>>().payload(tags).status(ApiMessageCode.NO_MESSAGE));
} else {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(new ResponseItem<List<Tag>>().status(ApiMessageCode.ERROR_MESSAGE).message("Elastic Services are not available"));
}
} }
} }

View File

@ -14,6 +14,7 @@ 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.xml.bind.JAXBException;
import java.util.List; import java.util.List;
import java.util.UUID; import java.util.UUID;
@ -41,7 +42,7 @@ public class UserInvitationController extends BaseController {
@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) { ResponseEntity<ResponseItem<UUID>> exchange(@PathVariable UUID invitationID, Principal principal) throws JAXBException {
UUID dmpId = invitationsManager.assignUserAcceptedInvitation(invitationID, principal); UUID dmpId = invitationsManager.assignUserAcceptedInvitation(invitationID, principal);
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));
} }

View File

@ -0,0 +1,22 @@
package eu.eudat.criteria;
public class RecentActivityCriteria {
private String like;
private String order;
public String getLike() {
return like;
}
public void setLike(String like) {
this.like = like;
}
public String getOrder() {
return order;
}
public void setOrder(String order) {
this.order = order;
}
}

View File

@ -17,6 +17,7 @@ public class PrincipalBuilder extends Builder<Principal> {
private UUID id; private UUID id;
private UUID token; private UUID token;
private String name; private String name;
private String email;
private Date expiresAt; private Date expiresAt;
private String avatarUrl; private String avatarUrl;
private Set<Authorities> authorities; private Set<Authorities> authorities;
@ -43,6 +44,11 @@ public class PrincipalBuilder extends Builder<Principal> {
return this; return this;
} }
public PrincipalBuilder email(String email) {
this.email = email;
return this;
}
public PrincipalBuilder expiresAt(Date expiresAt) { public PrincipalBuilder expiresAt(Date expiresAt) {
this.expiresAt = expiresAt; this.expiresAt = expiresAt;
return this; return this;
@ -98,6 +104,7 @@ public class PrincipalBuilder extends Builder<Principal> {
Principal principal = new Principal(); Principal principal = new Principal();
principal.setAuthorities(authorities); principal.setAuthorities(authorities);
principal.setName(name); principal.setName(name);
principal.setEmail(email);
principal.setExpiresAt(expiresAt); principal.setExpiresAt(expiresAt);
principal.setToken(token); principal.setToken(token);
principal.setId(id); principal.setId(id);

View File

@ -1,38 +1,59 @@
package eu.eudat.logic.managers; package eu.eudat.logic.managers;
import eu.eudat.data.dao.criteria.*; import eu.eudat.data.dao.criteria.DataManagementPlanCriteria;
import eu.eudat.data.dao.criteria.DatasetCriteria;
import eu.eudat.data.dao.criteria.GrantCriteria;
import eu.eudat.data.dao.criteria.OrganisationCriteria;
import eu.eudat.data.dao.entities.DMPDao; import eu.eudat.data.dao.entities.DMPDao;
import eu.eudat.data.dao.entities.DatasetDao; import eu.eudat.data.dao.entities.DatasetDao;
import eu.eudat.data.dao.entities.OrganisationDao;
import eu.eudat.data.dao.entities.GrantDao; import eu.eudat.data.dao.entities.GrantDao;
import eu.eudat.data.entities.*; import eu.eudat.data.dao.entities.OrganisationDao;
import eu.eudat.data.query.items.table.dmp.DataManagmentPlanPublicTableRequest; import eu.eudat.data.entities.DMP;
import eu.eudat.data.entities.Dataset;
import eu.eudat.data.entities.Grant;
import eu.eudat.data.entities.UserInfo;
import eu.eudat.data.query.PaginationService;
import eu.eudat.elastic.entities.Dmp; import eu.eudat.elastic.entities.Dmp;
import eu.eudat.logic.builders.model.models.RecentActivityDataBuilder; import eu.eudat.logic.builders.model.models.RecentActivityDataBuilder;
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.HintedModelFactory;
import eu.eudat.models.data.dashboard.recent.RecentActivity; import eu.eudat.models.data.dashboard.recent.RecentActivity;
import eu.eudat.models.data.dashboard.recent.RecentActivityData; import eu.eudat.models.data.dashboard.recent.RecentActivityData;
import eu.eudat.models.data.dashboard.recent.model.RecentActivityModel;
import eu.eudat.models.data.dashboard.recent.model.RecentDatasetModel;
import eu.eudat.models.data.dashboard.recent.model.RecentDmpModel;
import eu.eudat.models.data.dashboard.recent.tablerequest.RecentActivityTableRequest;
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.security.Principal; import eu.eudat.models.data.security.Principal;
import eu.eudat.queryable.QueryableList;
import eu.eudat.types.searchbar.SearchBarItemType; import eu.eudat.types.searchbar.SearchBarItemType;
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 javax.transaction.Transactional;
import java.io.IOException; import java.io.IOException;
import java.util.LinkedList; import java.util.*;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import java.util.stream.Stream;
@Component @Component
public class DashBoardManager { public class DashBoardManager {
private static final Logger logger = LoggerFactory.getLogger(DashBoardManager.class); private static final Logger logger = LoggerFactory.getLogger(DashBoardManager.class);
private final Map<String, Comparator<RecentActivityModel>> comparators = Stream.of(new Object[][] {
{ "modified", Comparator.comparing(o -> ((RecentActivityModel)o).getModified()).reversed()},
{ "created", Comparator.comparing(o -> ((RecentActivityModel)o).getCreated()).reversed()},
{ "label", Comparator.comparing(o -> ((RecentActivityModel)o).getTitle())},
{ "status", Comparator.comparing(o -> ((RecentActivityModel)o).getStatus()).reversed()},
{ "finalizedAt", Comparator.comparing(o -> ((RecentActivityModel)o).getFinalizedAt(), 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]));
private ApiContext apiContext; private ApiContext apiContext;
private DatabaseRepository databaseRepository; private DatabaseRepository databaseRepository;
@ -45,17 +66,12 @@ public class DashBoardManager {
public DashBoardStatistics getStatistics() { public DashBoardStatistics getStatistics() {
DashBoardStatistics statistics = new DashBoardStatistics(); DashBoardStatistics statistics = new DashBoardStatistics();
DataManagmentPlanPublicTableRequest publicTableRequest = new DataManagmentPlanPublicTableRequest(); DataManagementPlanCriteria publicCriteria = new DataManagementPlanCriteria();
publicCriteria.setIsPublic(true);
DataManagementPlanPublicCriteria publicCriteria = new DataManagementPlanPublicCriteria(); publicCriteria.setOnlyPublic(true);
publicCriteria.setAllVersions(false); publicCriteria.setAllVersions(false);
publicTableRequest.setCriteria(publicCriteria); List<DMP> dmps = apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().getWithCriteria(publicCriteria).toList();
publicTableRequest.setQuery(databaseRepository.getDmpDao().asQueryable());
List<DMP> dmps = publicTableRequest.applyCriteria().toList();
// DataManagementPlanCriteria dataManagementPlanCriteria = new DataManagementPlanCriteria(); // DataManagementPlanCriteria dataManagementPlanCriteria = new DataManagementPlanCriteria();
OrganisationCriteria organisationCriteria = new OrganisationCriteria(); OrganisationCriteria organisationCriteria = new OrganisationCriteria();
@ -121,10 +137,10 @@ public class DashBoardManager {
List<Integer> roles = new LinkedList<>(); List<Integer> roles = new LinkedList<>();
List<Dmp> finalDmps = dmps; List<Dmp> finalDmps = dmps;
CompletableFuture dmpFuture = dataManagementPlanRepository.getAuthenticated(dmps != null ? dataManagementPlanRepository.asQueryable().where((builder, root) -> root.get("id").in(finalDmps.stream().map(Dmp::getId).collect(Collectors.toList()))) : dataManagementPlanRepository.getWithCriteria(dataManagementPlanCriteria), principal.getId(), roles).countAsync() CompletableFuture dmpFuture = dataManagementPlanRepository.getAuthenticated((dmps != null && !dmps.isEmpty()) ? dataManagementPlanRepository.asQueryable().where((builder, root) -> root.get("id").in(finalDmps.stream().map(Dmp::getId).collect(Collectors.toList()))) : dataManagementPlanRepository.getWithCriteria(dataManagementPlanCriteria), principal.getId(), roles).distinct().countAsync()
.whenComplete((dmpsStats, throwable) -> statistics.setTotalDataManagementPlanCount(dmpsStats)); .whenComplete((dmpsStats, throwable) -> statistics.setTotalDataManagementPlanCount(dmpsStats));
List<eu.eudat.elastic.entities.Dataset> finalDatasets = datasets; List<eu.eudat.elastic.entities.Dataset> finalDatasets = datasets;
CompletableFuture datasetFuture = datasetRepository.getAuthenticated(datasets != null ? datasetRepository.asQueryable().where((builder, root) -> root.get("id").in(finalDatasets.stream().map(x -> UUID.fromString(x.getId())).collect(Collectors.toList()))) : datasetRepository.getWithCriteria(datasetCriteria), user, roles).countAsync() CompletableFuture datasetFuture = datasetRepository.getAuthenticated((datasets != null && !datasets.isEmpty()) ? datasetRepository.asQueryable().where((builder, root) -> root.get("id").in(finalDatasets.stream().map(x -> UUID.fromString(x.getId())).collect(Collectors.toList()))) : datasetRepository.getWithCriteria(datasetCriteria), user, roles).countAsync()
.whenComplete((datasetsStats, throwable) -> statistics.setTotalDataSetCount(datasetsStats)); .whenComplete((datasetsStats, throwable) -> statistics.setTotalDataSetCount(datasetsStats));
CompletableFuture grantFuture = grantRepository.getAuthenticated(grantRepository.getWithCriteria(grantCriteria), user).countAsync() CompletableFuture grantFuture = grantRepository.getAuthenticated(grantRepository.getWithCriteria(grantCriteria), user).countAsync()
.whenComplete((grantsStats, throwable) -> statistics.setTotalGrantCount(grantsStats)); .whenComplete((grantsStats, throwable) -> statistics.setTotalGrantCount(grantsStats));
@ -175,6 +191,135 @@ public class DashBoardManager {
return activity; return activity;
} }
@Transactional
public List<RecentActivityModel> getNewRecentActivity(RecentActivityTableRequest tableRequest, Principal principal) {
boolean isAuthenticated = principal.getId() != null;
List<RecentActivityModel> recentActivityModels = new ArrayList<>();
DMPDao dataManagementPlanRepository = databaseRepository.getDmpDao();
DatasetDao datasetRepository = databaseRepository.getDatasetDao();
UserInfo user = new UserInfo();
if (isAuthenticated) {
user.setId(principal.getId());
}
DatasetCriteria datasetCriteria = new DatasetCriteria();
datasetCriteria.setLike(tableRequest.getCriteria().getLike());
datasetCriteria.setAllVersions(false);
datasetCriteria.setIsPublic(!isAuthenticated);
DataManagementPlanCriteria dataManagementPlanCriteria = new DataManagementPlanCriteria();
dataManagementPlanCriteria.setAllVersions(false);
dataManagementPlanCriteria.setLike(tableRequest.getCriteria().getLike());
dataManagementPlanCriteria.setIsPublic(!isAuthenticated);
dataManagementPlanCriteria.setOnlyPublic(!isAuthenticated);
QueryableList<DMP> dmpList;
QueryableList<Dataset> datasetList;
List<eu.eudat.elastic.entities.Dataset> datasets = null;
List<eu.eudat.elastic.entities.Dmp> dmps = null;
if (apiContext.getOperationsContext().getElasticRepository().getDatasetRepository() != null) {
try {
eu.eudat.elastic.criteria.DatasetCriteria datasetElasticCriteria = new eu.eudat.elastic.criteria.DatasetCriteria();
datasetElasticCriteria.setLike(tableRequest.getCriteria().getLike());
datasetElasticCriteria.setAllowAllVersions(false);
datasetElasticCriteria.setPublic(!isAuthenticated);
datasets = apiContext.getOperationsContext().getElasticRepository().getDatasetRepository().query(datasetElasticCriteria);
}catch (Exception e) {
logger.warn(e.getMessage(), e);
datasets = null;
}
}
if (apiContext.getOperationsContext().getElasticRepository().getDmpRepository() != null) {
try {
eu.eudat.elastic.criteria.DmpCriteria dmpElasticCriteria = new eu.eudat.elastic.criteria.DmpCriteria();
dmpElasticCriteria.setLike(tableRequest.getCriteria().getLike());
dmpElasticCriteria.setAllowAllVersions(false);
dmpElasticCriteria.setPublic(!isAuthenticated);
dmps = apiContext.getOperationsContext().getElasticRepository().getDmpRepository().query(dmpElasticCriteria);
}catch (Exception e) {
logger.warn(e.getMessage(), e);
datasets = null;
}
}
if (dmps != null && !dmps.isEmpty()) {
List<Dmp> finalDmps = dmps;
dmpList = dataManagementPlanRepository.asQueryable().where((builder, root) -> root.get("id").in(finalDmps.stream().map(Dmp::getId).collect(Collectors.toList()))).distinct();
} else {
dmpList = dataManagementPlanRepository.getWithCriteria(dataManagementPlanCriteria).distinct();
}
if (datasets != null && !datasets.isEmpty()) {
List<eu.eudat.elastic.entities.Dataset> finalDatasets = datasets;
datasetList = datasetRepository.asQueryable().where((builder, root) -> root.get("id").in(finalDatasets.stream().map(x -> UUID.fromString(x.getId())).collect(Collectors.toList())));
} else {
datasetList = datasetRepository.getWithCriteria(datasetCriteria);
}
if (isAuthenticated) {
List<Integer> roles = new LinkedList<>();
dmpList = dataManagementPlanRepository.getAuthenticated(dmpList, principal.getId(), roles);
datasetList = datasetRepository.getAuthenticated(datasetList, user, roles);
}
PaginationService.applyOrder(dmpList, tableRequest.getOrderings());
for (int i = 0; i< tableRequest.getOrderings().getFields().length; i++) {
if (tableRequest.getOrderings().getFields()[i].contains("publishedAt")) {
String newField = tableRequest.getOrderings().getFields()[i].toCharArray()[0] + "dmp:publishedAt|join|";
tableRequest.getOrderings().getFields()[i] = newField;
}
}
PaginationService.applyOrder(datasetList, tableRequest.getOrderings());
/*CompletableFuture future = CompletableFuture.runAsync(() -> */{
recentActivityModels.addAll(dmpList
.withHint(HintedModelFactory.getHint(RecentDmpModel.class))
// .orderBy((builder, root) -> builder.desc(root.get(tableRequest.getCriteria().getOrder())))
.skip(tableRequest.getDmpOffset())
.take(tableRequest.getLength())
.select(item -> {
item.setDataset(
item.getDataset().stream()
.filter(dataset -> !dataset.getStatus().equals(Dataset.Status.DELETED.getValue()) && !dataset.getStatus().equals(Dataset.Status.CANCELED.getValue())).collect(Collectors.toList()).stream()
.filter(dataset -> dataset.getDmp().getUsers().stream()
.filter(x -> x.getUser().getId().equals(principal.getId()))
.collect(Collectors.toList()).size() > 0)
.collect(Collectors.toSet()));
return new RecentDmpModel().fromEntity(item);
}));
recentActivityModels.addAll(datasetList
.withHint(HintedModelFactory.getHint(RecentDatasetModel.class))
// .orderBy((builder, root) -> builder.desc(root.get(tableRequest.getCriteria().getOrder())))
.skip(tableRequest.getDatasetOffset())
.take(tableRequest.getLength())
.select(item -> {
return new RecentDatasetModel().fromEntity(item);
}));
}/*);*/
//GK: Shuffle the deck otherwise we will summon the DMPodia when sorting with status
int pos = -1;
for (int i = (recentActivityModels.size() / 2); i < recentActivityModels.size(); i++) {
RecentActivityModel recentActivityModel = recentActivityModels.remove(i);
while (pos < recentActivityModels.size()) {
pos++;
if (pos % 2 != 0) {
break;
}
}
recentActivityModels.add(pos, recentActivityModel);
}
//CompletableFuture.allOf(future).join();
// CompletableFuture.allOf(dmps, datasets).join();
return recentActivityModels.stream().sorted(this.comparators.get(tableRequest.getCriteria().getOrder())).limit(tableRequest.getLength()).collect(Collectors.toList());
}
public List<SearchBarItem> searchUserData(String like, Principal principal) { public List<SearchBarItem> searchUserData(String like, Principal principal) {
UserInfo user = new UserInfo(); UserInfo user = new UserInfo();
user.setId(principal.getId()); user.setId(principal.getId());

View File

@ -50,10 +50,7 @@ import eu.eudat.models.data.funder.FunderDMPEditorModel;
import eu.eudat.models.data.grant.GrantDMPEditorModel; import eu.eudat.models.data.grant.GrantDMPEditorModel;
import eu.eudat.models.data.helpermodels.Tuple; 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.DataManagementPlanListingModel; import eu.eudat.models.data.listingmodels.*;
import eu.eudat.models.data.listingmodels.DataManagementPlanOverviewModel;
import eu.eudat.models.data.listingmodels.DatasetListingModel;
import eu.eudat.models.data.listingmodels.UserInfoListingModel;
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.security.Principal;
import eu.eudat.models.data.user.composite.PagedDatasetProfile; import eu.eudat.models.data.user.composite.PagedDatasetProfile;
@ -87,6 +84,7 @@ import java.io.*;
import java.math.BigInteger; import java.math.BigInteger;
import java.nio.file.Files; import java.nio.file.Files;
import java.time.Instant; import java.time.Instant;
import java.time.temporal.ChronoUnit;
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;
@ -158,6 +156,7 @@ public class DataManagementPlanManager {
if (fieldsGroup.equals("listing")) { if (fieldsGroup.equals("listing")) {
if (!dataManagementPlanTableRequest.getCriteria().isOnlyPublic()) { if (!dataManagementPlanTableRequest.getCriteria().isOnlyPublic()) {
itemsFuture = pagedItems.withHint(HintedModelFactory.getHint(DataManagementPlanListingModel.class)) itemsFuture = pagedItems.withHint(HintedModelFactory.getHint(DataManagementPlanListingModel.class))
.distinct()
.selectAsync(item -> { .selectAsync(item -> {
item.setDataset( item.setDataset(
item.getDataset().stream() item.getDataset().stream()
@ -171,6 +170,7 @@ public class DataManagementPlanManager {
.whenComplete((resultList, throwable) -> dataTable.setData(resultList)); .whenComplete((resultList, throwable) -> dataTable.setData(resultList));
} else { } else {
itemsFuture = pagedItems.withHint(HintedModelFactory.getHint(DataManagementPlanListingModel.class)) itemsFuture = pagedItems.withHint(HintedModelFactory.getHint(DataManagementPlanListingModel.class))
.distinct()
.selectAsync(item -> { .selectAsync(item -> {
item.setDataset( item.setDataset(
item.getDataset().stream() item.getDataset().stream()
@ -181,15 +181,17 @@ public class DataManagementPlanManager {
} }
} else if (fieldsGroup.equals("autocomplete")) { } else if (fieldsGroup.equals("autocomplete")) {
itemsFuture = pagedItems itemsFuture = pagedItems
.distinct()
.selectAsync(item -> new DataManagementPlanListingModel().fromDataModelAutoComplete(item)) .selectAsync(item -> new DataManagementPlanListingModel().fromDataModelAutoComplete(item))
.whenComplete((resultList, throwable) -> dataTable.setData(resultList)); .whenComplete((resultList, throwable) -> dataTable.setData(resultList));
} else { } else {
itemsFuture = pagedItems itemsFuture = pagedItems
.distinct()
.selectAsync(item -> new DataManagementPlanListingModel().fromDataModelAssociatedProfiles(item)) .selectAsync(item -> new DataManagementPlanListingModel().fromDataModelAssociatedProfiles(item))
.whenComplete((resultList, throwable) -> dataTable.setData(resultList)); .whenComplete((resultList, throwable) -> dataTable.setData(resultList));
} }
CompletableFuture countFuture = authItems.countAsync().whenComplete((count, throwable) -> dataTable.setTotalCount(count)); CompletableFuture countFuture = authItems.distinct().countAsync().whenComplete((count, throwable) -> dataTable.setTotalCount(count));
CompletableFuture.allOf(itemsFuture, countFuture).join(); CompletableFuture.allOf(itemsFuture, countFuture).join();
return dataTable; return dataTable;
} }
@ -207,6 +209,24 @@ public class DataManagementPlanManager {
throw new ForbiddenException("Selected DMP is not public"); throw new ForbiddenException("Selected DMP is not public");
} }
dataManagementPlan.fromDataModel(dataManagementPlanEntity); dataManagementPlan.fromDataModel(dataManagementPlanEntity);
List<Dataset> datasetEnities = new ArrayList<>(dataManagementPlanEntity.getDataset());
/*for (int i = 0; i < datasetEnities.size(); i++) {
for (int j = i; j < dataManagementPlan.getDatasets().size(); j++) {
if (dataManagementPlan.getDatasets().get(j).getId().equals(datasetEnities.get(i).getId())) {
dataManagementPlan.getDatasets().get(j).setDatasetProfileDefinition(datasetManager.getPagedProfile(dataManagementPlan.getDatasets().get(j), datasetEnities.get(i)));
break;
}
}
}*/
datasetEnities.stream()
.filter(dataset -> !dataset.getStatus().equals(Dataset.Status.DELETED) && !dataset.getStatus().equals(Dataset.Status.CANCELED))
.forEach(dataset -> {
dataManagementPlan.getDatasets().stream().filter(datasetWizardModel -> datasetWizardModel.getId().equals(dataset.getId())).forEach(datasetWizardModel -> {
DatasetWizardModel wizardModel = datasetManager.getSingle(datasetWizardModel.getId().toString(), principal);
datasetWizardModel.setDatasetProfileDefinition(wizardModel.getDatasetProfileDefinition());
datasetWizardModel.setTags(wizardModel.getTags());
});
});
if (isPublic) { if (isPublic) {
dataManagementPlan.setDatasets(dataManagementPlan.getDatasets().stream().filter(dataset -> dataset.getStatus() == Dataset.Status.FINALISED.getValue()).collect(Collectors.toList())); dataManagementPlan.setDatasets(dataManagementPlan.getDatasets().stream().filter(dataset -> dataset.getStatus() == Dataset.Status.FINALISED.getValue()).collect(Collectors.toList()));
} }
@ -301,19 +321,49 @@ public class DataManagementPlanManager {
return data; return data;
} }
public List<VersionListingModel> getAllVersions(String groupId, Principal principal) {
UUID principalId = principal.getId();
List<VersionListingModel> versions = new ArrayList<>();
QueryableList<DMP> items = null;
QueryableList<DMP> authItems = null;
List<Integer> roles = new LinkedList<>();
DataManagementPlanCriteria criteria = new DataManagementPlanCriteria();
criteria.setGroupIds(Collections.singletonList(UUID.fromString(groupId)));
criteria.setAllVersions(true);
criteria.setIsPublic(principalId == null);
criteria.setOnlyPublic(principalId == null);
items = apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().getWithCriteria(criteria);
if (principalId != null) {
authItems = apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().getAuthenticated(items, principalId, roles);
} else {
authItems = items;
}
CompletableFuture<List<VersionListingModel>> versionFuture = authItems.withHint(HintedModelFactory.getHint(VersionListingModel.class))
.orderBy(((builder, root) -> builder.desc(root.get("version"))))
.selectAsync(item -> new VersionListingModel().fromDataModel(item))
.whenComplete(((versionListingModels, throwable) -> versions.addAll(versionListingModels)));
CompletableFuture.allOf(versionFuture).join();
return versions;
}
/* /*
* Data Management * Data Management
* */ * */
public DMP createOrUpdate(ApiContext apiContext, DataManagementPlanEditorModel dataManagementPlan, Principal principal) throws Exception { public DMP createOrUpdate(DataManagementPlanEditorModel dataManagementPlan, Principal principal) 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());
Instant dbTime = Instant.ofEpochMilli(dmp1.getModified().getTime()).truncatedTo(ChronoUnit.SECONDS);
Instant modelTime = Instant.ofEpochMilli(dataManagementPlan.getModified().getTime()).truncatedTo(ChronoUnit.SECONDS);
if (!isUserOwnerOfDmp(dmp1, principal)) { if (!isUserOwnerOfDmp(dmp1, principal)) {
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 (dmp1.getModified().getTime() != dataManagementPlan.getModified().getTime()) { if (dbTime.toEpochMilli() != modelTime.toEpochMilli()) {
throw new Exception("Another user have already edit that DMP."); throw new Exception("Another user have already edit that DMP.");
} }
List<Dataset> datasetList = new ArrayList<>(dmp1.getDataset()); List<Dataset> datasetList = new ArrayList<>(dmp1.getDataset());
@ -360,7 +410,9 @@ public class DataManagementPlanManager {
} }
} }
if (newDmp.getGrant().getType().equals(Grant.GrantType.INTERNAL.getValue())) {
checkIfUserCanEditGrant(newDmp, user); checkIfUserCanEditGrant(newDmp, user);
}
assignGrandUserIfInternal(newDmp, user); assignGrandUserIfInternal(newDmp, user);
assignFunderUserIfInternal(newDmp, user); assignFunderUserIfInternal(newDmp, user);
assignProjectUserIfInternal(newDmp, user); assignProjectUserIfInternal(newDmp, user);
@ -382,11 +434,14 @@ public class DataManagementPlanManager {
apiContext.getOperationsContext().getDatabaseRepository().getDatasetDao() apiContext.getOperationsContext().getDatabaseRepository().getDatasetDao()
.asQueryable().where((builder, root) -> root.get("id").in(dataManagementPlan.getDatasetsToBeFinalized())) .asQueryable().where((builder, root) -> root.get("id").in(dataManagementPlan.getDatasetsToBeFinalized()))
.update(root -> root.<Integer>get("status"), Dataset.Status.FINALISED.getValue()); .update(root -> root.<Integer>get("status"), Dataset.Status.FINALISED.getValue());
apiContext.getOperationsContext().getDatabaseRepository().getDatasetDao()
.asQueryable().where((builder, root) -> root.get("id").in(dataManagementPlan.getDatasetsToBeFinalized()))
.update(root -> root.<Date>get("finalizedat"), new Date());
List<UUID> datasetsToBeCanceled = new LinkedList<>(); List<UUID> datasetsToBeCanceled = new LinkedList<>();
for (DatasetListingModel dataset : dataManagementPlan.getDatasets()) { for (DatasetWizardModel dataset : dataManagementPlan.getDatasets()) {
if (!(dataset.getStatus() == (int) Dataset.Status.FINALISED.getValue()) && !dataManagementPlan.getDatasetsToBeFinalized().contains(UUID.fromString(dataset.getId()))) { if (!(dataset.getStatus() == (int) Dataset.Status.FINALISED.getValue()) && !dataManagementPlan.getDatasetsToBeFinalized().contains(dataset.getId())) {
datasetsToBeCanceled.add(UUID.fromString(dataset.getId())); datasetsToBeCanceled.add(UUID.fromString(dataset.getId().toString()));
} }
} }
if (!datasetsToBeCanceled.isEmpty()) if (!datasetsToBeCanceled.isEmpty())
@ -395,9 +450,9 @@ public class DataManagementPlanManager {
.update(root -> root.<Integer>get("status"), Dataset.Status.CANCELED.getValue()); .update(root -> root.<Integer>get("status"), Dataset.Status.CANCELED.getValue());
} else { } else {
List<UUID> datasetsToBeCanceled = new LinkedList<>(); List<UUID> datasetsToBeCanceled = new LinkedList<>();
for (DatasetListingModel dataset : dataManagementPlan.getDatasets()) { for (DatasetWizardModel dataset : dataManagementPlan.getDatasets()) {
if (!(dataset.getStatus() == (int) Dataset.Status.FINALISED.getValue())) { if (!(dataset.getStatus() == (int) Dataset.Status.FINALISED.getValue())) {
datasetsToBeCanceled.add(UUID.fromString(dataset.getId())); datasetsToBeCanceled.add(dataset.getId());
} }
} }
if (!datasetsToBeCanceled.isEmpty()) if (!datasetsToBeCanceled.isEmpty())
@ -423,7 +478,49 @@ public class DataManagementPlanManager {
return newDmp; return newDmp;
} }
public void newVersion(UUID uuid, DataManagementPlanNewVersionModel dataManagementPlan, Principal principal) throws Exception { public DMP createOrUpdateWithDatasets(DataManagementPlanEditorModel dataManagementPlan, Principal principal) throws Exception {
if (dataManagementPlan.getId() != null) {
DMP dmp1 = apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().find(dataManagementPlan.getId());
Instant dbTime = Instant.ofEpochMilli(dmp1.getModified().getTime()).truncatedTo(ChronoUnit.SECONDS);
Instant modelTime = Instant.ofEpochMilli(dataManagementPlan.getModified().getTime()).truncatedTo(ChronoUnit.SECONDS);
if (!isUserOwnerOfDmp(dmp1, principal)) {
throw new Exception("User not being the creator is not authorized to edit this DMP.");
}
if (dbTime.toEpochMilli() != modelTime.toEpochMilli()) {
throw new Exception("Another user have already edit that DMP.");
}
for (DatasetWizardModel dataset : dataManagementPlan.getDatasets()) {
if (dataManagementPlan.getProfiles().stream().filter(associatedProfile -> dataset.getProfile().getId().equals(associatedProfile.getId())).findAny().orElse(null) == null)
throw new Exception("Dataset Template for Dataset Description is missing from the DMP.");
}
if (dataManagementPlan.getStatus() == (int) DMP.DMPStatus.FINALISED.getValue() && dmp1.getStatus().equals(DMP.DMPStatus.FINALISED.getValue()))
throw new Exception("DMP is finalized, therefore cannot be edited.");
}
List<Dataset> datasets = new ArrayList<>();
DMP tempDMP = dataManagementPlan.toDataModel();
if (tempDMP.getStatus() == (int) DMP.DMPStatus.FINALISED.getValue()) {
checkDmpValidationRules(tempDMP);
}
UserInfo user = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(principal.getId());
createOrganisationsIfTheyDontExist(tempDMP, apiContext.getOperationsContext().getDatabaseRepository().getOrganisationDao());
createResearchersIfTheyDontExist(tempDMP, apiContext.getOperationsContext().getDatabaseRepository().getResearcherDao(), user);
createFunderIfItDoesntExist(tempDMP, apiContext.getOperationsContext().getDatabaseRepository().getFunderDao());
createGrantIfItDoesntExist(tempDMP, apiContext.getOperationsContext().getDatabaseRepository().getGrantDao());
DMP result = createOrUpdate(dataManagementPlan, principal);
for (DatasetWizardModel datasetWizardModel: dataManagementPlan.getDatasets()) {
datasetWizardModel.setDmp(new DataManagementPlan().fromDataModel(result));
Dataset dataset = datasetManager.createOrUpdate(datasetWizardModel, principal);
datasets.add(dataset);
}
return result;
}
public UUID newVersion(UUID uuid, DataManagementPlanNewVersionModel dataManagementPlan, Principal principal) throws Exception {
DMP oldDmp = databaseRepository.getDmpDao().find(uuid); DMP oldDmp = databaseRepository.getDmpDao().find(uuid);
if (!isUserOwnerOfDmp(oldDmp, principal)) { if (!isUserOwnerOfDmp(oldDmp, principal)) {
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.");
@ -473,13 +570,13 @@ public class DataManagementPlanManager {
newDmp.setDataset(new HashSet<>(databaseRepository.getDatasetDao().getWithCriteria(criteria1).toList())); newDmp.setDataset(new HashSet<>(databaseRepository.getDatasetDao().getWithCriteria(criteria1).toList()));
this.updateGroupIndex(newDmp.getGroupId()); this.updateGroupIndex(newDmp.getGroupId());
return newDmp.getId();
} else { } else {
throw new DMPNewVersionException("Version to update not the latest."); throw new DMPNewVersionException("Version to update not the latest.");
} }
} }
public void clone(DataManagementPlanNewVersionModel dataManagementPlan, Principal principal) throws Exception { public UUID clone(DataManagementPlanNewVersionModel dataManagementPlan, Principal principal) throws Exception {
DMP newDmp = dataManagementPlan.toDataModel(); DMP newDmp = dataManagementPlan.toDataModel();
UserInfo user = apiContext.getOperationsContext().getBuilderFactory().getBuilder(UserInfoBuilder.class).id(principal.getId()).build(); UserInfo user = apiContext.getOperationsContext().getBuilderFactory().getBuilder(UserInfoBuilder.class).id(principal.getId()).build();
@ -515,6 +612,8 @@ public class DataManagementPlanManager {
newDmp.setDataset(new HashSet<>(databaseRepository.getDatasetDao().getWithCriteria(criteria1).toList())); newDmp.setDataset(new HashSet<>(databaseRepository.getDatasetDao().getWithCriteria(criteria1).toList()));
this.updateIndex(newDmp); this.updateIndex(newDmp);
return newDmp.getId();
} }
public void delete(UUID uuid) throws DMPWithDatasetsDeleteException, IOException { public void delete(UUID uuid) throws DMPWithDatasetsDeleteException, IOException {
@ -817,8 +916,15 @@ public class DataManagementPlanManager {
apiContext.getOperationsContext().getDatabaseRepository().getDatasetDao() apiContext.getOperationsContext().getDatabaseRepository().getDatasetDao()
.asQueryable().where((builder, root) -> root.get("id").in(datasetsToBeFinalized.getUuids())) .asQueryable().where((builder, root) -> root.get("id").in(datasetsToBeFinalized.getUuids()))
.update(root -> root.<Integer>get("status"), Dataset.Status.FINALISED.getValue()); .update(root -> root.<Integer>get("status"), Dataset.Status.FINALISED.getValue());
apiContext.getOperationsContext().getDatabaseRepository().getDatasetDao()
.asQueryable().where((builder, root) -> root.get("id").in(datasetsToBeFinalized.getUuids()))
.update(root -> root.<Date>get("finalizedAt"), new Date());
List<Dataset> finalizedDatasets = dmp.getDataset().stream().filter(dataset -> datasetsToBeFinalized.getUuids().contains(dataset.getId())).collect(Collectors.toList()); List<Dataset> finalizedDatasets = dmp.getDataset().stream().filter(dataset -> datasetsToBeFinalized.getUuids().contains(dataset.getId())).collect(Collectors.toList());
finalizedDatasets.forEach(dataset -> dataset.setStatus(Dataset.Status.FINALISED.getValue())); finalizedDatasets.forEach(dataset ->{
dataset.setStatus(Dataset.Status.FINALISED.getValue());
dataset.setFinalizedAt(new Date());
dataset.setModified(new Date());
} );
indexDatasets.addAll(finalizedDatasets); indexDatasets.addAll(finalizedDatasets);
List<UUID> datasetsToBeCanceled = new LinkedList<>(); List<UUID> datasetsToBeCanceled = new LinkedList<>();
for (Dataset dataset : dmp.getDataset()) { for (Dataset dataset : dmp.getDataset()) {
@ -867,12 +973,24 @@ public class DataManagementPlanManager {
this.updateIndex(dmp); this.updateIndex(dmp);
} }
public void updateUsers(UUID id, List<UserInfoListingModel> users, Principal principal) throws Exception {
DMP dmp = this.apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().find(id);
if (!isUserOwnerOfDmp(dmp, principal))
throw new Exception("User does not have the privilege to do this action.");
clearUsers(dmp);
for (UserInfoListingModel userListing : users) {
UserInfo tempUser = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(userListing.getId());
assignUser(dmp, tempUser, UserDMP.UserDMPRoles.fromInteger(userListing.getRole()));
}
}
/* /*
* Export Data * Export Data
* */ * */
public FileEnvelope getWordDocument(String id, Principal principal, ConfigLoader configLoader) throws IOException { public FileEnvelope getWordDocument(String id, Principal principal, ConfigLoader configLoader) throws IOException {
return this.getWordDocument(id, principal, configLoader, false); return this.getWordDocument(id, principal, configLoader, true);
} }
public FileEnvelope getWordDocument(String id, Principal principal, ConfigLoader configLoader, Boolean versioned) throws IOException { public FileEnvelope getWordDocument(String id, Principal principal, ConfigLoader configLoader, Boolean versioned) throws IOException {
@ -1021,11 +1139,9 @@ public class DataManagementPlanManager {
document.removeBodyElement(0); document.removeBodyElement(0);
} }
String fileName = ""; String fileName = "DMP_" + dmpEntity.getGrant().getLabel();
if (versioned) { if (versioned) {
fileName = dmpEntity.getLabel() + " v" + dmpEntity.getVersion(); fileName += "_" + dmpEntity.getVersion();
} else {
fileName = dmpEntity.getLabel();
} }
fileName = fileName.replaceAll("[^a-zA-Z0-9+ ]", ""); fileName = fileName.replaceAll("[^a-zA-Z0-9+ ]", "");
FileEnvelope exportEnvelope = new FileEnvelope(); FileEnvelope exportEnvelope = new FileEnvelope();
@ -1171,7 +1287,7 @@ public class DataManagementPlanManager {
writer.close(); writer.close();
FileEnvelope fileEnvelope = new FileEnvelope(); FileEnvelope fileEnvelope = new FileEnvelope();
fileEnvelope.setFile(xmlFile); fileEnvelope.setFile(xmlFile);
fileEnvelope.setFilename(dmp.getLabel() + ".xml"); fileEnvelope.setFilename("DMP_" + dmp.getGrant().getLabel() + "_" + dmp.getVersion() + ".xml");
return fileEnvelope; return fileEnvelope;
} }
@ -1185,7 +1301,7 @@ public class DataManagementPlanManager {
/*ObjectMapper mapper = new ObjectMapper(); /*ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);*/ mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);*/
String fileName = dmp.getLabel(); String fileName = "DMP_" + dmp.getGrant().getLabel() + "_" + dmp.getVersion();//dmp.getLabel();
fileName = fileName.replaceAll("[^a-zA-Z0-9+ ]", ""); fileName = fileName.replaceAll("[^a-zA-Z0-9+ ]", "");
String uuid = UUID.randomUUID().toString(); String uuid = UUID.randomUUID().toString();
File file = new File(this.environment.getProperty("temp.temp") + uuid + ".json"); File file = new File(this.environment.getProperty("temp.temp") + uuid + ".json");
@ -1341,7 +1457,7 @@ public class DataManagementPlanManager {
dm.setDefinition(dmpProfile); dm.setDefinition(dmpProfile);
//createOrUpdate(apiContext, dm, principal); //createOrUpdate(apiContext, dm, principal);
DMP dmp = this.createOrUpdate(apiContext, dm, principal); DMP dmp = this.createOrUpdate(dm, principal);
if (dmp.getOrganisations() == null) { if (dmp.getOrganisations() == null) {
dmp.setOrganisations(new HashSet<>()); dmp.setOrganisations(new HashSet<>());
} }
@ -1802,21 +1918,17 @@ public class DataManagementPlanManager {
if (!update) { if (!update) {
if (unpublishedUrl == null) { if (unpublishedUrl == null) {
// Second step, add the file to the entry. // Second step, add the file to the entry.
HttpHeaders fileHeaders = new HttpHeaders();
fileHeaders.setContentType(MediaType.MULTIPART_FORM_DATA);
LinkedMultiValueMap<String, Object> addFileMap = new LinkedMultiValueMap<>();
FileEnvelope file = getWordDocument(id.toString(), principal, configLoader); FileEnvelope file = getWordDocument(id.toString(), principal, configLoader);
addFileMap.add("filename", file.getFilename()); String name = file.getFilename().substring(0, file.getFilename().length() - 5);
FileSystemResource fileSystemResource = new FileSystemResource(file.getFile()); File pdfFile = datasetManager.convertToPDF(file, environment);
addFileMap.add("file", fileSystemResource); String fileName = name + ".pdf";
HttpEntity<MultiValueMap<String, Object>> addFileMapRequest = new HttpEntity<>(addFileMap, fileHeaders); FileSystemResource fileSystemResource = new FileSystemResource(pdfFile);
HttpEntity<FileSystemResource> addFileMapRequest = new HttpEntity<>(fileSystemResource, null);
String addFileUrl = links.get("files") + "?access_token=" + zenodoToken; String addFileUrl = links.get("bucket") + "/" + fileName + "?access_token=" + zenodoToken;
ResponseEntity<String> addFileResponse = restTemplate.postForEntity(addFileUrl, addFileMapRequest, String.class); restTemplate.put(addFileUrl, addFileMapRequest);
Files.deleteIfExists(file.getFile().toPath()); Files.deleteIfExists(file.getFile().toPath());
// Third post call to Zenodo to publish the entry and return the DOI. // Third post call to Zenodo to publish the entry and return the DOI.
publishUrl = links.get("publish") + "?access_token=" + zenodoToken; publishUrl = links.get("publish") + "?access_token=" + zenodoToken;
} else { } else {

View File

@ -17,6 +17,7 @@ import eu.eudat.data.query.items.table.datasetprofile.DatasetProfileTableRequest
import eu.eudat.elastic.criteria.DatasetCriteria; import eu.eudat.elastic.criteria.DatasetCriteria;
import eu.eudat.elastic.entities.Tag; import eu.eudat.elastic.entities.Tag;
import eu.eudat.elastic.repository.DatasetRepository; import eu.eudat.elastic.repository.DatasetRepository;
import eu.eudat.exceptions.security.ForbiddenException;
import eu.eudat.exceptions.security.UnauthorisedException; import eu.eudat.exceptions.security.UnauthorisedException;
import eu.eudat.logic.builders.BuilderFactory; import eu.eudat.logic.builders.BuilderFactory;
import eu.eudat.logic.builders.entity.UserInfoBuilder; import eu.eudat.logic.builders.entity.UserInfoBuilder;
@ -32,9 +33,11 @@ import eu.eudat.logic.utilities.documents.xml.ExportXmlBuilder;
import eu.eudat.logic.utilities.helpers.StreamDistinctBy; import eu.eudat.logic.utilities.helpers.StreamDistinctBy;
import eu.eudat.logic.utilities.json.JsonSearcher; import eu.eudat.logic.utilities.json.JsonSearcher;
import eu.eudat.models.HintedModelFactory; import eu.eudat.models.HintedModelFactory;
import eu.eudat.models.data.dataset.DatasetOverviewModel;
import eu.eudat.models.data.datasetImport.DatasetImportField; import eu.eudat.models.data.datasetImport.DatasetImportField;
import eu.eudat.models.data.datasetImport.DatasetImportPagedDatasetProfile; import eu.eudat.models.data.datasetImport.DatasetImportPagedDatasetProfile;
import eu.eudat.models.data.datasetprofile.DatasetProfileListingModel; import eu.eudat.models.data.datasetprofile.DatasetProfileListingModel;
import eu.eudat.models.data.datasetprofile.DatasetProfileOverviewModel;
import eu.eudat.models.data.datasetwizard.DatasetWizardModel; import eu.eudat.models.data.datasetwizard.DatasetWizardModel;
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;
@ -49,6 +52,7 @@ 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;
import org.apache.poi.xwpf.usermodel.XWPFRun; import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.json.JSONArray;
import org.json.JSONObject; import org.json.JSONObject;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -67,6 +71,7 @@ import org.w3c.dom.NodeList;
import javax.activation.MimetypesFileTypeMap; import javax.activation.MimetypesFileTypeMap;
import javax.persistence.criteria.Join; import javax.persistence.criteria.Join;
import javax.persistence.criteria.JoinType; import javax.persistence.criteria.JoinType;
import javax.transaction.Transactional;
import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException; import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller; import javax.xml.bind.Unmarshaller;
@ -163,7 +168,7 @@ public class DatasetManager {
QueryableList<eu.eudat.data.entities.Dataset> authItems; QueryableList<eu.eudat.data.entities.Dataset> authItems;
if (!datasetTableRequest.getCriteria().getIsPublic()) { if (!datasetTableRequest.getCriteria().getIsPublic()) {
if (principal.getId() == null) { if (principal.getId() == null) {
throw new UnauthorisedException(); throw new UnauthorisedException("You are not allowed to access those datasets");
} }
if (datasetTableRequest.getCriteria().getRole() != null) if (datasetTableRequest.getCriteria().getRole() != null)
roles.add(datasetTableRequest.getCriteria().getRole()); roles.add(datasetTableRequest.getCriteria().getRole());
@ -177,24 +182,19 @@ public class DatasetManager {
}); });
} }
String[] strings = new String[1]; String[] strings = new String[1];
strings[0] = "-dmp:publishedAt|join|"; //strings[0] = "-dmp:publishedAt|join|";
datasetTableRequest.getOrderings().setFields(strings); //datasetTableRequest.getOrderings().setFields(strings);
authItems = items; authItems = items;
pagedItems = PaginationManager.applyPaging(items, datasetTableRequest); pagedItems = PaginationManager.applyPaging(items, datasetTableRequest);
} }
DataTableData<DatasetListingModel> dataTable = new DataTableData<>(); DataTableData<DatasetListingModel> dataTable = new DataTableData<>();
CompletableFuture<List<DatasetListingModel>> itemsFuture = pagedItems. dataTable.setData(pagedItems.select(this::mapModel).stream().filter(Objects::nonNull).collect(Collectors.toList()));
selectAsync(item -> new DatasetListingModel().fromDataModel(item)).whenComplete((resultList, throwable) -> {
dataTable.setData(resultList);
});
CompletableFuture countFuture = authItems.countAsync().whenComplete((count, throwable) -> { dataTable.setTotalCount(authItems.count());
dataTable.setTotalCount(count);
});
CompletableFuture.allOf(itemsFuture, countFuture).join(); //CompletableFuture.allOf(itemsFuture, countFuture).join();
return dataTable; return dataTable;
} }
@ -240,8 +240,8 @@ public class DatasetManager {
DataTableData<DatasetListingModel> dataTable = new DataTableData<>(); DataTableData<DatasetListingModel> dataTable = new DataTableData<>();
CompletableFuture<List<DatasetListingModel>> itemsFuture = pagedItems. CompletableFuture<List<DatasetListingModel>> itemsFuture = pagedItems.
selectAsync(item -> new DatasetListingModel().fromDataModel(item)).whenComplete((resultList, throwable) -> { selectAsync(this::mapModel).whenComplete((resultList, throwable) -> {
dataTable.setData(resultList); dataTable.setData(resultList.stream().filter(Objects::nonNull).collect(Collectors.toList()));
}); });
CompletableFuture countFuture = pagedItems.countAsync().whenComplete((count, throwable) -> { CompletableFuture countFuture = pagedItems.countAsync().whenComplete((count, throwable) -> {
@ -257,7 +257,7 @@ public class DatasetManager {
eu.eudat.data.entities.Dataset datasetEntity = databaseRepository.getDatasetDao().find(UUID.fromString(id), HintedModelFactory.getHint(DatasetWizardModel.class)); eu.eudat.data.entities.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() == principal.getId())
.collect(Collectors.toList()).size() == 0) .collect(Collectors.toList()).size() == 0 && !datasetEntity.getDmp().isPublic())
throw new UnauthorisedException(); throw new UnauthorisedException();
eu.eudat.elastic.entities.Dataset datasetElastic; eu.eudat.elastic.entities.Dataset datasetElastic;
try { try {
@ -296,7 +296,11 @@ public class DatasetManager {
Stream<DatasetProfile> sorted = profileVersionsIncluded.stream().sorted(Comparator.comparing(DatasetProfile::getVersion).reversed()); Stream<DatasetProfile> sorted = profileVersionsIncluded.stream().sorted(Comparator.comparing(DatasetProfile::getVersion).reversed());
// Make the Stream into List and get the first item. // Make the Stream into List and get the first item.
DatasetProfile profile = sorted.collect(Collectors.toList()).iterator().next(); List<DatasetProfile> profiles = sorted.collect(Collectors.toList());
if (profiles.isEmpty())
throw new NoSuchElementException("No profiles found for the specific Dataset");
DatasetProfile profile = profiles.get(0);
// Check if the dataset is on the latest Version. // Check if the dataset is on the latest Version.
boolean latestVersion = profile.getVersion().toString().equals(datasetEntity.getProfile().getVersion().toString()); boolean latestVersion = profile.getVersion().toString().equals(datasetEntity.getProfile().getVersion().toString());
@ -325,6 +329,26 @@ public class DatasetManager {
} }
} }
public DatasetOverviewModel getOverviewSingle(String id, Principal principal, boolean isPublic) throws Exception {
Dataset datasetEntity = databaseRepository.getDatasetDao().find(UUID.fromString(id));
if (datasetEntity.getStatus() == Dataset.Status.DELETED.getValue()) {
throw new Exception("Dataset is deleted.");
}
if (!isPublic && principal == null) {
throw new UnauthorisedException();
} else
if (!isPublic && datasetEntity.getDmp().getUsers()
.stream().noneMatch(userInfo -> userInfo.getUser().getId() == principal.getId())) {
throw new UnauthorisedException();
} else if (isPublic && !datasetEntity.getDmp().isPublic()) {
throw new ForbiddenException("Selected Dataset is not public");
}
DatasetOverviewModel dataset = new DatasetOverviewModel();
dataset.fromDataModel(datasetEntity);
return dataset;
}
public PagedDatasetProfile getPagedProfile(DatasetWizardModel dataset, eu.eudat.data.entities.Dataset datasetEntity) { public PagedDatasetProfile getPagedProfile(DatasetWizardModel dataset, eu.eudat.data.entities.Dataset datasetEntity) {
eu.eudat.models.data.user.composite.DatasetProfile datasetprofile = userManager.generateDatasetProfileModel(datasetEntity.getProfile()); eu.eudat.models.data.user.composite.DatasetProfile datasetprofile = userManager.generateDatasetProfileModel(datasetEntity.getProfile());
datasetprofile.setStatus(dataset.getStatus()); datasetprofile.setStatus(dataset.getStatus());
@ -584,7 +608,7 @@ public class DatasetManager {
if (datasetWizardModel.getDmp().getGrant() == null) { if (datasetWizardModel.getDmp().getGrant() == null) {
datasetWizardModel.setDmp(new DataManagementPlan().fromDataModelNoDatasets(dataset1.getDmp())); datasetWizardModel.setDmp(new DataManagementPlan().fromDataModelNoDatasets(dataset1.getDmp()));
} }
dataset1.setProfile(this.apiContext.getOperationsContext().getDatabaseRepository().getDatasetProfileDao().find(datasetWizardModel.getProfile())); dataset1.setProfile(this.apiContext.getOperationsContext().getDatabaseRepository().getDatasetProfileDao().find(datasetWizardModel.getProfile().getId()));
// datasetWizardModel.setDatasetProfileDefinition(getPagedProfile(datasetWizardModel, dataset1)); // datasetWizardModel.setDatasetProfileDefinition(getPagedProfile(datasetWizardModel, dataset1));
updateTags(dataset1, datasetWizardModel.getTags()); updateTags(dataset1, datasetWizardModel.getTags());
if (sendNotification) { if (sendNotification) {
@ -916,7 +940,7 @@ public class DatasetManager {
// Sets the latest version of dataet Profile to the Dataset in question. // Sets the latest version of dataet Profile to the Dataset in question.
dataset.setDatasetProfileDefinition(getLatestDatasetProfile(datasetEntity, item)); dataset.setDatasetProfileDefinition(getLatestDatasetProfile(datasetEntity, item));
dataset.setProfile(item.getId()); dataset.setProfile(new DatasetProfileOverviewModel().fromDataModel(item));
// Now at latest version. // Now at latest version.
dataset.setIsProfileLatestVersion(true); dataset.setIsProfileLatestVersion(true);
@ -995,15 +1019,12 @@ public class DatasetManager {
if (!tagNodes.isEmpty()) { if (!tagNodes.isEmpty()) {
tagNodes.forEach(node -> { tagNodes.forEach(node -> {
JsonNode value = node.get("value"); JsonNode value = node.get("value");
if (value.isArray()) { String stringValue = value.asText().replaceAll("=", ":");
value.elements().forEachRemaining(element -> { JSONArray values = new JSONArray(stringValue);
try { if (values != null) {
Map<String, String> data = mapper.readValue(element.asText(), HashMap.class); values.iterator().forEachRemaining(element -> {
this.addTag(tags, wizardModel.getTags(), data.get("id"), data.get("name")); Map<String, Object> data = ((JSONObject) element).toMap();
} catch (IOException e) { this.addTag(tags, wizardModel.getTags(), data.get("id").toString(), data.get("name").toString());
logger.error(e.getMessage(), e);
}
}); });
} else { } else {
this.addTag(tags, wizardModel.getTags(), "", value.asText()); this.addTag(tags, wizardModel.getTags(), "", value.asText());
@ -1024,4 +1045,21 @@ public class DatasetManager {
dstTags.add(tag); dstTags.add(tag);
} }
} }
@Transactional
private DatasetListingModel mapModel(Dataset item) {
if (item.getProfile() == null)
return null;
DatasetListingModel listingModel = new DatasetListingModel().fromDataModel(item);
DatasetProfileCriteria criteria = new DatasetProfileCriteria();
criteria.setGroupIds(Collections.singletonList(item.getProfile().getGroupId()));
List<DatasetProfile> profiles = apiContext.getOperationsContext().getDatabaseRepository().getDatasetProfileDao().getWithCriteria(criteria).toList();
boolean islast = false;
if (!profiles.isEmpty()) {
profiles = profiles.stream().sorted(Comparator.comparing(DatasetProfile::getVersion)).collect(Collectors.toList());
islast = profiles.get(0).getId().equals(item.getProfile().getId());
}
listingModel.setProfileLatestVersion(islast);
return listingModel;
}
} }

View File

@ -26,6 +26,10 @@ import org.slf4j.LoggerFactory;
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;
import org.springframework.http.*; import org.springframework.http.*;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate; import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
@ -109,7 +113,9 @@ public class DatasetProfileManager {
public List<ExternalAutocompleteFieldModel> getAutocomplete(AutoCompleteData data, String like) { public List<ExternalAutocompleteFieldModel> getAutocomplete(AutoCompleteData data, String like) {
List<ExternalAutocompleteFieldModel> result = new LinkedList<>(); List<ExternalAutocompleteFieldModel> result = new LinkedList<>();
RestTemplate restTemplate = new RestTemplate(); SimpleClientHttpRequestFactory simpleFactory = new SimpleClientHttpRequestFactory();
RestTemplate restTemplate = new RestTemplate(simpleFactory);
HttpHeaders headers = new HttpHeaders(); HttpHeaders headers = new HttpHeaders();
DocumentContext jsonContext = null; DocumentContext jsonContext = null;
HttpEntity<String> entity; HttpEntity<String> entity;
@ -122,8 +128,12 @@ public class DatasetProfileManager {
String url = singleData.getUrl(); String url = singleData.getUrl();
String mediaType = ""; String mediaType = "";
if (url.contains("openaire")) { if (url.contains("openaire") || url.contains("zenodo")) {
mediaType = "application/json; charset=utf-8"; mediaType = "application/json; charset=utf-8";
if (url.contains("zenodo")) {
url = url.replace("?", "/?");
}
url = url.replace("{like}", like.equals("") ? "*" : like); url = url.replace("{like}", like.equals("") ? "*" : like);
url = url.replace("%20", " "); url = url.replace("%20", " ");
url = url.replace("%22", "\""); url = url.replace("%22", "\"");
@ -133,14 +143,17 @@ public class DatasetProfileManager {
url += "?search=" + like; url += "?search=" + like;
} }
if (!url.contains("zenodo")) {
headers.setAccept(Collections.singletonList(MediaType.valueOf(mediaType))); headers.setAccept(Collections.singletonList(MediaType.valueOf(mediaType)));
}
headers.setContentType(MediaType.APPLICATION_JSON); headers.setContentType(MediaType.APPLICATION_JSON);
entity = new HttpEntity<>("parameters", headers); entity = new HttpEntity<>("parameters", headers);
response = restTemplate.exchange(url, HttpMethod.GET, entity, Object.class); response = restTemplate.exchange(url, HttpMethod.GET, entity, Object.class);
jsonContext = JsonPath.parse(response.getBody()); jsonContext = JsonPath.parse(response.getBody());
jsonItems = jsonContext.read(singleData.getOptionsRoot() + "['" + singleData.getAutoCompleteOptions().getLabel() + "','" + singleData.getAutoCompleteOptions().getValue() + "','" + singleData.getAutoCompleteOptions().getSource() + "','" + "uri" + "']"); jsonItems = jsonContext.read(singleData.getOptionsRoot() + "['" + singleData.getAutoCompleteOptions().getLabel() + "','" + singleData.getAutoCompleteOptions().getValue() + "','" + singleData.getAutoCompleteOptions().getSource() + "','" + "uri" + "']");
jsonItems.forEach(item -> result.add(new ExternalAutocompleteFieldModel(item.get(singleData.getAutoCompleteOptions().getValue()), item.get(singleData.getAutoCompleteOptions().getLabel()), item.get(singleData.getAutoCompleteOptions().getSource()), item.get("uri")))); jsonItems.forEach(item -> result.add(new ExternalAutocompleteFieldModel(item.get(singleData.getAutoCompleteOptions().getValue()), item.get(singleData.getAutoCompleteOptions().getLabel()), item.get(singleData.getAutoCompleteOptions().getSource()) != null ? item.get(singleData.getAutoCompleteOptions().getSource()) : singleData.getAutoCompleteOptions().getSource(), item.get("uri"))));
break; break;
case CACHED: case CACHED:
headers.setAccept(Collections.singletonList(MediaType.valueOf("text/plain; charset=utf-8"))); headers.setAccept(Collections.singletonList(MediaType.valueOf("text/plain; charset=utf-8")));
@ -199,7 +212,10 @@ public class DatasetProfileManager {
public eu.eudat.logic.utilities.documents.xml.datasetProfileXml.datasetProfileModel.DatasetProfile createDatasetProfileFromXml(MultipartFile multiPartFile) { public eu.eudat.logic.utilities.documents.xml.datasetProfileXml.datasetProfileModel.DatasetProfile createDatasetProfileFromXml(MultipartFile multiPartFile) {
ImportXmlBuilderDatasetProfile xmlBuilder = new ImportXmlBuilderDatasetProfile(); ImportXmlBuilderDatasetProfile xmlBuilder = new ImportXmlBuilderDatasetProfile();
try { try {
return xmlBuilder.build(convert(multiPartFile)); File localFile = convert(multiPartFile);
eu.eudat.logic.utilities.documents.xml.datasetProfileXml.datasetProfileModel.DatasetProfile profile = xmlBuilder.build(localFile);
Files.deleteIfExists(localFile.toPath());
return profile;
} catch (IOException e) { } catch (IOException e) {
logger.error(e.getMessage(), e); logger.error(e.getMessage(), e);
} }

View File

@ -7,15 +7,18 @@ import eu.eudat.exceptions.security.UnauthorisedException;
import eu.eudat.logic.services.ApiContext; 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.security.Principal; 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 org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import java.util.Collection; import javax.xml.bind.JAXBContext;
import java.util.LinkedList; import javax.xml.bind.JAXBException;
import java.util.List; import javax.xml.bind.Unmarshaller;
import java.util.UUID; import java.io.StringReader;
import java.util.*;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import java.util.stream.Stream; import java.util.stream.Stream;
@ -32,12 +35,19 @@ public class InvitationsManager {
public void inviteUsers(Invitation invitation, Principal principal) throws Exception { public void inviteUsers(Invitation invitation, Principal principal) throws Exception {
UserInfo principalUser = new UserInfo(); UserInfo principalUser = new UserInfo();
principalUser.setId(principal.getId()); principalUser.setId(principal.getId());
invitation.getUsers().stream().filter(item -> item.getId() == null).forEach(item -> {
UserInfo existingUser = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().asQueryable().where((builder, root) -> builder.equal(root.get("email"), item.getEmail())).getSingleOrDefault();
if (existingUser != null) {
item.setId(existingUser.getId());
}
});
List<UserInfoInvitationModel> alreadySignedInUsers = invitation.getUsers().stream().filter(item -> item.getId() != null).collect(Collectors.toList()); List<UserInfoInvitationModel> alreadySignedInUsers = invitation.getUsers().stream().filter(item -> item.getId() != null).collect(Collectors.toList());
List<UserInfo> alreadySignedInUsersEntities = alreadySignedInUsers.stream().map(UserInfoInvitationModel::toDataModel).collect(Collectors.toList()); List<UserInfo> alreadySignedInUsersEntities = alreadySignedInUsers.stream().map(UserInfoInvitationModel::toDataModel).collect(Collectors.toList());
List<UserDMP> userInfoToUserDmp = new LinkedList<>(); List<UserDMP> userInfoToUserDmp = new LinkedList<>();
for (UserInfo userInfo : alreadySignedInUsersEntities) { for (UserInfo userInfo : alreadySignedInUsersEntities) {
UserDMP userDMP = new UserDMP(); UserDMP userDMP = new UserDMP();
userDMP.setUser(userInfo); userDMP.setUser(userInfo);
userDMP.setRole(invitation.getRole());
userInfoToUserDmp.add(userDMP); userInfoToUserDmp.add(userDMP);
/*if (!apiContext.getOperationsContext().getDatabaseRepository().getUserAssociationDao().areAssociated(principalUser, userInfo)) { /*if (!apiContext.getOperationsContext().getDatabaseRepository().getUserAssociationDao().areAssociated(principalUser, userInfo)) {
UserAssociation userAssociation = new UserAssociation(); UserAssociation userAssociation = new UserAssociation();
@ -47,7 +57,7 @@ public class InvitationsManager {
}*/ }*/
} }
DMP dataManagementPlan = apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().find(invitation.getDataManagementPlan()); DMP dataManagementPlan = apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().find(invitation.getDataManagementPlan());
apiContext.getUtilitiesService().getInvitationService().createInvitations(apiContext.getOperationsContext().getDatabaseRepository().getInvitationDao(), apiContext.getUtilitiesService().getMailService(), invitation.getUsers().stream().map(UserInfoInvitationModel::toDataModel).collect(Collectors.toList()), dataManagementPlan, principalUser); apiContext.getUtilitiesService().getInvitationService().createInvitations(apiContext.getOperationsContext().getDatabaseRepository().getInvitationDao(), apiContext.getUtilitiesService().getMailService(), invitation.getUsers().stream().map(UserInfoInvitationModel::toDataModel).collect(Collectors.toList()), dataManagementPlan, invitation.getRole(), principalUser);
apiContext.getUtilitiesService().getInvitationService().assignToDmp(apiContext.getOperationsContext().getDatabaseRepository().getDmpDao(), userInfoToUserDmp, dataManagementPlan); apiContext.getUtilitiesService().getInvitationService().assignToDmp(apiContext.getOperationsContext().getDatabaseRepository().getDmpDao(), userInfoToUserDmp, dataManagementPlan);
} }
@ -69,16 +79,37 @@ public class InvitationsManager {
return userModels; return userModels;
} }
public UUID assignUserAcceptedInvitation(UUID invitationID, Principal principal) throws UnauthorisedException { public UUID assignUserAcceptedInvitation(UUID invitationID, Principal principal) throws UnauthorisedException, JAXBException {
eu.eudat.data.entities.Invitation invitation = apiContext.getOperationsContext().getDatabaseRepository().getInvitationDao().find(invitationID); eu.eudat.data.entities.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");
if (invitation.getAcceptedInvitation()) throw new UnauthorisedException("This Url Has Expired"); if (invitation.getAcceptedInvitation()) throw new UnauthorisedException("This Url Has Expired");
JAXBContext context = JAXBContext.newInstance(Properties.class);
Unmarshaller unmarshaller = context.createUnmarshaller();
Properties properties = (Properties) unmarshaller.unmarshal(new StringReader(invitation.getProperties()));
UserInfo invitedUser = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(principal.getId()); UserInfo invitedUser = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(principal.getId());
QueryableList<UserDMP> userDMPQueryableList = apiContext.getOperationsContext().getDatabaseRepository().getUserDmpDao().asQueryable().where(((builder, root) -> builder.and(builder.equal(root.get("dmp").get("id"), invitation.getDmp().getId()), builder.equal(root.get("user").get("id"), invitedUser.getId()))));
UserDMP existingUserDMP = userDMPQueryableList.getSingleOrDefault();
if (existingUserDMP != null) {
if (properties.getRole() != null && existingUserDMP.getRole() > properties.getRole()) {
existingUserDMP.setRole(properties.getRole());
DMP datamanagementPlan = invitation.getDmp();
apiContext.getOperationsContext().getDatabaseRepository().getUserDmpDao().createOrUpdate(existingUserDMP);
apiContext.getUtilitiesService().getInvitationService().assignToDmp(apiContext.getOperationsContext().getDatabaseRepository().getDmpDao(), existingUserDMP, datamanagementPlan);
invitation.setAcceptedInvitation(true);
apiContext.getOperationsContext().getDatabaseRepository().getInvitationDao().createOrUpdate(invitation);
return datamanagementPlan.getId();
}
} else {
UserDMP userDMP = new UserDMP(); UserDMP userDMP = new UserDMP();
userDMP.setUser(invitedUser); userDMP.setUser(invitedUser);
userDMP.setDmp(invitation.getDmp()); userDMP.setDmp(invitation.getDmp());
if (properties.getRole() != null) {
userDMP.setRole(properties.getRole());
} else {
userDMP.setRole(UserDMP.UserDMPRoles.USER.getValue()); userDMP.setRole(UserDMP.UserDMPRoles.USER.getValue());
}
/*if (!apiContext.getOperationsContext().getDatabaseRepository().getUserAssociationDao().areAssociated(invitedUser, invitation.getUser())) { /*if (!apiContext.getOperationsContext().getDatabaseRepository().getUserAssociationDao().areAssociated(invitedUser, invitation.getUser())) {
UserAssociation userAssociation = new UserAssociation(); UserAssociation userAssociation = new UserAssociation();
userAssociation.setFirstUser(invitedUser); userAssociation.setFirstUser(invitedUser);
@ -92,4 +123,6 @@ public class InvitationsManager {
apiContext.getOperationsContext().getDatabaseRepository().getInvitationDao().createOrUpdate(invitation); apiContext.getOperationsContext().getDatabaseRepository().getInvitationDao().createOrUpdate(invitation);
return datamanagementPlan.getId(); return datamanagementPlan.getId();
} }
return invitation.getDmp().getId();
}
} }

View File

@ -24,6 +24,7 @@ import eu.eudat.models.data.dmp.DataManagementPlan;
import eu.eudat.models.data.doi.DOIRequest; import eu.eudat.models.data.doi.DOIRequest;
import eu.eudat.models.data.helpers.common.DataTableData; import eu.eudat.models.data.helpers.common.DataTableData;
import eu.eudat.models.data.login.Credentials; import eu.eudat.models.data.login.Credentials;
import eu.eudat.models.data.principal.PrincipalModel;
import eu.eudat.models.data.security.Principal; import eu.eudat.models.data.security.Principal;
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;
@ -105,10 +106,11 @@ public class UserManager {
.createOrUpdate(userInfo); .createOrUpdate(userInfo);
} }
public Principal authenticate(AuthenticationService authenticationServiceImpl, Credentials credentials) throws NullEmailException { public PrincipalModel authenticate(AuthenticationService authenticationServiceImpl, Credentials credentials) throws NullEmailException {
Principal principal = authenticationServiceImpl.Touch(credentials); Principal principal = authenticationServiceImpl.Touch(credentials);
if (principal == null) throw new UnauthorisedException("Could not Sign In User"); if (principal == null) throw new UnauthorisedException("Could not Sign In User");
return principal; PrincipalModel principalModel = PrincipalModel.fromEntity(principal);
return principalModel;
} }
public DataTableData<UserListingModel> getCollaboratorsPaged(UserInfoTableRequestItem userInfoTableRequestItem, Principal principal) throws Exception { public DataTableData<UserListingModel> getCollaboratorsPaged(UserInfoTableRequestItem userInfoTableRequestItem, Principal principal) throws Exception {

View File

@ -3,9 +3,7 @@ package eu.eudat.logic.mapper.elastic;
import eu.eudat.data.dao.criteria.DataManagementPlanCriteria; import eu.eudat.data.dao.criteria.DataManagementPlanCriteria;
import eu.eudat.data.entities.DMP; import eu.eudat.data.entities.DMP;
import eu.eudat.elastic.criteria.DatasetCriteria; import eu.eudat.elastic.criteria.DatasetCriteria;
import eu.eudat.elastic.entities.Collaborator;
import eu.eudat.elastic.entities.Dataset; import eu.eudat.elastic.entities.Dataset;
import eu.eudat.elastic.entities.Organization;
import eu.eudat.elastic.entities.Tag; import eu.eudat.elastic.entities.Tag;
import eu.eudat.logic.managers.DatasetManager; import eu.eudat.logic.managers.DatasetManager;
import eu.eudat.logic.services.ApiContext; import eu.eudat.logic.services.ApiContext;
@ -39,6 +37,9 @@ public class DatasetMapper {
tags.forEach(tag -> tag.setId(UUID.randomUUID().toString())); tags.forEach(tag -> tag.setId(UUID.randomUUID().toString()));
elastic.setTags(tags); elastic.setTags(tags);
} else { } else {
if (tags1.size() < tags.size()) {
tags.stream().filter(tag -> tag.getId() == null || tag.getId().equals("")).forEach(tag -> tags1.add(new Tag(UUID.randomUUID().toString(), tag.getName())));
}
elastic.setTags(tags1); elastic.setTags(tags1);
} }
} }

View File

@ -15,6 +15,8 @@ public class DataFieldsUrlConfiguration {
private String path; private String path;
private String host; private String host;
private String types; private String types;
private String firstName;
private String lastName;
public String getId() { public String getId() {
return id; return id;
@ -94,4 +96,20 @@ public class DataFieldsUrlConfiguration {
public void setTypes(String types) { public void setTypes(String types) {
this.types = types; this.types = types;
} }
@XmlElement(name = "firstName")
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
@XmlElement(name = "lastName")
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
} }

View File

@ -16,7 +16,14 @@ 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.cache.annotation.Cacheable; import org.springframework.cache.annotation.Cacheable;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller; import javax.xml.bind.Unmarshaller;
@ -43,7 +50,7 @@ public class RemoteFetcher {
} }
@Cacheable("repositories") @Cacheable("repositories")
public List<Map<String, Object>> getRepositories(ExternalUrlCriteria externalUrlCriteria, String key) throws NoURLFound, HugeResultSet { public List<Map<String, String>> getRepositories(ExternalUrlCriteria externalUrlCriteria, String key) throws NoURLFound, HugeResultSet {
List<UrlConfiguration> urlConfigs = List<UrlConfiguration> urlConfigs =
key != null && !key.isEmpty() ? configLoader.getExternalUrls().getRepositories().getUrls().stream().filter(item -> item.getKey().equals(key)).collect(Collectors.toList()) key != null && !key.isEmpty() ? configLoader.getExternalUrls().getRepositories().getUrls().stream().filter(item -> item.getKey().equals(key)).collect(Collectors.toList())
: configLoader.getExternalUrls().getRepositories().getUrls(); : configLoader.getExternalUrls().getRepositories().getUrls();
@ -52,28 +59,28 @@ public class RemoteFetcher {
} }
@Cacheable("grants") @Cacheable("grants")
public List<Map<String, Object>> getGrants(ExternalUrlCriteria externalUrlCriteria) throws NoURLFound, HugeResultSet { public List<Map<String, String>> getGrants(ExternalUrlCriteria externalUrlCriteria) throws NoURLFound, HugeResultSet {
List<UrlConfiguration> urlConfigs = configLoader.getExternalUrls().getGrants().getUrls(); List<UrlConfiguration> urlConfigs = configLoader.getExternalUrls().getGrants().getUrls();
FetchStrategy fetchStrategy = configLoader.getExternalUrls().getGrants().getFetchMode(); FetchStrategy fetchStrategy = configLoader.getExternalUrls().getGrants().getFetchMode();
return getAll(urlConfigs, fetchStrategy, externalUrlCriteria); return getAll(urlConfigs, fetchStrategy, externalUrlCriteria);
} }
@Cacheable("projects") @Cacheable("projects")
public List<Map<String, Object>> getProjects(ExternalUrlCriteria externalUrlCriteria) throws NoURLFound, HugeResultSet { public List<Map<String, String>> getProjects(ExternalUrlCriteria externalUrlCriteria) throws NoURLFound, HugeResultSet {
List<UrlConfiguration> urlConfigs = configLoader.getExternalUrls().getProjects().getUrls(); List<UrlConfiguration> urlConfigs = configLoader.getExternalUrls().getProjects().getUrls();
FetchStrategy fetchStrategy = configLoader.getExternalUrls().getProjects().getFetchMode(); FetchStrategy fetchStrategy = configLoader.getExternalUrls().getProjects().getFetchMode();
return getAll(urlConfigs, fetchStrategy, externalUrlCriteria); return getAll(urlConfigs, fetchStrategy, externalUrlCriteria);
} }
@Cacheable("funders") @Cacheable("funders")
public List<Map<String, Object>> getFunders(ExternalUrlCriteria externalUrlCriteria) throws NoURLFound, HugeResultSet { public List<Map<String, String>> getFunders(ExternalUrlCriteria externalUrlCriteria) throws NoURLFound, HugeResultSet {
List<UrlConfiguration> urlConfigs = configLoader.getExternalUrls().getFunders().getUrls(); List<UrlConfiguration> urlConfigs = configLoader.getExternalUrls().getFunders().getUrls();
FetchStrategy fetchStrategy = configLoader.getExternalUrls().getFunders().getFetchMode(); FetchStrategy fetchStrategy = configLoader.getExternalUrls().getFunders().getFetchMode();
return getAll(urlConfigs, fetchStrategy, externalUrlCriteria); return getAll(urlConfigs, fetchStrategy, externalUrlCriteria);
} }
@Cacheable("organisations") @Cacheable("organisations")
public List<Map<String, Object>> getOrganisations(ExternalUrlCriteria externalUrlCriteria, String key) throws NoURLFound, HugeResultSet { public List<Map<String, String>> getOrganisations(ExternalUrlCriteria externalUrlCriteria, String key) throws NoURLFound, HugeResultSet {
List<UrlConfiguration> urlConfigs = List<UrlConfiguration> urlConfigs =
key != null && !key.isEmpty() ? configLoader.getExternalUrls().getOrganisations().getUrls().stream().filter(item -> item.getKey().equals(key)).collect(Collectors.toList()) key != null && !key.isEmpty() ? configLoader.getExternalUrls().getOrganisations().getUrls().stream().filter(item -> item.getKey().equals(key)).collect(Collectors.toList())
: configLoader.getExternalUrls().getOrganisations().getUrls(); : configLoader.getExternalUrls().getOrganisations().getUrls();
@ -82,7 +89,7 @@ public class RemoteFetcher {
} }
@Cacheable("registries") @Cacheable("registries")
public List<Map<String, Object>> getRegistries(ExternalUrlCriteria externalUrlCriteria, String key) throws NoURLFound, HugeResultSet { public List<Map<String, String>> getRegistries(ExternalUrlCriteria externalUrlCriteria, String key) throws NoURLFound, HugeResultSet {
List<UrlConfiguration> urlConfigs = List<UrlConfiguration> urlConfigs =
key != null && !key.isEmpty() ? configLoader.getExternalUrls().getRegistries().getUrls().stream().filter(item -> item.getKey().equals(key)).collect(Collectors.toList()) key != null && !key.isEmpty() ? configLoader.getExternalUrls().getRegistries().getUrls().stream().filter(item -> item.getKey().equals(key)).collect(Collectors.toList())
: configLoader.getExternalUrls().getRegistries().getUrls(); : configLoader.getExternalUrls().getRegistries().getUrls();
@ -91,7 +98,7 @@ public class RemoteFetcher {
} }
@Cacheable("services") @Cacheable("services")
public List<Map<String, Object>> getServices(ExternalUrlCriteria externalUrlCriteria, String key) throws NoURLFound, HugeResultSet { public List<Map<String, String>> getServices(ExternalUrlCriteria externalUrlCriteria, String key) throws NoURLFound, HugeResultSet {
List<UrlConfiguration> urlConfigs = List<UrlConfiguration> urlConfigs =
key != null && !key.isEmpty() ? configLoader.getExternalUrls().getServices().getUrls().stream().filter(item -> item.getKey().equals(key)).collect(Collectors.toList()) key != null && !key.isEmpty() ? configLoader.getExternalUrls().getServices().getUrls().stream().filter(item -> item.getKey().equals(key)).collect(Collectors.toList())
: configLoader.getExternalUrls().getServices().getUrls(); : configLoader.getExternalUrls().getServices().getUrls();
@ -100,7 +107,7 @@ public class RemoteFetcher {
} }
@Cacheable("researchers") @Cacheable("researchers")
public List<Map<String, Object>> getResearchers(ExternalUrlCriteria externalUrlCriteria, String key) throws NoURLFound, HugeResultSet { public List<Map<String, String>> getResearchers(ExternalUrlCriteria externalUrlCriteria, String key) throws NoURLFound, HugeResultSet {
List<UrlConfiguration> urlConfigs = List<UrlConfiguration> urlConfigs =
key != null && !key.isEmpty() ? configLoader.getExternalUrls().getResearchers().getUrls().stream().filter(item -> item.getKey().equals(key)).collect(Collectors.toList()) key != null && !key.isEmpty() ? configLoader.getExternalUrls().getResearchers().getUrls().stream().filter(item -> item.getKey().equals(key)).collect(Collectors.toList())
: configLoader.getExternalUrls().getResearchers().getUrls(); : configLoader.getExternalUrls().getResearchers().getUrls();
@ -118,7 +125,7 @@ public class RemoteFetcher {
}*/ }*/
@Cacheable("externalDatasets") @Cacheable("externalDatasets")
public List<Map<String, Object>> getDatasets(ExternalUrlCriteria externalUrlCriteria, String key) throws NoURLFound, HugeResultSet { public List<Map<String, String>> getDatasets(ExternalUrlCriteria externalUrlCriteria, String key) throws NoURLFound, HugeResultSet {
List<UrlConfiguration> urlConfigs = List<UrlConfiguration> urlConfigs =
key != null && !key.isEmpty() ? configLoader.getExternalUrls().getDatasets().getUrls().stream().filter(item -> item.getKey().equals(key)).collect(Collectors.toList()) key != null && !key.isEmpty() ? configLoader.getExternalUrls().getDatasets().getUrls().stream().filter(item -> item.getKey().equals(key)).collect(Collectors.toList())
: configLoader.getExternalUrls().getDatasets().getUrls(); : configLoader.getExternalUrls().getDatasets().getUrls();
@ -127,7 +134,7 @@ public class RemoteFetcher {
} }
@Cacheable("licenses") @Cacheable("licenses")
public List<Map<String, Object>> getlicenses(ExternalUrlCriteria externalUrlCriteria, String key) throws NoURLFound, HugeResultSet { public List<Map<String, String>> getlicenses(ExternalUrlCriteria externalUrlCriteria, String key) throws NoURLFound, HugeResultSet {
List<UrlConfiguration> urlConfigs = List<UrlConfiguration> urlConfigs =
key != null && !key.isEmpty() ? configLoader.getExternalUrls().getLicenses().getUrls().stream().filter(item -> item.getKey().equals(key)).collect(Collectors.toList()) key != null && !key.isEmpty() ? configLoader.getExternalUrls().getLicenses().getUrls().stream().filter(item -> item.getKey().equals(key)).collect(Collectors.toList())
: configLoader.getExternalUrls().getLicenses().getUrls(); : configLoader.getExternalUrls().getLicenses().getUrls();
@ -136,9 +143,9 @@ public class RemoteFetcher {
} }
private List<Map<String, Object>> getAll(List<UrlConfiguration> urlConfigs, FetchStrategy fetchStrategy, ExternalUrlCriteria externalUrlCriteria) throws NoURLFound, HugeResultSet { private List<Map<String, String>> getAll(List<UrlConfiguration> urlConfigs, FetchStrategy fetchStrategy, ExternalUrlCriteria externalUrlCriteria) throws NoURLFound, HugeResultSet {
List<Map<String, Object>> results = new LinkedList<>(); List<Map<String, String>> results = new LinkedList<>();
if (urlConfigs == null || urlConfigs.isEmpty()) return results; if (urlConfigs == null || urlConfigs.isEmpty()) return results;
// throw new NoURLFound("No Repository urls found in configuration"); // throw new NoURLFound("No Repository urls found in configuration");
@ -183,11 +190,10 @@ public class RemoteFetcher {
if (funderId.toCharArray()[0] == ':') { if (funderId.toCharArray()[0] == ':') {
funderId = externalUrlCriteria.getFunderId(); funderId = externalUrlCriteria.getFunderId();
} }
try { /*
funderId = URLEncoder.encode(funderId, "UTF-8"); try { funderId = URLEncoder.encode(funderId, "UTF-8"); } catch
} catch (UnsupportedEncodingException e) { (UnsupportedEncodingException e) { logger.error(e.getMessage(), e); }
logger.error(e.getMessage(), e); */
}
completedPath = completedPath.replace("{funderId}", funderId); completedPath = completedPath.replace("{funderId}", funderId);
} }
if (externalUrlCriteria.getPage() != null) { if (externalUrlCriteria.getPage() != null) {
@ -217,7 +223,7 @@ public class RemoteFetcher {
return completedPath; return completedPath;
} }
private List<Map<String, Object>> getAllResultsFromUrl(String path, FetchStrategy fetchStrategy, final DataUrlConfiguration jsonDataPath, final String jsonPaginationPath, ExternalUrlCriteria externalUrlCriteria, String tag, String key, String contentType, String firstPage) throws HugeResultSet { private List<Map<String, String>> getAllResultsFromUrl(String path, FetchStrategy fetchStrategy, final DataUrlConfiguration jsonDataPath, final String jsonPaginationPath, ExternalUrlCriteria externalUrlCriteria, String tag, String key, String contentType, String firstPage) throws HugeResultSet {
Set<Integer> pages = new HashSet<>(); Set<Integer> pages = new HashSet<>();
String replacedPath = replaceCriteriaOnUrl(path, externalUrlCriteria, firstPage); String replacedPath = replaceCriteriaOnUrl(path, externalUrlCriteria, firstPage);
@ -250,21 +256,28 @@ public class RemoteFetcher {
private Results getResultsFromUrl(String urlString, DataUrlConfiguration jsonDataPath, String jsonPaginationPath, String contentType) { private Results getResultsFromUrl(String urlString, DataUrlConfiguration jsonDataPath, String jsonPaginationPath, String contentType) {
try { try {
RestTemplate restTemplate = new RestTemplate();
URL url = new URL(urlString.replace(" ", "%20")); HttpHeaders headers = new HttpHeaders();
HttpEntity<String> entity;
HttpURLConnection con = (HttpURLConnection) url.openConnection(); ResponseEntity<String> response;
con.setRequestMethod("GET"); /*
* URL url = new URL(urlString.replaceAll(" ", "%20"));
*
* HttpURLConnection con = (HttpURLConnection) url.openConnection();
* con.setRequestMethod("GET");
*/
if (contentType != null && !contentType.isEmpty()) { if (contentType != null && !contentType.isEmpty()) {
con.setRequestProperty("Accept", contentType); headers.setAccept(Collections.singletonList(MediaType.valueOf(contentType)));
} }
int responseCode = con.getResponseCode(); entity = new HttpEntity<>("parameters", headers);
if (responseCode == HttpURLConnection.HTTP_OK) { // success
response = restTemplate.exchange(urlString, HttpMethod.GET, entity, String.class);
if (response.getStatusCode() == HttpStatus.OK) { // success
//do here all the parsing //do here all the parsing
Results results = new Results(); Results results = new Results();
if (con.getHeaderField("Content-Type").contains("json")) { if (response.getHeaders().get("Content-Type").get(0).contains("json")) {
DocumentContext jsonContext = JsonPath.parse(con.getInputStream()); DocumentContext jsonContext = JsonPath.parse(response.getBody());
if (jsonDataPath.getFieldsUrlConfiguration().getSource() != null) { if (jsonDataPath.getFieldsUrlConfiguration().getSource() != null) {
results = new Results(jsonContext.read(jsonDataPath.getPath() results = new Results(jsonContext.read(jsonDataPath.getPath()
@ -277,25 +290,32 @@ public class RemoteFetcher {
+ "[" + jsonDataPath.getFieldsUrlConfiguration().getName() + "[" + jsonDataPath.getFieldsUrlConfiguration().getName()
+ "," + jsonDataPath.getFieldsUrlConfiguration().getId() + "]"), + "," + jsonDataPath.getFieldsUrlConfiguration().getId() + "]"),
new HashMap<>(1, 1)); new HashMap<>(1, 1));
List<Map<String, Object>> fixedResults = results.getResults().stream().map(item -> { List<Map<String, String>> fixedResults = results.getResults().stream().map(item -> {
String id = jsonDataPath.getFieldsUrlConfiguration().getId().replace("'", ""); for (int i = 0; i < 2; i++) {
String name = jsonDataPath.getFieldsUrlConfiguration().getName().replace("'", ""); String id;
if (! (item.get(id) instanceof String)) { if (i == 0) {
if (item.get(id) instanceof LinkedHashMap) { id = jsonDataPath.getFieldsUrlConfiguration().getId().replace("'", "");
item.put(id, ((Map)item.get(id)).get("content"));
} else { } else {
id = jsonDataPath.getFieldsUrlConfiguration().getName().replace("'", "");
}
if (!(item.get(id) instanceof String)) {
Object obj = item.get(id); Object obj = item.get(id);
if (obj instanceof JSONArray) {
JSONArray jarr = (JSONArray) obj; JSONArray jarr = (JSONArray) obj;
if (jarr.get(0) instanceof String) {
item.put(id, jarr.get(0).toString()); item.put(id, jarr.get(0).toString());
}
}
if (! (item.get(name) instanceof String)) {
if (item.get(name) instanceof LinkedHashMap) {
item.put(name, ((Map)item.get(name)).get("content"));
} else { } else {
Object obj = item.get(name); for (int j = 0; j < jarr.size(); j++) {
JSONArray jarr = (JSONArray) obj; mapToMap(id, (Map<String, String>)jarr.get(j), item, i == 1);
item.put(name, ((Map)jarr.get(1)).get("content")); }
}
} else {
if (obj instanceof Map) {
mapToMap(id, (Map<String, String>) obj, item, i == 1);
} else if (obj != null){
item.put(id, obj.toString());
}
}
} }
} }
return item; return item;
@ -308,10 +328,10 @@ public class RemoteFetcher {
+ "," + jsonDataPath.getFieldsUrlConfiguration().getHost() + "]"), + "," + jsonDataPath.getFieldsUrlConfiguration().getHost() + "]"),
new HashMap<>(1, 1)); new HashMap<>(1, 1));
List<Map<String, Object>> multiResults = results.results.stream().map(result -> { List<Map<String, String>> multiResults = results.results.stream().map(result -> {
ExternalUrlCriteria externalUrlCriteria = new ExternalUrlCriteria(); ExternalUrlCriteria externalUrlCriteria = new ExternalUrlCriteria();
externalUrlCriteria.setPath((String) result.get("path")); externalUrlCriteria.setPath(result.get("path"));
externalUrlCriteria.setHost((String) result.get("host")); externalUrlCriteria.setHost(result.get("host"));
String replacedPath = replaceCriteriaOnUrl(jsonDataPath.getUrlConfiguration().getUrl(), externalUrlCriteria, jsonDataPath.getUrlConfiguration().getFirstpage()); String replacedPath = replaceCriteriaOnUrl(jsonDataPath.getUrlConfiguration().getUrl(), externalUrlCriteria, jsonDataPath.getUrlConfiguration().getFirstpage());
return getResultsFromUrl(replacedPath, jsonDataPath.getUrlConfiguration().getData(), jsonDataPath.getUrlConfiguration().getData().getPath(), jsonDataPath.getUrlConfiguration().getContentType()); return getResultsFromUrl(replacedPath, jsonDataPath.getUrlConfiguration().getData(), jsonDataPath.getUrlConfiguration().getData().getPath(), jsonDataPath.getUrlConfiguration().getContentType());
}).filter(Objects::nonNull).map(results1 -> results1.results.get(0)).collect(Collectors.toList()); }).filter(Objects::nonNull).map(results1 -> results1.results.get(0)).collect(Collectors.toList());
@ -320,9 +340,9 @@ public class RemoteFetcher {
List<Map<String, Object>> tempRes = jsonContext.read(jsonDataPath.getPath() List<Map<String, Object>> tempRes = jsonContext.read(jsonDataPath.getPath()
+ "[" + jsonDataPath.getFieldsUrlConfiguration().getId() + "," + jsonDataPath.getFieldsUrlConfiguration().getName() + "[" + jsonDataPath.getFieldsUrlConfiguration().getId() + "," + jsonDataPath.getFieldsUrlConfiguration().getName()
+ "," + jsonDataPath.getFieldsUrlConfiguration().getTypes() + "," + jsonDataPath.getFieldsUrlConfiguration().getUri() + "]"); + "," + jsonDataPath.getFieldsUrlConfiguration().getTypes() + "," + jsonDataPath.getFieldsUrlConfiguration().getUri() + "]");
List<Map<String, Object>> finalRes = new ArrayList<>(); List<Map<String, String>> finalRes = new ArrayList<>();
tempRes.forEach(map -> { tempRes.forEach(map -> {
Map<String, Object> resMap = new HashMap<>(); Map<String, String> resMap = new HashMap<>();
map.forEach((key, value) -> { map.forEach((key, value) -> {
if (key.equals(jsonDataPath.getFieldsUrlConfiguration().getTypes().substring(1, jsonDataPath.getFieldsUrlConfiguration().getTypes().length() - 1))) { if (key.equals(jsonDataPath.getFieldsUrlConfiguration().getTypes().substring(1, jsonDataPath.getFieldsUrlConfiguration().getTypes().length() - 1))) {
resMap.put("tags", ((JSONArray) value).toJSONString()); resMap.put("tags", ((JSONArray) value).toJSONString());
@ -338,6 +358,17 @@ public class RemoteFetcher {
results = new Results(finalRes, results = new Results(finalRes,
new HashMap<>(1, 1)); new HashMap<>(1, 1));
} else if (jsonDataPath.getFieldsUrlConfiguration().getFirstName() != null) {
results = new Results(jsonContext.read(jsonDataPath.getPath()
+ "[" + jsonDataPath.getFieldsUrlConfiguration().getId() + "," + jsonDataPath.getFieldsUrlConfiguration().getFirstName()
+ "," + jsonDataPath.getFieldsUrlConfiguration().getLastName() + "]"),
new HashMap<>(1, 1));
results.getResults().stream().forEach(entry -> {
String name = entry.get(jsonDataPath.getFieldsUrlConfiguration().getFirstName().replace("'", "")) + " " + entry.get(jsonDataPath.getFieldsUrlConfiguration().getLastName().replace("'", ""));
entry.put("name", name);
entry.remove(jsonDataPath.getFieldsUrlConfiguration().getFirstName().replace("'", ""));
entry.remove(jsonDataPath.getFieldsUrlConfiguration().getLastName().replace("'", ""));
});
} else { } else {
results = new Results(jsonContext.read(jsonDataPath.getPath() results = new Results(jsonContext.read(jsonDataPath.getPath()
+ "[" + jsonDataPath.getFieldsUrlConfiguration().getName() + "," + jsonDataPath.getFieldsUrlConfiguration().getDescription() + "[" + jsonDataPath.getFieldsUrlConfiguration().getName() + "," + jsonDataPath.getFieldsUrlConfiguration().getDescription()
@ -347,17 +378,18 @@ public class RemoteFetcher {
results.results = results.results.stream().map(e -> e.entrySet().stream().collect(Collectors.toMap(x -> this.transformKey(jsonDataPath,x.getKey()), Map.Entry::getValue))) results.results = results.results.stream().map(e -> e.entrySet().stream().collect(Collectors.toMap(x -> this.transformKey(jsonDataPath,x.getKey()), Map.Entry::getValue)))
.collect(Collectors.toList()); .collect(Collectors.toList());
} }
else if (con.getHeaderField("Content-Type").contains("xml")) { else if (response.getHeaders().get("Content-Type").get(0).contains("xml")) {
Class<?> aClass = Class.forName(jsonDataPath.getParseClass()); Class<?> aClass = Class.forName(jsonDataPath.getParseClass());
JAXBContext jaxbContext = JAXBContext.newInstance(aClass); JAXBContext jaxbContext = JAXBContext.newInstance(aClass);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
Object data = unmarshaller.unmarshal(con.getInputStream()); StringReader stringReader = new StringReader(response.getBody());
Object data = unmarshaller.unmarshal(stringReader);
Method reader = null; Method reader = null;
if (jsonDataPath.getParseField() != null && !jsonDataPath.getParseField().isEmpty()) { if (jsonDataPath.getParseField() != null && !jsonDataPath.getParseField().isEmpty()) {
reader = new PropertyDescriptor(jsonDataPath.getParseField(), aClass).getReadMethod(); reader = new PropertyDescriptor(jsonDataPath.getParseField(), aClass).getReadMethod();
} }
ObjectMapper objectMapper = new ObjectMapper(); ObjectMapper objectMapper = new ObjectMapper();
List<Map<String, Object>> values = new ArrayList<>(); List<Map<String, String>> values = new ArrayList<>();
int max = 1; int max = 1;
if (reader != null) { if (reader != null) {
Object invokedField = reader.invoke(data); Object invokedField = reader.invoke(data);
@ -377,10 +409,10 @@ public class RemoteFetcher {
} else { } else {
value = data; value = data;
} }
Map<String, Object> map = objectMapper.convertValue(value, Map.class); Map<String, String> map = objectMapper.convertValue(value, Map.class);
if (jsonDataPath.getMergedFields() != null && !jsonDataPath.getMergedFields().isEmpty() && jsonDataPath.getMergedFieldName() != null && !jsonDataPath.getMergedFieldName().isEmpty()) { if (jsonDataPath.getMergedFields() != null && !jsonDataPath.getMergedFields().isEmpty() && jsonDataPath.getMergedFieldName() != null && !jsonDataPath.getMergedFieldName().isEmpty()) {
Map<String, Object> finalMap = new HashMap<>(); Map<String, String> finalMap = new HashMap<>();
for (Map.Entry<String, Object> entry : map.entrySet()) { for (Map.Entry<String, String> entry : map.entrySet()) {
if (jsonDataPath.getMergedFields().contains(entry.getKey())) { if (jsonDataPath.getMergedFields().contains(entry.getKey())) {
if (!finalMap.containsKey(jsonDataPath.getMergedFieldName())) { if (!finalMap.containsKey(jsonDataPath.getMergedFieldName())) {
finalMap.put(jsonDataPath.getMergedFieldName(), entry.getValue()); finalMap.put(jsonDataPath.getMergedFieldName(), entry.getValue());
@ -401,13 +433,7 @@ public class RemoteFetcher {
return results; return results;
} }
} catch (MalformedURLException e1) { } catch (Exception exception) {
logger.error(e1.getMessage(), e1);
} //maybe print smth...
catch (IOException e2) {
logger.error(e2.getMessage(), e2);
} //maybe print smth...
catch (Exception exception) {
logger.error(exception.getMessage(), exception); logger.error(exception.getMessage(), exception);
} //maybe print smth... } //maybe print smth...
finally { finally {
@ -416,8 +442,8 @@ public class RemoteFetcher {
return null; return null;
} }
private List<Map<String, Object>> getAllResultsFromMockUpJson(String path, String query) { private List<Map<String, String>> getAllResultsFromMockUpJson(String path, String query) {
List<Map<String, Object>> internalResults; List<Map<String, String>> internalResults;
try { try {
String filePath = Paths.get(path).toUri().toURL().toString(); String filePath = Paths.get(path).toUri().toURL().toString();
ObjectMapper mapper = new ObjectMapper(); ObjectMapper mapper = new ObjectMapper();
@ -429,14 +455,14 @@ public class RemoteFetcher {
} }
} }
private List<Map<String, Object>> searchListMap(List<Map<String, Object>> internalResults, String query) { private List<Map<String, String>> searchListMap(List<Map<String, String>> internalResults, String query) {
List<Map<String, Object>> list = new LinkedList<>(); List<Map<String, String>> list = new LinkedList<>();
for (Map<String, Object> map : internalResults) for (Map<String, String> map : internalResults)
{ {
if (map.get("name") != null && ((String)map.get("name")).toUpperCase().contains(query.toUpperCase())) { if (map.get("name") != null && map.get("name").toUpperCase().contains(query.toUpperCase())) {
list.add(map); list.add(map);
} }
if (map.get("label") != null && ((String)map.get("label")).toUpperCase().contains(query.toUpperCase())) { if (map.get("label") != null && map.get("label").toUpperCase().contains(query.toUpperCase())) {
list.add(map); list.add(map);
} }
} }
@ -457,7 +483,7 @@ public class RemoteFetcher {
static class Results { static class Results {
List<Map<String, Object>> results; List<Map<String, String>> results;
Map<String, Integer> pagination; Map<String, Integer> pagination;
Results() { Results() {
@ -465,16 +491,16 @@ public class RemoteFetcher {
this.pagination = new HashMap<>(); this.pagination = new HashMap<>();
} }
Results(List<Map<String, Object>> results, Map<String, Integer> pagination) { Results(List<Map<String, String>> results, Map<String, Integer> pagination) {
this.results = results; this.results = results;
this.pagination = pagination; this.pagination = pagination;
} }
List<Map<String, Object>> getResults() { List<Map<String, String>> getResults() {
return results; return results;
} }
public void setResults(List<Map<String, Object>> results) { public void setResults(List<Map<String, String>> results) {
this.results = results; this.results = results;
} }
@ -486,4 +512,18 @@ public class RemoteFetcher {
this.pagination = pagination; this.pagination = pagination;
} }
} }
private void mapToMap(String key, Map<String, String> source, Map<String, String> destination, boolean isTitle) {
if (source != null) {
String content = source.get("content");
if (isTitle) {
String classId = source.get("classid");
if (classId.equals("main title")) {
destination.put(key, content);
}
} else {
destination.put(key, content);
}
}
}
} }

View File

@ -4,6 +4,7 @@ import eu.eudat.exceptions.security.NonValidTokenException;
import eu.eudat.exceptions.security.NullEmailException; import eu.eudat.exceptions.security.NullEmailException;
import eu.eudat.exceptions.security.UnauthorisedException; import eu.eudat.exceptions.security.UnauthorisedException;
import eu.eudat.models.data.login.LoginInfo; import eu.eudat.models.data.login.LoginInfo;
import eu.eudat.models.data.principal.PrincipalModel;
import eu.eudat.models.data.security.Principal; import eu.eudat.models.data.security.Principal;
import eu.eudat.logic.security.validators.TokenValidatorFactory; import eu.eudat.logic.security.validators.TokenValidatorFactory;
import org.slf4j.Logger; import org.slf4j.Logger;
@ -22,11 +23,11 @@ public class CustomAuthenticationProvider {
@Autowired @Autowired
private TokenValidatorFactory tokenValidatorFactory; private TokenValidatorFactory tokenValidatorFactory;
public Principal authenticate(LoginInfo credentials) throws GeneralSecurityException, NullEmailException { public PrincipalModel authenticate(LoginInfo credentials) throws GeneralSecurityException, NullEmailException {
String token = credentials.getTicket(); String token = credentials.getTicket();
try { try {
Principal principal = this.tokenValidatorFactory.getProvider(credentials.getProvider()).validateToken(credentials); Principal principal = this.tokenValidatorFactory.getProvider(credentials.getProvider()).validateToken(credentials);
return principal; return PrincipalModel.fromEntity(principal);
} catch (NonValidTokenException e) { } catch (NonValidTokenException e) {
logger.error("Could not validate a user by his token! Reason: " + e.getMessage(), e); logger.error("Could not validate a user by his token! Reason: " + e.getMessage(), e);
throw new UnauthorisedException("Token validation failed - Not a valid token"); throw new UnauthorisedException("Token validation failed - Not a valid token");

View File

@ -20,7 +20,9 @@ import org.slf4j.LoggerFactory;
import org.springframework.core.env.Environment; import org.springframework.core.env.Environment;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import java.sql.Timestamp;
import java.time.Instant; import java.time.Instant;
import java.time.LocalDateTime;
import java.util.*; import java.util.*;
public abstract class AbstractAuthenticationService implements AuthenticationService { public abstract class AbstractAuthenticationService implements AuthenticationService {
@ -98,7 +100,7 @@ public abstract class AbstractAuthenticationService implements AuthenticationSer
UserToken userToken = this.apiContext.getOperationsContext().getBuilderFactory().getBuilder(UserTokenBuilder.class) UserToken userToken = this.apiContext.getOperationsContext().getBuilderFactory().getBuilder(UserTokenBuilder.class)
.issuedAt(new Date()).user(credential.getUserInfo()) .issuedAt(new Date()).user(credential.getUserInfo())
.token(UUID.randomUUID()).expiresAt(addADay(new Date())) .token(UUID.randomUUID()).expiresAt(Timestamp.valueOf(LocalDateTime.now().plusDays(1)))
.build(); .build();
userToken = apiContext.getOperationsContext().getDatabaseRepository().getUserTokenDao().createOrUpdate(userToken); userToken = apiContext.getOperationsContext().getDatabaseRepository().getUserTokenDao().createOrUpdate(userToken);
@ -187,7 +189,7 @@ public abstract class AbstractAuthenticationService implements AuthenticationSer
UserToken userToken = this.apiContext.getOperationsContext().getBuilderFactory().getBuilder(UserTokenBuilder.class) UserToken userToken = this.apiContext.getOperationsContext().getBuilderFactory().getBuilder(UserTokenBuilder.class)
.token(UUID.randomUUID()).user(userInfo) .token(UUID.randomUUID()).user(userInfo)
.expiresAt(addADay(new Date())).issuedAt(new Date()) .expiresAt(Timestamp.valueOf(LocalDateTime.now().plusDays(1))).issuedAt(new Date())
.build(); .build();
apiContext.getOperationsContext().getDatabaseRepository().getUserTokenDao().createOrUpdate(userToken); apiContext.getOperationsContext().getDatabaseRepository().getUserTokenDao().createOrUpdate(userToken);

View File

@ -78,7 +78,9 @@ public class NonVerifiedUserEmailAuthenticationService extends AbstractAuthentic
} }
Principal principal = this.apiContext.getOperationsContext().getBuilderFactory().getBuilder(PrincipalBuilder.class) Principal principal = this.apiContext.getOperationsContext().getBuilderFactory().getBuilder(PrincipalBuilder.class)
.id(user.getId()).token(token.getToken()) .id(user.getId()).token(token.getToken())
.expiresAt(token.getExpiresAt()).name(user.getName()) .expiresAt(token.getExpiresAt())
.name(user.getName())
.email(user.getEmail())
.avatarUrl(avatarUrl) .avatarUrl(avatarUrl)
.culture(culture) .culture(culture)
.language(language) .language(language)

View File

@ -87,7 +87,9 @@ public class VerifiedUserAuthenticationService extends AbstractAuthenticationSer
} }
Principal principal = this.apiContext.getOperationsContext().getBuilderFactory().getBuilder(PrincipalBuilder.class) Principal principal = this.apiContext.getOperationsContext().getBuilderFactory().getBuilder(PrincipalBuilder.class)
.id(user.getId()).token(token.getToken()) .id(user.getId()).token(token.getToken())
.expiresAt(token.getExpiresAt()).name(user.getName()) .expiresAt(token.getExpiresAt())
.name(user.getName())
.email(user.getEmail())
.avatarUrl(avatarUrl) .avatarUrl(avatarUrl)
.culture(culture) .culture(culture)
.language(language) .language(language)

View File

@ -16,7 +16,7 @@ public interface InvitationService {
void assignToDmp(DMPDao dmpDao, eu.eudat.data.entities.UserDMP user, DMP dmp); void assignToDmp(DMPDao dmpDao, eu.eudat.data.entities.UserDMP user, DMP dmp);
void createInvitations(InvitationDao invitationDao, MailService mailService, List<eu.eudat.data.entities.UserInfo> users, DMP dmp, eu.eudat.data.entities.UserInfo creator) throws MessagingException; void createInvitations(InvitationDao invitationDao, MailService mailService, List<eu.eudat.data.entities.UserInfo> users, DMP dmp, Integer role, eu.eudat.data.entities.UserInfo creator) throws MessagingException;
CompletableFuture sendInvitationAsync(DMP dmp, Invitation invitation, String recipient, MailService mailService) throws MessagingException; CompletableFuture sendInvitationAsync(DMP dmp, Invitation invitation, String recipient, MailService mailService, Integer role) throws MessagingException;
} }

View File

@ -5,6 +5,8 @@ import eu.eudat.data.dao.entities.DMPDao;
import eu.eudat.data.dao.entities.InvitationDao; import eu.eudat.data.dao.entities.InvitationDao;
import eu.eudat.data.entities.DMP; import eu.eudat.data.entities.DMP;
import eu.eudat.data.entities.Invitation; import eu.eudat.data.entities.Invitation;
import eu.eudat.data.entities.UserDMP;
import eu.eudat.models.data.invitation.Properties;
import eu.eudat.models.data.mail.SimpleMail; import eu.eudat.models.data.mail.SimpleMail;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -13,6 +15,9 @@ import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import javax.mail.MessagingException; import javax.mail.MessagingException;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import java.io.StringWriter;
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;
@ -46,7 +51,7 @@ public class InvitationServiceImpl implements InvitationService {
} }
@Override @Override
public void createInvitations(InvitationDao invitationDao, MailService mailService, List<eu.eudat.data.entities.UserInfo> users, DMP dmp, eu.eudat.data.entities.UserInfo creator) throws MessagingException { public void createInvitations(InvitationDao invitationDao, MailService mailService, List<eu.eudat.data.entities.UserInfo> users, DMP dmp, Integer role, eu.eudat.data.entities.UserInfo creator) throws MessagingException {
for (eu.eudat.data.entities.UserInfo userInfo : users) { for (eu.eudat.data.entities.UserInfo userInfo : users) {
Invitation invitation = new Invitation(); Invitation invitation = new Invitation();
invitation.setDmp(dmp); invitation.setDmp(dmp);
@ -54,17 +59,28 @@ public class InvitationServiceImpl implements InvitationService {
invitation.setUser(creator); invitation.setUser(creator);
invitation.setToken(UUID.randomUUID()); invitation.setToken(UUID.randomUUID());
invitation.setAcceptedInvitation(false); invitation.setAcceptedInvitation(false);
Properties properties = new Properties();
properties.setRole(role);
try {
JAXBContext context = JAXBContext.newInstance(Properties.class);
Marshaller marshaller = context.createMarshaller();
StringWriter propertyWriter = new StringWriter();
marshaller.marshal(properties, propertyWriter);
invitation.setProperties(propertyWriter.toString());
}catch (Exception e) {
logger.error(e.getMessage(), e);
}
invitationDao.createOrUpdate(invitation); invitationDao.createOrUpdate(invitation);
sendInvitationAsync(dmp, invitation, userInfo.getName(), mailService); sendInvitationAsync(dmp, invitation, userInfo.getName(), mailService, role);
} }
} }
@Override @Override
public CompletableFuture sendInvitationAsync(DMP dmp, Invitation invitation, String recipient, MailService mailService) { public CompletableFuture sendInvitationAsync(DMP dmp, Invitation invitation, String recipient, MailService mailService, Integer role) {
return CompletableFuture.runAsync(() -> { return CompletableFuture.runAsync(() -> {
SimpleMail mail = new SimpleMail(); SimpleMail mail = new SimpleMail();
mail.setSubject(createSubject(dmp, mailService.getMailTemplateSubject())); mail.setSubject(createSubject(dmp, mailService.getMailTemplateSubject()));
mail.setContent(createContent(invitation.getId(), dmp, recipient, mailService.getMailTemplateContent("classpath:templates/email/email.html"))); mail.setContent(createContent(invitation.getId(), dmp, recipient, mailService.getMailTemplateContent("classpath:templates/email/email.html"), role));
mail.setTo(invitation.getInvitationEmail()); mail.setTo(invitation.getInvitationEmail());
try { try {
mailService.sendSimpleMail(mail); mailService.sendSimpleMail(mail);
@ -79,11 +95,12 @@ public class InvitationServiceImpl implements InvitationService {
return subject; return subject;
} }
private String createContent(UUID invitationID, DMP dmp, String recipient, String templateContent) { private String createContent(UUID invitationID, DMP dmp, String recipient, String templateContent, Integer role) {
String content = templateContent.replace("{dmpname}", dmp.getLabel()); String content = templateContent.replace("{dmpname}", dmp.getLabel());
content = content.replace("{invitationID}", invitationID.toString()); content = content.replace("{invitationID}", invitationID.toString());
content = content.replace("{recipient}", recipient); content = content.replace("{recipient}", recipient);
content = content.replace("{host}", this.environment.getProperty("dmp.domain")); content = content.replace("{host}", this.environment.getProperty("dmp.domain"));
content = content.replace("{dmprole}", UserDMP.UserDMPRoles.fromInteger(role).name());
return content; return content;
} }

View File

@ -205,6 +205,7 @@ public class ExportXmlBuilderDatasetProfile {
WordListData wordListDataObject = (WordListData) field.getData(); WordListData wordListDataObject = (WordListData) field.getData();
dataOut.setAttribute("label", wordListDataObject.getLabel()); dataOut.setAttribute("label", wordListDataObject.getLabel());
dataOut.setAttribute("type", wordListDataObject.getType()); dataOut.setAttribute("type", wordListDataObject.getType());
dataOut.setAttribute("multiList", wordListDataObject.getMultiList().toString());
Element options = element.createElement("options"); Element options = element.createElement("options");
wordListDataObject.getOptions().forEach(optionChildFor -> { wordListDataObject.getOptions().forEach(optionChildFor -> {
Element optionChild = element.createElement("option"); Element optionChild = element.createElement("option");

View File

@ -0,0 +1,13 @@
package eu.eudat.logic.utilities.json;
public class JavaToJson {
public static String objectStringToJson(String object) {
String result = object.replaceAll("=", "\":\"")
.replaceAll("\\{", "{\"")
.replaceAll(", ", "\", \"")
.replaceAll("}", "\"}" ).
replaceAll("}\", \"\\{", "}, {");
return result;
}
}

View File

@ -129,6 +129,9 @@ public class AutoCompleteData extends ComboBoxData<AutoCompleteData> {
this.multiAutoComplete = (Boolean) ((Map<Boolean, Object>) data).get("multiAutoComplete"); this.multiAutoComplete = (Boolean) ((Map<Boolean, Object>) data).get("multiAutoComplete");
List<Map<String, Object>> dataList = (List<Map<String, Object>>) ((Map<String, Object>) data).get("autocompleteSingle"); List<Map<String, Object>> dataList = (List<Map<String, Object>>) ((Map<String, Object>) data).get("autocompleteSingle");
if (dataList == null) {
dataList = (List<Map<String, Object>>) ((Map<String, Object>) data).get("autoCompleteSingleDataList");
}
this.autoCompleteSingleDataList = new ArrayList<>(); this.autoCompleteSingleDataList = new ArrayList<>();
@ -174,14 +177,15 @@ public class AutoCompleteData extends ComboBoxData<AutoCompleteData> {
List<Map<String, Object>> autoCompletes = new ArrayList<>(); List<Map<String, Object>> autoCompletes = new ArrayList<>();
NodeList autoCompleteSingles = item.getChildNodes(); NodeList autoCompleteSingles = item.getChildNodes();
for (int i = 0; i < autoCompleteSingles.getLength(); i++) { for (int i = 0; i < autoCompleteSingles.getLength(); i++) {
if (autoCompleteSingles.item(i) instanceof Element && !((Element) autoCompleteSingles.item(i)).getTagName().equals("option")) { if (autoCompleteSingles.item(i) instanceof Element) {
if (!((Element) autoCompleteSingles.item(i)).getTagName().equals("option")) {
Element node = (Element) autoCompleteSingles.item(i); Element node = (Element) autoCompleteSingles.item(i);
if (!node.hasChildNodes()) { if (!node.hasChildNodes()) {
node.appendChild(node); node.appendChild(node);
} }
autoCompletes.add(singleToMap(node)); autoCompletes.add(singleToMap(node));
} else if (((Element) autoCompleteSingles.item(i)).getTagName().equals("option")) { } else {
Element node = item.getOwnerDocument().createElement("autocompleteSingle"); Element node = item.getOwnerDocument().createElement("autocompleteSingle");
node.appendChild(autoCompleteSingles.item(i)); node.appendChild(autoCompleteSingles.item(i));
node.setAttribute("url", item.getAttribute("url")); node.setAttribute("url", item.getAttribute("url"));
@ -189,6 +193,7 @@ public class AutoCompleteData extends ComboBoxData<AutoCompleteData> {
autoCompletes.add(singleToMap(node)); autoCompletes.add(singleToMap(node));
} }
} }
}
dataMap.put("autocompleteSingle", autoCompletes); dataMap.put("autocompleteSingle", autoCompletes);
//dataMap.put("optionsRoot", item != null ? item.getAttribute("optionsRoot") : ""); //dataMap.put("optionsRoot", item != null ? item.getAttribute("optionsRoot") : "");
//Element optionElement = (Element) item.getElementsByTagName("option").item(0); //Element optionElement = (Element) item.getElementsByTagName("option").item(0);

View File

@ -12,6 +12,7 @@ import java.util.Map;
public class WordListData extends ComboBoxData<WordListData> { public class WordListData extends ComboBoxData<WordListData> {
private List<Option> options; private List<Option> options;
private Boolean multiList;
public List<Option> getOptions() { public List<Option> getOptions() {
return options; return options;
@ -21,10 +22,18 @@ public class WordListData extends ComboBoxData<WordListData> {
this.options = options; this.options = options;
} }
public Boolean getMultiList() {
return multiList;
}
public void setMultiList(Boolean multiList) {
this.multiList = multiList;
}
@Override @Override
public Element toXml(Document doc) { public Element toXml(Document doc) {
Element root = super.toXml(doc); Element root = super.toXml(doc);
root.setAttribute("multiList", this.multiList != null ? this.multiList.toString() : "false");
Element element = doc.createElement("options"); Element element = doc.createElement("options");
if (this.options != null) { if (this.options != null) {
for (Option option : this.options) { for (Option option : this.options) {
@ -50,6 +59,8 @@ public class WordListData extends ComboBoxData<WordListData> {
} }
} }
} }
Boolean temp = Boolean.parseBoolean(item.getAttribute("multiList"));
this.multiList = temp != null ? temp : false;
return this; return this;
} }
@ -57,7 +68,6 @@ public class WordListData extends ComboBoxData<WordListData> {
public WordListData fromData(Object data) { public WordListData fromData(Object data) {
super.fromData(data); super.fromData(data);
this.options = new LinkedList(); this.options = new LinkedList();
if (data != null) { if (data != null) {
List<Map<String, String>> options = ((Map<String, List<Map<String, String>>>) data).get("options"); List<Map<String, String>> options = ((Map<String, List<Map<String, String>>>) data).get("options");
if (options != null) { if (options != null) {
@ -68,8 +78,9 @@ public class WordListData extends ComboBoxData<WordListData> {
this.options.add(newOption); this.options.add(newOption);
} }
} }
Object multiList1 = ((Map<String, Object>) data).get("multiList");
this.multiList = multiList1 instanceof String ? Boolean.parseBoolean((String) multiList1) : (Boolean) multiList1;
} }
return this; return this;
} }
@ -82,6 +93,7 @@ public class WordListData extends ComboBoxData<WordListData> {
@Override @Override
public Map<String, Object> toMap(Element item) { public Map<String, Object> toMap(Element item) {
HashMap dataMap = new HashMap(); HashMap dataMap = new HashMap();
dataMap.put("multiList", item != null ? item.getAttribute("multiList") : "false");
dataMap.put("label", item != null ? item.getAttribute("label") : ""); dataMap.put("label", item != null ? item.getAttribute("label") : "");
dataMap.put("type", item != null ? item.getAttribute("type") : "wordlist"); dataMap.put("type", item != null ? item.getAttribute("type") : "wordlist");
Element optionsElement = (Element) item.getElementsByTagName("options").item(0); Element optionsElement = (Element) item.getElementsByTagName("options").item(0);

View File

@ -0,0 +1,184 @@
package eu.eudat.models.data.dashboard.recent.model;
import eu.eudat.models.DataModel;
import eu.eudat.models.data.datasetprofile.DatasetProfileOverviewModel;
import eu.eudat.models.data.listingmodels.UserInfoListingModel;
import eu.eudat.queryable.queryableentity.DataEntity;
import java.util.Date;
import java.util.List;
public abstract class RecentActivityModel<T extends DataEntity, S extends DataModel> implements DataModel<T, S> {
private String id;
private String title;
private String description;
private Date created;
private Date modified;
private int status;
private int version;
private String grant;
private String grantAbbreviation;
private String grantId;
private Date finalizedAt;
private Date publishedAt;
private DatasetProfileOverviewModel profile;
private int type;
private List<UserInfoListingModel> users;
private Boolean isPublic;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public Date getModified() {
return modified;
}
public void setModified(Date modified) {
this.modified = modified;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public int getVersion() {
return version;
}
public void setVersion(int version) {
this.version = version;
}
public String getGrant() {
return grant;
}
public void setGrant(String grant) {
this.grant = grant;
}
public String getGrantAbbreviation() {
return grantAbbreviation;
}
public void setGrantAbbreviation(String grantAbbreviation) {
this.grantAbbreviation = grantAbbreviation;
}
public String getGrantId() {
return grantId;
}
public void setGrantId(String grantId) {
this.grantId = grantId;
}
public Date getFinalizedAt() {
return finalizedAt;
}
public void setFinalizedAt(Date finalizedAt) {
this.finalizedAt = finalizedAt;
}
public Date getPublishedAt() {
return publishedAt;
}
public void setPublishedAt(Date publishedAt) {
this.publishedAt = publishedAt;
}
public DatasetProfileOverviewModel getProfile() {
return profile;
}
public void setProfile(DatasetProfileOverviewModel profile) {
this.profile = profile;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public List<UserInfoListingModel> getUsers() {
return users;
}
public void setUsers(List<UserInfoListingModel> users) {
this.users = users;
}
public Boolean getPublic() {
return isPublic;
}
public void setPublic(Boolean aPublic) {
isPublic = aPublic;
}
public abstract RecentActivityModel fromEntity(T entity);
public enum RecentActivityType {
DMP(2), DATASET(1);
private final int index;
RecentActivityType(int index) {
this.index = index;
}
public int getIndex() {
return index;
}
public static RecentActivityType fromIndex(int index) {
switch (index) {
case 2:
return DMP;
case 1:
return DATASET;
default:
throw new IllegalArgumentException("Recent Activity Type : \"" + index + "\" is not supported.");
}
}
}
}

View File

@ -0,0 +1,121 @@
package eu.eudat.models.data.dashboard.recent.model;
import eu.eudat.data.entities.Dataset;
import eu.eudat.logic.utilities.helpers.LabelBuilder;
import eu.eudat.models.data.dataset.DataRepository;
import eu.eudat.models.data.dataset.Service;
import eu.eudat.models.data.datasetprofile.DatasetProfileOverviewModel;
import eu.eudat.models.data.listingmodels.UserInfoListingModel;
import java.util.Date;
import java.util.stream.Collectors;
public class RecentDatasetModel extends RecentActivityModel<Dataset, RecentDatasetModel> {
private String dmp;
private String dmpId;
private String dataRepositories;
private String registries;
private String services;
public String getDmp() {
return dmp;
}
public void setDmp(String dmp) {
this.dmp = dmp;
}
public String getDmpId() {
return dmpId;
}
public void setDmpId(String dmpId) {
this.dmpId = dmpId;
}
public String getDataRepositories() {
return dataRepositories;
}
public void setDataRepositories(String dataRepositories) {
this.dataRepositories = dataRepositories;
}
public String getRegistries() {
return registries;
}
public void setRegistries(String registries) {
this.registries = registries;
}
public String getServices() {
return services;
}
public void setServices(String services) {
this.services = services;
}
@Override
public RecentActivityModel fromEntity(Dataset entity) {
this.setType(RecentActivityType.DATASET.getIndex());
this.setId(entity.getId().toString());
this.setTitle(entity.getLabel());
this.setDescription(entity.getDescription());
this.setCreated(entity.getCreated());
this.setModified(entity.getModified());
this.setStatus(entity.getStatus());
this.setVersion(entity.getDmp() != null ? entity.getDmp().getVersion(): 0);
this.setFinalizedAt(entity.getFinalizedAt());
this.setGrantAbbreviation(entity.getDmp() != null ? entity.getDmp().getGrant().getAbbreviation() : "");
this.setPublishedAt(entity.getDmp() != null ? entity.getDmp().getPublishedAt() : new Date());
this.setGrantId(entity.getDmp() != null ? entity.getDmp().getGrant().getId().toString() : "");
this.setProfile(entity.getProfile() != null ? new DatasetProfileOverviewModel().fromDataModel(entity.getProfile()): null);
this.setGrant(entity.getDmp() != null ? entity.getDmp().getGrant().getLabel() : "");
this.setDataRepositories(entity.getDatasetDataRepositories() != null && !entity.getDatasetDataRepositories().isEmpty()? LabelBuilder.getLabel(entity.getDatasetDataRepositories().stream().map(item -> new DataRepository().fromDataModel(item.getDataRepository())).collect(Collectors.toList())) : "");
this.setDmp( entity.getDmp() != null ? entity.getDmp().getLabel() : "");
this.setDmpId(entity.getDmp() != null ? entity.getDmp().getId().toString() : "");
this.setRegistries(LabelBuilder.getLabel(entity.getRegistries().stream().map(item -> new eu.eudat.models.data.dataset.Registry().fromDataModel(item)).collect(Collectors.toList())));
this.setServices(LabelBuilder.getLabel(entity.getServices().stream().map(item -> new Service().fromDataModel(item.getService())).collect(Collectors.toList())));
this.setPublic(entity.getDmp().isPublic());
this.setUsers(entity.getDmp().getUsers().stream().map(x -> new UserInfoListingModel().fromDataModel(x)).collect(Collectors.toList()));
return this;
}
public RecentDatasetModel fromDmpEntity(Dataset entity) {
this.setType(RecentActivityType.DATASET.getIndex());
this.setId(entity.getId().toString());
this.setTitle(entity.getLabel());
this.setDescription(entity.getDescription());
this.setCreated(entity.getCreated());
this.setModified(entity.getModified());
this.setStatus(entity.getStatus());
this.setVersion(entity.getDmp() != null ? entity.getDmp().getVersion(): 0);
this.setFinalizedAt(entity.getFinalizedAt());
this.setGrantAbbreviation(entity.getDmp() != null ? entity.getDmp().getGrant().getAbbreviation() : "");
this.setPublishedAt(entity.getDmp() != null ? entity.getDmp().getPublishedAt() : new Date());
this.setGrantId(entity.getDmp() != null ? entity.getDmp().getGrant().getId().toString() : "");
this.setProfile(entity.getProfile() != null ? new DatasetProfileOverviewModel().fromDataModel(entity.getProfile()) : null);
this.setGrant(entity.getDmp() != null ? entity.getDmp().getGrant().getLabel() : "");
this.setDmp( entity.getDmp() != null ? entity.getDmp().getLabel() : "");
this.setDmpId(entity.getDmp() != null ? entity.getDmp().getId().toString() : "");
return this;
}
@Override
public RecentDatasetModel fromDataModel(Dataset entity) {
return (RecentDatasetModel) this.fromEntity(entity);
}
@Override
public Dataset toDataModel() throws Exception {
return null;
}
@Override
public String getHint() {
return "recentDatasetModel";
}
}

View File

@ -0,0 +1,114 @@
package eu.eudat.models.data.dashboard.recent.model;
import eu.eudat.data.entities.DMP;
import eu.eudat.logic.utilities.helpers.LabelBuilder;
import eu.eudat.models.data.dmp.AssociatedProfile;
import eu.eudat.models.data.dmp.Organisation;
import eu.eudat.models.data.listingmodels.UserInfoListingModel;
import eu.eudat.models.data.urls.DatasetUrlListing;
import javax.transaction.Transactional;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;
public class RecentDmpModel extends RecentActivityModel<DMP, RecentDmpModel> {
private String doi;
private Map<String, Object> extraProperties;
private List<DatasetUrlListing> datasets;
private List<AssociatedProfile> associatedProfiles;
private String organisations;
private UUID groupId;
public String getDoi() {
return doi;
}
public void setDoi(String doi) {
this.doi = doi;
}
public Map<String, Object> getExtraProperties() {
return extraProperties;
}
public void setExtraProperties(Map<String, Object> extraProperties) {
this.extraProperties = extraProperties;
}
public List<DatasetUrlListing> getDatasets() {
return datasets;
}
public void setDatasets(List<DatasetUrlListing> datasets) {
this.datasets = datasets;
}
public List<AssociatedProfile> getAssociatedProfiles() {
return associatedProfiles;
}
public void setAssociatedProfiles(List<AssociatedProfile> associatedProfiles) {
this.associatedProfiles = associatedProfiles;
}
public String getOrganisations() {
return organisations;
}
public void setOrganisations(String organisations) {
this.organisations = organisations;
}
public UUID getGroupId() {
return groupId;
}
public void setGroupId(UUID groupId) {
this.groupId = groupId;
}
@Override
@Transactional
public RecentActivityModel fromEntity(DMP entity) {
this.setType(RecentActivityType.DMP.getIndex());
this.setId(entity.getId().toString());
this.setTitle(entity.getLabel());
this.setDescription(entity.getDescription());
this.setCreated(entity.getCreated());
this.setModified(entity.getModified());
this.setStatus(entity.getStatus());
this.setVersion(entity.getVersion());
//this.datasets = entity.getDataset().stream().map(dataset -> new RecentDatasetModel().fromDmpEntity(dataset)).collect(Collectors.toList());
this.datasets = entity.getDataset().stream().map(dataset -> new DatasetUrlListing().fromDataModel(dataset)).collect(Collectors.toList());
this.associatedProfiles = entity.getAssociatedDmps().stream().map(item -> new AssociatedProfile().fromData(item)).collect(Collectors.toList());
this.setFinalizedAt(entity.getFinalizedAt());
this.setGrant(entity.getGrant().getLabel());
this.setGrantAbbreviation(entity.getGrant().getAbbreviation());
this.setGrantId(entity.getGrant().getId().toString());
this.groupId = entity.getGroupId();
this.setPublic(entity.isPublic());
this.organisations = LabelBuilder.getLabel(entity.getOrganisations().stream().map(item -> new Organisation().fromDataModel(item)).collect(Collectors.toList()));
//if (entity.getProfile() != null) this.setProfile(new DatasetProfileOverviewModel().fromDataModel(entity.getProfile()));
this.setPublishedAt(entity.getPublishedAt());
this.setUsers(entity.getUsers().stream().map(x -> new UserInfoListingModel().fromDataModel(x)).collect(Collectors.toList()));
return this;
}
@Override
public RecentDmpModel fromDataModel(DMP entity) {
return (RecentDmpModel) this.fromEntity(entity);
}
@Override
public DMP toDataModel() throws Exception {
return null;
}
@Override
public String getHint() {
return "recentDmpModel";
}
}

View File

@ -0,0 +1,52 @@
package eu.eudat.models.data.dashboard.recent.tablerequest;
import eu.eudat.criteria.RecentActivityCriteria;
import eu.eudat.data.query.definition.helpers.ColumnOrderings;
public class RecentActivityTableRequest {
private ColumnOrderings orderings;
private RecentActivityCriteria criteria;
private int dmpOffset;
private int datasetOffset;
private int length;
public int getDmpOffset() {
return dmpOffset;
}
public void setDmpOffset(int dmpOffset) {
this.dmpOffset = dmpOffset;
}
public int getDatasetOffset() {
return datasetOffset;
}
public void setDatasetOffset(int datasetOffset) {
this.datasetOffset = datasetOffset;
}
public int getLength() {
return length;
}
public void setLength(int length) {
this.length = length;
}
public RecentActivityCriteria getCriteria() {
return criteria;
}
public void setCriteria(RecentActivityCriteria criteria) {
this.criteria = criteria;
}
public ColumnOrderings getOrderings() {
return orderings;
}
public void setOrderings(ColumnOrderings orderings) {
this.orderings = orderings;
}
}

View File

@ -3,8 +3,14 @@ package eu.eudat.models.data.dataset;
import eu.eudat.data.entities.Dataset; import eu.eudat.data.entities.Dataset;
import eu.eudat.models.DataModel; import eu.eudat.models.DataModel;
import eu.eudat.models.data.datasetprofile.DatasetProfileOverviewModel; import eu.eudat.models.data.datasetprofile.DatasetProfileOverviewModel;
import eu.eudat.models.data.grant.GrantOverviewModel;
import eu.eudat.models.data.listingmodels.DataManagementPlanOverviewModel;
import eu.eudat.models.data.listingmodels.UserInfoListingModel;
import java.util.Date;
import java.util.List;
import java.util.UUID; import java.util.UUID;
import java.util.stream.Collectors;
public class DatasetOverviewModel implements DataModel<Dataset, DatasetOverviewModel> { public class DatasetOverviewModel implements DataModel<Dataset, DatasetOverviewModel> {
@ -12,6 +18,12 @@ public class DatasetOverviewModel implements DataModel<Dataset, DatasetOverviewM
private String label; private String label;
private short status; private short status;
private DatasetProfileOverviewModel datasetTemplate; private DatasetProfileOverviewModel datasetTemplate;
private List<UserInfoListingModel> users;
private DataManagementPlanOverviewModel dmp;
private GrantOverviewModel grant;
private String description;
private Boolean isPublic;
private Date modified;
public UUID getId() { public UUID getId() {
return id; return id;
@ -41,12 +53,66 @@ public class DatasetOverviewModel implements DataModel<Dataset, DatasetOverviewM
this.datasetTemplate = datasetTemplate; this.datasetTemplate = datasetTemplate;
} }
public List<UserInfoListingModel> getUsers() {
return users;
}
public void setUsers(List<UserInfoListingModel> users) {
this.users = users;
}
public DataManagementPlanOverviewModel getDmp() {
return dmp;
}
public void setDmp(DataManagementPlanOverviewModel dmp) {
this.dmp = dmp;
}
public GrantOverviewModel getGrant() {
return grant;
}
public void setGrant(GrantOverviewModel grant) {
this.grant = grant;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Boolean getPublic() {
return isPublic;
}
public void setPublic(Boolean aPublic) {
isPublic = aPublic;
}
public Date getModified() {
return modified;
}
public void setModified(Date modified) {
this.modified = modified;
}
@Override @Override
public DatasetOverviewModel fromDataModel(Dataset entity) { public DatasetOverviewModel fromDataModel(Dataset entity) {
this.id = entity.getId(); this.id = entity.getId();
this.label = entity.getLabel(); this.label = entity.getLabel();
this.status = entity.getStatus(); this.status = entity.getStatus();
this.datasetTemplate = new DatasetProfileOverviewModel().fromDataModel(entity.getProfile()); this.datasetTemplate = new DatasetProfileOverviewModel().fromDataModel(entity.getProfile());
this.users = entity.getDmp().getUsers().stream().map(x -> new UserInfoListingModel().fromDataModel(x)).collect(Collectors.toList());
this.dmp = new DataManagementPlanOverviewModel().fromDataModel(entity.getDmp());
this.grant = new GrantOverviewModel().fromDataModel(entity.getDmp().getGrant());
this.description = entity.getDescription();
this.isPublic = entity.getDmp().isPublic();
this.modified = entity.getModified();
return this; return this;
} }

View File

@ -6,7 +6,7 @@ import eu.eudat.models.DataModel;
import eu.eudat.models.data.dataset.DataRepository; import eu.eudat.models.data.dataset.DataRepository;
import eu.eudat.models.data.dataset.Registry; import eu.eudat.models.data.dataset.Registry;
import eu.eudat.models.data.dataset.Service; import eu.eudat.models.data.dataset.Service;
import eu.eudat.models.data.datasetprofile.DatasetProfileListingModel; import eu.eudat.models.data.datasetprofile.DatasetProfileOverviewModel;
import eu.eudat.models.data.dmp.DataManagementPlan; import eu.eudat.models.data.dmp.DataManagementPlan;
import eu.eudat.models.data.externaldataset.ExternalDatasetListingModel; import eu.eudat.models.data.externaldataset.ExternalDatasetListingModel;
import eu.eudat.models.data.user.composite.PagedDatasetProfile; import eu.eudat.models.data.user.composite.PagedDatasetProfile;
@ -32,7 +32,7 @@ public class DatasetWizardModel implements DataModel<Dataset, DatasetWizardModel
private List<DataRepository> dataRepositories; private List<DataRepository> dataRepositories;
private List<Tag> tags; private List<Tag> tags;
private List<ExternalDatasetListingModel> externalDatasets; private List<ExternalDatasetListingModel> externalDatasets;
private UUID profile; private DatasetProfileOverviewModel profile;
private Boolean isProfileLatestVersion; private Boolean isProfileLatestVersion;
private Date modified; private Date modified;
@ -120,10 +120,11 @@ public class DatasetWizardModel implements DataModel<Dataset, DatasetWizardModel
this.dataRepositories = dataRepositories; this.dataRepositories = dataRepositories;
} }
public UUID getProfile() { public DatasetProfileOverviewModel getProfile() {
return profile; return profile;
} }
public void setProfile(UUID profile) {
public void setProfile(DatasetProfileOverviewModel profile) {
this.profile = profile; this.profile = profile;
} }
@ -162,7 +163,8 @@ public class DatasetWizardModel implements DataModel<Dataset, DatasetWizardModel
this.status = entity.getStatus(); this.status = entity.getStatus();
this.reference = entity.getReference(); this.reference = entity.getReference();
this.description = entity.getDescription(); this.description = entity.getDescription();
this.profile = entity.getProfile().getId(); this.profile = new DatasetProfileOverviewModel();
this.profile = this.profile.fromDataModel(entity.getProfile());
this.uri = entity.getUri(); this.uri = entity.getUri();
this.registries = entity.getRegistries() != null ? entity.getRegistries().stream().map(item -> new Registry().fromDataModel(item)).collect(Collectors.toList()) : new ArrayList<>(); this.registries = entity.getRegistries() != null ? entity.getRegistries().stream().map(item -> new Registry().fromDataModel(item)).collect(Collectors.toList()) : new ArrayList<>();
this.dataRepositories = entity.getDatasetDataRepositories() != null ? entity.getDatasetDataRepositories().stream().map(item -> { this.dataRepositories = entity.getDatasetDataRepositories() != null ? entity.getDatasetDataRepositories().stream().map(item -> {
@ -191,6 +193,41 @@ public class DatasetWizardModel implements DataModel<Dataset, DatasetWizardModel
return this; return this;
} }
public DatasetWizardModel fromDataModelNoDmp(Dataset entity) {
this.id = entity.getId();
this.label = entity.getLabel();
this.status = entity.getStatus();
this.reference = entity.getReference();
this.description = entity.getDescription();
this.profile = new DatasetProfileOverviewModel();
this.profile = this.profile.fromDataModel(entity.getProfile());
this.uri = entity.getUri();
this.registries = entity.getRegistries() != null ? entity.getRegistries().stream().map(item -> new Registry().fromDataModel(item)).collect(Collectors.toList()) : new ArrayList<>();
this.dataRepositories = entity.getDatasetDataRepositories() != null ? entity.getDatasetDataRepositories().stream().map(item -> {
DataRepository dataRepository = new DataRepository().fromDataModel(item.getDataRepository());
if (item.getData() != null) {
Map<String, Map<String, String>> data = (Map<String, Map<String, String>>) JSONValue.parse(item.getData());
Map<String, String> values = data.get("data");
dataRepository.setInfo(values.get("info"));
}
return dataRepository;
}).collect(Collectors.toList()) : new ArrayList<>();
this.services = entity.getServices() != null ? entity.getServices().stream().map(item -> new Service().fromDataModel(item.getService())).collect(Collectors.toList()) : new ArrayList<>();
this.created = entity.getCreated();
this.externalDatasets = entity.getDatasetExternalDatasets() != null ? entity.getDatasetExternalDatasets().stream().map(item -> {
ExternalDatasetListingModel externalDatasetListingModel = new ExternalDatasetListingModel().fromDataModel(item.getExternalDataset());
if (item.getData() != null) {
Map<String, Map<String, String>> data = (Map<String, Map<String, String>>) JSONValue.parse(item.getData());
Map<String, String> values = data.get("data");
externalDatasetListingModel.setInfo(values.get("info"));
externalDatasetListingModel.setType(Integer.parseInt(values.get("type")));
}
return externalDatasetListingModel;
}).collect(Collectors.toList()) : new ArrayList<>();
this.modified = entity.getModified();
return this;
}
@Override @Override
public Dataset toDataModel() throws Exception { public Dataset toDataModel() throws Exception {
eu.eudat.data.entities.Dataset entity = new eu.eudat.data.entities.Dataset(); eu.eudat.data.entities.Dataset entity = new eu.eudat.data.entities.Dataset();
@ -208,7 +245,7 @@ public class DatasetWizardModel implements DataModel<Dataset, DatasetWizardModel
entity.setCreated(this.created != null ? this.created : new Date()); entity.setCreated(this.created != null ? this.created : new Date());
entity.setModified(new Date()); entity.setModified(new Date());
DatasetProfile profile = new DatasetProfile(); DatasetProfile profile = new DatasetProfile();
profile.setId(this.profile); profile.setId(this.profile.getId());
entity.setProfile(profile); entity.setProfile(profile);
if (this.registries != null && !this.registries.isEmpty()) { if (this.registries != null && !this.registries.isEmpty()) {
entity.setRegistries(new HashSet<>()); entity.setRegistries(new HashSet<>());

View File

@ -3,6 +3,7 @@ package eu.eudat.models.data.dmp;
import eu.eudat.data.entities.*; import eu.eudat.data.entities.*;
import eu.eudat.logic.utilities.builders.XmlBuilder; import eu.eudat.logic.utilities.builders.XmlBuilder;
import eu.eudat.models.DataModel; import eu.eudat.models.DataModel;
import eu.eudat.models.data.datasetwizard.DatasetWizardModel;
import eu.eudat.models.data.dynamicfields.DynamicFieldWithValue; import eu.eudat.models.data.dynamicfields.DynamicFieldWithValue;
import eu.eudat.models.data.entities.xmlmodels.dmpprofiledefinition.DataManagementPlanProfile; import eu.eudat.models.data.entities.xmlmodels.dmpprofiledefinition.DataManagementPlanProfile;
import eu.eudat.models.data.funder.Funder; import eu.eudat.models.data.funder.Funder;
@ -26,7 +27,7 @@ public class DataManagementPlan implements DataModel<DMP, DataManagementPlan> {
private int status; private int status;
private boolean lockable; private boolean lockable;
private String description; private String description;
private List<DatasetListingModel> datasets; private List<DatasetWizardModel> datasets;
private List<AssociatedProfile> profiles; private List<AssociatedProfile> profiles;
private Grant grant; private Grant grant;
private List<Organisation> organisations; private List<Organisation> organisations;
@ -178,10 +179,11 @@ public class DataManagementPlan implements DataModel<DMP, DataManagementPlan> {
this.lockable = lockable; this.lockable = lockable;
} }
public List<DatasetListingModel> getDatasets() { public List<DatasetWizardModel> getDatasets() {
return datasets; return datasets;
} }
public void setDatasets(List<DatasetListingModel> datasets) {
public void setDatasets(List<DatasetWizardModel> datasets) {
this.datasets = datasets; this.datasets = datasets;
} }
@ -233,8 +235,8 @@ public class DataManagementPlan implements DataModel<DMP, DataManagementPlan> {
public DataManagementPlan fromDataModel(DMP entity) { public DataManagementPlan fromDataModel(DMP entity) {
this.id = entity.getId(); this.id = entity.getId();
this.profile = entity.getProfile() != null ? new Tuple<UUID, String>(entity.getProfile().getId(), entity.getProfile().getLabel()) : null; this.profile = entity.getProfile() != null ? new Tuple<UUID, String>(entity.getProfile().getId(), entity.getProfile().getLabel()) : null;
this.organisations = entity.getOrganisations().stream().map(item -> new Organisation().fromDataModel(item)).collect(Collectors.toList()); this.organisations = entity.getOrganisations() != null ? entity.getOrganisations().stream().map(item -> new Organisation().fromDataModel(item)).collect(Collectors.toList()) : new ArrayList<>();
this.researchers = entity.getResearchers().stream().map(item -> new Researcher().fromDataModel(item)).collect(Collectors.toList()); this.researchers = entity.getResearchers() != null ? entity.getResearchers().stream().map(item -> new Researcher().fromDataModel(item)).collect(Collectors.toList()): new ArrayList<>();
this.version = entity.getVersion(); this.version = entity.getVersion();
this.groupId = this.groupId == null ? null : entity.getGroupId(); this.groupId = this.groupId == null ? null : entity.getGroupId();
this.label = entity.getLabel(); this.label = entity.getLabel();
@ -243,7 +245,7 @@ public class DataManagementPlan implements DataModel<DMP, DataManagementPlan> {
this.grant.fromDataModel(entity.getGrant()); this.grant.fromDataModel(entity.getGrant());
this.creator = new eu.eudat.models.data.userinfo.UserInfo(); this.creator = new eu.eudat.models.data.userinfo.UserInfo();
this.groupId = entity.getGroupId(); this.groupId = entity.getGroupId();
this.lockable = entity.getDataset().stream().findAny().isPresent(); this.lockable = entity.getDataset() != null && entity.getDataset().stream().findAny().isPresent();
this.definition = entity.getProfile() == null ? null : new DataManagementPlanProfile().fromXml(XmlBuilder.fromXml(entity.getProfile().getDefinition()).getDocumentElement()); this.definition = entity.getProfile() == null ? null : new DataManagementPlanProfile().fromXml(XmlBuilder.fromXml(entity.getProfile().getDefinition()).getDocumentElement());
if (this.definition != null && this.definition.getFields() != null && !this.definition.getFields().isEmpty() && this.properties != null) { if (this.definition != null && this.definition.getFields() != null && !this.definition.getFields().isEmpty() && this.properties != null) {
this.definition.getFields().forEach(item -> { this.definition.getFields().forEach(item -> {
@ -251,7 +253,7 @@ public class DataManagementPlan implements DataModel<DMP, DataManagementPlan> {
if (fieldOptional.isPresent()) item.setValue(fieldOptional.get().get("value")); if (fieldOptional.isPresent()) item.setValue(fieldOptional.get().get("value"));
}); });
} }
if (entity.getUsers().stream().anyMatch(userDMP -> userDMP.getRole().equals(UserDMP.UserDMPRoles.OWNER.getValue()))) if (entity.getUsers() != null && entity.getUsers().stream().anyMatch(userDMP -> userDMP.getRole().equals(UserDMP.UserDMPRoles.OWNER.getValue())))
this.creator.fromDataModel(entity.getUsers().stream().filter(user -> user.getRole().equals(UserDMP.UserDMPRoles.OWNER.getValue())).findFirst().get().getUser()); this.creator.fromDataModel(entity.getUsers().stream().filter(user -> user.getRole().equals(UserDMP.UserDMPRoles.OWNER.getValue())).findFirst().get().getUser());
if (entity.getAssociatedDmps() != null && !entity.getAssociatedDmps().isEmpty()) { if (entity.getAssociatedDmps() != null && !entity.getAssociatedDmps().isEmpty()) {
@ -261,21 +263,23 @@ public class DataManagementPlan implements DataModel<DMP, DataManagementPlan> {
this.profiles.add(associatedProfile); this.profiles.add(associatedProfile);
} }
} }
if (entity.getDataset() != null) {
if (entity.isPublic()) { if (entity.isPublic()) {
this.datasets = entity.getDataset().stream() this.datasets = entity.getDataset().stream()
.filter(dataset -> !dataset.getStatus().equals(Dataset.Status.DELETED.getValue()) && !dataset.getStatus().equals(Dataset.Status.CANCELED.getValue()) && !dataset.getStatus().equals(Dataset.Status.SAVED.getValue())) .filter(dataset -> !dataset.getStatus().equals(Dataset.Status.DELETED.getValue()) && !dataset.getStatus().equals(Dataset.Status.CANCELED.getValue()) && !dataset.getStatus().equals(Dataset.Status.SAVED.getValue()))
.map(x-> new DatasetListingModel().fromDataModel(x)).collect(Collectors.toList()); .map(x -> new DatasetWizardModel().fromDataModelNoDmp(x)).collect(Collectors.toList());
} else { } else {
this.datasets = entity.getDataset().stream() this.datasets = entity.getDataset().stream()
.filter(dataset -> !dataset.getStatus().equals(Dataset.Status.DELETED.getValue()) && !dataset.getStatus().equals(Dataset.Status.CANCELED.getValue())) .filter(dataset -> !dataset.getStatus().equals(Dataset.Status.DELETED.getValue()) && !dataset.getStatus().equals(Dataset.Status.CANCELED.getValue()))
.map(x-> new DatasetListingModel().fromDataModel(x)).collect(Collectors.toList()); .map(x -> new DatasetWizardModel().fromDataModelNoDmp(x)).collect(Collectors.toList());
}
} }
this.modified = entity.getModified(); this.modified = entity.getModified();
this.created = entity.getCreated(); this.created = entity.getCreated();
this.description = entity.getDescription(); this.description = entity.getDescription();
this.status = entity.getStatus(); this.status = entity.getStatus();
this.associatedUsers = entity.getUsers().stream().map(item -> new UserListingModel().fromDataModel(item.getUser())).collect(Collectors.toList()); this.associatedUsers = entity.getUsers() != null ? entity.getUsers().stream().map(item -> new UserListingModel().fromDataModel(item.getUser())).collect(Collectors.toList()) : new ArrayList<>();
this.users = entity.getUsers().stream().map(item -> new UserInfoListingModel().fromDataModel(item)).collect(Collectors.toList()); this.users = entity.getUsers() != null ? entity.getUsers().stream().map(item -> new UserInfoListingModel().fromDataModel(item)).collect(Collectors.toList()) : new ArrayList<>();
this.doi = entity.getDoi(); this.doi = entity.getDoi();
if (entity.getProject() != null) { if (entity.getProject() != null) {

View File

@ -3,6 +3,7 @@ package eu.eudat.models.data.dmp;
import eu.eudat.data.entities.*; import eu.eudat.data.entities.*;
import eu.eudat.logic.utilities.builders.XmlBuilder; import eu.eudat.logic.utilities.builders.XmlBuilder;
import eu.eudat.models.DataModel; import eu.eudat.models.DataModel;
import eu.eudat.models.data.datasetwizard.DatasetWizardModel;
import eu.eudat.models.data.dynamicfields.DynamicFieldWithValue; import eu.eudat.models.data.dynamicfields.DynamicFieldWithValue;
import eu.eudat.models.data.entities.xmlmodels.dmpprofiledefinition.DataManagementPlanProfile; import eu.eudat.models.data.entities.xmlmodels.dmpprofiledefinition.DataManagementPlanProfile;
import eu.eudat.models.data.funder.FunderDMPEditorModel; import eu.eudat.models.data.funder.FunderDMPEditorModel;
@ -26,7 +27,7 @@ public class DataManagementPlanEditorModel implements DataModel<DMP, DataManagem
private int status; private int status;
private boolean lockable; private boolean lockable;
private String description; private String description;
private List<DatasetListingModel> datasets; private List<DatasetWizardModel> datasets;
private List<AssociatedProfile> profiles; private List<AssociatedProfile> profiles;
private eu.eudat.models.data.grant.GrantDMPEditorModel grant; private eu.eudat.models.data.grant.GrantDMPEditorModel grant;
private List<Organisation> organisations; private List<Organisation> organisations;
@ -177,10 +178,11 @@ public class DataManagementPlanEditorModel implements DataModel<DMP, DataManagem
this.lockable = lockable; this.lockable = lockable;
} }
public List<DatasetListingModel> getDatasets() { public List<DatasetWizardModel> getDatasets() {
return datasets; return datasets;
} }
public void setDatasets(List<DatasetListingModel> datasets) {
public void setDatasets(List<DatasetWizardModel> datasets) {
this.datasets = datasets; this.datasets = datasets;
} }
@ -253,7 +255,7 @@ public class DataManagementPlanEditorModel implements DataModel<DMP, DataManagem
this.profiles.add(associatedProfile); this.profiles.add(associatedProfile);
} }
} }
this.datasets = entity.getDataset().stream().map(item -> new DatasetListingModel().fromDataModel(item)).collect(Collectors.toList()); this.datasets = entity.getDataset().stream().map(item -> new DatasetWizardModel().fromDataModelNoDmp(item)).collect(Collectors.toList());
this.modified = entity.getModified(); this.modified = entity.getModified();
this.created = entity.getCreated(); this.created = entity.getCreated();
this.description = entity.getDescription(); this.description = entity.getDescription();

View File

@ -4,6 +4,7 @@ import eu.eudat.models.DataModel;
import eu.eudat.logic.utilities.helpers.LabelGenerator; import eu.eudat.logic.utilities.helpers.LabelGenerator;
import java.util.Date; import java.util.Date;
import java.util.UUID;
public class Organisation implements DataModel<eu.eudat.data.entities.Organisation, Organisation>, LabelGenerator { public class Organisation implements DataModel<eu.eudat.data.entities.Organisation, Organisation>, LabelGenerator {
private String label; private String label;
@ -85,6 +86,9 @@ public class Organisation implements DataModel<eu.eudat.data.entities.Organisati
organisationEntity.setReference(this.key + ":" + this.reference); organisationEntity.setReference(this.key + ":" + this.reference);
} }
} }
if (this.id != null) {
organisationEntity.setId(UUID.fromString(this.id));
}
organisationEntity.setLabel(this.name); organisationEntity.setLabel(this.name);
organisationEntity.setUri(this.label); organisationEntity.setUri(this.label);
organisationEntity.setCreated(new Date()); organisationEntity.setCreated(new Date());

View File

@ -6,14 +6,20 @@ import java.util.Map;
public class ResearchersExternalSourcesModel extends ExternalListingItem<ResearchersExternalSourcesModel> { public class ResearchersExternalSourcesModel extends ExternalListingItem<ResearchersExternalSourcesModel> {
@Override @Override
public ResearchersExternalSourcesModel fromExternalItem(List<Map<String, Object>> values) { public ResearchersExternalSourcesModel fromExternalItem(List<Map<String, String>> values) {
for (Map<String, Object> item : values) { for (Map<String, String> item : values) {
ExternalSourcesItemModel model = new ExternalSourcesItemModel(); ExternalSourcesItemModel model = new ExternalSourcesItemModel();
model.setRemoteId((String)item.get("pid")); model.setRemoteId(item.get("pid"));
model.setUri((String)item.get("uri")); model.setUri(item.get("uri"));
model.setName((String)item.get("name")); switch (item.get("tag")) {
model.setTag((String)item.get("tag")); case "ORCID":
model.setKey((String)item.get("key")); model.setName(item.get("name") + " (orcid:" + item.get("pid") + ")");
break;
default:
model.setName(item.get("name"));
}
model.setTag(item.get("tag"));
model.setKey(item.get("key"));
this.add(model); this.add(model);
} }
return this; return this;

View File

@ -9,6 +9,7 @@ import java.util.UUID;
public class Invitation { public class Invitation {
private UUID dataManagementPlan; private UUID dataManagementPlan;
private List<UserInfoInvitationModel> users; private List<UserInfoInvitationModel> users;
private Integer role;
public UUID getDataManagementPlan() { public UUID getDataManagementPlan() {
return dataManagementPlan; return dataManagementPlan;
@ -25,4 +26,12 @@ public class Invitation {
public void setUsers(List<UserInfoInvitationModel> users) { public void setUsers(List<UserInfoInvitationModel> users) {
this.users = users; this.users = users;
} }
public Integer getRole() {
return role;
}
public void setRole(Integer role) {
this.role = role;
}
} }

View File

@ -0,0 +1,18 @@
package eu.eudat.models.data.invitation;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Properties {
private Integer role;
@XmlElement(name = "role")
public Integer getRole() {
return role;
}
public void setRole(Integer role) {
this.role = role;
}
}

View File

@ -176,12 +176,15 @@ public class DataManagementPlanOverviewModel implements DataModel<DMP, DataManag
this.id = entity.getId().toString(); this.id = entity.getId().toString();
this.label = entity.getLabel(); this.label = entity.getLabel();
this.groupId = entity.getGroupId(); this.groupId = entity.getGroupId();
this.status = entity.getStatus();
if (entity.getResearchers() != null) {
this.researchers = entity.getResearchers().stream().map(item -> new Researcher().fromDataModel(item)).collect(Collectors.toList());
}
return this; return this;
} }
public DataManagementPlanOverviewModel fromDataModelDatasets(DMP entity) { public DataManagementPlanOverviewModel fromDataModelDatasets(DMP entity) {
this.fromDataModel(entity); this.fromDataModel(entity);
this.status = entity.getStatus();
this.version = entity.getVersion(); this.version = entity.getVersion();
this.grant = new GrantOverviewModel().fromDataModel(entity.getGrant()); this.grant = new GrantOverviewModel().fromDataModel(entity.getGrant());
if (entity.getProfile() != null) this.profile = entity.getProfile().getLabel(); if (entity.getProfile() != null) this.profile = entity.getProfile().getLabel();
@ -192,7 +195,9 @@ public class DataManagementPlanOverviewModel implements DataModel<DMP, DataManag
this.datasets = entity.getDataset().stream().filter(dataset -> !dataset.getStatus().equals(Dataset.Status.DELETED.getValue()) && !dataset.getStatus().equals(Dataset.Status.CANCELED.getValue())).map(x-> new DatasetOverviewModel().fromDataModel(x)).collect(Collectors.toList()); this.datasets = entity.getDataset().stream().filter(dataset -> !dataset.getStatus().equals(Dataset.Status.DELETED.getValue()) && !dataset.getStatus().equals(Dataset.Status.CANCELED.getValue())).map(x-> new DatasetOverviewModel().fromDataModel(x)).collect(Collectors.toList());
this.users = entity.getUsers().stream().map(x -> new UserInfoListingModel().fromDataModel(x)).collect(Collectors.toList()); this.users = entity.getUsers().stream().map(x -> new UserInfoListingModel().fromDataModel(x)).collect(Collectors.toList());
this.description = entity.getDescription(); this.description = entity.getDescription();
if (entity.getResearchers() != null) {
this.researchers = entity.getResearchers().stream().map(item -> new Researcher().fromDataModel(item)).collect(Collectors.toList()); this.researchers = entity.getResearchers().stream().map(item -> new Researcher().fromDataModel(item)).collect(Collectors.toList());
}
if (entity.getAssociatedDmps() != null && !entity.getAssociatedDmps().isEmpty()) { if (entity.getAssociatedDmps() != null && !entity.getAssociatedDmps().isEmpty()) {
this.associatedProfiles = new LinkedList<>(); this.associatedProfiles = new LinkedList<>();

View File

@ -5,8 +5,11 @@ import eu.eudat.models.DataModel;
import eu.eudat.models.data.dataset.DataRepository; import eu.eudat.models.data.dataset.DataRepository;
import eu.eudat.models.data.dataset.Service; import eu.eudat.models.data.dataset.Service;
import eu.eudat.logic.utilities.helpers.LabelBuilder; import eu.eudat.logic.utilities.helpers.LabelBuilder;
import eu.eudat.models.data.datasetprofile.DatasetProfileOverviewModel;
import java.util.ArrayList;
import java.util.Date; import java.util.Date;
import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@ -16,7 +19,7 @@ public class DatasetListingModel implements DataModel<Dataset, DatasetListingMod
private String grant; private String grant;
private String dmp; private String dmp;
private String dmpId; private String dmpId;
private String profile; private DatasetProfileOverviewModel profile;
private String dataRepositories; private String dataRepositories;
private String registries; private String registries;
private String services; private String services;
@ -29,6 +32,9 @@ public class DatasetListingModel implements DataModel<Dataset, DatasetListingMod
private Date finalizedAt; private Date finalizedAt;
private Date dmpPublishedAt; private Date dmpPublishedAt;
private int version; private int version;
private List<UserInfoListingModel> users;
private Boolean isPublic;
private Boolean isProfileLatestVersion;
public String getId() { public String getId() {
return id; return id;
@ -65,10 +71,11 @@ public class DatasetListingModel implements DataModel<Dataset, DatasetListingMod
this.dmpId = dmpId; this.dmpId = dmpId;
} }
public String getProfile() { public DatasetProfileOverviewModel getProfile() {
return profile; return profile;
} }
public void setProfile(String profile) {
public void setProfile(DatasetProfileOverviewModel profile) {
this.profile = profile; this.profile = profile;
} }
@ -156,6 +163,30 @@ public class DatasetListingModel implements DataModel<Dataset, DatasetListingMod
this.version = version; this.version = version;
} }
public List<UserInfoListingModel> getUsers() {
return users;
}
public void setUsers(List<UserInfoListingModel> users) {
this.users = users;
}
public Boolean getPublic() {
return isPublic;
}
public void setPublic(Boolean aPublic) {
isPublic = aPublic;
}
public Boolean getProfileLatestVersion() {
return isProfileLatestVersion;
}
public void setProfileLatestVersion(Boolean profileLatestVersion) {
isProfileLatestVersion = profileLatestVersion;
}
@Override @Override
public DatasetListingModel fromDataModel(Dataset entity) { public DatasetListingModel fromDataModel(Dataset entity) {
this.id = entity.getId() != null ? entity.getId().toString() : ""; this.id = entity.getId() != null ? entity.getId().toString() : "";
@ -165,7 +196,7 @@ public class DatasetListingModel implements DataModel<Dataset, DatasetListingMod
this.grant = entity.getDmp() != null ? entity.getDmp().getGrant().getLabel() : ""; this.grant = entity.getDmp() != null ? entity.getDmp().getGrant().getLabel() : "";
this.dmp = entity.getDmp() != null ? entity.getDmp().getLabel() : ""; this.dmp = entity.getDmp() != null ? entity.getDmp().getLabel() : "";
this.dmpId = entity.getDmp() != null ? entity.getDmp().getId().toString() : ""; this.dmpId = entity.getDmp() != null ? entity.getDmp().getId().toString() : "";
this.profile = entity.getProfile() != null ? entity.getProfile().getLabel() : ""; this.profile = entity.getProfile() != null ? new DatasetProfileOverviewModel().fromDataModel(entity.getProfile()) : null;
this.description = entity.getDescription(); this.description = entity.getDescription();
this.status = entity.getStatus(); this.status = entity.getStatus();
this.grantAbbreviation = entity.getDmp() != null ? entity.getDmp().getGrant().getAbbreviation() : ""; this.grantAbbreviation = entity.getDmp() != null ? entity.getDmp().getGrant().getAbbreviation() : "";
@ -173,9 +204,15 @@ public class DatasetListingModel implements DataModel<Dataset, DatasetListingMod
this.registries = LabelBuilder.getLabel(entity.getRegistries().stream().map(item -> new eu.eudat.models.data.dataset.Registry().fromDataModel(item)).collect(Collectors.toList())); this.registries = LabelBuilder.getLabel(entity.getRegistries().stream().map(item -> new eu.eudat.models.data.dataset.Registry().fromDataModel(item)).collect(Collectors.toList()));
this.dataRepositories = LabelBuilder.getLabel(entity.getDatasetDataRepositories().stream().map(item -> new DataRepository().fromDataModel(item.getDataRepository())).collect(Collectors.toList())); this.dataRepositories = LabelBuilder.getLabel(entity.getDatasetDataRepositories().stream().map(item -> new DataRepository().fromDataModel(item.getDataRepository())).collect(Collectors.toList()));
this.services = LabelBuilder.getLabel(entity.getServices().stream().map(item -> new Service().fromDataModel(item.getService())).collect(Collectors.toList())); this.services = LabelBuilder.getLabel(entity.getServices().stream().map(item -> new Service().fromDataModel(item.getService())).collect(Collectors.toList()));
if (entity.getFinalizedAt() == null && entity.getStatus() == Dataset.Status.FINALISED.getValue()) {
this.finalizedAt = entity.getDmp().getFinalizedAt();
} else {
this.finalizedAt = entity.getFinalizedAt(); this.finalizedAt = entity.getFinalizedAt();
}
this.dmpPublishedAt = entity.getDmp().getPublishedAt(); this.dmpPublishedAt = entity.getDmp().getPublishedAt();
this.version = entity.getDmp().getVersion(); this.version = entity.getDmp().getVersion();
this.users = entity.getDmp() != null ? entity.getDmp().getUsers().stream().map(x -> new UserInfoListingModel().fromDataModel(x)).collect(Collectors.toList()) : new ArrayList<>();
this.isPublic = entity.getDmp() != null ? entity.getDmp().isPublic() : false;
return this; return this;
} }

View File

@ -0,0 +1,53 @@
package eu.eudat.models.data.listingmodels;
import eu.eudat.data.entities.DMP;
import eu.eudat.models.DataModel;
public class VersionListingModel implements DataModel<DMP, VersionListingModel> {
private String id;
private String groupId;
private Integer version;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getGroupId() {
return groupId;
}
public void setGroupId(String groupId) {
this.groupId = groupId;
}
public Integer getVersion() {
return version;
}
public void setVersion(Integer version) {
this.version = version;
}
@Override
public VersionListingModel fromDataModel(DMP entity) {
this.id = entity.getId().toString();
this.groupId = entity.getGroupId().toString();
this.version = entity.getVersion();
return this;
}
@Override
public DMP toDataModel() throws Exception {
return null;
}
@Override
public String getHint() {
return "versionListingModel";
}
}

View File

@ -0,0 +1,131 @@
package eu.eudat.models.data.principal;
import eu.eudat.models.data.security.Principal;
import eu.eudat.types.Authorities;
import java.util.Date;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;
public class PrincipalModel {
private UUID id;
private UUID token;
private String name;
private String email;
private Date expiresAt;
private String avatarUrl;
private Set<Authorities> authorities;
private String culture;
private String language;
private String timezone;
private String zenodoEmail;
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public UUID getToken() {
return token;
}
public void setToken(UUID token) {
this.token = token;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Date getExpiresAt() {
return expiresAt;
}
public void setExpiresAt(Date expiresAt) {
this.expiresAt = expiresAt;
}
public String getAvatarUrl() {
return avatarUrl;
}
public void setAvatarUrl(String avatarUrl) {
this.avatarUrl = avatarUrl;
}
public Set<Authorities> getAuthz() {
return authorities;
}
public Set<Integer> getAuthorities() {
return authorities.stream().map(authz -> authz.getValue()).collect(Collectors.toSet());
}
public void setAuthorities(Set<Authorities> authorities) {
this.authorities = authorities;
}
public String getCulture() {
return culture;
}
public void setCulture(String culture) {
this.culture = culture;
}
public String getLanguage() {
return language;
}
public void setLanguage(String language) {
this.language = language;
}
public String getTimezone() {
return timezone;
}
public void setTimezone(String timezone) {
this.timezone = timezone;
}
public String getZenodoEmail() {
return zenodoEmail;
}
public void setZenodoEmail(String zenodoEmail) {
this.zenodoEmail = zenodoEmail;
}
public static PrincipalModel fromEntity(Principal principal) {
PrincipalModel model = new PrincipalModel();
model.setId(principal.getId());
model.setToken(principal.getToken());
model.setAuthorities(principal.getAuthz());
model.setAvatarUrl(principal.getAvatarUrl());
model.setCulture(principal.getCulture());
model.setEmail(principal.getEmail());
model.setExpiresAt(principal.getExpiresAt());
model.setLanguage(principal.getLanguage());
model.setName(principal.getName());
model.setTimezone(principal.getTimezone());
model.setZenodoEmail(principal.getZenodoEmail());
return model;
}
}

View File

@ -1,6 +1,8 @@
package eu.eudat.models.data.quickwizard; package eu.eudat.models.data.quickwizard;
import eu.eudat.data.entities.DatasetProfile;
import eu.eudat.models.data.datasetprofile.DatasetProfileOverviewModel;
import eu.eudat.models.data.dmp.DataManagementPlan; import eu.eudat.models.data.dmp.DataManagementPlan;
import eu.eudat.data.entities.Dataset; import eu.eudat.data.entities.Dataset;
import eu.eudat.models.data.datasetwizard.DatasetWizardModel; import eu.eudat.models.data.datasetwizard.DatasetWizardModel;
@ -22,11 +24,11 @@ public class DatasetDescriptionQuickWizardModel extends PagedDatasetProfile {
} }
public DatasetWizardModel toDataModel(DataManagementPlan dmp,UUID profile){ public DatasetWizardModel toDataModel(DataManagementPlan dmp, DatasetProfile profile){
DatasetWizardModel newDataset = new DatasetWizardModel(); DatasetWizardModel newDataset = new DatasetWizardModel();
newDataset.setLabel(datasetLabel); newDataset.setLabel(datasetLabel);
newDataset.setCreated(new Date()); newDataset.setCreated(new Date());
newDataset.setProfile(profile); newDataset.setProfile(new DatasetProfileOverviewModel().fromDataModel(profile));
newDataset.setDmp(dmp); newDataset.setDmp(dmp);
newDataset.setStatus((short) this.getStatus()); newDataset.setStatus((short) this.getStatus());
//newDataset.setStatus(Dataset.Status.SAVED.getValue()); //newDataset.setStatus(Dataset.Status.SAVED.getValue());

View File

@ -101,6 +101,8 @@ public class DmpQuickWizardModel {
dataManagementPlanEntity.setAssociatedUsers(user); dataManagementPlanEntity.setAssociatedUsers(user);
dataManagementPlanEntity.setExtraProperties(new HashMap<>()); dataManagementPlanEntity.setExtraProperties(new HashMap<>());
dataManagementPlanEntity.getExtraProperties().put("language", this.language); dataManagementPlanEntity.getExtraProperties().put("language", this.language);
dataManagementPlanEntity.getExtraProperties().put("visible", false);
dataManagementPlanEntity.getExtraProperties().put("contact", principal.getId().toString());
return dataManagementPlanEntity; return dataManagementPlanEntity;
} }

View File

@ -12,6 +12,7 @@ public class Principal {
private UUID id; private UUID id;
private UUID token; private UUID token;
private String name; private String name;
private String email;
private Date expiresAt; private Date expiresAt;
private String avatarUrl; private String avatarUrl;
private Set<Authorities> authorities; private Set<Authorities> authorities;
@ -47,6 +48,14 @@ public class Principal {
this.name = name; this.name = name;
} }
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Date getExpiresAt() { public Date getExpiresAt() {
return expiresAt; return expiresAt;
} }

View File

@ -22,7 +22,7 @@ public class UserInfo implements DataModel<eu.eudat.data.entities.UserInfo, User
private Date lastloggedin = null; private Date lastloggedin = null;
private String additionalinfo; // private String additionalinfo;
public UUID getId() { public UUID getId() {
return id; return id;
@ -88,13 +88,13 @@ public class UserInfo implements DataModel<eu.eudat.data.entities.UserInfo, User
this.lastloggedin = lastloggedin; this.lastloggedin = lastloggedin;
} }
public String getAdditionalinfo() { /*public String getAdditionalinfo() {
return additionalinfo; return additionalinfo;
} }
public void setAdditionalinfo(String additionalinfo) { public void setAdditionalinfo(String additionalinfo) {
this.additionalinfo = additionalinfo; this.additionalinfo = additionalinfo;
} }*/
@Override @Override
public UserInfo fromDataModel(eu.eudat.data.entities.UserInfo entity) { public UserInfo fromDataModel(eu.eudat.data.entities.UserInfo entity) {
@ -111,7 +111,7 @@ public class UserInfo implements DataModel<eu.eudat.data.entities.UserInfo, User
entity.setId(this.getId()); entity.setId(this.getId());
entity.setEmail(this.getEmail()); entity.setEmail(this.getEmail());
entity.setName(this.getName()); entity.setName(this.getName());
entity.setAdditionalinfo(this.getAdditionalinfo()); //entity.setAdditionalinfo(this.getAdditionalinfo());
entity.setAuthorization_level(this.getAuthorization_level()); entity.setAuthorization_level(this.getAuthorization_level());
entity.setCreated(this.getCreated()); entity.setCreated(this.getCreated());
entity.setLastloggedin(this.getLastloggedin()); entity.setLastloggedin(this.getLastloggedin());

View File

@ -17,7 +17,7 @@ public class UserListingModel implements DataModel<eu.eudat.data.entities.UserIn
private String name; private String name;
private Date created; private Date created;
private Date lastloggedin; private Date lastloggedin;
private String additionalinfo; //private String additionalinfo;
private List<Integer> appRoles; private List<Integer> appRoles;
public UUID getId() { public UUID getId() {
@ -69,12 +69,12 @@ public class UserListingModel implements DataModel<eu.eudat.data.entities.UserIn
this.lastloggedin = lastloggedin; this.lastloggedin = lastloggedin;
} }
public String getAdditionalinfo() { /*public String getAdditionalinfo() {
return additionalinfo; return additionalinfo;
} }
public void setAdditionalinfo(String additionalinfo) { public void setAdditionalinfo(String additionalinfo) {
this.additionalinfo = additionalinfo; this.additionalinfo = additionalinfo;
} }*/
public List<Integer> getAppRoles() { public List<Integer> getAppRoles() {
return appRoles; return appRoles;
@ -92,7 +92,7 @@ public class UserListingModel implements DataModel<eu.eudat.data.entities.UserIn
this.name = entity.getName(); this.name = entity.getName();
this.created = entity.getCreated(); this.created = entity.getCreated();
this.lastloggedin = entity.getLastloggedin(); this.lastloggedin = entity.getLastloggedin();
this.additionalinfo = entity.getAdditionalinfo(); // this.additionalinfo = entity.getAdditionalinfo();
this.appRoles = entity.getUserRoles().stream().map(item -> item.getRole()).collect(Collectors.toList()); this.appRoles = entity.getUserRoles().stream().map(item -> item.getRole()).collect(Collectors.toList());
return this; return this;
} }
@ -107,7 +107,7 @@ public class UserListingModel implements DataModel<eu.eudat.data.entities.UserIn
userInfo.setName(this.name); userInfo.setName(this.name);
userInfo.setCreated(this.created); userInfo.setCreated(this.created);
userInfo.setLastloggedin(this.lastloggedin); userInfo.setLastloggedin(this.lastloggedin);
userInfo.setAdditionalinfo(this.additionalinfo); // userInfo.setAdditionalinfo(this.additionalinfo);
return userInfo; return userInfo;
} }

View File

@ -1,27 +1,37 @@
package eu.eudat.models.data.userinfo; package eu.eudat.models.data.userinfo;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.ObjectMapper;
import eu.eudat.data.entities.*; import eu.eudat.data.entities.*;
import eu.eudat.data.entities.UserInfo; import eu.eudat.data.entities.UserInfo;
import eu.eudat.models.DataModel; import eu.eudat.models.DataModel;
import eu.eudat.models.data.dmp.DataManagementPlan; import eu.eudat.models.data.dmp.DataManagementPlan;
import net.minidev.json.parser.JSONParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Date; import java.io.IOException;
import java.util.List; import java.util.*;
import java.util.UUID;
import java.util.stream.Collectors; import java.util.stream.Collectors;
/** /**
* Created by ikalyvas on 8/24/2018. * Created by ikalyvas on 8/24/2018.
*/ */
public class UserProfile implements DataModel<eu.eudat.data.entities.UserInfo, UserProfile> { public class UserProfile implements DataModel<eu.eudat.data.entities.UserInfo, UserProfile> {
private static final Logger logger = LoggerFactory.getLogger(UserProfile.class);
private UUID id; private UUID id;
private String email; private String email;
private Short usertype; private Short usertype;
private String name; private String name;
private Date lastloggedin; private Date lastloggedin;
private String additionalinfo; //private String additionalinfo;
private List<DataManagementPlan> associatedDmps; private List<DataManagementPlan> associatedDmps;
private String zenodoEmail;
private Map<String, Object> language;
private String timezone;
private Map<String, Object> culture;
private String avatarUrl;
public UUID getId() { public UUID getId() {
return id; return id;
@ -63,13 +73,13 @@ public class UserProfile implements DataModel<eu.eudat.data.entities.UserInfo, U
this.lastloggedin = lastloggedin; this.lastloggedin = lastloggedin;
} }
public String getAdditionalinfo() { /*public String getAdditionalinfo() {
return additionalinfo; return additionalinfo;
} }
public void setAdditionalinfo(String additionalinfo) { public void setAdditionalinfo(String additionalinfo) {
this.additionalinfo = additionalinfo; this.additionalinfo = additionalinfo;
} }*/
public List<DataManagementPlan> getAssociatedDmps() { public List<DataManagementPlan> getAssociatedDmps() {
return associatedDmps; return associatedDmps;
@ -79,6 +89,46 @@ public class UserProfile implements DataModel<eu.eudat.data.entities.UserInfo, U
this.associatedDmps = associatedDmps; this.associatedDmps = associatedDmps;
} }
public String getZenodoEmail() {
return zenodoEmail;
}
public void setZenodoEmail(String zenodoEmail) {
this.zenodoEmail = zenodoEmail;
}
public Map<String, Object> getLanguage() {
return language;
}
public void setLanguage(Map<String, Object> language) {
this.language = language;
}
public String getTimezone() {
return timezone;
}
public void setTimezone(String timezone) {
this.timezone = timezone;
}
public Map<String, Object> getCulture() {
return culture;
}
public void setCulture(Map<String, Object> culture) {
this.culture = culture;
}
public String getAvatarUrl() {
return avatarUrl;
}
public void setAvatarUrl(String avatarUrl) {
this.avatarUrl = avatarUrl;
}
@Override @Override
public UserProfile fromDataModel(UserInfo entity) { public UserProfile fromDataModel(UserInfo entity) {
this.id = entity.getId(); this.id = entity.getId();
@ -86,7 +136,17 @@ public class UserProfile implements DataModel<eu.eudat.data.entities.UserInfo, U
this.usertype = entity.getUsertype(); this.usertype = entity.getUsertype();
this.name = entity.getName(); this.name = entity.getName();
this.lastloggedin = entity.getLastloggedin(); this.lastloggedin = entity.getLastloggedin();
this.additionalinfo = entity.getAdditionalinfo(); //this.additionalinfo = entity.getAdditionalinfo();
try {
Map<String, Object> additionalInfo = new ObjectMapper().readValue(entity.getAdditionalinfo(), HashMap.class);
this.language = (Map)additionalInfo.get("language");
this.culture = (Map) additionalInfo.get("culture");
this.timezone = (String) additionalInfo.get("timezone");
this.zenodoEmail = (String) additionalInfo.get("zenodoEmail");
this.avatarUrl = (String) additionalInfo.get("avatarUrl");
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
return this; return this;
} }

View File

@ -53,6 +53,14 @@ public class DatasetId implements Serializable
private Map<String, Object> additionalProperties = new HashMap<String, Object>(); private Map<String, Object> additionalProperties = new HashMap<String, Object>();
private final static long serialVersionUID = -6295164005851378031L; private final static long serialVersionUID = -6295164005851378031L;
public DatasetId() {
}
public DatasetId(String identifier, Type type) {
this.identifier = identifier;
this.type = type;
}
/** /**
* The Dataset Identifier Schema * The Dataset Identifier Schema
* <p> * <p>

View File

@ -52,6 +52,7 @@ public class DatasetIdRDAMapper {
} }
private static void finalRDAMap(DatasetId rda, String property, String value) { private static void finalRDAMap(DatasetId rda, String property, String value) {
if (value != null) {
for (DatasetIdProperties datasetIdProperties : DatasetIdProperties.values()) { for (DatasetIdProperties datasetIdProperties : DatasetIdProperties.values()) {
if (property.contains(datasetIdProperties.getName())) { if (property.contains(datasetIdProperties.getName())) {
switch (datasetIdProperties) { switch (datasetIdProperties) {
@ -64,6 +65,7 @@ public class DatasetIdRDAMapper {
} }
} }
} }
}
} }

View File

@ -7,9 +7,11 @@ import eu.eudat.elastic.entities.Tag;
import eu.eudat.logic.managers.DatasetManager; import eu.eudat.logic.managers.DatasetManager;
import eu.eudat.logic.services.ApiContext; import eu.eudat.logic.services.ApiContext;
import eu.eudat.logic.utilities.json.JsonSearcher; import eu.eudat.logic.utilities.json.JsonSearcher;
import eu.eudat.models.data.datasetprofile.DatasetProfileOverviewModel;
import eu.eudat.models.data.datasetwizard.DatasetWizardModel; import eu.eudat.models.data.datasetwizard.DatasetWizardModel;
import eu.eudat.models.rda.Contributor; import eu.eudat.models.rda.Contributor;
import eu.eudat.models.rda.Dataset; import eu.eudat.models.rda.Dataset;
import eu.eudat.models.rda.DatasetId;
import eu.eudat.models.rda.Language; import eu.eudat.models.rda.Language;
import org.json.JSONObject; import org.json.JSONObject;
import org.slf4j.Logger; import org.slf4j.Logger;
@ -55,11 +57,14 @@ public class DatasetRDAMapper {
if (!idNodes.isEmpty()) { if (!idNodes.isEmpty()) {
rda.setDatasetId(DatasetIdRDAMapper.toRDA(idNodes)); rda.setDatasetId(DatasetIdRDAMapper.toRDA(idNodes));
} }
if (rda.getDatasetId() == null) {
rda.setDatasetId(new DatasetId(dataset.getId().toString(), DatasetId.Type.OTHER));
}
List<JsonNode> typeNodes = JsonSearcher.findNodes(datasetDescriptionObj, "rdaProperty", "dataset.type"); List<JsonNode> typeNodes = JsonSearcher.findNodes(datasetDescriptionObj, "rdaProperty", "dataset.type");
if (!typeNodes.isEmpty()) { if (!typeNodes.isEmpty()) {
rda.setType(typeNodes.get(0).get("value").asText()); rda.setType(typeNodes.get(0).get("value").asText());
} else { } else {
rda.setType(dataset.getLabel()); rda.setType("DMP Dataset");
} }
List<JsonNode> languageNodes = JsonSearcher.findNodes(datasetDescriptionObj, "rdaProperty", "dataset.language"); List<JsonNode> languageNodes = JsonSearcher.findNodes(datasetDescriptionObj, "rdaProperty", "dataset.language");
if (!languageNodes.isEmpty()) { if (!languageNodes.isEmpty()) {
@ -92,9 +97,9 @@ public class DatasetRDAMapper {
rda.setKeyword(keywordNodes.stream().map(keywordNode -> { rda.setKeyword(keywordNodes.stream().map(keywordNode -> {
JsonNode value = keywordNode.get("value"); JsonNode value = keywordNode.get("value");
if (value.isArray()) { if (value.isArray()) {
return StreamSupport.stream(value.spliterator(), false).map(node -> KeywordRDAMapper.toRDA(node.asText())).collect(Collectors.toList()); return StreamSupport.stream(value.spliterator(), false).map(node -> KeywordRDAMapper.toRDA(node.asText())).flatMap(Collection::stream).collect(Collectors.toList());
} else { } else {
return Collections.singletonList(KeywordRDAMapper.toRDA(keywordNode.get("value").asText())); return KeywordRDAMapper.toRDA(keywordNode.get("value").asText());
} }
}).flatMap(Collection::stream).collect(Collectors.toList())); }).flatMap(Collection::stream).collect(Collectors.toList()));
for (int i = 0; i < keywordNodes.size(); i++) { for (int i = 0; i < keywordNodes.size(); i++) {
@ -117,6 +122,8 @@ public class DatasetRDAMapper {
List<JsonNode> sensitiveDataNodes = JsonSearcher.findNodes(datasetDescriptionObj, "rdaProperty", "dataset.sensitive_data"); List<JsonNode> sensitiveDataNodes = JsonSearcher.findNodes(datasetDescriptionObj, "rdaProperty", "dataset.sensitive_data");
if (!sensitiveDataNodes.isEmpty()) { if (!sensitiveDataNodes.isEmpty()) {
rda.setSensitiveData(sensitiveDataNodes.stream().map(sensitiveDataNode -> Dataset.SensitiveData.fromValue(sensitiveDataNode.get("value").asText())).findFirst().get()); rda.setSensitiveData(sensitiveDataNodes.stream().map(sensitiveDataNode -> Dataset.SensitiveData.fromValue(sensitiveDataNode.get("value").asText())).findFirst().get());
} else {
rda.setSensitiveData(Dataset.SensitiveData.UNKNOWN);
} }
List<JsonNode> technicalResourceNodes = JsonSearcher.findNodes(datasetDescriptionObj, "rdaProperty", "dataset.technical_resource"); List<JsonNode> technicalResourceNodes = JsonSearcher.findNodes(datasetDescriptionObj, "rdaProperty", "dataset.technical_resource");
if (!technicalResourceNodes.isEmpty()) { if (!technicalResourceNodes.isEmpty()) {
@ -170,7 +177,7 @@ public class DatasetRDAMapper {
try { try {
Map<String, Object> properties = new HashMap<>(); Map<String, Object> properties = new HashMap<>();
DatasetWizardModel datasetWizardModel = new DatasetWizardModel(); DatasetWizardModel datasetWizardModel = new DatasetWizardModel();
datasetWizardModel.setProfile(entity.getProfile().getId()); datasetWizardModel.setProfile(new DatasetProfileOverviewModel().fromDataModel(entity.getProfile()));
datasetWizardModel.setDatasetProfileDefinition(datasetManager.getPagedProfile(datasetWizardModel, entity)); datasetWizardModel.setDatasetProfileDefinition(datasetManager.getPagedProfile(datasetWizardModel, entity));
ObjectMapper mapper = new ObjectMapper(); ObjectMapper mapper = new ObjectMapper();
String datasetDescriptionJson = mapper.writeValueAsString(datasetWizardModel.getDatasetProfileDefinition()); String datasetDescriptionJson = mapper.writeValueAsString(datasetWizardModel.getDatasetProfileDefinition());

View File

@ -31,6 +31,18 @@ public class DmpRDAMapper {
@Transactional @Transactional
public Dmp toRDA(DMP dmp) { public Dmp toRDA(DMP dmp) {
Map<String, Object> extraProperties;
if (dmp.getExtraProperties() == null) {
throw new IllegalArgumentException("DMP is missing required Data for RDA export");
} else {
extraProperties = new org.json.JSONObject(dmp.getExtraProperties()).toMap();
if (extraProperties.get("language") == null) {
throw new IllegalArgumentException("DMP must have it's language property defined");
}
if (extraProperties.get("contact") == null) {
throw new IllegalArgumentException("DMP must have it's contact property defined");
}
}
Dmp rda = new Dmp(); Dmp rda = new Dmp();
if (dmp.getDoi() != null && !dmp.getDoi().isEmpty()) { if (dmp.getDoi() != null && !dmp.getDoi().isEmpty()) {
rda.setDmpId(DmpIdRDAMapper.toRDA(dmp.getDoi())); rda.setDmpId(DmpIdRDAMapper.toRDA(dmp.getDoi()));
@ -42,11 +54,13 @@ public class DmpRDAMapper {
rda.setModified(dmp.getModified()); rda.setModified(dmp.getModified());
rda.setTitle(dmp.getLabel()); rda.setTitle(dmp.getLabel());
Map<String, Object> extraProperties = new org.json.JSONObject(dmp.getExtraProperties()).toMap();
if (!extraProperties.isEmpty()) { if (!extraProperties.isEmpty()) {
if (extraProperties.get("language") != null) { if (extraProperties.get("ethicalIssues") != null) {
rda.setLanguage(LanguageRDAMapper.mapLanguageIsoToRDAIso(extraProperties.get("language").toString())); rda.setEthicalIssuesExist(Dmp.EthicalIssuesExist.fromValue(extraProperties.get("ethicalIsses").toString()));
} else {
rda.setEthicalIssuesExist(Dmp.EthicalIssuesExist.UNKNOWN);
} }
rda.setLanguage(LanguageRDAMapper.mapLanguageIsoToRDAIso(extraProperties.get("language").toString()));
if (extraProperties.get("costs") != null) { if (extraProperties.get("costs") != null) {
rda.setCost(new ArrayList<>()); rda.setCost(new ArrayList<>());
((List) extraProperties.get("costs")).forEach(costl -> { ((List) extraProperties.get("costs")).forEach(costl -> {
@ -59,11 +73,9 @@ public class DmpRDAMapper {
rda.getCost().add(cost); rda.getCost().add(cost);
}); });
} }
if (extraProperties.get("contact") != null) { UserInfo contact = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(UUID.fromString((String) extraProperties.get("contact")));
UserInfo contact = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(UUID.fromString((String)extraProperties.get("contact")));
rda.setContact(ContactRDAMapper.toRDA(contact)); rda.setContact(ContactRDAMapper.toRDA(contact));
} }
}
/*UserInfo creator; /*UserInfo creator;
if (dmp.getCreator() != null) { if (dmp.getCreator() != null) {
@ -101,7 +113,7 @@ public class DmpRDAMapper {
entity.getAssociatedDmps().add(exProfile); entity.getAssociatedDmps().add(exProfile);
} }
} }
if (rda.getContributor() != null && !rda.getContributor().isEmpty()) { if (rda.getContributor() != null && !rda.getContributor().isEmpty() && rda.getContributor().get(0).getContributorId() != null) {
entity.setResearchers(rda.getContributor().stream().map(ContributorRDAMapper::toEntity).filter(StreamDistinctBy.distinctByKey(Researcher::getReference)).collect(Collectors.toSet())); entity.setResearchers(rda.getContributor().stream().map(ContributorRDAMapper::toEntity).filter(StreamDistinctBy.distinctByKey(Researcher::getReference)).collect(Collectors.toSet()));
} }
entity.setCreated(rda.getCreated()); entity.setCreated(rda.getCreated());

View File

@ -1,25 +1,29 @@
package eu.eudat.models.rda.mapper; package eu.eudat.models.rda.mapper;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import eu.eudat.elastic.entities.Tag;
import eu.eudat.logic.utilities.json.JavaToJson;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.io.IOException; import java.io.IOException;
import java.util.HashMap; import java.util.*;
import java.util.Map; import java.util.stream.Collectors;
public class KeywordRDAMapper { public class KeywordRDAMapper {
private static final Logger logger = LoggerFactory.getLogger(KeywordRDAMapper.class); private static final Logger logger = LoggerFactory.getLogger(KeywordRDAMapper.class);
public static String toRDA(String value) { public static List<String> toRDA(String value) {
ObjectMapper mapper = new ObjectMapper(); ObjectMapper mapper = new ObjectMapper();
try { try {
Map<String, Object> map = mapper.readValue(value, HashMap.class); value = JavaToJson.objectStringToJson(value);
return (String) map.get("name"); List<Tag> tags = Arrays.asList(mapper.readValue(value, Tag[].class));
List<String> keywordNames = tags.stream().map(Tag::getName).collect(Collectors.toList());
return keywordNames;
} catch (IOException e) { } catch (IOException e) {
logger.error(e.getMessage(), e); logger.error(e.getMessage(), e);
} }
return value; return new ArrayList<>();
} }
} }

View File

@ -18,7 +18,7 @@ http-logger.server-address = http://localhost:31311
pdf.converter.url=http://localhost:88/ pdf.converter.url=http://localhost:88/
####################CONFIGURATION FILES OVERRIDES CONFIGURATIONS########## ####################CONFIGURATION FILES OVERRIDES CONFIGURATIONS##########
configuration.externalUrls=ExternalUrls.xml configuration.externalUrls=externalUrls/ExternalUrls.xml
configuration.rda=RDACommonStandards.txt configuration.rda=RDACommonStandards.txt
configuration.h2020template=documents/h2020.docx configuration.h2020template=documents/h2020.docx
configuration.configurable_login_providers=configurableLoginProviders.json configuration.configurable_login_providers=configurableLoginProviders.json

View File

@ -20,10 +20,10 @@ spring.mail.properties.mail.smtp.auth=false
spring.mail.properties.mail.smtp.starttls.enable=false spring.mail.properties.mail.smtp.starttls.enable=false
####################CONFIGURATION FILES OVERRIDES CONFIGURATIONS########## ####################CONFIGURATION FILES OVERRIDES CONFIGURATIONS##########
configuration.externalUrls= configuration.externalUrls=externalUrls/ExternalUrls.xml
configuration.rda= configuration.rda=RDACommonStandards.txt
configuration.h2020template= configuration.h2020template=documents/h2020.docx
configuration.configurable_login_providers= configuration.configurable_login_providers=ConfigurableLoginProviders.json
#############LOGIN CONFIGURATIONS######### #############LOGIN CONFIGURATIONS#########
#############GENERIC LOGIN CONFIGURATIONS######### #############GENERIC LOGIN CONFIGURATIONS#########

View File

@ -149,8 +149,8 @@
<key>openaire</key> <key>openaire</key>
<label>OpenAIRE</label> <label>OpenAIRE</label>
<ordinal>1</ordinal> <ordinal>1</ordinal>
<url>https://services.openaire.eu/search/v2/api/resources?query=((oaftype%20exact%20project)%20and%20((projectcode_nt%20exact%20%22{like}%22)or({like}))){funderQuery}&amp;page={page}&amp;size={pageSize}&amp;format=json</url> <url>https://services.openaire.eu/search/v2/api/resources?query=((oaftype exact project) and ((projectcode_nt exact "{like}")or({like}))){funderQuery}&amp;page={page}&amp;size={pageSize}&amp;format=json</url>
<funderQuery>&amp;fq=(funder%20exact%20%22{funderId}%22)</funderQuery> <funderQuery>&amp;fq=(funder exact "{funderId}")</funderQuery>
<firstPage>0</firstPage> <firstPage>0</firstPage>
<contenttype>application/json; charset=utf-8</contenttype> <contenttype>application/json; charset=utf-8</contenttype>
<data> <data>
@ -228,7 +228,7 @@
<label>OpenAIRE</label> <label>OpenAIRE</label>
<ordinal>1</ordinal> <ordinal>1</ordinal>
<type>External</type> <type>External</type>
<url>https://services.openaire.eu/search/v2/api/resources?query=((oaftype%20exact%20project)%20and%20((projectcode_nt%20exact%20%22*%22)or(*)))&amp;fq=(funder%20exact%20{funderId})&amp;page={page}&amp;size={pageSize}&amp;format=json</url> <url>https://services.openaire.eu/search/v2/api/resources?query=((oaftype exact project) and ((projectcode_nt exact "*")or(*)))&amp;fq=(funder exact {funderId})&amp;page={page}&amp;size={pageSize}&amp;format=json</url>
<firstPage>0</firstPage> <firstPage>0</firstPage>
<contenttype>application/json; charset=utf-8</contenttype> <contenttype>application/json; charset=utf-8</contenttype>
<data> <data>
@ -501,7 +501,7 @@
<label>OpenAIRE</label> <label>OpenAIRE</label>
<ordinal>1</ordinal> <ordinal>1</ordinal>
<type>External</type> <type>External</type>
<url>https://services.openaire.eu/search/v2/api/datasources?q={like}&amp;fq=datasourcetypeuiname%20exact%20%22Data%20Repository%22&amp;page={page}&amp;size={pageSize}&amp;format=json</url> <url>https://services.openaire.eu/search/v2/api/datasources?q={like}&amp;fq=datasourcetypeuiname exact "Data Repository"&amp;page={page}&amp;size={pageSize}&amp;format=json</url>
<firstPage>0</firstPage> <firstPage>0</firstPage>
<contenttype>application/json;charset=UTF-8</contenttype> <contenttype>application/json;charset=UTF-8</contenttype>
<data> <data>
@ -519,7 +519,7 @@
<label>OpenAIRE Alternative</label> <label>OpenAIRE Alternative</label>
<ordinal>1</ordinal> <ordinal>1</ordinal>
<type>External</type> <type>External</type>
<url>https://services.openaire.eu/search/v2/api/resources?query=oaftype%20exact%20datasource%20and%20{like}&amp;page={page}&amp;size={pageSize}&amp;format=json</url> <url>https://services.openaire.eu/search/v2/api/resources?query=oaftype exact datasource and {like}&amp;page={page}&amp;size={pageSize}&amp;format=json</url>
<firstPage>0</firstPage> <firstPage>0</firstPage>
<contenttype>application/json;charset=UTF-8</contenttype> <contenttype>application/json;charset=UTF-8</contenttype>
<data> <data>
@ -615,6 +615,25 @@
</data> </data>
<paginationpath>$['meta']['pagination']['page','pages','count']</paginationpath> <paginationpath>$['meta']['pagination']['page','pages','count']</paginationpath>
</urlConfig> </urlConfig>
<urlConfig>
<key>eosc</key>
<label>EOSC Providers</label>
<ordinal>2</ordinal>
<type>External</type>
<url>https://beta.providers.eosc-portal.eu/api/service/all?query={like}&amp;from={page}&amp;quantity={pageSize}</url>
<firstPage>0</firstPage>
<contenttype>application/json; charset=utf-8</contenttype>
<data>
<path>$['results'][*]</path>
<fields>
<id>'id'</id>
<name>'name'</name>
<uri>'webpage'</uri>
<description>'description'</description>
</fields>
</data>
<paginationpath>$['from','to','total']</paginationpath>
</urlConfig>
<!-- <urlConfig> <!-- <urlConfig>
<key>openAire</key> <key>openAire</key>
<label>OpenAIRE</label> <label>OpenAIRE</label>
@ -678,44 +697,6 @@
</data> </data>
<paginationpath>$['meta']['pagination']['page','pages','count']</paginationpath> <paginationpath>$['meta']['pagination']['page','pages','count']</paginationpath>
</urlConfig> </urlConfig>
<!--<urlConfig>
<key>orcid</key>
<label>ORCID</label>
<ordinal>2</ordinal>
<type>External</type>
<url>https://pub.sandbox.orcid.org/v3.0/search/?q={like}&amp;start={page}&amp;rows={pageSize}</url>
<firstPage>0</firstPage>
<contenttype>application/json; charset=utf-8</contenttype>
<data>
<path>$['result'][*]['orcid-identifier']</path>
<fields>
<id>'id'</id>
<name>'name'</name>
<uri>'uri'</uri>
<path>'path'</path>
<host>'host'</host>
</fields>
<urlConfig>
<key>orcid</key>
<label>ORCID</label>
<ordinal>3</ordinal>
<type>External</type>
<url>https://pub.{host}/v3.0/{path}/personal-details</url>
<firstPage>0</firstPage>
<data>
<parse-class>eu.eudat.models.data.external.orcid.PersonalDetails</parse-class>
<parse-field>name</parse-field>
<merge-fields>
<field>givenNames</field>
<field>familyName</field>
</merge-fields>
<merge-field-name>name</merge-field-name>
</data>
<paginationpath>$['num-found']</paginationpath>
</urlConfig>
</data>
<paginationpath>$['num-found']</paginationpath>
</urlConfig>-->
<urlConfig> <urlConfig>
<key>orcid</key> <key>orcid</key>
<label>ORCID</label> <label>ORCID</label>
@ -723,15 +704,15 @@
<type>External</type> <type>External</type>
<url>https://pub.sandbox.orcid.org/v3.0/expanded-search/?q={like}&amp;start={page}&amp;rows={pageSize}</url> <url>https://pub.sandbox.orcid.org/v3.0/expanded-search/?q={like}&amp;start={page}&amp;rows={pageSize}</url>
<firstPage>0</firstPage> <firstPage>0</firstPage>
<contenttype>application/vnd.orcid+xml; qs=5;charset=UTF-8</contenttype> <contenttype>application/json; charset=UTF-8</contenttype>
<data> <data>
<parse-class>eu.eudat.models.data.external.orcid.ExpandedSearch</parse-class> <path>$['expanded-result'][*]</path>
<parse-field>expandedResults</parse-field> <fields>
<merge-fields> <id>'orcid-id'</id>
<field>givenNames</field> <firstName>'given-names'</firstName>
<field>familyName</field> <lastName>'family-names'</lastName>
</merge-fields> <name>'name'</name>
<merge-field-name>name</merge-field-name> </fields>
</data> </data>
<paginationpath>$['num-found']</paginationpath> <paginationpath>$['num-found']</paginationpath>
</urlConfig> </urlConfig>
@ -899,7 +880,7 @@
</urlConfig> </urlConfig>
<urlConfig> <urlConfig>
<key>openaire</key> <key>openaire</key>
<label>OpenAire</label> <label>OpenAIRE</label>
<ordinal>2</ordinal> <ordinal>2</ordinal>
<type>External</type> <type>External</type>
<url>https://services.openaire.eu/search/v2/api/datasets/?q={like}&amp;page={page}&amp;size={pageSize}&amp;format=json</url> <url>https://services.openaire.eu/search/v2/api/datasets/?q={like}&amp;page={page}&amp;size={pageSize}&amp;format=json</url>
@ -908,12 +889,12 @@
<data> <data>
<path>$['results'][*]['result']['metadata']['oaf:entity']['oaf:result']</path> <path>$['results'][*]['result']['metadata']['oaf:entity']['oaf:result']</path>
<fields> <fields>
<id>'pid'</id> <id>'originalId'</id>
<name>'title'</name> <name>'title'</name>
<count>'count'</count> <count>'count'</count>
</fields> </fields>
</data> </data>
<paginationpath>$['meta']['page','size','total']</paginationpath> <paginationpath>$['meta']['pagination']['page','pages','count']</paginationpath>
</urlConfig> </urlConfig>
<!-- <urlConfig> <!-- <urlConfig>
<key>openAire</key> <key>openAire</key>

View File

@ -58,8 +58,8 @@
<key>openAIRE</key> <key>openAIRE</key>
<label>OpenAIRE</label> <label>OpenAIRE</label>
<ordinal>1</ordinal> <ordinal>1</ordinal>
<url>https://services.openaire.eu/search/v2/api/resources?query=((oaftype%20exact%20project)%20and%20((projectcode_nt%20exact%20%22{like}%22)or({like}))){funderQuery}&amp;page={page}&amp;size={pageSize}&amp;format=json</url> <url>https://services.openaire.eu/search/v2/api/resources?query=((oaftype exact project) and ((projectcode_nt exact "{like}")or({like}))){funderQuery}&amp;page={page}&amp;size={pageSize}&amp;format=json</url>
<funderQuery>&amp;fq=(funder%20exact%20%22{funderId}%22)</funderQuery> <funderQuery>&amp;fq=(funder exact "{funderId}")</funderQuery>
<firstPage>0</firstPage> <firstPage>0</firstPage>
<contenttype>application/json; charset=utf-8</contenttype> <contenttype>application/json; charset=utf-8</contenttype>
<data> <data>
@ -223,6 +223,25 @@
</data> </data>
<paginationpath>$['meta']['pagination']['page','pages','count']</paginationpath> <paginationpath>$['meta']['pagination']['page','pages','count']</paginationpath>
</urlConfig> </urlConfig>
<urlConfig>
<key>orcid</key>
<label>ORCID</label>
<ordinal>2</ordinal>
<type>External</type>
<url>https://pub.orcid.org/v3.0/expanded-search/?q={like}&amp;start={page}&amp;rows={pageSize}</url>
<firstPage>0</firstPage>
<contenttype>application/json; charset=UTF-8</contenttype>
<data>
<path>$['expanded-result'][*]</path>
<fields>
<id>'orcid-id'</id>
<firstName>'given-names'</firstName>
<lastName>'family-names'</lastName>
<name>'name'</name>
</fields>
</data>
<paginationpath>$['num-found']</paginationpath>
</urlConfig>
</urls> </urls>
<fetchMode>FIRST</fetchMode> <!-- EITHER 'FIRST' OR 'ALL' --> <fetchMode>FIRST</fetchMode> <!-- EITHER 'FIRST' OR 'ALL' -->
</researchers> </researchers>

View File

@ -61,8 +61,8 @@
<key>openAIRE</key> <key>openAIRE</key>
<label>OpenAIRE</label> <label>OpenAIRE</label>
<ordinal>1</ordinal> <ordinal>1</ordinal>
<url>https://services.openaire.eu/search/v2/api/resources?query=((oaftype%20exact%20project)%20and%20((projectcode_nt%20exact%20%22{like}%22)or({like}))){funderQuery}&amp;page={page}&amp;size={pageSize}&amp;format=json</url> <url>https://services.openaire.eu/search/v2/api/resources?query=((oaftype exact project) and ((projectcode_nt exact "{like}")or({like}))){funderQuery}&amp;page={page}&amp;size={pageSize}&amp;format=json</url>
<funderQuery>&amp;fq=(funder%20exact%20%22{funderId}%22)</funderQuery> <funderQuery>&amp;fq=(funder exact "{funderId}")</funderQuery>
<firstPage>0</firstPage> <firstPage>0</firstPage>
<contenttype>application/json; charset=utf-8</contenttype> <contenttype>application/json; charset=utf-8</contenttype>
<data> <data>
@ -235,6 +235,25 @@
</data> </data>
<paginationpath>$['meta']['pagination']['page','pages','count']</paginationpath> <paginationpath>$['meta']['pagination']['page','pages','count']</paginationpath>
</urlConfig> </urlConfig>
<urlConfig>
<key>orcid</key>
<label>ORCID</label>
<ordinal>2</ordinal>
<type>External</type>
<url>https://pub.orcid.org/v3.0/expanded-search/?q={like}&amp;start={page}&amp;rows={pageSize}</url>
<firstPage>0</firstPage>
<contenttype>application/json; charset=UTF-8</contenttype>
<data>
<path>$['expanded-result'][*]</path>
<fields>
<id>'orcid-id'</id>
<firstName>'given-names'</firstName>
<lastName>'family-names'</lastName>
<name>'name'</name>
</fields>
</data>
<paginationpath>$['num-found']</paginationpath>
</urlConfig>
</urls> </urls>
<fetchMode>FIRST</fetchMode> <!-- EITHER 'FIRST' OR 'ALL' --> <fetchMode>FIRST</fetchMode> <!-- EITHER 'FIRST' OR 'ALL' -->
</researchers> </researchers>

View File

@ -261,7 +261,7 @@
<tr> <tr>
<td> <td>
<p>Dear {recipient},</p> <p>Dear {recipient},</p>
<p>You have been invited to collaborate to Data Management plan {dmpname}.</p> <p>You have been invited to collaborate to Data Management plan {dmpname} with role {dmprole}.</p>
<p>Click the button to redirect to {dmpname}.</p> <p>Click the button to redirect to {dmpname}.</p>
<table border="0" cellpadding="0" cellspacing="0" class="btn btn-primary"> <table border="0" cellpadding="0" cellspacing="0" class="btn btn-primary">

View File

@ -1,4 +1,10 @@
DROP TABLE IF EXISTS "UserAssociation"; DO $$DECLARE
this_version CONSTANT varchar := '00.00.005';
BEGIN
PERFORM * FROM "DBVersion" WHERE version = this_version;
IF FOUND THEN RETURN; END IF;
INSERT INTO public."DBVersion" VALUES ('DMPDB', '00.00.005', '2020-06-03 12:00:00.000000+03', now(), 'Remove user association table'); DROP TABLE IF EXISTS "UserAssociation";
INSERT INTO public."DBVersion" VALUES ('DMPDB', '00.00.005', '2020-06-03 12:00:00.000000+03', now(), 'Remove user association table');
END$$;

View File

@ -0,0 +1,31 @@
# stage1 as builder
FROM node:12-alpine as builder
# copy the package.json to install dependencies
COPY package.json ./
# Install the dependencies and make the folder
RUN npm install && mkdir /src && mv ./node_modules ./src
WORKDIR /src
COPY . .
# Build the project and copy the files
RUN npm run ng build -- --deploy-url=/ --prod
FROM nginx:alpine
#!/bin/sh
COPY nginx.conf.CI /etc/nginx/nginx.conf
## Remove default nginx index page
RUN rm -rf /usr/share/nginx/html/*
# Copy from the stahg 1
COPY --from=builder /src/dist /usr/share/nginx/html
EXPOSE 8080
ENTRYPOINT ["nginx", "-g", "daemon off;"]

View File

@ -19,9 +19,7 @@
"assets": [ "assets": [
"src/assets", "src/assets",
"src/favicon.ico", "src/favicon.ico",
{ "glob": "**/*", "input": "node_modules/tinymce/skins", "output": "/tinymce/skins/" }, { "glob": "**/*", "input": "node_modules/tinymce", "output": "/tinymce/" }
{ "glob": "**/*", "input": "node_modules/tinymce/themes", "output": "/tinymce/themes/" },
{ "glob": "**/*", "input": "node_modules/tinymce/plugins", "output": "/tinymce/plugins/" }
], ],
"styles": [ "styles": [
"src/styles.scss", "src/styles.scss",

View File

@ -0,0 +1,28 @@
server {
listen 8080;
sendfile on;
default_type application/octet-stream;
gzip on;
gzip_http_version 1.1;
gzip_disable "MSIE [1-6]\.";
gzip_min_length 1100;
gzip_vary on;
gzip_proxied expired no-cache no-store private auth;
gzip_types text/plain text/css application/json application/javascript application/x-javascript text/xml application/xml application/xml+rss text/javascript;
gzip_comp_level 9;
root /usr/share/nginx/html;
location / {
try_files $uri $uri/ /index.html =404;
add_header Cache-Control "no-store, no-cache, must-revalidate";
}
}

View File

@ -22,7 +22,7 @@
"@ngx-translate/core": "^11.0.1", "@ngx-translate/core": "^11.0.1",
"@ngx-translate/http-loader": "^4.0.0", "@ngx-translate/http-loader": "^4.0.0",
"@swimlane/ngx-datatable": "^16.0.2", "@swimlane/ngx-datatable": "^16.0.2",
"@tinymce/tinymce-angular": "^3.4.0", "@tinymce/tinymce-angular": "^3.6.1",
"@w11k/angular-sticky-things": "^1.1.2", "@w11k/angular-sticky-things": "^1.1.2",
"bootstrap": "^4.3.1", "bootstrap": "^4.3.1",
"cookieconsent": "^3.1.1", "cookieconsent": "^3.1.1",
@ -30,10 +30,13 @@
"file-saver": "^2.0.2", "file-saver": "^2.0.2",
"moment": "^2.24.0", "moment": "^2.24.0",
"moment-timezone": "^0.5.26", "moment-timezone": "^0.5.26",
"ng-dialog-animation": "^9.0.3",
"ngx-cookie-service": "^2.2.0", "ngx-cookie-service": "^2.2.0",
"ngx-cookieconsent": "^2.2.3", "ngx-cookieconsent": "^2.2.3",
"ngx-dropzone": "^2.2.2",
"ngx-guided-tour": "^1.1.10",
"rxjs": "^6.3.2", "rxjs": "^6.3.2",
"tinymce": "^5.1.6", "tinymce": "^5.4.2",
"tslib": "^1.10.0", "tslib": "^1.10.0",
"web-animations-js": "^2.3.2", "web-animations-js": "^2.3.2",
"zone.js": "~0.9.1" "zone.js": "~0.9.1"

View File

@ -139,6 +139,14 @@ const appRoutes: Routes = [
title: 'GENERAL.TITLES.PRIVACY' title: 'GENERAL.TITLES.PRIVACY'
} }
}, },
{
path: 'opensource-licences',
loadChildren: () => import('./ui/sidebar/sidebar-footer/opensource-licences/opensource-licenses.module').then(m => m.OpensourceLicencesModule),
data: {
breadcrumb: true,
title: 'GENERAL.TITLES.OPENSOURCE-LICENCES'
}
},
{ {
path: 'terms-and-conditions', path: 'terms-and-conditions',
loadChildren: () => import('./ui/sidebar/sidebar-footer/terms/terms.module').then(m => m.TermsModule), loadChildren: () => import('./ui/sidebar/sidebar-footer/terms/terms.module').then(m => m.TermsModule),

View File

@ -1,6 +1,16 @@
<div class="wrapper" *ngIf="!onlySplash"> <div class="wrapper" *ngIf="!onlySplash">
<div class="sidebar sidebar-shadow" data-color="danger" data-background-color="white" <app-navbar (sidebarToggled)="sidenav.toggle(); toggleNavbar($event);"></app-navbar>
data-image="./assets/images/logan-troxell-9187-unsplash.jpg"> <mat-sidenav-container fullscreen class="main-container">
<mat-sidenav #sidenav mode="side" opened class="sidenav" [fixedInViewport]="true" [fixedTopGap]="80">
<app-sidebar></app-sidebar>
</mat-sidenav>
<mat-sidenav-content class="sidenav-content">
<div id="main-page">
<router-outlet (activate)='onActivate($event)' (deactivate)='onDeactivate($event)'></router-outlet>
</div>
</mat-sidenav-content>
</mat-sidenav-container>
<!-- <div class="sidebar sidebar-shadow" data-color="danger" data-background-color="white" data-image="./assets/images/logan-troxell-9187-unsplash.jpg">
<app-sidebar></app-sidebar> <app-sidebar></app-sidebar>
<div class="sidebar-background" style="background-image: url(./assets/images/logan-troxell-9187-unsplash.jpg)"> <div class="sidebar-background" style="background-image: url(./assets/images/logan-troxell-9187-unsplash.jpg)">
</div> </div>
@ -8,35 +18,11 @@
<div class="main-panel"> <div class="main-panel">
<app-navbar></app-navbar> <app-navbar></app-navbar>
<div> <div>
<!-- <app-breadcrumb *ngIf="this.isAuthenticated() && (hasBreadCrumb | async)"></app-breadcrumb> -->
<router-outlet (activate)='onActivate($event)' (deactivate)='onDeactivate($event)'></router-outlet> <router-outlet (activate)='onActivate($event)' (deactivate)='onDeactivate($event)'></router-outlet>
</div> </div>
</div> </div> -->
</div> </div>
<app-notification *ngIf="!onlySplash"></app-notification> <app-notification *ngIf="!onlySplash"></app-notification>
<router-outlet *ngIf="onlySplash"></router-outlet> <router-outlet *ngIf="onlySplash"></router-outlet>
<ngx-guided-tour></ngx-guided-tour>
<!-- <app-navigation class="fixed"></app-navigation>
<div class="container-fluid main-container">
<div class="row" *ngIf="helpContentEnabled">
<app-help-content position="top"></app-help-content>
</div>
<div class="row">
<div class="col-md-2">
<app-help-content position="left" *ngIf="helpContentEnabled"></app-help-content>
</div>
<div class="col-md-8">
<app-breadcrumb *ngIf="this.isAuthenticated() && (hasBreadCrumb | async)"></app-breadcrumb>
<router-outlet (activate)='onActivate($event)' (deactivate)='onDeactivate($event)'></router-outlet>
</div>
<div class="col-md-2">
<app-help-content position="right" *ngIf="helpContentEnabled"></app-help-content>
</div>
</div>
<div class="row" *ngIf="helpContentEnabled">
<app-help-content position="bottom"></app-help-content>
</div>
</div>
<app-notification></app-notification> -->

View File

@ -6,9 +6,30 @@
width: 100%; width: 100%;
} }
// .main-container {
// margin-top: 64px;
// padding-top: 10px;
// }
.main-container { .main-container {
margin-top: 64px; top: 80px;
padding-top: 10px; left: 0;
right: 0;
}
.sidenav {
display: flex;
align-items: center;
justify-content: center;
width: 260px;
background: #ffffff 0% 0% no-repeat padding-box;
box-shadow: 0px 0px 16px 2px #00000029;
border-right-width: 0px;
opacity: 1;
}
.sidenav-content {
background-color: whitesmoke;
} }
.sidebar-shadow { .sidebar-shadow {

View File

@ -32,7 +32,7 @@ export class AppComponent implements OnInit {
sideNavOpen = false; sideNavOpen = false;
helpContentEnabled: boolean; helpContentEnabled: boolean;
private statusChangeSubscription: Subscription; private statusChangeSubscription: Subscription;
onlySplash = false; onlySplash = true;
constructor( constructor(
private router: Router, private router: Router,
@ -91,26 +91,19 @@ export class AppComponent implements OnInit {
filter(event => event instanceof NavigationEnd), filter(event => event instanceof NavigationEnd),
map(() => { map(() => {
let child = this.route.firstChild; let child = this.route.firstChild;
if (child != null) {
while (child.firstChild) { while (child.firstChild) {
child = child.firstChild; child = child.firstChild;
} }
if (child.snapshot.data['title']) { if (child.snapshot.data['title']) {
return child.snapshot.data['title']; return child.snapshot.data['title'];
} }
}
return appTitle; return appTitle;
}) })
).subscribe((ttl: string) => { ).subscribe((ttl: string) => {
if (ttl.length > 0) { this.translateTitle(ttl);
this.translate.get(ttl).subscribe((translated: string) => { this.translate.onLangChange.subscribe(() => this.translateTitle(ttl));
this.translate.get('GENERAL.TITLES.PREFIX').subscribe((titlePrefix: string) => {
this.titleService.setTitle(titlePrefix + translated);
});
});
} else {
this.translate.get('GENERAL.TITLES.GENERAL').subscribe((translated: string) => {
this.titleService.setTitle(translated);
});
}
}); });
this.statusChangeSubscription = this.ccService.statusChange$.subscribe((event: NgcStatusChangeEvent) => { this.statusChangeSubscription = this.ccService.statusChange$.subscribe((event: NgcStatusChangeEvent) => {
@ -140,6 +133,20 @@ export class AppComponent implements OnInit {
}) })
} }
translateTitle(ttl: string) {
if (ttl.length > 0) {
this.translate.get(ttl).subscribe((translated: string) => {
this.translate.get('GENERAL.TITLES.PREFIX').subscribe((titlePrefix: string) => {
this.titleService.setTitle(titlePrefix + translated);
});
});
} else {
this.translate.get('GENERAL.TITLES.GENERAL').subscribe((translated: string) => {
this.titleService.setTitle(translated);
});
}
}
ngOnDestroy() { ngOnDestroy() {
this.statusChangeSubscription.unsubscribe(); this.statusChangeSubscription.unsubscribe();
} }
@ -171,5 +178,9 @@ export class AppComponent implements OnInit {
this.authentication.current() && this.authentication.current().culture ? this.cultureService.cultureSelected(this.authentication.current().culture) : this.cultureService.cultureSelected(this.configurationService.defaultCulture); this.authentication.current() && this.authentication.current().culture ? this.cultureService.cultureSelected(this.authentication.current().culture) : this.cultureService.cultureSelected(this.configurationService.defaultCulture);
this.authentication.current() && this.authentication.current().language ? this.language.changeLanguage(this.authentication.current().language) : this.language.changeLanguage('en'); this.authentication.current() && this.authentication.current().language ? this.language.changeLanguage(this.authentication.current().language) : this.language.changeLanguage('en');
} }
toggleNavbar(event) {
document.getElementById('hamburger').classList.toggle("change");
}
} }

View File

@ -31,6 +31,8 @@ import { TranslateServerLoader } from './core/services/language/server.loader';
import { BaseHttpService } from './core/services/http/base-http.service'; import { BaseHttpService } from './core/services/http/base-http.service';
import { ConfigurationService } from './core/services/configuration/configuration.service'; import { ConfigurationService } from './core/services/configuration/configuration.service';
import { Oauth2DialogModule } from './ui/misc/oauth2-dialog/oauth2-dialog.module'; import { Oauth2DialogModule } from './ui/misc/oauth2-dialog/oauth2-dialog.module';
import { MAT_FORM_FIELD_DEFAULT_OPTIONS, MatFormFieldDefaultOptions } from '@angular/material';
import { GuidedTourModule } from './library/guided-tour/guided-tour.module';
// AoT requires an exported function for factories // AoT requires an exported function for factories
export function HttpLoaderFactory(http: HttpClient, appConfig: ConfigurationService) { export function HttpLoaderFactory(http: HttpClient, appConfig: ConfigurationService) {
@ -69,6 +71,11 @@ const cookieConfig: NgcCookieConsentConfig = {
type: 'info' type: 'info'
}; };
const appearance: MatFormFieldDefaultOptions = {
appearance: 'outline'
// appearance: 'standard'
};
@NgModule({ @NgModule({
imports: [ imports: [
BrowserModule, BrowserModule,
@ -99,7 +106,8 @@ const cookieConfig: NgcCookieConsentConfig = {
NavbarModule, NavbarModule,
SidebarModule, SidebarModule,
NgcCookieConsentModule.forRoot(cookieConfig), NgcCookieConsentModule.forRoot(cookieConfig),
Oauth2DialogModule Oauth2DialogModule,
GuidedTourModule.forRoot()
], ],
declarations: [ declarations: [
AppComponent, AppComponent,
@ -118,6 +126,10 @@ const cookieConfig: NgcCookieConsentConfig = {
deps: [CultureService], deps: [CultureService],
useFactory: (cultureService) => cultureService.getCurrentCulture().name useFactory: (cultureService) => cultureService.getCurrentCulture().name
}, },
{
provide: MAT_FORM_FIELD_DEFAULT_OPTIONS,
useValue: appearance
},
Title, Title,
CookieService CookieService
], ],

View File

@ -0,0 +1,9 @@
export enum RecentActivityOrder {
LABEL = "label",
CREATED = "created",
MODIFIED = "modified",
FINALIZED = "finalizedAt",
PUBLISHED = "publishedAt",
DATASETPUBLISHED = "dmp:publishedAt|join|",
STATUS = "status"
}

View File

@ -0,0 +1,4 @@
export enum SaveType {
close = 0,
addNew = 1
}

View File

@ -4,6 +4,7 @@ export interface Principal {
id: string; id: string;
token: string; token: string;
name: string; name: string;
email: string;
expiresAt: Date; expiresAt: Date;
authorities: AppRole[]; authorities: AppRole[];
avatarUrl: string; avatarUrl: string;

View File

@ -12,3 +12,17 @@ export class DataTableRequest<T> extends RequestItem<T> {
this.orderings = orderings; this.orderings = orderings;
} }
} }
export class DataTableMultiTypeRequest<T> extends RequestItem<T> {
dmpOffset = 0;
datasetOffset = 0;
length = 0;
public orderings: ColumnOrdering;
constructor(dmpOffset: number, datasetOffset: number, length: number, orderings: ColumnOrdering) {
super();
this.length = length;
this.dmpOffset = dmpOffset;
this.datasetOffset = datasetOffset;
this.orderings = orderings;
}
}

View File

@ -41,6 +41,7 @@ export interface TextAreaFieldData extends FieldData {
export interface WordListFieldData extends FieldData { export interface WordListFieldData extends FieldData {
type: DatasetProfileComboBoxType; type: DatasetProfileComboBoxType;
options: Array<FieldDataOption>; options: Array<FieldDataOption>;
multiList: boolean;
} }
export interface FieldDataOption extends FieldData { export interface FieldDataOption extends FieldData {

View File

@ -1,20 +1,25 @@
import { DatasetProfileModel } from './dataset-profile';
export interface DatasetListingModel { export interface DatasetListingModel {
id: String; id: string;
label: String; label: string;
dmp: String; dmp: String;
dmpId: String; dmpId: String;
grant: String; grant: String;
grantId: String; grantId: String;
grantAbbreviation: String; grantAbbreviation: String;
profile: String; profile: DatasetProfileModel;
dataRepositories: String; dataRepositories: String;
registries: String; registries: String;
services: String; services: String;
description: String; description: String;
status: Number; status: number;
created: Date; created: Date;
modified: Date; modified: Date;
finalizedAt: Date; finalizedAt: Date;
dmpPublishedAt?: Date; dmpPublishedAt?: Date;
version: number; version: number;
users: any[];
public: boolean;
isProfileLatestVersion: boolean;
} }

View File

@ -1,8 +1,17 @@
import { DatasetProfileModel } from "./dataset-profile"; import { DatasetProfileModel } from "./dataset-profile";
import { GrantOverviewModel } from '../grant/grant-overview';
import { DmpOverviewModel } from '../dmp/dmp-overview';
export interface DatasetOverviewModel { export interface DatasetOverviewModel {
id: string; id: string;
label: string; label: string;
status: any; status: number;
datasetTemplate: DatasetProfileModel; datasetTemplate: DatasetProfileModel;
users: any[];
dmp: DmpOverviewModel;
grant: GrantOverviewModel;
description: String;
public: boolean;
modified: Date;
} }

View File

@ -1,23 +1,24 @@
import { DmpStatus } from "../../common/enum/dmp-status"; import { DmpStatus } from "../../common/enum/dmp-status";
import { DmpAssociatedProfileModel } from '../dmp-profile/dmp-associated-profile';
export interface DmpListingModel { export interface DmpListingModel {
id: string; id: string;
label: String; label: string;
description: String; description: String;
status: DmpStatus; status: DmpStatus;
grant: String; grant: String;
grantId: String; grantId: String;
grantAbbreviation: String; grantAbbreviation: String;
profile: String; profile: String;
creationTime: String; creationTime: string;
modifiedTime: String; modifiedTime: string;
publishedAt: Date; publishedAt: Date;
finalizedAt: Date; finalizedAt: Date;
organisations: String; organisations: String;
groupId: string; groupId: string;
version: number; version: number;
datasets: any[]; datasets: any[];
associatedProfiles: any[]; associatedProfiles: DmpAssociatedProfileModel[];
users: any[]; users: any[];
public: boolean; public: boolean;
} }

View File

@ -1,5 +1,4 @@
import { OrganizationModel } from "../organisation/organization"; import { OrganizationModel } from "../organisation/organization";
import { DatasetUrlListing } from "../dataset/dataset-url-listing";
import { UserInfoListingModel } from "../user/user-info-listing"; import { UserInfoListingModel } from "../user/user-info-listing";
import { DmpAssociatedProfileModel } from "../dmp-profile/dmp-associated-profile"; import { DmpAssociatedProfileModel } from "../dmp-profile/dmp-associated-profile";
import { ResearcherModel } from "../researcher/researcher"; import { ResearcherModel } from "../researcher/researcher";

View File

@ -11,6 +11,7 @@ import { ProjectModel } from "../project/project";
import { FunderModel } from "../funder/funder"; import { FunderModel } from "../funder/funder";
import { DmpStatus } from '@app/core/common/enum/dmp-status'; import { DmpStatus } from '@app/core/common/enum/dmp-status';
import { ExtraPropertiesFormModel } from '@app/ui/dmp/editor/general-tab/extra-properties-form.model'; import { ExtraPropertiesFormModel } from '@app/ui/dmp/editor/general-tab/extra-properties-form.model';
import { DatasetWizardModel } from '../dataset/dataset-wizard';
export interface DmpModel { export interface DmpModel {
id: string; id: string;
@ -24,7 +25,7 @@ export interface DmpModel {
grant: GrantListingModel; grant: GrantListingModel;
project: ProjectModel; project: ProjectModel;
funder: FunderModel; funder: FunderModel;
datasets: DatasetModel[]; datasets: DatasetWizardModel[];
datasetsToBeFinalized: string[]; datasetsToBeFinalized: string[];
profiles: DmpProfile[]; profiles: DmpProfile[];
organisations: OrganizationModel[]; organisations: OrganizationModel[];

View File

@ -5,11 +5,13 @@ export class DmpInvitation {
public dataManagementPlan: string; public dataManagementPlan: string;
public users = new Array<DmpInvitationUser>(); public users = new Array<DmpInvitationUser>();
public role: number;
buildForm(): FormGroup { buildForm(): FormGroup {
const formGroup = new FormBuilder().group({ const formGroup = new FormBuilder().group({
dataManagementPlan: [this.dataManagementPlan], dataManagementPlan: [this.dataManagementPlan],
users: [this.users] users: [this.users],
role: [this.role]
}); });
return formGroup; return formGroup;

View File

@ -0,0 +1,23 @@
import { RecentActivityType } from '@app/core/common/enum/recent-activity-type';
import { UserInfoListingModel } from '../user/user-info-listing';
import { DatasetProfileModel } from '../dataset/dataset-profile';
export class RecentActivityModel {
id: string;
title: string;
description: String;
created: Date;
modified: Date;
status: number;
version: number;
grant: String;
grantAbbreviation: String;
grantId: String;
finalizedAt: Date;
publishedAt: Date;
profile: DatasetProfileModel;
type: RecentActivityType;
users: UserInfoListingModel[];
public: boolean;
}

View File

@ -0,0 +1,9 @@
import { RecentActivityModel } from "./recent-activity.model";
export class RecentDatasetModel extends RecentActivityModel {
dmp: String;
dmpId: String;
dataRepositories: String;
registries: String;
services: String;
}

View File

@ -0,0 +1,14 @@
import { RecentActivityModel } from './recent-activity.model';
import { RecentDatasetModel } from './recent-dataset-activity.model';
import { DmpAssociatedProfileModel } from '../dmp-profile/dmp-associated-profile';
import { UserInfoListingModel } from '../user/user-info-listing';
import { DatasetUrlListing } from '../dataset/dataset-url-listing';
export class RecentDmpModel extends RecentActivityModel {
doi: String;
extraProperties: Map<String, any>;
datasets: DatasetUrlListing[];
associatedProfiles: DmpAssociatedProfileModel[];
organisations: String;
groupId: string;
}

View File

@ -1,5 +1,5 @@
export interface ResearcherModel { export interface ResearcherModel {
id: String; id: string;
name: String; name: String;
reference: String; reference: String;
lastName: String; lastName: String;

View File

@ -5,6 +5,10 @@ export interface UserListingModel {
name: String; name: String;
email: string; email: string;
appRoles: AppRole[]; appRoles: AppRole[];
additionalinfo: any;
associatedDmps: any[]; associatedDmps: any[];
language: any;
culture: any;
timezone: String;
zenodoEmail: String;
avatarUrl: String;
} }

View File

@ -0,0 +1,5 @@
export interface VersionListingModel {
id: string;
groupId: string;
version: number;
}

View File

@ -0,0 +1,6 @@
import { RecentActivityOrder } from '@app/core/common/enum/recent-activity-order';
import { BaseCriteria } from '../base-criteria';
export class RecentActivityCriteria extends BaseCriteria{
public order: RecentActivityOrder = RecentActivityOrder.MODIFIED;
}

View File

@ -48,8 +48,14 @@ export class AuthService extends BaseService {
return principal; return principal;
} }
const principalJson = localStorage.getItem('principal'); const principalJson = localStorage.getItem('principal');
if (!principalJson) { return null; } if (principalJson === null || principalJson === undefined) {
const principalObj = JSON.parse(principalJson) as Principal; return null;
}
let principalObj = JSON.parse(principalJson) as Principal;
principalObj.expiresAt = new Date(principalObj.expiresAt);
if (principalObj.expiresAt < new Date()) {
return null;
}
return principalObj; return principalObj;
} }
@ -121,7 +127,8 @@ export class AuthService extends BaseService {
} }
public me(): Observable<Principal> { public me(): Observable<Principal> {
const url = this.actionUrl + '/me'; this.actionUrl = this.configurationService.server + 'auth/';
const url = this.actionUrl + 'me';
const principal = this.current(); const principal = this.current();
if (!principal) { if (!principal) {
this.clear(); this.clear();
@ -132,6 +139,8 @@ export class AuthService extends BaseService {
return this.http.post(url, null, { headers: headers }).pipe( return this.http.post(url, null, { headers: headers }).pipe(
map((res: any) => { map((res: any) => {
const princ = this.current(res.payload); const princ = this.current(res.payload);
princ.expiresAt = new Date(princ.expiresAt);
console.log("Token Expires at: " + princ.expiresAt.toDateString() + ' ' + princ.expiresAt.toLocaleTimeString());
return princ; return princ;
}), }),
catchError((error: any) => { catchError((error: any) => {

View File

@ -71,6 +71,10 @@ export class ConfigurationService extends BaseComponent {
return this._useSplash; return this._useSplash;
} }
private _orcidPath: string;
get orcidPath(): string {
return this._orcidPath;
}
public loadConfiguration(): Promise<any> { public loadConfiguration(): Promise<any> {
return new Promise((r, e) => { return new Promise((r, e) => {
@ -109,6 +113,7 @@ export class ConfigurationService extends BaseComponent {
this._allowOrganizationCreator = config.allowOrganizationCreator; this._allowOrganizationCreator = config.allowOrganizationCreator;
this._doiLink = config.doiLink; this._doiLink = config.doiLink;
this._useSplash = config.useSplash; this._useSplash = config.useSplash;
this._orcidPath = config.orcidPath;
} }
} }

View File

@ -5,6 +5,9 @@ import { environment } from '../../../../environments/environment';
import { DashboardStatisticsModel } from '../../model/dashboard/dashboard-statistics-model'; import { DashboardStatisticsModel } from '../../model/dashboard/dashboard-statistics-model';
import { BaseHttpService } from '../http/base-http.service'; import { BaseHttpService } from '../http/base-http.service';
import { ConfigurationService } from '../configuration/configuration.service'; import { ConfigurationService } from '../configuration/configuration.service';
import { RecentActivityModel } from '@app/core/model/recent-activity/recent-activity.model';
import { RecentActivityCriteria } from '@app/core/query/recent-activity/recent-activity-criteria';
import { DataTableRequest, DataTableMultiTypeRequest } from '@app/core/model/data-table/data-table-request';
@Injectable() @Injectable()
export class DashboardService { export class DashboardService {
@ -24,4 +27,12 @@ export class DashboardService {
getUserStatistics(): Observable<DashboardStatisticsModel> { getUserStatistics(): Observable<DashboardStatisticsModel> {
return this.http.get<DashboardStatisticsModel>(this.actionUrl + 'me/getStatistics', { headers: this.headers }); return this.http.get<DashboardStatisticsModel>(this.actionUrl + 'me/getStatistics', { headers: this.headers });
} }
getRecentActivity(request: DataTableMultiTypeRequest<RecentActivityCriteria>): Observable<RecentActivityModel[]> {
return this.http.post<RecentActivityModel[]>(this.actionUrl + 'recentActivity', request, {headers: this.headers});
}
// getRecentActivity(request: DataTableRequest<RecentActivityCriteria>): Observable<DataTableData<RecentActivityModel>> {
// return this.http.post<DataTableData<RecentActivityModel>>(this.actionUrl + 'recentActivity', request, {headers: this.headers});
// }
} }

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