From 6c669a15711f67621fc5a1047c0d4222e2ddfd00 Mon Sep 17 00:00:00 2001 From: annampak Date: Fri, 15 Dec 2017 17:33:18 +0200 Subject: [PATCH 1/3] dataset table --- dmp-frontend/src/app/app.module.ts | 5 +- .../dataset-listing.component.css | 0 .../dataset-listing.component.html | 59 ++++++++ .../datasets_new/dataset-listing.component.ts | 128 ++++++++++++++++++ .../src/app/homepage/homepage.component.html | 68 +--------- .../src/app/homepage/homepage.component.ts | 2 +- .../models/datasets/DatasetListingModel.ts | 21 +++ .../app/services/dataset/dataset.service.ts | 34 +++++ dmp-frontend/src/assets/lang/en.json | 10 ++ 9 files changed, 258 insertions(+), 69 deletions(-) create mode 100644 dmp-frontend/src/app/datasets_new/dataset-listing.component.css create mode 100644 dmp-frontend/src/app/datasets_new/dataset-listing.component.html create mode 100644 dmp-frontend/src/app/datasets_new/dataset-listing.component.ts create mode 100644 dmp-frontend/src/app/models/datasets/DatasetListingModel.ts create mode 100644 dmp-frontend/src/app/services/dataset/dataset.service.ts diff --git a/dmp-frontend/src/app/app.module.ts b/dmp-frontend/src/app/app.module.ts index 5b219e249..b2e81e013 100644 --- a/dmp-frontend/src/app/app.module.ts +++ b/dmp-frontend/src/app/app.module.ts @@ -104,7 +104,9 @@ import { SharedModule } from './shared/shared.module'; import { MaterialModule } from './shared/material/material.module'; import { AuthService } from './services/auth/auth.service'; import { ProjectListingComponent } from './projects/project-listing.component'; +import { DatasetListingComponent } from './datasets_new/dataset-listing.component'; import { DashboardService } from './services/dashboard/dashboard.service'; +import { DatasetService } from './services/dataset/dataset.service'; import { BaseHttpService } from './utilities/cite-http-service-module/base-http.service'; import { DataManagementPlanListingComponent } from './dmps/dmp-listing.component'; import { ProjectEditorComponent } from './projects/editor/project-editor.component'; @@ -133,6 +135,7 @@ import { FigurecardComponent } from './shared/components/figurecard/figurecard.c HomepageComponent, ModalComponent, ProjectListingComponent, + DatasetListingComponent, DataManagementPlanListingComponent, DatasetsComponent, ConfirmationComponent, @@ -196,7 +199,7 @@ import { FigurecardComponent } from './shared/components/figurecard/figurecard.c }, ServerService, VisibilityRulesService, PaginationService, GlobalVariables, AuthGuard, TokenService, LocalStorageService, RestBase, EestoreService, NativeLoginService, PDFService, - AuthService,DashboardService, + AuthService,DashboardService,DatasetService, BaseHttpService ], bootstrap: [AppComponent] diff --git a/dmp-frontend/src/app/datasets_new/dataset-listing.component.css b/dmp-frontend/src/app/datasets_new/dataset-listing.component.css new file mode 100644 index 000000000..e69de29bb diff --git a/dmp-frontend/src/app/datasets_new/dataset-listing.component.html b/dmp-frontend/src/app/datasets_new/dataset-listing.component.html new file mode 100644 index 000000000..a87ed6ea5 --- /dev/null +++ b/dmp-frontend/src/app/datasets_new/dataset-listing.component.html @@ -0,0 +1,59 @@ +
+

{{'DATASET-LISTING.TITLE' | translate}}

