187 Commits

Author SHA1 Message Date
acf80cc78d Merge pull request 'token-package' (#28) from token-package into master
Reviewed-on: http://git.plannaplan.pl/filipizydorczyk/backend/pulls/28
2020-12-07 23:31:59 +01:00
c34d53d056 Added taken place in course response (needs refactor later) 2020-12-07 23:32:11 +01:00
48394d3583 students endpoint 2020-12-07 22:21:34 +01:00
82200acc06 swagger update 2020-12-07 22:01:45 +01:00
f9baed5df7 Changed token response in controller 2020-12-07 21:46:47 +01:00
3061fb1edf Token response 2020-12-07 21:39:47 +01:00
b412ee2a5b Merge pull request 'new-cas-configuration' (#27) from new-cas-configuration into master
Reviewed-on: http://git.plannaplan.pl/filipizydorczyk/backend/pulls/27
2020-12-07 21:10:49 +01:00
2037f0bf07 Added
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2020-12-07 21:09:54 +01:00
b4f23aa5d2 Added metadata to plannaplan propterties + we should create sssl bean instead inerting properties 2020-12-05 16:38:22 +01:00
495098eeed Added init test data on dev profile 2020-12-05 16:28:02 +01:00
751d4b1744 Readme update 2020-12-05 15:59:47 +01:00
cbe8f96700 Getch chanmges 2020-12-05 15:10:03 +01:00
2dd1f70eee Updated 2020-12-04 17:15:08 +01:00
c70cac58b2 Updated
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2020-12-04 16:16:10 +01:00
616f782155 Updated
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2020-12-04 15:54:49 +01:00
6dfb99f253 Updated
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2020-12-04 15:42:28 +01:00
b897fce416 Fixed TokenController
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2020-12-03 17:14:39 +01:00
f4db74b899 Added test UserServiceTest - shouldCreateUser shouldReturnExistingUser
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2020-12-03 17:07:41 +01:00
453907782a CAS Part 2
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2020-12-03 16:57:53 +01:00
3ebfda5316 CAS Part 1
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2020-12-03 16:23:39 +01:00
b6c2e43975 Added cas module + add customuamcasvalidator + test passed
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2020-12-03 15:11:23 +01:00
6298bb4765 Updated
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2020-12-02 15:00:18 +01:00
c24aa73bb0 CustomUAMCasValidatorTest
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2020-12-02 14:37:44 +01:00
20d261635b Added CustomUAMCasValidator
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2020-12-02 13:51:07 +01:00
1e3cccc991 Added CasValidator.java; Update DefaultUAMCasValidator
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2020-12-02 13:48:28 +01:00
cd96e74c29 Added folder cas
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2020-12-02 13:31:18 +01:00
7d747b60a8 Renamed CasValidator -> DefaultUAMCasValidator
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2020-12-02 12:38:17 +01:00
c3fd450499 Merge pull request 'ZPI-163: Dodanie dokumentacji do kodu + javadoc' (#24) from ZPI-163 into master
Reviewed-on: http://git.plannaplan.pl/filipizydorczyk/backend/pulls/24
2020-12-02 12:28:38 +01:00
b966b64fdb Resolved confilics with master
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2020-12-02 12:16:31 +01:00
1d15d295e0 Merge pull request 'group-count' (#25) from group-count into master
Reviewed-on: http://git.plannaplan.pl/filipizydorczyk/backend/pulls/25
2020-12-02 11:58:42 +01:00
f8b12d831b Added CourseService into javadoc
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2020-12-02 11:14:30 +01:00
20341d5441 Added CommisionService into javadoc
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2020-12-02 10:22:50 +01:00
3faa228745 Added AssignmentService into javadoc
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2020-12-02 10:14:32 +01:00
e6fffba899 Added FileData into javadocs
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2020-12-01 21:31:06 +01:00
708cedf7b4 Added ConfigData into javadocs 2020-12-01 21:16:47 +01:00
96c903ed15 Added javadocs to User
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2020-12-01 21:13:05 +01:00
160930c3c3 Added javadocs to Lecturer - fix errors
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2020-12-01 21:03:26 +01:00
823f4af218 Added javadocs to Lecturer
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2020-12-01 20:59:16 +01:00
b2b9178bc1 Added missing config tests. Ready to pull. Other resposnes to fix in another task 2020-12-01 17:31:55 +01:00
7e45da1306 Not null group response 2020-12-01 17:21:54 +01:00
c2c82b75ba repaired places failing 2020-12-01 17:00:56 +01:00
78ed2f75f3 Vhevkpoint implemented but stiull some errors 2020-11-30 13:22:53 +01:00
082b30133c mapToGetCourseGroupsDefaultResponse overloaded 2020-11-30 13:10:40 +01:00
25e9571a06 Group capacity response places overload 2020-11-30 12:35:35 +01:00
593084aeba Group default response places overload 2020-11-30 12:07:18 +01:00
911f2e54f5 Added Course into javadoc
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2020-11-27 17:05:47 +01:00
13eb8dae77 Added service method tests + javadocs 2020-11-27 16:55:15 +01:00
7d5522e413 Added Course into javadoc
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2020-11-27 16:53:36 +01:00
9ed4197005 Added Assignment
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2020-11-27 16:45:06 +01:00
dc3a554ed1 Added Assignment
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2020-11-27 16:40:39 +01:00
f6a8953c17 Added
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2020-11-27 16:18:30 +01:00
2545a0e682 Added another repository method + test 2020-11-26 13:58:27 +01:00
0130fb77e1 Works with native query now needst to be hql 2020-11-22 03:51:24 +01:00
9d3500c1fb Added api endpoiunt mapper needs to be rewriteen 2020-11-20 16:20:38 +01:00
b4bb13f2dd Added tests and service 2020-11-20 15:56:43 +01:00
e752ad06cd mit
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2020-11-20 15:31:29 +01:00
6d9c5a8a5d Added
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2020-11-20 14:55:20 +01:00
85052f5728 Check it !!! UserRepository.java
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2020-11-20 14:53:45 +01:00
50c1397db2 Added docs into repositories
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2020-11-20 14:50:07 +01:00
af8e2ced28 Added docs into services 2020-11-20 13:20:44 +01:00
9ad8db527d Merge remote-tracking branch 'origin/master' into ZPI-163 2020-11-18 09:05:43 +01:00
bc6c55165e Added docs into branch
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2020-11-18 09:01:45 +01:00
3e7086eab9 Checkopoint added hql 2020-11-17 19:36:56 +01:00
c34ce94fb0 Added flaging assignment. Coumetr froup infor needs to be added 2020-11-14 16:52:22 +01:00
17e5625315 Updated
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2020-11-12 17:50:53 +01:00
1ddeb83cb4 Merge pull request 'Token expiration added' (#22) from token-expiration into master
Reviewed-on: http://git.plannaplan.pl/filipizydorczyk/backend/pulls/22
2020-11-11 14:08:12 +01:00
b713066a2f Merge pull request 'ZPI-161' (#23) from ZPI-161 into master
Reviewed-on: http://git.plannaplan.pl/filipizydorczyk/backend/pulls/23
2020-11-10 17:19:25 +01:00
029300815e Added auth to swagger-ui
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2020-11-09 17:08:51 +01:00
7c7045c0e1 Part3 has been ended. Renamed the test files. The test had status successed.
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2020-11-09 16:47:12 +01:00
035de011f2 Part 2 has been ended. The Part 3: chanaged test 2020-11-08 17:20:00 +01:00
1b126c7792 Token expiration fixed 2020-11-08 17:06:08 +01:00
a30c3af09c Part 1
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2020-11-08 16:55:56 +01:00
62bbf148b2 Token expiration added 2020-11-07 16:30:25 +01:00
8ba148617a Merge pull request 'Added empty table' (#21) from ZPI-144 into master
Reviewed-on: http://git.plannaplan.pl/filipizydorczyk/backend/pulls/21
2020-11-05 16:14:31 +01:00
48fdeb726f Added empty table
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2020-11-05 16:14:50 +01:00
bd4591f442 Merge pull request 'refactor-api-endpoints' (#20) from refactor-api-endpoints into master
Reviewed-on: http://git.plannaplan.pl/filipizydorczyk/backend/pulls/20
2020-11-05 15:34:26 +01:00
0fbc6d6baa Merge 2020-11-05 15:27:51 +01:00
feff5c4b9c Merge pull request 'user-commisions-list' (#18) from user-commisions-list into master
Reviewed-on: http://git.plannaplan.pl/filipizydorczyk/backend/pulls/18
2020-11-05 14:55:55 +01:00
d2343acc2d merge with master 2020-11-05 14:44:09 +01:00
cbd9074a89 Merge pull request 'Made wepAppContex commont' (#19) from tests-refactor into master
Reviewed-on: http://git.plannaplan.pl/filipizydorczyk/backend/pulls/19
2020-11-05 14:40:16 +01:00
228969efce Error fix 2020-11-05 14:32:42 +01:00
e0df090a0e update docs 2020-11-04 17:27:20 +01:00
6a7fc03e7c Api params 2020-11-04 17:23:29 +01:00
4818905422 Api operations 2020-11-04 16:58:26 +01:00
b308373062 Added controllers description 2020-11-04 16:40:02 +01:00
ba26d67cd4 Swagger ui works needs refactor to be done 2020-11-04 15:09:44 +01:00
1a30ac3374 Works json endpoint ui dont 2020-11-04 15:06:24 +01:00
b4f51d4382 Added tests 2020-10-31 15:24:17 +01:00
6ab2ec50dd merged wqith master 2020-10-31 14:52:26 +01:00
9bff6460d6 Merge origin/deanery-plan-changing to master: With fixed restservice/.../App.java
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2020-10-30 17:34:32 +01:00
1571bccb49 Changed api links in the Tests 2020-10-30 17:22:40 +01:00
1327a239e8 Made wepAppContex commont 2020-10-30 16:53:41 +01:00
2b59c181e5 Refactor part 1
{{url}}/api/v1/courses/getCourses =>  {{url}}/api/v1/courses/all
{{url}}/api/v1/groups/getCourseGroups?id=13 => {{url}}/api/v1/groups/course/13
{{url}}/api/v1/courses/getCoursesWithGroups => {{url}}/api/v1/courses/all?groups=true
{{url}}/api/v1/commisions/add => {{url}}/api/v1/commisions/user
{{url}}/api/v1/commisions/getAllCommisions => {{url}}/api/v1/commisions/user
{{url}}/api/v1/assignments/getCurrentAssignments =>{{url}}/api/v1/assignments/user
{{url}}/api/v1/users/searchForStudents => {{url}}/api/v1/users/search

Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2020-10-30 16:42:57 +01:00
ca01b20221 Added endpoint - waiting for other branch to merge to master 2020-10-30 14:53:33 +01:00
956b53439f Tests works 2020-10-30 14:27:13 +01:00
b40acf8919 Added tests to fill 2020-10-29 17:45:15 +01:00
ed00731654 little refactor 2020-10-29 17:38:05 +01:00
3a3e6dc427 Functionality done 2020-10-29 16:25:55 +01:00
4267fadf62 Deleted __pycache__
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2020-10-29 15:36:14 +01:00
41f37ee9ad Merge pull request 'Added argv to python script' (#16) from python-change into master
Reviewed-on: http://git.plannaplan.pl/filipizydorczyk/backend/pulls/16
2020-10-29 15:32:54 +01:00
4ca2837b59 Merge pull request 'Chenged newest plan response' (#14) from endpoint-changes into master
Reviewed-on: http://git.plannaplan.pl/filipizydorczyk/backend/pulls/14
2020-10-29 15:32:31 +01:00
953168a452 Added argv to python script
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2020-10-29 15:22:31 +01:00
d3a2256334 Merge pull request 'token-plugin' (#15) from token-plugin into master
Reviewed-on: http://git.plannaplan.pl/filipizydorczyk/backend/pulls/15
2020-10-29 14:29:01 +01:00
933e09172b removed unused plugin 2020-10-28 14:30:51 +01:00
f0eae82d9f Added script to accessing token more efficient way 2020-10-28 14:29:27 +01:00
7073e3b1d8 Chenged newest plan response 2020-10-28 13:44:13 +01:00
bdfed57942 Script to get token - checkpoint 2020-10-27 18:21:45 +01:00
db0115280f Windows white spaces 2020-10-24 18:04:59 +02:00
f71715fd6b Merge pull request 'scurity-roles' (#13) from scurity-roles into master
Reviewed-on: http://git.plannaplan.pl/filipizydorczyk/backend/pulls/13
LGMT
2020-10-24 18:01:29 +02:00
9dba639674 Merge pull request 'ZPI-139' (#12) from ZPI-139 into master
Reviewed-on: http://git.plannaplan.pl/filipizydorczyk/backend/pulls/12
2020-10-24 18:01:17 +02:00
4614a11a8b Cors 2020-10-24 17:54:00 +02:00
a1f17d271f WE HAVE THE GOD DMAN TEST 2020-10-24 17:51:16 +02:00
6384f3d9b9 User Controller Tests 2020-10-24 17:28:10 +02:00
7d57157078 Mapper test 2020-10-24 17:08:51 +02:00
468b6e6b87 ShearchForStduentsResponseTest.java 2020-10-24 16:49:26 +02:00
c003198aa1 Fixed old tests 2020-10-24 16:43:42 +02:00
603dadd9c1 Mapping of getCourseGroups
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2020-10-20 19:02:18 +02:00
4b07793849 Added test to implement and some tests failed rightnow 2020-10-19 12:33:54 +02:00
67c8b9bf25 Added response mappers 2020-10-19 12:13:02 +02:00
0ad97a8e3f Added auth endpoint 2020-10-19 11:12:24 +02:00
5fd688fc7a Added roles 2020-10-16 16:31:10 +02:00
a20bc89fc6 Added GetCourseGroupsResponse(-Test)
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2020-10-16 16:13:40 +02:00
9c02a0b596 Merge pull request 'refactor' (#11) from refactor into master
Reviewed-on: http://git.plannaplan.pl/filipizydorczyk/backend/pulls/11
2020-10-15 18:14:13 +02:00
2b067f63fc Commisions respone updatede 2020-10-15 17:29:40 +02:00
010f0b4566 Warinings fix 2020-10-15 17:09:23 +02:00
cb60b17389 groups by course fix 2020-10-15 16:56:31 +02:00
3e8bfe85d6 Checkpoint - group controller needs to be fixed 2020-10-13 18:03:37 +02:00
932e1a8830 Little refactor 2020-10-13 17:13:43 +02:00
148d7a31c6 Responses up[dated 2020-10-13 17:07:04 +02:00
bdd0278880 Moved CoursesResponse To Abstract 2020-10-13 16:19:40 +02:00
29851dac0d Courses Controller getCourses Mapping 2020-10-09 14:53:54 +02:00
f97e22fa5f Made ASsignm,ents Conmtroller more readable 2020-10-08 16:41:13 +02:00
9d97306e5c Added Assignment Response Model 2020-10-08 15:57:42 +02:00
f9706e0e01 Tests works 2020-10-08 15:24:23 +02:00
f9dd6e38c3 3/4 Commisions test 2020-10-05 17:56:35 +02:00
73104850fe Assignments Controller test + authj test fix 2020-10-05 16:52:52 +02:00
fe5d2d20c3 lol small diff fix 2020-10-02 18:01:51 +02:00
30222d6856 Commision service tests 2020-10-02 17:55:42 +02:00
95fcfc4e06 Assignments tests 2020-10-02 17:18:03 +02:00
e9ae1a0ed0 Checkpoint: Added tests to impleement 2020-10-02 16:51:49 +02:00
bb9ea7529f Added what commision tests needst to be written 2020-10-01 17:08:10 +02:00
398a84854f Merge with assign 2020-10-01 16:46:45 +02:00
51ea557a06 Small fix 2020-09-30 19:16:15 +02:00
fa74965504 Works 2020-09-30 19:15:32 +02:00
b503ebcbcc Added commisions endponts 2020-09-30 17:46:04 +02:00
b4d1c87461 Checkpoint getting authority works + added new user 2020-09-29 19:06:29 +02:00
3ad4d3a84b Checkpoint kinda workls. Ill take a nap and go bacjk to work 2020-09-29 17:21:34 +02:00
4efedf7f35 concept for assigmnents 2020-09-28 16:07:10 +02:00
917a4e3535 optional to users 2020-09-25 17:01:51 +02:00
15a4c526b4 access modifiers and constructors fix 2020-09-25 17:01:38 +02:00
44bcc24110 access modifiers and constructors fix 2020-09-25 16:43:24 +02:00
ce4a5942d5 Added missing tests 2020-09-25 16:17:52 +02:00
9cec5a902c CHECKPOINT: Tests for rest service 2020-09-24 19:12:04 +02:00
305b86945d Small test fixc 2020-09-24 17:46:35 +02:00
3d1269037b Buisness logic tests 2020-09-24 17:44:23 +02:00
694fe74690 CHECKPOINT: Made configuyrator as a service. Test and java access modifier correction needs to be done before pull request 2020-09-23 19:12:25 +02:00
9599d58543 Removed unimplemented classes (no longer needed due to coneption changed) 2020-09-23 18:39:43 +02:00
bf6e1fc2b1 Maciek refactor works + delete unnecesery interface (conception changed) 2020-09-23 18:17:52 +02:00
ec77fa782b Moved to new computer 2020-09-22 18:00:28 +02:00
c449bc22e1 Major refactor of reading from excel to db 2020-09-21 17:45:52 +02:00
e91965e9b5 Merge pull request 'CourseServiceTest' (#10) from CourseServiceTest into master
Reviewed-on: http://git.plannaplan.pl/filipizydorczyk/backend/pulls/10
2020-09-17 16:24:58 +02:00
6be6bd0184 Added LecturerServiceTest with createAndDeleteLecturer
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2020-09-16 17:41:36 +02:00
1cff3ceb74 Added delete method into LecturerService
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2020-09-16 17:35:39 +02:00
a717a85a80 Created test GroupServiceTest.java. It contains createAndDeleteGroup
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2020-09-16 17:33:39 +02:00
d5e32a487b Added delete method in GroupService
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2020-09-16 17:23:33 +02:00
551011db1c Zmiana nazwy z Remove na Delete, dodanie testu na usuwanie.
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2020-09-16 17:21:01 +02:00
283be6603d Dodanie usuniecie kursu.
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2020-09-16 17:15:56 +02:00
43660c4fe9 Dodanie nowego testu do dodawnia kursu.
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2020-09-16 17:14:37 +02:00
579da3f038 Merge pull request 'security' (#9) from security into master
Reviewed-on: http://git.plannaplan.pl/filipizydorczyk/backend/pulls/9
2020-09-15 17:27:04 +02:00
b951f1f934 Added some endpoints not protected 2020-09-15 11:31:30 +02:00
82c4c9d0fe Added forbiden urls and protected 2020-09-14 14:02:05 +02:00
478ea27480 Endpoint returnung token if valid data 2020-09-14 12:55:47 +02:00
11f3625684 User service added login and returning token 2020-09-14 12:39:25 +02:00
8c16b2f3d1 Added auth endpoint 2020-09-11 14:33:29 +02:00
c9f50c5b16 Cas update 2020-09-11 14:12:13 +02:00
3deebe9248 Added CasValidator 2020-09-11 13:15:22 +02:00
824c137141 Merge pull request 'Removed ConfiguratorTest.java, and rewrite it into configutils/FileToDatabaseMigratorTest.java' (#8) from ConfiguratorTest-to-FileToDatabaseMigratorTest into master
Reviewed-on: http://git.plannaplan.pl/filipizydorczyk/backend/pulls/8
2020-09-09 16:34:00 +02:00
408c8a8242 Removed ConfiguratorTest.java, and rewrite it into configutils/FileToDatabaseMigratorTest.java
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2020-09-09 16:26:42 +02:00
333ceb9b74 Merge pull request 'testing-web' (#7) from testing-web into master
Testy zakończone sukcesem. Brak błędów pomiędzy discro.

Reviewed-on: http://git.plannaplan.pl/filipizydorczyk/backend/pulls/7
2020-09-04 16:25:40 +02:00
7a7c882163 Added config test 2020-09-04 16:24:00 +02:00
16b9cb3cf2 Spring starts on test run 2020-09-04 16:09:57 +02:00
56e519dcd6 Updated
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2020-09-03 17:09:35 +02:00
b659f70a1f Changed version junit 4.11 to 4.12
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2020-09-03 17:02:17 +02:00
f6d4674ec8 Inny error, zmiana lokalizacji pliku
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2020-09-03 16:59:27 +02:00
9ea2912e98 Added ConfiguratorTest.java. Updated pom.xml
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2020-09-03 16:30:42 +02:00
b65c56078b Merge pull request 'sql -> hql' (#6) from hql into master
Reviewed-on: http://git.plannaplan.pl/filipizydorczyk/backend/pulls/6
2020-09-03 15:27:37 +02:00
bf5b78c3b6 sql -> hql 2020-09-02 16:56:49 +02:00
152 changed files with 4850 additions and 1010 deletions

5
.gitignore vendored Normal file → Executable file
View File

@ -29,3 +29,8 @@ build/
### VS Code ###
.vscode/
### Python ###
__pycache__
.pytest_cache

60
README.md Normal file → Executable file
View File

@ -3,28 +3,44 @@
Zeby wystartowac aplikacje backendu najpierw nalezy postawic testowa baze danych na naszym komputerze za pomoca dockera. Jesli raz juz go odpalimy przy nastepnym razem bardzo mozliwe, ze wlaczy sie sam. AAby sprawdzic czy docker jesty wystartowany mozna uzyc `docker ps`
```
docker-compose -f stack.yml up
```
Nastepnie w `restservice/src/main/resources/application.properties` nalezy podac ip naszego kontenera.
```
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=example
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.hibernate.ddl-auto=create
server.port=1285
docker-compose -f stack.yml up -d
```
Następnym krokiem jest odpalenie poniższych komend w terminalu.
```
cd restservice
mvn spring-boot:run
```
## Token obtaining
Żeby tesotwać API wpełni potrzebny nam jest token który otrzymujemy na podstawie ticketa z systemu autoryzacyjnego **CAS**. Z tego powodu system autoryzacji działa inaczej niż w "książkowych" restowych aplikacjach i np Postman za nas jej nie dokona. Musimy mu podać już uzyskany token. Aby łatwo go uzyskać odpal skrypt
```
python gettoken.py
```
Na koniec w przęglądarce dostaniesz w odpowiedzi token. W samym pliku można zmienić porty aplikacji jeśli to potrzebne.
## Profiles
W aplikacji posiadamy dwa profile. `dev` i `prod`. **Dev** używamy do testowania aplikacji lokalnie. **Pord** służy do stworzenia builda na produkcję.
Profil wybieramy w pliku `restservice/src/main/resources/application.properties` wpisując odpowiednią nazwę
```
spring.profiles.active=prod
```
Jeżeli chcemy zmienić jakieś opcję dla pordukcji to robimy to w tym sammym katalogi w pliku `application-prod.properties` i dla dev analogicznie w `application-dev.properties`.
W paczce dla proda w protpertiesach poufne dane odczytywane są ze zmiennych środowiskowych systemu na którym odpalana jest aplikacja. Ustawić trzeba następujące zmienne:
- PLANNAPLAN_MYSQL_DB_HOST - host bazy danych np `localhost`
- PLANNAPLAN_MYSQL_DB_PORT - port na którym działa baza
- PLANNAPLAN_MYSQL_DB - nazwa bazy dancyh. W profilu **dev** jest to np test
- PLANNAPLAN_MYSQL_DB_USERNAME - nazwa użytkownika bazy
- PLANNAPLAN_MYSQL_DB_PASSWORD - hasło użytkownika bazy
## Packaging
Zeby spakowac apke do `jara` wystarcza dwie komendy zaczynajac z glownego katalogu projektu
@ -38,6 +54,22 @@ mvn clean package spring-boot:repackage
Utworzony zostanie jar w `restservice/target/restservice-1.0-SNAPSHOT.jar`. Oczywiscie zeby jar zadzialal kontenery dockerowe musza byc odpalone (lub baza danych na serwerze jesli zmienialismy propertisy z localhost)
## Generowanie dokumentacji
### Javadocs
```bash
mvn javadoc:javadoc
```
### Api docs
Żeby zobaczyć dokumentację api trzeba wejść w przeglądarce na `http://localhost:1285/swagger-ui.html` po odpaleniu aplikacji.
#### Nazewnictwo odpowiedzi
Każdą odpowiedź zaczynamy od modelu, który opisuje np. `Courses` a kończymy na `Response`. Między tymi dwoma członami możemy dodawać modyfikatory opisujące dokładniej odpowiedź np. `Default`. W ten sposób możemy otrzymać nazwę `CoursesDefaultResponse.java`
## Troubleshooting
Spring chyba cacheuje jakies dane dotyczace polaczenia wiec jesli spring wywali Ci blad `Connection Refused`, a wiesz, ze ta baza stoi na podanym ip i porcie to sprobuj

33
buisnesslogic/pom.xml Normal file → Executable file
View File

@ -12,24 +12,32 @@
<version>1.0-SNAPSHOT</version>
<name>buisnesslogic</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<url>http://plannaplan.pl</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.source>14</maven.compiler.source>
<maven.compiler.target>14</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
@ -49,7 +57,7 @@
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
<version>4.0.0</version>
</dependency>
<!-- dependency used for XLS older file format
@ -76,6 +84,15 @@
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>3.0.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>

View File

@ -1,9 +0,0 @@
package com.plannaplan;
public class Acceptor {
public Acceptor() {
}
public void run() {
}
}

View File

@ -1,46 +0,0 @@
package com.plannaplan;
import java.util.Date;
import com.plannaplan.types.AppStates;
public class App {
private static App instance;
private Date round1;
private Date round2;
private AppStates state;
private App() {
}
public AppStates getState() {
return state;
}
public void setState(AppStates state) {
this.state = state;
}
public Date getRound2() {
return round2;
}
public void setRound2(Date round2) {
this.round2 = round2;
}
public Date getRound1() {
return round1;
}
public void setRound1(Date round1) {
this.round1 = round1;
}
public App getInstance() {
if (App.instance == null) {
App.instance = new App();
}
return App.instance;
}
}

View File

@ -1,26 +0,0 @@
package com.plannaplan;
import com.plannaplan.interfaces.Historable;
import com.plannaplan.interfaces.ProtectedAction;
public class Assigner implements Historable, ProtectedAction {
public Assigner() {
}
public void assing() {
}
@Override
public void validateAction() {
// TODO Auto-generated method stub
}
@Override
public void addActionToHistory() {
// TODO Auto-generated method stub
}
}

View File

@ -1,43 +0,0 @@
package com.plannaplan;
import com.plannaplan.interfaces.ProtectedAction;
import com.plannaplan.models.ConfigData;
import com.plannaplan.models.FileData;
import com.plannaplan.services.CourseService;
import com.plannaplan.services.GroupService;
import com.plannaplan.services.LecturerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.plannaplan.configutils.*;
@Component
public class Configurator implements ProtectedAction {
@Autowired
private LecturerService lecturerService;
@Autowired
private CourseService courseService;
@Autowired
private GroupService groupService;
public Configurator() {
}
public void config(ConfigData data) {
FileReader reader = new FileReader(data.getFilestream());
FileData coursesData = reader.read();
FileToDatabaseMigrator mgtr = new FileToDatabaseMigrator(lecturerService, courseService, groupService);
mgtr.migrate(coursesData);
}
@Override
public void validateAction() {
// TODO Auto-generated method stub
}
}

View File

@ -1,41 +0,0 @@
package com.plannaplan;
import com.plannaplan.models.ConfigData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class Controller {
@Autowired
private Configurator configurator;
public Controller() {
}
public void startApp() {
}
public void assignCourse() {
}
public void addUnavailibility() {
}
public void addGroup() {
}
public void editGroup() {
}
public void getHistoryAtPoint() {
}
public void config(ConfigData data) {
configurator.config(data);
}
public void createTransfer() {
}
}

View File

@ -1,9 +0,0 @@
package com.plannaplan;
public class Emailer {
public Emailer() {
}
public void performAllMails() {
}
}

View File

@ -1,13 +0,0 @@
package com.plannaplan;
import com.plannaplan.interfaces.EventCreator;
public class EventChcker implements EventCreator {
@Override
public void update() {
// TODO Auto-generated method stub
}
}

View File

@ -1,26 +0,0 @@
package com.plannaplan;
import com.plannaplan.interfaces.Historable;
import com.plannaplan.interfaces.ProtectedAction;
public class GroupAdder implements Historable, ProtectedAction {
public GroupAdder() {
}
public void addGroup() {
}
@Override
public void addActionToHistory() {
// TODO Auto-generated method stub
}
@Override
public void validateAction() {
// TODO Auto-generated method stub
}
}

View File

@ -1,19 +0,0 @@
package com.plannaplan;
import com.plannaplan.interfaces.ProtectedAction;
public class GroupEditor implements ProtectedAction {
public GroupEditor() {
}
public void setNewCapacity(int capaity) {
}
@Override
public void validateAction() {
// TODO Auto-generated method stub
}
}

View File

@ -1,22 +0,0 @@
package com.plannaplan;
import com.plannaplan.interfaces.ProtectedAction;
public class HistoryResolver implements ProtectedAction {
public HistoryResolver() {
}
public void getHistoryAtPoint() {
}
public void reproduce() {
}
@Override
public void validateAction() {
// TODO Auto-generated method stub
}
}

View File

@ -1,26 +0,0 @@
package com.plannaplan;
import com.plannaplan.interfaces.Historable;
import com.plannaplan.interfaces.ProtectedAction;
public class TransferCreator implements Historable, ProtectedAction {
public TransferCreator() {
}
public void createTransfer() {
}
@Override
public void validateAction() {
// TODO Auto-generated method stub
}
@Override
public void addActionToHistory() {
// TODO Auto-generated method stub
}
}

View File

@ -1,19 +0,0 @@
package com.plannaplan;
import com.plannaplan.interfaces.Historable;
public class TransferValidator implements Historable {
public TransferValidator() {
}
public void performAllTransfers() {
}
@Override
public void addActionToHistory() {
// TODO Auto-generated method stub
}
}

View File

@ -1,26 +0,0 @@
package com.plannaplan;
import com.plannaplan.interfaces.Historable;
import com.plannaplan.interfaces.ProtectedAction;
public class UnavailabilityAdder implements Historable, ProtectedAction {
public UnavailabilityAdder() {
}
public void add() {
}
@Override
public void validateAction() {
// TODO Auto-generated method stub
}
@Override
public void addActionToHistory() {
// TODO Auto-generated method stub
}
}

View File

@ -1,26 +0,0 @@
package com.plannaplan.abstracts;
import java.util.ArrayList;
import java.util.List;
import com.plannaplan.interfaces.EventCreator;
public abstract class EventWatcher {
protected List<EventCreator> creators;
public EventWatcher() {
this.creators = new ArrayList<>();
}
public void attach(EventCreator creator) {
this.creators.add(creator);
}
public void detach(EventCreator creator) {
this.creators.remove(creator);
}
public void update() {
}
}

View File

@ -2,7 +2,7 @@ package com.plannaplan.configutils;
import java.io.IOException;
import java.io.InputStream;
import java.util.Hashtable;
import java.util.HashMap;
import java.util.Iterator;
import org.apache.poi.xssf.usermodel.XSSFSheet;
@ -11,6 +11,9 @@ import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import com.plannaplan.models.FileData;
/**
* FileReader is used for reading xls file from input stream.
*/
public class FileReader {
private InputStream fileInputStream;
@ -33,12 +36,12 @@ public class FileReader {
Row row = rowIt.next();
Iterator<Cell> cellIt = row.cellIterator();
Hashtable<String, Integer> keys = new Hashtable<>();
HashMap<String, Integer> keys = new HashMap<>();
int index = 0;
while (cellIt.hasNext()) {
Cell c = cellIt.next();
keys.put(c.toString(), index);
index+=1;
index += 1;
}
rowIt.remove();
@ -53,4 +56,4 @@ public class FileReader {
return result;
}
}
}

View File

@ -1,7 +1,6 @@
package com.plannaplan.configutils;
import java.util.Iterator;
import com.plannaplan.entities.Course;
import com.plannaplan.entities.Groups;
import com.plannaplan.entities.Lecturer;
@ -9,140 +8,88 @@ import com.plannaplan.models.FileData;
import com.plannaplan.services.CourseService;
import com.plannaplan.services.GroupService;
import com.plannaplan.services.LecturerService;
import com.plannaplan.types.GroupType;
import com.plannaplan.types.WeekDay;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* FileToDatabaseMigrator is used for migrate data from file (it reads line by line) and push it into database
*/
@Component
public class FileToDatabaseMigrator {
public static String LECTURER_NAME_STRING = "imie";
public static String LECTURER_SURNAME_STRING = "nazwisko";
public static String LECTURER_TITLE_STRING = "tytul";
public static String COURSE_SYMBOL_STRING = "sym";
public static String COURSE_NAME_STRING = "nazwa";
private static final String LECTURER_NAME_STRING = "imie";
private static final String LECTURER_SURNAME_STRING = "nazwisko";
private static final String LECTURER_TITLE_STRING = "tytul";
public static String GROUP_DAY_STRING = "dzien";
public static String GROUP_TIME_STRING = "godz_od";
public static String ROOM_STRING = "sala";
public static String CAPACITY_STRING = "Mc";
private static final String COURSE_SYMBOL_STRING = "sym";
private static final String COURSE_NAME_STRING = "nazwa";
LecturerService lecturerService;
CourseService courseService;
GroupService groupService;
private static final String groupDay_STRING = "dzien";
private static final String GROUP_TIME_STRING = "godz_od";
private static final String ROOM_STRING = "sala";
private static final String CAPACITY_STRING = "Mc";
public FileToDatabaseMigrator(LecturerService lecturerService, CourseService courseService,
GroupService groupService) {
this.lecturerService = lecturerService;
this.groupService = groupService;
this.courseService = courseService;
@Autowired
private LecturerService lecturerService;
@Autowired
private CourseService courseService;
@Autowired
private GroupService groupService;
public FileToDatabaseMigrator() {
}
public void migrate(FileData data) {
Iterator<Row> rows = data.getRows();
int courseNameIndex = data.getIndexOf(FileToDatabaseMigrator.COURSE_NAME_STRING);
int symbolIndex = data.getIndexOf(FileToDatabaseMigrator.COURSE_SYMBOL_STRING);
int course_name_index = data.getIndexOf(FileToDatabaseMigrator.COURSE_NAME_STRING);
int sym_index = data.getIndexOf(FileToDatabaseMigrator.COURSE_SYMBOL_STRING);
int titleIndex = data.getIndexOf(FileToDatabaseMigrator.LECTURER_TITLE_STRING);
int surnameIndex = data.getIndexOf(FileToDatabaseMigrator.LECTURER_SURNAME_STRING);
int nameIndex = data.getIndexOf(FileToDatabaseMigrator.LECTURER_NAME_STRING);
int title_index = data.getIndexOf(FileToDatabaseMigrator.LECTURER_TITLE_STRING);
int surname_index = data.getIndexOf(FileToDatabaseMigrator.LECTURER_SURNAME_STRING);
int name_index = data.getIndexOf(FileToDatabaseMigrator.LECTURER_NAME_STRING);
int day_index = data.getIndexOf(FileToDatabaseMigrator.GROUP_DAY_STRING);
int time_index = data.getIndexOf(FileToDatabaseMigrator.GROUP_TIME_STRING);
int room_index = data.getIndexOf(FileToDatabaseMigrator.ROOM_STRING);
int capacity_index = data.getIndexOf(FileToDatabaseMigrator.CAPACITY_STRING);
int dayIndex = data.getIndexOf(FileToDatabaseMigrator.groupDay_STRING);
int timeIndex = data.getIndexOf(FileToDatabaseMigrator.GROUP_TIME_STRING);
int roomIndex = data.getIndexOf(FileToDatabaseMigrator.ROOM_STRING);
int capacityIndex = data.getIndexOf(FileToDatabaseMigrator.CAPACITY_STRING);
while (rows.hasNext()) {
Row row = rows.next();
Cell course_name_cell = row.getCell(course_name_index);
Cell sym = row.getCell(sym_index);
String courseName = row.getCell(courseNameIndex).toString().trim();
String symbol = row.getCell(symbolIndex).toString().trim();
Cell title_cell = row.getCell(title_index);
Cell name_cell = row.getCell(name_index);
Cell surname_cell = row.getCell(surname_index);
String lecturerTitle = row.getCell(titleIndex) != null ? row.getCell(titleIndex).toString().trim() : "";
String lecturerName = row.getCell(nameIndex) != null ? row.getCell(nameIndex).toString().trim() : "";
String lecturerSurname = row.getCell(surnameIndex) != null ? row.getCell(surnameIndex).toString().trim()
: "";
Cell day_cell = row.getCell(day_index);
Cell time_cell = row.getCell(time_index);
Cell room_cell = row.getCell(room_index);
Cell capacity_cell = row.getCell(capacity_index);
int day = (int) Double.parseDouble(row.getCell(dayIndex).toString());
WeekDay groupDay = WeekDay.getDay(day - 1);
int time = parseTimeToInt(row.getCell(timeIndex).toString());
String room = row.getCell(roomIndex).toString().trim();
int capacity = (int) Double.parseDouble(row.getCell(capacityIndex).toString());
String lecturer_title = "";
String lecturer_surname = "";
String lecturer_name = "";
Course course = this.courseService.getCourseByName(courseName)
.orElseGet(() -> this.courseService.save(new Course(courseName, symbol)));
String course_name = course_name_cell.toString().trim();
String sym_str = sym.toString().trim();
Lecturer lecturer = this.lecturerService.getLecturer(lecturerTitle, lecturerName, lecturerSurname)
.orElseGet(() -> this.lecturerService
.save(new Lecturer(lecturerTitle, lecturerName, lecturerSurname)));
int day = (int) Double.parseDouble(day_cell.toString());
WeekDay group_day = WeekDay.getDay(day - 1);
String room = room_cell.toString().trim();
int time = this.parseTimeToInt(time_cell.toString());
int capacity = (int) Double.parseDouble(capacity_cell.toString());
Groups group = groupService.find(time, capacity, room);
Course course = this.courseService.getCourseByName(course_name);
if (course == null) {
course = new Course();
course.setName(course_name);
course.setSymbol(sym_str);
}
courseService.save(course);
if (title_cell != null) {
lecturer_title = title_cell.toString().trim();
}
if (name_cell != null) {
lecturer_name = name_cell.toString().trim();
}
if (surname_cell != null) {
lecturer_surname = surname_cell.toString().trim();
}
Lecturer lecturer = lecturerService.getLecturer(lecturer_title, lecturer_name, lecturer_surname);
if (lecturer == null) {
lecturer = new Lecturer(lecturer_title, lecturer_name, lecturer_surname);
lecturerService.save(lecturer);
}
if (group == null) {
group = new Groups();
group.setCapacity(capacity);
group.setRoom(room);
group.setCourseId(course);
group.setTime(time);
if (capacity >= 50) {
group.setType(GroupType.LECTURE);
} else {
group.setType(GroupType.CLASS);
}
group.setDay(group_day);
group.setLecturer(lecturer);
groupService.save(group);
}
this.groupService.find(time, capacity, room).orElseGet(
() -> this.groupService.save(new Groups(capacity, room, course, time, groupDay, lecturer)));
}
}
private Integer parseTimeToInt(String time) {
String times[] = time.split("\\.");
if (times.length == 2) {
return Integer.parseInt(times[0]) * 60 + Integer.parseInt(times[1]);
}
times = time.split("\\:");
if (times.length == 2) {
return Integer.parseInt(times[0]) * 60 + Integer.parseInt(times[1]);
}
private static int parseTimeToInt(String time) {
String times[] = time.split("\\.|\\:");
return times.length == 2 ? Integer.parseInt(times[0]) * 60 + Integer.parseInt(times[1]) : 0;
return 0;
}
}

View File

@ -7,6 +7,11 @@ import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
/**
* Entity of Assignment grouping of state associated about group_id and commision_id
*
*/
@Entity
public class Assignment {
@Id
@ -16,9 +21,64 @@ public class Assignment {
@JoinColumn(name = "group_id")
private Groups group;
@ManyToOne
@JoinColumn(name = "user_id")
private User user;
@JoinColumn(name = "commision_id")
private Commision commision;
private boolean isPastAssignment;
/**
* Assignment
* @param group group we would like to assign
* @param commision commision that assignment belongs to
* @param isPastAssignment is assignment past or no
*/
public Assignment(Groups group, Commision commision, boolean isPastAssignment) {
this.commision = commision;
this.group = group;
}
/**
* Assignment
* @param group group we would like to assign
* @param commision commision that assignment belongs to
*/
public Assignment(Groups group, Commision commision) {
this(group, commision, false);
}
public Assignment() {
}
/**
* Id getter
* @return id id of assignment
*/
public Long getId() {
return this.id;
}
/**
* getGroup
*
* @return group
*/
public Groups getGroup() {
return this.group;
}
/**
* isPastAssignment getter
* @return isPastAssignment
*/
public boolean isPastAssignment() {
return isPastAssignment;
}
/**
* setter isPastAssignment
* @param isPastAssignment
*/
public void setPastAssignment(boolean isPastAssignment) {
this.isPastAssignment = isPastAssignment;
}
}

View File

@ -0,0 +1,77 @@
package com.plannaplan.entities;
import java.sql.Timestamp;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
/**
* Entity of Commision grouping of state associated about commison and owner_id
*/
@Entity
public class Commision {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@OneToOne
@JoinColumn(name = "owner_id")
private User commisionOwner;
private Timestamp commisionDate;
@OneToMany(mappedBy = "commision", fetch = FetchType.EAGER)
private List<Assignment> assignments;
/**
*
* @param user owner of commission. Can not be null otherwise saving commision
* will fail.
*/
public Commision(User user) {
this.commisionDate = new Timestamp(System.currentTimeMillis());
this.commisionOwner = user;
}
public Commision() {
}
/**
* Id getter
* @return id id of commision
*/
public Long getId() {
return this.id;
}
/**
* CommisionDate getter
* @return commisionDate
*/
public Timestamp getCommisionDate() {
return commisionDate;
}
/**
* User of given commision getter
* @return User commisionOwner
*/
public User getCommisionOwner() {
return commisionOwner;
}
/**
* Assigments getter
* @return List of assignments
*/
public List<Assignment> getAssignments() {
return this.assignments;
}
}

View File

@ -10,6 +10,10 @@ import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
/**
* Entity of Course grouping of state of course
*/
@Entity
public class Course {
@Id
@ -17,34 +21,69 @@ public class Course {
private Long id;
private String name;
private String symbol;
@OneToMany(mappedBy = "courseId", fetch = FetchType.EAGER)
@OneToMany(mappedBy = "course", fetch = FetchType.EAGER)
private List<Groups> groups = new ArrayList<>();
public Course() {
}
/**
* Course
*
* @param name name given to the course
* @param symbol symbol given to the course
*/
public Course(String name, String symbol) {
this.name = name;
this.symbol = symbol;
}
/**
* getId
* @return id
*/
public Long getId() {
return this.id;
}
/**
* getName
* @return name
*/
public String getName() {
return name;
}
/**
* getSymbol
* @return symbol
*/
public String getSymbol() {
return symbol;
}
/**
* setSymbol
* @param symbol set symbol in the course
*/
public void setSymbol(String symbol) {
this.symbol = symbol;
}
/**
* setName
* @param name set name in the course
*/
public void setName(String name) {
this.name = name;
}
public List<Groups> getGroups(){
/**
* getGroups
* @return groups return list groups
*/
public List<Groups> getGroups() {
return this.groups;
}
}
}

View File

@ -1,32 +0,0 @@
package com.plannaplan.entities;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import com.plannaplan.types.EventTypes;
@Entity
public class Event {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private EventTypes type;
@ManyToOne
@JoinColumn(name = "user_id")
private User user;
public Event() {
}
public EventTypes getType() {
return type;
}
public void setType(EventTypes type) {
this.type = type;
}
}

View File

@ -10,6 +10,10 @@ import javax.persistence.ManyToOne;
import com.plannaplan.types.GroupType;
import com.plannaplan.types.WeekDay;
/**
* Entity of Groups grouping of state ssociated about course,time,room,capacity,type,day
*/
@Entity
public class Groups {
@Id
@ -17,7 +21,7 @@ public class Groups {
private Long id;
@ManyToOne
@JoinColumn(name = "course_id")
private Course courseId;
private Course course;
private int time;
private String room;
private int capacity;
@ -30,66 +34,150 @@ public class Groups {
public Groups() {
}
/**
* Groups
*
* @param capacity capacity given to the groups
* @param room room given to the groups
* @param course course given to the groups
* @param time time given to the groups
* @param day day given to the groups
* @param lecturer lecturer given to the groups
*/
public Groups(int capacity, String room, Course course, int time, WeekDay day, Lecturer lecturer) {
this.capacity = capacity;
this.room = room;
this.course = course;
this.time = time;
this.day = day;
this.lecturer = lecturer;
this.type = capacity >= 50 ? GroupType.LECTURE : GroupType.CLASS;
}
/**
* getId
* @return id
*/
public Long getId() {
return this.id;
}
/**
* getLecturer
* @return lecturer
*/
public Lecturer getLecturer() {
return lecturer;
}
/**
* setLecturer
* @param lecturer set lecturer into groups
*/
public void setLecturer(Lecturer lecturer) {
this.lecturer = lecturer;
}
/**
* WeekDay
* @return day
*/
public WeekDay getDay() {
return day;
}
/**
* setLecturer
* @param day set day into groups
*/
public void setDay(WeekDay day) {
this.day = day;
}
/**
* GroupType
* @return type
*/
public GroupType getType() {
return type;
}
/**
* setType
* @param type set type into groups
*/
public void setType(GroupType type) {
this.type = type;
}
/**
* getCapacity
* @return capacity
*/
public int getCapacity() {
return capacity;
}
/**
* setCapacity
* @param capacity set capacity into groups
*/
public void setCapacity(int capacity) {
this.capacity = capacity;
}
/**
* getRoom
* @return room
*/
public String getRoom() {
return room;
}
/**
* setRoom
* @param room set room into groups
*/
public void setRoom(String room) {
this.room = room;
}
/**
* getTime
* @return time
*/
public int getTime() {
return time;
}
/**
* setTime
* @param time set time into groups
*/
public void setTime(int time) {
this.time = time;
}
/**
* getCourseId
* @return course
*/
public Course getCourseId() {
return courseId;
return course;
}
/**
* setCourseId
* @param courseId set courseId into groups
*/
public void setCourseId(Course courseId) {
this.courseId = courseId;
this.course = courseId;
}
/**
* getTimeString
* @return time as formated String
*/
public String getTimeString() {
int minutes = this.getTime() % 60;
String hoursString = Integer.toString(this.getTime() / 60);
@ -99,4 +187,4 @@ public class Groups {
}
return String.format("%s.%s", hoursString, minutesString);
}
}
}

View File

@ -1,25 +0,0 @@
package com.plannaplan.entities;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
@Entity
public class HistoryElement {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@ManyToOne
@JoinColumn(name = "user_id")
private User user;
@ManyToOne
@JoinColumn(name = "incoming_id")
private Groups incoming;
@ManyToOne
@JoinColumn(name = "outcoming_id")
private Groups outcoming;
}

View File

@ -5,6 +5,10 @@ import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
/**
* Entity of Lecturer grouping of state ssociated about id,title,name,surname
*/
@Entity
public class Lecturer {
@Id
@ -14,30 +18,14 @@ public class Lecturer {
private String name;
private String surname;
public String getTitle() {
return title;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void setTitle(String title) {
this.title = title;
}
/**
* Lecturer
*
* @param title title given to the lecturer
* @param name name given to the lecturer
* @param surname surname given to the lecturer
*/
public Lecturer(String title, String name, String surname) {
this.title = title;
this.name = name;
@ -47,9 +35,63 @@ public class Lecturer {
public Lecturer() {
}
/**
* getTitle
* @return title
*
*/
public String getTitle() {
return title;
}
/**
* getSurname
* @return surname
*
*/
public String getSurname() {
return surname;
}
/**
* setSurname
* @param surname set surname to the lecturer
*
*/
public void setSurname(String surname) {
this.surname = surname;
}
/**
* getName
* @return name
*
*/
public String getName() {
return name;
}
/**
* setName
* @param name set name to the lecturer
*
*/
public void setName(String name) {
this.name = name;
}
/**
* setTitle
* @param title set title to the lecturer
*
*/
public void setTitle(String title) {
this.title = title;
}
@Override
public String toString() {
return String.format("%s %s %s", this.title, this.name, this.surname);
}
}
}

View File

@ -1,28 +0,0 @@
package com.plannaplan.entities;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
@Entity
public class Transfer {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@ManyToOne
@JoinColumn(name = "owner_id")
private User ownerUser;
@ManyToOne
@JoinColumn(name = "group_id")
private Groups ownerGroup;
@ManyToOne
@JoinColumn(name = "target_id")
private Groups targetGroup;
public Transfer() {
}
}

View File

@ -1,30 +0,0 @@
package com.plannaplan.entities;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
@Entity
public class Unavailability {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@ManyToOne
@JoinColumn(name = "user_id")
private User lecturer;
private int time;
public Unavailability() {
}
public int getTime() {
return time;
}
public void setTime(int time) {
this.time = time;
}
}

View File

@ -1,5 +1,8 @@
package com.plannaplan.entities;
import java.sql.Timestamp;
import java.util.concurrent.TimeUnit;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
@ -7,39 +10,182 @@ import javax.persistence.Id;
import com.plannaplan.types.UserRoles;
/**
* Entity of User grouping of state ssociated about id,name,surname,email,role,token,tokenCreatedDate
*/
@Entity
public class User {
private static final float TOKEN_EXPIRE_MINUTES = 15;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
private String surname;
private String email;
private String usosId;
private UserRoles role;
private String token;
private Timestamp tokenUsageDate;
public User() {
}
/*
* User
*
* @param name name given to the user
* @param surname surname given to the user
* @param email mail given to the user
* @param role role given to the user
*/
public User(String name, String surname, String mail, UserRoles role) {
this.name = name;
this.surname = surname;
this.email = mail;
this.role = role;
}
/*
* User
*
* @param name name given to the user
* @param surname surname given to the user
* @param email mail given to the user
* @param usosId id in the USOS system
* @param role role given to the user
*/
public User(String name, String surname, String mail, String usosId, UserRoles role){
this(name,surname,mail,role);
this.usosId = usosId;
}
/*
* getusosId
*
* @return usosId
*/
public String getUsosId() {
return usosId;
}
/*
* getEmail
*
* @return email
*/
public String getEmail() {
return email;
}
/*
* setEmail
*
* @param email set email to the user
*/
public void setEmail(String email) {
this.email = email;
}
/*
* getTokenUsageDate
*
* @return tokenUsageDate
*/
public Timestamp getTokenUsageDate() {
return tokenUsageDate;
}
/*
* getToken
*
* @return token
*/
public String getToken() {
return token;
}
/*
* setToken
*
* @param token set token to the entity
*/
public void setToken(String token) {
this.tokenUsageDate = new Timestamp(System.currentTimeMillis());
this.token = token;
}
/* getName
*
* @return name
*/
public String getName() {
return name;
}
/* getRole
*
* @return role
*/
public UserRoles getRole() {
return role;
}
/* setRole
*
* @param role set role to the entity
*/
public void setRole(UserRoles role) {
this.role = role;
}
/*
* getSurname
* @return surname
*/
public String getSurname() {
return surname;
}
/*
* setSurname
* @param surname set surname into entity user
*/
public void setSurname(String surname) {
this.surname = surname;
}
/*
* setName
* @param name set name into entity user
*/
public void setName(String name) {
this.name = name;
}
}
/*
* getId
* @return id
*/
public Long getId() {
return this.id;
}
/*
* isCredentialsNonExpired
* Returns TRUE if is Credentials Non Expired in the otherwise it returns false
*/
public boolean isCredentialsNonExpired() {
final long diffInMilliseconds = Math
.abs(this.tokenUsageDate.getTime() - new Timestamp(System.currentTimeMillis()).getTime());
final long minutes = TimeUnit.MILLISECONDS.toMinutes(diffInMilliseconds);
if (minutes > TOKEN_EXPIRE_MINUTES) {
return false;
}
this.tokenUsageDate = new Timestamp(System.currentTimeMillis());
return true;
}
}

View File

@ -0,0 +1,13 @@
package com.plannaplan.exceptions;
public class TokenExpiredException extends RuntimeException {
/**
*
*/
private static final long serialVersionUID = 1L;
public TokenExpiredException(String message) {
super(message);
}
}

View File

@ -0,0 +1,13 @@
package com.plannaplan.exceptions;
public class UserNotFoundException extends Exception {
/**
*
*/
private static final long serialVersionUID = 1L;
public UserNotFoundException(String message) {
super(message);
}
}

View File

@ -1,5 +0,0 @@
package com.plannaplan.interfaces;
public interface EventCreator {
void update();
}

View File

@ -1,5 +0,0 @@
package com.plannaplan.interfaces;
public interface Historable {
void addActionToHistory();
}

View File

@ -1,5 +0,0 @@
package com.plannaplan.interfaces;
public interface ProtectedAction {
void validateAction();
}

View File

@ -8,22 +8,44 @@ public class ConfigData {
private Date end;
private InputStream filestream;
/*
* ConfigData
*
* @param start when the configdata begins
* @param end when the configdata ends
* @param filestream where the filestream is
*/
public ConfigData(Date start, Date end, InputStream filestream) {
this.start = start;
this.end = end;
this.filestream = filestream;
}
/*
* getFilestream
*
* @return filestream
*/
public InputStream getFilestream() {
return filestream;
}
/*
* getEnd
*
* @return end
*/
public Date getEnd() {
return end;
}
/*
* getStart
*
* @return start
*/
public Date getStart() {
return start;
}
}
}

View File

@ -1,39 +1,65 @@
package com.plannaplan.models;
import java.util.Dictionary;
import java.util.HashMap;
import java.util.Iterator;
import org.apache.poi.ss.usermodel.Row;
public class FileData {
private Dictionary<String, Integer> keys;
private HashMap<String, Integer> keys;
private Iterator<Row> rows;
public FileData(Dictionary<String, Integer> keys, Iterator<Row> rows) {
this.setKeys(keys);
this.setRows(rows);
/*
* FileData
*
* @param keys this is a hashmap of String and Integer
* @param rows this is a iterator of rows.
*/
public FileData(HashMap<String, Integer> keys, Iterator<Row> rows) {
this.keys = keys;
this.rows = rows;
}
/*
* getRows
*
* @return rows
*/
public Iterator<Row> getRows() {
return rows;
}
/*
* setRows
* @param rows set the rows to given function
*/
public void setRows(Iterator<Row> rows) {
this.rows = rows;
}
public Dictionary<String, Integer> getKeys() {
/*
* getKeys
* @return keys
*/
public HashMap<String, Integer> getKeys() {
return keys;
}
public void setKeys(Dictionary<String, Integer> keys) {
/*
* setKeys
* @param keys set the key is being a struck of hashmap (String, Integer)
*/
public void setKeys(HashMap<String, Integer> keys) {
this.keys = keys;
}
/*
* getIndexOf
* @return index
*/
public int getIndexOf(String key) {
int index = this.keys.get(key);
return index;
}
}
}

View File

@ -1,11 +1,25 @@
package com.plannaplan.repositories;
import java.util.List;
import com.plannaplan.entities.Assignment;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
/**
* AssignmentRepository.getByCommision:
* Return list of:
* SELECT * FROM Assignment WHERE commision_id = i .
*
* Where i, ?1 are equale to variables.
*/
@Repository
public interface AssignmentRepository extends JpaRepository<Assignment, Long> {
@Query("FROM Assignment WHERE commision_id = ?1")
List<Assignment> getByCommision(@Param("commision_id") Long id);
}

View File

@ -0,0 +1,33 @@
package com.plannaplan.repositories;
import java.util.List;
import com.plannaplan.entities.Commision;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
/**
* CommisionRepository.getUsers:
* Return list of:
* SELECT * FROM Commision WHERE owner_id = i .
*
* Where i, ?1 are equale to variables.
*
* CommisionRepository.getNewestCommision
* Return list of:
* SELECT * FROM Commision WHERE owner_id = i Order by commisionDate desc.
*
* Where i, ?1 are equale to variables.
*/
@Repository
public interface CommisionRepository extends JpaRepository<Commision, Long> {
@Query("FROM Commision WHERE owner_id = ?1")
List<Commision> getUsers(@Param("owner_id") Long id);
@Query("FROM Commision WHERE owner_id = ?1 order by commisionDate desc")
List<Commision> getNewestCommision(@Param("owner_id") Long id);
}

View File

@ -1,5 +1,7 @@
package com.plannaplan.repositories;
import java.util.Optional;
import com.plannaplan.entities.Course;
import org.springframework.data.jpa.repository.JpaRepository;
@ -7,8 +9,15 @@ import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
/**
* CourseRepository.findByName:
* Return list of:
* SELECT * FROM Course WHERE name = i .
*
* Where i, ?1 are equale to variables.
*/
@Repository
public interface CourseRepository extends JpaRepository<Course, Long> {
@Query(value = "SELECT * FROM course WHERE name = :name", nativeQuery = true)
Course findByName(@Param("name") String name);
@Query("FROM Course WHERE name = ?1")
Optional<Course> findByName(@Param("name") String name);
}

View File

@ -1,11 +0,0 @@
package com.plannaplan.repositories;
import com.plannaplan.entities.Event;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface EventRepository extends JpaRepository<Event, Long> {
}

View File

@ -1,6 +1,7 @@
package com.plannaplan.repositories;
import java.util.List;
import java.util.Optional;
import com.plannaplan.entities.Groups;
@ -9,12 +10,39 @@ import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
/**
* GroupRepository.find:
* Return list of:
* SELECT * FROM Groups WHERE time = i AND room = j AND capacity = k .
*
* Where i, j, k, ?1, ?2, ?3 are equale to variables.
*
* GroupRepository.getByCourse:
* Return list of:
* SELECT * FROM Groups WHERE course_id = i .
*
* Where i, ?1 are equale to variables.
*/
@Repository
public interface GroupRepository extends JpaRepository<Groups, Long> {
@Query(value = "SELECT * FROM groups WHERE time = :time AND room = :room AND capacity = :capacity ", nativeQuery = true)
Groups find(@Param("time") int time, @Param("room") String room, @Param("capacity") int capacity);
@Query("FROM Groups WHERE time = ?1 AND room = ?2 AND capacity = ?3")
Optional<Groups> find(@Param("time") int time, @Param("room") String room, @Param("capacity") int capacity);
@Query(value = "SELECT * FROM groups WHERE course_id = :id", nativeQuery = true)
@Query("FROM Groups WHERE course_id = ?1")
List<Groups> getByCourse(@Param("id") Long id);
@Query("SELECT COUNT(*) AS assinged_times FROM Assignment WHERE isPastAssignment=false GROUP BY group HAVING group_id=?1")
Optional<Number> getAssignedAmount(Long groupId);
/**
* PLAIN SQL QUERY: SELECT group_id, COUNT(*) assinged_times FROM assignment
* WHERE is_past_assignment=0 GROUP BY group_id HAVING group_id IN (:ids)")
*
* @param groupIds list of groups ids
* @return list of objects arrays where first object is Groups instance and
* second is Long that is taken places value
*/
@Query("SELECT group, COUNT(*) AS assinged_times FROM Assignment a WHERE a.isPastAssignment=false GROUP BY a.group HAVING group_id IN (:ids)")
List<Object[]> getAssignedAmounts(@Param("ids") List<Long> groupIds);
}

View File

@ -1,11 +0,0 @@
package com.plannaplan.repositories;
import com.plannaplan.entities.HistoryElement;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface HistoryRepository extends JpaRepository<HistoryElement, Long> {
}

View File

@ -1,5 +1,7 @@
package com.plannaplan.repositories;
import java.util.Optional;
import com.plannaplan.entities.Lecturer;
import org.springframework.data.jpa.repository.JpaRepository;
@ -7,8 +9,15 @@ import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
/**
* LecturerRepository.find:
* Return list of:
* SELECT * FROM Lecturer WHERE title = i AND name = j AND surname = k.
*
* Where i, j, k, ?1, ?2, ?3 are equale to variables.
*/
@Repository
public interface LecturerRepository extends JpaRepository<Lecturer, Long> {
@Query(value = "SELECT * FROM lecturer WHERE name = :name AND surname = :surname AND title = :title ", nativeQuery = true)
Lecturer find(@Param("title") String title, @Param("name") String name, @Param("surname") String surname);
@Query("FROM Lecturer WHERE title = ?1 AND name = ?2 AND surname = ?3")
Optional<Lecturer> find(@Param("title") String title, @Param("name") String name, @Param("surname") String surname);
}

View File

@ -1,11 +0,0 @@
package com.plannaplan.repositories;
import com.plannaplan.entities.Transfer;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface TransferRepository extends JpaRepository<Transfer, Long> {
}

View File

@ -1,11 +0,0 @@
package com.plannaplan.repositories;
import com.plannaplan.entities.Unavailability;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface UnavailabilityRepository extends JpaRepository<Unavailability, Long> {
}

View File

@ -1,11 +1,56 @@
package com.plannaplan.repositories;
import java.util.List;
import java.util.Optional;
import com.plannaplan.entities.User;
import com.plannaplan.types.UserRoles;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
/**
* UserRepository.getByAuthority:
* Return list of:
* SELECT * FROM User WHERE email = i.
*
* Where i, ?1 are equale to variables.
*
* UserRepository.getByToken:
* Return list of:
* SELECT * FROM User WHERE token = i.
*
* Where i, ?1 are equale to variables.
*
* UserRepository.searchForUsers:
* Return list of:
* SELECT * FROM User WHERE (name LIKE %?1% OR surname LIKE %?1%).
*
* Where i, ?1 are equale to variables.
*
* UserRepository.searchForUsers with role:
* Return list of:
* SELECT * FROM User WHERE (name LIKE %?1% OR surname LIKE %?1%) AND role=?2").
*
* Where i, ?1 are equale to variables.
*/
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
@Query("FROM User WHERE email = ?1")
Optional<User> getByAuthority(@Param("authority") String authority);
@Query("FROM User WHERE token = ?1")
Optional<User> getByToken(@Param("token") String token);
@Query("FROM User WHERE (name LIKE %?1% OR surname LIKE %?1%)")
List<User> searchForUsers(@Param("query") String query);
@Query("FROM User WHERE (name LIKE %?1% OR surname LIKE %?1%) AND role=?2")
List<User> searchForUsers(@Param("query") String query, @Param("role") UserRoles role);
@Query("FROM User WHERE usosId = ?1")
Optional<User> getByUsosId(@Param("usosId") String usosId);
}

View File

@ -1,17 +1,58 @@
package com.plannaplan.services;
import com.plannaplan.abstracts.EventWatcher;
import java.util.List;
import java.util.Optional;
import com.plannaplan.entities.Assignment;
import com.plannaplan.entities.Commision;
import com.plannaplan.repositories.AssignmentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* Service of Assignment which can save assignments, diplay assignments, get ammount of assigments.
*/
@Service
public class AssignmentService extends EventWatcher {
public class AssignmentService {
@Autowired
private AssignmentRepository repo;
public AssignmentService() {
super();
}
}
/**
* Save given assignment
* @param assignment assignment to save
* @return assignment saved assignment with database id
*/
public Assignment save(Assignment assignment) {
return this.repo.save(assignment);
}
/*
* getCommisionAssignments
* Return id of the commision
*/
public List<Assignment> getCommisionAssignments(Commision com) {
return this.repo.getByCommision(com.getId());
}
/*
* getAssignmentsAmmount
* Return count assignments ammount
*/
public long getAssignmentsAmmount() {
return this.repo.count();
}
/**
* Get assigmnent by id
* @param id id of assigmnent
* @return Optional of assignment
*/
public Optional<Assignment> getById(Long id) {
return this.repo.findById(id);
}
}

View File

@ -0,0 +1,71 @@
package com.plannaplan.services;
import java.util.List;
import java.util.Optional;
import com.plannaplan.entities.Commision;
import com.plannaplan.entities.User;
import com.plannaplan.repositories.AssignmentRepository;
import com.plannaplan.repositories.CommisionRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* Service of CommisionService which can save commision, get user's commisions, get newest user's commision, get ammount of commisions.
*/
@Service
public class CommisionService {
@Autowired
private CommisionRepository repo;
@Autowired
private AssignmentRepository aRepository;
public CommisionService() {
}
/*
* save
*
* @param commision which assignment should be save in service
* @return commision
*/
public Commision save(Commision commision) {
Optional<Commision> lastCommision = this.getNewestCommision(commision.getCommisionOwner());
if (lastCommision.isPresent()) {
final Commision lastCom = lastCommision.get();
lastCom.getAssignments().forEach(assignment -> {
assignment.setPastAssignment(true);
this.aRepository.save(assignment);
});
}
this.repo.save(commision);
return commision;
}
/*
* getUsersCommisions
* Return given users id
*/
public List<Commision> getUsersCommisions(User user) {
return this.repo.getUsers(user.getId());
}
/*
* getNewestCommision
* Return the newest commision of the user
*/
public Optional<Commision> getNewestCommision(User user) {
return this.repo.getNewestCommision(user.getId()).stream().findFirst();
}
/*
* getCommisionsAmmount
* Return ammount of commisions
*/
public long getCommisionsAmmount() {
return this.repo.count();
}
}

View File

@ -0,0 +1,29 @@
package com.plannaplan.services;
import com.plannaplan.models.ConfigData;
import com.plannaplan.models.FileData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.plannaplan.configutils.*;
/**
* FileReader is used for reading xls file from input stream.
*/
@Component
public class ConfiguratorService {
@Autowired
private FileToDatabaseMigrator migrator;
public ConfiguratorService() {
}
public void config(ConfigData data) {
FileReader reader = new FileReader(data.getFilestream());
FileData coursesData = reader.read();
migrator.migrate(coursesData);
}
}

View File

@ -1,6 +1,7 @@
package com.plannaplan.services;
import java.util.List;
import java.util.Optional;
import com.plannaplan.entities.Course;
import com.plannaplan.repositories.CourseRepository;
@ -8,20 +9,53 @@ import com.plannaplan.repositories.CourseRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* Service of CourseService which can get(Course By Name, All Courses, Courses Ammount ), save, delete course.
*/
@Service
public class CourseService {
@Autowired
private CourseRepository repo;
public Course getCourseByName(String name) {
/*
* getCourseByName
* Return Course By Name
*/
public Optional<Course> getCourseByName(String name) {
return this.repo.findByName(name);
}
/*
* getAllCourses
* Return List of get courses
*/
public List<Course> getAllCourses() {
return this.repo.findAll();
}
public void save(Course course) {
/*
* save
* @param course which course you would like to save
*/
public Course save(Course course) {
this.repo.save(course);
return course;
}
}
/*
* delete
* @param course which course you would like to delete
*/
public void delete(Course course) {
this.repo.delete(course);
}
/*
* getCoursesAmmount
* Return a ammount of courses
*/
public int getCoursesAmmount() {
return (int) this.repo.count();
}
}

View File

@ -1,12 +0,0 @@
package com.plannaplan.services;
import com.plannaplan.repositories.EventRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class EventService {
@Autowired
private EventRepository repo;
}

View File

@ -1,6 +1,11 @@
package com.plannaplan.services;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.function.Function;
import com.plannaplan.entities.Groups;
import com.plannaplan.repositories.GroupRepository;
@ -8,6 +13,11 @@ import com.plannaplan.repositories.GroupRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* Service of GroupService which can find(optional), get(By Course, Groups
* Ammount, Group By Id, find Not Existing Group), save, delete group.
*/
@Service
public class GroupService {
@Autowired
@ -16,7 +26,7 @@ public class GroupService {
public GroupService() {
}
public Groups find(int time, int capacity, String room) {
public Optional<Groups> find(int time, int capacity, String room) {
return this.repo.find(time, room, capacity);
}
@ -24,7 +34,59 @@ public class GroupService {
return this.repo.getByCourse(id);
}
public void save(Groups group) {
this.repo.save(group);
public Groups save(Groups group) {
return this.repo.save(group);
}
public void delete(Groups groups) {
this.repo.delete(groups);
}
public int getGroupsAmmount() {
return (int) this.repo.count();
}
public Optional<Groups> getGroupById(Long id) {
return this.repo.findById(id);
}
public Optional<Long> findNotExistingGroup(List<Long> ids) {
for (Long oneId : ids) {
if (this.repo.existsById(oneId) == false) {
return Optional.of(oneId);
}
}
return Optional.empty();
}
/**
*
* @param groups list of groups you want to get taken places ammount
* @return HashMap<Long, Integer> where Long is group id and Integer is how many
* places in gorup is already taken
*/
public HashMap<Long, Integer> getTakenPlaces(List<Groups> groups) {
HashMap<Long, Integer> response = new HashMap<>();
if (groups.size() == 0) {
return response;
}
List<Object[]> respoonses = this.repo
.getAssignedAmounts(groups.stream().filter(Objects::nonNull).map(new Function<Groups, Long>() {
@Override
public Long apply(Groups p) {
final Long id = p.getId();
response.put(id, 0);
return id;
}
}).collect(Collectors.toList()));
for (Object[] element : respoonses) {
response.put(((Groups) element[0]).getId(), ((Long) element[1]).intValue());
}
return response;
}
}

View File

@ -1,12 +0,0 @@
package com.plannaplan.services;
import com.plannaplan.repositories.HistoryRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class HistoryService {
@Autowired
private HistoryRepository repo;
}

View File

@ -1,21 +1,35 @@
package com.plannaplan.services;
import java.util.Optional;
import com.plannaplan.entities.Lecturer;
import com.plannaplan.repositories.LecturerRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* Service of LecturerService which can get(Lecturer, Lecturers Ammount), save, delete lecturers.
*/
@Service
public class LecturerService {
@Autowired
private LecturerRepository repo;
public Lecturer getLecturer(String title, String name, String surname) {
public Optional<Lecturer> getLecturer(String title, String name, String surname) {
return repo.find(title, name, surname);
}
public void save(Lecturer lecturer) {
public Lecturer save(Lecturer lecturer) {
repo.save(lecturer);
return lecturer;
}
public void delete(Lecturer lecturer) {
repo.delete(lecturer);
}
public int getLecturersAmmount() {
return (int) this.repo.count();
}
}

View File

@ -1,17 +0,0 @@
package com.plannaplan.services;
import com.plannaplan.abstracts.EventWatcher;
import com.plannaplan.repositories.TransferRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class TransferService extends EventWatcher {
@Autowired
private TransferRepository repo;
public TransferService() {
super();
}
}

View File

@ -1,12 +0,0 @@
package com.plannaplan.services;
import com.plannaplan.repositories.UnavailabilityRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UnavailabilityService {
@Autowired
private UnavailabilityRepository repos;
}

View File

@ -1,13 +1,22 @@
package com.plannaplan.services;
import com.plannaplan.abstracts.EventWatcher;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import com.plannaplan.entities.User;
import com.plannaplan.exceptions.UserNotFoundException;
import com.plannaplan.repositories.UserRepository;
import com.plannaplan.types.UserRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* Service of UserService which can get(By Email), login, save user.
*/
@Service
public class UserService extends EventWatcher {
public class UserService {
@Autowired
private UserRepository repo;
@ -15,4 +24,57 @@ public class UserService extends EventWatcher {
super();
}
public User checkForUser(String email, String usosId) {
if (usosId == null) {
Optional<User> user = this.repo.getByAuthority(email.replace("\n", "").trim());
if (user.isPresent()) {
return user.get();
} else {
final User newUser = new User(null, null, email.replace("\n", "").trim(), UserRoles.STUDENT);
return this.repo.save(newUser);
}
} else {
Optional<User> user = this.repo.getByUsosId(usosId.replace("\n", "").trim());
if (user.isPresent()) {
return user.get();
} else {
final User newUser = new User(null, null, email.replace("\n", "").trim(), usosId, UserRoles.STUDENT);
return this.repo.save(newUser);
}
}
}
public User login(User authority) throws UserNotFoundException {
final String token = UUID.randomUUID().toString();
try {
authority.setToken(token);
this.repo.save(authority);
} catch (Exception e) {
throw new UserNotFoundException(e.getMessage());
}
return authority;
}
public User save(User user) {
return this.repo.save(user);
}
public User getUserByEmail(String email) throws UserNotFoundException {
return this.repo.getByAuthority(email.replace("\n", "").trim())
.orElseThrow(() -> new UserNotFoundException("Cannot find user with given authority"));
}
public Optional<User> getByToken(String token) {
return this.repo.getByToken(token);
}
public List<User> searchForStudents(String query) {
return this.repo.searchForUsers(query, UserRoles.STUDENT);
}
public Optional<User> getById(Long userId) {
return this.repo.findById(userId);
}
}

View File

@ -1,10 +0,0 @@
package com.plannaplan.statisticutils;
public class Statistics {
public Statistics() {
}
public void getAll() {
}
}

View File

@ -1,9 +0,0 @@
package com.plannaplan.transferutils;
public class TransferMatcher {
public TransferMatcher() {
}
public void findMatches() {
}
}

View File

@ -1,9 +0,0 @@
package com.plannaplan.transferutils;
public class TransfersExecuter {
public TransfersExecuter() {
}
public void execute() {
}
}

View File

@ -1,5 +0,0 @@
package com.plannaplan.types;
public enum ActionTypes {
ADD, DELETE, REPLACE
}

View File

@ -1,5 +0,0 @@
package com.plannaplan.types;
public enum AppStates {
STOPPED, RUNNING, PAUSED
}

View File

@ -1,5 +0,0 @@
package com.plannaplan.types;
public enum EventTypes {
DROPPED_OUT, TOUR_STARTED, TRANSFER_FOUND, TOUR_FINISHED, COURSES_ACCEPTED
}

View File

@ -1,5 +1,9 @@
package com.plannaplan.types;
/**
* GroupType contains types: LECTURE, CLASS
*/
public enum GroupType {
LECTURE, CLASS
}

View File

@ -1,5 +1,9 @@
package com.plannaplan.types;
/**
* UserRoles contains types: STUDENT, DEANERY, ADMIN, TEST_USER
*/
public enum UserRoles {
STUDENT, DEANERY, ADMIN
STUDENT, DEANERY, ADMIN, TEST_USER
}

View File

@ -1,5 +1,9 @@
package com.plannaplan.types;
/**
* WeekDay contains types: MONDAY(0), TUESDAY(1), WEDNESDAY(2), THURSDAY(3), FRIDAY(4), SATURDAY(5), SUNDAY(6).
*/
public enum WeekDay {
MONDAY(0), TUESDAY(1), WEDNESDAY(2), THURSDAY(3), FRIDAY(4), SATURDAY(5), SUNDAY(6);

View File

@ -0,0 +1,8 @@
package com.plannaplan;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class TestApplication {
public final static String TEST_CONFIG_FILE = "Zajecia.xlsx";
}

View File

@ -11,9 +11,9 @@ import org.junit.Test;
public class FileReaderTest {
@Test
public void shoulReturnNull() {
InputStream inputStream = getClass().getClassLoader().getResourceAsStream("Zajecia.xlsx");
FileReader r = new FileReader(inputStream);
FileData d = r.read();
final InputStream inputStream = getClass().getClassLoader().getResourceAsStream("Zajecia.xlsx");
final FileReader r = new FileReader(inputStream);
final FileData d = r.read();
assertTrue(d.getRows().next().getCell(0).toString().equals("1.0"));
assertTrue(d.getKeys().size() == 22);
assertTrue(d != null);

View File

@ -1,19 +1,49 @@
package com.plannaplan.configutils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.Assert.assertTrue;
import java.io.InputStream;
import com.plannaplan.models.FileData;
import com.plannaplan.TestApplication;
import com.plannaplan.services.CourseService;
import com.plannaplan.services.GroupService;
import com.plannaplan.services.LecturerService;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(SpringRunner.class)
@SpringBootTest
@ContextConfiguration
public class FileToDatabaseMigratorTest {
@Autowired
private FileToDatabaseMigrator migrator;
@Autowired
private CourseService courseService;
@Autowired
private GroupService groupService;
@Autowired
private LecturerService lecturerService;
@Test
public void shouldInsertToDatabase() {
// FileToDatabaseMigrator migrator = new FileToDatabaseMigrator();
// InputStream inputStream =
// getClass().getClassLoader().getResourceAsStream("Zajecia.xlsx");
// FileReader r = new FileReader(inputStream);
// FileData d = r.read();
// migrator.migrate(d);
public void shouldImportDataFromFileToDatabase() throws Exception {
final InputStream inputStream = getClass().getClassLoader()
.getResourceAsStream(TestApplication.TEST_CONFIG_FILE);
final FileReader reader = new FileReader(inputStream);
this.migrator.migrate(reader.read());
int courses_ammount = this.courseService.getCoursesAmmount();
int groups_ammount = this.groupService.getGroupsAmmount();
int lecturers_ammount = this.lecturerService.getLecturersAmmount();
assertTrue(courses_ammount > 0 && groups_ammount > 0 && lecturers_ammount > 0);
}
}

View File

@ -0,0 +1,71 @@
package com.plannaplan.entities;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.lang.reflect.Field;
import java.sql.Timestamp;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
public class UserTest {
@Test
public void shouldResturnTokenIsNotExpired() {
final User user = new User();
user.setToken("testowy-bezpieczny-token");
assertTrue(user.isCredentialsNonExpired(), "Credential shouldnt expire yet");
long minutes = this.getMinutesDiff(user.getTokenUsageDate());
assertTrue(minutes == 0, "Should update last token usage");
}
@Test
public void shouldResturnTokenIsNotExpiredWithLessThan15minutes()
throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
final User user = new User();
user.setToken("testowy-bezpieczny-token");
this.setLastTokenUsage(user, new Timestamp(System.currentTimeMillis() - (6 * 60 * 1000)));
assertTrue(user.isCredentialsNonExpired(), "Credential shouldnt expire yet");
final long minutes = this.getMinutesDiff(user.getTokenUsageDate());
assertTrue(minutes == 0, "Should update last token usage");
}
@Test
public void shouldResturnTokenIsExpired()
throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
final User user = new User();
user.setToken("testowy-bezpieczny-token");
this.setLastTokenUsage(user, new Timestamp(System.currentTimeMillis() - (25 * 60 * 1000)));
assertFalse(user.isCredentialsNonExpired(), "Credential should expire");
final long diffInMilliseconds = Math
.abs(user.getTokenUsageDate().getTime() - new Timestamp(System.currentTimeMillis()).getTime());
final long minutes = TimeUnit.MILLISECONDS.toMinutes(diffInMilliseconds);
assertTrue(minutes > 0, "Shouldn't update last token usage");
}
private long getMinutesDiff(Timestamp timestamp) {
final long diffInMilliseconds = Math
.abs(timestamp.getTime() - new Timestamp(System.currentTimeMillis()).getTime());
final long minutes = TimeUnit.MILLISECONDS.toMinutes(diffInMilliseconds);
return minutes;
}
private void setLastTokenUsage(User user, Timestamp timestampToSet)
throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException {
Field reader = User.class.getDeclaredField("tokenUsageDate");
reader.setAccessible(true);
reader.set(user, timestampToSet);
}
}

View File

@ -0,0 +1,106 @@
package com.plannaplan.repositories;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.Assert.assertTrue;
import java.util.List;
import com.plannaplan.entities.Assignment;
import com.plannaplan.entities.Commision;
import com.plannaplan.entities.Groups;
import com.plannaplan.entities.User;
import com.plannaplan.services.AssignmentService;
import com.plannaplan.services.CommisionService;
import com.plannaplan.services.GroupService;
import com.plannaplan.services.UserService;
import com.plannaplan.types.UserRoles;
import com.plannaplan.types.WeekDay;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(SpringRunner.class)
@SpringBootTest
@ContextConfiguration
public class GroupRepositoryTest {
@Autowired
private GroupRepository repository;
@Autowired
private AssignmentService assignmentService;
@Autowired
private GroupService groupService;
@Autowired
private UserService userService;
@Autowired
private CommisionService commisionService;
@Test
public void shouldReturnGroupAssignmentTimes() throws InterruptedException {
final Groups testGroup = groupService.save(new Groups(43, "A-41", null, 235, WeekDay.MONDAY, null));
int startGroupAmmount = this.repository.getAssignedAmount(testGroup.getId()).orElse(Integer.valueOf(0))
.intValue();
final User user = this.userService.save(new User("Luis", "Vita",
"shouldReturnGroupAssignmentTimes@grouprepository.test", UserRoles.STUDENT));
final Commision commision = this.commisionService.save(new Commision(user));
this.assignmentService.save(new Assignment(testGroup, commision));
Thread.sleep(1000);
int afterAssignedGroupAmmount = this.repository.getAssignedAmount(testGroup.getId())
.orElse(Integer.valueOf(0)).intValue();
assertTrue(afterAssignedGroupAmmount > startGroupAmmount);
final Commision recommision = this.commisionService.save(new Commision(user));
this.assignmentService.save(new Assignment(testGroup, recommision));
Thread.sleep(1000);
int afterreAssignedGroupAmmount = this.repository.getAssignedAmount(testGroup.getId())
.orElse(Integer.valueOf(0)).intValue();
assertTrue(afterAssignedGroupAmmount == afterreAssignedGroupAmmount);
this.commisionService.save(new Commision(user));
Thread.sleep(1000);
int afterdeAssignedGroupAmmount = this.repository.getAssignedAmount(testGroup.getId())
.orElse(Integer.valueOf(0)).intValue();
assertTrue(afterdeAssignedGroupAmmount < afterreAssignedGroupAmmount);
}
@Test
public void shouldReturnGroupAssignmentTimesList() throws InterruptedException {
final Groups testGroup = groupService.save(new Groups(43, "A-41", null, 645, WeekDay.MONDAY, null));
final Groups testGroup2 = groupService.save(new Groups(433, "A-41", null, 235, WeekDay.TUESDAY, null));
final Groups testGroup3 = groupService.save(new Groups(23, "A-41", null, 340, WeekDay.MONDAY, null));
final User user = this.userService.save(new User("Dare", "Oc",
"shouldReturnGroupAssignmentTimesList@grouprepository.test", UserRoles.STUDENT));
final Commision commision = this.commisionService.save(new Commision(user));
this.assignmentService.save(new Assignment(testGroup, commision));
this.assignmentService.save(new Assignment(testGroup2, commision));
this.assignmentService.save(new Assignment(testGroup3, commision));
Thread.sleep(1000);
List<Object[]> response = this.repository
.getAssignedAmounts(List.of(testGroup.getId(), testGroup2.getId(), testGroup3.getId()));
assertTrue("Response should have size 3", response.size() == 3);
assertTrue("Instance of firest element should be Group", response.get(0)[0] instanceof Groups);
assertTrue("Instance of firest element should be Long", response.get(0)[1] instanceof Long);
}
}

View File

@ -0,0 +1,64 @@
package com.plannaplan.services;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.Assert.assertTrue;
import java.util.List;
import com.plannaplan.entities.Assignment;
import com.plannaplan.entities.Commision;
import com.plannaplan.entities.User;
import com.plannaplan.types.UserRoles;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(SpringRunner.class)
@SpringBootTest
@ContextConfiguration
public class AssignmentServiceTest {
@Autowired
private AssignmentService service;
@Autowired
private CommisionService comServie;
@Autowired
private UserService userService;
@Test
public void shouldSaveAssignment() {
final User user = new User("Gibi", "Kovalsky", "shouldSaveAssignment@assignmentservice.test",
UserRoles.STUDENT);
this.userService.save(user);
long beginState = this.service.getAssignmentsAmmount();
Commision com = new Commision(user);
this.comServie.save(com);
this.addAssignmentToCommision(com);
assertTrue("Assign ammount should increase", this.service.getAssignmentsAmmount() > beginState);
}
@Test
public void shouldGetCommisionAssignments() {
final User user = new User("Gibi", "Kovalsky", "shouldGetCommisionAssignments@assignmentservice.test",
UserRoles.STUDENT);
this.userService.save(user);
Commision com = new Commision(user);
this.comServie.save(com);
this.addAssignmentToCommision(com);
final List<Assignment> response = this.service.getCommisionAssignments(com);
assertTrue("Returned list size should be 1", response.size() == 1);
}
private void addAssignmentToCommision(Commision com) {
Assignment a = new Assignment(null, com);
this.service.save(a);
}
}

View File

@ -0,0 +1,94 @@
package com.plannaplan.services;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.Assert.assertTrue;
import com.plannaplan.entities.Assignment;
import com.plannaplan.entities.Commision;
import com.plannaplan.entities.User;
import com.plannaplan.types.UserRoles;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(SpringRunner.class)
@SpringBootTest
@ContextConfiguration
public class CommisionServiceTest {
@Autowired
private CommisionService service;
@Autowired
private UserService userService;
@Autowired
private AssignmentService assignmentService;
@Test
public void shouldSaveCommision() {
User usr = new User();
this.userService.save(usr);
long beginState = this.service.getCommisionsAmmount();
this.service.save(new Commision(usr));
assertTrue("Commision ammount should have changed", this.service.getCommisionsAmmount() > beginState);
}
@Test
public void shouldGetUserCommisions() {
User usr = new User();
this.userService.save(usr);
this.service.save(new Commision(usr));
assertTrue("User should have one commision", this.service.getUsersCommisions(usr).size() == 1);
}
@Test
public void shouldGetNewestCommision() throws NullPointerException, InterruptedException {
User usr = new User();
this.userService.save(usr);
this.service.save(new Commision(usr));
Thread.sleep(2000);
final Commision newestCommision = new Commision(usr);
this.service.save(newestCommision);
final Commision result = this.service.getNewestCommision(usr)
.orElseThrow(() -> new NullPointerException("There was no commision"));
assertTrue("Wrong commision was returned", result.getId().equals(newestCommision.getId()));
}
@Test
public void shouldMarkAssignmentsOfPreviousCommisionPast() {
final User usr = new User("Trevor", "Hammolt",
"shouldMarkAssignmentsOfPreviousCommisionPast@commisionservice.test", UserRoles.STUDENT);
this.userService.save(usr);
final Commision firstCommision = new Commision(usr);
this.service.save(firstCommision);
Assignment firstCommisionAssignment = this.assignmentService.save(new Assignment(null, firstCommision));
assertTrue("FirstCommisionAssignment should be flaged as present assignment",
!firstCommisionAssignment.isPastAssignment());
final Commision secondCommision = new Commision(usr);
this.service.save(secondCommision);
Assignment secondCommisionAssignment = new Assignment(null, secondCommision);
this.assignmentService.save(secondCommisionAssignment);
assertTrue("SecondCommisionAssignment should be flaged as present assignment",
!secondCommisionAssignment.isPastAssignment());
assertTrue("FirstCommisionAssignment should be flaged as past assignment",
this.assignmentService.getById(firstCommisionAssignment.getId()).get().isPastAssignment());
}
}

View File

@ -0,0 +1,49 @@
package com.plannaplan.services;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.Assert.assertTrue;
import java.io.InputStream;
import com.plannaplan.TestApplication;
import com.plannaplan.models.ConfigData;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(SpringRunner.class)
@SpringBootTest
@ContextConfiguration
public class ConfiguratorServiceTest {
@Autowired
private ConfiguratorService configuratorService;
@Autowired
private CourseService courseService;
@Autowired
private GroupService groupService;
@Autowired
private LecturerService lecturerService;
@Test
public void shouldImportDataToDataBase() {
final InputStream inputStream = getClass().getClassLoader()
.getResourceAsStream(TestApplication.TEST_CONFIG_FILE);
final ConfigData data = new ConfigData(null, null, inputStream);
this.configuratorService.config(data);
int courses_ammount = this.courseService.getCoursesAmmount();
int groups_ammount = this.groupService.getGroupsAmmount();
int lecturers_ammount = this.lecturerService.getLecturersAmmount();
assertTrue(courses_ammount > 0 && groups_ammount > 0 && lecturers_ammount > 0);
}
}

View File

@ -0,0 +1,32 @@
package com.plannaplan.services;
import static org.junit.Assert.assertTrue;
import com.plannaplan.entities.Course;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
@ContextConfiguration
public class CourseServiceTest {
@Autowired
private CourseService courseService;
@Test
public void createAndDeleteCourse() {
Course course = new Course("Testowy kurs", "TK");
int startAmmount = this.courseService.getCoursesAmmount();
courseService.save(course);
assertTrue(this.courseService.getCoursesAmmount() > startAmmount);
courseService.delete(course);
assertTrue(this.courseService.getCoursesAmmount() == startAmmount);
}
}

View File

@ -0,0 +1,71 @@
package com.plannaplan.services;
import static org.junit.Assert.assertTrue;
import java.util.HashMap;
import java.util.List;
import com.plannaplan.entities.Assignment;
import com.plannaplan.entities.Commision;
import com.plannaplan.entities.Groups;
import com.plannaplan.entities.User;
import com.plannaplan.types.UserRoles;
import com.plannaplan.types.WeekDay;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
@ContextConfiguration
public class GroupServiceTest {
@Autowired
private GroupService groupService;
@Autowired
private AssignmentService assignmentService;
@Autowired
private CommisionService commisionService;
@Autowired
private UserService userService;
@Test
public void createAndDeleteGroup() {
int startAmmount = this.groupService.getGroupsAmmount();
Groups group = new Groups();
group.setRoom("A1");
groupService.save(group);
assertTrue(this.groupService.getGroupsAmmount() > startAmmount);
groupService.delete(group);
assertTrue(this.groupService.getGroupsAmmount() == startAmmount);
}
@Test
public void shouldGetGroupsAssignmentsAmmounts() throws InterruptedException {
final Groups testGroup = groupService.save(new Groups(43, "A-41", null, 645, WeekDay.MONDAY, null));
final Groups testGroup2 = groupService.save(new Groups(433, "A-41", null, 235, WeekDay.TUESDAY, null));
final Groups testGroup3 = groupService.save(new Groups(23, "A-41", null, 340, WeekDay.MONDAY, null));
final User user = this.userService.save(
new User("Dare", "Oc", "shouldReturnGroupAssignmentTimesList@grouprepository.test", UserRoles.STUDENT));
final Commision commision = this.commisionService.save(new Commision(user));
this.assignmentService.save(new Assignment(testGroup, commision));
this.assignmentService.save(new Assignment(testGroup2, commision));
this.assignmentService.save(new Assignment(testGroup3, commision));
Thread.sleep(1000);
HashMap<Long, Integer> response = this.groupService.getTakenPlaces(List.of(testGroup, testGroup2, testGroup3));
assertTrue(response.size() == 3);
assertTrue(response.get(testGroup.getId()) == 1);
assertTrue(response.get(testGroup2.getId()) == 1);
assertTrue(response.get(testGroup3.getId()) == 1);
}
}

View File

@ -0,0 +1,32 @@
package com.plannaplan.services;
import static org.junit.Assert.assertTrue;
import com.plannaplan.entities.Lecturer;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
@ContextConfiguration
public class LecturerServiceTest {
@Autowired
private LecturerService lecturerService;
@Test
public void createAndDeleteLecturer() {
int startAmmount = this.lecturerService.getLecturersAmmount();
Lecturer lecturer = new Lecturer("prof.", "Tomasz", "Kowalski");
lecturerService.save(lecturer);
assertTrue(this.lecturerService.getLecturersAmmount() > startAmmount);
lecturerService.delete(lecturer);
assertTrue(this.lecturerService.getLecturersAmmount() == startAmmount);
}
}

View File

@ -0,0 +1,103 @@
package com.plannaplan.services;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.List;
import com.plannaplan.entities.User;
import com.plannaplan.exceptions.UserNotFoundException;
import com.plannaplan.types.UserRoles;
import org.junit.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;
import org.junit.runner.RunWith;
@RunWith(SpringRunner.class)
@SpringBootTest
@ContextConfiguration
@TestMethodOrder(OrderAnnotation.class)
public class UserServiceTest {
private static String TEST_USER_MAIL = "noteexisitingmail@notexistingdomain.com";
private static String TEST_USER_NAME = "Tom";
private static String TEST_USER_SUERNAME = "Kovalsky";
@Autowired
private UserService userService;
@Test
public void shouldReturnToken() {
User testUser = this.userService
.save(new User(TEST_USER_NAME, TEST_USER_SUERNAME, TEST_USER_MAIL, UserRoles.TEST_USER));
try {
testUser = this.userService.login(testUser);
System.out.println("Returned token: " + testUser.getToken());
assertTrue(testUser.getToken() != null);
assertTrue(this.userService.getUserByEmail(TEST_USER_MAIL).getToken() != null);
} catch (UserNotFoundException e) {
e.printStackTrace();
assertTrue(false);
}
}
@Test
public void shouldFindStudents() {
this.userService.save(new User("Nemo", "TheFish", "Nemo@shouldFindStudents.test", UserRoles.STUDENT));
final List<User> response = this.userService.searchForStudents("Nemo");
assertTrue(response.size() >= 1);
assertTrue(containsName(response, "Nemo"));
}
@Test
public void shouldReturnAllStudents() {
final User veryWantedUser = new User("Xavier", "123", "Xavier@shouldReturnAllStudents.test", UserRoles.STUDENT);
final User littleLessWanted = new User("Ravier", "321", "Ravier@shouldReturnAllStudents.test",
UserRoles.STUDENT);
final User notWantadUser = new User("Fiona", "Raskolnikov", "Fiona@shouldReturnAllStudents.test",
UserRoles.DEANERY);
this.userService.save(veryWantedUser);
this.userService.save(littleLessWanted);
this.userService.save(notWantadUser);
final List<User> response = this.userService.searchForStudents("");
assertTrue(response.size() >= 2);
assertTrue(!containsName(response, notWantadUser.getName()));
assertTrue(containsName(response, littleLessWanted.getName()));
assertTrue(containsName(response, veryWantedUser.getName()));
}
@Test
public void shouldntFindStudents() {
this.userService.save(new User("Nadia", "Ladia", "Nadia@shouldntFindStudents.test", UserRoles.STUDENT));
final List<User> response = this.userService.searchForStudents(
"THISisIMPOIBLEQUEryThatShouldntReturnAnyPersonAtAllfnjiasdfjivlsdfnjgklsomerandomcharsjustinCaseXD");
assertTrue(response.size() == 0);
}
private boolean containsName(final List<User> list, final String name) {
return list.stream().map(User::getName).filter(name::equals).findFirst().isPresent();
}
@Test
public void shouldCreateUser() {
final User user = this.userService.checkForUser("shouldCreateUser@UserService.test", null);
assertTrue(user.getId() != null);
}
@Test
public void shouldReturnExistingUser() {
final String email = "shouldReturnExistingUser@UserService.test";
this.userService.save(new User("Tom", "Smieszne", email, UserRoles.TEST_USER));
final User user = this.userService.checkForUser(email, null);
assertTrue(user.getName() != "Tom");
}
}

0
buisnesslogic/src/test/resources/Zajecia.xlsx Normal file → Executable file
View File

View File

@ -6,5 +6,7 @@ spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.open-in-view=true
spring.jpa.hibernate.ddl-auto=create-drop
spring.jackson.serialization.fail-on-empty-beans=false
spring.main.allow-bean-definition-overriding=true
spring.jackson.default-property-inclusion = NON_NULL
server.port=1285

View File

@ -1,69 +0,0 @@
# Dokumetacja API
| Api | Zadania endpointa |
| ---------------------------------------------- | ---------------------------------------------------------- |
| [/config](#config) | Załadowanie konfiguracji startowej do aplikacji PlanNaPlan |
| [/getCoursesWithGroups](#getcourseswithgroups) | Zwrócenie wszytskich kursów razem z grupami |
| [/getCourseGroups](#getcoursegroups) | Zwrócenie grup dla danego kursu |
| [/getCourses](#getcourses) | Zwrócenie wszystkich kursów |
## config
Source code: [link](../restservice/src/main/java/com/plannaplan/controllers/ConfigController.java)
```
POST /config
```
#### Opis
Endpoint konfigurujacy caly system i importujacy dane do bazy.
#### Parametry
| Type | Name | Consumes | Opis | Type |
| ---- | ----------------------- | ------------------- | ------------------------------- | ---- |
| Body | **file** </br> required | multipart/form-data | Plik .xlsx z potrzebnymi danymi | file |
## getCoursesWithGroups
Source code: [link](../restservice/src/main/java/com/plannaplan/controllers/getCoursesWithGroups.java)
```
GET /getCoursesWithGroups
```
#### Opis
Zwraca wszystkie dostepne kursy wraz z listą grup.
## getCourseGroups
Source code: [link](../restservice/src/main/java/com/plannaplan/controllers/GroupController.java)
```
GET /getCourseGroups
```
#### Opis
Zwraca wszytskie grupy dla danego kursu.
#### Parametry
| Type | Name | Consumes | Opis | Type |
| ----------- | --------------------- | -------- | ----------------------------------------- | ---- |
| Query Param | **id** </br> required | - | id kursu dla ktorego chcemy zwrocic grupy | int |
| Query Param | **capacity** </br> | - | czy ma zwrocic pole pojemnosci grupy | bool |
## getCourses
Source code: [link](../restservice/src/main/java/com/plannaplan/controllers/CoursesController.java)
```
GET /getCourses
```
#### Opis
Zwraca wszystkie dostepne kursy.

42
gettoken.py Executable file
View File

@ -0,0 +1,42 @@
import webbrowser
from http.server import BaseHTTPRequestHandler, HTTPServer, SimpleHTTPRequestHandler
import urllib.parse as urlparse
from urllib.parse import parse_qs
import sys
import requests as r
if len(sys.argv) > 1 :
API_ADDRESS = "http://" + sys.argv[1] + ":1285"
else:
API_ADDRESS = "http://localhost:1285"
PORT = 3000
class S(BaseHTTPRequestHandler):
def _set_response(self):
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
def do_GET(self):
parsed = urlparse.urlparse(str(self.path))
ticket = str(parse_qs(parsed.query)['ticket'][0])
print(ticket)
response = r.get(API_ADDRESS + "/token?ticket=" + ticket)
self._set_response()
self.wfile.write("Your token: {}".format(
response.text).encode('utf-8'))
def wait_for_request(server_class=HTTPServer,
handler_class=S):
server_address = ('localhost', PORT)
httpd = server_class(server_address, handler_class)
return httpd.handle_request()
url = 'https://cas.amu.edu.pl/cas/login?service=http://localhost:' + \
str(PORT) + '&locale=pl'
webbrowser.open_new_tab(url)
wait_for_request()

0
init.sql Normal file → Executable file
View File

16
pom.xml Normal file → Executable file
View File

@ -2,11 +2,11 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.2.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>com.plannaplan</groupId>
<artifactId>backend</artifactId>
@ -19,8 +19,8 @@
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.source>14</maven.compiler.source>
<maven.compiler.target>14</maven.compiler.target>
</properties>
<dependencies>
@ -78,7 +78,7 @@
</plugins>
</pluginManagement>
</build>
<modules>
<modules>
<module>buisnesslogic</module>
<module>restservice</module>
</modules>

80
restservice/pom.xml Normal file → Executable file
View File

@ -16,26 +16,78 @@
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<profiles>
<profile>
<id>dev</id>
<properties>
<activatedProperties>dev</activatedProperties>
</properties>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<profile>
<id>prod</id>
<properties>
<activatedProperties>prod</activatedProperties>
</properties>
</profile>
</profiles>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.source>14</maven.compiler.source>
<maven.compiler.target>14</maven.compiler.target>
<start-class>com.plannaplan.App</start-class>
<swagger.version>2.9.2</swagger.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.vavr</groupId>
<artifactId>vavr</artifactId>
<version>0.9.0</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.10</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.security/spring-security-test -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<version>5.3.4.RELEASE</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.jasig.cas.client/cas-client-core -->
<dependency>
<groupId>org.jasig.cas.client</groupId>
<artifactId>cas-client-core</artifactId>
<version>3.6.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
<version>2.3.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
@ -48,11 +100,33 @@
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.8.1</version>
</dependency>
<dependency>
<artifactId>buisnesslogic</artifactId>
<groupId>com.plannaplan</groupId>
<version>1.0-SNAPSHOT</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${swagger.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${swagger.version}</version>
</dependency>
</dependencies>
<build>

114
restservice/src/main/java/com/plannaplan/App.java Normal file → Executable file
View File

@ -1,15 +1,117 @@
package com.plannaplan;
import java.io.InputStream;
import com.plannaplan.models.ConfigData;
import com.plannaplan.entities.User;
import com.plannaplan.services.UserService;
import com.plannaplan.types.UserRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import com.plannaplan.services.ConfiguratorService;
@SpringBootApplication
public class App {
public static void main(String[] args) {
Logo logo = new Logo("beta");
System.out.println(logo.getLogo());
System.out.println("|=============================================================================================|");
SpringApplication.run(App.class, args);
}
public final static String API_VERSION = "v1";
@Autowired
private ConfiguratorService contrl;
@Autowired
UserService userService;
@Value("${plannaplan.dev}")
private boolean isDev;
public static void main(String[] args) {
Logo logo = new Logo("beta");
System.out.println(logo.getLogo());
System.out.println(
"|=============================================================================================|");
SpringApplication.run(App.class, args);
}
@EventListener(ApplicationReadyEvent.class)
public void importData() {
System.out.println(Logo.getInitInfo(isDev));
if (this.isDev) {
InputStream inputStream = getClass().getClassLoader().getResourceAsStream("Zajecia.xlsx");
ConfigData data = new ConfigData(null, null, inputStream);
this.contrl.config(data);
User newuser = new User();
newuser.setEmail("tommy@st.amu.edu.pl");
newuser.setName("Tomek");
newuser.setSurname("Atomek");
newuser.setRole(UserRoles.STUDENT);
this.userService.save(newuser);
newuser = new User();
newuser.setEmail("robercik@st.amu.edu.pl");
newuser.setName("Robert");
newuser.setSurname("Głowacki");
newuser.setRole(UserRoles.STUDENT);
this.userService.save(newuser);
newuser = new User();
newuser.setEmail("mewa@st.amu.edu.pl");
newuser.setName("Poznanska");
newuser.setSurname("Mewa");
newuser.setRole(UserRoles.STUDENT);
this.userService.save(newuser);
newuser = new User();
newuser.setEmail("tkul2@st.amu.edu.pl");
newuser.setName("Tomasz");
newuser.setSurname("Kula");
newuser.setRole(UserRoles.STUDENT);
this.userService.save(newuser);
newuser = new User();
newuser.setEmail("annana@st.amu.edu.pl");
newuser.setName("Anna");
newuser.setSurname("Na");
newuser.setRole(UserRoles.STUDENT);
this.userService.save(newuser);
newuser = new User();
newuser.setEmail("mnart@st.amu.edu.pl");
newuser.setName("Marta");
newuser.setSurname("Narta");
newuser.setRole(UserRoles.STUDENT);
this.userService.save(newuser);
newuser = new User();
newuser.setEmail("zmineniane@st.amu.edu.pl");
newuser.setName("Tutaj");
newuser.setSurname("Koncza");
newuser.setRole(UserRoles.STUDENT);
this.userService.save(newuser);
newuser = new User();
newuser.setEmail("mi@st.amu.edu.pl");
newuser.setName("Mi");
newuser.setSurname("Sie");
newuser.setRole(UserRoles.STUDENT);
this.userService.save(newuser);
newuser = new User();
newuser.setEmail("pms@st.amu.edu.pl");
newuser.setName("Pomysly");
newuser.setSurname("Sad");
newuser.setRole(UserRoles.STUDENT);
this.userService.save(newuser);
}
System.out.println(Logo.getStartedInfo(isDev));
}
}

26
restservice/src/main/java/com/plannaplan/Logo.java Normal file → Executable file
View File

@ -1,11 +1,14 @@
package com.plannaplan;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class Logo {
public static final String ANSI_RESET = "\u001B[0m";
public static final String ANSI_YELLOW = "\u001B[33m";
public static final String ANSI_BLUE = "\u001B[34m";
public static final String ANSI_BLACK = "\u001B[30m";
public static final String ANSI_BLACK = "\u001B[37m";
private String version;
public Logo(String version){
@ -30,4 +33,25 @@ public class Logo {
ANSI_RESET;
return result;
}
public static String getInitInfo(boolean isDev){
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
LocalDateTime now = LocalDateTime.now();
if(isDev){
return ANSI_BLACK + dtf.format(now) + ANSI_YELLOW + " plannaplan" + ANSI_RESET + " initializing [" +ANSI_BLUE + "dev" + ANSI_RESET +"]";
}
return ANSI_BLACK + dtf.format(now) + ANSI_YELLOW + " plannaplan" + ANSI_RESET + " initializing [" +ANSI_BLUE + "prod" + ANSI_RESET +"]";
}
public static String getStartedInfo(boolean isDev){
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
LocalDateTime now = LocalDateTime.now();
if(isDev){
return ANSI_BLACK + dtf.format(now) +ANSI_YELLOW + " plannaplan" + ANSI_RESET + " started [" +ANSI_BLUE + "dev" + ANSI_RESET +"]";
}
return ANSI_BLACK + dtf.format(now) + ANSI_YELLOW + " plannaplan" + ANSI_RESET + " started [" +ANSI_BLUE + "prod" + ANSI_RESET +"]";
}
}

View File

@ -0,0 +1,50 @@
package com.plannaplan;
import java.util.Collections;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import springfox.documentation.service.Parameter;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class Swagger2Config extends WebMvcConfigurationSupport {
@Bean
public Docket createRestApi() {
Parameter authHeader = new ParameterBuilder()
.parameterType("header")
.name("Authorization")
.modelRef(new ModelRef("string"))
.build();
return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select()
.apis(RequestHandlerSelectors.basePackage("com.plannaplan")).paths(PathSelectors.any())
.build()
.globalOperationParameters(Collections.singletonList(authHeader));
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder().title("plannaplan").description("Aplikacja do zapisów na zajęcia UAM.")
.termsOfServiceUrl("https://plannaplan.pl/")
// .contact("")
.version("1.0").build();
}
}

View File

@ -0,0 +1,54 @@
package com.plannaplan.controllers;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import com.plannaplan.App;
import com.plannaplan.entities.Assignment;
import com.plannaplan.entities.Commision;
import com.plannaplan.entities.User;
import com.plannaplan.responses.mappers.AssignmentResponseMappers;
import com.plannaplan.responses.models.AssignmentResponse;
import com.plannaplan.services.AssignmentService;
import com.plannaplan.services.CommisionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
@RestController
@CrossOrigin
@RequestMapping("/api/" + App.API_VERSION + "/assignments")
@Api(tags = {
"Assignments" }, value = "Assignments", description = "Assignment is representation of student willing to join given group (lecture or calss)")
public class AssignmentsController extends TokenBasedController {
@Autowired
private CommisionService commisionService;
@Autowired
private AssignmentService assignmentService;
@GetMapping("/user")
@ApiOperation(value = "Return user current assignemts (from newest commision). STUDENT Token needs to be provided.")
public ResponseEntity<List<AssignmentResponse>> getCurrentAssignments() throws Exception {
User user = this.getCurrentUser().orElseThrow(() -> new NullPointerException("User not found"));
Optional<Commision> com = this.commisionService.getNewestCommision(user);
if (com.isPresent()) {
List<Assignment> respone = this.assignmentService.getCommisionAssignments(com.get());
return new ResponseEntity<>(AssignmentResponseMappers.mapToResponse(respone), HttpStatus.OK);
}
return new ResponseEntity<>(new ArrayList<>(), HttpStatus.OK);
}
}

View File

@ -0,0 +1,117 @@
package com.plannaplan.controllers;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.PathVariable;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import java.util.List;
import java.util.Optional;
import com.plannaplan.App;
import com.plannaplan.entities.Assignment;
import com.plannaplan.entities.Commision;
import com.plannaplan.entities.Groups;
import com.plannaplan.entities.User;
import com.plannaplan.exceptions.UserNotFoundException;
import com.plannaplan.responses.mappers.CommisionResponseMappers;
import com.plannaplan.responses.models.CommisionResponse;
import com.plannaplan.services.AssignmentService;
import com.plannaplan.services.CommisionService;
import com.plannaplan.services.GroupService;
import com.plannaplan.types.UserRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestMapping;
@RestController
@CrossOrigin
@RequestMapping("/api/" + App.API_VERSION + "/commisions")
@Api(tags = { "Commisions" }, value = "Commisions", description = "Commision is representation of student selected assignments at time. All assignments are attached to some commision so we can see current assignments and also browse history of changes for given user")
public class CommisionController extends TokenBasedController {
@Autowired
private CommisionService commisionService;
@Autowired
private GroupService groupServcicxe;
@Autowired
private AssignmentService assignmentService;
public CommisionController() {
}
@PostMapping(value = { "/user", "/user/{id}" })
@ApiOperation(value = "Create commision with assignents to given groups. If group doesn't exist error will be thrown")
public ResponseEntity<String> addCommision(
@RequestBody @ApiParam(value = "List of groups ids user want to assign to. If group doesnt exisit error will be thrown") List<Long> groups,
@PathVariable(name = "id", required = false) Long userId) {
try {
final User asker = this.getCurrentUser()
.orElseThrow(() -> new UserNotFoundException("Invalid token"));
final User user = userId != null
? userService.getById(userId).orElseThrow(
() -> new UserNotFoundException("Given user id not exist"))
: asker;
Assert.isTrue((asker.getRole() == UserRoles.DEANERY && user.getRole() == UserRoles.STUDENT
|| (asker.getId().equals(user.getId()) && user.getRole() == UserRoles.STUDENT)),
"Incorrect attempt to change plan");
Optional<Long> notExistingGroup = this.groupServcicxe.findNotExistingGroup(groups);
Assert.isTrue(!notExistingGroup.isPresent(), "Group "
+ notExistingGroup.orElse(Long.MIN_VALUE).toString() + "doesn't exist");
final Commision com = new Commision(user);
this.commisionService.save(com);
groups.stream().forEach((groupId) -> {
Groups group = this.groupServcicxe.getGroupById(groupId)
.orElseThrow(() -> new NullPointerException());
Assignment a = new Assignment(group, com);
this.assignmentService.save(a);
});
return new ResponseEntity<>("Succes", HttpStatus.OK);
} catch (UserNotFoundException exception) {
return new ResponseEntity<>(exception.getMessage(), HttpStatus.NOT_FOUND);
} catch (IllegalArgumentException exception) {
return new ResponseEntity<>(exception.getMessage(), HttpStatus.BAD_REQUEST);
}
}
@GetMapping("/user")
@ApiOperation("Return list of user all commisions (history of schedules)")
public ResponseEntity<List<CommisionResponse>> getAlCommisions() throws UserNotFoundException {
User user = this.getCurrentUser().orElseThrow(() -> new NullPointerException());
List<CommisionResponse> result = CommisionResponseMappers
.mapToResponse(this.commisionService.getUsersCommisions(user));
return new ResponseEntity<>(result, HttpStatus.OK);
}
@PreAuthorize("hasRole('ROLE_DEANERY')")
@GetMapping("/user/{id}")
@ApiOperation("Return list of commisions for given user. To be able to access this data u need to provide DEANERY token")
public ResponseEntity<List<CommisionResponse>> getCommision(@PathVariable(name = "id") Long userId)
throws UserNotFoundException {
User user = this.userService.getById(userId).orElseThrow(() -> new NullPointerException());
List<CommisionResponse> result = CommisionResponseMappers
.mapToResponse(this.commisionService.getUsersCommisions(user));
return new ResponseEntity<>(result, HttpStatus.OK);
}
}

View File

@ -5,27 +5,41 @@ import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
import com.plannaplan.Controller;
import com.plannaplan.App;
import com.plannaplan.models.ConfigData;
import com.plannaplan.services.ConfiguratorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
@RestController
@CrossOrigin
@RequestMapping("/api/" + App.API_VERSION + "/configurator")
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Api(tags = { "ConfigController" }, value = "ConfigController", description = "All endpoints to configure an app")
public class ConfigController {
@Autowired
private Controller contrl;
private ConfiguratorService contrl;
@PostMapping("/config")
public ResponseEntity<String> configApp(@RequestParam("file") MultipartFile file) {
@PreAuthorize("hasRole('ROLE_ADMIN')")
@ApiOperation("Imports data to system. To call you need to provide ADMIN token")
public ResponseEntity<String> configApp(
@RequestParam("file") @ApiParam(value = "file .xlsx that contains courses and groups with apoinnted rules") MultipartFile file) {
try {
ConfigData data = new ConfigData(null, null, file.getInputStream());
final ConfigData data = new ConfigData(null, null, file.getInputStream());
this.contrl.config(data);
return new ResponseEntity<>("Sucess", HttpStatus.OK);
} catch (IOException e) {

View File

@ -1,66 +1,82 @@
package com.plannaplan.controllers;
import java.util.ArrayList;
import java.util.Dictionary;
import java.util.Hashtable;
import java.util.HashMap;
import java.util.List;
import com.plannaplan.App;
import com.plannaplan.entities.Course;
import com.plannaplan.entities.Groups;
import com.plannaplan.responses.mappers.CoursesResponseMappers;
import com.plannaplan.responses.models.CoursesDefaultResponse;
import com.plannaplan.responses.models.CoursesWithGroupsResponse;
import com.plannaplan.responses.models.GroupDefaultResponse;
import com.plannaplan.services.CourseService;
import com.plannaplan.services.GroupService;
import com.plannaplan.types.GroupType;
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.RestController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.plannaplan.responses.models.abstracts.CoursesResponse;
@RestController
@CrossOrigin
@RequestMapping("/api/" + App.API_VERSION + "/courses")
@Api(tags = {
"Course" }, value = "Course", description = "Endpoints to deal with courses. All courses can have classes, lectures or both.")
public class CoursesController {
@Autowired
private CourseService courseService;
@GetMapping("/getCourses")
public ResponseEntity<List<Dictionary<String,Object>>> getMethodName() {
List<Course> courses = this.courseService.getAllCourses();
List<Dictionary<String,Object>> response = new ArrayList<>();
for(Course c : courses){
Dictionary<String, Object> element = new Hashtable<>();
element.put("id", c.getId());
element.put("name",c.getName());
response.add(element);
}
return new ResponseEntity<>(response, HttpStatus.OK);
}
@Autowired
private GroupService groupService;
@GetMapping("/getCoursesWithGroups")
public ResponseEntity<List<Dictionary<String,Object>>> getCoursesWithGroups() {
@GetMapping("/all")
@ApiOperation(value = "Return all courses")
public ResponseEntity<List<? extends CoursesResponse>> getMethodName(
@RequestParam(name = "groups", defaultValue = "false") @ApiParam(value = "Boolean if you want to have resopnse with associated groups or without") Boolean groups,
@RequestParam(name = "takenPlaces", defaultValue = "false") @ApiParam(value = "Boolean if we want to have respoonse with information about taken places by other students. Needs to be set groups true first") Boolean takenPlaces) {
List<Course> courses = this.courseService.getAllCourses();
List<Dictionary<String,Object>> response = new ArrayList<>();
for(Course c : courses){
Dictionary<String, Object> element = new Hashtable<>();
element.put("id", c.getId());
element.put("name",c.getName());
List<Dictionary<String,Object>> groups = new ArrayList<>();
for(Groups g : c.getGroups()){
Dictionary<String,Object> group = new Hashtable<>();
group.put("id", g.getId());
group.put("day", g.getDay().label);
group.put("time", g.getTimeString());
group.put("lecturer", g.getLecturer().toString());
group.put("room", g.getRoom());
group.put("type", g.getType());
groups.add(group);
if (groups) {
if (takenPlaces) {
final List<CoursesWithGroupsResponse> response = new ArrayList<>();
courses.forEach(course -> {
final List<GroupDefaultResponse> lectures = new ArrayList<>();
final List<GroupDefaultResponse> classes = new ArrayList<>();
final HashMap<Long, Integer> ammounts = this.groupService.getTakenPlaces(course.getGroups());
course.getGroups().stream().forEach(group -> {
if (group.getType() == GroupType.CLASS) {
classes.add(new GroupDefaultResponse(group, ammounts.get(group.getId())));
} else {
lectures.add(new GroupDefaultResponse(group, ammounts.get(group.getId())));
}
});
response.add(new CoursesWithGroupsResponse(course, lectures, classes));
});
return new ResponseEntity<>(response, HttpStatus.OK);
}
element.put("groups", groups);
response.add(element);
final List<CoursesWithGroupsResponse> response = CoursesResponseMappers
.mapToGetCoursesWithGroupsResponse(courses);
return new ResponseEntity<>(response, HttpStatus.OK);
}
final List<CoursesDefaultResponse> response = CoursesResponseMappers.mapToGetCoursesResponse(courses);
return new ResponseEntity<>(response, HttpStatus.OK);
}
}

View File

@ -1,11 +1,13 @@
package com.plannaplan.controllers;
import java.util.ArrayList;
import java.util.Dictionary;
import java.util.Hashtable;
import java.util.HashMap;
import java.util.List;
import com.plannaplan.App;
import com.plannaplan.entities.Groups;
import com.plannaplan.responses.mappers.GroupsMappers;
import com.plannaplan.responses.models.GroupDefaultResponse;
import com.plannaplan.responses.models.CourseWithGroupsResponse;
import com.plannaplan.services.GroupService;
import org.springframework.beans.factory.annotation.Autowired;
@ -13,36 +15,46 @@ import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
@RestController
@CrossOrigin
@RequestMapping("/api/" + App.API_VERSION + "/groups")
@Api(tags = {
"Group" }, value = "Group", description = "Enpoints to deal with gorups. Group is related directly to course and can be either class and lecture")
public class GroupController {
@Autowired
private GroupService groupService;
@GetMapping("/getCourseGroups")
public ResponseEntity<List<Dictionary<String, Object>>> getCourses(@RequestParam("id") Long id, @RequestParam(name="capacity", defaultValue="true") Boolean capacity){
@GetMapping("/course/{id}")
@ApiOperation(value = "Return list of lectures and classes (if present) given course")
public ResponseEntity<CourseWithGroupsResponse<? extends GroupDefaultResponse>> getCourses(
@PathVariable(name = "id") Long id,
@RequestParam(name = "capacity", defaultValue = "true") @ApiParam(value = "Boolean if we want to have capacity field in response") Boolean capacity,
@RequestParam(name = "takenPlaces", defaultValue = "false") @ApiParam(value = "Boolean if we want to have respoonse with information about taken places by other students") Boolean takenPlaces) {
List<Groups> groups = this.groupService.getGroupsByCourse(id);
List<Dictionary<String, Object>> response = new ArrayList<>();
for (Groups g : groups) {
Dictionary<String, Object> group = new Hashtable<>();
group.put("id", g.getId());
group.put("day", g.getDay().label);
group.put("time", g.getTimeString());
group.put("lecturer", g.getLecturer().toString());
group.put("room", g.getRoom());
if (takenPlaces) {
HashMap<Long, Integer> ammounts = this.groupService.getTakenPlaces(groups);
if (capacity) {
group.put("capacity", g.getCapacity());
}
group.put("type", g.getType());
response.add(group);
return new ResponseEntity<>(GroupsMappers.mapToGetCourseGroupsWithCapacityResponse(groups, ammounts),
HttpStatus.OK);
}
return new ResponseEntity<>(GroupsMappers.mapToGetCourseGroupsDefaultResponse(groups, ammounts),
HttpStatus.OK);
}
return new ResponseEntity<>(response, HttpStatus.OK);
if (capacity) {
return new ResponseEntity<>(GroupsMappers.mapToGetCourseGroupsWithCapacityResponse(groups), HttpStatus.OK);
}
return new ResponseEntity<>(GroupsMappers.mapToGetCourseGroupsDefaultResponse(groups), HttpStatus.OK);
}
}

View File

@ -0,0 +1,30 @@
package com.plannaplan.controllers;
import java.util.Optional;
import com.plannaplan.entities.User;
import com.plannaplan.exceptions.UserNotFoundException;
import com.plannaplan.services.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
public abstract class TokenBasedController {
@Autowired
protected UserService userService;
public TokenBasedController() {
}
protected Optional<User> getCurrentUser() throws UserNotFoundException {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (!(authentication instanceof AnonymousAuthenticationToken)) {
return Optional.of(this.userService.getUserByEmail(authentication.getName()));
} else {
return Optional.empty();
}
}
}

View File

@ -0,0 +1,64 @@
package com.plannaplan.controllers;
import com.plannaplan.entities.User;
import com.plannaplan.exceptions.UserNotFoundException;
import com.plannaplan.responses.models.TokenResponse;
import com.plannaplan.security.cas.CasUserIdentity;
import com.plannaplan.security.cas.CasValidationExcepiton;
import com.plannaplan.security.cas.CasValidator;
import com.plannaplan.security.cas.CustomUAMCasValidator;
import com.plannaplan.security.cas.DefaultUAMCasValidator;
import com.plannaplan.services.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
@RestController
@CrossOrigin
@Api(tags = { "Token" }, value = "Token", description = "Enpoints to get authorization.")
public class TokenController {
@Value("${plannaplan.frontendUrl}")
private String serviceUrl;
@Value("${plannaplan.dev}")
private boolean isDev;
@Autowired
private UserService userService;
@GetMapping("/token")
@ApiOperation(value = "Endpoint to access token required to call secured endpoints. In order to access token we need to provide access token comming from unviersity CAS system")
public ResponseEntity<TokenResponse> getToken(
@RequestParam("ticket") @ApiParam(value = "Ticket get from CAS system. It should look like ST-1376572-wo41gty5R0JCZFKMMie2-cas.amu.edu.psl") final String ticket) {
final CasValidator validator = isDev ? new DefaultUAMCasValidator(serviceUrl, ticket)
: new CustomUAMCasValidator(serviceUrl, ticket);
try {
final CasUserIdentity casUserIdentity = validator.validate();
final String usosId = casUserIdentity.getUsosId();
final String authority = casUserIdentity.getEmail();
User user = this.userService.checkForUser(authority, usosId);
user = this.userService.login(user);
return new ResponseEntity<>(new TokenResponse(user), HttpStatus.OK);
} catch (CasValidationExcepiton e) {
return new ResponseEntity<>(null, HttpStatus.UNAUTHORIZED);
} catch (UserNotFoundException e) {
return new ResponseEntity<>(null, HttpStatus.NOT_FOUND);
} catch (Exception e) {
return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}

View File

@ -0,0 +1,54 @@
package com.plannaplan.controllers;
import java.util.List;
import com.plannaplan.App;
import com.plannaplan.entities.User;
import com.plannaplan.responses.mappers.UserResponseMappers;
import com.plannaplan.responses.models.UserResponse;
import com.plannaplan.services.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RestController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
@RestController
@CrossOrigin
@RequestMapping("/api/" + App.API_VERSION + "/users")
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Api(tags = { "Users" }, value = "Users", description = "Endpoints to deal with users.")
public class UsersController {
@Autowired
private UserService userService;
@GetMapping("/student/search")
@PreAuthorize("hasRole('ROLE_DEANERY')")
@ApiOperation(value = "Serch for user by providing query. If query is empty it will return all students. You need token with DEANERY role to call this")
public ResponseEntity<List<UserResponse>> searchForStudent(
@RequestParam("query") @ApiParam(value = "Query to filter all students. If empty will match everyone") String query) {
final List<User> searches = this.userService.searchForStudents(query);
final List<UserResponse> response = UserResponseMappers.mapToDefaultResponse(searches);
return new ResponseEntity<>(response, HttpStatus.OK);
}
@GetMapping("/students")
@PreAuthorize("hasRole('ROLE_DEANERY')")
@ApiOperation(value = "Gets all students. You need token with DEANERY role to call this")
public ResponseEntity<List<UserResponse>> getAllStudents() {
final List<User> searches = this.userService.searchForStudents("");
final List<UserResponse> response = UserResponseMappers.mapToDefaultResponse(searches);
return new ResponseEntity<>(response, HttpStatus.OK);
}
}

View File

@ -0,0 +1,45 @@
package com.plannaplan.responses.mappers;
import java.util.List;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import com.plannaplan.entities.Assignment;
import com.plannaplan.entities.Course;
import com.plannaplan.entities.Groups;
import com.plannaplan.responses.models.AssignmentResponse;
import com.plannaplan.types.GroupType;
public class AssignmentResponseMappers {
public static final List<AssignmentResponse> mapToResponse(List<Assignment> assignments) {
List<AssignmentResponse> response = new ArrayList<>();
HashMap<Course, List<Groups>> courses = new HashMap<>();
assignments.stream().forEach((Assignment assignment) -> {
final Groups group = assignment.getGroup();
final Course course = group.getCourseId();
if (courses.get(course) == null) {
courses.put(course, new ArrayList<>());
}
courses.get(course).add(group);
});
for (Map.Entry<Course, List<Groups>> entry : courses.entrySet()) {
final Course course = entry.getKey();
final List<Groups> courseGroups = entry.getValue();
if (courseGroups.size() == 1) {
response.add(new AssignmentResponse(course, courseGroups.get(0)));
}
if (courseGroups.size() == 2) {
final Groups lecture = courseGroups.stream().filter(o -> o.getType() == GroupType.LECTURE).findFirst()
.get();
final Groups classes = courseGroups.stream().filter(o -> o.getType() == GroupType.CLASS).findFirst()
.get();
response.add(new AssignmentResponse(course, lecture, classes));
}
}
return response;
}
}

View File

@ -0,0 +1,14 @@
package com.plannaplan.responses.mappers;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import com.plannaplan.entities.Commision;
import com.plannaplan.responses.models.CommisionResponse;
public class CommisionResponseMappers {
public static final List<CommisionResponse> mapToResponse(List<Commision> commisions) {
return commisions.stream().filter(Objects::nonNull).map(CommisionResponse::new).collect(Collectors.toList());
}
}

View File

@ -0,0 +1,20 @@
package com.plannaplan.responses.mappers;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import com.plannaplan.entities.Course;
import com.plannaplan.responses.models.CoursesDefaultResponse;
import com.plannaplan.responses.models.CoursesWithGroupsResponse;
public class CoursesResponseMappers {
public static final List<CoursesDefaultResponse> mapToGetCoursesResponse(List<Course> courses) {
return courses.stream().filter(Objects::nonNull).map(CoursesDefaultResponse::new).collect(Collectors.toList());
}
public static final List<CoursesWithGroupsResponse> mapToGetCoursesWithGroupsResponse(List<Course> courses) {
return courses.stream().filter(Objects::nonNull).map(CoursesWithGroupsResponse::new)
.collect(Collectors.toList());
}
}

View File

@ -0,0 +1,113 @@
package com.plannaplan.responses.mappers;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;
import com.plannaplan.entities.Groups;
import com.plannaplan.responses.models.GroupDefaultResponse;
import com.plannaplan.responses.models.CourseWithGroupsResponse;
import com.plannaplan.responses.models.GroupWithCapacityResponse;
import com.plannaplan.types.GroupType;
public class GroupsMappers {
public static List<GroupDefaultResponse> mapToDefaultResponse(List<Groups> groups, HashMap<Long, Integer> taken) {
return groups.stream().filter(Objects::nonNull).map(new Function<Groups, GroupDefaultResponse>() {
@Override
public GroupDefaultResponse apply(Groups p) {
if (taken != null) {
return new GroupDefaultResponse(p, taken.get(p.getId()));
} else {
return new GroupDefaultResponse(p);
}
}
}).collect(Collectors.toList());
}
public static List<GroupDefaultResponse> mapToDefaultResponse(List<Groups> groups) {
return GroupsMappers.mapToDefaultResponse(groups, null);
}
public static List<GroupWithCapacityResponse> mapToCapacityResponse(List<Groups> groups,
HashMap<Long, Integer> taken) {
return groups.stream().filter(Objects::nonNull).map(new Function<Groups, GroupWithCapacityResponse>() {
@Override
public GroupWithCapacityResponse apply(Groups p) {
if (taken != null) {
return new GroupWithCapacityResponse(p, taken.get(p.getId()));
} else {
return new GroupWithCapacityResponse(p);
}
}
}).collect(Collectors.toList());
}
public static List<GroupWithCapacityResponse> mapToCapacityResponse(List<Groups> groups) {
return GroupsMappers.mapToCapacityResponse(groups, null);
}
public static CourseWithGroupsResponse<GroupDefaultResponse> mapToGetCourseGroupsDefaultResponse(
List<Groups> groups, HashMap<Long, Integer> taken) {
List<GroupDefaultResponse> lectures = new ArrayList<>();
List<GroupDefaultResponse> classes = new ArrayList<>();
groups.stream().forEach(group -> {
if (group.getType() == GroupType.CLASS) {
if (taken != null) {
classes.add(new GroupDefaultResponse(group, taken.get(group.getId())));
} else {
classes.add(new GroupDefaultResponse(group));
}
} else {
if (taken != null) {
lectures.add(new GroupDefaultResponse(group, taken.get(group.getId())));
} else {
lectures.add(new GroupDefaultResponse(group));
}
}
});
return new CourseWithGroupsResponse<>(classes, lectures);
}
public static CourseWithGroupsResponse<GroupDefaultResponse> mapToGetCourseGroupsDefaultResponse(
List<Groups> groups) {
return GroupsMappers.mapToGetCourseGroupsDefaultResponse(groups, null);
}
public static CourseWithGroupsResponse<GroupWithCapacityResponse> mapToGetCourseGroupsWithCapacityResponse(
List<Groups> groups, HashMap<Long, Integer> taken) {
List<GroupWithCapacityResponse> lectures = new ArrayList<>();
List<GroupWithCapacityResponse> classes = new ArrayList<>();
groups.stream().forEach(group -> {
if (group.getType() == GroupType.CLASS) {
if (taken != null) {
classes.add(new GroupWithCapacityResponse(group, taken.get(group.getId())));
} else {
classes.add(new GroupWithCapacityResponse(group));
}
} else {
if (taken != null) {
lectures.add(new GroupWithCapacityResponse(group, taken.get(group.getId())));
} else {
lectures.add(new GroupWithCapacityResponse(group));
}
}
});
return new CourseWithGroupsResponse<>(classes, lectures);
}
public static CourseWithGroupsResponse<GroupWithCapacityResponse> mapToGetCourseGroupsWithCapacityResponse(
List<Groups> groups) {
return GroupsMappers.mapToGetCourseGroupsWithCapacityResponse(groups, null);
}
}

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