250 Commits

Author SHA1 Message Date
9c1a148e20 Merge pull request 'Nowa funkcjonalność: wymiana-przedmiotami' (#41) from wymiana-przedmiotami into master
Reviewed-on: http://git.plannaplan.pl/filipizydorczyk/backend/pulls/41
2021-01-13 17:00:48 +01:00
ab32ad8561 Added emial to exchanges 2021-01-13 16:52:18 +01:00
1506270dec Master mergerd 2021-01-13 15:53:29 +01:00
75a3bc46f2 Checkpoint: Added performExchange into cron
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2021-01-13 14:42:13 +01:00
986407b8f8 Checkpoint: Removed unused imports
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2021-01-13 14:29:01 +01:00
11469e9314 Checkpoint: ExchangeServiceTest
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2021-01-13 14:13:26 +01:00
d1641277ac Checkpoint: ExchangeServiceTest
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2021-01-13 13:30:46 +01:00
ed528ad9a0 Checkpoint: ExchangeServiceTest
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2021-01-13 12:23:00 +01:00
f9a27abb32 Checkpoint: Added mew test
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2021-01-12 18:39:22 +01:00
1e1160736d Checkpoint: Added ShouldPerformExchange
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2021-01-12 14:35:11 +01:00
bc8f7407fc Checkpoint: added performExchange 2021-01-12 14:10:48 +01:00
1c12a778af Checkpoint: Added ExchangeServiceTest
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2021-01-12 13:04:57 +01:00
3583d30b26 Checkpoint: Added test to ExchangeRepo
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2021-01-11 16:56:39 +01:00
76faedc40d Checkpoint: Added test to ExchangeRepo
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2021-01-11 16:21:25 +01:00
5e459ac429 Checkpoint: Added test to ExchangeRepo
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2021-01-11 16:20:59 +01:00
b18f9cd50e Checkpoint: adding docs
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2021-01-10 15:59:26 +01:00
6311ecee92 Checkpoint: removed unsed imports
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2021-01-10 14:37:03 +01:00
6fe72465b9 Checkpoint: All test good :3
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2021-01-10 14:24:39 +01:00
00f639ad55 Removed unused import
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2021-01-10 14:16:31 +01:00
81f870eaa1 Checkpoint: 15/1
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2021-01-10 14:15:58 +01:00
2e6f373997 Checkpoint: 5/11
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2021-01-10 12:45:51 +01:00
c7feb10997 Checkpoint: ownedGroups.contains(groupId) and tests
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2021-01-10 10:57:33 +01:00
b0a1d929e4 Fixed problem
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2021-01-09 17:35:53 +01:00
3335155cd8 Proba naprawienia]
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2021-01-09 17:05:00 +01:00
df90a57715 Proba naprawienia]
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2021-01-09 14:17:39 +01:00
2320d66a35 Proba naprawienia
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2021-01-09 14:00:29 +01:00
11d21be627 Proba naprawienia
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2021-01-09 13:11:10 +01:00
756e854f31 Proba naprawienia
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2021-01-08 16:33:02 +01:00
bbf14b0ff9 Proba naprawienia
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2021-01-08 16:26:47 +01:00
a25843ebfd Proba naprawienia
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2021-01-08 16:17:24 +01:00
149796c42a Proba naprawienia
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2021-01-08 16:03:35 +01:00
c6c67e7e29 Poprawki 2021-01-08 15:53:15 +01:00
ad0d9e40c1 Proba naprawienia
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2021-01-08 15:28:59 +01:00
1682448627 Proba naprawienia
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2021-01-08 15:19:45 +01:00
e24938dfce Checkpoint: return per ID works
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2021-01-07 17:02:12 +01:00
842e38898a Checkpoint: return all exchanges works
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2021-01-07 16:51:35 +01:00
56120c4724 Checkpoint: deleting is working
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2021-01-07 16:01:25 +01:00
c8c8b62263 gettoken.py, README.md - update
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2021-01-06 17:29:18 +01:00
ebacbe892d gettoken.py WORKING IN MY GENTOO
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2021-01-06 17:20:49 +01:00
90f154f23b Checkpoint: Added docs, improved ExchangeEntity 2021-01-06 17:12:20 +01:00
b633d2c2df Checkpoints: WORKS but not for all
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2021-01-06 16:50:08 +01:00
df7701ebc8 Checkpoints: Part 1 of Added docs
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2021-01-06 16:23:18 +01:00
f24e62a335 Checkpoint: works first try with endpoint
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2021-01-06 14:50:34 +01:00
3bcc35e75b Checkpoint: dziala sprawdzanie values in the exchanges/exchange
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2021-01-06 14:34:25 +01:00
6e65c26e3c Checkpoint: szkielet
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2021-01-06 13:40:04 +01:00
cfc1e3eba7 Added changes
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2021-01-06 12:41:49 +01:00
3b80a70921 Merge pull request 'Changing-file-xls' (#40) from Changing-file-xls into master
Reviewed-on: http://git.plannaplan.pl/filipizydorczyk/backend/pulls/40
2021-01-06 12:24:54 +01:00
5edec5aa71 Remove unused import
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2021-01-06 11:56:04 +01:00
5b0097e6c7 Added systemout
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2021-01-06 11:47:18 +01:00
fddd5b757d Changed tests
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2021-01-06 11:39:58 +01:00
7813f148eb Added new column type with reading it and write groupType into DB
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2021-01-06 11:39:42 +01:00
8c0b880412 Change update function and added new contrutor in the Groups 2021-01-06 11:39:02 +01:00
fe06243bda Added new enums and desription
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2021-01-06 11:38:16 +01:00
f9fc7fa7bd Added new data
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2021-01-06 11:36:29 +01:00
68dfd2473a Merge pull request 'accept-algorythm' (#39) from accept-algorythm into master
Reviewed-on: http://git.plannaplan.pl/filipizydorczyk/backend/pulls/39
2021-01-05 12:20:34 +01:00
ddabc1a0b9 Docs fixes 2021-01-05 11:50:25 +01:00
463af01dc6 Added tests 2021-01-05 11:44:54 +01:00
0b40d3729c 0 0 2021-01-05 11:14:29 +01:00
3485dff86f Added performing tours and docs 2021-01-05 11:14:10 +01:00
2141f35e3f Chcekpoint - needs docs cleaning and tests 2021-01-04 18:10:14 +01:00
a6e6618202 Added structare for tour endindgs 2021-01-03 18:06:25 +01:00
44f8c610d9 Tested in big data set 2021-01-03 17:57:32 +01:00
95cc34c676 Docs + email sending 2021-01-03 17:10:36 +01:00
61d035e342 Code cleaning 2021-01-03 16:30:15 +01:00
0f8b4eafb5 Checkpint - algorythm works 2021-01-03 16:21:06 +01:00
2c0008afe1 Checkpoint - added many to many user group relations and test cerating users and groups to accept test 2021-01-02 15:26:05 +01:00
4b096a50bf Added getting sorted students 2021-01-02 14:35:00 +01:00
ff9aa64470 Added accepted status to assignments 2021-01-02 14:01:50 +01:00
a41c6f2583 Added points ranking to entity 2021-01-02 13:45:03 +01:00
ef896e9c12 Added
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2021-01-02 13:16:43 +01:00
3bce1f91ec Merge pull request 'api-service' (#38) from api-service into master
Reviewed-on: http://git.plannaplan.pl/filipizydorczyk/backend/pulls/38
2020-12-31 14:33:50 +01:00
665807240f Adden user data completion and docs correction 2020-12-31 14:24:55 +01:00
cd0f4bccd9 Added api service 2020-12-31 13:45:07 +01:00
ccb0161609 Checkpoint 2020-12-29 19:01:09 +01:00
9f1e21a29f Merge pull request 'forntend-fixes' (#37) from forntend-fixes into master
Reviewed-on: http://git.plannaplan.pl/filipizydorczyk/backend/pulls/37
2020-12-29 16:41:04 +01:00
a0570a055f Schedule taken places 2020-12-29 16:36:12 +01:00
eecb1a6d36 Added capacioty to course/all 2020-12-29 15:32:09 +01:00
389e934035 changed pres 2020-12-27 14:15:52 +01:00
4cec07e369 Merge pull request 'admin-user' (#36) from admin-user into master
Reviewed-on: http://git.plannaplan.pl/filipizydorczyk/backend/pulls/36
2020-12-27 14:09:55 +01:00
817350e85e Added UserRepositoryTest and users/admin users/deanery
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2020-12-27 13:54:33 +01:00
da4e683248 Added new /config/tours, tests
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2020-12-26 15:33:17 +01:00
09cc994d92 Added new tests
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2020-12-26 14:31:09 +01:00
c3d78505c8 Added new test for new columns and update groups
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2020-12-26 14:18:47 +01:00
f51979484f Added new columns into a FileMigrator and etc
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2020-12-26 13:17:39 +01:00
038d0b95d2 Added ne xlsx file
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2020-12-26 13:01:19 +01:00
4758c505c4 Merge branch 'Dodanie-nowych-kolumn' into admin-user 2020-12-26 12:47:13 +01:00
7a62c8d7d8 Added ne xlsx file
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2020-12-26 12:22:00 +01:00
9e6ee6dbb3 Updated
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2020-12-26 12:09:55 +01:00
2ba4082373 Added tests
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2020-12-23 14:38:36 +01:00
2ec3699978 Added javadocs
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2020-12-23 14:26:29 +01:00
507d9fddc0 Method body ready
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2020-12-23 14:21:16 +01:00
e647698591 Fix problem with admin test - cleaning database
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2020-12-23 14:06:02 +01:00
da46582fc0 Added check for admin user and test it
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2020-12-23 13:48:26 +01:00
165dee5bd2 Updated gitlab-ci
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2020-12-23 12:56:37 +01:00
76cf5c8e96 Merge pull request 'refresh-token' (#35) from refresh-token into master
Accepted
Reviewed-on: http://git.plannaplan.pl/filipizydorczyk/backend/pulls/35
2020-12-23 12:41:03 +01:00
6eac8e6266 Added tests 2020-12-23 12:12:50 +01:00
61c5a43192 Added refresh token endpoint 2020-12-23 11:51:17 +01:00
7f630ccdac email date update 2020-12-21 17:58:11 +01:00
64447b61c8 email date update 2020-12-21 17:48:27 +01:00
7584f3600f email date update 2020-12-21 17:34:03 +01:00
e18f285dd6 Merge pull request 'email' (#34) from email into master
Reviewed-on: http://git.plannaplan.pl/filipizydorczyk/backend/pulls/34
2020-12-21 17:11:32 +01:00
28c09bea6e Added event service 2020-12-21 17:12:10 +01:00
a294ecac37 Servcice mail 2020-12-20 16:44:30 +01:00
0d6ad184bc Merge pull request 'timeto-owner' (#33) from timeto-owner into master
Reviewed-on: http://git.plannaplan.pl/filipizydorczyk/backend/pulls/33
2020-12-20 15:15:03 +01:00
dfae6d7c78 Added info about commiter to comision entity 2020-12-20 13:04:25 +01:00
c62674b9d8 Added time to in group resonse 2020-12-20 12:14:12 +01:00
8dc94f84c0 user response fix 2020-12-18 17:43:03 +01:00
48c23ad4f8 Merge pull request 'user-fix' (#32) from user-fix into master
Reviewed-on: http://git.plannaplan.pl/filipizydorczyk/backend/pulls/32
2020-12-18 17:28:02 +01:00
b93d44346c new endpoint testd 2020-12-18 17:23:41 +01:00
4a12dceab6 logs 2020-12-18 16:33:58 +01:00
ce0d63d7f9 Added docs 2020-12-18 15:52:05 +01:00
300130af7e Checnging endpoints added needs docs 2020-12-18 15:49:46 +01:00
5ef7c19ade user nules 2020-12-18 15:24:01 +01:00
ca440a3fd5 Merge pull request 'turs' (#31) from turs into master
Reviewed-on: http://git.plannaplan.pl/filipizydorczyk/backend/pulls/31
2020-12-14 15:50:35 +01:00
ffc4f4709b Merged with master 2020-12-12 15:38:47 +01:00
84d7ed8e65 Added method to getting app states 2020-12-12 15:33:00 +01:00
e02523b4f4 Added current config getter 2020-12-12 13:33:11 +01:00
5a1108e1bf Added getting newest config 2020-12-11 18:08:23 +01:00
15533525af Database timezone fixed 2020-12-11 16:18:43 +01:00
d2a679fb22 added dev conig 2020-12-11 15:27:38 +01:00
e9927f832d permission problems 2020-12-10 16:58:55 +01:00
98bbc1aac6 Merge pull request 'forntend-fixes' (#30) from forntend-fixes into master
Reviewed-on: http://git.plannaplan.pl/filipizydorczyk/backend/pulls/30
2020-12-10 16:55:20 +01:00
a6acab932c New endpints tests 2020-12-10 16:50:47 +01:00
831358128e endpointsd refactore 2020-12-10 16:35:23 +01:00
dfe534a835 endpointsd refactore 2020-12-10 16:34:42 +01:00
7c457ce232 Deanery response 2020-12-10 16:19:58 +01:00
f31a50aa06 Commision with grouos response 2020-12-10 16:13:03 +01:00
52abb281ff commision date fix 2020-12-10 15:17:13 +01:00
0b807e355c chckpoint: test to buisnesslogic/src/test/java/com/plannaplan/repositories/AppConfigRepositoryTest.java 2020-12-09 17:43:48 +01:00
062b02da6c user docs corrected 2020-12-09 16:57:49 +01:00
0cee454356 Added saving conifg to databse 2020-12-09 16:43:29 +01:00
f08e7cf1e5 Swagger doscs 2020-12-09 15:10:19 +01:00
7c0c22e790 Added required parameters to config 2020-12-09 15:02:06 +01:00
1cdb301adf Updated .git-ci
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2020-12-08 19:09:35 +01:00
c1dce7d3bb Merge pull request 'git-ci' (#29) from git-ci into master
Reviewed-on: http://git.plannaplan.pl/filipizydorczyk/backend/pulls/29
2020-12-08 19:01:57 +01:00
2921c98c35 Updated .git-ci
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2020-12-08 19:02:02 +01:00
181d93082c Updated .git-ci
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2020-12-08 18:42:18 +01:00
b495fd7f65 Updated .git-ci
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2020-12-08 18:41:08 +01:00
086e4be458 Updated .git-ci
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2020-12-08 18:37:02 +01:00
0c471162f2 Updated .git-ci
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2020-12-08 18:31:58 +01:00
9f3e41e601 Updated .git-ci
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2020-12-08 18:31:07 +01:00
d85cdb9b22 Added gitci
Signed-off-by: Marcin Woźniak <y0rune@aol.com>
2020-12-08 18:26:35 +01:00
b1091cd3bc Added tour data model 2020-12-08 18:16:17 +01:00
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
146 changed files with 6920 additions and 758 deletions

11
.gitignore vendored
View File

@ -29,3 +29,14 @@ build/
### VS Code ###
.vscode/
### Python ###
__pycache__
.pytest_cache
### Parser ###
parser/
envs.sh

42
.gitlab-ci.yml Executable file
View File

@ -0,0 +1,42 @@
stages:
- build
- deploy
build:
stage: build
image: maven
script:
- echo "Start building App"
- echo "spring.profiles.active=prod" > restservice/src/main/resources/application.properties
- mvn clean
- mvn install
- cd restservice
- mvn clean package spring-boot:repackage
- echo "Build successfully!"
artifacts:
expire_in: 1 hour
paths:
- restservice/target/
only:
- master
deploy_production:
stage: deploy
before_script:
- apt-get update
- apt-get --yes --force-yes install rsync
script:
- 'which ssh-agent || ( apt-get update -y && apt-get install openssh-client -y )'
- eval $(ssh-agent -s)
- ssh-add <(echo "$SSH_PRIVATE_KEY")
- mkdir -p ~/.ssh
- '[[ -f /.dockerenv ]] && echo -e "Host *\n\tStrictHostKeyChecking no\n\n" > ~/.ssh/config'
- echo "Deploying to server"
- ssh backend@wmi-backend-gc.plannaplan.pl -t "sudo systemctl stop plannaplan-backend"
- ssh backend@wmi-backend-gc.plannaplan.pl -t "rm -rf /opt/plannaplan-backend/backend.jar"
- rsync --progress restservice/target/*.jar backend@wmi-backend-gc.plannaplan.pl:/opt/plannaplan-backend/backend.jar
- sleep 5
- ssh backend@wmi-backend-gc.plannaplan.pl -t "sudo systemctl start plannaplan-backend"
- echo "Deployed"
only:
- master

117
README.md
View File

@ -1,44 +1,94 @@
## Start aplikacji
# Start aplikacji
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
```
## Packaging
# 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
```bash
python gettoken.py
```
Jeżeli chcesz używać skryptu zmiejaniąc gdzie znajduje się backend wpisz:
```bash
python gettoken.py 192.168.0.212
```
Jeżeli chcesz używać skryptu bez uruchamiania przeglądarki wpisz:
```bash
python gettoken.py no-browser
```
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
- `PLANNAPLAN_EMAIL_HOST` - host naszego dostawcy maila z którego będziemy wssyłać wiadomości
- `PLANNAPLAN_EMAIL_PORT` - port naszego dostawcy maila
- `PLANNAPLAN_EMAIL_USERNAME` - login naszego maila
- `PLANNAPLAN_EMAIL_PASSWORD` - hasło naszego maila
- `PLANNAPLAN_EMAIL` - nasz adres maila
- `PLANNAPLAN_CONSUMER_KEY` - nasz klucz do usos api
- `PLANNAPLAN_CONSUMER_SECRET` - secret naszego klucza
Należy też pamiętać, że zmienne `PLANNAPLAN_CONSUMER_KEY` oraz `PLANNAPLAN_CONSUMER_SECRET` są potrzebne również w profilu `dev` więc trzeba je dodać w celu tesotowania do zmiennych we własnym systemie
# Packaging
Zeby spakowac apke do `jara` wystarcza dwie komendy zaczynajac z glownego katalogu projektu
```
mvn clean
mvn install
cd restservice
mvn clean package spring-boot:repackage
mvn clean; mvn install; cd restservice; 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)
## Troubleshooting
# 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
@ -46,3 +96,28 @@ Spring chyba cacheuje jakies dane dotyczace polaczenia wiec jesli spring wywali
mvn clean
mvn install
```
Jeżeli używasz VSCode i testy, które wymagają podanych zmiennych środowiskowych (testy odpytywania usos api) trzeba podać te zmienne w pliku `.vscode/settings.json`
```json
{
"files.exclude": {
"**/.classpath": true,
"**/.project": true,
"**/.settings": true,
"**/.factorypath": true
},
"java.configuration.updateBuildConfiguration": "disabled",
"java.format.settings.url": "eclipse-formatter.xml",
"java.test.config": [
{
"name": "myConfiguration",
"workingDirectory": "${workspaceFolder}",
"env": {
"PLANNAPLAN_CONSUMER_KEY": "value",
"PLANNAPLAN_CONSUMER_SECRET": "value"
}
}
]
}
```

View File

@ -16,8 +16,8 @@
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.14</maven.compiler.source>
<maven.compiler.target>1.14</maven.compiler.target>
<maven.compiler.source>14</maven.compiler.source>
<maven.compiler.target>14</maven.compiler.target>
</properties>
<dependencies>
@ -68,6 +68,37 @@
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
<version>2.2.5.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.social/spring-social-core -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.12</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.github.scribejava</groupId>
<artifactId>scribejava-core</artifactId>
<version>8.1.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.8</version>
</dependency>
</dependencies>
<build>
@ -84,6 +115,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

@ -0,0 +1,24 @@
{
"properties": [
{
"name": "plannaplan.email",
"type": "java.lang.String",
"description": "Email from which app sends message"
},
{
"name": "plannaplan.apiurl",
"type": "java.lang.String",
"description": "Url to usos api endpoints"
},
{
"name": "plannaplan.apikey",
"type": "java.lang.String",
"description": "Api consumer key"
},
{
"name": "plannaplan.apisecret",
"type": "java.lang.String",
"description": "Api consumer secret"
}
]
}

View File

@ -0,0 +1,61 @@
package com.plannaplan.api;
import com.github.scribejava.core.builder.api.DefaultApi10a;
/**
* singleton class to sign usos api requests with oauth
*/
public class UsosOauth1Service extends DefaultApi10a {
private static final String AUTHORIZE_URL = "https://usosapidemo.amu.edu.pl/services/oauth/authorize";
private static final String REQUEST_TOKEN_URL = "https://usosapidemo.amu.edu.pl/services/oauth/request_token";
private final String scopesAsString;
protected UsosOauth1Service() {
scopesAsString = null;
}
protected UsosOauth1Service(String... scopes) {
final StringBuilder builder = new StringBuilder();
for (String scope : scopes) {
builder.append('+').append(scope);
}
scopesAsString = "?scope=" + builder.substring(1);
}
private static class InstanceHolder {
private static final UsosOauth1Service INSTANCE = new UsosOauth1Service();
}
public static UsosOauth1Service instance() {
return InstanceHolder.INSTANCE;
}
/**
* get instance withj scopes
*
* @param scopes to get instance with
* @return UsosOauth1Service instance
*/
public static UsosOauth1Service instance(String... scopes) {
return scopes == null || scopes.length == 0 ? instance() : new UsosOauth1Service(scopes);
}
@Override
public String getRequestTokenEndpoint() {
return scopesAsString == null ? REQUEST_TOKEN_URL : REQUEST_TOKEN_URL + scopesAsString;
}
@Override
public String getAccessTokenEndpoint() {
return "https://usosapidemo.amu.edu.pl/services/oauth/access_token";
}
@Override
protected String getAuthorizationBaseUrl() {
return AUTHORIZE_URL;
}
}

View File

@ -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;

View File

@ -8,12 +8,16 @@ 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.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 {
@ -28,6 +32,10 @@ public class FileToDatabaseMigrator {
private static final String GROUP_TIME_STRING = "godz_od";
private static final String ROOM_STRING = "sala";
private static final String CAPACITY_STRING = "Mc";
private static final String TYPE_GROUP= "typ";
private static final String ZAJ_CYK_ID = "zaj_cyk_id";
private static final String GR_NR = "gr_nr";
@Autowired
private LecturerService lecturerService;
@ -52,6 +60,10 @@ public class FileToDatabaseMigrator {
int timeIndex = data.getIndexOf(FileToDatabaseMigrator.GROUP_TIME_STRING);
int roomIndex = data.getIndexOf(FileToDatabaseMigrator.ROOM_STRING);
int capacityIndex = data.getIndexOf(FileToDatabaseMigrator.CAPACITY_STRING);
int typeGroupIndex = data.getIndexOf(FileToDatabaseMigrator.TYPE_GROUP);
int zajCykIdIndex = data.getIndexOf(FileToDatabaseMigrator.ZAJ_CYK_ID);
int grNrIndex = data.getIndexOf(FileToDatabaseMigrator.GR_NR);
while (rows.hasNext()) {
Row row = rows.next();
@ -64,11 +76,18 @@ public class FileToDatabaseMigrator {
String lecturerSurname = row.getCell(surnameIndex) != null ? row.getCell(surnameIndex).toString().trim()
: "";
int day = (int) Double.parseDouble(row.getCell(dayIndex).toString());
Integer zajCykId = row.getCell(zajCykIdIndex) != null ? (int) Double.parseDouble(row.getCell(zajCykIdIndex).toString().trim())
: null;
Integer grNr = row.getCell(grNrIndex) != null ? (int) Double.parseDouble(row.getCell(grNrIndex).toString().trim())
: null;
int day = row.getCell(dayIndex) != null ? (int) Double.parseDouble(row.getCell(dayIndex).toString()) : 0;
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());
GroupType typeGroup = GroupType.getType(row.getCell(typeGroupIndex).toString());
Course course = this.courseService.getCourseByName(courseName)
.orElseGet(() -> this.courseService.save(new Course(courseName, symbol)));
@ -77,8 +96,11 @@ public class FileToDatabaseMigrator {
.orElseGet(() -> this.lecturerService
.save(new Lecturer(lecturerTitle, lecturerName, lecturerSurname)));
this.groupService.find(time, capacity, room).orElseGet(
() -> this.groupService.save(new Groups(capacity, room, course, time, groupDay, lecturer)));
Groups group = this.groupService.find(zajCykId, grNr).orElseGet(
() -> new Groups(capacity, room, course, time, groupDay, lecturer, zajCykId, grNr, typeGroup));
group.update(capacity, room, course, time, null, groupDay, lecturer, typeGroup);
this.groupService.save(group);
}

View File

@ -0,0 +1,171 @@
package com.plannaplan.entities;
import java.sql.Date;
import java.sql.Timestamp;
import java.time.LocalDate;
import java.util.TimeZone;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import com.plannaplan.models.TourData;
import com.plannaplan.types.AppState;
import org.springframework.scheduling.support.CronTrigger;
/**
* entity that keeps app configurations
*/
@Entity
public class AppConfig {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private Date firstTourStart;
private Date firstTourEnd;
private Date secondTourStart;
private Date secondTourEnd;
private Timestamp configDate;
/**
* no parameter construcotor
*/
public AppConfig() {
}
/**
* constructor
*
* @param firstTour first TourData instacne
* @param scondTour second TourData instacne
*/
public AppConfig(TourData firstTour, TourData scondTour) {
this.firstTourStart = firstTour.getStart();
this.firstTourEnd = firstTour.getEnd();
this.secondTourStart = scondTour.getStart();
this.secondTourEnd = scondTour.getEnd();
this.configDate = new Timestamp(System.currentTimeMillis());
}
/**
*
* second tour end getter
*
* @return Date inforamtion when second tour ends
*/
public Date getSecondTourEnd() {
return secondTourEnd;
}
/**
* first second start getter
*
* @return Date inforamtion when second tour start
*/
public Date getSecondTourStart() {
return secondTourStart;
}
/**
* first tour end getter
*
* @return Date inforamtion when first tour end
*/
public Date getFirstTourEnd() {
return firstTourEnd;
}
/**
* first tour start getter
*
* @return Date inforamtion when first tour start
*/
public Date getFirstTourStart() {
return firstTourStart;
}
/**
* config date getter
*
* @return Timestamp when configuration took place
*/
public Timestamp getConfigDate() {
return configDate;
}
/**
* current state getter
*
* @return AppState of app at the moment of calling method
*/
public AppState getCurrentState() {
final Date now = new Date(System.currentTimeMillis());
if (this.secondTourEnd.before(now)) {
return AppState.NO_TOUR;
}
if (this.secondTourStart.before(now)) {
return AppState.SECOND_TOUR;
}
if (this.firstTourEnd.before(now)) {
return AppState.NO_TOUR;
}
if (this.firstTourStart.before(now)) {
return AppState.FIRST_TOUR;
}
return AppState.NO_TOUR;
}
/**
* get cron expression of first tour end
*
* @return spring cron expression
*/
public CronTrigger getFirstTourEndCron() {
return getCron(this.firstTourEnd);
}
/**
* get cron expression of second tour end
*
* @return spring cron expression
*/
public CronTrigger getSecondTourEndCron() {
return getCron(this.secondTourEnd);
}
/**
* get cron expression of first tour start
*
* @return spring cron expression
*/
public CronTrigger getFirstTourStartCron() {
return getCron(this.firstTourStart);
}
/**
* get cron expression of second tour start
*
* @return spring cron expression
*/
public CronTrigger getSecondTourStartCron() {
return getCron(this.secondTourStart);
}
/**
* create spring cron expression
*
* @param date date to create cron exp from
* @return spring cron expression. Remember that spring's cron deosn't contain
* year in it.
*/
private CronTrigger getCron(Date date) {
final LocalDate tourEnd = date.toLocalDate();
return new CronTrigger("0 0 0 " + tourEnd.getDayOfMonth() + " " + tourEnd.getMonthValue() + " ?",
TimeZone.getTimeZone(TimeZone.getDefault().getID()));
}
}

View File

@ -7,6 +7,12 @@ 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
@ -18,20 +24,87 @@ public class Assignment {
@ManyToOne
@JoinColumn(name = "commision_id")
private Commision commision;
private boolean isPastAssignment;
public Assignment(Groups group, Commision commision) {
/**
* 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;
}
/**
* If it returns trues it mesans u are assigned to group accepted by algorythm
*
* @return boolean isAccepted
*/
public boolean isAccepted() {
return this.group.getRegisteredStudents().contains(this.commision.getCommisionOwner());
}
/**
* Getter of commision
* @return Commision Commision of given assignments
*/
public Commision getCommision(){
return this.commision;
}
/**
* 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() {
}
public void setCommision(Commision commision) {
this.commision = commision;
}
/**
* 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 is assignment past or not
*/
public void setPastAssignment(boolean isPastAssignment) {
this.isPastAssignment = isPastAssignment;
}
}

View File

@ -4,6 +4,7 @@ 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;
@ -11,6 +12,10 @@ 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
@ -19,29 +24,82 @@ public class Commision {
@OneToOne
@JoinColumn(name = "owner_id")
private User commisionOwner;
@OneToOne
@JoinColumn(name = "commiter_id")
private User commisionCommiter;
private Timestamp commisionDate;
@OneToMany(mappedBy = "commision")
@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;
this.commisionCommiter = user;
}
/**
*
* @param user user whose shedule is being commited
* @param commiter user that commited new schedule
*/
public Commision(User user, User commiter) {
this(user);
this.commisionCommiter = commiter;
}
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;
}
/**
* @return User entity that created commision (can be owner or deanery user)
*/
public User getCommisionCommiter() {
if (commisionCommiter == null) {
return commisionOwner;
}
return commisionCommiter;
}
/**
* 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
@ -23,31 +27,61 @@ public class Course {
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;
}
/**
* getGroups
* @return groups return list groups
*/
public List<Groups> getGroups() {
return this.groups;
}

View File

@ -0,0 +1,102 @@
package com.plannaplan.entities;
import java.sql.Timestamp;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
/**
* Entity that keeps user exchange offer.
*/
@Entity
public class Exchange {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@OneToOne
@JoinColumn(name = "owned_id")
private Assignment ownedAssignment;
@OneToOne
@JoinColumn(name = "desired_id")
private Groups desiredAssignment;
private Long ownerId;
private Timestamp dateExchange;
public Exchange(){
}
/**
* @return Long ID of exchange trader
*/
public Long getOwnerId() {
return ownerId;
}
/**
* @param ownerId ID of exchange trader
*/
public void setOwnerId(Long ownerId) {
this.ownerId = ownerId;
}
public Timestamp getDataExchange() {
return this.dateExchange;
}
/**
*
* @param ownedAssignment Assignment which owner would like to trade
* @param desiredAssignment Groups instance that trader wants
*/
public Exchange(Assignment ownedAssignment, Groups desiredAssignment) {
this.ownedAssignment = ownedAssignment;
this.desiredAssignment = desiredAssignment;
this.ownerId = this.ownedAssignment != null ? this.ownedAssignment.getCommision().getCommisionOwner().getId() : null;
this.dateExchange = new Timestamp(System.currentTimeMillis());
}
/**
* @return Long ID in database
*/
public Long getId(){
return this.id;
}
/**
* @return Groups Target group
*/
public Groups getDesiredAssignment() {
return desiredAssignment;
}
/**
* @param desiredAssignment Target group
*/
public void setDesiredAssignment(Groups desiredAssignment) {
this.desiredAssignment = desiredAssignment;
}
/**
* @return Assignment Owned assignment
*/
public Assignment getOwnedAssignment() {
return ownedAssignment;
}
/**
* @param ownedAssignment Owned assignment
*/
public void setOwnedAssignment(Assignment ownedAssignment) {
this.ownedAssignment = ownedAssignment;
}
}

View File

@ -1,19 +1,29 @@
package com.plannaplan.entities;
import java.util.HashSet;
import java.util.Set;
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.ManyToMany;
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 {
private static final int DEFAULT_CLASS_TIME = 90;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@ -21,6 +31,7 @@ public class Groups {
@JoinColumn(name = "course_id")
private Course course;
private int time;
private int endTime;
private String room;
private int capacity;
private GroupType type;
@ -28,80 +39,351 @@ public class Groups {
@ManyToOne
@JoinColumn(name = "lecturer_id")
private Lecturer lecturer;
private Integer zajCykId;
private Integer grNr;
@ManyToMany(mappedBy = "studentRegisteredGrups", fetch = FetchType.EAGER)
private Set<User> registeredStudents;
public Set<User> getRegisteredStudents() {
return this.registeredStudents;
}
public void assignUser(User user) {
if (this.registeredStudents == null) {
this.registeredStudents = new HashSet<>();
}
this.registeredStudents.add(user);
}
public Groups() {
}
public Groups(int capacity, String room, Course course, int time, WeekDay day, Lecturer lecturer) {
public Integer getGrNr() {
return grNr;
}
public void setGrNr(Integer grNr) {
this.grNr = grNr;
}
public Integer getZajCykId() {
return zajCykId;
}
public void setZajCykId(Integer zajCykId) {
this.zajCykId = zajCykId;
}
/**
* 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 endTime end time of class in minutes
* @param day day given to the groups
* @param lecturer lecturer given to the groups
*/
public Groups(int capacity, String room, Course course, int time, int endTime, WeekDay day, Lecturer lecturer) {
this.capacity = capacity;
this.room = room;
this.course = course;
this.time = time;
this.endTime = endTime;
this.day = day;
this.lecturer = lecturer;
this.type = capacity >= 50 ? GroupType.LECTURE : GroupType.CLASS;
}
/**
* 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 endTime end time of class in minutes
* @param day day given to the groups
* @param lecturer lecturer given to the groups
* @param zajCykId number of class in the term
* @param grNr Number of class/course
* @param type type of class/cource
*/
public Groups(int capacity, String room, Course course, int time, int endTime, WeekDay day, Lecturer lecturer,
Integer zajCykId, Integer grNr, GroupType type) {
this(capacity, room, course, time, endTime, day, lecturer, zajCykId, grNr);
this.type = type;
}
/**
* 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
* @param zajCykId number of class in the term
* @param grNr Number of class/course
* @param type type of class/cource
*/
public Groups(int capacity, String room, Course course, int time, WeekDay day, Lecturer lecturer,
Integer zajCykId, Integer grNr, GroupType type) {
this(capacity, room, course, time, time + DEFAULT_CLASS_TIME, day, lecturer, zajCykId, grNr);
this.type = type;
}
/**
* 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 endTime end time of class in minutes
* @param day day given to the groups
* @param lecturer lecturer given to the groups
* @param zajCykId number of class in the term
* @param grNr Number of class/course
*/
public Groups(int capacity, String room, Course course, int time, int endTime, WeekDay day, Lecturer lecturer,
Integer zajCykId, Integer grNr) {
this(capacity, room, course, time, endTime, day, lecturer);
this.zajCykId = zajCykId;
this.grNr = grNr;
}
/**
* 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
* @param zajCykId number of class in the term
* @param grNr Number of class/course
*/
public Groups(int capacity, String room, Course course, int time, WeekDay day, Lecturer lecturer, Integer zajCykId,
Integer grNr) {
this(capacity, room, course, time, time + DEFAULT_CLASS_TIME, day, lecturer);
this.zajCykId = zajCykId;
this.grNr = grNr;
}
/**
* Create groups with default class duration
*
* @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, room, course, time, time + DEFAULT_CLASS_TIME, day, lecturer);
}
/**
* Updates given values other that are not null
*
* @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 endTime end time of class in minutes
* @param day day given to the groups
* @param lecturer lecturer given to the groups
* @param type type given to the groups
*/
public void update(Integer capacity, String room, Course course, Integer time, Integer endTime, WeekDay day,
Lecturer lecturer, GroupType type) {
if (capacity != null) {
this.capacity = capacity;
}
if (room != null) {
this.room = room;
}
if (course != null) {
this.course = course;
}
if (time != null) {
this.time = time;
}
if (endTime != null) {
this.endTime = endTime;
}
if (day != null) {
this.day = day;
}
if (lecturer != null) {
this.lecturer = lecturer;
}
if (type != null) {
this.type = type;
}
}
/**
* get time of class end
*
* @return hour of class finish time in minutes
*/
public int getEndTime() {
return endTime;
}
/**
* 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 course;
}
/**
* setCourseId
*
* @param courseId set courseId into groups
*/
public void setCourseId(Course 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);
@ -111,4 +393,19 @@ public class Groups {
}
return String.format("%s.%s", hoursString, minutesString);
}
/**
* gets end time formated strins
*
* @return end time as formated String
*/
public String getEndTimeString() {
int minutes = this.getEndTime() % 60;
String hoursString = Integer.toString(this.getEndTime() / 60);
String minutesString = Integer.toString(minutes);
if (minutes < 10) {
minutesString = "0" + minutesString;
}
return String.format("%s.%s", hoursString, minutesString);
}
}

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,6 +35,60 @@ 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,29 +1,74 @@
package com.plannaplan.entities;
import java.sql.Date;
import java.sql.Timestamp;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import com.plannaplan.models.UserApiResponse;
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 Date tokenCreatedDate;
private String refreshToken;
private Timestamp tokenUsageDate;
private Integer ranking;
@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinTable
private Set<Groups> studentRegisteredGrups;
public Set<Groups> getStudentRegisteredGrups() {
return this.studentRegisteredGrups;
}
public void removeGroup(Long id) {
final Groups groupToDelete = this.studentRegisteredGrups.stream().filter(e -> e.getId().equals(id)).findFirst().get();
this.studentRegisteredGrups.remove(groupToDelete);
}
public void claimGroup(Groups group) {
if (this.studentRegisteredGrups == null) {
this.studentRegisteredGrups = new HashSet<>();
}
this.studentRegisteredGrups.add(group);
}
public User() {
}
/**
*
* @param name name given to the user
* @param surname surname given to the user
* @param mail mail given to the user
* @param role user's role
*/
public User(String name, String surname, String mail, UserRoles role) {
this.name = name;
this.surname = surname;
@ -31,52 +76,204 @@ public class User {
this.role = role;
}
/**
*
* @param name name given to the user
* @param surname surname given to the user
* @param mail mail given to the user
* @param usosId id in the USOS system
* @param role user's role
*/
public User(String name, String surname, String mail, String usosId, UserRoles role) {
this(name, surname, mail, role);
this.usosId = usosId;
}
/**
*
* @param name name given to the user
* @param surname surname given to the user
* @param mail mail given to the user
* @param usosId id in the USOS system
* @param role user's role
* @param ranking ranking points [100;500]. It's calculated by
* gradesAvg*100*studiesYear
*/
public User(String name, String surname, String mail, String usosId, UserRoles role, Integer ranking) {
this(name, surname, mail, usosId, role);
this.ranking = ranking;
}
/**
* usos id getter
*
* @return usosid
*/
public String getUsosId() {
return usosId;
}
/**
* email getter
*
* @return mailof user
*/
public String getEmail() {
return email;
}
/**
* email setter
*
* @param email user email
*/
public void setEmail(String email) {
this.email = email;
}
public Date getTokenCreatedDate() {
return tokenCreatedDate;
/**
* token usage getter
*
* @return Timestamp when token was used
*/
public Timestamp getTokenUsageDate() {
return tokenUsageDate;
}
/**
* token getter
*
* @return user token
*/
public String getToken() {
return token;
}
public void setToken(String token) {
this.tokenCreatedDate = new Date(System.currentTimeMillis());
this.token = token;
/**
* @return token needed to call refresh token after it expired
*/
public String getRefreshToken() {
return refreshToken;
}
/**
* token seter. Sets token and automaticly set time when was set
*
* @param token token to set
*/
public void setToken(String token) {
this.tokenUsageDate = new Timestamp(System.currentTimeMillis());
this.token = token;
this.refreshToken = UUID.randomUUID().toString();
}
/**
* name setter
*
* @return String user name
*/
public String getName() {
return name;
}
/**
* user rolse getter
*
* @return UserRoles of user
*/
public UserRoles getRole() {
return role;
}
/**
* user role setter
*
* @param role to be set
*/
public void setRole(UserRoles role) {
this.role = role;
}
/**
* surname getter
*
* @return string surname
*/
public String getSurname() {
return surname;
}
/**
* surname setter
*
* @param surname string to be set as surnames
*/
public void setSurname(String surname) {
this.surname = surname;
}
/**
* name stter
*
* @param name stirng to be set as name
*/
public void setName(String name) {
this.name = name;
}
/**
* id getter
*
* @return id in database
*/
public Long getId() {
return this.id;
}
/**
* Ranking points are [100;500]. It's calculated by gradesAvg*100*studiesYear
*
* @return ranking points [100;500]
*/
public Integer getRanking() {
return ranking;
}
/**
* Ranking points setter. Ranking points are [100;500]. It's calculated by
* gradesAvg*100*studiesYear
*
* @param ranking ranking points [100;500]
*/
public void setRanking(Integer ranking) {
this.ranking = ranking;
}
/**
* updates user entity with data got by UsosApiService::getUserData
*
* @param usosData UserApiResponse model with needed data
*/
public void updateWithUsosData(UserApiResponse usosData) {
this.name = usosData.getName();
this.surname = usosData.getSurname();
}
/**
* it checks if given ammount of time passed since last token usage. If not
* retunr true and reset time otherwise return false and token won work anymore
*
* @return boolena if credentials (token) is expired or not
*/
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

@ -1,29 +1,50 @@
package com.plannaplan.models;
import java.util.Date;
import java.io.InputStream;
public class ConfigData {
private Date start;
private Date end;
private TourData firstTour;
private TourData secondTour;
private InputStream filestream;
public ConfigData(Date start, Date end, InputStream filestream) {
this.start = start;
this.end = end;
/**
* constructor
*
* @param firstTour date of first tours
* @param secondTour date of second tours
* @param filestream filestram with data to import
*/
public ConfigData(TourData firstTour, TourData secondTour, InputStream filestream) {
this.firstTour = firstTour;
this.secondTour = secondTour;
this.filestream = filestream;
}
/**
* second tour getter
*
* @return TourData second tour
*/
public TourData getSecondTour() {
return secondTour;
}
/**
* first tour getter
*
* @return TourData first tour
*/
public TourData getFirstTour() {
return firstTour;
}
/**
* filestream getter
*
* @return InputStream with data to import
*/
public InputStream getFilestream() {
return filestream;
}
public Date getEnd() {
return end;
}
public Date getStart() {
return start;
}
}

View File

@ -0,0 +1,97 @@
package com.plannaplan.models;
import java.util.Iterator;
import java.util.List;
import com.plannaplan.entities.Groups;
/**
* Instance to keep data to send in mail about accepted courses results
*/
public class EmailAcceptedData {
private List<Groups> accepted;
private List<Groups> removed;
public EmailAcceptedData() {
}
/**
* creates instance of class
*
* @param accepted list of groups that user joined to
* @param removed lsit of groups that user failed to join
*/
public EmailAcceptedData(List<Groups> accepted, List<Groups> removed) {
this.accepted = accepted;
this.removed = removed;
}
/**
* get list of removed assignments
*
* @return removed assingments
*/
public List<Groups> getRemoved() {
return removed;
}
/**
* set list of removed assignments
*
* @param removed list of removed assignments
*/
public void setRemoved(List<Groups> removed) {
this.removed = removed;
}
/**
* get list of accepted assignments
*
* @return accepted assingments
*/
public List<Groups> getAccepted() {
return accepted;
}
/**
* set list of accepted assignments
*
* @param accepted list of accepted assignments
*/
public void setAccepted(List<Groups> accepted) {
this.accepted = accepted;
}
/**
* it creates and return email message body
*
* @return string with emiale massage
*/
public String getEmailMessage() {
String response = "Akceptacja Twoich przedmiotów właśnie dobiegła końca.\n\n";
if (this.accepted != null && this.accepted.size() > 0) {
response += "Zatwierdzone grupy: \n";
Iterator<Groups> iterator = accepted.iterator();
while (iterator.hasNext()) {
final Groups gorup = iterator.next();
final String courseName = gorup.getCourseId() != null ? gorup.getCourseId().getName()
: "Nieznana grupa";
response += (" - " + courseName + " - " + gorup.getType() + "\n");
}
}
if (this.removed != null && this.removed.size() > 0) {
response += "Usunięte grupy: \n";
Iterator<Groups> iterator = removed.iterator();
while (iterator.hasNext()) {
final Groups gorup = iterator.next();
final String courseName = gorup.getCourseId() != null ? gorup.getCourseId().getName()
: "Nieznana grupa";
response += (" - " + courseName + " - " + gorup.getType() + "\n");
}
}
return response;
}
}

View File

@ -0,0 +1,45 @@
package com.plannaplan.models;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.plannaplan.entities.Exchange;
import com.plannaplan.entities.User;
/**
* Class to keepm data to be send after exchanges being accept
*/
public class EmailExchangesData {
private Map<Long, List<Exchange>> data;
public EmailExchangesData() {
this.data = new HashMap<>();
}
/**
* method to add user and his event to data to be send
*
* @param user owner of exchange being performed
* @param data exchange that was executed
*/
public void addExchange(User user, Exchange data) {
final Long id = user.getId();
if (this.data.get(id) == null) {
this.data.put(id, new ArrayList<>());
}
this.data.get(id).add(data);
}
/**
* get datas entry set
*
* @return set with entries that contains Long that is user id and list of hiss
* performed Exchanges
*/
public Set<Map.Entry<Long, List<Exchange>>> getDataEntry() {
return this.data.entrySet();
}
}

View File

@ -9,27 +9,54 @@ public class FileData {
private HashMap<String, Integer> keys;
private Iterator<Row> 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;
}
/*
* getKeys
* @return keys
*/
public HashMap<String, Integer> getKeys() {
return 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

@ -0,0 +1,66 @@
package com.plannaplan.models;
import com.plannaplan.entities.Assignment;
import com.plannaplan.entities.Exchange;
public class MatchData {
private Exchange exchangeOne;
private Exchange exchangeTwo;
public MatchData(Exchange exchangeOne, Exchange exchangeTwo) {
this.exchangeOne = exchangeOne;
this.exchangeTwo = exchangeTwo;
}
public Exchange getExchangeOne() {
return this.exchangeOne;
}
public Exchange getExchangeTwo() {
return this.exchangeTwo;
}
public Assignment getAssignmentTwo() {
return this.exchangeTwo.getOwnedAssignment();
}
public Assignment getAssignmentOne() {
return this.exchangeOne.getOwnedAssignment();
}
@Override
public int hashCode() {
return this.getAssignmentOne().hashCode() + this.getAssignmentTwo().hashCode();
}
@Override
public boolean equals(Object o) {
// If the object is compared with itself then return true
if (o == this) {
return true;
}
/*
* Check if o is an instance of Complex or not "null instanceof [type]" also
* returns false
*/
if (!(o instanceof MatchData)) {
return false;
}
// typecast o to Complex so that we can compare data members
MatchData c = (MatchData) o;
// Compare the data members and return accordingly
return (this.getAssignmentOne().equals(c.getAssignmentOne()) && this.getAssignmentTwo().equals(c.getAssignmentTwo())) || (this.getAssignmentOne().equals(c.getAssignmentTwo()) && this.getAssignmentTwo().equals(c.getAssignmentOne()));
}
public int compare(MatchData m1) {
return Long.compare(m1.getExchangesMsValue(), this.getExchangesMsValue());
}
public long getExchangesMsValue(){
return this.exchangeOne.getDataExchange().getTime() + this.exchangeTwo.getDataExchange().getTime();
}
}

View File

@ -0,0 +1,49 @@
package com.plannaplan.models;
import java.sql.Date;
public class TourData {
private Date start;
private Date end;
/**
* construcotr for java.sql.Date
*
* @param start Date when tour start
* @param end Date when tour end
*/
public TourData(Date start, Date end) {
this.start = start;
this.end = end;
}
/**
* constructor construcotr for java.util.Date
*
* @param start Date when tour start
* @param end Date when tour end
*/
public TourData(java.util.Date start, java.util.Date end) {
this.start = new Date(start.getTime());
this.end = new Date(end.getTime());
}
/**
* tour end getter
*
* @return Date end of tour
*/
public Date getEnd() {
return end;
}
/**
* tour start getter
*
* @return Date beginning of tour
*/
public Date getStart() {
return start;
}
}

View File

@ -0,0 +1,29 @@
package com.plannaplan.models;
/**
* Model to keep data from /services/users/user response called in
* UsosApiService
*/
public class UserApiResponse {
private String name;
private String surname;
public UserApiResponse() {
}
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;
}
}

View File

@ -0,0 +1,8 @@
package com.plannaplan.repositories;
import com.plannaplan.entities.AppConfig;
import org.springframework.data.jpa.repository.JpaRepository;
public interface AppConfigRepository extends JpaRepository<AppConfig, Long> {
}

View File

@ -9,6 +9,13 @@ 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> {

View File

@ -9,6 +9,19 @@ 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")

View File

@ -9,6 +9,13 @@ 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("FROM Course WHERE name = ?1")

View File

@ -0,0 +1,26 @@
package com.plannaplan.repositories;
import java.util.List;
import java.util.Optional;
import com.plannaplan.entities.Assignment;
import com.plannaplan.entities.Exchange;
import com.plannaplan.entities.Groups;
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;
@Repository
public interface ExchangeRepository extends JpaRepository<Exchange, Long>{
@Query("FROM Exchange WHERE owned_id = ?1 AND desired_id = ?2")
Optional<Exchange> checkForExchange(@Param("owned_id") Assignment assignment, @Param("desired_id") Groups group);
@Query("FROM Exchange WHERE ownerId = ?1")
List<Exchange> getByUserId(@Param("id") Long id);
@Query("Select e1,e2 FROM Exchange e1, Exchange e2 WHERE e1.ownedAssignment.group.id = e2.desiredAssignment.id")
List<Object[]> getMatches();
}

View File

@ -10,12 +10,42 @@ 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("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("FROM Groups WHERE zajCykId = ?1 AND grNr = ?2")
Optional<Groups> find(@Param("zajCykId") Integer zaj_cyk_id, @Param("grNr") Integer gr_nr);
@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

@ -9,6 +9,13 @@ 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("FROM Lecturer WHERE title = ?1 AND name = ?2 AND surname = ?3")

View File

@ -11,17 +11,64 @@ 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")
/**
* return user by given authority
*
* @param authority user usosId or email
* @return optional with user if found
*/
@Query("FROM User WHERE email = ?1 OR usosId = ?1")
Optional<User> getByAuthority(@Param("authority") String authority);
@Query("FROM User WHERE email = ?1")
Optional<User> getByEmail(@Param("authority") String authority);
@Query("FROM User WHERE refreshToken = ?1")
Optional<User> getByRefreshToken(@Param("refreshToken") String refreshToken);
@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);
/**
* search for user with given query
*
* @param query string that will be matched to users name and surname
* @param role limits results by role
* @return list opf results
*/
@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 role=?1")
List<User> getAllByRole(@Param("role") UserRoles role);
@Query("FROM User WHERE usosId = ?1")
Optional<User> getByUsosId(@Param("usosId") String usosId);
}

View File

@ -1,31 +1,107 @@
package com.plannaplan.services;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import com.plannaplan.entities.Assignment;
import com.plannaplan.entities.Commision;
import com.plannaplan.entities.Groups;
import com.plannaplan.entities.User;
import com.plannaplan.models.EmailAcceptedData;
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 {
@Autowired
private AssignmentRepository repo;
@Autowired
private CommisionService service;
@Autowired
private UserService userService;
@Autowired
private EmailService emailService;
public AssignmentService() {
}
public void save(Assignment assignment) {
this.repo.save(assignment);
/**
* 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);
}
/**
* gets list of assignments of given commision
*
* @param com Commision to get assinments from
* @return list of assignments
*/
public List<Assignment> getCommisionAssignments(Commision com) {
return this.repo.getByCommision(com.getId());
}
/**
* get ammount of all assignments (not only for selected commision)
*
* @return long - ammount of assingments
*/
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);
}
/**
* this method will activate accept algorythm for all students. Algorythm is
* takeing each student in order defined by ranking and accept for him groups
* that are joinable for him
*/
public void callAcceptAlgorythm() {
final List<User> students = this.userService.getStudentsSortedByRanking();
students.forEach(e -> {
final Optional<Commision> com = this.service.getNewestCommision(e);
final List<Groups> accepted = new ArrayList<>();
final List<Groups> removed = new ArrayList<>();
if (com.isPresent()) {
final List<Assignment> assignments = this.getCommisionAssignments(com.get());
assignments.forEach(a -> {
final Groups group = a.getGroup();
if (group.getCapacity() > group.getRegisteredStudents().size()) {
e.claimGroup(group);
accepted.add(group);
} else {
removed.add(group);
}
});
}
this.userService.save(e);
this.emailService.sendAcceptationResult(e, new EmailAcceptedData(accepted, removed));
});
}
}

View File

@ -5,33 +5,67 @@ 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() {
}
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;
}
/**
* gets user commisions
*
* @param user owner of commisions
* @return list of user commisions
*/
public List<Commision> getUsersCommisions(User user) {
return this.repo.getUsers(user.getId());
}
/**
* get newest commision ov given user
*
* @param user owener of commision we attemp to get
* @return optional if commition was found
*/
public Optional<Commision> getNewestCommision(User user) {
return this.repo.getNewestCommision(user.getId()).stream().findFirst();
}
/**
* get ammpounts of commisions
*
* @return long - ammounts of commisions (all even from history, not only
* cutrrent one)
*/
public long getCommisionsAmmount() {
return this.repo.count();
}

View File

@ -2,25 +2,136 @@ package com.plannaplan.services;
import com.plannaplan.models.ConfigData;
import com.plannaplan.models.FileData;
import com.plannaplan.models.TourData;
import com.plannaplan.repositories.AppConfigRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.plannaplan.configutils.*;
import java.io.InputStream;
import java.sql.Date;
import java.time.LocalDate;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import com.plannaplan.configutils.*;
import com.plannaplan.entities.AppConfig;
/**
* FileReader is used for reading xls file from input stream.
*/
@Component
public class ConfiguratorService {
@Autowired
private FileToDatabaseMigrator migrator;
@Autowired
private AppConfigRepository configRepo;
@Autowired
private EventService eventService;
@Autowired
private AssignmentService assignmentService;
public ConfiguratorService() {
}
/**
* methoid to config system. it shedules PerformAcceptAlgorythmTask as a side
* effect
*
* @param data ConfigData containng system configs
*/
public void config(ConfigData data) {
FileReader reader = new FileReader(data.getFilestream());
FileData coursesData = reader.read();
final AppConfig config = new AppConfig(data.getFirstTour(), data.getSecondTour());
this.configRepo.save(config);
migrator.migrate(coursesData);
this.shceduleTaskAfterToursDateChange(config);
}
/**
* Save tours to DataBase and shedule PerformAcceptAlgorythmTask as a side
* effect
*
* @param firstTour First tour period.
* @param secondTour Second tour period.
*/
public void saveTours(TourData firstTour, TourData secondTour) {
final AppConfig config = new AppConfig(firstTour, secondTour);
this.configRepo.save(config);
this.shceduleTaskAfterToursDateChange(config);
}
/**
* current config getter
*
* @return AppConfig with newest config_date
*/
public AppConfig getCurrentConfig() {
final List<AppConfig> repsonse = this.configRepo.findAll().stream().sorted(new Comparator<AppConfig>() {
@Override
public int compare(AppConfig i1, AppConfig i2) {
if (i1.getConfigDate().after(i2.getConfigDate())) {
return -1;
}
if (i1.getConfigDate().before(i2.getConfigDate())) {
return 1;
}
return 0;
}
}).collect(Collectors.toList());
return repsonse.get(0);
}
/**
*
* @param inputStream This input stream contains new courses to import.
*/
public void importCoursesStream(InputStream inputStream) {
FileReader reader = new FileReader(inputStream);
FileData coursesData = reader.read();
migrator.migrate(coursesData);
}
private void shceduleTaskAfterToursDateChange(AppConfig config) {
this.eventService.scheduleTask(EventService.FIRST_TOUR_SCHEDULE,
new AlgorythmAcceptTask(config.getFirstTourEnd()), config.getFirstTourEndCron());
this.eventService.scheduleTask(EventService.SECOND_TOUR_SCHEDULE,
new AlgorythmAcceptTask(config.getSecondTourEnd()), config.getSecondTourEndCron());
}
/**
* It's local class to perform accept Task. It's needed to be here due to have
* acces to AssignmentService.
*/
private class AlgorythmAcceptTask implements Runnable {
private LocalDate localDate;
/**
* create instance of AlgorythmAcceptTask
*
* @param date date of algorythm perform. Needed to check if ti's being called
* in correct year
*/
public AlgorythmAcceptTask(Date date) {
this.localDate = date.toLocalDate();
}
@Override
public void run() {
System.out.println("Performing event");
if (localDate.getYear() == LocalDate.now().getYear()) {
assignmentService.callAcceptAlgorythm();
}
}
}
}

View File

@ -9,28 +9,52 @@ 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;
/*
* 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();
}
/*
* 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

@ -0,0 +1,101 @@
package com.plannaplan.services;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import com.plannaplan.entities.Exchange;
import com.plannaplan.entities.User;
import com.plannaplan.models.EmailAcceptedData;
import com.plannaplan.models.EmailExchangesData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
/**
* Service to send emails
*/
@Service
public class EmailService {
@Autowired
private JavaMailSender emailSender;
@Autowired
private UserService userService;
@Value("${plannaplan.email}")
private String appEmail;
public EmailService() {
}
/**
* send simple text email
*
* @param destination destitnaion mail
* @param message text to be send
*/
public void sendMail(String destination, String message) {
SimpleMailMessage mailMessage = new SimpleMailMessage();
mailMessage.setFrom(appEmail);
mailMessage.setTo(destination);
mailMessage.setSubject("[Plan na plan] INFO");
mailMessage.setText(message);
emailSender.send(mailMessage);
}
/**
* sends email with infromation about accepted groups
*
* @param user user to send a mail
* @param data EmailAcceptedData instance containing informations about accepted
* and removed groups
*/
public void sendAcceptationResult(User user, EmailAcceptedData data) {
SimpleMailMessage mailMessage = new SimpleMailMessage();
mailMessage.setFrom(appEmail);
mailMessage.setTo(user.getEmail());
mailMessage.setSubject("[PlanNaPlan] Akceptacja przedmiotów");
mailMessage.setText(data.getEmailMessage());
emailSender.send(mailMessage);
}
/**
* method to send email for students whose groups were swaped
*
* @param data EmailExchangesData instance that contains pair of datas user and
* list of performed exhanges
*/
public void sendExchangesResults(EmailExchangesData data) {
for (Map.Entry<Long, List<Exchange>> entry : data.getDataEntry()) {
final User user = this.userService.getById(entry.getKey()).get();
String response = "Znaleźliśmy dla Ciebie osobę, która zamieniła się z Tobą przedmiotami!!!\n Zamienione przedmioty: \n";
final Iterator<Exchange> interator = entry.getValue().iterator();
while (interator.hasNext()) {
final Exchange exchange = interator.next();
final String courseFrom = exchange.getDesiredAssignment().getCourseId() != null
? exchange.getDesiredAssignment().getCourseId().getName()
: "Nieznane zajęcie";
final String courseTo = exchange.getOwnedAssignment().getGroup().getCourseId() != null
? exchange.getOwnedAssignment().getGroup().getCourseId().getName()
: "Nieznane zajęcie";
response += (" - " + courseFrom + " za " + courseTo.toLowerCase());
}
SimpleMailMessage mailMessage = new SimpleMailMessage();
mailMessage.setFrom(appEmail);
mailMessage.setTo(user.getEmail());
mailMessage.setSubject("[PlanNaPlan] Zamiana przedmiotów");
mailMessage.setText(response);
emailSender.send(mailMessage);
}
}
}

View File

@ -0,0 +1,61 @@
package com.plannaplan.services;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ScheduledFuture;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Service;
@Service
public class EventService {
@Autowired
private ExchangeService exchangeService;
public static final int FIRST_TOUR_SCHEDULE = 0;
public static final int SECOND_TOUR_SCHEDULE = 1;
private ThreadPoolTaskScheduler scheduler;
private Map<Integer, ScheduledFuture<?>> jobsMap = new HashMap<>();
@Scheduled(cron = "0 24 17 * * *")
public void collectGroupLosses() {
System.out.println("Checking for groups");
}
@Scheduled(cron = "0 0 0 * * *")
public void performExchangeService() {
System.out.println("Performing Exchange");
this.exchangeService.performExchange();
}
/**
* Schedule provided task to perform
*
* @param taskId static filed of this class that represents to what event
* we want to assign task
* @param task runnable class that perform task in implemented run method
* @param cronTrigger CronTrigger instance with date to perform
*/
public void scheduleTask(int taskId, Runnable task, CronTrigger cronTrigger) {
ScheduledFuture<?> scheduledTask = jobsMap.get(taskId);
if (scheduledTask != null) {
scheduledTask.cancel(true);
jobsMap.put(taskId, null);
}
scheduledTask = this.scheduler.schedule(task, cronTrigger);
jobsMap.put(taskId, scheduledTask);
}
@PostConstruct
public void initialize() {
this.scheduler = new ThreadPoolTaskScheduler();
this.scheduler.initialize();
}
}

View File

@ -0,0 +1,143 @@
package com.plannaplan.services;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import com.plannaplan.entities.Assignment;
import com.plannaplan.entities.Commision;
import com.plannaplan.entities.Exchange;
import com.plannaplan.entities.Groups;
import com.plannaplan.entities.User;
import com.plannaplan.models.EmailExchangesData;
import com.plannaplan.models.MatchData;
import com.plannaplan.repositories.ExchangeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class ExchangeService {
@Autowired
private ExchangeRepository repo;
@Autowired
private AssignmentService assignmentService;
@Autowired
private UserService userService;
@Autowired
private EmailService emailService;
/**
* @param exchange Instance to save in database
* @return Exchange Instance contains database id
*/
public Exchange save(Exchange exchange) {
return this.repo.save(exchange);
}
/**
* @param id Id of exchange in database
* @return Optional Exchange if found
*/
public Optional<Exchange> getById(Long id) {
return this.repo.findById(id);
}
public List<Exchange> getAllExchanges() {
return this.repo.findAll();
}
/**
* @param id Id of user
* @return List of exchanges that belong to user
*/
public List<Exchange> getByUserId(Long id) {
return this.repo.getByUserId(id);
}
/**
* @param entity Exchange entity which we would like to delete
*/
public void deleteExchange(Exchange entity) {
this.repo.delete(entity);
}
/**
* @param assignment Assignment to trade for
* @param group Desired group
* @return Optional with Exchange if exist
*/
public Optional<Exchange> checkForExchange(Assignment assignment, Groups group) {
return this.repo.checkForExchange(assignment, group);
}
public void performExchange() {
final List<MatchData> matchData = this.getMatches();
final List<Long> performedAssignmentExchanges = new ArrayList<>();
final EmailExchangesData emailData = new EmailExchangesData();
final List<Exchange> exchangesToDelete = new ArrayList<>();
matchData.forEach(m -> {
final Assignment assignmentOne = m.getAssignmentOne();
final Assignment assignmentTwo = m.getAssignmentTwo();
final Exchange exchange1 = m.getExchangeOne();
final Exchange exchange2 = m.getExchangeTwo();
if (!(performedAssignmentExchanges.contains(assignmentOne.getId())
|| performedAssignmentExchanges.contains(assignmentTwo.getId()))) {
final Commision commisionOne = assignmentOne.getCommision();
final User userOne = commisionOne.getCommisionOwner();
final Commision commisionTwo = assignmentTwo.getCommision();
final User userTwo = commisionTwo.getCommisionOwner();
assignmentOne.setCommision(commisionTwo);
assignmentTwo.setCommision(commisionOne);
userOne.removeGroup(assignmentOne.getGroup().getId());
userTwo.removeGroup(assignmentTwo.getGroup().getId());
userOne.claimGroup(assignmentTwo.getGroup());
userTwo.claimGroup(assignmentOne.getGroup());
this.assignmentService.save(assignmentOne);
this.assignmentService.save(assignmentTwo);
this.userService.save(userOne);
this.userService.save(userTwo);
performedAssignmentExchanges.add(assignmentOne.getId());
performedAssignmentExchanges.add(assignmentTwo.getId());
emailData.addExchange(exchange1.getOwnedAssignment().getCommision().getCommisionOwner(), exchange1);
emailData.addExchange(exchange2.getOwnedAssignment().getCommision().getCommisionOwner(), exchange2);
}
exchangesToDelete.add(exchange1);
exchangesToDelete.add(exchange2);
});
this.emailService.sendExchangesResults(emailData);
this.repo.deleteAll(exchangesToDelete);
}
public List<MatchData> getMatches() {
final List<MatchData> matches = this.repo.getMatches().stream().map(m -> {
final Exchange exchangeOne = (Exchange) m[0];
final Exchange exchangeTwo = (Exchange) m[1];
return new MatchData(exchangeOne, exchangeTwo);
}).collect(Collectors.toList());
final Set<MatchData> uniqData = new HashSet<>(matches);
final List<MatchData> matchDataListSorted = uniqData.stream().sorted((m1, m2) -> -1 * m1.compare(m2))
.collect(Collectors.toList());
return matchDataListSorted;
}
}

View File

@ -1,14 +1,24 @@
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.Assignment;
import com.plannaplan.entities.Groups;
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
@ -21,13 +31,16 @@ public class GroupService {
return this.repo.find(time, room, capacity);
}
public Optional<Groups> find(Integer zajCykId, Integer nrGr) {
return this.repo.find(zajCykId, nrGr);
}
public List<Groups> getGroupsByCourse(Long id) {
return this.repo.getByCourse(id);
}
public Groups save(Groups group) {
this.repo.save(group);
return group;
return this.repo.save(group);
}
public void delete(Groups groups) {
@ -41,4 +54,54 @@ public class GroupService {
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 assignments list of assignments you want to get taken places ammount
* @return HashMap of Long to Integer where Long is group id and Integer is how
* many places in gorup is already taken
*/
public HashMap<Long, Integer> getTakenPlacesOfAssignments(List<Assignment> assignments) {
return getTakenPlaces(assignments.stream().map(Assignment::getGroup).collect(Collectors.toList()));
}
/**
*
* @param groups list of groups you want to get taken places ammount
* @return HashMap of Long to 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

@ -8,6 +8,9 @@ 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

View File

@ -3,50 +3,170 @@ package com.plannaplan.services;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.stream.Collectors;
import com.plannaplan.entities.User;
import com.plannaplan.exceptions.UserNotFoundException;
import com.plannaplan.models.UserApiResponse;
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 {
@Autowired
private UserRepository repo;
@Autowired
private UsosApiService service;
public UserService() {
super();
}
public String login(String authority) throws UserNotFoundException {
User user = this.repo.getByAuthority(authority.replace("\n", "").trim())
.orElseThrow(() -> new UserNotFoundException("Can not find user with given authority"));
/**
* checks if user exist and return him or creates new one with student role
* otherwise
*
* @param email user email in usos
* @param usosId user id in usos
* @return user entity instace containing changes saved in database
*/
public User checkForUser(String email, String usosId) {
return this.checkForUser(email, usosId, UserRoles.STUDENT);
}
/**
* checks if user exist and creates new one if doesn't
*
* @param email user email in usos
* @param usosId user id in usos
* @param roleIfNotExist role to be set in case user is not in database yet
* @return user entity instace containing changes saved in database
*/
public User checkForUser(String email, String usosId, UserRoles roleIfNotExist) {
if (usosId == null) {
Optional<User> user = this.repo.getByEmail(email.replace("\n", "").trim());
if (user.isPresent()) {
return user.get();
} else {
final User newUser = new User(null, null, email.replace("\n", "").trim(), roleIfNotExist);
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, roleIfNotExist);
return this.repo.save(newUser);
}
}
}
/**
* generates token for user and if user don't have name in database it will
* attemp to obtain these from usos api and saves changes in database
*
* @param authority user we want to login
* @return user with changed values after save in db
* @throws UserNotFoundException throwed if user doesn't exist
*/
public User login(User authority) throws UserNotFoundException {
final String token = UUID.randomUUID().toString();
user.setToken(token);
this.repo.save(user);
return token;
if ((authority.getName() == null || authority.getSurname() == null) && authority.getUsosId() != null) {
final UserApiResponse resp = this.service.getUserData(authority.getUsosId());
authority.updateWithUsosData(resp);
}
try {
authority.setToken(token);
this.repo.save(authority);
} catch (Exception e) {
throw new UserNotFoundException(e.getMessage());
}
return authority;
}
public void save(User user) {
this.repo.save(user);
/**
* sacves user to databse and return instatnce with id
*
* @param user to be saved
* @return instatnce with bd id
*/
public User save(User user) {
return this.repo.save(user);
}
/**
*
* @param email of user to be find
* @return user with given mail
* @throws UserNotFoundException throwed if user doesn't exist
*/
public User getUserByEmail(String email) throws UserNotFoundException {
return this.repo.getByAuthority(email.replace("\n", "").trim())
return this.repo.getByEmail(email.replace("\n", "").trim())
.orElseThrow(() -> new UserNotFoundException("Cannot find user with given authority"));
}
/**
* return user by given authority
*
* @param authority user usosId or email
* @return optional with user if found
*/
public Optional<User> getByAuthority(String authority) {
return this.repo.getByAuthority(authority);
}
public Optional<User> getByToken(String token) {
return this.repo.getByToken(token);
}
/**
* search for user with given query
*
* @param query string that will be matched to users name and surname
* @return list opf results
*/
public List<User> searchForStudents(String query) {
return this.repo.searchForUsers(query, UserRoles.STUDENT);
}
public Optional<User> getById(Long userId) {
return this.repo.findById(userId);
}
public List<User> getAllStudents() {
return this.repo.getAllByRole(UserRoles.STUDENT);
}
public Optional<User> getUserByRefreshToken(String refreshToken) {
return this.repo.getByRefreshToken(refreshToken);
}
public boolean adminExists() {
return this.repo.getAllByRole(UserRoles.ADMIN).size() > 0;
}
public void saveAll(List<User> users) {
this.repo.saveAll(users);
}
/**
* get students sorted by their ranking
*
* @return list of students
*/
public List<User> getStudentsSortedByRanking() {
return this.repo.getAllByRole(UserRoles.STUDENT).stream().sorted((u1, u2) -> {
return -1 * u1.getRanking().compareTo(u2.getRanking());
}).collect(Collectors.toList());
}
}

View File

@ -0,0 +1,75 @@
package com.plannaplan.services;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.type.TypeReference;
import com.github.scribejava.core.builder.ServiceBuilder;
import com.github.scribejava.core.model.OAuth1AccessToken;
import com.github.scribejava.core.model.OAuthRequest;
import com.github.scribejava.core.model.Response;
import com.github.scribejava.core.model.Verb;
import com.github.scribejava.core.oauth.OAuth10aService;
import com.plannaplan.api.UsosOauth1Service;
import com.plannaplan.models.UserApiResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
/**
* service to call usos api endpoints
*/
@Service
public class UsosApiService {
private static final String NAME_FIELD = "first_name";
private static final String SURNAME_FIELD = "last_name";
@Value("${plannaplan.apiurl}")
private String apiUrl;
@Value("${plannaplan.apikey}")
private String apikey;
@Value("${plannaplan.apisecret}")
private String apisecret;
public UsosApiService() {
}
/**
* /services/users/user
*
* @param usosId user id in usos
* @return UserApiResponse modle contatining desired values
*/
public UserApiResponse getUserData(String usosId) {
final UserApiResponse apiResponse = new UserApiResponse();
try {
final OAuth10aService service = new ServiceBuilder(apikey).apiSecret(apisecret)
.build(UsosOauth1Service.instance());
final OAuthRequest request = new OAuthRequest(Verb.GET, apiUrl + "/services/users/user?user_id=" + usosId);
service.signRequest(new OAuth1AccessToken("", ""), request);
try (Response response = service.execute(request)) {
final String json = response.getBody();
if (!json.equals("null")){
final ObjectMapper mapper = new ObjectMapper();
Map<String, String> map = mapper.readValue(json, new TypeReference<Map<String, String>>() {
});
apiResponse.setName(map.get(NAME_FIELD));
apiResponse.setSurname(map.get(SURNAME_FIELD));
}
}
} catch (IOException | InterruptedException | ExecutionException e) {
e.printStackTrace();
}
return apiResponse;
}
}

View File

@ -0,0 +1,5 @@
package com.plannaplan.types;
public enum AppState {
FIRST_TOUR, SECOND_TOUR, NO_TOUR
}

View File

@ -1,5 +1,23 @@
package com.plannaplan.types;
/**
* GroupType contains types: LECTURE, CLASS, LAB, SEMINAR, CONSERVATORY, PRATICE
*/
public enum GroupType {
LECTURE, CLASS
LECTURE("Wykład"), CLASS("Ćwiczenia"), LAB("Laboratorium"), SEMINAR("Seminarium"),CONSERVATORY("Konwersatorium"), PRATICE("Praktyka");
public final String type;
private GroupType(String type) {
this.type = type;
}
public final static GroupType getType(String type) {
for (GroupType d : values()) {
if (d.type.equals(type)) {
return d;
}
}
return null;
}
}

View File

@ -1,5 +1,9 @@
package com.plannaplan.types;
/**
* UserRoles contains types: STUDENT, DEANERY, ADMIN, TEST_USER
*/
public enum UserRoles {
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

@ -10,12 +10,11 @@ import org.junit.Test;
public class FileReaderTest {
@Test
public void shoulReturnNull() {
public void shouldNotReturnNull() {
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.getKeys().size() == 12);
assertTrue(d != null);
}
}

View File

@ -0,0 +1,189 @@
package com.plannaplan.entities;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.sql.Date;
import com.plannaplan.models.TourData;
import com.plannaplan.types.AppState;
import org.junit.Test;
public class AppConfigTest {
private static long ONE_DAY = 86400000;
@Test
public void shouldReturnNoTourDueToTooEarly() {
final Date firtstTourStart = new Date(System.currentTimeMillis() + ONE_DAY);
final Date firtstTourEnd = new Date(System.currentTimeMillis() + 2 * ONE_DAY);
final Date secondTourStart = new Date(System.currentTimeMillis() + 3 * ONE_DAY);
final Date secondTourEnd = new Date(System.currentTimeMillis() + 4 * ONE_DAY);
final AppConfig config = new AppConfig(new TourData(firtstTourStart, firtstTourEnd),
new TourData(secondTourStart, secondTourEnd));
assertTrue(config.getCurrentState() == AppState.NO_TOUR);
}
@Test
public void shouldReturnFirstTourDueToStart() throws InterruptedException {
final Date firtstTourStart = new Date(System.currentTimeMillis());
final Date firtstTourEnd = new Date(System.currentTimeMillis() + 2 * ONE_DAY);
final Date secondTourStart = new Date(System.currentTimeMillis() + 3 * ONE_DAY);
final Date secondTourEnd = new Date(System.currentTimeMillis() + 4 * ONE_DAY);
final AppConfig config = new AppConfig(new TourData(firtstTourStart, firtstTourEnd),
new TourData(secondTourStart, secondTourEnd));
Thread.sleep(1000);
assertTrue(config.getCurrentState() == AppState.FIRST_TOUR);
}
@Test
public void shouldReturnFirstTourDueToInBetween() {
final Date firtstTourStart = new Date(System.currentTimeMillis() - ONE_DAY);
final Date firtstTourEnd = new Date(System.currentTimeMillis() + 2 * ONE_DAY);
final Date secondTourStart = new Date(System.currentTimeMillis() + 3 * ONE_DAY);
final Date secondTourEnd = new Date(System.currentTimeMillis() + 4 * ONE_DAY);
final AppConfig config = new AppConfig(new TourData(firtstTourStart, firtstTourEnd),
new TourData(secondTourStart, secondTourEnd));
assertTrue(config.getCurrentState() == AppState.FIRST_TOUR);
}
@Test
public void shouldReturnNoTourInLastDay() throws InterruptedException {
final Date firtstTourStart = new Date(System.currentTimeMillis() - ONE_DAY);
final Date firtstTourEnd = new Date(System.currentTimeMillis());
final Date secondTourStart = new Date(System.currentTimeMillis() + 3 * ONE_DAY);
final Date secondTourEnd = new Date(System.currentTimeMillis() + 4 * ONE_DAY);
final AppConfig config = new AppConfig(new TourData(firtstTourStart, firtstTourEnd),
new TourData(secondTourStart, secondTourEnd));
Thread.sleep(1000);
assertTrue(config.getCurrentState() == AppState.NO_TOUR);
}
@Test
public void shouldReturnNoTourInBetween() {
final Date firtstTourStart = new Date(System.currentTimeMillis() - 2 * ONE_DAY);
final Date firtstTourEnd = new Date(System.currentTimeMillis() - ONE_DAY);
final Date secondTourStart = new Date(System.currentTimeMillis() + 3 * ONE_DAY);
final Date secondTourEnd = new Date(System.currentTimeMillis() + 4 * ONE_DAY);
final AppConfig config = new AppConfig(new TourData(firtstTourStart, firtstTourEnd),
new TourData(secondTourStart, secondTourEnd));
assertTrue(config.getCurrentState() == AppState.NO_TOUR);
}
@Test
public void shouldReturnSecondTourInStart() throws InterruptedException {
final Date firtstTourStart = new Date(System.currentTimeMillis() - 2 * ONE_DAY);
final Date firtstTourEnd = new Date(System.currentTimeMillis() - ONE_DAY);
final Date secondTourStart = new Date(System.currentTimeMillis());
final Date secondTourEnd = new Date(System.currentTimeMillis() + 4 * ONE_DAY);
final AppConfig config = new AppConfig(new TourData(firtstTourStart, firtstTourEnd),
new TourData(secondTourStart, secondTourEnd));
Thread.sleep(1000);
assertTrue(config.getCurrentState() == AppState.SECOND_TOUR);
}
@Test
public void shouldReturnSecondTourInBetween() {
final Date firtstTourStart = new Date(System.currentTimeMillis() - 3 * ONE_DAY);
final Date firtstTourEnd = new Date(System.currentTimeMillis() - 2 * ONE_DAY);
final Date secondTourStart = new Date(System.currentTimeMillis() - ONE_DAY);
final Date secondTourEnd = new Date(System.currentTimeMillis() + 4 * ONE_DAY);
final AppConfig config = new AppConfig(new TourData(firtstTourStart, firtstTourEnd),
new TourData(secondTourStart, secondTourEnd));
assertTrue(config.getCurrentState() == AppState.SECOND_TOUR);
}
@Test
public void shouldReturnNoTourDueToEndSecond() throws InterruptedException {
final Date firtstTourStart = new Date(System.currentTimeMillis() - 3 * ONE_DAY);
final Date firtstTourEnd = new Date(System.currentTimeMillis() - 2 * ONE_DAY);
final Date secondTourStart = new Date(System.currentTimeMillis() - ONE_DAY);
final Date secondTourEnd = new Date(System.currentTimeMillis());
final AppConfig config = new AppConfig(new TourData(firtstTourStart, firtstTourEnd),
new TourData(secondTourStart, secondTourEnd));
Thread.sleep(1000);
assertTrue(config.getCurrentState() == AppState.NO_TOUR);
}
@Test
public void shouldReturnNoTourAfterSecondEnd() {
final Date firtstTourStart = new Date(System.currentTimeMillis() - 4 * ONE_DAY);
final Date firtstTourEnd = new Date(System.currentTimeMillis() - 3 * ONE_DAY);
final Date secondTourStart = new Date(System.currentTimeMillis() - 2 * ONE_DAY);
final Date secondTourEnd = new Date(System.currentTimeMillis() - ONE_DAY);
final AppConfig config = new AppConfig(new TourData(firtstTourStart, firtstTourEnd),
new TourData(secondTourStart, secondTourEnd));
assertTrue(config.getCurrentState() == AppState.NO_TOUR);
}
@Test
public void shouldReturnSecondTourWhereThereIsABrake() throws InterruptedException {
final Date firtstTourStart = new Date(System.currentTimeMillis() - 4 * ONE_DAY);
final Date firtstTourEnd = new Date(System.currentTimeMillis());
final Date secondTourStart = new Date(System.currentTimeMillis());
final Date secondTourEnd = new Date(System.currentTimeMillis() + ONE_DAY);
final AppConfig config = new AppConfig(new TourData(firtstTourStart, firtstTourEnd),
new TourData(secondTourStart, secondTourEnd));
Thread.sleep(1000);
assertTrue(config.getCurrentState() == AppState.SECOND_TOUR);
}
@Test
public void shouldReturnFirstStartDatesCorns() {
final Date firtstTourStart = Date.valueOf("2020-11-12");
final Date firtstTourEnd = Date.valueOf("2020-11-13");
final Date secondTourStart = Date.valueOf("2020-11-14");
final Date secondTourEnd = Date.valueOf("2020-11-15");
final AppConfig config = new AppConfig(new TourData(firtstTourStart, firtstTourEnd),
new TourData(secondTourStart, secondTourEnd));
assertTrue(config.getFirstTourStartCron().getExpression().equals("0 0 0 12 11 ?"));
}
@Test
public void shouldReturnSecondStartDatesCorns() {
final Date firtstTourStart = Date.valueOf("2020-11-12");
final Date firtstTourEnd = Date.valueOf("2020-11-13");
final Date secondTourStart = Date.valueOf("2020-11-14");
final Date secondTourEnd = Date.valueOf("2020-11-15");
final AppConfig config = new AppConfig(new TourData(firtstTourStart, firtstTourEnd),
new TourData(secondTourStart, secondTourEnd));
assertTrue(config.getSecondTourStartCron().getExpression().equals("0 0 0 14 11 ?"));
}
@Test
public void shouldReturnFirstEndDatesCorns() {
final Date firtstTourStart = Date.valueOf("2020-11-12");
final Date firtstTourEnd = Date.valueOf("2020-11-13");
final Date secondTourStart = Date.valueOf("2020-11-14");
final Date secondTourEnd = Date.valueOf("2020-11-15");
final AppConfig config = new AppConfig(new TourData(firtstTourStart, firtstTourEnd),
new TourData(secondTourStart, secondTourEnd));
assertTrue(config.getFirstTourEndCron().getExpression().equals("0 0 0 13 11 ?"));
}
@Test
public void shouldReturnSecondEndDatesCorns() {
final Date firtstTourStart = Date.valueOf("2020-11-12");
final Date firtstTourEnd = Date.valueOf("2020-11-13");
final Date secondTourStart = Date.valueOf("2020-11-14");
final Date secondTourEnd = Date.valueOf("2020-11-15");
final AppConfig config = new AppConfig(new TourData(firtstTourStart, firtstTourEnd),
new TourData(secondTourStart, secondTourEnd));
assertTrue(config.getSecondTourEndCron().getExpression().equals("0 0 0 15 11 ?"));
}
}

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,69 @@
package com.plannaplan.repositories;
import static org.junit.Assert.assertTrue;
import java.util.List;
import com.plannaplan.entities.Assignment;
import com.plannaplan.entities.Commision;
import com.plannaplan.entities.Exchange;
import com.plannaplan.entities.Groups;
import com.plannaplan.entities.User;
import com.plannaplan.services.AssignmentService;
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;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.annotation.DirtiesContext.MethodMode;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
@ContextConfiguration
public class ExchangeRepositoryTest{
@Autowired
private ExchangeRepository exchangeRepository;
@Autowired
private AssignmentService assignmentService;
@Autowired
private GroupService groupService;
@Autowired
private UserService userService;
@Autowired
private CommisionRepository commisionRepository;
@Test
@DirtiesContext(methodMode = MethodMode.BEFORE_METHOD)
public void shouldReturnMatches() {
final User user1 = this.userService.save(
new User(null, null, "shouldReturnMatches@ExchangeRepository.test", "123454", UserRoles.STUDENT, 451));
final Groups group1 = this.groupService.save(new Groups(123, "A2-3", null, 430, WeekDay.MONDAY, null));
final Commision commision1 = this.commisionRepository.save(new Commision(user1));
final User user2 = this.userService.save(
new User(null, null, "shouldReturnMatches@ExchangeRepository.test", "123454", UserRoles.STUDENT, 451));
final Groups group2 = this.groupService.save(new Groups(123, "A2-3", null, 430, WeekDay.MONDAY, null));
final Commision commision2 = this.commisionRepository.save(new Commision(user2));
final Assignment assignmentUser1 = this.assignmentService.save(new Assignment(group1, commision1));
final Assignment assignmentUser2 = this.assignmentService.save(new Assignment(group2, commision2));
this.assignmentService.callAcceptAlgorythm();
this.exchangeRepository.save(new Exchange(assignmentUser1, group2));
this.exchangeRepository.save(new Exchange(assignmentUser2, group1));
final List<Object[]> exchangeRepoMatches = this.exchangeRepository.getMatches();
assertTrue(exchangeRepoMatches.size() == 2);
}
}

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,52 @@
package com.plannaplan.repositories;
import static org.junit.Assert.assertTrue;
import java.util.Optional;
import com.plannaplan.entities.User;
import com.plannaplan.services.UserService;
import com.plannaplan.types.UserRoles;
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 UserRepositoryTest {
@Autowired
private UserService userService;
@Autowired
private UserRepository userRepository;
@Test
public void shouldReturnByAuthorityWithGivenEmail(){
final String email = "shouldReturnByAuthorityWithGivenEmail@UserRepository.Test";
final String usosId = "45678";
final User user = this.userService.save(new User("shouldReturnByAuthority", "WithGivenEmail", email, usosId, UserRoles.TEST_USER));
final Optional<User> response = this.userRepository.getByAuthority(email);
assertTrue(response.get().getEmail().equals(email));
assertTrue(response.get().getUsosId().equals(usosId));
assertTrue(response.get().getId().equals(user.getId()));
}
@Test
public void shouldReturnByAuthorityWithUsosId(){
final String email = "shouldReturnByAuthorityWithUsosId@UserRepository.Test";
final String usosId = "45678";
final User user = this.userService.save(new User("shouldReturnByAuthority", "WithGivenEmail", email, usosId, UserRoles.TEST_USER));
final Optional<User> response = this.userRepository.getByAuthority(usosId);
assertTrue(response.get().getEmail().equals(email));
assertTrue(response.get().getUsosId().equals(usosId));
assertTrue(response.get().getId().equals(user.getId()));
}
}

View File

@ -2,17 +2,27 @@ package com.plannaplan.services;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.annotation.DirtiesContext.MethodMode;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import java.util.stream.IntStream;
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.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
@ -26,28 +36,101 @@ public class AssignmentServiceTest {
private AssignmentService service;
@Autowired
private CommisionService comServie;
private Commision com;
@Before
public void init() {
this.com = new Commision();
this.comServie.save(this.com);
}
@Autowired
private UserService userService;
@Autowired
private GroupService groupService;
@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();
this.addAssignmentToCommision(this.com);
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() {
this.addAssignmentToCommision(this.com);
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);
}
@Test
@Ignore
@DirtiesContext(methodMode = MethodMode.BEFORE_METHOD)
public void shouldPerformAcceptAlgorythm() {
final Random generator = new Random();
final List<Groups> groups = new ArrayList<>();
IntStream.range(0, 418).forEach(i -> {
groups.add(this.groupService.save(new Groups(generator.nextInt(80) + 20, null, null,
generator.nextInt(9) * 30 + 9 * 30, WeekDay.getDay(generator.nextInt(5)), null)));
});
IntStream.range(0, 1700).forEach(i -> {
final User user = this.userService.save(new User(null, null,
"shouldPerformAcceptAlgorythm-" + UUID.randomUUID().toString() + "@AssignmentService.test", null,
UserRoles.STUDENT, generator.nextInt(400) + 100));
final Commision com = this.comServie.save(new Commision(user));
IntStream.range(0, 5).forEach(j -> {
this.service.save(new Assignment(groups.get(generator.nextInt(groups.size())), com));
});
});
this.service.callAcceptAlgorythm();
}
/**
* This test will also sand a mail to users as a side effect. U can check them
* in mailcater
*/
@Test
@DirtiesContext(methodMode = MethodMode.BEFORE_METHOD)
public void shouldNotAcceptForOnePerson() {
final Random generator = new Random();
final Groups group = this.groupService.save(new Groups(5, null, null, 840, WeekDay.MONDAY, null));
IntStream.range(0, 6).forEach(i -> {
final User user = this.userService.save(new User(null, null,
"shouldNotAcceptForOnePerson-" + UUID.randomUUID().toString() + "@AssignmentService.test", null,
UserRoles.STUDENT, generator.nextInt(400) + 100));
final Commision com = this.comServie.save(new Commision(user));
this.service.save(new Assignment(group, com));
});
this.service.callAcceptAlgorythm();
final List<User> users = this.userService.getStudentsSortedByRanking();
final User loser = users.get(users.size() - 1);
assertTrue(loser.getStudentRegisteredGrups().size() == 0);
users.forEach(u -> {
final Commision com = this.comServie.getNewestCommision(u).get();
final List<Assignment> assignments = com.getAssignments();
if (u.getId() == loser.getId()) {
assertTrue(!assignments.get(0).isAccepted());
} else {
assertTrue(assignments.get(0).isAccepted());
}
});
}
private void addAssignmentToCommision(Commision com) {
Assignment a = new Assignment(null, com);
this.service.save(a);

View File

@ -7,8 +7,10 @@ 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;
@ -24,10 +26,15 @@ public class CommisionServiceTest {
@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());
this.service.save(new Commision(usr));
assertTrue("Commision ammount should have changed", this.service.getCommisionsAmmount() > beginState);
}
@ -57,4 +64,31 @@ public class CommisionServiceTest {
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

@ -2,15 +2,26 @@ package com.plannaplan.services;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.annotation.DirtiesContext.MethodMode;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.Assert.assertTrue;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.sql.Date;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ScheduledFuture;
import com.plannaplan.TestApplication;
import com.plannaplan.entities.AppConfig;
import com.plannaplan.entities.Groups;
import com.plannaplan.models.ConfigData;
import com.plannaplan.models.TourData;
import com.plannaplan.repositories.AppConfigRepository;
import org.junit.Test;
import org.junit.runner.RunWith;
@ -20,6 +31,9 @@ import org.junit.runner.RunWith;
@ContextConfiguration
public class ConfiguratorServiceTest {
private final static String BEFORE_UPDATE_FILE = "ZajeciaBeforeUpdate.xlsx";
private final static String AFTER_UPDATE_FILE = "ZajeciaAfterUpdate.xlsx";
@Autowired
private ConfiguratorService configuratorService;
@ -32,11 +46,21 @@ public class ConfiguratorServiceTest {
@Autowired
private LecturerService lecturerService;
@Autowired
private AppConfigRepository appConfigRepo;
@Autowired
private EventService eventService;
@Test
public void shouldImportDataToDataBase() {
final InputStream inputStream = getClass().getClassLoader()
.getResourceAsStream(TestApplication.TEST_CONFIG_FILE);
final ConfigData data = new ConfigData(null, null, inputStream);
final ConfigData data = new ConfigData(
new TourData(new Date(System.currentTimeMillis()), new Date(System.currentTimeMillis() + 86400000)),
new TourData(new Date(System.currentTimeMillis() + 86400000),
new Date(System.currentTimeMillis() + 2 * 86400000)),
inputStream);
this.configuratorService.config(data);
int courses_ammount = this.courseService.getCoursesAmmount();
@ -46,4 +70,65 @@ public class ConfiguratorServiceTest {
assertTrue(courses_ammount > 0 && groups_ammount > 0 && lecturers_ammount > 0);
}
@Test
@DirtiesContext(methodMode = MethodMode.BEFORE_METHOD)
public void shouldUpdatePreviousImport() {
final InputStream inputStream = getClass().getClassLoader()
.getResourceAsStream(ConfiguratorServiceTest.BEFORE_UPDATE_FILE);
this.configuratorService.importCoursesStream(inputStream);
int groups_ammount = this.groupService.getGroupsAmmount();
assertTrue(groups_ammount == 2);
final InputStream inputStream2 = getClass().getClassLoader()
.getResourceAsStream(ConfiguratorServiceTest.AFTER_UPDATE_FILE);
this.configuratorService.importCoursesStream(inputStream2);
int groups_ammount2 = this.groupService.getGroupsAmmount();
Optional<Groups> newGroup = this.groupService.find(456458, 3);
Optional<Groups> updateGroup = this.groupService.find(456457, 2);
assertTrue(groups_ammount2 == 3);
assertTrue(newGroup.isPresent());
assertTrue(updateGroup.get().getLecturer().getSurname().equals("Murawski"));
assertTrue(updateGroup.get().getLecturer().getName().equals("Roman"));
assertTrue(updateGroup.get().getLecturer().getTitle().equals("prof. dr hab."));
}
@Test
public void shouldRetrunNewestConfig() throws InterruptedException {
final Date dateToCheck = new Date(System.currentTimeMillis());
this.appConfigRepo.save(new AppConfig(new TourData(null, null), new TourData(null, null)));
Thread.sleep(2000);
this.appConfigRepo.save(new AppConfig(new TourData(dateToCheck, null), new TourData(null, null)));
AppConfig response = this.configuratorService.getCurrentConfig();
assertTrue(response.getFirstTourStart() != null);
}
@Test
@DirtiesContext(methodMode = MethodMode.BEFORE_METHOD)
public void shlouldScheduleTaskWhenSetTourDate()
throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
final InputStream inputStream = getClass().getClassLoader()
.getResourceAsStream(TestApplication.TEST_CONFIG_FILE);
final ConfigData data = new ConfigData(
new TourData(new Date(System.currentTimeMillis()), new Date(System.currentTimeMillis() + 86400000)),
new TourData(new Date(System.currentTimeMillis() + 86400000),
new Date(System.currentTimeMillis() + 2 * 86400000)),
inputStream);
this.configuratorService.config(data);
final Field reader = EventService.class.getDeclaredField("jobsMap");
reader.setAccessible(true);
@SuppressWarnings("unchecked")
final Map<Integer, ScheduledFuture<?>> map = (Map<Integer, ScheduledFuture<?>>) reader.get(this.eventService);
assertTrue(map.size() == 2);
assertTrue(map.get(EventService.FIRST_TOUR_SCHEDULE).isDone() == false);
assertTrue(map.get(EventService.SECOND_TOUR_SCHEDULE).isDone() == false);
}
}

View File

@ -0,0 +1,29 @@
package com.plannaplan.services;
import org.junit.Ignore;
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 EmailServiceTest {
@Autowired
private EmailService service;
@Test
@Ignore
/**
* This test is ignored because we don't have way to check if email has arrived.
* Check mailchater to check this manually
*/
public void shouldSendSimpleEmail() {
this.service.sendMail("shouldSendSimpleEmail@EmailService.test", "This is totally simple message");
}
}

View File

@ -0,0 +1,208 @@
package com.plannaplan.services;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import com.plannaplan.entities.Assignment;
import com.plannaplan.entities.Commision;
import com.plannaplan.entities.Exchange;
import com.plannaplan.entities.Groups;
import com.plannaplan.entities.User;
import com.plannaplan.models.MatchData;
import com.plannaplan.repositories.CommisionRepository;
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.annotation.DirtiesContext;
import org.springframework.test.annotation.DirtiesContext.MethodMode;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
@ContextConfiguration
public class ExchangeServiceTest {
@Autowired
private AssignmentService assignmentService;
@Autowired
private GroupService groupService;
@Autowired
private UserService userService;
@Autowired
private CommisionRepository commisionRepository;
@Autowired
private ExchangeService exchangeService;
@Test
@DirtiesContext(methodMode = MethodMode.BEFORE_METHOD)
public void shouldReturnUniqMatches() {
final User user1 = this.userService.save(
new User(null, null, "shouldReturnMatches@ExchangeRepository.test", "123454", UserRoles.STUDENT, 451));
final Groups group1 = this.groupService.save(new Groups(123, "A2-3", null, 430, WeekDay.MONDAY, null));
final Commision commision1 = this.commisionRepository.save(new Commision(user1));
final User user2 = this.userService.save(
new User(null, null, "shouldReturnMatches@ExchangeRepository.test", "123454", UserRoles.STUDENT, 451));
final Groups group2 = this.groupService.save(new Groups(123, "A2-3", null, 430, WeekDay.MONDAY, null));
final Commision commision2 = this.commisionRepository.save(new Commision(user2));
final Assignment assignmentUser1 = this.assignmentService.save(new Assignment(group1, commision1));
final Assignment assignmentUser2 = this.assignmentService.save(new Assignment(group2, commision2));
this.assignmentService.callAcceptAlgorythm();
this.exchangeService.save(new Exchange(assignmentUser1, group2));
this.exchangeService.save(new Exchange(assignmentUser2, group1));
final List<MatchData> uniqList = this.exchangeService.getMatches();
assertTrue(uniqList.size() == 1);
}
@Test
@DirtiesContext(methodMode = MethodMode.BEFORE_METHOD)
public void shouldPerformExchange() throws Exception{
User user1 = this.userService.save(
new User(null, null, "1shouldReturnMatches@ExchangeRepository.test", "123454", UserRoles.STUDENT, 451));
final Long user1Id = user1.getId();
final Groups group1 = this.groupService.save(new Groups(123, "A2-3", null, 430, WeekDay.MONDAY, null));
final Commision commision1 = this.commisionRepository.save(new Commision(user1));
User user2 = this.userService.save(
new User(null, null, "2shouldReturnMatches@ExchangeRepository.test", "123455", UserRoles.STUDENT, 452));
final Long user2Id = user2.getId();
final Groups group2 = this.groupService.save(new Groups(123, "A2-3", null, 430, WeekDay.THURSDAY, null));
final Commision commision2 = this.commisionRepository.save(new Commision(user2));
User user3 = this.userService.save(
new User(null, null, "3shouldReturnMatches@ExchangeRepository.test", "123456", UserRoles.STUDENT, 453));
final Long user3Id = user3.getId();
final Groups group3 = this.groupService.save(new Groups(123, "A2-3", null, 430, WeekDay.WEDNESDAY, null));
final Commision commision3 = this.commisionRepository.save(new Commision(user3));
User user4 = this.userService.save(
new User(null, null, "2shouldReturnMatches@ExchangeRepository.test", "123457", UserRoles.STUDENT, 455));
final Long user4Id = user4.getId();
final Groups group4 = this.groupService.save(new Groups(123, "A2-3", null, 430, WeekDay.FRIDAY, null));
final Commision commision4 = this.commisionRepository.save(new Commision(user4));
final Assignment assignmentUser1 = this.assignmentService.save(new Assignment(group1, commision1));
final Assignment assignmentUser2 = this.assignmentService.save(new Assignment(group2, commision2));
final Assignment assignmentUser3 = this.assignmentService.save(new Assignment(group2, commision3));
final Assignment assignmentUser4 = this.assignmentService.save(new Assignment(group4, commision4));
this.assignmentService.callAcceptAlgorythm();
this.exchangeService.save(new Exchange(assignmentUser1, group2));
Thread.sleep(1000);
this.exchangeService.save(new Exchange(assignmentUser2, group1));
Thread.sleep(1000);
this.exchangeService.save(new Exchange(assignmentUser3, group1));
Thread.sleep(1000);
this.exchangeService.save(new Exchange(assignmentUser4, group3));
this.exchangeService.performExchange();
user1 = this.userService.getById(user1Id).get();
Thread.sleep(1000);
user2 = this.userService.getById(user2Id).get();
Thread.sleep(1000);
user3 = this.userService.getById(user3Id).get();
Thread.sleep(1000);
user4 = this.userService.getById(user4Id).get();
Thread.sleep(1000);
final List<Long> listGroupsOfUser1 = user1.getStudentRegisteredGrups().stream().map(Groups::getId)
.collect(Collectors.toList());
final List<Long> listGroupsOfUser2 = user2.getStudentRegisteredGrups().stream().map(Groups::getId)
.collect(Collectors.toList());
final List<Long> listGroupsOfUser3 = user3.getStudentRegisteredGrups().stream().map(Groups::getId)
.collect(Collectors.toList());
final List<Long> listGroupsOfUser4 = user4.getStudentRegisteredGrups().stream().map(Groups::getId)
.collect(Collectors.toList());
assertTrue(listGroupsOfUser1.contains(group2.getId()));
assertTrue(listGroupsOfUser2.contains(group1.getId()));
assertTrue(listGroupsOfUser3.contains(group2.getId()));
assertTrue(listGroupsOfUser4.contains(group4.getId()));
}
@Test
@DirtiesContext(methodMode = MethodMode.BEFORE_METHOD)
public void shouldRemoveOutDatedExchnages() throws Exception {
User user1 = this.userService.save(
new User(null, null, "1shouldReturnMatches@ExchangeRepository.test", "123454", UserRoles.STUDENT, 451));
final Long user1Id = user1.getId();
final Groups group1 = this.groupService.save(new Groups(123, "A2-3", null, 430, WeekDay.MONDAY, null));
final Commision commision1 = this.commisionRepository.save(new Commision(user1));
User user2 = this.userService.save(
new User(null, null, "2shouldReturnMatches@ExchangeRepository.test", "123455", UserRoles.STUDENT, 452));
final Long user2Id = user2.getId();
final Groups group2 = this.groupService.save(new Groups(123, "A2-3", null, 430, WeekDay.THURSDAY, null));
final Commision commision2 = this.commisionRepository.save(new Commision(user2));
final Groups group3 = this.groupService.save(new Groups(123, "A2-3", null, 430, WeekDay.THURSDAY, null));
final Groups group4 = this.groupService.save(new Groups(123, "A2-3", null, 430, WeekDay.THURSDAY, null));
final Assignment assignmentUser1 = this.assignmentService.save(new Assignment(group1, commision1));
final Assignment assignmentUser2 = this.assignmentService.save(new Assignment(group2, commision2));
this.assignmentService.callAcceptAlgorythm();
this.exchangeService.save(new Exchange(assignmentUser1, group2));
Thread.sleep(1000);
this.exchangeService.save(new Exchange(assignmentUser2, group1));
Thread.sleep(1000);
this.exchangeService.save(new Exchange(assignmentUser1, group3));
Thread.sleep(1000);
this.exchangeService.save(new Exchange(assignmentUser1, group4));
Thread.sleep(1000);
this.exchangeService.performExchange();
user1 = this.userService.getById(user1Id).get();
user2 = this.userService.getById(user2Id).get();
final List<Long> listGroupsOfUser1 = user1.getStudentRegisteredGrups().stream().map(Groups::getId)
.collect(Collectors.toList());
final List<Long> listGroupsOfUser2 = user2.getStudentRegisteredGrups().stream().map(Groups::getId)
.collect(Collectors.toList());
assertTrue(listGroupsOfUser1.contains(group2.getId()));
assertTrue(listGroupsOfUser2.contains(group1.getId()));
assertTrue(this.exchangeService.getAllExchanges().size() == 2);
}
@Test
@DirtiesContext(methodMode = MethodMode.BEFORE_METHOD)
public void shouldSortExchanges() throws Exception{
final List<MatchData> listMatrix = new ArrayList<>();
final Exchange exchange1 = new Exchange(null, null);
Thread.sleep(1000);
final Exchange exchange2 = new Exchange(null, null);
Thread.sleep(1000);
final Exchange exchange3 = new Exchange(null, null);
Thread.sleep(1000);
final Exchange exchange4 = new Exchange(null, null);
Thread.sleep(1000);
listMatrix.add(new MatchData(exchange2, exchange4));
listMatrix.add(new MatchData(exchange1, exchange3));
final List<MatchData> matchDataListSorted = listMatrix.stream().sorted((m1, m2) -> -1 * m1.compare(m2)).collect(Collectors.toList());
assertTrue(listMatrix.get(0).equals(matchDataListSorted.get(1)));
assertTrue(listMatrix.get(1).equals(matchDataListSorted.get(0)));
assertTrue(matchDataListSorted.size() == 2);
}
}

View File

@ -2,7 +2,15 @@ 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;
@ -18,6 +26,12 @@ public class GroupServiceTest {
@Autowired
private GroupService groupService;
@Autowired
private AssignmentService assignmentService;
@Autowired
private CommisionService commisionService;
@Autowired
private UserService userService;
@Test
public void createAndDeleteGroup() {
@ -31,4 +45,27 @@ public class GroupServiceTest {
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

@ -2,6 +2,8 @@ package com.plannaplan.services;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.annotation.DirtiesContext.MethodMode;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
@ -32,12 +34,12 @@ public class UserServiceTest {
@Test
public void shouldReturnToken() {
final User testUser = new User(TEST_USER_NAME, TEST_USER_SUERNAME, TEST_USER_MAIL, UserRoles.TEST_USER);
this.userService.save(testUser);
User testUser = this.userService
.save(new User(TEST_USER_NAME, TEST_USER_SUERNAME, TEST_USER_MAIL, UserRoles.TEST_USER));
try {
final String token = this.userService.login(TEST_USER_MAIL);
System.out.println("Returned token: " + token);
assertTrue(token != null);
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();
@ -45,16 +47,6 @@ public class UserServiceTest {
}
}
@Test
public void shouldThrowException() {
try {
this.userService.login("thiseamilisnotindatabase@gmail.com");
assertTrue(false);
} catch (UserNotFoundException e) {
assertTrue(true);
}
}
@Test
public void shouldFindStudents() {
this.userService.save(new User("Nemo", "TheFish", "Nemo@shouldFindStudents.test", UserRoles.STUDENT));
@ -93,4 +85,37 @@ public class UserServiceTest {
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");
}
@Test
public void shouldReturnAdminExists() {
final String email = "shouldReturnAdminExists@UserService.test";
this.userService.save(new User("AdminTom", "Smieszny", email, UserRoles.ADMIN));
assertTrue(userService.adminExists());
}
@Test
@DirtiesContext(methodMode = MethodMode.BEFORE_METHOD)
public void shouldReturnNotAdminExists() {
final String email = "shouldReturnNotAdminExists@UserService.test";
this.userService.save(new User("StudentTom", "Smieszny", email, UserRoles.STUDENT));
assertTrue(userService.adminExists() == false);
}
}

View File

@ -0,0 +1,38 @@
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.io.IOException;
import java.util.concurrent.ExecutionException;
import com.plannaplan.models.UserApiResponse;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(SpringRunner.class)
@SpringBootTest
@ContextConfiguration
public class UsosApiServiceTest {
@Autowired
private UsosApiService service;
@Test
@Ignore
public void shouldReturnPersonalData() throws IOException, InterruptedException, ExecutionException {
final UserApiResponse response = this.service.getUserData("499054");
assertTrue(response.getName().equals("Marcin"));
assertTrue(response.getSurname().equals("Woźniak"));
}
}

Binary file not shown.

Binary file not shown.

View File

@ -7,5 +7,15 @@ 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
spring.mail.host=localhost
spring.mail.port=1025
spring.mail.properties.mail.smtp.auth=false
spring.mail.properties.mail.smtp.starttls.enable=false
plannaplan.email = plannaplan.kontakt@gmail.com
plannaplan.apiurl = https://usosapidemo.amu.edu.pl
plannaplan.apikey=${PLANNAPLAN_CONSUMER_KEY}
plannaplan.apisecret=${PLANNAPLAN_CONSUMER_SECRET}
server.port=1285

View File

@ -1,88 +0,0 @@
# Dokumetacja API
| Api | Zadania endpointa |
| ------------------------------------------------------------- | ---------------------------------------------------------------------------- |
| [/api/v1/configurator/config](#config) | Załadowanie konfiguracji startowej do aplikacji PlanNaPlan |
| [/api/v1/courses/getCoursesWithGroups](#getcourseswithgroups) | Zwrócenie wszytskich kursów razem z grupami |
| [/api/v1/groups/getCourseGroups](#getcoursegroups) | Zwrócenie grup dla danego kursu |
| [/api/v1/courses/getCourses](#getcourses) | Zwrócenie wszystkich kursów |
| [/token](#token) | Wymienia ticket z CAS-a na token ktorym beda autoryzowane chronione requesty |
## 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 /api/v1/courses/getCoursesWithGroups
```
#### Opis
Zwraca wszystkie dostepne kursy wraz z listą grup.
## getCourseGroups
Source code: [link](../restservice/src/main/java/com/plannaplan/controllers/GroupController.java)
```
GET /api/v1/groups/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 /api/v1/courses/getCourses
```
#### Opis
Zwraca wszystkie dostepne kursy.
## token
Source code: [link](../restservice/src/main/java/com/plannaplan/controllers/TokenController.java)
```
GET /token?ticket=ST-668405-W0gfvSVDRBdMUWLweKzv-cas.amu.edu.pl
```
#### Opis
Po odpytaniu tego endpointa z podanym ticketem system zrobi nma nim validate i dostanie uzytkownika dla ktorego zostal on wygenerowany. System utworzy dla niego access token i go zwroci w odpowiedzi
#### Parametry
| Type | Name | Consumes | Opis | Type |
| ----------- | ------------------------- | -------- | --------------------------------------- | ------ |
| Query Param | **ticket** </br> required | - | ticket uzyskany z logowania poprzez CAS | string |

48
gettoken.py Executable file
View File

@ -0,0 +1,48 @@
#!/usr/bin/python
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
no_browser = False
API_ADDRESS = "http://localhost:1285"
if len(sys.argv) > 1 :
if (sys.argv[1] == "no-browser" or sys.argv[2] == "no-browser"):
no_browser = True
else:
API_ADDRESS = "http://" + sys.argv[1] + ":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'
if no_browser == False:
webbrowser.open_new_tab(url)
wait_for_request()

View File

@ -1 +1,2 @@
CREATE DATABASE IF NOT EXISTS test;
SET GLOBAL time_zone = '+1:00';

View File

@ -16,11 +16,30 @@
<!-- 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.14</maven.compiler.source>
<maven.compiler.target>1.14</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>
@ -56,6 +75,13 @@
<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>
@ -85,6 +111,22 @@
<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>

View File

@ -1,22 +1,40 @@
package com.plannaplan;
import java.io.InputStream;
import java.sql.Date;
import java.util.Random;
import com.plannaplan.models.ConfigData;
import com.plannaplan.models.TourData;
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 org.springframework.scheduling.annotation.EnableScheduling;
import com.plannaplan.services.ConfiguratorService;
@SpringBootApplication
@EnableScheduling
public class App {
public final static String API_VERSION = "v1";
@Autowired
UserService userService;
private ConfiguratorService contrl;
@Autowired
private UserService userService;
@Value("${plannaplan.dev}")
private boolean isDev;
public static void main(String[] args) {
Logo logo = new Logo("beta");
@ -26,35 +44,105 @@ public class App {
SpringApplication.run(App.class, args);
}
/**
* method to import mocked data to testing app after startz. It is called only
* in dev profile
*/
@EventListener(ApplicationReadyEvent.class)
public void importData() {
User filip = new User();
filip.setEmail("filizy@st.amu.edu.pl");
filip.setName("Filip");
filip.setSurname("Izydorczyk");
filip.setRole(UserRoles.DEANERY);
this.userService.save(filip);
System.out.println(Logo.getInitInfo(isDev));
User hub = new User();
hub.setEmail("hubwrz1@st.amu.edu.pl");
hub.setName("Hubert");
hub.setSurname("Wrzesiński");
hub.setRole(UserRoles.STUDENT);
this.userService.save(hub);
if (this.isDev) {
final Random generator = new Random();
final InputStream inputStream = getClass().getClassLoader().getResourceAsStream("Zajecia.xlsx");
final ConfigData data = new ConfigData(
new TourData(new Date(System.currentTimeMillis() - 86400000),
new Date(System.currentTimeMillis())),
new TourData(new Date(System.currentTimeMillis() + 86400000),
new Date(System.currentTimeMillis() + 2 * 86400000)),
inputStream);
this.contrl.config(data);
User mac = new User();
mac.setEmail("macglo2@st.amu.edu.pl");
mac.setName("Maciej");
mac.setSurname("Głowacki");
mac.setRole(UserRoles.STUDENT);
this.userService.save(mac);
User newuser = new User();
newuser.setEmail("tommy@st.amu.edu.pl");
newuser.setName("Tomek");
newuser.setSurname("Atomek");
newuser.setRanking(generator.nextInt(400) + 100);
newuser.setRole(UserRoles.STUDENT);
this.userService.save(newuser);
User mar = new User();
mar.setEmail("marwoz16@st.amu.edu.pl");
mar.setName("Marcin");
mar.setSurname("Woźniak");
mar.setRole(UserRoles.STUDENT);
this.userService.save(mar);
newuser = new User();
newuser.setEmail("robercik@st.amu.edu.pl");
newuser.setName("Robert");
newuser.setSurname("Głowacki");
newuser.setRanking(generator.nextInt(400) + 100);
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.setRanking(generator.nextInt(400) + 100);
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.setRanking(generator.nextInt(400) + 100);
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.setRanking(generator.nextInt(400) + 100);
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.setRanking(generator.nextInt(400) + 100);
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.setRanking(generator.nextInt(400) + 100);
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.setRanking(generator.nextInt(400) + 100);
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.setRanking(generator.nextInt(400) + 100);
newuser.setRole(UserRoles.STUDENT);
this.userService.save(newuser);
newuser = new User();
newuser.setEmail("iamnull@st.amu.edu.pl");
newuser.setRanking(generator.nextInt(400) + 100);
newuser.setRole(UserRoles.STUDENT);
this.userService.save(newuser);
}
System.out.println(Logo.getStartedInfo(isDev));
}
}

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,46 @@
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

@ -4,6 +4,10 @@ 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;
@ -12,7 +16,7 @@ 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.GetCurrentAssignmentsResponse;
import com.plannaplan.responses.models.AssignmentResponse;
import com.plannaplan.services.AssignmentService;
import com.plannaplan.services.CommisionService;
@ -24,6 +28,9 @@ 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). This comtroller is depreaceted. Use commission instead")
@Deprecated
public class AssignmentsController extends TokenBasedController {
@Autowired
@ -32,8 +39,10 @@ public class AssignmentsController extends TokenBasedController {
@Autowired
private AssignmentService assignmentService;
@GetMapping("/getCurrentAssignments")
public ResponseEntity<List<GetCurrentAssignmentsResponse>> getCurrentAssignments() throws Exception {
@GetMapping("/user")
@ApiOperation(value = "Return user current assignemts (from newest commision). STUDENT Token needs to be provided. This method is depreaceted. Use `/api/v1/commisions/user/schedule` instead.")
@Deprecated
public ResponseEntity<List<AssignmentResponse>> getCurrentAssignments() throws Exception {
User user = this.getCurrentUser().orElseThrow(() -> new NullPointerException("User not found"));
Optional<Commision> com = this.commisionService.getNewestCommision(user);
@ -42,6 +51,6 @@ public class AssignmentsController extends TokenBasedController {
return new ResponseEntity<>(AssignmentResponseMappers.mapToResponse(respone), HttpStatus.OK);
}
return new ResponseEntity<>(null, HttpStatus.OK);
return new ResponseEntity<>(new ArrayList<>(), HttpStatus.OK);
}
}

View File

@ -3,8 +3,14 @@ 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;
@ -17,17 +23,28 @@ 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;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.ArrayList;
import java.util.HashMap;
import com.plannaplan.responses.mappers.AssignmentResponseMappers;
import com.plannaplan.responses.models.AssignmentResponse;
@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
@ -42,28 +59,122 @@ public class CommisionController extends TokenBasedController {
public CommisionController() {
}
@PostMapping("/add")
public ResponseEntity<String> addCommision(@RequestBody List<Long> groups) throws UserNotFoundException {
@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) {
User user = this.getCurrentUser().orElseThrow(() -> new NullPointerException());
Commision com = new Commision(user);
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, asker);
this.commisionService.save(com);
groups.stream().forEach((groupId) -> {
Groups group = this.groupServcicxe.getGroupById(groupId).orElseThrow(() -> new NullPointerException());
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("/getAllCommisions")
public ResponseEntity<List<CommisionResponse>> getAlCommisions() throws UserNotFoundException {
@GetMapping("/user")
@ApiOperation("Return list of user all commisions (history of schedules)")
public ResponseEntity<List<? extends CommisionResponse>> getAlCommisions(
@RequestParam(name = "groups", defaultValue = "false") @ApiParam(value = "Boolean if we want to display wiht commision's group ids") Boolean groups)
throws UserNotFoundException {
User user = this.getCurrentUser().orElseThrow(() -> new NullPointerException());
List<CommisionResponse> result = CommisionResponseMappers
.mapToResponse(this.commisionService.getUsersCommisions(user));
List<? extends CommisionResponse> result;
if (!groups) {
result = CommisionResponseMappers.mapToResponse(this.commisionService.getUsersCommisions(user));
} else {
result = CommisionResponseMappers
.mapToResponseWithGroups(this.commisionService.getUsersCommisions(user));
}
return new ResponseEntity<>(result, HttpStatus.OK);
}
@GetMapping("/user/schedule")
@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());
final HashMap<Long, Integer> ammounts = this.groupServcicxe
.getTakenPlacesOfAssignments(respone);
return new ResponseEntity<>(AssignmentResponseMappers.mapToResponse(respone, ammounts),
HttpStatus.OK);
}
return new ResponseEntity<>(new ArrayList<>(), 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<? extends CommisionResponse>> getCommision(@PathVariable(name = "id") Long userId,
@RequestParam(name = "groups", defaultValue = "false") @ApiParam(value = "Boolean if we want to display wiht commision's group ids") Boolean groups)
throws UserNotFoundException {
User user = this.userService.getById(userId).orElseThrow(() -> new NullPointerException());
List<? extends CommisionResponse> result;
if (!groups) {
result = CommisionResponseMappers.mapToResponse(this.commisionService.getUsersCommisions(user));
} else {
result = CommisionResponseMappers
.mapToResponseWithGroups(this.commisionService.getUsersCommisions(user));
}
return new ResponseEntity<>(result, HttpStatus.OK);
}
@PreAuthorize("hasRole('ROLE_DEANERY')")
@GetMapping("/user/{id}/schedule")
@ApiOperation(value = "Return given user current assignemts (from newest commision). DEANERY Token needs to be provided.")
public ResponseEntity<List<AssignmentResponse>> getCurrentAssignmentsDeanery(
@PathVariable(name = "id") Long userId) throws Exception {
User user = this.userService.getById(userId).orElseThrow(() -> new NullPointerException());
if (user.getRole() == UserRoles.DEANERY) {
return new ResponseEntity<>(null, HttpStatus.BAD_REQUEST);
}
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

@ -4,12 +4,24 @@ import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
import java.util.Date;
import com.plannaplan.App;
import com.plannaplan.entities.User;
import com.plannaplan.models.ConfigData;
import com.plannaplan.models.TourData;
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.ConfiguratorService;
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.format.annotation.DateTimeFormat;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
@ -19,21 +31,50 @@ 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 {
@Value("${plannaplan.frontendUrl}")
private String serviceUrl;
@Value("${plannaplan.dev}")
private boolean isDev;
@Autowired
private ConfiguratorService contrl;
@PostMapping("/config")
@PreAuthorize("hasRole('ROLE_ADMIN')")
@Autowired
private UserService userService;
public ResponseEntity<String> configApp(@RequestParam("file") MultipartFile file) {
@PostMapping(path = "/config", consumes = { "multipart/form-data" })
@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,
@RequestParam("firstTourBegin") @DateTimeFormat(pattern = "dd.MM.yyyy") @ApiParam(value = "Date when first tour begin in format dd.MM.yyyy") Date firstTourBegin,
@RequestParam("firstTourEnd") @DateTimeFormat(pattern = "dd.MM.yyyy") @ApiParam(value = "Date when first tour ends in format dd.MM.yyyy") Date firstTourEnd,
@RequestParam("secondTourBegin") @DateTimeFormat(pattern = "dd.MM.yyyy") @ApiParam(value = "Date when second tour begin in format dd.MM.yyyy") Date secondTourBegin,
@RequestParam("secondTourEnd") @DateTimeFormat(pattern = "dd.MM.yyyy") @ApiParam(value = "Date when second tour ends in format dd.MM.yyyy") Date secondTourEnd) {
try {
final ConfigData data = new ConfigData(null, null, file.getInputStream());
if (!(firstTourBegin.before(firstTourEnd)
&& (firstTourEnd.before(secondTourBegin) || firstTourEnd.equals(secondTourBegin))
&& secondTourBegin.before(secondTourEnd))) {
return new ResponseEntity<>("Bad dates", HttpStatus.BAD_REQUEST);
}
final TourData firstTour = new TourData(firstTourBegin, firstTourEnd);
final TourData secondTour = new TourData(secondTourBegin, secondTourEnd);
final ConfigData data = new ConfigData(firstTour, secondTour, file.getInputStream());
this.contrl.config(data);
return new ResponseEntity<>("Sucess", HttpStatus.OK);
} catch (IOException e) {
@ -41,4 +82,63 @@ public class ConfigController {
}
}
@PostMapping(path = "/config/tours")
@PreAuthorize("hasRole('ROLE_ADMIN')")
@ApiOperation("Set tours dates. To call you need to provide ADMIN token")
public ResponseEntity<String> configToursApp(
@RequestParam("firstTourBegin") @DateTimeFormat(pattern = "dd.MM.yyyy") @ApiParam(value = "Date when first tour begin in format dd.MM.yyyy") Date firstTourBegin,
@RequestParam("firstTourEnd") @DateTimeFormat(pattern = "dd.MM.yyyy") @ApiParam(value = "Date when first tour ends in format dd.MM.yyyy") Date firstTourEnd,
@RequestParam("secondTourBegin") @DateTimeFormat(pattern = "dd.MM.yyyy") @ApiParam(value = "Date when second tour begin in format dd.MM.yyyy") Date secondTourBegin,
@RequestParam("secondTourEnd") @DateTimeFormat(pattern = "dd.MM.yyyy") @ApiParam(value = "Date when second tour ends in format dd.MM.yyyy") Date secondTourEnd) {
if (!(firstTourBegin.before(firstTourEnd)
&& (firstTourEnd.before(secondTourBegin) || firstTourEnd.equals(secondTourBegin))
&& secondTourBegin.before(secondTourEnd))) {
return new ResponseEntity<>("Bad dates", HttpStatus.BAD_REQUEST);
}
final TourData firstTour = new TourData(firstTourBegin, firstTourEnd);
final TourData secondTour = new TourData(secondTourBegin, secondTourEnd);
this.contrl.saveTours(firstTour, secondTour);
return new ResponseEntity<>("Sucess", HttpStatus.OK);
}
@PostMapping(path = "/config/courses", consumes = { "multipart/form-data" })
@PreAuthorize("hasRole('ROLE_ADMIN')")
@ApiOperation("Imports data to system. To call you need to provide ADMIN token")
public ResponseEntity<String> configAppChangeCources(
@RequestParam("file") @ApiParam(value = "file .xlsx that contains courses and groups with apoinnted rules") MultipartFile file)
{
try {
this.contrl.importCoursesStream(file.getInputStream());
return new ResponseEntity<>("Sucess", HttpStatus.OK);
} catch (IOException e) {
return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@PostMapping(path = "/admin/init")
@ApiOperation("It can be run only in the initialization of the application. It will create admin user to manage the application.")
public ResponseEntity<String> initAdmin(@RequestParam("ticket") @ApiParam(value = "Ticket for validation.") String ticket){
if (this.userService.adminExists()){
return new ResponseEntity<>("Admin had been already created.", HttpStatus.FORBIDDEN);
}
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();
this.userService.save(new User(null, null, authority, usosId, UserRoles.ADMIN));
return new ResponseEntity<>("Success", HttpStatus.OK);
} catch (CasValidationExcepiton e) {
return new ResponseEntity<>("CAS validation failed", HttpStatus.UNAUTHORIZED);
} catch (Exception e) {
return new ResponseEntity<>("Internal Server Error", HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}

View File

@ -1,43 +1,82 @@
package com.plannaplan.controllers;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import com.plannaplan.App;
import com.plannaplan.entities.Course;
import com.plannaplan.responses.mappers.CoursesResponseMappers;
import com.plannaplan.responses.models.GetCoursesResponse;
import com.plannaplan.responses.models.GetCoursesWithGroupsResponse;
import com.plannaplan.responses.models.CoursesDefaultResponse;
import com.plannaplan.responses.models.CoursesWithGroupsResponse;
import com.plannaplan.responses.models.GroupWithCapacityResponse;
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<GetCoursesResponse>> getMethodName() {
@Autowired
private GroupService groupService;
@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<GetCoursesResponse> response = CoursesResponseMappers.mapToGetCoursesResponse(courses);
if (groups) {
if (takenPlaces) {
final List<CoursesWithGroupsResponse> response = new ArrayList<>();
courses.forEach(course -> {
final List<GroupWithCapacityResponse> lectures = new ArrayList<>();
final List<GroupWithCapacityResponse> 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 GroupWithCapacityResponse(group, ammounts.get(group.getId())));
} else {
lectures.add(new GroupWithCapacityResponse(group, ammounts.get(group.getId())));
}
});
response.add(new CoursesWithGroupsResponse(course, lectures, classes));
});
return new ResponseEntity<>(response, HttpStatus.OK);
}
@GetMapping("/getCoursesWithGroups")
public ResponseEntity<List<GetCoursesWithGroupsResponse>> getCoursesWithGroups() {
final List<Course> courses = this.courseService.getAllCourses();
final List<GetCoursesWithGroupsResponse> response = CoursesResponseMappers
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

@ -0,0 +1,151 @@
package com.plannaplan.controllers;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import com.plannaplan.App;
import com.plannaplan.entities.Assignment;
import com.plannaplan.entities.Exchange;
import com.plannaplan.entities.Groups;
import com.plannaplan.entities.User;
import com.plannaplan.exceptions.UserNotFoundException;
import com.plannaplan.responses.mappers.ExchangeResponseMappers;
import com.plannaplan.responses.models.ExchangeResponse;
import com.plannaplan.services.AssignmentService;
import com.plannaplan.services.ExchangeService;
import com.plannaplan.services.GroupService;
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.PostMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
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 + "/exchanges")
@Api(tags = { "Exchange" }, value = "Exchange", description = "Endpoint to exchange with accepted assignments.")
public class ExchangeController extends TokenBasedController{
@Autowired
private GroupService groupService;
@Autowired
private AssignmentService assignmentService;
@Autowired
private ExchangeService exchangeService;
@PostMapping("/exchange")
@ApiOperation(value = "Creates exchange offer.")
public ResponseEntity<String> createExchange(
@ApiParam( value = "Json object that contains assignment to trade and desired group")
@RequestBody
Map<String, Long> exchangeRequest)
throws UserNotFoundException {
final User asker = this.getCurrentUser()
.orElseThrow(() -> new UserNotFoundException("Invalid token"));
final Long assignmentId = exchangeRequest.get("assignment");
final Long groupId = exchangeRequest.get("group");
final List<Long> ownedGroups = asker.getStudentRegisteredGrups().stream().map(Groups::getId).collect(Collectors.toList());
if(ownedGroups.contains(groupId)){
return new ResponseEntity<>("User has already got this group.", HttpStatus.BAD_REQUEST);
}
if(assignmentId == null || groupId == null ){
return new ResponseEntity<>("Some of values are missing", HttpStatus.BAD_REQUEST);
}
final Optional<Assignment> assignment = this.assignmentService.getById(assignmentId);
final Optional<Groups> group = this.groupService.getGroupById(groupId);
if(assignment.isEmpty() || group.isEmpty()){
return new ResponseEntity<>("Some of provided value does not exist.", HttpStatus.BAD_REQUEST);
}
final Assignment assignmentInstance = assignment.get();
final Groups groupInstance = group.get();
if(!(assignmentInstance.getCommision().getCommisionOwner().getId().equals(asker.getId()) && assignmentInstance.isAccepted())){
return new ResponseEntity<>("Some of problems appeared. Check if you have access to given assignment and if it is accepted or the exchange has not been already added.", HttpStatus.BAD_REQUEST);
}
this.exchangeService.save(new Exchange(assignmentInstance, groupInstance));
return new ResponseEntity<>("Success", HttpStatus.OK);
}
@DeleteMapping("/exchange/{id}")
@ApiOperation(value = "Delete exchange offer")
public ResponseEntity<String> deleteExchange(@PathVariable(name = "id", required = false) Long offerId)
throws UserNotFoundException {
final User asker = this.getCurrentUser()
.orElseThrow(() -> new UserNotFoundException("Invalid token"));
final Optional<Exchange> exchange = this.exchangeService.getById(offerId);
if(exchange.isEmpty()){
return new ResponseEntity<>("Given offer does not exist.", HttpStatus.BAD_REQUEST);
}
final Exchange exchangeToDelete = exchange.get();
if(!(exchangeToDelete.getOwnedAssignment().getCommision().getCommisionOwner().getId().equals(asker.getId()))){
return new ResponseEntity<>("You have not permission for that action.", HttpStatus.BAD_REQUEST);
}
this.exchangeService.deleteExchange(exchangeToDelete);
return new ResponseEntity<>("Success", HttpStatus.OK);
}
@GetMapping("/exchange/all")
@ApiOperation(value = "Get exchange offers")
public ResponseEntity<List<ExchangeResponse>> getExchange()
throws UserNotFoundException {
final User asker = this.getCurrentUser()
.orElseThrow(() -> new UserNotFoundException("Invalid token"));
final List<Exchange> response = exchangeService.getByUserId(asker.getId());
final List<ExchangeResponse> listOfResponses = ExchangeResponseMappers.mapToDefaultResponse(response);
return new ResponseEntity<>(listOfResponses, HttpStatus.OK);
}
@GetMapping("/exchange/{id}")
@ApiOperation(value = "Get exchange offers")
public ResponseEntity<ExchangeResponse> getExchangeById(@PathVariable(name = "id", required = false) Long offerId)
throws UserNotFoundException {
final User asker = this.getCurrentUser()
.orElseThrow(() -> new UserNotFoundException("Invalid token"));
final Optional<Exchange> exchange = this.exchangeService.getById(offerId);
if(exchange.isEmpty()){
return new ResponseEntity<>(null, HttpStatus.BAD_REQUEST);
}
final Exchange exchangeInstance = exchange.get();
if(!exchangeInstance.getOwnerId().equals(asker.getId())){
return new ResponseEntity<>(null, HttpStatus.BAD_REQUEST);
}
return new ResponseEntity<>(new ExchangeResponse(exchangeInstance), HttpStatus.OK);
}
}

View File

@ -1,37 +1,79 @@
package com.plannaplan.controllers;
import java.util.HashMap;
import java.util.List;
import java.util.Optional;
import com.plannaplan.App;
import com.plannaplan.entities.Groups;
import com.plannaplan.responses.mappers.GroupsMappers;
import com.plannaplan.responses.models.DefaultGroupResponse;
import com.plannaplan.responses.models.GetCourseGroupsResponse;
import com.plannaplan.responses.models.GroupDefaultResponse;
import com.plannaplan.responses.models.CourseWithGroupsResponse;
import com.plannaplan.services.GroupService;
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.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
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<GetCourseGroupsResponse<? extends DefaultGroupResponse>> 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);
if (takenPlaces) {
HashMap<Long, Integer> ammounts = this.groupService.getTakenPlaces(groups);
if (capacity) {
return new ResponseEntity<>(GroupsMappers.mapToGetCourseGroupsWithCapacityResponse(groups, ammounts),
HttpStatus.OK);
}
return new ResponseEntity<>(GroupsMappers.mapToGetCourseGroupsDefaultResponse(groups, ammounts),
HttpStatus.OK);
}
if (capacity) {
return new ResponseEntity<>(GroupsMappers.mapToGetCourseGroupsWithCapacityResponse(groups), HttpStatus.OK);
}
return new ResponseEntity<>(GroupsMappers.mapToGetCourseGroupsDefaultResponse(groups), HttpStatus.OK);
}
@PutMapping("/{id}/capacity")
@PreAuthorize("hasRole('ROLE_DEANERY')")
@ApiOperation(value = "Change capacity of given group. You need to provide DEANERY token to be ale to change capacity")
public ResponseEntity<String> updateCapacity(
@PathVariable(name = "id", required = true) @ApiParam(value = "id of group to change capacity") Long id,
@RequestParam(name = "newcapacity", required = true) Integer newcapacity) {
final Optional<Groups> group = this.groupService.getGroupById(id);
if (group.isEmpty()) {
return new ResponseEntity<>("Given group doens't exist", HttpStatus.NOT_FOUND);
}
final Groups gr = group.get();
gr.setCapacity(newcapacity);
this.groupService.save(gr);
return new ResponseEntity<>("Success", HttpStatus.OK);
}
}

View File

@ -1,11 +1,20 @@
package com.plannaplan.controllers;
import java.util.Optional;
import java.util.UUID;
import com.plannaplan.entities.User;
import com.plannaplan.exceptions.UserNotFoundException;
import com.plannaplan.security.CasValidationExcepiton;
import com.plannaplan.security.CasValidator;
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;
@ -13,30 +22,61 @@ 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 {
private final static String SERVICE_URL = "http://localhost:3000";
@Value("${plannaplan.frontendUrl}")
private String serviceUrl;
@Value("${plannaplan.dev}")
private boolean isDev;
@Autowired
private UserService userService;
@GetMapping("/token")
public ResponseEntity<String> getToken(@RequestParam("ticket") final String ticket) {
final CasValidator validator = new CasValidator(SERVICE_URL, ticket);
@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 {
String authority = validator.validate();
String token = this.userService.login(authority);
return new ResponseEntity<>(token, HttpStatus.OK);
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<>("Wrong ticket", HttpStatus.UNAUTHORIZED);
return new ResponseEntity<>(null, HttpStatus.UNAUTHORIZED);
} catch (UserNotFoundException e) {
return new ResponseEntity<>("User not found", HttpStatus.NOT_FOUND);
return new ResponseEntity<>(null, HttpStatus.NOT_FOUND);
} catch (Exception e) {
return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@GetMapping("/token/refresh")
@ApiOperation(value = "Endpoint to access new token based on refresh token. It's needed when request with provided token fail with code 403")
public ResponseEntity<TokenResponse> getRefreshToken(
@RequestParam("refreshToken") @ApiParam(value = "Refresh token obtained in /token request") final String refreshToken)
throws NullPointerException {
Optional<User> userResult = this.userService.getUserByRefreshToken(refreshToken);
if (userResult.isEmpty()) {
return new ResponseEntity<>(null, HttpStatus.NOT_FOUND);
}
User user = userResult.get();
user.setToken(UUID.randomUUID().toString());
user = this.userService.save(user);
return new ResponseEntity<>(new TokenResponse(user), HttpStatus.OK);
}
}

View File

@ -1,12 +1,14 @@
package com.plannaplan.controllers;
import java.util.List;
import java.util.Optional;
import com.plannaplan.App;
import com.plannaplan.entities.User;
import com.plannaplan.responses.mappers.UserResponseMappers;
import com.plannaplan.responses.models.SearchForStudentsResponse;
import com.plannaplan.responses.models.UserResponse;
import com.plannaplan.services.UserService;
import com.plannaplan.types.UserRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
@ -15,7 +17,13 @@ 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.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
@ -23,16 +31,49 @@ import org.springframework.web.bind.annotation.RequestParam;
@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("/searchForStudents")
@GetMapping("/student/search")
@PreAuthorize("hasRole('ROLE_DEANERY')")
public ResponseEntity<List<SearchForStudentsResponse>> configApp(@RequestParam("query") String query) {
@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<SearchForStudentsResponse> response = UserResponseMappers.mapToDefaultResponse(searches);
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.getAllStudents();
final List<UserResponse> response = UserResponseMappers.mapToDefaultResponse(searches);
return new ResponseEntity<>(response, HttpStatus.OK);
}
@PostMapping(path = "/admin")
@PreAuthorize("hasRole('ROLE_ADMIN')")
@ApiOperation(value = "Adds new admin user.")
public ResponseEntity<String> addAdmin(@RequestParam("authority") @ApiParam(value = "USOS ID or E-mail. If user does not exist it should be USOS ID") String authority) {
final Optional<User> userResponse = this.userService.getByAuthority(authority);
final User user = userResponse.orElseGet(() -> new User(null, null, null, authority, UserRoles.ADMIN));
user.setRole(UserRoles.ADMIN);
this.userService.save(user);
return new ResponseEntity<>("Success", HttpStatus.OK);
}
@PostMapping(path = "/deanery")
@PreAuthorize("hasRole('ROLE_ADMIN')")
@ApiOperation(value = "Adds new deanery user.")
public ResponseEntity<String> addDeanery(@RequestParam("authority") @ApiParam(value = "USOS ID or E-mail. If user does not exist it should be USOS ID") String authority) {
final Optional<User> userResponse = this.userService.getByAuthority(authority);
final User user = userResponse.orElseGet(() -> new User(null, null, null, authority, UserRoles.DEANERY));
user.setRole(UserRoles.DEANERY);
this.userService.save(user);
return new ResponseEntity<>("Success", HttpStatus.OK);
}
}

View File

@ -1,16 +1,59 @@
package com.plannaplan.responses.mappers;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import com.plannaplan.entities.Assignment;
import com.plannaplan.responses.models.GetCurrentAssignmentsResponse;
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<GetCurrentAssignmentsResponse> mapToResponse(List<Assignment> assignments) {
return assignments.stream().filter(Objects::nonNull).map(GetCurrentAssignmentsResponse::new)
.collect(Collectors.toList());
public static final List<AssignmentResponse> mapToResponse(List<Assignment> assignments) {
return mapToResponse(assignments, null);
}
public static final List<AssignmentResponse> mapToResponse(List<Assignment> assignments,
HashMap<Long, Integer> ammounts) {
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) {
if (ammounts != null) {
response.add(new AssignmentResponse(course, courseGroups.get(0), ammounts));
} else {
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();
if (ammounts != null) {
response.add(new AssignmentResponse(course, lecture, classes, ammounts));
} else {
response.add(new AssignmentResponse(course, lecture, classes));
}
}
}
return response;
}
}

View File

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

View File

@ -5,16 +5,16 @@ import java.util.Objects;
import java.util.stream.Collectors;
import com.plannaplan.entities.Course;
import com.plannaplan.responses.models.GetCoursesResponse;
import com.plannaplan.responses.models.GetCoursesWithGroupsResponse;
import com.plannaplan.responses.models.CoursesDefaultResponse;
import com.plannaplan.responses.models.CoursesWithGroupsResponse;
public class CoursesResponseMappers {
public static final List<GetCoursesResponse> mapToGetCoursesResponse(List<Course> courses) {
return courses.stream().filter(Objects::nonNull).map(GetCoursesResponse::new).collect(Collectors.toList());
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<GetCoursesWithGroupsResponse> mapToGetCoursesWithGroupsResponse(List<Course> courses) {
return courses.stream().filter(Objects::nonNull).map(GetCoursesWithGroupsResponse::new)
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,14 @@
package com.plannaplan.responses.mappers;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import com.plannaplan.entities.Exchange;
import com.plannaplan.responses.models.ExchangeResponse;
public class ExchangeResponseMappers {
public static final List<ExchangeResponse> mapToDefaultResponse(List<Exchange> exchanges) {
return exchanges.stream().filter(Objects::nonNull).map(ExchangeResponse::new).collect(Collectors.toList());
}
}

View File

@ -1,58 +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.DefaultGroupResponse;
import com.plannaplan.responses.models.GetCourseGroupsResponse;
import com.plannaplan.responses.models.WithCapacityGroupResponse;
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<DefaultGroupResponse> mapToDefaultResponse(List<Groups> groups) {
return groups.stream().filter(Objects::nonNull).map(DefaultGroupResponse::new).collect(Collectors.toList());
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<WithCapacityGroupResponse> mapToCapacityResponse(List<Groups> groups) {
return groups.stream().filter(Objects::nonNull).map(WithCapacityGroupResponse::new)
.collect(Collectors.toList());
public static List<GroupDefaultResponse> mapToDefaultResponse(List<Groups> groups) {
return GroupsMappers.mapToDefaultResponse(groups, null);
}
public static GetCourseGroupsResponse<DefaultGroupResponse> mapToGetCourseGroupsDefaultResponse (List<Groups> groups){
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());
}
List<DefaultGroupResponse> lectures = new ArrayList<>();
List<DefaultGroupResponse> classes = new ArrayList<>();
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) {
classes.add(new DefaultGroupResponse(group));
if (taken != null) {
classes.add(new GroupDefaultResponse(group, taken.get(group.getId())));
} else {
lectures.add(new DefaultGroupResponse(group));
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 GetCourseGroupsResponse<>(classes, lectures);
return new CourseWithGroupsResponse<>(classes, lectures);
}
public static GetCourseGroupsResponse<WithCapacityGroupResponse> mapToGetCourseGroupsWithCapacityResponse (List<Groups> groups){
public static CourseWithGroupsResponse<GroupDefaultResponse> mapToGetCourseGroupsDefaultResponse(
List<Groups> groups) {
return GroupsMappers.mapToGetCourseGroupsDefaultResponse(groups, null);
}
List<WithCapacityGroupResponse> lectures = new ArrayList<>();
List<WithCapacityGroupResponse> classes = new ArrayList<>();
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) {
classes.add(new WithCapacityGroupResponse(group));
if (taken != null) {
classes.add(new GroupWithCapacityResponse(group, taken.get(group.getId())));
} else {
lectures.add(new WithCapacityGroupResponse(group));
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);
}
return new GetCourseGroupsResponse<>(classes, lectures);
public static CourseWithGroupsResponse<GroupWithCapacityResponse> mapToGetCourseGroupsWithCapacityResponse(
List<Groups> groups) {
return GroupsMappers.mapToGetCourseGroupsWithCapacityResponse(groups, null);
}
}

View File

@ -5,11 +5,11 @@ import java.util.Objects;
import java.util.stream.Collectors;
import com.plannaplan.entities.User;
import com.plannaplan.responses.models.SearchForStudentsResponse;
import com.plannaplan.responses.models.UserResponse;
public class UserResponseMappers {
public static List<SearchForStudentsResponse> mapToDefaultResponse(List<User> groups) {
return groups.stream().filter(Objects::nonNull).map(SearchForStudentsResponse::new)
public static List<UserResponse> mapToDefaultResponse(List<User> groups) {
return groups.stream().filter(Objects::nonNull).map(UserResponse::new)
.collect(Collectors.toList());
}
}

View File

@ -0,0 +1,58 @@
package com.plannaplan.responses.models;
import java.util.HashMap;
import com.plannaplan.entities.Course;
import com.plannaplan.entities.Groups;
import com.plannaplan.types.GroupType;
import io.swagger.annotations.ApiModel;
@ApiModel(description = "Response shows information about given assigment to course.", value = "AssignmentResponse")
public class AssignmentResponse {
private Long id;
private String name;
private GroupWithCapacityResponse classes;
private GroupWithCapacityResponse lecture;
public AssignmentResponse(Course course, Groups lecture, Groups classes) {
this.id = course.getId();
this.name = course.getName();
this.lecture = lecture == null ? null : new GroupWithCapacityResponse(lecture);
this.classes = classes == null ? null : new GroupWithCapacityResponse(classes);
}
public AssignmentResponse(Course course, Groups lecture, Groups classes, HashMap<Long, Integer> ammounts) {
this.id = course.getId();
this.name = course.getName();
this.lecture = lecture == null ? null : new GroupWithCapacityResponse(lecture, ammounts.get(lecture.getId()));
this.classes = classes == null ? null : new GroupWithCapacityResponse(classes, ammounts.get(classes.getId()));
}
public AssignmentResponse(Course course, Groups group) {
this(course, group.getType() == GroupType.LECTURE ? group : null,
group.getType() == GroupType.CLASS ? group : null);
}
public AssignmentResponse(Course course, Groups group, HashMap<Long, Integer> ammounts) {
this(course, group.getType() == GroupType.LECTURE ? group : null,
group.getType() == GroupType.CLASS ? group : null, ammounts);
}
public GroupWithCapacityResponse getLecture() {
return this.lecture;
}
public GroupWithCapacityResponse getClasses() {
return this.classes;
}
public String getName() {
return this.name;
}
public Long getId() {
return this.id;
}
}

View File

@ -1,19 +1,41 @@
package com.plannaplan.responses.models;
import java.sql.Timestamp;
import com.plannaplan.entities.Commision;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
@ApiModel(description = "Response shows information about commision.", value = "CommisionResponse")
public class CommisionResponse {
@ApiModelProperty(value = "ID created by database")
private Long id;
private Timestamp commisionDate;
@ApiModelProperty(value = "ID of user that commision belongs to")
private UserResponse owner;
@ApiModelProperty(value = "ID of user that created commision")
private UserResponse commiter;
@ApiModelProperty(value = "Timestamp where the user commit the commision")
private String commisionDate;
public CommisionResponse(Commision commision) {
this.id = commision.getId();
this.commisionDate = commision.getCommisionDate();
this.commisionDate = commision.getCommisionDate().toString();
this.owner = commision.getCommisionOwner() != null ? new UserResponse(commision.getCommisionOwner()) : null;
this.commiter = commision.getCommisionCommiter() != null ? new UserResponse(commision.getCommisionCommiter())
: null;
}
public Timestamp getCommisionDate() {
public UserResponse getCommiter() {
return commiter;
}
public UserResponse getOwner() {
return owner;
}
public String getCommisionDate() {
return commisionDate;
}

View File

@ -0,0 +1,36 @@
package com.plannaplan.responses.models;
import java.util.List;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;
import com.plannaplan.entities.Assignment;
import com.plannaplan.entities.Commision;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
@ApiModel(description = "Response shows information about commision and its groups.", value = "CommisionWithGroupsResponse")
public class CommisionWithGroupsResponse extends CommisionResponse {
@ApiModelProperty(value = "List of groups ids in databse that belongs to commision")
private List<Long> groups;
public CommisionWithGroupsResponse(Commision commision) {
super(commision);
this.groups = commision.getAssignments().stream().filter(Objects::nonNull)
.map(new Function<Assignment, Long>() {
@Override
public Long apply(Assignment arg0) {
return arg0.getGroup().getId();
}
}).collect(Collectors.toList());
}
public List<Long> getGroups() {
return groups;
}
}

View File

@ -3,12 +3,15 @@ package com.plannaplan.responses.models;
import java.util.ArrayList;
import java.util.List;
public class GetCourseGroupsResponse <T> {
import io.swagger.annotations.ApiModel;
@ApiModel(description = "Response shows information about groups to given course.", value = "CourseWithGroupsResponse")
public class CourseWithGroupsResponse <T> {
private List<T> lectures = new ArrayList<>();
private List<T> classes = new ArrayList<>();
public GetCourseGroupsResponse(List<T> classes, List<T> lectures ){
public CourseWithGroupsResponse(List<T> classes, List<T> lectures ){
this.lectures = lectures;
this.classes = classes;
}

View File

@ -0,0 +1,15 @@
package com.plannaplan.responses.models;
import com.plannaplan.entities.Course;
import com.plannaplan.responses.models.abstracts.CoursesResponse;
import io.swagger.annotations.ApiModel;
@ApiModel(description = "Response shows information about course.", value = "CoursesDefaultResponse")
public class CoursesDefaultResponse extends CoursesResponse {
public CoursesDefaultResponse(Course course) {
super(course);
}
}

View File

@ -0,0 +1,44 @@
package com.plannaplan.responses.models;
import java.util.ArrayList;
import java.util.List;
import com.plannaplan.entities.Course;
import com.plannaplan.responses.models.abstracts.CoursesResponse;
import com.plannaplan.types.GroupType;
import io.swagger.annotations.ApiModel;
@ApiModel(description = "Response shows information about groups to given course.", value = "CoursesWithGroupsResponse")
public class CoursesWithGroupsResponse extends CoursesResponse {
private List<GroupWithCapacityResponse> lectures = new ArrayList<>();
private List<GroupWithCapacityResponse> classes = new ArrayList<>();
public CoursesWithGroupsResponse(Course course) {
super(course);
course.getGroups().stream().forEach(group -> {
if (group.getType() == GroupType.CLASS) {
this.classes.add(new GroupWithCapacityResponse(group));
} else {
this.lectures.add(new GroupWithCapacityResponse(group));
}
});
}
public CoursesWithGroupsResponse(Course course, List<GroupWithCapacityResponse> lectures,
List<GroupWithCapacityResponse> classes) {
super(course);
this.lectures = lectures;
this.classes = classes;
}
public List<GroupWithCapacityResponse> getClasses() {
return this.classes;
}
public List<GroupWithCapacityResponse> getLectures() {
return this.lectures;
}
}

View File

@ -1,53 +0,0 @@
package com.plannaplan.responses.models;
import com.plannaplan.entities.Assignment;
import com.plannaplan.entities.Groups;
import com.plannaplan.types.GroupType;
public class DefaultGroupResponse {
private Long id;
private int day;
private String time;
private String lecturer;
private String room;
private GroupType type;
public DefaultGroupResponse(Groups group) {
this.id = group.getId() != null ? group.getId() : null;
this.day = group.getDay() != null ? group.getDay().label : -1;
this.time = group.getTimeString() != null ? group.getTimeString() : "";
this.lecturer = group.getLecturer() != null ? group.getLecturer().toString() : "";
this.room = group.getRoom() != null ? group.getRoom() : "";
this.type = group.getType() != null ? group.getType() : null;
}
public DefaultGroupResponse(Assignment assignment) {
this(assignment.getGroup());
}
public GroupType getType() {
return type;
}
public String getRoom() {
return room;
}
public String getLecturer() {
return lecturer;
}
public String getTime() {
return time;
}
public int getDay() {
return day;
}
public Long getId() {
return id;
}
}

View File

@ -0,0 +1,36 @@
package com.plannaplan.responses.models;
import com.plannaplan.entities.Exchange;
public class ExchangeResponse {
private Long id;
private GroupDefaultResponse ownedAssignment;
private GroupDefaultResponse desiredGroup;
public ExchangeResponse(Exchange exchange){
this.id = exchange.getId();
this.ownedAssignment = new GroupDefaultResponse(exchange.getOwnedAssignment().getGroup());
this.desiredGroup = new GroupDefaultResponse(exchange.getDesiredAssignment());
}
public GroupDefaultResponse getDesiredGroup() {
return desiredGroup;
}
public void setDesiredGroup(GroupDefaultResponse desiredGroup) {
this.desiredGroup = desiredGroup;
}
public GroupDefaultResponse getOwnedAssignment() {
return ownedAssignment;
}
public void setOwnedAssignment(GroupDefaultResponse ownedAssignment) {
this.ownedAssignment = ownedAssignment;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}

View File

@ -1,12 +0,0 @@
package com.plannaplan.responses.models;
import com.plannaplan.entities.Course;
import com.plannaplan.responses.models.abstracts.CoursesResponse;
public class GetCoursesResponse extends CoursesResponse {
public GetCoursesResponse(Course course) {
super(course);
}
}

View File

@ -1,34 +0,0 @@
package com.plannaplan.responses.models;
import java.util.ArrayList;
import java.util.List;
import com.plannaplan.entities.Course;
import com.plannaplan.responses.models.abstracts.CoursesResponse;
import com.plannaplan.types.GroupType;
public class GetCoursesWithGroupsResponse extends CoursesResponse {
private List<DefaultGroupResponse> lectures = new ArrayList<>();
private List<DefaultGroupResponse> classes = new ArrayList<>();
public GetCoursesWithGroupsResponse(Course course) {
super(course);
course.getGroups().stream().forEach(group -> {
if (group.getType() == GroupType.CLASS) {
this.classes.add(new DefaultGroupResponse(group));
} else {
this.lectures.add(new DefaultGroupResponse(group));
}
});
}
public List<DefaultGroupResponse> getClasses() {
return this.classes;
}
public List<DefaultGroupResponse> getLectures() {
return this.lectures;
}
}

View File

@ -1,11 +0,0 @@
package com.plannaplan.responses.models;
import com.plannaplan.entities.Assignment;
public class GetCurrentAssignmentsResponse extends WithCapacityGroupResponse {
public GetCurrentAssignmentsResponse(Assignment assignment) {
super(assignment);
}
}

View File

@ -0,0 +1,90 @@
package com.plannaplan.responses.models;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.plannaplan.entities.Assignment;
import com.plannaplan.entities.Groups;
import com.plannaplan.types.GroupType;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
@JsonInclude(JsonInclude.Include.NON_NULL)
@ApiModel(description = "Response shows information about given group.", value = "GroupDefaultResponse")
public class GroupDefaultResponse {
@ApiModelProperty(value = "ID created by database.")
private Long id;
@ApiModelProperty(value = "Value shows what day when the course is. Example 0 is Monday.")
private int day;
@ApiModelProperty(value = "Value shows time when the course takes.")
private String time;
@ApiModelProperty(value = "Value shows time when the course ends.")
private String endTime;
@ApiModelProperty(value = "Value shows degree, name and surname.")
private String lecturer;
@ApiModelProperty(value = "Value shows room where the class takes.")
private String room;
@ApiModelProperty(value = "Value shows kind of group. The types are LECTURE or CLASS.")
private GroupType type;
@ApiModelProperty(value = "Value shows how many places is already taken by other students.")
private Integer takenPlaces;
public GroupDefaultResponse(Groups group) {
this.id = group.getId() != null ? group.getId() : null;
this.day = group.getDay() != null ? group.getDay().label : -1;
this.time = group.getTimeString() != null ? group.getTimeString() : "";
this.endTime = group.getEndTimeString() != null ? group.getEndTimeString() : "";
this.lecturer = group.getLecturer() != null ? group.getLecturer().toString() : "";
this.room = group.getRoom() != null ? group.getRoom() : "";
this.type = group.getType() != null ? group.getType() : null;
}
public GroupDefaultResponse(Groups group, int takenPlaces) {
this(group);
this.takenPlaces = takenPlaces;
}
public GroupDefaultResponse(Assignment assignment) {
this(assignment.getGroup());
}
public GroupType getType() {
return type;
}
public String getRoom() {
return room;
}
public String getLecturer() {
return lecturer;
}
public String getTime() {
return time;
}
public String getEndTime() {
return endTime;
}
public int getDay() {
return day;
}
public Long getId() {
return id;
}
public Integer getTakenPlaces() {
return this.takenPlaces;
}
}

View File

@ -0,0 +1,34 @@
package com.plannaplan.responses.models;
import com.plannaplan.entities.Assignment;
import com.plannaplan.entities.Groups;
import io.swagger.annotations.ApiModel;
@ApiModel(description = "Response shows information about group with included capacity.", value = "GroupWithCapacityResponse")
public class GroupWithCapacityResponse extends GroupDefaultResponse {
private int capacity;
public GroupWithCapacityResponse(Groups group) {
super(group);
this.capacity = group.getCapacity();
}
public GroupWithCapacityResponse(Groups group, int takenPlaces) {
super(group, takenPlaces);
this.capacity = group.getCapacity();
}
public GroupWithCapacityResponse(Assignment assignment) {
this(assignment.getGroup());
}
public GroupWithCapacityResponse(Assignment assignment, int takenPlaces) {
this(assignment.getGroup(), takenPlaces);
}
public int getCapacity() {
return capacity;
}
}

View File

@ -0,0 +1,49 @@
package com.plannaplan.responses.models;
import com.plannaplan.entities.User;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
@ApiModel(description = "Response shows information about logged user.", value = "TokenResponse")
public class TokenResponse {
@ApiModelProperty(value = "user token used to verify requests")
private String token;
@ApiModelProperty(value = "user token needed to refresh")
private String refreshToken;
@ApiModelProperty(value = "user id in database")
private Long id;
@ApiModelProperty(value = "user app role")
private String authorityRole;
@ApiModelProperty(value = "user unviersity email")
private String email;
public TokenResponse(User user) {
this.id = user.getId();
this.authorityRole = user.getRole().toString();
this.email = user.getEmail();
this.token = user.getToken();
this.refreshToken = user.getRefreshToken();
}
public String getEmail() {
return email;
}
public String getAuthorityRole() {
return authorityRole;
}
public Long getId() {
return id;
}
public String getToken() {
return token;
}
public String getRefreshToken() {
return this.refreshToken;
}
}

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