+ + + + + + + + + + {{'DATASET-LISTING.COLUMNS.NAME' | translate}} + {{row.label}} + + + + + {{'DATASET-LISTING.COLUMNS.REFERNCE' | translate}} + {{row.reference}} + + + + + {{'DATASET-LISTING.COLUMNS.URI' | translate}} + {{row.uri}} + + + + + {{'DATASET-LISTING.COLUMNS.STATUS' | translate}} + {{row.status}} + + + + + {{'DATASET-LISTING.COLUMNS.DESCRIPTION' | translate}} + {{row.description}} + + + + + {{'PROJECT-LISTING.COLUMNS.ACTIONS' | translate}} + + + + + + + + + + + + +
diff --git a/dmp-frontend/src/app/datasets_new/dataset-listing.component.ts b/dmp-frontend/src/app/datasets_new/dataset-listing.component.ts new file mode 100644 index 000000000..e9068fac5 --- /dev/null +++ b/dmp-frontend/src/app/datasets_new/dataset-listing.component.ts @@ -0,0 +1,128 @@ +import { Component, ViewChild, OnInit, AfterViewInit } from "@angular/core"; +import { MatPaginator, MatSort, MatSnackBar } from "@angular/material"; +import { Router } from "@angular/router"; +import { TranslateService } from "@ngx-translate/core"; +import { DataSource } from "@angular/cdk/table"; + +import { ProjectCriteriaComponent } from "../shared/components/criteria/projects/projects-criteria.component"; +import { ProjectCriteria } from "../models/criteria/project/ProjectCriteria"; +import { Observable } from "rxjs/Observable"; +import { DataTableRequest } from "../models/data-table/DataTableRequest"; +import { SnackBarNotificationComponent } from "../shared/components/notificaiton/snack-bar-notification.component"; +import { DatasetService } from "../services/dataset/dataset.service"; +import { DatasetListingModel } from "../models/datasets/DatasetListingModel"; + + + +@Component({ + selector: 'app-dataset-listing-component', + templateUrl: 'dataset-listing.component.html', + styleUrls: ['./dataset-listing.component.css'], + providers: [DatasetService] +}) +export class DatasetListingComponent implements OnInit, AfterViewInit { + + @ViewChild(MatPaginator) _paginator: MatPaginator; + @ViewChild(MatSort) sort: MatSort; + @ViewChild(ProjectCriteriaComponent) criteria: ProjectCriteriaComponent; + + dataSource: DatasetDataSource | null; + displayedColumns: String[] = ['label', 'reference', 'uri', 'status', 'description', 'actions']; + + constructor( + private datasetService: DatasetService, + private router: Router, + private languageService: TranslateService, + public snackBar: MatSnackBar, + ) { + + } + + ngOnInit() { + + } + + ngAfterViewInit() { + setTimeout(() => { + this.criteria.setRefreshCallback(() => this.refresh()); + this.criteria.setCriteria(this.getDefaultCriteria()); + this.criteria.controlModified(); + }); + } + + refresh() { + this.dataSource = new DatasetDataSource(this.datasetService, this._paginator, this.sort, this.languageService, this.snackBar, this.criteria, ); + } + + rowClick(rowId: String) { + this.router.navigate(['/project/' + rowId]); + } + + getDefaultCriteria(): ProjectCriteria { + const defaultCriteria = new ProjectCriteria(); + return defaultCriteria; + } + +} + +export class DatasetDataSource extends DataSource { + + totalCount = 0; + isLoadingResults = false; + + constructor( + private _service: DatasetService, + private _paginator: MatPaginator, + private _sort: MatSort, + private _languageService: TranslateService, + private _snackBar: MatSnackBar, + private _criteria: ProjectCriteriaComponent + ) { + super(); + + } + + connect(): Observable { + const displayDataChanges = [ + this._paginator.page + //this._sort.matSortChange + ]; + + + return Observable.merge(...displayDataChanges) + .startWith(null) + .switchMap(() => { + setTimeout(() => { + this.isLoadingResults = true; + }); + const startIndex = this._paginator.pageIndex * this._paginator.pageSize; + const request = new DataTableRequest(startIndex, this._paginator.pageSize); + request.projectCriteria = this._criteria.getFormData(); + return this._service.getPaged(request); + }) + .catch((error: any) => { + this._snackBar.openFromComponent(SnackBarNotificationComponent, { + data: { message: 'GENERAL.SNACK-BAR.FORMS-BAD-REQUEST', language: this._languageService }, + duration: 3000, + extraClasses: ['snackbar-warning'] + }); + this._criteria.onCallbackError(error); + return Observable.of(null); + }) + .map(result => { + setTimeout(() => { + this.isLoadingResults = false; + }); + return result.data; + }) + .map(result => { + if (!result) { return []; } + if (this._paginator.pageIndex === 0) { this.totalCount = result.totalCount; } + return result.data; + }); + } + + disconnect() { + // No-op + } +} \ No newline at end of file diff --git a/dmp-frontend/src/app/homepage/homepage.component.html b/dmp-frontend/src/app/homepage/homepage.component.html index a056b7540..836bb68af 100644 --- a/dmp-frontend/src/app/homepage/homepage.component.html +++ b/dmp-frontend/src/app/homepage/homepage.component.html @@ -99,71 +99,5 @@ -
- -
-
-
-
- assignment - add_circle -
-
-

Active Datasets

-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
First NameCountryCitySalary
Dakota RiceNigerOud-Turnhout$36,738
Minerva HooperCuraçaoSinaai-Waas$23,789
Sage RodriguezNetherlandsBaileux$56,142
Philip ChaneyKorea, SouthOverland Park$38,735
Doris GreeneMalawiFeldkirchen in Kärnten$63,542
Mason PorterChileGloucester$78,615
-
-
-
-
-
-
- + \ No newline at end of file diff --git a/dmp-frontend/src/app/homepage/homepage.component.ts b/dmp-frontend/src/app/homepage/homepage.component.ts index 9964f9695..a7c8c6a8d 100644 --- a/dmp-frontend/src/app/homepage/homepage.component.ts +++ b/dmp-frontend/src/app/homepage/homepage.component.ts @@ -4,6 +4,7 @@ import { ServerService } from '../../app/services/server.service'; import { DashboardService } from '../../app/services/dashboard/dashboard.service'; import { DashboardStatisticsModel } from '../models/dashboard/DashboardStatisticsModel'; import { JsonSerializer } from '../utilities/JsonSerializer'; +import { DatasetListingComponent } from '../../app/datasets_new/dataset-listing.component'; @Component({ selector: 'homepage', @@ -33,7 +34,6 @@ export class HomepageComponent implements OnInit{ ); this.dashBoardService.getStatistics().subscribe(data =>{ - debugger; this.dashboardStatisticsData = new JsonSerializer().fromJSONObject(data,DashboardStatisticsModel); }) diff --git a/dmp-frontend/src/app/models/datasets/DatasetListingModel.ts b/dmp-frontend/src/app/models/datasets/DatasetListingModel.ts new file mode 100644 index 000000000..c5d218824 --- /dev/null +++ b/dmp-frontend/src/app/models/datasets/DatasetListingModel.ts @@ -0,0 +1,21 @@ +import { Serializable } from "../Serializable"; + +export class DatasetListingModel implements Serializable { + public id: String; + private label:String; + private reference: String; + private uri: String; + private description: String; + private status: Number; + + fromJSONObject(item: any): DatasetListingModel { + this.id = item.id; + this.label = item.label; + this.reference = item.reference; + this.uri = item.uri; + this.status = item.status; + this.description = item.description; + + return this; + } +} \ No newline at end of file diff --git a/dmp-frontend/src/app/services/dataset/dataset.service.ts b/dmp-frontend/src/app/services/dataset/dataset.service.ts new file mode 100644 index 000000000..56c38ba64 --- /dev/null +++ b/dmp-frontend/src/app/services/dataset/dataset.service.ts @@ -0,0 +1,34 @@ +import 'rxjs/add/operator/map'; +import { HttpClient, HttpHeaders } from '@angular/common/http'; +import { Injectable } from '@angular/core'; +import { HostConfiguration } from './../../app.constants'; +import { BaseHttpService } from '../../utilities/cite-http-service-module/base-http.service'; +import { Observable } from 'rxjs/Observable'; +import { DataTableRequest } from '../../models/data-table/DataTableRequest'; +import { DataTableData } from '../../models/data-table/DataTableData'; +import { DatasetListingModel } from '../../models/datasets/DatasetListingModel'; + + +@Injectable() +export class DatasetService { + + private actionUrl: string; + private headers: HttpHeaders; + + constructor(private http: BaseHttpService) { + + this.actionUrl = HostConfiguration.Server + 'datasets/'; + + this.headers = new HttpHeaders(); + this.headers = this.headers.set('Content-Type', 'application/json'); + this.headers = this.headers.set('Accept', 'application/json'); + } + + getPaged(dataTableRequest: DataTableRequest): Observable> { + return this.http.post>(this.actionUrl + 'getPaged', dataTableRequest, { headers: this.headers }); + } + + // getSingle(id: string): Observable { + // return this.http.get(this.actionUrl + id, { headers: this.headers }); + // } +} diff --git a/dmp-frontend/src/assets/lang/en.json b/dmp-frontend/src/assets/lang/en.json index 184d150d0..48daff671 100644 --- a/dmp-frontend/src/assets/lang/en.json +++ b/dmp-frontend/src/assets/lang/en.json @@ -22,6 +22,16 @@ "ACTIONS": "Actions" } }, + "DATASET-LISTING": { + "TITLE": "Datasets", + "COLUMNS": { + "NAME": "Name", + "REFERNCE": "Reference", + "URI": "Uri", + "STATUS": "Status", + "DESCRIPTION": "Description" + } + }, "PROJECT-EDITOR": { "TITLE": { "NEW": "New Project", From b0923b87d997254cfbf01559c88141e2cfacf870 Mon Sep 17 00:00:00 2001 From: annabakouli Date: Fri, 15 Dec 2017 18:57:41 +0200 Subject: [PATCH 2/3] no message --- .../main/java/eu/eudat/EuDatApplication.java | 6 + .../configurations/WebMVCConfiguration.java | 21 +++ .../main/java/eu/eudat/controllers/DMPs.java | 13 +- .../controllers/DashBoardController.java | 8 +- .../java/eu/eudat/controllers/Datasets.java | 13 +- .../main/java/eu/eudat/controllers/Login.java | 36 ++++ .../java/eu/eudat/controllers/Projects.java | 17 +- .../eu/eudat/dao/entities/UserInfoDao.java | 4 +- .../eudat/dao/entities/UserInfoDaoImpl.java | 18 -- .../dao/entities/security/CredentialDao.java | 13 ++ .../entities/security/CredentialDaoImpl.java | 19 ++ .../dao/entities/security/UserAuthDao.java | 15 -- .../entities/security/UserAuthDaoImpl.java | 51 ------ .../dao/entities/security/UserTokenDao.java | 13 ++ .../entities/security/UserTokenDaoImpl.java | 18 ++ .../java/eu/eudat/entities/Credential.java | 116 ++++++++++++ .../main/java/eu/eudat/entities/UserInfo.java | 48 ++--- .../java/eu/eudat/entities/UserToken.java | 62 +++++++ .../eu/eudat/entities/security/UserAuth.java | 61 ------- .../handlers/PrincipalArgumentResolver.java | 33 ++++ .../src/main/java/eu/eudat/login/Login.java | 170 ------------------ .../eu/eudat/models/login/Credentials.java | 25 +++ .../eudat/models/responses/ResponseItem.java | 52 ++++++ .../eu/eudat/models/security/Principal.java | 56 ++++++ .../CustomAuthenticationProvider.java | 43 +---- .../validators/GoogleTokenValidator.java | 35 +++- .../validators/NativeTokenValidator.java | 5 +- .../security/validators/TokenValidator.java | 3 +- .../eudat/services/AuthenticationService.java | 67 +++++++ 29 files changed, 620 insertions(+), 421 deletions(-) create mode 100644 dmp-backend/src/main/java/eu/eudat/configurations/WebMVCConfiguration.java create mode 100644 dmp-backend/src/main/java/eu/eudat/controllers/Login.java create mode 100644 dmp-backend/src/main/java/eu/eudat/dao/entities/security/CredentialDao.java create mode 100644 dmp-backend/src/main/java/eu/eudat/dao/entities/security/CredentialDaoImpl.java delete mode 100644 dmp-backend/src/main/java/eu/eudat/dao/entities/security/UserAuthDao.java delete mode 100644 dmp-backend/src/main/java/eu/eudat/dao/entities/security/UserAuthDaoImpl.java create mode 100644 dmp-backend/src/main/java/eu/eudat/dao/entities/security/UserTokenDao.java create mode 100644 dmp-backend/src/main/java/eu/eudat/dao/entities/security/UserTokenDaoImpl.java create mode 100644 dmp-backend/src/main/java/eu/eudat/entities/Credential.java create mode 100644 dmp-backend/src/main/java/eu/eudat/entities/UserToken.java delete mode 100644 dmp-backend/src/main/java/eu/eudat/entities/security/UserAuth.java create mode 100644 dmp-backend/src/main/java/eu/eudat/handlers/PrincipalArgumentResolver.java delete mode 100644 dmp-backend/src/main/java/eu/eudat/login/Login.java create mode 100644 dmp-backend/src/main/java/eu/eudat/models/login/Credentials.java create mode 100644 dmp-backend/src/main/java/eu/eudat/models/responses/ResponseItem.java create mode 100644 dmp-backend/src/main/java/eu/eudat/models/security/Principal.java create mode 100644 dmp-backend/src/main/java/eu/eudat/services/AuthenticationService.java diff --git a/dmp-backend/src/main/java/eu/eudat/EuDatApplication.java b/dmp-backend/src/main/java/eu/eudat/EuDatApplication.java index 39f2c2410..fe4b30503 100644 --- a/dmp-backend/src/main/java/eu/eudat/EuDatApplication.java +++ b/dmp-backend/src/main/java/eu/eudat/EuDatApplication.java @@ -1,13 +1,19 @@ package eu.eudat; +import eu.eudat.handlers.PrincipalArgumentResolver; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.web.method.support.HandlerMethodArgumentResolver; + +import java.util.List; /** * Created by ikalyvas on 12/15/2017. */ @SpringBootApplication public class EuDatApplication { + + public static void main(String[] args) { System.setProperty("spring.devtools.restart.enabled", "true"); SpringApplication.run(EuDatApplication.class, args); diff --git a/dmp-backend/src/main/java/eu/eudat/configurations/WebMVCConfiguration.java b/dmp-backend/src/main/java/eu/eudat/configurations/WebMVCConfiguration.java new file mode 100644 index 000000000..449ca039f --- /dev/null +++ b/dmp-backend/src/main/java/eu/eudat/configurations/WebMVCConfiguration.java @@ -0,0 +1,21 @@ +package eu.eudat.configurations; + +import eu.eudat.handlers.PrincipalArgumentResolver; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.method.support.HandlerMethodArgumentResolver; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; + +import java.util.List; + +/** + * Created by ikalyvas on 12/15/2017. + */ +@Configuration +public class WebMVCConfiguration extends WebMvcConfigurerAdapter { + + + @Override + public void addArgumentResolvers(List argumentResolvers) { + argumentResolvers.add(new PrincipalArgumentResolver()); + } +} diff --git a/dmp-backend/src/main/java/eu/eudat/controllers/DMPs.java b/dmp-backend/src/main/java/eu/eudat/controllers/DMPs.java index 1b0665b31..92e805fde 100644 --- a/dmp-backend/src/main/java/eu/eudat/controllers/DMPs.java +++ b/dmp-backend/src/main/java/eu/eudat/controllers/DMPs.java @@ -15,6 +15,7 @@ import eu.eudat.models.dmp.DataManagementPlan; import eu.eudat.models.dmp.DataManagementPlanTableRequest; import eu.eudat.models.helpers.DataTableData; +import eu.eudat.models.responses.ResponseItem; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; @@ -68,27 +69,27 @@ public class DMPs { @RequestMapping(method = RequestMethod.POST, value = { "/dmps/getPaged" }, consumes = "application/json", produces="application/json") - public @ResponseBody ResponseEntity> getPaged(@RequestBody DataManagementPlanTableRequest dataManagementPlanTableRequest) { + public @ResponseBody ResponseItem> getPaged(@RequestBody DataManagementPlanTableRequest dataManagementPlanTableRequest) { try { DataTableData dataTable = new DataManagementPlanManager().getPaged(dMPDao, dataManagementPlanTableRequest); - return ResponseEntity.status(HttpStatus.OK).body(dataTable); + return new ResponseItem>().status(HttpStatus.OK).payload(dataTable); } catch (Exception ex) { ex.printStackTrace(); - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null); + return new ResponseItem>().status(HttpStatus.BAD_REQUEST).message(ex.getMessage()); } } @RequestMapping(method = RequestMethod.GET, value = { "/dmps/getSingle/{id}" }, produces="application/json") - public @ResponseBody ResponseEntity getPaged(@PathVariable String id) { + public @ResponseBody ResponseItem getPaged(@PathVariable String id) { try { eu.eudat.models.dmp.DataManagementPlan project = new DataManagementPlanManager().getSingle(dMPDao, id); - return ResponseEntity.status(HttpStatus.OK).body(project); + return new ResponseItem().status(HttpStatus.OK).payload(project); } catch (Exception ex) { ex.printStackTrace(); - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null); + return new ResponseItem().status(HttpStatus.BAD_REQUEST).message(ex.getMessage()); } } diff --git a/dmp-backend/src/main/java/eu/eudat/controllers/DashBoardController.java b/dmp-backend/src/main/java/eu/eudat/controllers/DashBoardController.java index 9df9d3842..ea52b4541 100644 --- a/dmp-backend/src/main/java/eu/eudat/controllers/DashBoardController.java +++ b/dmp-backend/src/main/java/eu/eudat/controllers/DashBoardController.java @@ -3,6 +3,8 @@ package eu.eudat.controllers; import java.util.Map; import java.util.UUID; +import eu.eudat.models.responses.ResponseItem; +import eu.eudat.models.security.Principal; import org.json.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; @@ -38,14 +40,14 @@ public class DashBoardController { @Autowired private ProjectDao projectDao; @RequestMapping(method = RequestMethod.GET, value = { "/dashboard/getStatistics" }, produces="application/json") - public ResponseEntity getStatistics(){ + public ResponseItem getStatistics(Principal principal){ try { DashBoardStatistics statistics = new DashBoardManager().getStatistics(datasetDao, dMPDao, projectDao); - return ResponseEntity.status(HttpStatus.OK).body(statistics); + return new ResponseItem().status(HttpStatus.OK).payload(statistics); } catch(Exception ex) { ex.printStackTrace(); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null); + return new ResponseItem().status(HttpStatus.INTERNAL_SERVER_ERROR).message(ex.getMessage()); } } } diff --git a/dmp-backend/src/main/java/eu/eudat/controllers/Datasets.java b/dmp-backend/src/main/java/eu/eudat/controllers/Datasets.java index 7fedf775a..235e0f4f6 100644 --- a/dmp-backend/src/main/java/eu/eudat/controllers/Datasets.java +++ b/dmp-backend/src/main/java/eu/eudat/controllers/Datasets.java @@ -14,6 +14,7 @@ import eu.eudat.models.dataset.DatasetTableRequest; import eu.eudat.models.helpers.DataTableData; import eu.eudat.models.project.Project; import eu.eudat.models.project.ProjectTableRequest; +import eu.eudat.models.responses.ResponseItem; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; @@ -68,25 +69,25 @@ public class Datasets { @RequestMapping(method = RequestMethod.POST, value = { "/datasets/getPaged" }, consumes = "application/json", produces="application/json") - public @ResponseBody ResponseEntity> getPaged(@RequestBody DatasetTableRequest datasetTableRequest) { + public @ResponseBody ResponseItem> getPaged(@RequestBody DatasetTableRequest datasetTableRequest) { try { DataTableData dataTable = new DatasetManager().getPaged(datasetDao, datasetTableRequest); - return ResponseEntity.status(HttpStatus.OK).body(dataTable); + return new ResponseItem>().status(HttpStatus.OK).payload(dataTable); } catch (Exception ex) { ex.printStackTrace(); - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null); + return new ResponseItem>().status(HttpStatus.OK).message(ex.getMessage()); } } @RequestMapping(method = RequestMethod.GET, value = { "/datasets/getSingle/{id}" }, produces="application/json") - public @ResponseBody ResponseEntity getPaged(@PathVariable String id) { + public @ResponseBody ResponseItem getPaged(@PathVariable String id) { try { eu.eudat.models.dataset.Dataset dataset = new DatasetManager().getSingle(datasetDao, id); - return ResponseEntity.status(HttpStatus.OK).body(dataset); + return new ResponseItem().status(HttpStatus.OK).payload(dataset); } catch (Exception ex) { ex.printStackTrace(); - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null); + return new ResponseItem().status(HttpStatus.OK).message(ex.getMessage()); } } diff --git a/dmp-backend/src/main/java/eu/eudat/controllers/Login.java b/dmp-backend/src/main/java/eu/eudat/controllers/Login.java new file mode 100644 index 000000000..99a3d70d0 --- /dev/null +++ b/dmp-backend/src/main/java/eu/eudat/controllers/Login.java @@ -0,0 +1,36 @@ +package eu.eudat.controllers; + +import eu.eudat.managers.DataManagementPlanManager; +import eu.eudat.models.dmp.DataManagementPlan; +import eu.eudat.models.dmp.DataManagementPlanTableRequest; +import eu.eudat.models.helpers.DataTableData; +import eu.eudat.models.login.Credentials; +import eu.eudat.models.responses.ResponseItem; +import eu.eudat.models.security.Principal; +import eu.eudat.security.CustomAuthenticationProvider; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.*; + +/** + * Created by ikalyvas on 12/15/2017. + */ +@RestController +@CrossOrigin +@RequestMapping(value = "/login") +public class Login { + + @Autowired + private CustomAuthenticationProvider customAuthenticationProvider; + + @RequestMapping(method = RequestMethod.POST, value = { "/googlelogin" }, consumes = "application/json", produces="application/json") + public @ResponseBody ResponseItem googleLogin(@RequestBody Credentials credentials) { + try { + return new ResponseItem().payload(customAuthenticationProvider.authenticate(credentials)).status(HttpStatus.OK); + + } catch (Exception ex) { + ex.printStackTrace(); + return new ResponseItem().status(HttpStatus.BAD_REQUEST).message(ex.getMessage()); + } + } +} diff --git a/dmp-backend/src/main/java/eu/eudat/controllers/Projects.java b/dmp-backend/src/main/java/eu/eudat/controllers/Projects.java index 1fd32d3d4..c6f71ec23 100644 --- a/dmp-backend/src/main/java/eu/eudat/controllers/Projects.java +++ b/dmp-backend/src/main/java/eu/eudat/controllers/Projects.java @@ -11,6 +11,7 @@ import java.util.stream.Collectors; import javax.transaction.Transactional; +import eu.eudat.models.responses.ResponseItem; import org.apache.commons.lang3.SerializationUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; @@ -94,34 +95,34 @@ public class Projects { @RequestMapping(method = RequestMethod.POST, value = { "/projects/getPaged" }, consumes = "application/json", produces="application/json") - public @ResponseBody ResponseEntity> getPaged(@RequestBody ProjectTableRequest projectTableRequest) { + public @ResponseBody ResponseItem> getPaged(@RequestBody ProjectTableRequest projectTableRequest) { try { DataTableData dataTable = new ProjectManager().getPaged(projectDao, projectTableRequest); - return ResponseEntity.status(HttpStatus.OK).body(dataTable); + return new ResponseItem>().payload(dataTable).status(HttpStatus.OK); } catch (Exception ex) { ex.printStackTrace(); - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null); + return new ResponseItem>().status(HttpStatus.BAD_REQUEST).message(ex.getMessage()); } } @RequestMapping(method = RequestMethod.GET, value = { "/projects/getSingle/{id}" }, produces="application/json") - public @ResponseBody ResponseEntity getPaged(@PathVariable String id) { + public @ResponseBody ResponseItem getPaged(@PathVariable String id) { try { eu.eudat.models.project.Project project = new ProjectManager().getSingle(projectDao, id); - return ResponseEntity.status(HttpStatus.OK).body(project); + return new ResponseItem().payload(project).status(HttpStatus.OK); } catch (Exception ex) { ex.printStackTrace(); - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null); + return new ResponseItem().status(HttpStatus.BAD_REQUEST).message(ex.getMessage()); } } @Transactional @RequestMapping(method = RequestMethod.POST, value = { "/projects/add" }, consumes = "application/json", produces="application/json") - public @ResponseBody ResponseEntity addProject(@RequestBody eu.eudat.models.project.Project project) { + public @ResponseBody ResponseItem addProject(@RequestBody eu.eudat.models.project.Project project) { Project createdProject = projectDao.update(project.toDataModel()); - return ResponseEntity.status(HttpStatus.CREATED).body(createdProject); + return new ResponseItem().payload(createdProject).status(HttpStatus.OK); } diff --git a/dmp-backend/src/main/java/eu/eudat/dao/entities/UserInfoDao.java b/dmp-backend/src/main/java/eu/eudat/dao/entities/UserInfoDao.java index 2f6db17cf..28a9fb1f4 100644 --- a/dmp-backend/src/main/java/eu/eudat/dao/entities/UserInfoDao.java +++ b/dmp-backend/src/main/java/eu/eudat/dao/entities/UserInfoDao.java @@ -15,9 +15,7 @@ public interface UserInfoDao extends Dao { public UserInfo getByIdAndMail(String id, String email); public UserInfo getByMail(String email); - - public UserInfo getByAuthenticationId(String authentication); - + public UserInfo getByUsername(String username); public List getDmpsOfUser(String userID); diff --git a/dmp-backend/src/main/java/eu/eudat/dao/entities/UserInfoDaoImpl.java b/dmp-backend/src/main/java/eu/eudat/dao/entities/UserInfoDaoImpl.java index 00153e50c..7a265be81 100644 --- a/dmp-backend/src/main/java/eu/eudat/dao/entities/UserInfoDaoImpl.java +++ b/dmp-backend/src/main/java/eu/eudat/dao/entities/UserInfoDaoImpl.java @@ -1,7 +1,6 @@ package eu.eudat.dao.entities; import java.util.List; -import java.util.Set; import java.util.UUID; import javax.persistence.NoResultException; @@ -10,7 +9,6 @@ import javax.persistence.TypedQuery; import eu.eudat.dao.JpaDao; import eu.eudat.entities.DMP; import eu.eudat.entities.UserInfo; -import eu.eudat.entities.security.UserAuth; import org.springframework.stereotype.Component; @Component("userInfoDao") @@ -51,22 +49,6 @@ public class UserInfoDaoImpl extends JpaDao implements UserInfoD return null; } } - - @Override - public UserInfo getByAuthenticationId(String authenticationID) { - UserAuth userauth = new UserAuth(); - userauth.setId(UUID.fromString(authenticationID)); - String queryString = "FROM UserInfo userInfo where userInfo.authentication = :auth"; - TypedQuery typedQuery = entityManager.createQuery(queryString, UserInfo.class); - typedQuery.setParameter("auth", userauth); - try { - return typedQuery.getSingleResult(); - } - catch(NoResultException ex) { - return null; - } - } - @Override diff --git a/dmp-backend/src/main/java/eu/eudat/dao/entities/security/CredentialDao.java b/dmp-backend/src/main/java/eu/eudat/dao/entities/security/CredentialDao.java new file mode 100644 index 000000000..4c258d96e --- /dev/null +++ b/dmp-backend/src/main/java/eu/eudat/dao/entities/security/CredentialDao.java @@ -0,0 +1,13 @@ +package eu.eudat.dao.entities.security; + +import eu.eudat.dao.Dao; +import eu.eudat.entities.Credential; +import eu.eudat.entities.UserToken; + +import java.util.UUID; + +/** + * Created by ikalyvas on 12/15/2017. + */ +public interface CredentialDao extends Dao { +} diff --git a/dmp-backend/src/main/java/eu/eudat/dao/entities/security/CredentialDaoImpl.java b/dmp-backend/src/main/java/eu/eudat/dao/entities/security/CredentialDaoImpl.java new file mode 100644 index 000000000..1326c3d49 --- /dev/null +++ b/dmp-backend/src/main/java/eu/eudat/dao/entities/security/CredentialDaoImpl.java @@ -0,0 +1,19 @@ +package eu.eudat.dao.entities.security; + +import eu.eudat.dao.JpaDao; +import eu.eudat.entities.Credential; +import eu.eudat.entities.UserToken; +import org.springframework.stereotype.Component; + +import java.util.UUID; + +/** + * Created by ikalyvas on 12/15/2017. + */ +@Component("credentialDao") +public class CredentialDaoImpl extends JpaDao implements CredentialDao { + @Override + public Credential loadDetails(Credential credential) { + return null; + } +} diff --git a/dmp-backend/src/main/java/eu/eudat/dao/entities/security/UserAuthDao.java b/dmp-backend/src/main/java/eu/eudat/dao/entities/security/UserAuthDao.java deleted file mode 100644 index e1e3c1669..000000000 --- a/dmp-backend/src/main/java/eu/eudat/dao/entities/security/UserAuthDao.java +++ /dev/null @@ -1,15 +0,0 @@ -package eu.eudat.dao.entities.security; - -import java.util.UUID; - -import eu.eudat.dao.Dao; -import eu.eudat.entities.security.UserAuth; - -public interface UserAuthDao extends Dao { - - - public String getPasswordHashOfUser(String username); - - public UserAuth getUserAuthBy(String username); - -} diff --git a/dmp-backend/src/main/java/eu/eudat/dao/entities/security/UserAuthDaoImpl.java b/dmp-backend/src/main/java/eu/eudat/dao/entities/security/UserAuthDaoImpl.java deleted file mode 100644 index 0c1abb399..000000000 --- a/dmp-backend/src/main/java/eu/eudat/dao/entities/security/UserAuthDaoImpl.java +++ /dev/null @@ -1,51 +0,0 @@ -package eu.eudat.dao.entities.security; - -import java.util.UUID; - -import javax.persistence.TypedQuery; - -import eu.eudat.dao.JpaDao; -import eu.eudat.entities.security.UserAuth; -import org.springframework.stereotype.Component; - -@Component("userAuthDaoImpl") -public class UserAuthDaoImpl extends JpaDao implements UserAuthDao { - - @Override - public UserAuth loadDetails(UserAuth t) { - // TODO Auto-generated method stub - return null; - } - - - @Override - public String getPasswordHashOfUser(String username) { - - String queryString = "SELECT userAuth.password FROM UserAuth userAuth where userAuth.username = :username"; - TypedQuery typedQuery = entityManager.createQuery(queryString, String.class); - typedQuery.setParameter("username", username); - try { - return typedQuery.getSingleResult(); - } - catch(Exception ex) { - return null; - } - } - - @Override - public UserAuth getUserAuthBy(String username) { - - String queryString = "FROM UserAuth userAuth where userAuth.username = :username"; - TypedQuery typedQuery = entityManager.createQuery(queryString, UserAuth.class); - typedQuery.setParameter("username", username); - try { - return typedQuery.getSingleResult(); - } - catch(Exception ex) { - return null; - } - } - - - -} diff --git a/dmp-backend/src/main/java/eu/eudat/dao/entities/security/UserTokenDao.java b/dmp-backend/src/main/java/eu/eudat/dao/entities/security/UserTokenDao.java new file mode 100644 index 000000000..2250bfd68 --- /dev/null +++ b/dmp-backend/src/main/java/eu/eudat/dao/entities/security/UserTokenDao.java @@ -0,0 +1,13 @@ +package eu.eudat.dao.entities.security; + +import eu.eudat.dao.Dao; +import eu.eudat.entities.UserToken; + +import java.util.UUID; + +/** + * Created by ikalyvas on 12/15/2017. + */ +public interface UserTokenDao extends Dao { + +} diff --git a/dmp-backend/src/main/java/eu/eudat/dao/entities/security/UserTokenDaoImpl.java b/dmp-backend/src/main/java/eu/eudat/dao/entities/security/UserTokenDaoImpl.java new file mode 100644 index 000000000..0ce6b797d --- /dev/null +++ b/dmp-backend/src/main/java/eu/eudat/dao/entities/security/UserTokenDaoImpl.java @@ -0,0 +1,18 @@ +package eu.eudat.dao.entities.security; + +import eu.eudat.dao.JpaDao; +import eu.eudat.entities.UserToken; +import org.springframework.stereotype.Component; + +import java.util.UUID; + +/** + * Created by ikalyvas on 12/15/2017. + */ +@Component("userTokenDao") +public class UserTokenDaoImpl extends JpaDao implements UserTokenDao { + @Override + public UserToken loadDetails(UserToken userToken) { + return null; + } +} diff --git a/dmp-backend/src/main/java/eu/eudat/entities/Credential.java b/dmp-backend/src/main/java/eu/eudat/entities/Credential.java new file mode 100644 index 000000000..c2543108e --- /dev/null +++ b/dmp-backend/src/main/java/eu/eudat/entities/Credential.java @@ -0,0 +1,116 @@ +package eu.eudat.entities; + +import org.hibernate.annotations.GenericGenerator; + +import javax.persistence.*; +import java.util.Date; +import java.util.UUID; + +/** + * Created by ikalyvas on 12/15/2017. + */ +@Entity +@Table(name="\"Credential\"") +public class Credential { + + @Id + @Column(name = "\"ID\"", updatable = false, nullable = false, columnDefinition = "BINARY(16)") + private UUID id; + + @ManyToOne + @JoinColumn(name="userid", nullable=false) + private UserInfo userInfo; + + @Column(name = "status", nullable = false) + private Integer status; + + @Column(name = "provider", nullable = false) + private Integer provider; + @Column(name = "publicValue", nullable = false) + private String publicValue; + @Column(name = "secret", nullable = false) + private String secret; + @Column(name = "creationtime", nullable = false) + private Date creationTime; + @Column(name = "lastupdatetime", nullable = false) + private Date lastUpdateTime; + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public UserInfo getUserInfo() { + return userInfo; + } + + public void setUserInfo(UserInfo userInfo) { + this.userInfo = userInfo; + } + + public Integer getStatus() { + return status; + } + + public void setStatus(Integer status) { + this.status = status; + } + + public Integer getProvider() { + return provider; + } + + public void setProvider(Integer provider) { + this.provider = provider; + } + + public String getPublicValue() { + return publicValue; + } + + public void setPublicValue(String publicValue) { + this.publicValue = publicValue; + } + + public String getSecret() { + return secret; + } + + public void setSecret(String secret) { + this.secret = secret; + } + + public Date getCreationTime() { + return creationTime; + } + + public void setCreationTime(Date creationTime) { + this.creationTime = creationTime; + } + + public Date getLastUpdateTime() { + return lastUpdateTime; + } + + public void setLastUpdateTime(Date lastUpdateTime) { + this.lastUpdateTime = lastUpdateTime; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + Credential that = (Credential) o; + + return provider.intValue() == that.provider.intValue(); + } + + @Override + public int hashCode() { + return provider.intValue(); + } +} diff --git a/dmp-backend/src/main/java/eu/eudat/entities/UserInfo.java b/dmp-backend/src/main/java/eu/eudat/entities/UserInfo.java index 471e50253..4c534f4db 100644 --- a/dmp-backend/src/main/java/eu/eudat/entities/UserInfo.java +++ b/dmp-backend/src/main/java/eu/eudat/entities/UserInfo.java @@ -2,20 +2,11 @@ package eu.eudat.entities; import java.io.Serializable; import java.util.Date; +import java.util.HashSet; import java.util.Set; import java.util.UUID; -import java.util.stream.Collectors; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.JoinTable; -import javax.persistence.OneToMany; -import javax.persistence.OneToOne; -import javax.persistence.Table; +import javax.persistence.*; import org.hibernate.annotations.GenericGenerator; import org.hibernate.annotations.Type; @@ -23,8 +14,6 @@ import org.hibernate.annotations.Type; import com.fasterxml.jackson.annotation.JsonIdentityInfo; import com.fasterxml.jackson.annotation.ObjectIdGenerators; -import eu.eudat.entities.security.UserAuth; - @Entity @Table(name="\"UserInfo\"") @@ -49,10 +38,6 @@ public class UserInfo implements Serializable,DataEntity{ @Column(name = "usertype", nullable = false) private Short usertype; // 0 internal, 1 external - @OneToOne(fetch = FetchType.LAZY) - @JoinColumn(name = "authentication", nullable = true) - private UserAuth authentication; - @Column(name = "verified_email", nullable = true) private Boolean verified_email = null; @@ -78,13 +63,9 @@ public class UserInfo implements Serializable,DataEntity{ inverseJoinColumns={@JoinColumn(name="dmp", referencedColumnName="\"ID\"")} ) private Set dmps; - - - /* - public Set getDmpsNonDeleted(){ - return getDmps().parallelStream().filter(dmp -> dmp.getStatus()>=0).collect(Collectors.toSet()); - } - */ + + @OneToMany(mappedBy="userInfo",fetch = FetchType.LAZY) + Set credentials = new HashSet<>(); public Set getDmps() { return dmps; @@ -142,14 +123,6 @@ public class UserInfo implements Serializable,DataEntity{ this.usertype = usertype; } - public UserAuth getAuthentication() { - return authentication; - } - - public void setAuthentication(UserAuth authentication) { - this.authentication = authentication; - } - public Boolean getVerified_email() { return verified_email; } @@ -173,7 +146,12 @@ public class UserInfo implements Serializable,DataEntity{ public void setAdditionalinfo(String additionalinfo) { this.additionalinfo = additionalinfo; } - - - + + public Set getCredentials() { + return credentials; + } + + public void setCredentials(Set credentials) { + this.credentials = credentials; + } } diff --git a/dmp-backend/src/main/java/eu/eudat/entities/UserToken.java b/dmp-backend/src/main/java/eu/eudat/entities/UserToken.java new file mode 100644 index 000000000..d38595483 --- /dev/null +++ b/dmp-backend/src/main/java/eu/eudat/entities/UserToken.java @@ -0,0 +1,62 @@ +package eu.eudat.entities; + +import javax.persistence.*; +import java.util.Date; +import java.util.UUID; + +/** + * Created by ikalyvas on 12/15/2017. + */ +@Entity +@Table(name="\"UserToken\"") +public class UserToken implements DataEntity{ + + private static final long serialVersionUID = 1225151430484658395L; + + @Id + @Column(name = "token", updatable = false, nullable = false, columnDefinition = "BINARY(16)") + private UUID token; + + @OneToOne(fetch = FetchType.EAGER) + @JoinColumn(name = "userid", nullable = false) + private UserInfo user; + + @Column(name = "issuedat", nullable = false) + private Date issuedAt = null; + + + @Column(name = "expiresat", nullable = false) + private Date expiresAt = null; + + public UUID getToken() { + return token; + } + + public void setToken(UUID token) { + this.token = token; + } + + public UserInfo getUser() { + return user; + } + + public void setUser(UserInfo user) { + this.user = user; + } + + public Date getIssuedAt() { + return issuedAt; + } + + public void setIssuedAt(Date issuedAt) { + this.issuedAt = issuedAt; + } + + public Date getExpiresAt() { + return expiresAt; + } + + public void setExpiresAt(Date expiresAt) { + this.expiresAt = expiresAt; + } +} diff --git a/dmp-backend/src/main/java/eu/eudat/entities/security/UserAuth.java b/dmp-backend/src/main/java/eu/eudat/entities/security/UserAuth.java deleted file mode 100644 index 8aa51577c..000000000 --- a/dmp-backend/src/main/java/eu/eudat/entities/security/UserAuth.java +++ /dev/null @@ -1,61 +0,0 @@ -package eu.eudat.entities.security; - -import java.util.UUID; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import javax.persistence.Table; - -import org.hibernate.annotations.GenericGenerator; - -import com.fasterxml.jackson.annotation.JsonIdentityInfo; -import com.fasterxml.jackson.annotation.ObjectIdGenerators; - -@Entity -@Table(name="\"UserAuth\"") -@JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="id") -public class UserAuth { - - @Id - @GeneratedValue - @GenericGenerator(name = "uuid2", strategy = "uuid2") - @Column(name = "id", updatable = false, nullable = false, columnDefinition = "BINARY(16)") - private UUID id; - - @Column(name = "username", nullable = false) - private String username; - - @Column(name = "password", nullable = false) - private String password; //hash-encoded password - - - - public UUID getId() { - return id; - } - - public void setId(UUID id) { - this.id = id; - } - - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } - - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } - - - -} diff --git a/dmp-backend/src/main/java/eu/eudat/handlers/PrincipalArgumentResolver.java b/dmp-backend/src/main/java/eu/eudat/handlers/PrincipalArgumentResolver.java new file mode 100644 index 000000000..96862f1c0 --- /dev/null +++ b/dmp-backend/src/main/java/eu/eudat/handlers/PrincipalArgumentResolver.java @@ -0,0 +1,33 @@ +package eu.eudat.handlers; + +import eu.eudat.models.security.Principal; +import org.springframework.core.MethodParameter; +import org.springframework.web.bind.support.WebDataBinderFactory; +import org.springframework.web.context.request.NativeWebRequest; +import org.springframework.web.method.support.HandlerMethodArgumentResolver; +import org.springframework.web.method.support.ModelAndViewContainer; + +import java.util.Date; +import java.util.UUID; + +/** + * Created by ikalyvas on 12/15/2017. + */ +public final class PrincipalArgumentResolver implements HandlerMethodArgumentResolver { + + @Override + public boolean supportsParameter(MethodParameter methodParameter) { + return methodParameter.getParameterType().equals(Principal.class); + } + + @Override + public Object resolveArgument(MethodParameter methodParameter,ModelAndViewContainer modelAndViewContainer,NativeWebRequest nativeWebRequest,WebDataBinderFactory webDataBinderFactory) throws Exception { + Principal principal = new Principal(); + principal.setName("Giannis"); + principal.setId(UUID.randomUUID()); + principal.setExpiresAt(new Date()); + principal.setToken(UUID.randomUUID()); + return principal; + } + +} \ No newline at end of file diff --git a/dmp-backend/src/main/java/eu/eudat/login/Login.java b/dmp-backend/src/main/java/eu/eudat/login/Login.java deleted file mode 100644 index 574a63f11..000000000 --- a/dmp-backend/src/main/java/eu/eudat/login/Login.java +++ /dev/null @@ -1,170 +0,0 @@ -package eu.eudat.login; - -import java.io.Serializable; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.security.SecureRandom; -import java.util.concurrent.TimeUnit; - -import javax.annotation.PostConstruct; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.CrossOrigin; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.ResponseBody; -import org.springframework.web.bind.annotation.RestController; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; - -import eu.eudat.dao.entities.UserInfoDao; -import eu.eudat.dao.entities.security.UserAuthDao; -import eu.eudat.entities.UserInfo; -import eu.eudat.entities.security.UserAuth; -import eu.eudat.security.TokenSessionManager; - - -@RestController -@CrossOrigin -public class Login { - - - @Autowired private UserInfoDao userInfoDao; - @Autowired private UserAuthDao userAuthDao; - - @Autowired private TokenSessionManager tokenSessionManager; - - - - @RequestMapping(method = RequestMethod.POST, value = { "/nativeLogin" }, consumes = "application/json", produces = "application/json") - public @ResponseBody ResponseEntity nativeLogin(@RequestBody Credentials credentials) { - - String token = null; - - if(credentials == null || credentials.getPassword() == null || credentials.getUsername() ==null || - credentials.getPassword().isEmpty() || credentials.getUsername().isEmpty()) { - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Username and/or password cannot be empty."); - } - - UserAuth userAuth = userAuthDao.getUserAuthBy(credentials.getUsername()); - - if(userAuth == null) userAuth = new UserAuth(); - - String userHash = userAuth.getPassword(); - - String providedHash = ""; - try { - providedHash = tokenSessionManager.hashPassword(credentials.getPassword()); - } - catch(NoSuchAlgorithmException ex) { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Internal error. Cannot authenticate."); - } - - if(userHash == null || "".equals(userHash) || !userHash.equals(providedHash)) { - return ResponseEntity.status(HttpStatus.NOT_ACCEPTABLE).body("Wrong username or password"); - } - else if(userHash.equals(providedHash)) { - // create a token - token = tokenSessionManager.generateRandomAlphanumeric(512); - // add it to the eu.eudat.cache - tokenSessionManager.set(token, credentials.getUsername()); - } - - //get also the additional info of the user (if he has) - UserInfo userInfo = userInfoDao.getByAuthenticationId((userAuth.getId() == null) ? "" : userAuth.getId().toString()); - if(userInfo == null) userInfo = new UserInfo(); - - Response response = new Response(); - response.setToken(token); - response.setEmail(userInfo.getEmail()); - response.setName(userInfo.getName()); - response.setUsername(credentials.getUsername()); - - return new ResponseEntity(response.toJson(), HttpStatus.OK); - - } - - -} - -class Credentials implements Serializable{ - - private static final long serialVersionUID = 3519634756673886633L; - - private String username; - private String password; - - public String getUsername() { - return username; - } - public void setUsername(String username) { - this.username = username; - } - public String getPassword() { - return password; - } - public void setPassword(String password) { - this.password = password; - } - -} - -class Response implements Serializable { - - private static final long serialVersionUID = -3855159530298902864L; - - private String token; - private String username; - private String email; - private String name; - - - public String getToken() { - return token; - } - - public void setToken(String token) { - this.token = token; - } - - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } - - public String getEmail() { - return email; - } - - public void setEmail(String email) { - this.email = email; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - - public String toJson() { - ObjectMapper objMapper = new ObjectMapper(); - try { - return objMapper.writeValueAsString(this); - } - catch(JsonProcessingException ex) { - return "{}"; - } - } - -} - diff --git a/dmp-backend/src/main/java/eu/eudat/models/login/Credentials.java b/dmp-backend/src/main/java/eu/eudat/models/login/Credentials.java new file mode 100644 index 000000000..72786d291 --- /dev/null +++ b/dmp-backend/src/main/java/eu/eudat/models/login/Credentials.java @@ -0,0 +1,25 @@ +package eu.eudat.models.login; + +/** + * Created by ikalyvas on 12/15/2017. + */ +public class Credentials { + private String username; + private String secret; + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getSecret() { + return secret; + } + + public void setSecret(String secret) { + this.secret = secret; + } +} diff --git a/dmp-backend/src/main/java/eu/eudat/models/responses/ResponseItem.java b/dmp-backend/src/main/java/eu/eudat/models/responses/ResponseItem.java new file mode 100644 index 000000000..1ea0e57b1 --- /dev/null +++ b/dmp-backend/src/main/java/eu/eudat/models/responses/ResponseItem.java @@ -0,0 +1,52 @@ +package eu.eudat.models.responses; + +import org.springframework.http.HttpStatus; + +/** + * Created by ikalyvas on 12/15/2017. + */ +public class ResponseItem { + private HttpStatus statusCode; + private String message; + private T payload; + + public HttpStatus getStatusCode() { + return statusCode; + } + + public void setStatusCode(HttpStatus statusCode) { + this.statusCode = statusCode; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + public T getPayload() { + return payload; + } + + public void setpayload(T payload) { + this.payload = payload; + } + + public ResponseItem status(HttpStatus statusCode){ + this.statusCode = statusCode; + return this; + } + + public ResponseItem message(String message){ + this.message = message; + return this; + } + + public ResponseItem payload(T payload){ + this.payload = payload; + return this; + } + +} diff --git a/dmp-backend/src/main/java/eu/eudat/models/security/Principal.java b/dmp-backend/src/main/java/eu/eudat/models/security/Principal.java new file mode 100644 index 000000000..f1d6509ed --- /dev/null +++ b/dmp-backend/src/main/java/eu/eudat/models/security/Principal.java @@ -0,0 +1,56 @@ +package eu.eudat.models.security; + +import java.util.Date; +import java.util.Set; +import java.util.UUID; + +/** + * Created by ikalyvas on 12/15/2017. + */ +public class Principal { + private UUID id; + private UUID token; + private String name; + private Date expiresAt; + private Set roles; + + 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 Date getExpiresAt() { + return expiresAt; + } + + public void setExpiresAt(Date expiresAt) { + this.expiresAt = expiresAt; + } + + public Set getRoles() { + return roles; + } + + public void setRoles(Set roles) { + this.roles = roles; + } +} diff --git a/dmp-backend/src/main/java/eu/eudat/security/CustomAuthenticationProvider.java b/dmp-backend/src/main/java/eu/eudat/security/CustomAuthenticationProvider.java index 3e5934b7e..3a2920dbe 100644 --- a/dmp-backend/src/main/java/eu/eudat/security/CustomAuthenticationProvider.java +++ b/dmp-backend/src/main/java/eu/eudat/security/CustomAuthenticationProvider.java @@ -4,6 +4,8 @@ import java.util.ArrayList; import javax.naming.NameAlreadyBoundException; +import eu.eudat.models.login.Credentials; +import eu.eudat.models.security.Principal; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.authentication.AuthenticationServiceException; @@ -20,7 +22,7 @@ import eu.eudat.security.validators.NativeTokenValidator; import eu.eudat.security.validators.TokenValidator; @Component -public class CustomAuthenticationProvider implements AuthenticationProvider { +public class CustomAuthenticationProvider { @Autowired private UserInfoDao userInfoDao; @@ -28,43 +30,14 @@ public class CustomAuthenticationProvider implements AuthenticationProvider { @Autowired private GoogleTokenValidator googleTokenValidator; @Autowired private NativeTokenValidator nativeTokenValidator; - - @Override - public Authentication authenticate(Authentication authentication) throws AuthenticationException { - - if (authentication != null) { - - String token = (String)authentication.getCredentials(); - TokenValidator tokenValidator = null; - - if(TokenAuthenticationFilter.HEADER_GOOGLE_TOKEN_FIELD.equals(authentication.getPrincipal())) - tokenValidator = googleTokenValidator; - else if(TokenAuthenticationFilter.HEADER_NATIVE_TOKEN_FIELD.equals(authentication.getPrincipal())) - tokenValidator = nativeTokenValidator; - else - throw new AuthenticationServiceException("The appropriate http headers have not been set. Please check!"); - - UserInfo userInfo; + public Principal authenticate(Credentials credentials) throws AuthenticationException { + String token = credentials.getSecret(); try { - userInfo = tokenValidator.validateToken(token); + Principal principal = googleTokenValidator.validateToken(token); + return principal; } catch (NonValidTokenException e) { - System.out.println("Could not validate a user by his token! Reason: "+e.getMessage()); + System.out.println("Could not validate a user by his token! Reason: " + e.getMessage()); throw new AuthenticationServiceException("Token validation failed - Not a valid token"); } - - // if reached this point, authentication is ok, so return just an instance where the principal is the UserInfo ID - //(to have it at the webservices calls - it's ESSENTIAL) while the password can be whatever... - return new UsernamePasswordAuthenticationToken(userInfo.getId(), authentication.getCredentials(), new ArrayList<>()); - - } - else - throw new AuthenticationServiceException("Authentication failed"); - } - - @Override - public boolean supports(Class authentication) { - return authentication.equals(UsernamePasswordAuthenticationToken.class); - } - } \ No newline at end of file diff --git a/dmp-backend/src/main/java/eu/eudat/security/validators/GoogleTokenValidator.java b/dmp-backend/src/main/java/eu/eudat/security/validators/GoogleTokenValidator.java index 5cab1485c..9188a606d 100644 --- a/dmp-backend/src/main/java/eu/eudat/security/validators/GoogleTokenValidator.java +++ b/dmp-backend/src/main/java/eu/eudat/security/validators/GoogleTokenValidator.java @@ -2,10 +2,13 @@ package eu.eudat.security.validators; import java.io.IOException; import java.security.GeneralSecurityException; -import java.util.Arrays; -import java.util.Date; -import java.util.List; +import java.security.Principal; +import java.util.*; +import eu.eudat.dao.entities.security.CredentialDao; +import eu.eudat.entities.Credential; +import eu.eudat.entities.UserToken; +import eu.eudat.services.AuthenticationService; import org.springframework.beans.factory.annotation.Autowired; import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken; @@ -28,8 +31,8 @@ public class GoogleTokenValidator implements TokenValidator { private static final HttpTransport transport = new NetHttpTransport(); @Autowired private UserInfoDao userInfoDao; - - + @Autowired private CredentialDao credentialDao; + @Autowired private AuthenticationService authenticationService; private static final List clientIDs = Arrays.asList( "1010962018903-glegmqudqtl1lub0150vacopbu06lgsg.apps.googleusercontent.com", "1010962018903-glegmqudqtl1lub0150vacopbu06lgsg.apps.googleusercontent.com" @@ -48,7 +51,7 @@ public class GoogleTokenValidator implements TokenValidator { @Override - public UserInfo validateToken(String token) throws NonValidTokenException { + public eu.eudat.models.security.Principal validateToken(String token) throws NonValidTokenException { GoogleIdToken idToken = null; try { @@ -72,6 +75,15 @@ public class GoogleTokenValidator implements TokenValidator { UserInfo userInfo = userInfoDao.getByMail(payload.getEmail()); + Credential credential = new Credential(); + credential.setCreationTime(new Date()); + credential.setId(UUID.randomUUID()); + credential.setLastUpdateTime(new Date()); + credential.setProvider(1); + credential.setSecret(token); + credential.setPublicValue(userInfo.getName()); + credential.setUserInfo(userInfo); + if(userInfo == null) { //means not existing in db, so create one userInfo = new UserInfo(); userInfo.setName((String)payload.get("name")); @@ -82,13 +94,22 @@ public class GoogleTokenValidator implements TokenValidator { userInfo.setAuthorization_level(new Short("1")); userInfo.setUsertype(new Short("1")); userInfo = userInfoDao.create(userInfo); + credential = credentialDao.create(credential); } else { userInfo.setLastloggedin(new Date()); + Set credentials = userInfo.getCredentials(); + credentials.add(credential); userInfo = userInfoDao.update(userInfo); } + + UserToken userToken = new UserToken(); + userToken.setUser(userInfo); + userToken.setIssuedAt(new Date()); + userToken.setToken(UUID.randomUUID()); + userToken.setExpiresAt(new Date()); - return userInfo; + return authenticationService.Touch(userToken.getToken()); } diff --git a/dmp-backend/src/main/java/eu/eudat/security/validators/NativeTokenValidator.java b/dmp-backend/src/main/java/eu/eudat/security/validators/NativeTokenValidator.java index 9609b7c99..89c9a2e13 100644 --- a/dmp-backend/src/main/java/eu/eudat/security/validators/NativeTokenValidator.java +++ b/dmp-backend/src/main/java/eu/eudat/security/validators/NativeTokenValidator.java @@ -1,5 +1,6 @@ package eu.eudat.security.validators; +import eu.eudat.models.security.Principal; import org.springframework.beans.factory.annotation.Autowired; import eu.eudat.dao.entities.UserInfoDao; @@ -15,11 +16,11 @@ public class NativeTokenValidator implements TokenValidator { @Autowired private UserInfoDao userInfoDao; @Override - public UserInfo validateToken(String token) throws NonValidTokenException { + public Principal validateToken(String token) throws NonValidTokenException { String tokenUser = tokenSessionManager.getUser(token); if(tokenUser==null || tokenUser.isEmpty()) throw new NonValidTokenException("Login session has expired! Need to eu.eudat.login again!"); - return userInfoDao.getByUsername(tokenUser); + return new Principal(); } diff --git a/dmp-backend/src/main/java/eu/eudat/security/validators/TokenValidator.java b/dmp-backend/src/main/java/eu/eudat/security/validators/TokenValidator.java index 0a0cdb6fa..e7f0ce7de 100644 --- a/dmp-backend/src/main/java/eu/eudat/security/validators/TokenValidator.java +++ b/dmp-backend/src/main/java/eu/eudat/security/validators/TokenValidator.java @@ -2,9 +2,10 @@ package eu.eudat.security.validators; import eu.eudat.entities.UserInfo; import eu.eudat.exceptions.NonValidTokenException; +import eu.eudat.models.security.Principal; public interface TokenValidator { - public UserInfo validateToken(String token) throws NonValidTokenException; + public Principal validateToken(String token) throws NonValidTokenException; } diff --git a/dmp-backend/src/main/java/eu/eudat/services/AuthenticationService.java b/dmp-backend/src/main/java/eu/eudat/services/AuthenticationService.java new file mode 100644 index 000000000..86d377c51 --- /dev/null +++ b/dmp-backend/src/main/java/eu/eudat/services/AuthenticationService.java @@ -0,0 +1,67 @@ +package eu.eudat.services; + +import eu.eudat.dao.entities.UserInfoDao; +import eu.eudat.dao.entities.security.UserTokenDao; +import eu.eudat.entities.UserInfo; +import eu.eudat.entities.UserToken; +import eu.eudat.models.security.Principal; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import javax.xml.ws.ServiceMode; +import java.util.Date; +import java.util.List; +import java.util.UUID; + +/** + * Created by ikalyvas on 12/15/2017. + */ +@Service +public class AuthenticationService { + @Autowired + UserTokenDao userTokenDao; + @Autowired + UserInfoDao userInfoDao; + + public Principal Touch(UUID token) + { + UserToken tokenEntry = userTokenDao.read(token); + if (tokenEntry == null || tokenEntry.getExpiresAt().before(new Date())) return null; + + Principal principal = this.Touch(tokenEntry); + + return principal; + } + + public void Logout(UUID token) + { + UserToken tokenEntry = userTokenDao.read(token); + userTokenDao.delete(tokenEntry); + } + + private Principal Touch(UserToken token) + { + if (token == null || token.getExpiresAt().before(new Date())) return null; + + UserInfo user = this.userInfoDao.read(token.getUser().getId()); + if (user == null /*|| user.Status != ActivityStatus.Active*/) return null; + + //List appRoles = this._unitOfWork.UserRoles.GetAll().Where(x => x.UserId == token.UserId /*&& x.Status == ActivityStatus.Active*/).ToList(); + + Principal principal = new Principal(); + principal.setId(user.getId()); + principal.setToken(token.getToken()); + principal.setExpiresAt(token.getExpiresAt()); + principal.setName(user.getName()); + + /*foreach (UserRole item in appRoles) + { + if (principal.AppRoles == null) principal.AppRoles = new HashSet(); + principal.AppRoles.Add(item.Role); + } + + if (this._config.Refresh) token.ExpiresAt = DateTime.UtcNow.AddMinutes(this._config.Lifetime); + */ + return principal; + } +} From f3fdfa1dbf4e214fa73a9f6842b161fec5ca5778 Mon Sep 17 00:00:00 2001 From: ikalyvas Date: Sun, 17 Dec 2017 23:34:24 +0200 Subject: [PATCH 3/3] criteria application for queries with pagination --- .../main/java/eu/eudat/controllers/DMPs.java | 709 +++++++++--------- .../controllers/DashBoardController.java | 18 +- .../eudat/controllers/DataRepositories.java | 134 ++-- .../controllers/DatasetProfileController.java | 8 +- .../java/eu/eudat/controllers/Datasets.java | 505 +++++++------ .../main/java/eu/eudat/controllers/Login.java | 6 +- .../java/eu/eudat/controllers/Projects.java | 452 ++++++----- .../context/DatabaseContext.java | 42 ++ .../service/DatabaseService.java | 27 + .../java/eu/eudat/dao/entities/DMPDao.java | 16 +- .../eu/eudat/dao/entities/DMPDaoImpl.java | 67 +- .../eudat/dao/entities/DataRepositoryDao.java | 9 +- .../dao/entities/DataRepositoryDaoImpl.java | 45 +- .../eu/eudat/dao/entities/DatasetDao.java | 14 +- .../eu/eudat/dao/entities/DatasetDaoImpl.java | 56 +- .../eudat/dao/entities/DatasetServiceDao.java | 2 +- .../eu/eudat/dao/entities/ProjectDao.java | 17 +- .../eu/eudat/dao/entities/ProjectDaoImpl.java | 70 +- .../src/main/java/eu/eudat/entities/DMP.java | 12 +- .../java/eu/eudat/entities/DataEntity.java | 5 +- .../eu/eudat/entities/DataRepository.java | 12 +- .../main/java/eu/eudat/entities/Dataset.java | 18 +- .../eu/eudat/entities/DatasetProfile.java | 14 +- .../java/eu/eudat/entities/Organisation.java | 14 +- .../main/java/eu/eudat/entities/Project.java | 15 +- .../main/java/eu/eudat/entities/Registry.java | 14 +- .../java/eu/eudat/entities/Researcher.java | 14 +- .../main/java/eu/eudat/entities/Service.java | 14 +- .../main/java/eu/eudat/entities/UserInfo.java | 12 +- .../java/eu/eudat/entities/UserToken.java | 12 +- .../managers/DataManagementPlanManager.java | 8 +- .../eu/eudat/managers/DatasetManager.java | 7 +- .../eu/eudat/managers/PaginationManager.java | 13 + .../eu/eudat/managers/ProjectManager.java | 7 +- .../criteria/DataManagementPlanCriteria.java | 21 +- .../models/criteria/ProjectCriteria.java | 21 +- .../models/dataset/DatasetTableRequest.java | 32 +- .../dmp/DataManagementPlanTableRequest.java | 34 +- .../models/helpers/requests/RequestItem.java | 13 + .../models/helpers/requests/TableRequest.java | 22 + .../{ => helpers}/responses/ResponseItem.java | 2 +- .../models/project/ProjectTableRequest.java | 34 +- .../eu/eudat/queryable/QueryableList.java | 24 + .../QueryableHibernateList.java | 96 +++ .../predicates/OrderByPredicate.java | 10 + .../queryable/predicates/SelectPredicate.java | 5 + .../queryable/predicates/SinglePredicate.java | 9 + 47 files changed, 1454 insertions(+), 1257 deletions(-) create mode 100644 dmp-backend/src/main/java/eu/eudat/dao/databaselayer/context/DatabaseContext.java create mode 100644 dmp-backend/src/main/java/eu/eudat/dao/databaselayer/service/DatabaseService.java create mode 100644 dmp-backend/src/main/java/eu/eudat/managers/PaginationManager.java create mode 100644 dmp-backend/src/main/java/eu/eudat/models/helpers/requests/RequestItem.java create mode 100644 dmp-backend/src/main/java/eu/eudat/models/helpers/requests/TableRequest.java rename dmp-backend/src/main/java/eu/eudat/models/{ => helpers}/responses/ResponseItem.java (95%) create mode 100644 dmp-backend/src/main/java/eu/eudat/queryable/QueryableList.java create mode 100644 dmp-backend/src/main/java/eu/eudat/queryable/hibernatequeryablelist/QueryableHibernateList.java create mode 100644 dmp-backend/src/main/java/eu/eudat/queryable/predicates/OrderByPredicate.java create mode 100644 dmp-backend/src/main/java/eu/eudat/queryable/predicates/SelectPredicate.java create mode 100644 dmp-backend/src/main/java/eu/eudat/queryable/predicates/SinglePredicate.java diff --git a/dmp-backend/src/main/java/eu/eudat/controllers/DMPs.java b/dmp-backend/src/main/java/eu/eudat/controllers/DMPs.java index 92e805fde..e9b8cffd2 100644 --- a/dmp-backend/src/main/java/eu/eudat/controllers/DMPs.java +++ b/dmp-backend/src/main/java/eu/eudat/controllers/DMPs.java @@ -14,8 +14,7 @@ import eu.eudat.models.criteria.ResearcherCriteria; import eu.eudat.models.dmp.DataManagementPlan; import eu.eudat.models.dmp.DataManagementPlanTableRequest; import eu.eudat.models.helpers.DataTableData; - -import eu.eudat.models.responses.ResponseItem; +import eu.eudat.models.helpers.responses.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; @@ -96,365 +95,365 @@ public class DMPs { @Transactional @RequestMapping(method = RequestMethod.POST, value = { "/dmps/add" }, consumes = "application/json", produces="application/json") public @ResponseBody ResponseEntity addDmp(@RequestBody eu.eudat.models.dmp.DataManagementPlan dataManagementPlan) { - eu.eudat.entities.DMP createdProject = dMPDao.update(dataManagementPlan.toDataModel()); + eu.eudat.entities.DMP createdProject = dMPDao.createOrUpdate(dataManagementPlan.toDataModel()); return ResponseEntity.status(HttpStatus.CREATED).body(createdProject); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - @RequestMapping(method = RequestMethod.GET, value = { "/dmps" }, produces="text/plain") - public @ResponseBody ResponseEntity> listDMPs(){ - try { - List allIDs = dMPDao.listAllIDs(); - return ResponseEntity.status(HttpStatus.OK).body(allIDs); - } - catch(Exception ex) { - ex.printStackTrace(); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null); - } - } - - @RequestMapping(method = RequestMethod.GET, value = { "/dmps/{id}" }, produces="application/json") - public @ResponseBody ResponseEntity getDMP(@PathVariable("id") String id){ - try { - DMP dmp = dMPDao.read(UUID.fromString(id)); - DataManagementPlan dataManagementPlan = new DataManagementPlan(); - dataManagementPlan.fromDataModel(dmp); - return ResponseEntity.status(HttpStatus.OK).body(dataManagementPlan); - } - catch(Exception ex) { - ex.printStackTrace(); - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null); - } - } - - @RequestMapping(method = RequestMethod.GET, value = { "/dmp/listDMPLabelID" }, produces="text/plain") - public @ResponseBody ResponseEntity> listDmpLabelID(){ - try { - List allIDLabels = dMPDao.listAllIDsLabels(); - return ResponseEntity.status(HttpStatus.OK).body(allIDLabels); - } - catch(Exception ex) { - ex.printStackTrace(); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null); - } - } - - - /** - * This should be called on extreme cases. It's computationally intensive - */ - @RequestMapping(method = RequestMethod.GET, value = { "/dmp/getAll" }, produces="application/json") - public @ResponseBody ResponseEntity getAllDMPs(){ - - try { - List allDMPs = dMPDao.getAll(); - return ResponseEntity.status(HttpStatus.OK).body(allDMPs); - } - catch(Exception ex) { - ex.printStackTrace(); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null ); - } - } - - - @Transactional - @RequestMapping(method = RequestMethod.POST, value = { "/dmp/create" }, consumes = "application/json", produces="application/json") - public @ResponseBody ResponseEntity createDMP(@RequestBody DMP dmp) { - try { - DMP createdDmp = dMPDao.update(dmp); - return ResponseEntity.status(HttpStatus.CREATED).body(createdDmp); - } catch (Exception e) { - e.printStackTrace(); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null); - } - - } - - @Transactional - @RequestMapping(method = RequestMethod.POST, value = { "/dmp/update" }, consumes = "application/json", produces="application/json") - public @ResponseBody ResponseEntity updateDMP(@RequestBody DataManagementPlan dataManagementPlan) { - - DMP newDmp = dataManagementPlan.toDataModel(); - if(newDmp.getOrganisations()!=null&&!newDmp.getOrganisations().isEmpty()){ - for(eu.eudat.entities.Organisation organisation: newDmp.getOrganisations()){ - OrganisationCriteria criteria = new OrganisationCriteria(); - criteria.setLike(organisation.getReference()); - List entries = this.organisationDao.listBy(criteria); - if(entries!=null&&!entries.isEmpty())organisation.setId(entries.get(0).getId()); - else organisation = this.organisationDao.create(organisation); - } - } - - if(newDmp.getResearchers()!=null&&!newDmp.getResearchers().isEmpty()){ - for(eu.eudat.entities.Researcher researcher : newDmp.getResearchers()){ - ResearcherCriteria criteria = new ResearcherCriteria(); - criteria.setLike(researcher.getReference()); - List entries = this.researcherDao.listBy(criteria); - if(entries!=null&&!entries.isEmpty())researcher.setId(entries.get(0).getId()); - else researcher = this.researcherDao.create(researcher); - } - } - - DMP previousDmp = dMPDao.read(dataManagementPlan.getId()); - previousDmp.setResearchers(newDmp.getResearchers()); - previousDmp.setOrganisations(newDmp.getOrganisations()); - previousDmp.setLabel(dataManagementPlan.getLabel()); - previousDmp.setVersion(dataManagementPlan.getVersion()); - previousDmp.setStatus((short)dataManagementPlan.getStatus()); - //if(!previousDmp.getProject().getId().equals(newDmp.getProject().getId()))previousDmp.setProject(projectDao.read(newDmp.getProject().getId())); - - try { - DMP updatedDMP = dMPDao.update(previousDmp); - return ResponseEntity.status(HttpStatus.CREATED).body(updatedDMP); - } catch (Exception e) { - e.printStackTrace(); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null); - } - - } - - - - - - @RequestMapping(method = RequestMethod.POST, value = { "/dmp/getdatasets" }, consumes = "application/json", produces="application/json") - public @ResponseBody ResponseEntity> getDatasetsOfDMP(@RequestBody DMP dmp) { - try { - List datasets = datasetDao.getDatasetsOfDmp(dmp.getId()); - return ResponseEntity.status(HttpStatus.OK).body(datasets); - } catch (Exception e) { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null); - } - - } - - - - @RequestMapping(method = RequestMethod.POST, value = { "/dmp/delete" }, consumes = "application/json", produces="text/plain") - public @ResponseBody ResponseEntity delete(@RequestBody DMP dmp) { - - DMP d = new DMP(); - d.setId(dmp.getId()); - try { - dMPDao.delete(d); - return ResponseEntity.status(HttpStatus.CREATED).body("DELETED!"); - } catch (Exception e) { - e.printStackTrace(); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("{\"msg\":\"Could not Delete DMP!\""); - } - - } - - @RequestMapping(method = RequestMethod.POST, value = { "/dmp/softdelete" }, consumes = "application/json", produces="text/plain") - public @ResponseBody ResponseEntity softDelete(@RequestBody DMP dmp) { - - try{ - DMP d = dMPDao.read(dmp.getId()); - d.setStatus(new Short("-1")); - dMPDao.update(d); - return ResponseEntity.status(HttpStatus.OK).body("{\"msg\":\"deleted DMP!\""); - } catch (Exception e) { - e.printStackTrace(); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("{\"msg\":\"Could not soft delete DMP!\""); - } - - } - - - - - //////////////////////////////// - //// USER - RELATED ACTIONS //// - //////////////////////////////// - - @RequestMapping(method = RequestMethod.GET, value = { "/dmp/getofuser" }, produces="text/plain") - public @ResponseBody ResponseEntity> getDmpsOfUser(){ - - String userID = null; - try { - userID = SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString(); - } catch(NullPointerException ex) { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null); - } - - try { - //List nonDeleted = userInfoDao.getDmpsOfUser(userID); - List nonDeleted = dMPDao.getDMPsOfUser(userID); - return ResponseEntity.status(HttpStatus.OK).body(nonDeleted); - } - catch(Exception ex) { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null); - } - - } - - @RequestMapping(method = RequestMethod.POST, value = { "/dmp/createofuser" }, produces="text/plain", consumes = "application/json") - public @ResponseBody ResponseEntity createDmpOfUser(@RequestBody DataManagementPlan dataManagementPlan){ - - - String userID = null; - try { - userID = SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString(); - } catch(NullPointerException ex) { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null); - } - - UserInfo userInfo = userInfoDao.read(UUID.fromString(userID)); - - if(userInfo==null) //this should normally never happer - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null); - - try { - DMP dmp = dataManagementPlan.toDataModel(); - - if(dmp.getOrganisations()!=null&&!dmp.getOrganisations().isEmpty()){ - for(eu.eudat.entities.Organisation organisation: dmp.getOrganisations()){ - OrganisationCriteria criteria = new OrganisationCriteria(); - criteria.setLike(organisation.getReference()); - List entries = this.organisationDao.listBy(criteria); - if(entries!=null&&!entries.isEmpty())organisation.setId(entries.get(0).getId()); - else organisation = this.organisationDao.create(organisation); - } - } - - if(dmp.getResearchers()!=null&&!dmp.getResearchers().isEmpty()){ - for(eu.eudat.entities.Researcher researcher : dmp.getResearchers()){ - ResearcherCriteria criteria = new ResearcherCriteria(); - criteria.setLike(researcher.getReference()); - List entries = this.researcherDao.listBy(criteria); - if(entries!=null&&!entries.isEmpty())researcher.setId(entries.get(0).getId()); - else researcher = this.researcherDao.create(researcher); - } - } - dmp.setId(null); - - dmp.setCreator(userInfo); - dmp.setProject(this.projectDao.read(dataManagementPlan.getProject().getId())); - Set users = new HashSet(); - users.add(userInfo); - dmp.setUsers(users); - - dmp.setCreated(new Date()); - dmp.setModified(new Date()); - dmp.setStatus(new Short("0")); - - DMP newdmp = dMPDao.create(dmp); - - return ResponseEntity.status(HttpStatus.OK).body(newdmp); - } - catch(Exception ex) { - ex.printStackTrace(); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null); - } - - } - - @RequestMapping(method = RequestMethod.POST, value = { "/dmp/cloneforuser" }, produces="text/plain", consumes = "application/json") - public @ResponseBody ResponseEntity cloneDmpOfUser(@RequestBody DMP dmp){ - - String userID = null; - try { - userID = SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString(); - } catch(NullPointerException ex) { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null); - } - - UserInfo userInfo = userInfoDao.read(UUID.fromString(userID)); - - if(userInfo==null) //this should normally never happer - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null); - - DMP clone = dMPDao.read(dmp.getId()); - - - try { - - Set users = new HashSet(); - users.add(userInfo); - clone.setUsers(users); - - clone.setCreated(new Date()); - clone.setModified(new Date()); - clone.setStatus(new Short("0")); - - String cloneLabel = dmp.getLabel(); - if(cloneLabel==null || cloneLabel.isEmpty()) //if the provided label is null or empty, use parent's label + "_clone" - cloneLabel = clone.getLabel()+"_clone"; - clone.setVersion(clone.getVersion()+1); - clone.setLabel(cloneLabel); - clone.setPrevious(clone.getId()); - - - clone.setId(null); - - clone = dMPDao.create(clone); - - return ResponseEntity.status(HttpStatus.OK).body(clone); - } - catch(Exception ex) { - ex.printStackTrace(); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null); - } - - } - - - @RequestMapping(method = RequestMethod.POST, value = { "/dmp/adduser" }, produces="text/plain") - public @ResponseBody ResponseEntity addUserToDmp(@RequestBody DMP dmp){ - - - String userID = null; - try { - userID = SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString(); - } catch(NullPointerException ex) { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null); - } - - final UserInfo userInfo = userInfoDao.read(UUID.fromString(userID)); - - if(userInfo==null) //this should normally never happer - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null); - - if(dmp==null || dmp.getId()==null) - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null); - - try { - - DMP existingDMP = dMPDao.read(dmp.getId()); - - Set users = existingDMP.getUsers().parallelStream().filter(user -> user.getId().toString() != userInfo.getId().toString()).collect(Collectors.toSet()); - - users.add(userInfo); - dmp.setUsers(users); - - DMP updateddmp = dMPDao.update(dmp); - - return ResponseEntity.status(HttpStatus.OK).body(updateddmp); - } - catch(Exception ex) { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null); - } - - } - - - - - private static void addNullAndForeignElems(DMP existing, DMP newone) { - - newone.setModified(new Date()); - if(newone.getStatus()==null) - newone.setStatus(existing.getStatus()); - if(newone.getCreated()==null) - newone.setCreated(existing.getCreated()); - - newone.setDataset(existing.getDataset()); - newone.setOrganisations(existing.getOrganisations()); - newone.setResearchers(existing.getResearchers()); - newone.setUsers(existing.getUsers()); - } +// @RequestMapping(method = RequestMethod.GET, value = { "/dmps" }, produces="text/plain") +// public @ResponseBody ResponseEntity> listDMPs(){ +// try { +// List allIDs = dMPDao.listAllIDs(); +// return ResponseEntity.status(HttpStatus.OK).body(allIDs); +// } +// catch(Exception ex) { +// ex.printStackTrace(); +// return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null); +// } +// } +// +// @RequestMapping(method = RequestMethod.GET, value = { "/dmps/{id}" }, produces="application/json") +// public @ResponseBody ResponseEntity getDMP(@PathVariable("id") String id){ +// try { +// DMP dmp = dMPDao.read(UUID.fromString(id)); +// DataManagementPlan dataManagementPlan = new DataManagementPlan(); +// dataManagementPlan.fromDataModel(dmp); +// return ResponseEntity.status(HttpStatus.OK).body(dataManagementPlan); +// } +// catch(Exception ex) { +// ex.printStackTrace(); +// return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null); +// } +// } +// +// @RequestMapping(method = RequestMethod.GET, value = { "/dmp/listDMPLabelID" }, produces="text/plain") +// public @ResponseBody ResponseEntity> listDmpLabelID(){ +// try { +// List allIDLabels = dMPDao.listAllIDsLabels(); +// return ResponseEntity.status(HttpStatus.OK).body(allIDLabels); +// } +// catch(Exception ex) { +// ex.printStackTrace(); +// return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null); +// } +// } +// +// +// /** +// * This should be called on extreme cases. It's computationally intensive +// */ +// @RequestMapping(method = RequestMethod.GET, value = { "/dmp/getAll" }, produces="application/json") +// public @ResponseBody ResponseEntity getAllDMPs(){ +// +// try { +// List allDMPs = dMPDao.getAll(); +// return ResponseEntity.status(HttpStatus.OK).body(allDMPs); +// } +// catch(Exception ex) { +// ex.printStackTrace(); +// return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null ); +// } +// } +// +// +// @Transactional +// @RequestMapping(method = RequestMethod.POST, value = { "/dmp/create" }, consumes = "application/json", produces="application/json") +// public @ResponseBody ResponseEntity createDMP(@RequestBody DMP dmp) { +// try { +// DMP createdDmp = dMPDao.update(dmp); +// return ResponseEntity.status(HttpStatus.CREATED).body(createdDmp); +// } catch (Exception e) { +// e.printStackTrace(); +// return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null); +// } +// +// } +// +// @Transactional +// @RequestMapping(method = RequestMethod.POST, value = { "/dmp/update" }, consumes = "application/json", produces="application/json") +// public @ResponseBody ResponseEntity updateDMP(@RequestBody DataManagementPlan dataManagementPlan) { +// +// DMP newDmp = dataManagementPlan.toDataModel(); +// if(newDmp.getOrganisations()!=null&&!newDmp.getOrganisations().isEmpty()){ +// for(eu.eudat.entities.Organisation organisation: newDmp.getOrganisations()){ +// OrganisationCriteria criteria = new OrganisationCriteria(); +// criteria.setLike(organisation.getReference()); +// List entries = this.organisationDao.listBy(criteria); +// if(entries!=null&&!entries.isEmpty())organisation.setId(entries.get(0).getId()); +// else organisation = this.organisationDao.create(organisation); +// } +// } +// +// if(newDmp.getResearchers()!=null&&!newDmp.getResearchers().isEmpty()){ +// for(eu.eudat.entities.Researcher researcher : newDmp.getResearchers()){ +// ResearcherCriteria criteria = new ResearcherCriteria(); +// criteria.setLike(researcher.getReference()); +// List entries = this.researcherDao.listBy(criteria); +// if(entries!=null&&!entries.isEmpty())researcher.setId(entries.get(0).getId()); +// else researcher = this.researcherDao.create(researcher); +// } +// } +// +// DMP previousDmp = dMPDao.read(dataManagementPlan.getId()); +// previousDmp.setResearchers(newDmp.getResearchers()); +// previousDmp.setOrganisations(newDmp.getOrganisations()); +// previousDmp.setLabel(dataManagementPlan.getLabel()); +// previousDmp.setVersion(dataManagementPlan.getVersion()); +// previousDmp.setStatus((short)dataManagementPlan.getStatus()); +// //if(!previousDmp.getProject().getId().equals(newDmp.getProject().getId()))previousDmp.setProject(projectDao.read(newDmp.getProject().getId())); +// +// try { +// DMP updatedDMP = dMPDao.update(previousDmp); +// return ResponseEntity.status(HttpStatus.CREATED).body(updatedDMP); +// } catch (Exception e) { +// e.printStackTrace(); +// return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null); +// } +// +// } +// +// +// +// +// +// @RequestMapping(method = RequestMethod.POST, value = { "/dmp/getdatasets" }, consumes = "application/json", produces="application/json") +// public @ResponseBody ResponseEntity> getDatasetsOfDMP(@RequestBody DMP dmp) { +// try { +// List datasets = datasetDao.getDatasetsOfDmp(dmp.getId()); +// return ResponseEntity.status(HttpStatus.OK).body(datasets); +// } catch (Exception e) { +// return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null); +// } +// +// } +// +// +// +// @RequestMapping(method = RequestMethod.POST, value = { "/dmp/delete" }, consumes = "application/json", produces="text/plain") +// public @ResponseBody ResponseEntity delete(@RequestBody DMP dmp) { +// +// DMP d = new DMP(); +// d.setId(dmp.getId()); +// try { +// dMPDao.delete(d); +// return ResponseEntity.status(HttpStatus.CREATED).body("DELETED!"); +// } catch (Exception e) { +// e.printStackTrace(); +// return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("{\"msg\":\"Could not Delete DMP!\""); +// } +// +// } +// +// @RequestMapping(method = RequestMethod.POST, value = { "/dmp/softdelete" }, consumes = "application/json", produces="text/plain") +// public @ResponseBody ResponseEntity softDelete(@RequestBody DMP dmp) { +// +// try{ +// DMP d = dMPDao.read(dmp.getId()); +// d.setStatus(new Short("-1")); +// dMPDao.update(d); +// return ResponseEntity.status(HttpStatus.OK).body("{\"msg\":\"deleted DMP!\""); +// } catch (Exception e) { +// e.printStackTrace(); +// return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("{\"msg\":\"Could not soft delete DMP!\""); +// } +// +// } +// +// +// +// +// //////////////////////////////// +// //// USER - RELATED ACTIONS //// +// //////////////////////////////// +// +// @RequestMapping(method = RequestMethod.GET, value = { "/dmp/getofuser" }, produces="text/plain") +// public @ResponseBody ResponseEntity> getDmpsOfUser(){ +// +// String userID = null; +// try { +// userID = SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString(); +// } catch(NullPointerException ex) { +// return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null); +// } +// +// try { +// //List nonDeleted = userInfoDao.getDmpsOfUser(userID); +// List nonDeleted = dMPDao.getDMPsOfUser(userID); +// return ResponseEntity.status(HttpStatus.OK).body(nonDeleted); +// } +// catch(Exception ex) { +// return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null); +// } +// +// } +// +// @RequestMapping(method = RequestMethod.POST, value = { "/dmp/createofuser" }, produces="text/plain", consumes = "application/json") +// public @ResponseBody ResponseEntity createDmpOfUser(@RequestBody DataManagementPlan dataManagementPlan){ +// +// +// String userID = null; +// try { +// userID = SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString(); +// } catch(NullPointerException ex) { +// return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null); +// } +// +// UserInfo userInfo = userInfoDao.read(UUID.fromString(userID)); +// +// if(userInfo==null) //this should normally never happer +// return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null); +// +// try { +// DMP dmp = dataManagementPlan.toDataModel(); +// +// if(dmp.getOrganisations()!=null&&!dmp.getOrganisations().isEmpty()){ +// for(eu.eudat.entities.Organisation organisation: dmp.getOrganisations()){ +// OrganisationCriteria criteria = new OrganisationCriteria(); +// criteria.setLike(organisation.getReference()); +// List entries = this.organisationDao.listBy(criteria); +// if(entries!=null&&!entries.isEmpty())organisation.setId(entries.get(0).getId()); +// else organisation = this.organisationDao.create(organisation); +// } +// } +// +// if(dmp.getResearchers()!=null&&!dmp.getResearchers().isEmpty()){ +// for(eu.eudat.entities.Researcher researcher : dmp.getResearchers()){ +// ResearcherCriteria criteria = new ResearcherCriteria(); +// criteria.setLike(researcher.getReference()); +// List entries = this.researcherDao.listBy(criteria); +// if(entries!=null&&!entries.isEmpty())researcher.setId(entries.get(0).getId()); +// else researcher = this.researcherDao.create(researcher); +// } +// } +// dmp.setId(null); +// +// dmp.setCreator(userInfo); +// dmp.setProject(this.projectDao.read(dataManagementPlan.getProject().getId())); +// Set users = new HashSet(); +// users.add(userInfo); +// dmp.setUsers(users); +// +// dmp.setCreated(new Date()); +// dmp.setModified(new Date()); +// dmp.setStatus(new Short("0")); +// +// DMP newdmp = dMPDao.create(dmp); +// +// return ResponseEntity.status(HttpStatus.OK).body(newdmp); +// } +// catch(Exception ex) { +// ex.printStackTrace(); +// return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null); +// } +// +// } +// +// @RequestMapping(method = RequestMethod.POST, value = { "/dmp/cloneforuser" }, produces="text/plain", consumes = "application/json") +// public @ResponseBody ResponseEntity cloneDmpOfUser(@RequestBody DMP dmp){ +// +// String userID = null; +// try { +// userID = SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString(); +// } catch(NullPointerException ex) { +// return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null); +// } +// +// UserInfo userInfo = userInfoDao.read(UUID.fromString(userID)); +// +// if(userInfo==null) //this should normally never happer +// return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null); +// +// DMP clone = dMPDao.read(dmp.getId()); +// +// +// try { +// +// Set users = new HashSet(); +// users.add(userInfo); +// clone.setUsers(users); +// +// clone.setCreated(new Date()); +// clone.setModified(new Date()); +// clone.setStatus(new Short("0")); +// +// String cloneLabel = dmp.getLabel(); +// if(cloneLabel==null || cloneLabel.isEmpty()) //if the provided label is null or empty, use parent's label + "_clone" +// cloneLabel = clone.getLabel()+"_clone"; +// clone.setVersion(clone.getVersion()+1); +// clone.setLabel(cloneLabel); +// clone.setPrevious(clone.getId()); +// +// +// clone.setId(null); +// +// clone = dMPDao.create(clone); +// +// return ResponseEntity.status(HttpStatus.OK).body(clone); +// } +// catch(Exception ex) { +// ex.printStackTrace(); +// return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null); +// } +// +// } +// +// +// @RequestMapping(method = RequestMethod.POST, value = { "/dmp/adduser" }, produces="text/plain") +// public @ResponseBody ResponseEntity addUserToDmp(@RequestBody DMP dmp){ +// +// +// String userID = null; +// try { +// userID = SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString(); +// } catch(NullPointerException ex) { +// return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null); +// } +// +// final UserInfo userInfo = userInfoDao.read(UUID.fromString(userID)); +// +// if(userInfo==null) //this should normally never happer +// return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null); +// +// if(dmp==null || dmp.getId()==null) +// return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null); +// +// try { +// +// DMP existingDMP = dMPDao.read(dmp.getId()); +// +// Set users = existingDMP.getUsers().parallelStream().filter(user -> user.getId().toString() != userInfo.getId().toString()).collect(Collectors.toSet()); +// +// users.add(userInfo); +// dmp.setUsers(users); +// +// DMP updateddmp = dMPDao.update(dmp); +// +// return ResponseEntity.status(HttpStatus.OK).body(updateddmp); +// } +// catch(Exception ex) { +// return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null); +// } +// +// } +// +// +// +// +// private static void addNullAndForeignElems(DMP existing, DMP newone) { +// +// newone.setModified(new Date()); +// if(newone.getStatus()==null) +// newone.setStatus(existing.getStatus()); +// if(newone.getCreated()==null) +// newone.setCreated(existing.getCreated()); +// +// newone.setDataset(existing.getDataset()); +// newone.setOrganisations(existing.getOrganisations()); +// newone.setResearchers(existing.getResearchers()); +// newone.setUsers(existing.getUsers()); +// } } diff --git a/dmp-backend/src/main/java/eu/eudat/controllers/DashBoardController.java b/dmp-backend/src/main/java/eu/eudat/controllers/DashBoardController.java index ea52b4541..ec96dbd48 100644 --- a/dmp-backend/src/main/java/eu/eudat/controllers/DashBoardController.java +++ b/dmp-backend/src/main/java/eu/eudat/controllers/DashBoardController.java @@ -1,34 +1,18 @@ package eu.eudat.controllers; -import java.util.Map; -import java.util.UUID; - -import eu.eudat.models.responses.ResponseItem; +import eu.eudat.models.helpers.responses.ResponseItem; import eu.eudat.models.security.Principal; -import org.json.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.CrossOrigin; -import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import eu.eudat.dao.entities.DMPDao; -import eu.eudat.dao.entities.DMPProfileDao; -import eu.eudat.dao.entities.DataRepositoryDao; import eu.eudat.dao.entities.DatasetDao; -import eu.eudat.dao.entities.DatasetProfileDao; -import eu.eudat.dao.entities.DatasetProfileRulesetDao; -import eu.eudat.dao.entities.DatasetProfileViewstyleDao; -import eu.eudat.dao.entities.OrganisationDao; import eu.eudat.dao.entities.ProjectDao; -import eu.eudat.dao.entities.RegistryDao; -import eu.eudat.dao.entities.ResearcherDao; -import eu.eudat.dao.entities.ServiceDao; import eu.eudat.managers.DashBoardManager; -import eu.eudat.managers.UserManager; import eu.eudat.models.dashboard.DashBoardStatistics; @RestController diff --git a/dmp-backend/src/main/java/eu/eudat/controllers/DataRepositories.java b/dmp-backend/src/main/java/eu/eudat/controllers/DataRepositories.java index 0446fe7df..a329948bf 100644 --- a/dmp-backend/src/main/java/eu/eudat/controllers/DataRepositories.java +++ b/dmp-backend/src/main/java/eu/eudat/controllers/DataRepositories.java @@ -76,73 +76,73 @@ public class DataRepositories { // MANAGE DATAREPOSITORy(IES) - @RequestMapping(method = RequestMethod.GET, value = { "/datarepos" }) - public @ResponseBody ResponseEntity> listDataRepositories(){ - try { - List allIDs = dataRepositoryDao.listAllIDs(); - return ResponseEntity.status(HttpStatus.OK).body(allIDs); - } - catch(Exception ex) { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null); - } - } - - - @RequestMapping(method = RequestMethod.GET, value = { "/datarepos/{id}" }) - public @ResponseBody ResponseEntity getDataRepository(@PathVariable("id") String id) { - try { - DataRepository dataRepository = dataRepositoryDao.read(UUID.fromString(id)); - return ResponseEntity.status(HttpStatus.OK).body(dataRepository); - } - catch(Exception ex) { - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null); - } - } - - - - @RequestMapping(method = RequestMethod.GET, value = { "/datarepo/getAll" }, produces="application/json") - public @ResponseBody ResponseEntity> getAllDataRepositories(){ - - try { - List allDataRepositories = dataRepositoryDao.getAll(); - - return ResponseEntity.status(HttpStatus.OK).body(allDataRepositories); - - } - catch(Exception ex) { - ex.printStackTrace(); - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null); - } - - } - - - @Transactional - @RequestMapping(method = RequestMethod.POST, value = { "/datarepo/create" }, consumes = "application/json", produces="application/json") - public @ResponseBody ResponseEntity setOrganisation(@RequestBody DataRepository dataRepository) { - try { - DataRepository createdDataRepository = dataRepositoryDao.update(dataRepository); - return ResponseEntity.status(HttpStatus.CREATED).body(createdDataRepository); - } catch (Exception e) { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null); - } - } - - - @RequestMapping(method = RequestMethod.POST, value = { "/datarepo/delete" }, consumes = "application/json", produces="text/plain") - public @ResponseBody ResponseEntity delete(@RequestBody DataRepository dataRepository) { - - DataRepository dr = new DataRepository(); - dr.setId(dataRepository.getId()); - try { - dataRepositoryDao.delete(dr); - return ResponseEntity.status(HttpStatus.CREATED).body("{\"msg\":\"Deleted data repository!\"}"); - } catch (Exception e) { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("{\"msg\":\"Could not delete data repository!\"}"); - } - - } +// @RequestMapping(method = RequestMethod.GET, value = { "/datarepos" }) +// public @ResponseBody ResponseEntity> listDataRepositories(){ +// try { +// List allIDs = dataRepositoryDao.listAllIDs(); +// return ResponseEntity.status(HttpStatus.OK).body(allIDs); +// } +// catch(Exception ex) { +// return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null); +// } +// } +// +// +// @RequestMapping(method = RequestMethod.GET, value = { "/datarepos/{id}" }) +// public @ResponseBody ResponseEntity getDataRepository(@PathVariable("id") String id) { +// try { +// DataRepository dataRepository = dataRepositoryDao.read(UUID.fromString(id)); +// return ResponseEntity.status(HttpStatus.OK).body(dataRepository); +// } +// catch(Exception ex) { +// return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null); +// } +// } +// +// +// +// @RequestMapping(method = RequestMethod.GET, value = { "/datarepo/getAll" }, produces="application/json") +// public @ResponseBody ResponseEntity> getAllDataRepositories(){ +// +// try { +// List allDataRepositories = dataRepositoryDao.getAll(); +// +// return ResponseEntity.status(HttpStatus.OK).body(allDataRepositories); +// +// } +// catch(Exception ex) { +// ex.printStackTrace(); +// return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null); +// } +// +// } +// +// +// @Transactional +// @RequestMapping(method = RequestMethod.POST, value = { "/datarepo/create" }, consumes = "application/json", produces="application/json") +// public @ResponseBody ResponseEntity setOrganisation(@RequestBody DataRepository dataRepository) { +// try { +// DataRepository createdDataRepository = dataRepositoryDao.update(dataRepository); +// return ResponseEntity.status(HttpStatus.CREATED).body(createdDataRepository); +// } catch (Exception e) { +// return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null); +// } +// } +// +// +// @RequestMapping(method = RequestMethod.POST, value = { "/datarepo/delete" }, consumes = "application/json", produces="text/plain") +// public @ResponseBody ResponseEntity delete(@RequestBody DataRepository dataRepository) { +// +// DataRepository dr = new DataRepository(); +// dr.setId(dataRepository.getId()); +// try { +// dataRepositoryDao.delete(dr); +// return ResponseEntity.status(HttpStatus.CREATED).body("{\"msg\":\"Deleted data repository!\"}"); +// } catch (Exception e) { +// return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("{\"msg\":\"Could not delete data repository!\"}"); +// } +// +// } } diff --git a/dmp-backend/src/main/java/eu/eudat/controllers/DatasetProfileController.java b/dmp-backend/src/main/java/eu/eudat/controllers/DatasetProfileController.java index be1a65005..8eaa681b4 100644 --- a/dmp-backend/src/main/java/eu/eudat/controllers/DatasetProfileController.java +++ b/dmp-backend/src/main/java/eu/eudat/controllers/DatasetProfileController.java @@ -42,7 +42,7 @@ public class DatasetProfileController { @RequestMapping(method = RequestMethod.GET, value = { "/datasetprofile/get/{id}" }, produces="application/json") public ResponseEntity getSingle(@PathVariable String id){ try { - eu.eudat.entities.Dataset dataset = datasetDao.read(UUID.fromString(id)); + eu.eudat.entities.Dataset dataset = datasetDao.find(UUID.fromString(id)); eu.eudat.models.user.composite.DatasetProfile datasetprofile = UserManager.generateDatasetProfileModel(dataset.getProfile()); datasetprofile.setStatus(dataset.getStatus()); if(dataset.getProperties()!=null){ @@ -62,13 +62,13 @@ public class DatasetProfileController { @RequestMapping(method = RequestMethod.POST, value = { "/datasetprofile/save/{id}" }, consumes="application/json",produces="application/json") public ResponseEntity updateDataset(@PathVariable String id,@RequestBody PropertiesModel properties){ try { - eu.eudat.entities.Dataset dataset = datasetDao.read(UUID.fromString(id)); + eu.eudat.entities.Dataset dataset = datasetDao.find(UUID.fromString(id)); Map values = new HashMap(); properties.toMap(values); JSONObject jobject = new JSONObject(values); dataset.setProperties(jobject.toString()); dataset.setStatus((short)properties.getStatus()); - datasetDao.update(dataset); + datasetDao.createOrUpdate(dataset); //TODO return ResponseEntity.status(HttpStatus.OK).body(properties); } @@ -80,7 +80,7 @@ public class DatasetProfileController { @RequestMapping(method = RequestMethod.POST, value = { "/search/autocomplete" }, consumes="application/json",produces="application/json") public ResponseEntity getDataForAutocomplete(@RequestBody AutoCompleteLookupItem lookupItem){ try { - eu.eudat.entities.Dataset dataset = datasetDao.read(UUID.fromString(lookupItem.getProfileID())); + eu.eudat.entities.Dataset dataset = datasetDao.find(UUID.fromString(lookupItem.getProfileID())); Document viewStyleDoc = XmlBuilder.fromXml(dataset.getProfile().getViewstyle().getDefinition()); Element field = viewStyleDoc.getElementById(lookupItem.getFieldID()); eu.eudat.entities.xmlmodels.viewstyledefinition.Field modelfield = new eu.eudat.entities.xmlmodels.viewstyledefinition.Field(); diff --git a/dmp-backend/src/main/java/eu/eudat/controllers/Datasets.java b/dmp-backend/src/main/java/eu/eudat/controllers/Datasets.java index 235e0f4f6..49f565fb3 100644 --- a/dmp-backend/src/main/java/eu/eudat/controllers/Datasets.java +++ b/dmp-backend/src/main/java/eu/eudat/controllers/Datasets.java @@ -9,12 +9,9 @@ import eu.eudat.entities.Dataset; import eu.eudat.entities.DatasetProfile; import eu.eudat.entities.UserInfo; import eu.eudat.managers.DatasetManager; -import eu.eudat.managers.ProjectManager; import eu.eudat.models.dataset.DatasetTableRequest; import eu.eudat.models.helpers.DataTableData; -import eu.eudat.models.project.Project; -import eu.eudat.models.project.ProjectTableRequest; -import eu.eudat.models.responses.ResponseItem; +import eu.eudat.models.helpers.responses.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; @@ -98,256 +95,256 @@ public class Datasets { // FETCH BY DATASET(S) - @RequestMapping(method = RequestMethod.GET, value = { "/datasets" }) - public @ResponseBody ResponseEntity> listDatasets(){ - try { - List allIDs = datasetDao.listAllIDs(); - return ResponseEntity.status(HttpStatus.OK).body(allIDs); - } - catch(Exception ex) { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null); - } - } - - - @RequestMapping(method = RequestMethod.GET, value = { "/datasets/{id}" }) - public @ResponseBody ResponseEntity getDataset(@PathVariable("id") String id) { - try { - Dataset ds = datasetDao.read(UUID.fromString(id)); - eu.eudat.models.dataset.Dataset dataset = new eu.eudat.models.dataset.Dataset(); - dataset.fromDataModel(ds); - return ResponseEntity.status(HttpStatus.OK).body(dataset); - } - catch(Exception ex) { - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null); - } - } - - - /** - * This should be called on extreme cases. It's computationally intensive - */ - @RequestMapping(method = RequestMethod.GET, value = { "/dataset/getAll" }) - public @ResponseBody ResponseEntity> getAllDatasets(){ - - try { - List allDatasets = datasetDao.getAll(); - return ResponseEntity.status(HttpStatus.OK).body(allDatasets); - } - catch(Exception ex) { - ex.printStackTrace(); - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null); - } - - } - - - @RequestMapping(method = RequestMethod.POST, value = { "/dataset/create" }, consumes = "application/json", produces="application/json") - public @ResponseBody ResponseEntity createDataset(@RequestBody eu.eudat.models.dataset.Dataset modeldataset) { - - String userID = null; - try { - userID = SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString(); - } catch(NullPointerException ex) { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null); - } - - UserInfo userInfo = userInfoDao.read(UUID.fromString(userID)); - - if(userInfo==null) //this should normally never happer - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null); - - - Dataset dataset = modeldataset.toDataModel(); - if(dataset.getDataRepositories()!=null&&!dataset.getDataRepositories().isEmpty()){ - for(eu.eudat.entities.DataRepository dataRepo : dataset.getDataRepositories()){ - DataRepositoryCriteria criteria = new DataRepositoryCriteria(); - criteria.setLike(dataRepo.getReference()); - List entries = this.dataRepositoryDao.listBy(criteria); - if(entries!=null&&!entries.isEmpty())dataRepo.setId(entries.get(0).getId()); - else dataRepo = this.dataRepositoryDao.create(dataRepo); - } - } - - if(dataset.getServices()!=null&&!dataset.getServices().isEmpty()){ - for(eu.eudat.entities.Service service : dataset.getServices()){ - ServiceCriteria criteria = new ServiceCriteria(); - criteria.setLike(service.getReference()); - List entries = this.serviceDao.listBy(criteria); - if(entries!=null&&!entries.isEmpty())service.setId(entries.get(0).getId()); - else service = this.serviceDao.create(service); - } - } - - if(dataset.getRegistries()!=null&&!dataset.getRegistries().isEmpty()){ - for(eu.eudat.entities.Registry registry : dataset.getRegistries()){ - RegistryCriteria criteria = new RegistryCriteria(); - criteria.setLike(registry.getReference()); - List entries = this.registryDao.listBy(criteria); - if(entries!=null&&!entries.isEmpty())registry.setId( entries.get(0).getId()); - else registry = this.registryDao.create(registry); - } - } - - dataset.setId(null); - dataset.setCreated(new Date()); - dataset.setModified(new Date()); - dataset.setStatus(new Short("0")); - dataset.setCreator(userInfo); - if("".equals(dataset.getReference())) dataset.setReference(null); - if("".equals(dataset.getProperties())) dataset.setProperties(null); - - try { - dataset = datasetDao.create(dataset); - return ResponseEntity.status(HttpStatus.CREATED).body(dataset); - } - catch(Exception e) { - e.printStackTrace(); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null); - } - - } - - - @RequestMapping(method = RequestMethod.POST, value = { "/dataset/update" }, consumes = "application/json", produces="application/json") - public @ResponseBody ResponseEntity updateDataset(@RequestBody eu.eudat.models.dataset.Dataset modeldataset) { - - Dataset dataset = modeldataset.toDataModel(); - - if(dataset.getDataRepositories()!=null&&!dataset.getDataRepositories().isEmpty()){ - for(eu.eudat.entities.DataRepository dataRepo : dataset.getDataRepositories()){ - DataRepositoryCriteria criteria = new DataRepositoryCriteria(); - criteria.setLike(dataRepo.getReference()); - List entries = this.dataRepositoryDao.listBy(criteria); - if(entries!=null&&!entries.isEmpty())dataRepo.setId(entries.get(0).getId()); - else dataRepo = this.dataRepositoryDao.create(dataRepo); - } - } - - if(dataset.getServices()!=null&&!dataset.getServices().isEmpty()){ - for(eu.eudat.entities.Service service : dataset.getServices()){ - ServiceCriteria criteria = new ServiceCriteria(); - criteria.setLike(service.getReference()); - List entries = this.serviceDao.listBy(criteria); - if(entries!=null&&!entries.isEmpty())service.setId(entries.get(0).getId()); - else service = this.serviceDao.create(service); - } - } - - if(dataset.getRegistries()!=null&&!dataset.getRegistries().isEmpty()){ - for(eu.eudat.entities.Registry registry : dataset.getRegistries()){ - RegistryCriteria criteria = new RegistryCriteria(); - criteria.setLike(registry.getReference()); - List entries = this.registryDao.listBy(criteria); - if(entries!=null&&!entries.isEmpty())registry.setId( entries.get(0).getId()); - else registry = this.registryDao.create(registry); - } - } - - Dataset olddataset = datasetDao.read(modeldataset.getId()); - - olddataset.getServices().clear(); - olddataset.setServices(dataset.getServices()); - - olddataset.getDataRepositories().clear(); - olddataset.setDataRepositories(dataset.getDataRepositories()); - olddataset.getRegistries().clear(); - olddataset.setRegistries(dataset.getRegistries()); - - olddataset.setLabel(modeldataset.getLabel()); - olddataset.setDescription(modeldataset.getDescription()); - //SafeCleanAttribs.clean(dataset); - - if("".equals(dataset.getReference())) dataset.setReference(null); - if("".equals(dataset.getProperties())) dataset.setProperties(null); - - try { - dataset = datasetDao.update(olddataset); - return ResponseEntity.status(HttpStatus.CREATED).body(dataset); - } - catch(Exception ex) { - ex.printStackTrace(); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Could not create or update Dataset! Reason: " + ex.getMessage()); - } - - } - - - @RequestMapping(method = RequestMethod.POST, value = { "/dataset/delete" }, consumes = "application/json") - public @ResponseBody ResponseEntity deleteDataset(@RequestBody Dataset dataset) { - - //if we want to make sure it won't cascade up to other (child) components, we can just unhook them by setting them = new ones - // e.g: DMP dmp = new DMP() and then dataset.setDMP(dmp) - try { - datasetDao.delete(dataset); - RestResponse rr = new RestResponse("Deleted dataset with id: "+dataset.getId().toString(), dataset.getId().toString()); - return ResponseEntity.status(HttpStatus.OK).body(rr.toString()); - } - catch(Exception e) { - e.printStackTrace(); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Could not delete Dataset! Reason: " + e.getMessage()); - } - } - - - - @RequestMapping(method = RequestMethod.POST, value = { "/dataset/softdelete" }, consumes = "application/json", produces="text/plain") - public @ResponseBody ResponseEntity softDelete(@RequestBody Dataset dataset) { - try { - - Dataset d = datasetDao.read(dataset.getId()); - d.setStatus(new Short("-1")); - dataset = datasetDao.update(d); - return ResponseEntity.status(HttpStatus.OK).body("{\"msg\":\"Deleted dataset!\""); - } catch (Exception e) { - e.printStackTrace(); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("{\"msg\":\"Could not soft delete dataset!\""); - } - - } - - - @RequestMapping(method = RequestMethod.GET, value = { "/dataset/assignDMPToDataset" }) - public @ResponseBody ResponseEntity assignDMPToDataset(@RequestParam("datasetID") String datasetID, @RequestParam("dmpID") String dmpID) { - - Dataset dataset = null; - try { - dataset = datasetDao.read(UUID.fromString(datasetID)); - if(dataset==null || dataset.getId()==null) throw new Exception("Could not find a Dataset by this id"); - DMP dmp = new DMP(); - dmp.setId(UUID.fromString(dmpID)); - dataset.setDmp(dmp); - datasetDao.update(dataset); - return ResponseEntity.status(HttpStatus.OK).build(); - } - catch(Exception ex) { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); - } - - } - - - @RequestMapping(method = RequestMethod.GET, value = { "/dataset/assignProfileToDataset" }) - public @ResponseBody ResponseEntity assignProfileToDataset(@RequestParam("datasetID") String datasetID, @RequestParam("profileID") String profileID) { - - Dataset dataset = null; - try { - dataset = datasetDao.read(UUID.fromString(datasetID)); - if(dataset==null || dataset.getId()==null) throw new Exception("Could not find a Dataset by this id"); - DatasetProfile profile = new DatasetProfile(); - profile.setId(UUID.fromString(profileID)); - dataset.setProfile(profile); - datasetDao.update(dataset); - return ResponseEntity.status(HttpStatus.OK).build(); - } - catch(Exception ex) { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); - } - - } - - - +// @RequestMapping(method = RequestMethod.GET, value = { "/datasets" }) +// public @ResponseBody ResponseEntity> listDatasets(){ +// try { +// List allIDs = datasetDao.listAllIDs(); +// return ResponseEntity.status(HttpStatus.OK).body(allIDs); +// } +// catch(Exception ex) { +// return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null); +// } +// } +// +// +// @RequestMapping(method = RequestMethod.GET, value = { "/datasets/{id}" }) +// public @ResponseBody ResponseEntity getDataset(@PathVariable("id") String id) { +// try { +// Dataset ds = datasetDao.read(UUID.fromString(id)); +// eu.eudat.models.dataset.Dataset dataset = new eu.eudat.models.dataset.Dataset(); +// dataset.fromDataModel(ds); +// return ResponseEntity.status(HttpStatus.OK).body(dataset); +// } +// catch(Exception ex) { +// return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null); +// } +// } +// +// +// /** +// * This should be called on extreme cases. It's computationally intensive +// */ +// @RequestMapping(method = RequestMethod.GET, value = { "/dataset/getAll" }) +// public @ResponseBody ResponseEntity> getAllDatasets(){ +// +// try { +// List allDatasets = datasetDao.getAll(); +// return ResponseEntity.status(HttpStatus.OK).body(allDatasets); +// } +// catch(Exception ex) { +// ex.printStackTrace(); +// return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null); +// } +// +// } +// +// +// @RequestMapping(method = RequestMethod.POST, value = { "/dataset/create" }, consumes = "application/json", produces="application/json") +// public @ResponseBody ResponseEntity createDataset(@RequestBody eu.eudat.models.dataset.Dataset modeldataset) { +// +// String userID = null; +// try { +// userID = SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString(); +// } catch(NullPointerException ex) { +// return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null); +// } +// +// UserInfo userInfo = userInfoDao.read(UUID.fromString(userID)); +// +// if(userInfo==null) //this should normally never happer +// return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null); +// +// +// Dataset dataset = modeldataset.toDataModel(); +// if(dataset.getDataRepositories()!=null&&!dataset.getDataRepositories().isEmpty()){ +// for(eu.eudat.entities.DataRepository dataRepo : dataset.getDataRepositories()){ +// DataRepositoryCriteria criteria = new DataRepositoryCriteria(); +// criteria.setLike(dataRepo.getReference()); +// List entries = this.dataRepositoryDao.listBy(criteria); +// if(entries!=null&&!entries.isEmpty())dataRepo.setId(entries.get(0).getId()); +// else dataRepo = this.dataRepositoryDao.create(dataRepo); +// } +// } +// +// if(dataset.getServices()!=null&&!dataset.getServices().isEmpty()){ +// for(eu.eudat.entities.Service service : dataset.getServices()){ +// ServiceCriteria criteria = new ServiceCriteria(); +// criteria.setLike(service.getReference()); +// List entries = this.serviceDao.listBy(criteria); +// if(entries!=null&&!entries.isEmpty())service.setId(entries.get(0).getId()); +// else service = this.serviceDao.create(service); +// } +// } +// +// if(dataset.getRegistries()!=null&&!dataset.getRegistries().isEmpty()){ +// for(eu.eudat.entities.Registry registry : dataset.getRegistries()){ +// RegistryCriteria criteria = new RegistryCriteria(); +// criteria.setLike(registry.getReference()); +// List entries = this.registryDao.listBy(criteria); +// if(entries!=null&&!entries.isEmpty())registry.setId( entries.get(0).getId()); +// else registry = this.registryDao.create(registry); +// } +// } +// +// dataset.setId(null); +// dataset.setCreated(new Date()); +// dataset.setModified(new Date()); +// dataset.setStatus(new Short("0")); +// dataset.setCreator(userInfo); +// if("".equals(dataset.getReference())) dataset.setReference(null); +// if("".equals(dataset.getProperties())) dataset.setProperties(null); +// +// try { +// dataset = datasetDao.create(dataset); +// return ResponseEntity.status(HttpStatus.CREATED).body(dataset); +// } +// catch(Exception e) { +// e.printStackTrace(); +// return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null); +// } +// +// } +// +// +// @RequestMapping(method = RequestMethod.POST, value = { "/dataset/update" }, consumes = "application/json", produces="application/json") +// public @ResponseBody ResponseEntity updateDataset(@RequestBody eu.eudat.models.dataset.Dataset modeldataset) { +// +// Dataset dataset = modeldataset.toDataModel(); +// +// if(dataset.getDataRepositories()!=null&&!dataset.getDataRepositories().isEmpty()){ +// for(eu.eudat.entities.DataRepository dataRepo : dataset.getDataRepositories()){ +// DataRepositoryCriteria criteria = new DataRepositoryCriteria(); +// criteria.setLike(dataRepo.getReference()); +// List entries = this.dataRepositoryDao.listBy(criteria); +// if(entries!=null&&!entries.isEmpty())dataRepo.setId(entries.get(0).getId()); +// else dataRepo = this.dataRepositoryDao.create(dataRepo); +// } +// } +// +// if(dataset.getServices()!=null&&!dataset.getServices().isEmpty()){ +// for(eu.eudat.entities.Service service : dataset.getServices()){ +// ServiceCriteria criteria = new ServiceCriteria(); +// criteria.setLike(service.getReference()); +// List entries = this.serviceDao.listBy(criteria); +// if(entries!=null&&!entries.isEmpty())service.setId(entries.get(0).getId()); +// else service = this.serviceDao.create(service); +// } +// } +// +// if(dataset.getRegistries()!=null&&!dataset.getRegistries().isEmpty()){ +// for(eu.eudat.entities.Registry registry : dataset.getRegistries()){ +// RegistryCriteria criteria = new RegistryCriteria(); +// criteria.setLike(registry.getReference()); +// List entries = this.registryDao.listBy(criteria); +// if(entries!=null&&!entries.isEmpty())registry.setId( entries.get(0).getId()); +// else registry = this.registryDao.create(registry); +// } +// } +// +// Dataset olddataset = datasetDao.read(modeldataset.getId()); +// +// olddataset.getServices().clear(); +// olddataset.setServices(dataset.getServices()); +// +// olddataset.getDataRepositories().clear(); +// olddataset.setDataRepositories(dataset.getDataRepositories()); +// olddataset.getRegistries().clear(); +// olddataset.setRegistries(dataset.getRegistries()); +// +// olddataset.setLabel(modeldataset.getLabel()); +// olddataset.setDescription(modeldataset.getDescription()); +// //SafeCleanAttribs.clean(dataset); +// +// if("".equals(dataset.getReference())) dataset.setReference(null); +// if("".equals(dataset.getProperties())) dataset.setProperties(null); +// +// try { +// dataset = datasetDao.update(olddataset); +// return ResponseEntity.status(HttpStatus.CREATED).body(dataset); +// } +// catch(Exception ex) { +// ex.printStackTrace(); +// return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Could not create or update Dataset! Reason: " + ex.getMessage()); +// } +// +// } +// +// +// @RequestMapping(method = RequestMethod.POST, value = { "/dataset/delete" }, consumes = "application/json") +// public @ResponseBody ResponseEntity deleteDataset(@RequestBody Dataset dataset) { +// +// //if we want to make sure it won't cascade up to other (child) components, we can just unhook them by setting them = new ones +// // e.g: DMP dmp = new DMP() and then dataset.setDMP(dmp) +// try { +// datasetDao.delete(dataset); +// RestResponse rr = new RestResponse("Deleted dataset with id: "+dataset.getId().toString(), dataset.getId().toString()); +// return ResponseEntity.status(HttpStatus.OK).body(rr.toString()); +// } +// catch(Exception e) { +// e.printStackTrace(); +// return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Could not delete Dataset! Reason: " + e.getMessage()); +// } +// } +// +// +// +// @RequestMapping(method = RequestMethod.POST, value = { "/dataset/softdelete" }, consumes = "application/json", produces="text/plain") +// public @ResponseBody ResponseEntity softDelete(@RequestBody Dataset dataset) { +// try { +// +// Dataset d = datasetDao.read(dataset.getId()); +// d.setStatus(new Short("-1")); +// dataset = datasetDao.update(d); +// return ResponseEntity.status(HttpStatus.OK).body("{\"msg\":\"Deleted dataset!\""); +// } catch (Exception e) { +// e.printStackTrace(); +// return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("{\"msg\":\"Could not soft delete dataset!\""); +// } +// +// } +// +// +// @RequestMapping(method = RequestMethod.GET, value = { "/dataset/assignDMPToDataset" }) +// public @ResponseBody ResponseEntity assignDMPToDataset(@RequestParam("datasetID") String datasetID, @RequestParam("dmpID") String dmpID) { +// +// Dataset dataset = null; +// try { +// dataset = datasetDao.read(UUID.fromString(datasetID)); +// if(dataset==null || dataset.getId()==null) throw new Exception("Could not find a Dataset by this id"); +// DMP dmp = new DMP(); +// dmp.setId(UUID.fromString(dmpID)); +// dataset.setDmp(dmp); +// datasetDao.update(dataset); +// return ResponseEntity.status(HttpStatus.OK).build(); +// } +// catch(Exception ex) { +// return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); +// } +// +// } +// +// +// @RequestMapping(method = RequestMethod.GET, value = { "/dataset/assignProfileToDataset" }) +// public @ResponseBody ResponseEntity assignProfileToDataset(@RequestParam("datasetID") String datasetID, @RequestParam("profileID") String profileID) { +// +// Dataset dataset = null; +// try { +// dataset = datasetDao.read(UUID.fromString(datasetID)); +// if(dataset==null || dataset.getId()==null) throw new Exception("Could not find a Dataset by this id"); +// DatasetProfile profile = new DatasetProfile(); +// profile.setId(UUID.fromString(profileID)); +// dataset.setProfile(profile); +// datasetDao.update(dataset); +// return ResponseEntity.status(HttpStatus.OK).build(); +// } +// catch(Exception ex) { +// return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); +// } +// +// } +// +// +// diff --git a/dmp-backend/src/main/java/eu/eudat/controllers/Login.java b/dmp-backend/src/main/java/eu/eudat/controllers/Login.java index 99a3d70d0..7ed13f7d9 100644 --- a/dmp-backend/src/main/java/eu/eudat/controllers/Login.java +++ b/dmp-backend/src/main/java/eu/eudat/controllers/Login.java @@ -1,11 +1,7 @@ package eu.eudat.controllers; -import eu.eudat.managers.DataManagementPlanManager; -import eu.eudat.models.dmp.DataManagementPlan; -import eu.eudat.models.dmp.DataManagementPlanTableRequest; -import eu.eudat.models.helpers.DataTableData; import eu.eudat.models.login.Credentials; -import eu.eudat.models.responses.ResponseItem; +import eu.eudat.models.helpers.responses.ResponseItem; import eu.eudat.models.security.Principal; import eu.eudat.security.CustomAuthenticationProvider; import org.springframework.beans.factory.annotation.Autowired; diff --git a/dmp-backend/src/main/java/eu/eudat/controllers/Projects.java b/dmp-backend/src/main/java/eu/eudat/controllers/Projects.java index c6f71ec23..b924bf2ab 100644 --- a/dmp-backend/src/main/java/eu/eudat/controllers/Projects.java +++ b/dmp-backend/src/main/java/eu/eudat/controllers/Projects.java @@ -1,24 +1,18 @@ package eu.eudat.controllers; import java.util.Date; -import java.util.HashMap; -import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; -import java.util.stream.Collectors; import javax.transaction.Transactional; -import eu.eudat.models.responses.ResponseItem; -import org.apache.commons.lang3.SerializationUtils; +import eu.eudat.models.helpers.responses.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.util.MultiValueMap; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; @@ -28,11 +22,6 @@ import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; -import com.fasterxml.jackson.annotation.JsonInclude.Include; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.ObjectMapper; - import eu.eudat.dao.entities.DMPDao; import eu.eudat.dao.entities.DMPProfileDao; import eu.eudat.dao.entities.DataRepositoryDao; @@ -47,27 +36,16 @@ import eu.eudat.dao.entities.ResearcherDao; import eu.eudat.dao.entities.ServiceDao; import eu.eudat.dao.entities.UserInfoDao; import eu.eudat.entities.DMP; -import eu.eudat.entities.DMPProfile; -import eu.eudat.entities.DataRepository; -import eu.eudat.entities.Dataset; -import eu.eudat.entities.DatasetProfile; -import eu.eudat.entities.DatasetProfileRuleset; -import eu.eudat.entities.Organisation; import eu.eudat.entities.Project; -import eu.eudat.entities.Registry; -import eu.eudat.entities.Researcher; -import eu.eudat.entities.Service; import eu.eudat.entities.UserInfo; import eu.eudat.entities.responses.IDLabelPair; -import eu.eudat.helpers.Transformers; import eu.eudat.managers.ProjectManager; import eu.eudat.models.helpers.DataTableData; import eu.eudat.models.project.ProjectTableRequest; import eu.eudat.proxy.config.exceptions.HugeResultSet; import eu.eudat.proxy.config.exceptions.NoURLFound; import eu.eudat.proxy.fetching.RemoteFetcher; -import eu.eudat.responses.RestResponse; @RestController @@ -121,7 +99,7 @@ public class Projects { @Transactional @RequestMapping(method = RequestMethod.POST, value = { "/projects/add" }, consumes = "application/json", produces="application/json") public @ResponseBody ResponseItem addProject(@RequestBody eu.eudat.models.project.Project project) { - Project createdProject = projectDao.update(project.toDataModel()); + Project createdProject = projectDao.createOrUpdate(project.toDataModel()); return new ResponseItem().payload(createdProject).status(HttpStatus.OK); } @@ -145,219 +123,219 @@ public class Projects { // MANAGE PROJECT(S) - @RequestMapping(method = RequestMethod.GET, value = { "/projects" }, produces="application/json") - public @ResponseBody ResponseEntity> listProjects(){ - try { - List allIDs = projectDao.listAllIDs(); - return ResponseEntity.status(HttpStatus.OK).body(allIDs); - } - catch(Exception ex) { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null); - } - } - - @RequestMapping(method = RequestMethod.GET, value = { "/projects/{id}" }, produces="application/json") - public @ResponseBody ResponseEntity getProject(@PathVariable("id") String id) { - try { - Project project = projectDao.read(UUID.fromString(id)); - - System.out.println(project.getId().toString()); - - return ResponseEntity.status(HttpStatus.OK).body(project); - } - catch(Exception ex) { - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null); - } - } - - - @RequestMapping(method = RequestMethod.GET, value = { "/project/listAllLabelIDs" }, produces="application/json") - public @ResponseBody ResponseEntity> listLabelIds(){ - try { - List allIDs = projectDao.listAllIDsLabels(); - return ResponseEntity.status(HttpStatus.OK).body(allIDs); - } - catch(Exception ex) { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null); - } - } - - - @RequestMapping(method = RequestMethod.GET, value = { "/project/getAll" }, produces="application/json") - public @ResponseBody ResponseEntity getAllProjects(){ - try { - List allProjects = projectDao.getAll(); - return ResponseEntity.status(HttpStatus.OK).body(allProjects); - } - catch(Exception ex) { - return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR); - } - } - - - - @Transactional - @RequestMapping(method = RequestMethod.POST, value = { "/project/create" }, consumes = "application/json", produces="application/json") - public @ResponseBody ResponseEntity createProject(@RequestBody Project project) { - Project createdProject = projectDao.update(project); - return ResponseEntity.status(HttpStatus.CREATED).body(createdProject); - } - - - - @RequestMapping(method = RequestMethod.POST, value = { "/project/update" }, consumes = "application/json", produces="application/json") - public @ResponseBody ResponseEntity updateProject(@RequestBody Project project) { - Project updatedProject = projectDao.update(project); - return ResponseEntity.status(HttpStatus.CREATED).body(updatedProject); - } - - - @RequestMapping(method = RequestMethod.POST, value = { "/project/delete" }, consumes = "application/json", produces="application/json") - public @ResponseBody ResponseEntity delete(@RequestBody Project project) { - - Project p = new Project(); - p.setId(project.getId()); - try { - projectDao.delete(p); - return ResponseEntity.status(HttpStatus.CREATED).body(null); - } catch (Exception e) { - e.printStackTrace(); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null); - } - - } - - - - @RequestMapping(method = RequestMethod.POST, value = { "/project/softdelete" }, consumes = "application/json", produces="application/json") - public @ResponseBody ResponseEntity softDelete(@RequestBody Project project) { - - project.setStatus(new Short("-1")); - - try { - projectDao.update(project); - return ResponseEntity.status(HttpStatus.CREATED).body(null); - } catch (Exception e) { - e.printStackTrace(); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null); - } - - } - - - @Transactional - @RequestMapping(method = RequestMethod.POST, value = { "/project/getdmps" }, consumes = "application/json", produces="application/json") - public @ResponseBody ResponseEntity getProjectDmps(@RequestBody Project project) { - try { - Set dmps = projectDao.read(project.getId()).getDmps(); - return ResponseEntity.status(HttpStatus.CREATED).body(dmps); - } catch (Exception e) { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null); - } - } - - - - //////////////////////////////// - //// USER - RELATED ACTIONS //// - //////////////////////////////// - - - @RequestMapping(method = RequestMethod.GET, value = { "/project/getofuser" }, produces="text/plain") - public @ResponseBody ResponseEntity getProjectsOfUser(){ - - String userID = null; - try { - userID = SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString(); - } catch(NullPointerException ex) { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("You have not logged in. You shouldn't be here"); - } - - UserInfo userInfo = userInfoDao.read(UUID.fromString(userID)); - - if(userInfo==null) //this should normally never happen - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("There's no such a user on the system. You shouldn't be here"); - - - try { - List userProjects = projectDao.getProjectsOfUser(userID); - return ResponseEntity.status(HttpStatus.OK).body(userProjects); - } - catch(Exception ex) { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null); - } - - - /* - * OLD ONE - Map userProjects = new HashMap(); - - userInfo.getDmps().forEach( dmp -> { - Researcher proj = dmp.getProject(); - userProjects.put(proj.getId(), proj); - }); - - try { - return ResponseEntity.status(HttpStatus.OK).body(SerializerProvider.toJson(userProjects.values())); - } - catch(Exception ex) { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Serialization issue: "+ex.getMessage()); - } - */ - - } - - @Transactional - @RequestMapping(method = RequestMethod.POST, value = { "/project/createofuser" }, produces="text/plain", consumes = "application/json") - public @ResponseBody ResponseEntity createProjectOfUser(@RequestBody Project project){ - - - String userID = null; - try { - userID = SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString(); - } catch(NullPointerException ex) { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null); - } - - UserInfo userInfo = userInfoDao.read(UUID.fromString(userID)); - - - if(userInfo==null) //this should normally never happer - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null); - - try { - - project.setId(null); - project.setStatus(new Short("0")); - project.setCreationUser(userInfo); - project.setCreated(new Date()); - project.setModified(new Date()); - - Project newproj = projectDao.create(project); - -// DMP newdmp = new DMP(); -// newdmp.setId(null); -// newdmp.setLabel("Auto-Generated"); -// newdmp.setCreated(new Date()); -// newdmp.setVersion(1); -// newdmp.setStatus(new Short("0")); -// newdmp.setProject(newproj); -// -// Set users = new HashSet(); -// users.add(userInfo); -// newdmp.setUsers(users); -// -// newdmp = dMPDao.create(newdmp); - - return ResponseEntity.status(HttpStatus.OK).body(newproj); - } - catch(Exception ex) { - ex.printStackTrace(); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null); - } - - } - +// @RequestMapping(method = RequestMethod.GET, value = { "/projects" }, produces="application/json") +// public @ResponseBody ResponseEntity> listProjects(){ +// try { +// List allIDs = projectDao.listAllIDs(); +// return ResponseEntity.status(HttpStatus.OK).body(allIDs); +// } +// catch(Exception ex) { +// return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null); +// } +// } +// +// @RequestMapping(method = RequestMethod.GET, value = { "/projects/{id}" }, produces="application/json") +// public @ResponseBody ResponseEntity getProject(@PathVariable("id") String id) { +// try { +// Project project = projectDao.read(UUID.fromString(id)); +// +// System.out.println(project.getId().toString()); +// +// return ResponseEntity.status(HttpStatus.OK).body(project); +// } +// catch(Exception ex) { +// return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null); +// } +// } +// +// +// @RequestMapping(method = RequestMethod.GET, value = { "/project/listAllLabelIDs" }, produces="application/json") +// public @ResponseBody ResponseEntity> listLabelIds(){ +// try { +// List allIDs = projectDao.listAllIDsLabels(); +// return ResponseEntity.status(HttpStatus.OK).body(allIDs); +// } +// catch(Exception ex) { +// return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null); +// } +// } +// +// +// @RequestMapping(method = RequestMethod.GET, value = { "/project/getAll" }, produces="application/json") +// public @ResponseBody ResponseEntity getAllProjects(){ +// try { +// List allProjects = projectDao.getAll(); +// return ResponseEntity.status(HttpStatus.OK).body(allProjects); +// } +// catch(Exception ex) { +// return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR); +// } +// } +// +// +// +// @Transactional +// @RequestMapping(method = RequestMethod.POST, value = { "/project/create" }, consumes = "application/json", produces="application/json") +// public @ResponseBody ResponseEntity createProject(@RequestBody Project project) { +// Project createdProject = projectDao.update(project); +// return ResponseEntity.status(HttpStatus.CREATED).body(createdProject); +// } +// +// +// +// @RequestMapping(method = RequestMethod.POST, value = { "/project/update" }, consumes = "application/json", produces="application/json") +// public @ResponseBody ResponseEntity updateProject(@RequestBody Project project) { +// Project updatedProject = projectDao.update(project); +// return ResponseEntity.status(HttpStatus.CREATED).body(updatedProject); +// } +// +// +// @RequestMapping(method = RequestMethod.POST, value = { "/project/delete" }, consumes = "application/json", produces="application/json") +// public @ResponseBody ResponseEntity delete(@RequestBody Project project) { +// +// Project p = new Project(); +// p.setId(project.getId()); +// try { +// projectDao.delete(p); +// return ResponseEntity.status(HttpStatus.CREATED).body(null); +// } catch (Exception e) { +// e.printStackTrace(); +// return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null); +// } +// +// } +// +// +// +// @RequestMapping(method = RequestMethod.POST, value = { "/project/softdelete" }, consumes = "application/json", produces="application/json") +// public @ResponseBody ResponseEntity softDelete(@RequestBody Project project) { +// +// project.setStatus(new Short("-1")); +// +// try { +// projectDao.update(project); +// return ResponseEntity.status(HttpStatus.CREATED).body(null); +// } catch (Exception e) { +// e.printStackTrace(); +// return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null); +// } +// +// } +// +// +// @Transactional +// @RequestMapping(method = RequestMethod.POST, value = { "/project/getdmps" }, consumes = "application/json", produces="application/json") +// public @ResponseBody ResponseEntity getProjectDmps(@RequestBody Project project) { +// try { +// Set dmps = projectDao.read(project.getId()).getDmps(); +// return ResponseEntity.status(HttpStatus.CREATED).body(dmps); +// } catch (Exception e) { +// return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null); +// } +// } +// +// +// +// //////////////////////////////// +// //// USER - RELATED ACTIONS //// +// //////////////////////////////// +// +// +// @RequestMapping(method = RequestMethod.GET, value = { "/project/getofuser" }, produces="text/plain") +// public @ResponseBody ResponseEntity getProjectsOfUser(){ +// +// String userID = null; +// try { +// userID = SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString(); +// } catch(NullPointerException ex) { +// return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("You have not logged in. You shouldn't be here"); +// } +// +// UserInfo userInfo = userInfoDao.read(UUID.fromString(userID)); +// +// if(userInfo==null) //this should normally never happen +// return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("There's no such a user on the system. You shouldn't be here"); +// +// +// try { +// List userProjects = projectDao.getProjectsOfUser(userID); +// return ResponseEntity.status(HttpStatus.OK).body(userProjects); +// } +// catch(Exception ex) { +// return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null); +// } +// +// +// /* +// * OLD ONE +// Map userProjects = new HashMap(); +// +// userInfo.getDmps().forEach( dmp -> { +// Researcher proj = dmp.getProject(); +// userProjects.put(proj.getId(), proj); +// }); +// +// try { +// return ResponseEntity.status(HttpStatus.OK).body(SerializerProvider.toJson(userProjects.values())); +// } +// catch(Exception ex) { +// return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Serialization issue: "+ex.getMessage()); +// } +// */ +// +// } +// +// @Transactional +// @RequestMapping(method = RequestMethod.POST, value = { "/project/createofuser" }, produces="text/plain", consumes = "application/json") +// public @ResponseBody ResponseEntity createProjectOfUser(@RequestBody Project project){ +// +// +// String userID = null; +// try { +// userID = SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString(); +// } catch(NullPointerException ex) { +// return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null); +// } +// +// UserInfo userInfo = userInfoDao.read(UUID.fromString(userID)); +// +// +// if(userInfo==null) //this should normally never happer +// return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null); +// +// try { +// +// project.setId(null); +// project.setStatus(new Short("0")); +// project.setCreationUser(userInfo); +// project.setCreated(new Date()); +// project.setModified(new Date()); +// +// Project newproj = projectDao.create(project); +// +//// DMP newdmp = new DMP(); +//// newdmp.setId(null); +//// newdmp.setLabel("Auto-Generated"); +//// newdmp.setCreated(new Date()); +//// newdmp.setVersion(1); +//// newdmp.setStatus(new Short("0")); +//// newdmp.setProject(newproj); +//// +//// Set users = new HashSet(); +//// users.add(userInfo); +//// newdmp.setUsers(users); +//// +//// newdmp = dMPDao.create(newdmp); +// +// return ResponseEntity.status(HttpStatus.OK).body(newproj); +// } +// catch(Exception ex) { +// ex.printStackTrace(); +// return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null); +// } +// +// } +// // @Transactional // @RequestMapping(method = RequestMethod.POST, value = { "/project/updateofuser" }, produces="text/plain") // public @ResponseBody ResponseEntity updateProjectOfUser(@RequestBody Researcher project){ diff --git a/dmp-backend/src/main/java/eu/eudat/dao/databaselayer/context/DatabaseContext.java b/dmp-backend/src/main/java/eu/eudat/dao/databaselayer/context/DatabaseContext.java new file mode 100644 index 000000000..0ba671cb0 --- /dev/null +++ b/dmp-backend/src/main/java/eu/eudat/dao/databaselayer/context/DatabaseContext.java @@ -0,0 +1,42 @@ +package eu.eudat.dao.databaselayer.context; + +import eu.eudat.entities.DataEntity; +import eu.eudat.queryable.QueryableList; +import eu.eudat.queryable.hibernatequeryablelist.QueryableHibernateList; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Repository; + +import javax.persistence.EntityManager; +import javax.persistence.TypedQuery; +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.CriteriaQuery; +import javax.persistence.criteria.Root; +import java.util.List; + +/** + * Created by giannis on 7/16/2017. + */ +@Repository("databaseCtx") +public class DatabaseContext> { + @Autowired + private EntityManager entityManager; + + public QueryableList getQueryable(Class type) { + return new QueryableHibernateList<>(this.entityManager, type).setEntity(type); + } + + public T createOrUpdate(T item, Class type) { + if (item.getKeys()[0] != null) { + T oldItem = entityManager.find(type, item.getKeys()[0]); + oldItem.update(item); + entityManager.merge(oldItem); + return oldItem; + } else entityManager.persist(item); + return item; + } + + public long count(Class entityClass) { + return ((Number) entityManager.createQuery("select count(e) from " + entityClass.getSimpleName() + " e").getSingleResult()).longValue(); + } + +} diff --git a/dmp-backend/src/main/java/eu/eudat/dao/databaselayer/service/DatabaseService.java b/dmp-backend/src/main/java/eu/eudat/dao/databaselayer/service/DatabaseService.java new file mode 100644 index 000000000..0542132f6 --- /dev/null +++ b/dmp-backend/src/main/java/eu/eudat/dao/databaselayer/service/DatabaseService.java @@ -0,0 +1,27 @@ +package eu.eudat.dao.databaselayer.service; + + +import eu.eudat.dao.databaselayer.context.DatabaseContext; +import eu.eudat.entities.DataEntity; +import eu.eudat.queryable.QueryableList; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +/** + * Created by giannis on 7/17/2017. + */ +@Service("databaseService") +public class DatabaseService> { + @Autowired + private DatabaseContext databaseCtx; + + public QueryableList getQueryable(Class tClass) { + return this.databaseCtx.getQueryable(tClass); + } + + public T createOrUpdate(T item, Class tClass) { + return this.databaseCtx.createOrUpdate(item, tClass); + } + + public Long count(Class tClass){return this.databaseCtx.count(tClass);} +} diff --git a/dmp-backend/src/main/java/eu/eudat/dao/entities/DMPDao.java b/dmp-backend/src/main/java/eu/eudat/dao/entities/DMPDao.java index da009b8e0..f23c92ea1 100644 --- a/dmp-backend/src/main/java/eu/eudat/dao/entities/DMPDao.java +++ b/dmp-backend/src/main/java/eu/eudat/dao/entities/DMPDao.java @@ -6,17 +6,19 @@ import java.util.UUID; import eu.eudat.dao.Dao; import eu.eudat.entities.DMP; import eu.eudat.entities.responses.IDLabelPair; +import eu.eudat.models.criteria.DataManagementPlanCriteria; import eu.eudat.models.dmp.DataManagementPlanTableRequest; +import eu.eudat.queryable.QueryableList; import org.springframework.stereotype.Service; -public interface DMPDao extends Dao { +public interface DMPDao { - public List listAllIDs(); + public QueryableList getWithCriteria(DataManagementPlanCriteria criteria); - List listAllIDsLabels(); - - List getDMPsOfUser(String userID); - - public List getWithCriteria(DataManagementPlanTableRequest dataManagementPlanTableRequest); + DMP createOrUpdate(DMP item); + + DMP find(UUID id); + + Long count(); } \ No newline at end of file diff --git a/dmp-backend/src/main/java/eu/eudat/dao/entities/DMPDaoImpl.java b/dmp-backend/src/main/java/eu/eudat/dao/entities/DMPDaoImpl.java index 54041aede..276db6e37 100644 --- a/dmp-backend/src/main/java/eu/eudat/dao/entities/DMPDaoImpl.java +++ b/dmp-backend/src/main/java/eu/eudat/dao/entities/DMPDaoImpl.java @@ -10,65 +10,46 @@ import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Root; +import eu.eudat.dao.databaselayer.service.DatabaseService; +import eu.eudat.entities.Project; +import eu.eudat.models.criteria.DataManagementPlanCriteria; +import eu.eudat.queryable.QueryableList; import org.hibernate.query.Query; import eu.eudat.dao.JpaDao; import eu.eudat.entities.DMP; import eu.eudat.entities.responses.IDLabelPair; import eu.eudat.models.dmp.DataManagementPlanTableRequest; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component("dMPDao") -public class DMPDaoImpl extends JpaDao implements DMPDao { +public class DMPDaoImpl implements DMPDao { - public DMP loadDetails(DMP t) { - // TODO Auto-generated method stub - return null; + + @Autowired + DatabaseService databaseService; + + @Override + public QueryableList getWithCriteria(DataManagementPlanCriteria criteria) { + QueryableList query = databaseService.getQueryable(DMP.class); + if(criteria.getLike()!=null&&!criteria.getLike().isEmpty())query.where((builder, root) -> builder.like(root.get("label"),"%"+criteria.getLike()+"%")); + if(criteria.getPeriodEnd()!=null)query.where((builder, root) -> builder.lessThan(root.get("created"),criteria.getPeriodEnd())); + if(criteria.getPeriodStart()!=null)query.where((builder, root) -> builder.greaterThan(root.get("created"),criteria.getPeriodStart())); + return query; } @Override - public List listAllIDs() { - String queryString = "SELECT dmp.id FROM DMP dmp where dmp.status>=0"; - TypedQuery typedQuery = entityManager.createQuery(queryString, UUID.class); - return typedQuery.getResultList(); - } - - - @Override - public List listAllIDsLabels() { - String queryString = "SELECT dmp.id, dmp.label FROM DMP dmp where dmp.status>=0"; - Query query = (Query) entityManager.createQuery(queryString); - List rows = query.list(); - return rows.stream().map(row -> { - return new IDLabelPair(row[0].toString(), row[1].toString()); - }) - .collect(Collectors.toList()); + public DMP createOrUpdate(DMP item) { + return this.databaseService.createOrUpdate(item,DMP.class); } @Override - public List getDMPsOfUser(String userID) { - - String queryString = "select dmp from DMP dmp where dmp.creator.id=:userid and dmp.status >= 0"; - TypedQuery typedQuery = entityManager.createQuery(queryString, DMP.class); - typedQuery.setParameter("userid", UUID.fromString(userID)); - try { - return typedQuery.getResultList(); - } - catch(Exception ex) { //no need to distinguish between eu.eudat.exceptions for the moment - ex.printStackTrace(); - return null; - } + public DMP find(UUID id) { + return databaseService.getQueryable(DMP.class).where((builder, root) -> builder.equal((root.get("id")),id)).toList().get(0); } - @Override - public List getWithCriteria(DataManagementPlanTableRequest dataManagementPlanTableRequest) { - CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); - CriteriaQuery criteriaQuery = criteriaBuilder .createQuery(DMP.class); - Root root = criteriaQuery.from(DMP.class); - TypedQuery typedQuery = entityManager.createQuery(criteriaQuery); - typedQuery.setFirstResult(dataManagementPlanTableRequest.getOffset()); - typedQuery.setMaxResults(dataManagementPlanTableRequest.getLength()); - return typedQuery.getResultList(); - } - + public Long count(){ + return this.databaseService.count(DMP.class); + } } diff --git a/dmp-backend/src/main/java/eu/eudat/dao/entities/DataRepositoryDao.java b/dmp-backend/src/main/java/eu/eudat/dao/entities/DataRepositoryDao.java index 84b2289a9..7460943d4 100644 --- a/dmp-backend/src/main/java/eu/eudat/dao/entities/DataRepositoryDao.java +++ b/dmp-backend/src/main/java/eu/eudat/dao/entities/DataRepositoryDao.java @@ -9,12 +9,7 @@ import eu.eudat.entities.responses.IDLabelPair; import eu.eudat.models.criteria.Criteria; import org.springframework.stereotype.Service; -public interface DataRepositoryDao extends Dao { - - List listAllIDs(); - - List listAllIDsLabels(); - +public interface DataRepositoryDao { List listBy(Criteria criteria); - + DataRepository createOrUpdate(DataRepository item); } \ No newline at end of file diff --git a/dmp-backend/src/main/java/eu/eudat/dao/entities/DataRepositoryDaoImpl.java b/dmp-backend/src/main/java/eu/eudat/dao/entities/DataRepositoryDaoImpl.java index 2e8ecbd8e..493c044a6 100644 --- a/dmp-backend/src/main/java/eu/eudat/dao/entities/DataRepositoryDaoImpl.java +++ b/dmp-backend/src/main/java/eu/eudat/dao/entities/DataRepositoryDaoImpl.java @@ -9,52 +9,33 @@ import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Root; +import eu.eudat.dao.databaselayer.service.DatabaseService; +import eu.eudat.queryable.QueryableList; import org.hibernate.query.Query; import eu.eudat.dao.JpaDao; import eu.eudat.entities.DataRepository; import eu.eudat.entities.responses.IDLabelPair; import eu.eudat.models.criteria.Criteria; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.stereotype.Service; @Component("dataRepositoryDao") -public class DataRepositoryDaoImpl extends JpaDao implements DataRepositoryDao { - - public DataRepository loadDetails(DataRepository t) { - // TODO Auto-generated method stub - return null; - } - - @Override - public List listAllIDs() { - String queryString = "SELECT dataRepository.id FROM DataRepository dataRepository"; - TypedQuery typedQuery = entityManager.createQuery(queryString, UUID.class); - return typedQuery.getResultList(); - } - - - @Override - public List listAllIDsLabels() { - String queryString = "SELECT dataRepository.id, dataRepository.label FROM DataRepository dataRepository"; - Query query = (Query) entityManager.createQuery(queryString); - List rows = query.list(); - return rows.stream().map(row -> { - return new IDLabelPair(row[0].toString(), row[1].toString()); - }) - .collect(Collectors.toList()); - } +public class DataRepositoryDaoImpl implements DataRepositoryDao{ + @Autowired + DatabaseService databaseService; @Override public List listBy(Criteria criteria) { - CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); - CriteriaQuery criteriaQuery = criteriaBuilder .createQuery(DataRepository.class); - Root root = criteriaQuery.from(DataRepository.class); - criteriaQuery.where(criteriaBuilder.equal(root.get("reference"), criteria.getLike())); - TypedQuery typedQuery = entityManager.createQuery(criteriaQuery); - return typedQuery.getResultList(); + QueryableList query = databaseService.getQueryable(DataRepository.class); + if(criteria.getLike()!=null)query.where((builder, root) -> builder.equal(root.get("reference"),criteria.getLike())); + return query.toList(); } - + @Override + public DataRepository createOrUpdate(DataRepository item) { + return databaseService.createOrUpdate(item,DataRepository.class); + } } diff --git a/dmp-backend/src/main/java/eu/eudat/dao/entities/DatasetDao.java b/dmp-backend/src/main/java/eu/eudat/dao/entities/DatasetDao.java index 098b5178f..1c21091f7 100644 --- a/dmp-backend/src/main/java/eu/eudat/dao/entities/DatasetDao.java +++ b/dmp-backend/src/main/java/eu/eudat/dao/entities/DatasetDao.java @@ -7,19 +7,23 @@ import eu.eudat.dao.Dao; import eu.eudat.entities.Dataset; import eu.eudat.entities.Project; import eu.eudat.entities.responses.IDLabelPair; +import eu.eudat.models.criteria.DatasetCriteria; +import eu.eudat.models.criteria.ProjectCriteria; import eu.eudat.models.dataset.DatasetTableRequest; import eu.eudat.models.project.ProjectTableRequest; +import eu.eudat.queryable.QueryableList; import org.springframework.stereotype.Service; -public interface DatasetDao extends Dao { +public interface DatasetDao { - public List listAllIDs(); + public QueryableList getWithCriteria(DatasetCriteria criteria); - List listAllIDsLabels(); + Dataset createOrUpdate(Dataset item); - List getDatasetsOfDmp(UUID dmpID); + Dataset find(UUID id); + + Long count(); - public List getWithCriteria(DatasetTableRequest datasetTableRequest); } \ No newline at end of file diff --git a/dmp-backend/src/main/java/eu/eudat/dao/entities/DatasetDaoImpl.java b/dmp-backend/src/main/java/eu/eudat/dao/entities/DatasetDaoImpl.java index 87fd944fb..867430860 100644 --- a/dmp-backend/src/main/java/eu/eudat/dao/entities/DatasetDaoImpl.java +++ b/dmp-backend/src/main/java/eu/eudat/dao/entities/DatasetDaoImpl.java @@ -12,56 +12,40 @@ import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Root; import eu.eudat.dao.JpaDao; +import eu.eudat.dao.databaselayer.service.DatabaseService; import eu.eudat.entities.Dataset; import eu.eudat.entities.Project; import eu.eudat.entities.responses.IDLabelPair; +import eu.eudat.models.criteria.DatasetCriteria; import eu.eudat.models.dataset.DatasetTableRequest; +import eu.eudat.queryable.QueryableList; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component("datasetDao") -public class DatasetDaoImpl extends JpaDao implements DatasetDao { +public class DatasetDaoImpl implements DatasetDao { + + @Autowired + DatabaseService databaseService; - public Dataset loadDetails(Dataset t) { - // TODO Auto-generated method stub - return null; - } - @Override - public List listAllIDs() { - String queryString = "SELECT dataset.id FROM Dataset dataset where dataset.status>=0"; - TypedQuery typedQuery = entityManager.createQuery(queryString, UUID.class); - return typedQuery.getResultList(); - } - - - @Override - public List listAllIDsLabels() { - String queryString = "SELECT dataset.id, dataset.label FROM Dataset dataset where dataset.status>=0"; - Query query = (Query) entityManager.createQuery(queryString); - List rows = query.getResultList(); - return rows.stream().map(row -> { - return new IDLabelPair(row[0].toString(), row[1].toString()); - }) - .collect(Collectors.toList()); + public QueryableList getWithCriteria(DatasetCriteria criteria) { + QueryableList query = databaseService.getQueryable(Dataset.class); + if(criteria.getLike()!=null&&!criteria.getLike().isEmpty())query.where((builder, root) -> builder.like(root.get("label"),"%"+criteria.getLike()+"%")); + return query; } @Override - public List getDatasetsOfDmp(UUID dmpID) { - String queryString = "FROM Dataset dataset where dataset.dmp.id=:dmpID and dataset.status>=0"; - Query query = (Query) entityManager.createQuery(queryString); - query.setParameter("dmpID", dmpID); - List datasets = (List) query.getResultList(); - return datasets; + public Dataset createOrUpdate(Dataset item) { + return databaseService.createOrUpdate(item,Dataset.class); } @Override - public List getWithCriteria(DatasetTableRequest datasetTableRequest) { - CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); - CriteriaQuery criteriaQuery = criteriaBuilder .createQuery(Dataset.class); - Root root = criteriaQuery.from(Dataset.class); - TypedQuery typedQuery = entityManager.createQuery(criteriaQuery); - typedQuery.setFirstResult(datasetTableRequest.getOffset()); - typedQuery.setMaxResults(datasetTableRequest.getLength()); - return typedQuery.getResultList(); + public Dataset find(UUID id) { + return databaseService.getQueryable(Dataset.class).where((builder, root) -> builder.equal((root.get("id")),id)).toList().get(0); + } + + public Long count(){ + return this.databaseService.count(Dataset.class); } } diff --git a/dmp-backend/src/main/java/eu/eudat/dao/entities/DatasetServiceDao.java b/dmp-backend/src/main/java/eu/eudat/dao/entities/DatasetServiceDao.java index fac40ee7e..bdf42280e 100644 --- a/dmp-backend/src/main/java/eu/eudat/dao/entities/DatasetServiceDao.java +++ b/dmp-backend/src/main/java/eu/eudat/dao/entities/DatasetServiceDao.java @@ -6,6 +6,6 @@ import eu.eudat.dao.Dao; import eu.eudat.entities.DatasetService; import org.springframework.stereotype.Service; -public interface DatasetServiceDao extends Dao { +public interface DatasetServiceDao { } \ No newline at end of file diff --git a/dmp-backend/src/main/java/eu/eudat/dao/entities/ProjectDao.java b/dmp-backend/src/main/java/eu/eudat/dao/entities/ProjectDao.java index 23143beb4..6545833e8 100644 --- a/dmp-backend/src/main/java/eu/eudat/dao/entities/ProjectDao.java +++ b/dmp-backend/src/main/java/eu/eudat/dao/entities/ProjectDao.java @@ -6,17 +6,18 @@ import java.util.UUID; import eu.eudat.dao.Dao; import eu.eudat.entities.Project; import eu.eudat.entities.responses.IDLabelPair; +import eu.eudat.models.criteria.ProjectCriteria; import eu.eudat.models.project.ProjectTableRequest; +import eu.eudat.queryable.QueryableList; import org.springframework.stereotype.Service; -public interface ProjectDao extends Dao { +public interface ProjectDao { - public List listAllIDs(); + QueryableList getWithCriteria(ProjectCriteria criteria); - public List listAllIDsLabels(); - - public List getProjectsOfUser(String userID); - - public List getWithCriteria(ProjectTableRequest projectTableRequest); - + Project createOrUpdate(Project item); + + Project find(UUID id); + + Long count(); } \ No newline at end of file diff --git a/dmp-backend/src/main/java/eu/eudat/dao/entities/ProjectDaoImpl.java b/dmp-backend/src/main/java/eu/eudat/dao/entities/ProjectDaoImpl.java index 7f2ebf436..7a88e1f94 100644 --- a/dmp-backend/src/main/java/eu/eudat/dao/entities/ProjectDaoImpl.java +++ b/dmp-backend/src/main/java/eu/eudat/dao/entities/ProjectDaoImpl.java @@ -9,70 +9,44 @@ import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Root; +import eu.eudat.dao.databaselayer.service.DatabaseService; +import eu.eudat.models.criteria.ProjectCriteria; +import eu.eudat.queryable.QueryableList; import org.hibernate.query.Query; import eu.eudat.dao.JpaDao; import eu.eudat.entities.Project; import eu.eudat.entities.responses.IDLabelPair; import eu.eudat.models.project.ProjectTableRequest; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component("projectDao") -public class ProjectDaoImpl extends JpaDao implements ProjectDao { +public class ProjectDaoImpl implements ProjectDao { - public Project loadDetails(Project t) { - // TODO Auto-generated method stub - return null; + @Autowired + DatabaseService databaseService; + + @Override + public QueryableList getWithCriteria(ProjectCriteria criteria) { + QueryableList query = databaseService.getQueryable(Project.class); + if(criteria.getLike()!=null&&!criteria.getLike().isEmpty())query.where((builder, root) -> builder.like(root.get("label"),"%"+criteria.getLike()+"%")); + if(criteria.getPeriodEnd()!=null)query.where((builder, root) -> builder.lessThan(root.get("created"),criteria.getPeriodEnd())); + if(criteria.getPeriodStart()!=null)query.where((builder, root) -> builder.greaterThan(root.get("created"),criteria.getPeriodStart())); + return query; } @Override - public List listAllIDs() { - String queryString = "SELECT project.id FROM Project project"; - TypedQuery typedQuery = entityManager.createQuery(queryString, UUID.class); - return typedQuery.getResultList(); - } - - - @Override - public List listAllIDsLabels() { - String queryString = "SELECT project.id, project.label FROM Project project"; - Query query = (Query) entityManager.createQuery(queryString); - List rows = query.list(); - return rows.stream().map(row -> { - return new IDLabelPair(row[0].toString(), row[1].toString()); - }) - .collect(Collectors.toList()); - } - - - public List getProjectsOfUser(String userID){ - - String queryString = "select p from Project p where p.creationUser.id=:userid and project.status >= 0"; - TypedQuery typedQuery = entityManager.createQuery(queryString, Project.class); - typedQuery.setParameter("userid", UUID.fromString(userID)); - try { - return typedQuery.getResultList(); - } - catch(Exception ex) { //no need to distinguish between eu.eudat.exceptions for the moment - ex.printStackTrace(); - return null; - } - + public Project createOrUpdate(Project item) { + return databaseService.createOrUpdate(item,Project.class); } @Override - public List getWithCriteria(ProjectTableRequest projectTableRequest) { - CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); - CriteriaQuery criteriaQuery = criteriaBuilder .createQuery(Project.class); - Root root = criteriaQuery.from(Project.class); - TypedQuery typedQuery = entityManager.createQuery(criteriaQuery); - typedQuery.setFirstResult(projectTableRequest.getOffset()); - typedQuery.setMaxResults(projectTableRequest.getLength()); - return typedQuery.getResultList(); + public Project find(UUID id) { + return databaseService.getQueryable(Project.class).where((builder, root) -> builder.equal((root.get("id")),id)).toList().get(0); } - - - - + public Long count(){ + return this.databaseService.count(Project.class); + } } diff --git a/dmp-backend/src/main/java/eu/eudat/entities/DMP.java b/dmp-backend/src/main/java/eu/eudat/entities/DMP.java index 247fbc9c5..fb9d28652 100644 --- a/dmp-backend/src/main/java/eu/eudat/entities/DMP.java +++ b/dmp-backend/src/main/java/eu/eudat/entities/DMP.java @@ -27,7 +27,7 @@ import com.fasterxml.jackson.annotation.ObjectIdGenerators; @Entity @Table(name="\"DMP\"") @JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="id", scope = DMP.class) -public class DMP implements Serializable,DataEntity { +public class DMP implements Serializable,DataEntity { private static final long serialVersionUID = -8263056535208547615L; @@ -250,6 +250,16 @@ public class DMP implements Serializable,DataEntity { public void setResearchers(Set researchers) { this.researchers = researchers; } + + @Override + public void update(DMP entity) { + + } + + @Override + public Object[] getKeys() { + return new UUID[]{this.id == null ? null : this.id}; + } diff --git a/dmp-backend/src/main/java/eu/eudat/entities/DataEntity.java b/dmp-backend/src/main/java/eu/eudat/entities/DataEntity.java index da0055444..1be39124a 100644 --- a/dmp-backend/src/main/java/eu/eudat/entities/DataEntity.java +++ b/dmp-backend/src/main/java/eu/eudat/entities/DataEntity.java @@ -1,4 +1,7 @@ package eu.eudat.entities; -public interface DataEntity { +public interface DataEntity { + void update(T entity); + + Object[] getKeys(); } diff --git a/dmp-backend/src/main/java/eu/eudat/entities/DataRepository.java b/dmp-backend/src/main/java/eu/eudat/entities/DataRepository.java index e5cd2d932..933a6290b 100644 --- a/dmp-backend/src/main/java/eu/eudat/entities/DataRepository.java +++ b/dmp-backend/src/main/java/eu/eudat/entities/DataRepository.java @@ -25,7 +25,7 @@ import com.fasterxml.jackson.annotation.ObjectIdGenerators; @Entity @Table(name="\"DataRepository\"") @JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="id") -public class DataRepository implements Serializable,DataEntity { +public class DataRepository implements Serializable,DataEntity { private static final long serialVersionUID = 4162323701450468639L; @@ -162,5 +162,13 @@ public class DataRepository implements Serializable,DataEntity { this.datasets = datasets; } - + @Override + public void update(DataRepository entity) { + + } + + @Override + public Object[] getKeys() { + return new UUID[]{this.id == null ? null : this.id}; + } } diff --git a/dmp-backend/src/main/java/eu/eudat/entities/Dataset.java b/dmp-backend/src/main/java/eu/eudat/entities/Dataset.java index 160987fdc..f74e685f9 100644 --- a/dmp-backend/src/main/java/eu/eudat/entities/Dataset.java +++ b/dmp-backend/src/main/java/eu/eudat/entities/Dataset.java @@ -26,7 +26,7 @@ import com.fasterxml.jackson.annotation.ObjectIdGenerators; @Entity @Table(name="\"Dataset\"") @JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="id") -public class Dataset implements Serializable,DataEntity { +public class Dataset implements DataEntity { private static final long serialVersionUID = 3575723814399553259L; @@ -253,9 +253,15 @@ public class Dataset implements Serializable,DataEntity { public void setReference(String reference) { this.reference = reference; } - - - - - + + + @Override + public void update(Dataset entity) { + + } + + @Override + public Object[] getKeys() { + return new UUID[]{this.id == null ? null : this.id}; + } } diff --git a/dmp-backend/src/main/java/eu/eudat/entities/DatasetProfile.java b/dmp-backend/src/main/java/eu/eudat/entities/DatasetProfile.java index b104db1fb..ff96cfbea 100644 --- a/dmp-backend/src/main/java/eu/eudat/entities/DatasetProfile.java +++ b/dmp-backend/src/main/java/eu/eudat/entities/DatasetProfile.java @@ -26,7 +26,7 @@ import com.fasterxml.jackson.annotation.ObjectIdGenerators; @Entity @Table(name="\"DatasetProfile\"") @JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="id") -public class DatasetProfile implements Serializable,DataEntity { +public class DatasetProfile implements Serializable,DataEntity { private static final long serialVersionUID = 8203086344232867334L; @@ -177,6 +177,14 @@ public class DatasetProfile implements Serializable,DataEntity { + ", viewstyle=" + viewstyle + ", definition=" + definition + "]"; } - - + + @Override + public void update(DatasetProfile entity) { + + } + + @Override + public Object[] getKeys() { + return new UUID[]{this.id == null ? null : this.id}; + } } diff --git a/dmp-backend/src/main/java/eu/eudat/entities/Organisation.java b/dmp-backend/src/main/java/eu/eudat/entities/Organisation.java index 483b30da0..a4feab4a9 100644 --- a/dmp-backend/src/main/java/eu/eudat/entities/Organisation.java +++ b/dmp-backend/src/main/java/eu/eudat/entities/Organisation.java @@ -26,7 +26,7 @@ import com.fasterxml.jackson.annotation.ObjectIdGenerators; @Entity @Table(name="\"Organisation\"") @JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="id") -public class Organisation implements Serializable,DataEntity { +public class Organisation implements Serializable,DataEntity { private static final long serialVersionUID = 3614146195740867782L; @@ -164,6 +164,14 @@ public class Organisation implements Serializable,DataEntity { this.dMPs = dMPs; } - - + + @Override + public void update(Organisation entity) { + + } + + @Override + public Object[] getKeys() { + return new UUID[]{this.id == null ? null : this.id}; + } } diff --git a/dmp-backend/src/main/java/eu/eudat/entities/Project.java b/dmp-backend/src/main/java/eu/eudat/entities/Project.java index c330e6a22..3486568e5 100644 --- a/dmp-backend/src/main/java/eu/eudat/entities/Project.java +++ b/dmp-backend/src/main/java/eu/eudat/entities/Project.java @@ -29,7 +29,7 @@ import com.fasterxml.jackson.databind.SerializationFeature; @Entity @Table(name="\"Project\"") @JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="id") -public class Project implements Serializable,DataEntity { +public class Project implements Serializable,DataEntity { private static final long serialVersionUID = -767048645098311154L; @@ -226,7 +226,14 @@ public class Project implements Serializable,DataEntity { return ""; } } - - - + + @Override + public void update(Project entity) { + + } + + @Override + public Object[] getKeys() { + return new UUID[]{this.id == null ? null : this.id}; + } } diff --git a/dmp-backend/src/main/java/eu/eudat/entities/Registry.java b/dmp-backend/src/main/java/eu/eudat/entities/Registry.java index b5954f030..d318cebb7 100644 --- a/dmp-backend/src/main/java/eu/eudat/entities/Registry.java +++ b/dmp-backend/src/main/java/eu/eudat/entities/Registry.java @@ -26,7 +26,7 @@ import com.fasterxml.jackson.annotation.ObjectIdGenerators; @Entity @Table(name="\"Registry\"") @JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="id") -public class Registry implements Serializable,DataEntity { +public class Registry implements Serializable,DataEntity { private static final long serialVersionUID = -277572262583178090L; @@ -161,6 +161,14 @@ public class Registry implements Serializable,DataEntity { this.datasets = datasets; } - - + + @Override + public void update(Registry entity) { + + } + + @Override + public Object[] getKeys() { + return new UUID[]{this.id == null ? null : this.id}; + } } diff --git a/dmp-backend/src/main/java/eu/eudat/entities/Researcher.java b/dmp-backend/src/main/java/eu/eudat/entities/Researcher.java index c530d3f99..0474646db 100644 --- a/dmp-backend/src/main/java/eu/eudat/entities/Researcher.java +++ b/dmp-backend/src/main/java/eu/eudat/entities/Researcher.java @@ -26,7 +26,7 @@ import com.fasterxml.jackson.annotation.ObjectIdGenerators; @Entity @Table(name="\"Researcher\"") @JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="id") -public class Researcher implements Serializable,DataEntity { +public class Researcher implements Serializable,DataEntity { private static final long serialVersionUID = -2513186824704729896L; @@ -163,6 +163,14 @@ public class Researcher implements Serializable,DataEntity { this.dMPs = dMPs; } - - + + @Override + public void update(Researcher entity) { + + } + + @Override + public Object[] getKeys() { + return new UUID[]{this.id == null ? null : this.id}; + } } diff --git a/dmp-backend/src/main/java/eu/eudat/entities/Service.java b/dmp-backend/src/main/java/eu/eudat/entities/Service.java index 27ba8490b..de5dc38d9 100644 --- a/dmp-backend/src/main/java/eu/eudat/entities/Service.java +++ b/dmp-backend/src/main/java/eu/eudat/entities/Service.java @@ -26,7 +26,7 @@ import com.fasterxml.jackson.annotation.ObjectIdGenerators; @Entity @Table(name="\"Service\"") @JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="id") -public class Service implements Serializable,DataEntity { +public class Service implements Serializable,DataEntity { private static final long serialVersionUID = 163279108676904730L; @@ -160,6 +160,14 @@ public class Service implements Serializable,DataEntity { this.datasets = datasets; } - - + + @Override + public void update(Service entity) { + + } + + @Override + public Object[] getKeys() { + return new UUID[]{this.id == null ? null : this.id}; + } } diff --git a/dmp-backend/src/main/java/eu/eudat/entities/UserInfo.java b/dmp-backend/src/main/java/eu/eudat/entities/UserInfo.java index 4c534f4db..3e782b4e2 100644 --- a/dmp-backend/src/main/java/eu/eudat/entities/UserInfo.java +++ b/dmp-backend/src/main/java/eu/eudat/entities/UserInfo.java @@ -18,7 +18,7 @@ import com.fasterxml.jackson.annotation.ObjectIdGenerators; @Entity @Table(name="\"UserInfo\"") @JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="id") -public class UserInfo implements Serializable,DataEntity{ +public class UserInfo implements Serializable,DataEntity{ private static final long serialVersionUID = 1225151430484658395L; @@ -154,4 +154,14 @@ public class UserInfo implements Serializable,DataEntity{ public void setCredentials(Set credentials) { this.credentials = credentials; } + + @Override + public void update(UserInfo entity) { + + } + + @Override + public Object[] getKeys() { + return new Object[0]; + } } diff --git a/dmp-backend/src/main/java/eu/eudat/entities/UserToken.java b/dmp-backend/src/main/java/eu/eudat/entities/UserToken.java index d38595483..18c98a8a1 100644 --- a/dmp-backend/src/main/java/eu/eudat/entities/UserToken.java +++ b/dmp-backend/src/main/java/eu/eudat/entities/UserToken.java @@ -9,7 +9,7 @@ import java.util.UUID; */ @Entity @Table(name="\"UserToken\"") -public class UserToken implements DataEntity{ +public class UserToken implements DataEntity{ private static final long serialVersionUID = 1225151430484658395L; @@ -59,4 +59,14 @@ public class UserToken implements DataEntity{ public void setExpiresAt(Date expiresAt) { this.expiresAt = expiresAt; } + + @Override + public void update(UserToken entity) { + + } + + @Override + public Object[] getKeys() { + return new UUID[]{this.token == null ? null : this.token}; + } } diff --git a/dmp-backend/src/main/java/eu/eudat/managers/DataManagementPlanManager.java b/dmp-backend/src/main/java/eu/eudat/managers/DataManagementPlanManager.java index 3d29ddb1e..a5c2f152d 100644 --- a/dmp-backend/src/main/java/eu/eudat/managers/DataManagementPlanManager.java +++ b/dmp-backend/src/main/java/eu/eudat/managers/DataManagementPlanManager.java @@ -4,14 +4,18 @@ import java.util.List; import java.util.UUID; import eu.eudat.dao.entities.DMPDao; +import eu.eudat.entities.DMP; import eu.eudat.models.dmp.DataManagementPlanTableRequest; import eu.eudat.models.helpers.DataTableData; +import eu.eudat.queryable.QueryableList; import eu.eudat.utilities.builders.DomainModelConverter; public class DataManagementPlanManager { public DataTableData getPaged(DMPDao dmpsRepository, DataManagementPlanTableRequest dataManagementPlanTableRequest) throws IllegalAccessException, InstantiationException{ - List datamanagementPlans = new DomainModelConverter().fromDataModel( dmpsRepository.getWithCriteria(dataManagementPlanTableRequest), eu.eudat.models.dmp.DataManagementPlan.class); + QueryableList items = dmpsRepository.getWithCriteria(dataManagementPlanTableRequest.getCriteria()); + QueryableList pagedItems = PaginationManager.applyPaging(items,dataManagementPlanTableRequest); + List datamanagementPlans = new DomainModelConverter().fromDataModel( pagedItems.toList(), eu.eudat.models.dmp.DataManagementPlan.class); DataTableData dataTable = new DataTableData(); dataTable.setData(datamanagementPlans); dataTable.setTotalCount(dmpsRepository.count()); @@ -20,7 +24,7 @@ public class DataManagementPlanManager { public eu.eudat.models.dmp.DataManagementPlan getSingle(DMPDao dmpsRepository, String id) throws InstantiationException, IllegalAccessException{ eu.eudat.models.dmp.DataManagementPlan datamanagementPlan = new eu.eudat.models.dmp.DataManagementPlan(); - datamanagementPlan.fromDataModel(dmpsRepository.read(UUID.fromString(id))); + datamanagementPlan.fromDataModel(dmpsRepository.find(UUID.fromString(id))); return datamanagementPlan; } } diff --git a/dmp-backend/src/main/java/eu/eudat/managers/DatasetManager.java b/dmp-backend/src/main/java/eu/eudat/managers/DatasetManager.java index 187d3f3d8..ba3fece4d 100644 --- a/dmp-backend/src/main/java/eu/eudat/managers/DatasetManager.java +++ b/dmp-backend/src/main/java/eu/eudat/managers/DatasetManager.java @@ -7,6 +7,7 @@ import eu.eudat.models.dataset.DatasetTableRequest; import eu.eudat.models.helpers.DataTableData; import eu.eudat.models.project.Project; import eu.eudat.models.project.ProjectTableRequest; +import eu.eudat.queryable.QueryableList; import eu.eudat.utilities.builders.DomainModelConverter; import java.util.List; @@ -18,7 +19,9 @@ import java.util.UUID; public class DatasetManager { public DataTableData getPaged(DatasetDao datatasetRepository, DatasetTableRequest datasetTableRequest) throws IllegalAccessException, InstantiationException{ - List datasets = new DomainModelConverter().fromDataModel( datatasetRepository.getWithCriteria(datasetTableRequest), eu.eudat.models.dataset.Dataset.class); + QueryableList items = datatasetRepository.getWithCriteria(datasetTableRequest.getCriteria()); + QueryableList pagedItems = PaginationManager.applyPaging( items ,datasetTableRequest); + List datasets = new DomainModelConverter().fromDataModel( pagedItems.toList(), eu.eudat.models.dataset.Dataset.class); DataTableData dataTable = new DataTableData(); dataTable.setData(datasets); dataTable.setTotalCount(datatasetRepository.count()); @@ -27,7 +30,7 @@ public class DatasetManager { public eu.eudat.models.dataset.Dataset getSingle(DatasetDao datatasetRepository, String id) throws InstantiationException, IllegalAccessException{ eu.eudat.models.dataset.Dataset dataset = new eu.eudat.models.dataset.Dataset(); - dataset.fromDataModel(datatasetRepository.read(UUID.fromString(id))); + dataset.fromDataModel(datatasetRepository.find(UUID.fromString(id))); return dataset; } } diff --git a/dmp-backend/src/main/java/eu/eudat/managers/PaginationManager.java b/dmp-backend/src/main/java/eu/eudat/managers/PaginationManager.java new file mode 100644 index 000000000..f723567d0 --- /dev/null +++ b/dmp-backend/src/main/java/eu/eudat/managers/PaginationManager.java @@ -0,0 +1,13 @@ +package eu.eudat.managers; + +import eu.eudat.models.helpers.requests.TableRequest; +import eu.eudat.queryable.QueryableList; + +public class PaginationManager { + + public static QueryableList applyPaging(QueryableList items, TableRequest tableRequest){ + if(tableRequest.getLength()!=null)items.take(tableRequest.getLength()); + if(tableRequest.getOffset()!=null)items.skip(tableRequest.getOffset()); + return items; + } +} diff --git a/dmp-backend/src/main/java/eu/eudat/managers/ProjectManager.java b/dmp-backend/src/main/java/eu/eudat/managers/ProjectManager.java index 7d393d76c..efb9cb952 100644 --- a/dmp-backend/src/main/java/eu/eudat/managers/ProjectManager.java +++ b/dmp-backend/src/main/java/eu/eudat/managers/ProjectManager.java @@ -7,12 +7,15 @@ import eu.eudat.dao.entities.ProjectDao; import eu.eudat.models.helpers.DataTableData; import eu.eudat.models.project.Project; import eu.eudat.models.project.ProjectTableRequest; +import eu.eudat.queryable.QueryableList; import eu.eudat.utilities.builders.DomainModelConverter; public class ProjectManager { public DataTableData getPaged(ProjectDao projectRepository, ProjectTableRequest projectTableRequest) throws IllegalAccessException, InstantiationException{ - List projects = new DomainModelConverter().fromDataModel( projectRepository.getWithCriteria(projectTableRequest), eu.eudat.models.project.Project.class); + QueryableList items = projectRepository.getWithCriteria(projectTableRequest.getCriteria()); + QueryableList pagedItems = PaginationManager.applyPaging(items,projectTableRequest); + List projects = new DomainModelConverter().fromDataModel(pagedItems.toList(), eu.eudat.models.project.Project.class); DataTableData dataTable = new DataTableData(); dataTable.setData(projects); dataTable.setTotalCount(projectRepository.count()); @@ -21,7 +24,7 @@ public class ProjectManager { public eu.eudat.models.project.Project getSingle(ProjectDao projectRepository, String id) throws InstantiationException, IllegalAccessException{ eu.eudat.models.project.Project project = new eu.eudat.models.project.Project(); - project.fromDataModel(projectRepository.read(UUID.fromString(id))); + project.fromDataModel(projectRepository.find(UUID.fromString(id))); return project; } } diff --git a/dmp-backend/src/main/java/eu/eudat/models/criteria/DataManagementPlanCriteria.java b/dmp-backend/src/main/java/eu/eudat/models/criteria/DataManagementPlanCriteria.java index c1e2e11fc..7ad8b8d9b 100644 --- a/dmp-backend/src/main/java/eu/eudat/models/criteria/DataManagementPlanCriteria.java +++ b/dmp-backend/src/main/java/eu/eudat/models/criteria/DataManagementPlanCriteria.java @@ -2,6 +2,25 @@ package eu.eudat.models.criteria; import eu.eudat.entities.DMP; -public class DataManagementPlanCriteria extends Criteria{ +import java.util.Date; +public class DataManagementPlanCriteria extends Criteria{ + private Date periodStart; + private Date periodEnd; + + public Date getPeriodStart() { + return periodStart; + } + + public void setPeriodStart(Date periodStart) { + this.periodStart = periodStart; + } + + public Date getPeriodEnd() { + return periodEnd; + } + + public void setPeriodEnd(Date periodEnd) { + this.periodEnd = periodEnd; + } } diff --git a/dmp-backend/src/main/java/eu/eudat/models/criteria/ProjectCriteria.java b/dmp-backend/src/main/java/eu/eudat/models/criteria/ProjectCriteria.java index 5c846ce73..9255fffef 100644 --- a/dmp-backend/src/main/java/eu/eudat/models/criteria/ProjectCriteria.java +++ b/dmp-backend/src/main/java/eu/eudat/models/criteria/ProjectCriteria.java @@ -2,6 +2,25 @@ package eu.eudat.models.criteria; import eu.eudat.entities.Project; -public class ProjectCriteria extends Criteria{ +import java.util.Date; +public class ProjectCriteria extends Criteria{ + private Date periodStart; + private Date periodEnd; + + public Date getPeriodStart() { + return periodStart; + } + + public void setPeriodStart(Date periodStart) { + this.periodStart = periodStart; + } + + public Date getPeriodEnd() { + return periodEnd; + } + + public void setPeriodEnd(Date periodEnd) { + this.periodEnd = periodEnd; + } } diff --git a/dmp-backend/src/main/java/eu/eudat/models/dataset/DatasetTableRequest.java b/dmp-backend/src/main/java/eu/eudat/models/dataset/DatasetTableRequest.java index d82914170..8c48a455b 100644 --- a/dmp-backend/src/main/java/eu/eudat/models/dataset/DatasetTableRequest.java +++ b/dmp-backend/src/main/java/eu/eudat/models/dataset/DatasetTableRequest.java @@ -2,37 +2,11 @@ package eu.eudat.models.dataset; import eu.eudat.models.criteria.DatasetCriteria; import eu.eudat.models.criteria.ProjectCriteria; +import eu.eudat.models.helpers.requests.RequestItem; +import eu.eudat.models.helpers.requests.TableRequest; /** * Created by ikalyvas on 12/15/2017. */ -public class DatasetTableRequest { - private int length; - private int offset; - - private DatasetCriteria criteria; - - public int getLength() { - return length; - } - - public void setLength(int length) { - this.length = length; - } - - public int getOffset() { - return offset; - } - - public void setOffset(int offset) { - this.offset = offset; - } - - public DatasetCriteria getCriteria() { - return criteria; - } - - public void setCriteria(DatasetCriteria criteria) { - this.criteria = criteria; - } +public class DatasetTableRequest extends TableRequest { } diff --git a/dmp-backend/src/main/java/eu/eudat/models/dmp/DataManagementPlanTableRequest.java b/dmp-backend/src/main/java/eu/eudat/models/dmp/DataManagementPlanTableRequest.java index 6923d9433..63d6f3ac7 100644 --- a/dmp-backend/src/main/java/eu/eudat/models/dmp/DataManagementPlanTableRequest.java +++ b/dmp-backend/src/main/java/eu/eudat/models/dmp/DataManagementPlanTableRequest.java @@ -1,36 +1,8 @@ package eu.eudat.models.dmp; import eu.eudat.models.criteria.DataManagementPlanCriteria; +import eu.eudat.models.helpers.requests.RequestItem; +import eu.eudat.models.helpers.requests.TableRequest; -public class DataManagementPlanTableRequest { - private Integer length; - private Integer offset; - - private DataManagementPlanCriteria criteria; - - public Integer getLength() { - return length; - } - - public void setLength(Integer length) { - this.length = length; - } - - public Integer getOffset() { - return offset; - } - - public void setOffset(Integer offset) { - this.offset = offset; - } - - public DataManagementPlanCriteria getCriteria() { - return criteria; - } - - public void setCriteria(DataManagementPlanCriteria criteria) { - this.criteria = criteria; - } - - +public class DataManagementPlanTableRequest extends TableRequest { } diff --git a/dmp-backend/src/main/java/eu/eudat/models/helpers/requests/RequestItem.java b/dmp-backend/src/main/java/eu/eudat/models/helpers/requests/RequestItem.java new file mode 100644 index 000000000..9235ad382 --- /dev/null +++ b/dmp-backend/src/main/java/eu/eudat/models/helpers/requests/RequestItem.java @@ -0,0 +1,13 @@ +package eu.eudat.models.helpers.requests; + +public abstract class RequestItem{ + private T criteria; + + public T getCriteria() { + return criteria; + } + + public void setCriteria(T criteria) { + this.criteria = criteria; + } +} diff --git a/dmp-backend/src/main/java/eu/eudat/models/helpers/requests/TableRequest.java b/dmp-backend/src/main/java/eu/eudat/models/helpers/requests/TableRequest.java new file mode 100644 index 000000000..bd14475e8 --- /dev/null +++ b/dmp-backend/src/main/java/eu/eudat/models/helpers/requests/TableRequest.java @@ -0,0 +1,22 @@ +package eu.eudat.models.helpers.requests; + +public abstract class TableRequest extends RequestItem { + private Integer length; + private Integer offset; + + public Integer getLength() { + return length; + } + + public void setLength(Integer length) { + this.length = length; + } + + public Integer getOffset() { + return offset; + } + + public void setOffset(Integer offset) { + this.offset = offset; + } +} diff --git a/dmp-backend/src/main/java/eu/eudat/models/responses/ResponseItem.java b/dmp-backend/src/main/java/eu/eudat/models/helpers/responses/ResponseItem.java similarity index 95% rename from dmp-backend/src/main/java/eu/eudat/models/responses/ResponseItem.java rename to dmp-backend/src/main/java/eu/eudat/models/helpers/responses/ResponseItem.java index 1ea0e57b1..34129a6d0 100644 --- a/dmp-backend/src/main/java/eu/eudat/models/responses/ResponseItem.java +++ b/dmp-backend/src/main/java/eu/eudat/models/helpers/responses/ResponseItem.java @@ -1,4 +1,4 @@ -package eu.eudat.models.responses; +package eu.eudat.models.helpers.responses; import org.springframework.http.HttpStatus; diff --git a/dmp-backend/src/main/java/eu/eudat/models/project/ProjectTableRequest.java b/dmp-backend/src/main/java/eu/eudat/models/project/ProjectTableRequest.java index 57da09c23..59a08079b 100644 --- a/dmp-backend/src/main/java/eu/eudat/models/project/ProjectTableRequest.java +++ b/dmp-backend/src/main/java/eu/eudat/models/project/ProjectTableRequest.java @@ -1,36 +1,8 @@ package eu.eudat.models.project; import eu.eudat.models.criteria.ProjectCriteria; +import eu.eudat.models.helpers.requests.RequestItem; +import eu.eudat.models.helpers.requests.TableRequest; -public class ProjectTableRequest { - private int length; - private int offset; - - private ProjectCriteria criteria; - - public int getLength() { - return length; - } - - public void setLength(int length) { - this.length = length; - } - - public int getOffset() { - return offset; - } - - public void setOffset(int offset) { - this.offset = offset; - } - - public ProjectCriteria getCriteria() { - return criteria; - } - - public void setCriteria(ProjectCriteria criteria) { - this.criteria = criteria; - } - - +public class ProjectTableRequest extends TableRequest { } diff --git a/dmp-backend/src/main/java/eu/eudat/queryable/QueryableList.java b/dmp-backend/src/main/java/eu/eudat/queryable/QueryableList.java new file mode 100644 index 000000000..cbc3ffa33 --- /dev/null +++ b/dmp-backend/src/main/java/eu/eudat/queryable/QueryableList.java @@ -0,0 +1,24 @@ +package eu.eudat.queryable; + + +import eu.eudat.queryable.predicates.OrderByPredicate; +import eu.eudat.queryable.predicates.SelectPredicate; +import eu.eudat.queryable.predicates.SinglePredicate; + +import java.util.List; + +public interface QueryableList { + QueryableList where(SinglePredicate predicate); + + List select(SelectPredicate predicate); + + List toList(); + + QueryableList skip(Integer offset); + + QueryableList take(Integer length); + + QueryableList distinct(); + + QueryableList orderBy(OrderByPredicate predicate); +} diff --git a/dmp-backend/src/main/java/eu/eudat/queryable/hibernatequeryablelist/QueryableHibernateList.java b/dmp-backend/src/main/java/eu/eudat/queryable/hibernatequeryablelist/QueryableHibernateList.java new file mode 100644 index 000000000..a770efb8f --- /dev/null +++ b/dmp-backend/src/main/java/eu/eudat/queryable/hibernatequeryablelist/QueryableHibernateList.java @@ -0,0 +1,96 @@ +package eu.eudat.queryable.hibernatequeryablelist; + + + +import eu.eudat.queryable.QueryableList; +import eu.eudat.queryable.predicates.OrderByPredicate; +import eu.eudat.queryable.predicates.SelectPredicate; +import eu.eudat.queryable.predicates.SinglePredicate; + +import javax.persistence.EntityManager; +import javax.persistence.TypedQuery; +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.CriteriaQuery; +import javax.persistence.criteria.Predicate; +import javax.persistence.criteria.Root; +import java.util.LinkedList; +import java.util.List; + +public class QueryableHibernateList implements QueryableList { + + private EntityManager manager; + private CriteriaQuery query; + private Class tClass; + private Root root; + private LinkedList predicates = new LinkedList(); + private Integer length; + private Integer offset; + public QueryableHibernateList(EntityManager manager, Class tClass) { + this.manager = manager; + this.tClass = tClass; + } + + public QueryableHibernateList setManager(EntityManager manager) { + this.manager = manager; + return this; + } + + public QueryableHibernateList setEntity(Class type) { + CriteriaBuilder builder = this.manager.getCriteriaBuilder(); + this.query = builder.createQuery(type); + this.root = this.query.from(this.tClass); + return this; + } + + public void initiateQueryableList(Class type) { + CriteriaBuilder builder = this.manager.getCriteriaBuilder(); + this.query = builder.createQuery(type); + } + + @Override + public QueryableList skip(Integer offset) { + this.offset = offset; + return this; + } + + @Override + public QueryableList take(Integer length) { + this.length = length; + return this; + } + + public QueryableList where(SinglePredicate predicate) { + this.predicates.add(predicate.applyPredicate(this.manager.getCriteriaBuilder(), this.root)); + return this; + } + + public List select(SelectPredicate predicate) { + List list = this.toList(); + List newlist = new LinkedList(); + for (T item : list) { + newlist.add(predicate.applySelection(item)); + } + return newlist; + } + + public QueryableList distinct() { + this.query.distinct(true); + return this; + } + + public QueryableList orderBy(OrderByPredicate predicate) { + this.query.orderBy(predicate.applyPredicate(this.manager.getCriteriaBuilder(), this.root)); + return this; + } + + public List toList() { + Predicate[] array = new Predicate[this.predicates.size()]; + this.predicates.toArray(array); + this.query.where(array); + + TypedQuery typedQuery = this.manager.createQuery(this.query); + if(this.offset!=null)typedQuery.setFirstResult(this.offset); + if(this.length!=null)typedQuery.setMaxResults(this.length); + return typedQuery.getResultList(); + } +} diff --git a/dmp-backend/src/main/java/eu/eudat/queryable/predicates/OrderByPredicate.java b/dmp-backend/src/main/java/eu/eudat/queryable/predicates/OrderByPredicate.java new file mode 100644 index 000000000..1484500aa --- /dev/null +++ b/dmp-backend/src/main/java/eu/eudat/queryable/predicates/OrderByPredicate.java @@ -0,0 +1,10 @@ +package eu.eudat.queryable.predicates; + +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.Order; +import javax.persistence.criteria.Root; + +public interface OrderByPredicate { + Order applyPredicate(CriteriaBuilder builder, Root root); + +} diff --git a/dmp-backend/src/main/java/eu/eudat/queryable/predicates/SelectPredicate.java b/dmp-backend/src/main/java/eu/eudat/queryable/predicates/SelectPredicate.java new file mode 100644 index 000000000..d6e561330 --- /dev/null +++ b/dmp-backend/src/main/java/eu/eudat/queryable/predicates/SelectPredicate.java @@ -0,0 +1,5 @@ +package eu.eudat.queryable.predicates; + +public interface SelectPredicate { + R applySelection(T item); +} diff --git a/dmp-backend/src/main/java/eu/eudat/queryable/predicates/SinglePredicate.java b/dmp-backend/src/main/java/eu/eudat/queryable/predicates/SinglePredicate.java new file mode 100644 index 000000000..53f6f84fc --- /dev/null +++ b/dmp-backend/src/main/java/eu/eudat/queryable/predicates/SinglePredicate.java @@ -0,0 +1,9 @@ +package eu.eudat.queryable.predicates; + +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.Predicate; +import javax.persistence.criteria.Root; + +public interface SinglePredicate { + Predicate applyPredicate(CriteriaBuilder builder, Root root); +}