Compare commits

..

523 Commits

Author SHA1 Message Date
cacd5ec742 Add validation for having pending operations while app installation (#550)
## Purpose
Fixes https://roadmap.entgra.net/issues/11578

Co-authored-by: prathabanKavin <kavinprathaban025@gmail.com>
Reviewed-on: https://repository.entgra.net/community/device-mgt-core/pulls/550
Co-authored-by: Kavin Prathaban <kavin@entgra.io>
Co-committed-by: Kavin Prathaban <kavin@entgra.io>
2024-12-03 09:08:22 +00:00
subodhinie
91909aeda6 Add OS updates install scope for Windows operations (#559)
Fixes for https://roadmap.entgra.net/issues/11689

Co-authored-by: Subodhinie <subodhinie@entgra.io>
Reviewed-on: https://repository.entgra.net/community/device-mgt-core/pulls/559
Co-authored-by: subodhinie <subodhinie@entgra.io>
Co-committed-by: subodhinie <subodhinie@entgra.io>
2024-12-03 08:18:58 +00:00
Sathira Perera
7eb53adca9 Enrolled devices should be shown with latest first (#544)
Co-authored-by: sathira <Sathira@entgra.io>
Reviewed-on: https://repository.entgra.net/community/device-mgt-core/pulls/544
Co-authored-by: Sathira Perera <sathira@entgra.io>
Co-committed-by: Sathira Perera <sathira@entgra.io>
2024-12-02 15:35:36 +00:00
Lasantha Dharmakeerthi
9e34ec99aa Optimize FCM token refreshing 2024-12-02 06:16:31 +00:00
Lasantha Dharmakeerthi
23cea99d2d Add agent install scope 2024-11-30 03:05:24 +00:00
Jenkins
6e2b8b3b03 [maven-release-plugin] prepare for next development iteration 2024-11-29 17:40:51 +00:00
Jenkins
2fde5c375d [maven-release-plugin] prepare release v6.0.0 2024-11-29 17:40:44 +00:00
cedc8ab441 Optimize FCM token refreshing 2024-11-28 18:24:53 +05:30
Lasantha Dharmakeerthi
23fd74771a Upgrade JAVA version to JAVA 11 2024-11-25 17:43:08 +00:00
Rajitha Kumara
27d88f950c Upgrade java version to 11 2024-11-25 23:07:52 +05:30
Rajitha Kumara
81e7b4693b Downgrade maven bundle plugin version 2024-11-21 22:52:54 +05:30
Rajitha Kumara
d91ceb81e9 Fix feature installtion issues 2024-11-21 22:52:54 +05:30
tcdlpds
32dfe57fab Upgrade dependency versions 2024-11-21 22:52:53 +05:30
navodzoysa
3a2ebda47b Add agent install scope 2024-11-13 17:24:02 +05:30
Lasantha Dharmakeerthi
7d91cfff3c Fix error response formatting issue and NullPointerException when getting a fileName with a query param 2024-11-12 17:41:39 +00:00
nipuni
ba3e4623df Fix NullPointerException in getFileMetaEntry method for URLs with chunked transfer encoding. 2024-11-12 20:28:09 +05:30
nipuni
5853e529c7 Fix throwing NullPointerException when getting a fileName with a query param. 2024-11-12 20:25:57 +05:30
nipuni
16b7c4f3e7 Fix error response formatting issue. 2024-11-12 20:21:26 +05:30
Lasantha Dharmakeerthi
860470832f Fix test case failure when extracting cert from signature 2024-11-08 02:22:52 +00:00
Lasantha Dharmakeerthi
a10bdd1d05 Scopes related to tagging feature 2024-11-06 13:17:47 +00:00
uddhika
3094743045 Merge remote-tracking branch 'origin/uddhika-device-mgt' into uddhika-device-mgt 2024-11-06 18:43:46 +05:30
uddhika
85d7ed641a removed new line 2024-11-06 18:43:35 +05:30
Uddhika Ishara
663df92b42 Merge branch 'master' into uddhika-device-mgt 2024-11-06 11:53:28 +00:00
uddhika
bd8ecb8718 further added scope lines 2024-11-06 17:22:46 +05:30
uddhika
4792f4af72 fixes scope lines 2024-11-06 17:18:45 +05:30
uddhika
ae4978cee8 scopes related to tagging feature 2024-11-06 17:16:59 +05:30
navodzoysa
1aa32528b0 Fix test case failure when extracting cert from signature 2024-11-06 15:31:44 +05:30
Lasantha Dharmakeerthi
66c9c4f4e6 Fix Device statuses intermittently not saving issue 2024-10-31 05:13:00 +00:00
Arshana
b2b4c5c676 Add scpeific instructions in java doc comment 2024-10-31 10:36:03 +05:30
Lasantha Dharmakeerthi
7f06804823 Fix client cert verification issue in sub tenants 2024-10-29 04:55:29 +00:00
navodzoysa
00633e34f5 Fix client cert verification issue in sub tenants 2024-10-29 03:59:32 +05:30
Lasantha Dharmakeerthi
a2d9da923b Improved SQL query with DESC sorting 2024-10-28 13:59:53 +00:00
Lasantha Dharmakeerthi
09b9dd3ded Fix login issues in sub tenants 2024-10-24 02:45:02 +00:00
Navod Zoysa
3d872e3b72 Merge pull request 'Remove unused windows os updates scopes' (#535) from subodhinie/device-mgt-core:os_updates into master
Reviewed-on: https://repository.entgra.net/community/device-mgt-core/pulls/535
2024-10-23 15:46:45 +00:00
Navod Zoysa
66f6982098 Merge pull request 'Fix missing commit by moving transaction commit after metadata update.' (#532) from nipuni/device-mgt-core:11963 into master
Reviewed-on: https://repository.entgra.net/community/device-mgt-core/pulls/532
2024-10-23 14:50:10 +00:00
Subodhinie
0e82c9c304 Remove unused windows os updates scopes 2024-10-23 16:57:32 +05:30
20df0c879f Improved SQL query with DESC sorting 2024-10-23 09:13:59 +05:30
Rajitha Kumara
8f47c448bd Fix login issues in sub tenants 2024-10-22 14:32:49 +05:30
nipuni
b7e0580112 Fix missing commit by moving transaction commit after metadata update. 2024-10-21 13:53:27 +05:30
Lasantha Dharmakeerthi
a45820e845 Remove code quality check from PRs 2024-10-18 18:29:14 +00:00
Lasantha Dharmakeerthi
337f26446b Fix the validation issue when the APK file and screenshot names contain spaces 2024-10-16 06:47:22 +00:00
nipuni
cba9f7ce08 Fix the validation issue when the APK file and screenshot names contain spaces 2024-10-16 11:24:46 +05:30
prathabanKavin
0ac795903f Remove code quality check from PRs 2024-10-14 11:24:02 +05:30
Navod Zoysa
a6d46429e8 Merge pull request 'Add credentials name instead of cred ids' (#524) from prathabanKavin/device-mgt-core:jenfilequick into master
Reviewed-on: https://repository.entgra.net/community/device-mgt-core/pulls/524
2024-10-07 10:09:42 +00:00
prathabanKavin
f13342493d Add credentials name instead of cred ids 2024-10-07 15:34:56 +05:30
Lasantha Dharmakeerthi
32b385fc75 Fix issues with bundle imports 2024-10-05 19:19:10 +00:00
Charitha Goonetilleke
a903ff4313 Merge branch 'master' into master 2024-10-05 14:33:37 +00:00
cec3ff580e Merge pull request 'Add client certificate authentication for Windows' (#500) from navodzoysa/device-mgt-core:issue-10462/secure-pending-operation into master
Reviewed-on: https://repository.entgra.net/community/device-mgt-core/pulls/500
2024-10-04 05:42:10 +00:00
Lasantha Dharmakeerthi
b8a9b0be83 Add improvements for Allowed Device Status View 2024-10-03 18:37:05 +00:00
nipuni
10e647efb3 Add improvements for Allowed Device Status View 2024-10-02 11:06:55 +05:30
Charitha Goonetilleke
f8719c6dc4 Merge remote-tracking branch 'upstream/master' 2024-10-01 14:29:50 +05:30
Lasantha Dharmakeerthi
94371ce586 Add 204 status code and delete method json body handling in ui-request-handle 2024-10-01 08:58:49 +00:00
uddhika
a3178971e1 Merge remote-tracking branch 'origin/tagchange' into tagchange 2024-10-01 14:26:34 +05:30
uddhika
634763a6db changes to 204 status code handling 2024-10-01 14:26:20 +05:30
Charitha Goonetilleke
099d98ebfb Merge branch 'master' of ssh://repository.entgra.net:222/community/device-mgt-core
# Conflicts:
#	components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/pom.xml
2024-10-01 14:01:49 +05:30
Charitha Goonetilleke
900a707ce7 Fix issues with bundle imports 2024-10-01 14:00:35 +05:30
Lasantha Dharmakeerthi
c78d272bb8 Add device status filters updating logic (#519)
Co-authored-by: tcdlpds <tcdlpds@gmail.com>
Reviewed-on: https://repository.entgra.net/community/device-mgt-core/pulls/519
Co-authored-by: Lasantha Dharmakeerthi <lasantha@entgra.io>
Co-committed-by: Lasantha Dharmakeerthi <lasantha@entgra.io>
2024-10-01 08:23:04 +00:00
Lasantha Dharmakeerthi
3eced40f98 Bump version to 6.0.0-SNAPSHOT 2024-10-01 08:10:06 +00:00
Charitha Goonetilleke
08a6917d53 Remove old configs 2024-10-01 07:22:54 +05:30
Charitha Goonetilleke
da90ca8973 Bump version to 6.0.0-SNAPSHOT 2024-10-01 05:07:36 +05:30
Charitha Goonetilleke
721dc8753a Merge branch 'master' into tagchange 2024-09-30 22:06:13 +00:00
Lasantha Dharmakeerthi
600e865c8a Add jenkins file for PR review 2024-09-30 11:05:49 +00:00
Lasantha Dharmakeerthi
c5fd475d17 Add docUrl into metadata 2024-09-30 08:22:17 +00:00
nipuni
930f555835 Add docUrl into metadata. 2024-09-30 13:43:06 +05:30
prathabanKavin
aa35121a03 Add jenkins file for PR review 2024-09-25 16:51:52 +05:30
Navod Zoysa
c8528b68ab Merge pull request 'Fix warning message showing in login page' (#516) from tcdlpds/device-mgt-core:master into master
Reviewed-on: https://repository.entgra.net/community/device-mgt-core/pulls/516
2024-09-24 05:14:11 +00:00
tcdlpds
50a952a1fa Fix warning message showing in login page 2024-09-24 06:34:10 +05:30
Lasantha Dharmakeerthi
11ef711c5c Fix for the incorrect pagination in the group subscription details table 2024-09-21 04:23:38 +00:00
258b312a49 Set limit and offset to -1 for retrieving all device details
Updated the logic to set limit and offset values to -1 when fetching
device details, ensuring that all devices are retrieved. Without this
change, only the devices within the paginated range were being
fetched.

This change removes the pagination constraint, allowing retrieval of
all devices in the system.
2024-09-21 07:50:48 +05:30
Lasantha Dharmakeerthi
df129651fd Fix for the incorrect device statistics shown in the app store 2024-09-20 04:37:46 +00:00
uddhika
fe8b784cdf 204 status code and delete method json body handling 2024-09-20 09:04:28 +05:30
230192f2d9 Completed the requested changes 2024-09-19 23:05:52 +05:30
9107efb3a6 Added a method to get the device count based on app os type with group 2024-09-19 23:05:52 +05:30
Lasantha Dharmakeerthi
b40c5a625d Fix usage generation in billing 2024-09-19 10:40:57 +00:00
osh.silva
a2b8b8bda2 Remove unwanted connection 2024-09-19 14:17:26 +05:30
osh.silva
70f5a99e60 Merge branch 'master' of ssh://repository.entgra.net:222/community/device-mgt-core into usage-11591 2024-09-19 13:55:45 +05:30
a161791fc0 Added a method to retrieve the device count based on application type 2024-09-19 12:43:39 +05:30
Lasantha Dharmakeerthi
78e07f3154 Add improvements for the TenantMgtServiceComponent 2024-09-18 05:47:24 +00:00
nipuni
5cba2d6a81 Add improvements for the TenantMgtServiceComponent. 2024-09-18 11:15:50 +05:30
Lasantha Dharmakeerthi
97ee77fc19 Fix compilation failure 2024-09-11 22:35:48 +00:00
navodzoysa
b61af92293 Fix compile failure 2024-09-12 00:26:15 +05:30
Navod Zoysa
35f02ba7ac Merge pull request 'Improve device status management service' (#510) from tcdlpds/device-mgt-core:master into master
Reviewed-on: https://repository.entgra.net/community/device-mgt-core/pulls/510
2024-09-11 18:26:19 +00:00
tcdlpds
c6905b968e Improve device status management service 2024-09-11 23:26:43 +05:30
Lasantha Dharmakeerthi
7a54b16cc9 Add missing cope 2024-09-11 11:39:40 +00:00
0609b3a9c2 Used constants instead of hardcoding 2024-09-11 07:21:33 +05:30
Arshana
30837f2f3d Add missing cope 2024-09-10 10:02:26 +05:30
6934827920 Fixed the incorrect device statistics issue happening due to REMOVED and DELETED devices. 2024-09-10 07:28:29 +05:30
2da8cdd05f Fixed the incorrect device statistics issue happening due to REMOVED and DELETED devices. 2024-09-10 07:25:08 +05:30
Lasantha Dharmakeerthi
a42e4ec411 Add special warning message for Factory Reset, Enterprise Wipe, Disneroll operations. 2024-09-09 02:56:26 +00:00
nipuni
77a521e550 Add special warning message for Factory Reset, Enterprise Wipe, disneroll operations. 2024-09-06 23:10:04 +05:30
Lasantha Dharmakeerthi
00686e75d1 Update operations status when serve startup 2024-09-05 06:16:51 +00:00
pasindu
0272bda2ce Get server startup handlers to a single point in device-mgt core 2024-09-05 09:40:52 +05:30
pasindu
87b98a6cb5 Use try with resources for dao layer 2024-09-03 09:46:05 +05:30
pasindu
6d324c084a Throw msg and the exception in relevent places 2024-09-03 09:45:07 +05:30
pasindu
f59208f6e7 Save OperationStartupHandler in data holder 2024-09-03 09:44:11 +05:30
Lasantha Dharmakeerthi
f14e2cecdf Add tool tip component to operation features 2024-09-03 04:02:13 +00:00
osh.silva
21290dfba6 Merge branch 'master' of ssh://repository.entgra.net:222/community/device-mgt-core into secure-folder-policy 2024-09-03 00:41:28 +05:30
osh.silva
59056cc8ff Add tooltip component to features 2024-09-03 00:40:45 +05:30
pasindu
c37cf31ffe Update operations status when serve startup 2024-09-02 13:27:49 +05:30
Lasantha Dharmakeerthi
f58721b3b6 Implement the search API for Subscription details view 2024-09-02 05:55:45 +00:00
Lasantha Dharmakeerthi
470f9c52a3 Fix search by middle part of the username is not working in uninstall table in app store 2024-09-02 04:39:23 +00:00
nipuni
320d5215de Implement the search API for Subscription details view 2024-08-30 22:54:59 +05:30
Lasantha Dharmakeerthi
dec953b638 Update release rating data type 2024-08-30 12:30:06 +00:00
Rajitha Kumara
9ce605d883 Update release rating data type 2024-08-30 17:43:32 +05:30
Lasantha Dharmakeerthi
974fc46e54 Fix data type inconsistency in tag db scripts 2024-08-30 01:56:07 +00:00
nipuni
afa3294555 Fix search by middle part of the username is not working in uninstall table in app store. 2024-08-30 06:21:10 +05:30
Gimhan-minion
b8542bfffd Fix data type inconsistency in tag db scripts 2024-08-30 01:44:40 +05:30
Lasantha Dharmakeerthi
16365f95a0 Add release version report getting function 2024-08-28 19:07:59 +00:00
Rajitha Kumara
476fe5f849 Add release version report supportablility 2024-08-28 19:18:00 +05:30
navodzoysa
31e9a6e457 Add client certificate authentication for Windows 2024-08-27 21:35:52 +05:30
Navod Zoysa
35ab8ceb97 Merge pull request 'Fix enroll-web-agent login issue' (#499) from rajitha/device-mgt-core:final-apim420 into master
Reviewed-on: https://repository.entgra.net/community/device-mgt-core/pulls/499
2024-08-26 10:49:13 +00:00
Rajitha Kumara
55f5865726 Fix enroll-web-agent login issue 2024-08-26 14:35:08 +05:30
Lasantha Dharmakeerthi
e79a512cf6 Migrate to APIM 420 2024-08-24 03:41:42 +00:00
Lasantha Dharmakeerthi
45b90a4749 Sync with master 2024-08-23 02:03:55 +00:00
tcdlpds
ec4e8255a2 Sync with master 2024-08-23 06:46:33 +05:30
Lasantha Dharmakeerthi
fa4d466798 Implement Device Tagging Feature 2024-08-23 01:01:28 +00:00
Gimhan-minion
cfa40c0d2b Fix tag feature modifications after review 2024-08-22 18:08:15 +05:30
Lasantha Dharmakeerthi
2cc7f8ccb7 Sync with master 2024-08-22 04:06:37 +00:00
Rajitha Kumara
0f58430717 Sync with master 2024-08-22 09:30:19 +05:30
Lasantha Dharmakeerthi
52ea270e9f Fix permission updating issue 2024-08-21 16:29:33 +00:00
Rajitha Kumara
1e20b3d15c Fix permission updating issue 2024-08-21 09:40:42 +05:30
Charitha Goonetilleke
5a12dc7601 Fix logic issue with user authorization validation for groups
Co-authored-by: Charitha Goonetilleke <charitha@entgra.io>
Co-committed-by: Charitha Goonetilleke <charitha@entgra.io>
2024-08-21 03:09:48 +00:00
Gimhan-minion
8d2fb5fa76 Fix tenant id constraint in DM_TAG table 2024-08-20 11:59:39 +05:30
Gimhan-minion
295f1831d8 Initialize device tag feature updated req changes 2024-08-17 19:41:48 +05:30
Lasantha Dharmakeerthi
19287b515f Change the return type of the app lifecycle's updated time 2024-08-16 06:14:04 +00:00
Gimhan-minion
5e1bfd6d9a Initialize device tag feature 2024-08-16 04:18:56 +05:30
Gimhan-minion
07794f97d9 Initialize device tag feature 2024-08-16 04:18:52 +05:30
tcdlpds
bc81c8923c Change the return type of the app lifecycle's updated time
If the API returns Timestamp object it creates from the Unix timestamp (in milliseconds), but its string representation depends on the JVM’s default timezone. Therefore it returns timestamp based on JVM's timezone. Since it is required to return UTC time, changed the data type and returns the long value. With this improvement it is guaranteed that client gets the UTC time of the app lifecycle's updated time.
2024-08-15 20:21:31 +05:30
Lasantha Dharmakeerthi
4660b59c97 Add improvements for api publishing procedure 2024-08-14 19:48:48 +00:00
Rajitha Kumara
db1f12ea88 Improve retrying logic and refactor the code 2024-08-15 01:13:20 +05:30
Rajitha Kumara
c6f65d9675 Refactor the code 2024-08-14 23:28:42 +05:30
Rajitha Kumara
26d4ffdf8a Add improvements for api publishing procedure 2024-08-14 23:28:38 +05:30
Lasantha Dharmakeerthi
0cd0d98ecd Sync with master 2024-08-14 13:50:13 +00:00
tcdlpds
a4f1f64a70 Sync with master 2024-08-14 17:11:34 +05:30
Lasantha Dharmakeerthi
152b1ad929 Fix default scopes not updating issue 2024-08-14 06:09:24 +00:00
Rajitha Kumara
e384adc657 Fix default scopes not updating issue 2024-08-14 09:30:01 +05:30
Lasantha Dharmakeerthi
8d685382e3 Fix inconsistencies with subtypes and operation templates 2024-08-12 12:15:23 +00:00
Charitha Goonetilleke
a4138b4778 Fix inconsistencies with subtypes and operation templates 2024-08-12 16:32:02 +05:30
Lasantha Dharmakeerthi
34a9aa7431 Add FCM request improvements 2024-08-09 04:53:56 +00:00
7f8f6d6f75 Add FCM request improvements 2024-08-09 09:41:24 +05:30
Lasantha Dharmakeerthi
d1a9fbe67d Add supported operations param to subtype 2024-08-09 03:52:58 +00:00
Charitha Goonetilleke
57e05b4ca9 Add supported operations param to subtype 2024-08-09 09:15:46 +05:30
Lasantha Dharmakeerthi
2348e92326 Refactor source 2024-08-08 15:17:46 +00:00
tcdlpds
b284bf1276 Refactor source 2024-08-08 20:44:53 +05:30
Lasantha Dharmakeerthi
289f6ef352 Improve tenant deleting logic 2024-07-31 08:53:16 +00:00
tcdlpds
e1594c00f1 Improve tenant deleting logic 2024-07-31 14:17:41 +05:30
Lasantha Dharmakeerthi
0ae083b8ed Fix server starting issue 2024-07-30 19:06:39 +00:00
tcdlpds
56f864a3f5 Fix server starting issue 2024-07-31 00:35:02 +05:30
Lasantha Dharmakeerthi
cafa88a866 Sync with master 2024-07-30 04:26:08 +00:00
tcdlpds
2d49cfe2c8 Sync with master branch 2024-07-30 08:51:34 +05:30
osh.silva
a472f73adc Fix status connection issue 2024-07-29 23:44:18 +05:30
osh.silva
101c096859 Merge branch 'master' of ssh://repository.entgra.net:222/community/device-mgt-core into usage-11591 2024-07-29 16:21:13 +05:30
osh.silva
748c28d368 Fix ambigous column error 2024-07-29 16:21:01 +05:30
builder
fa24f95a69 [maven-release-plugin] prepare for next development iteration 2024-07-25 16:34:08 +05:30
builder
5f94113adf [maven-release-plugin] prepare release v5.2.3 2024-07-25 16:34:01 +05:30
Jenkins
770575999e [maven-release-plugin] prepare for next development iteration 2024-07-24 21:34:16 +05:30
Jenkins
41985cc347 [maven-release-plugin] prepare release v5.2.2 2024-07-24 21:34:10 +05:30
Lasantha Dharmakeerthi
23af900343 Fix device count issues in subscription view 2024-07-24 11:24:11 +00:00
prathabanKavin
8a24255089 Fix device count issues in subscription view 2024-07-24 16:20:17 +05:30
Lasantha Dharmakeerthi
56231e5a7e Fix search issues 2024-07-24 07:44:24 +00:00
osh.silva
d2d341963d Fix search issues 2024-07-24 13:05:41 +05:30
Jenkins
b1ff511d4c [maven-release-plugin] prepare for next development iteration 2024-07-23 22:30:33 +05:30
Jenkins
0deebf09d8 [maven-release-plugin] prepare release v5.2.1 2024-07-23 22:30:27 +05:30
Lasantha Dharmakeerthi
a6e55516f2 Update unsubscribed status check 2024-07-23 16:35:53 +00:00
Rajitha Kumara
78cb44d708 Update unsubscribed status check 2024-07-23 21:10:54 +05:30
Lasantha Dharmakeerthi
b5adeff7ab Update generic device dao 2024-07-23 14:14:49 +00:00
Rajitha Kumara
8f8e5e67d4 Update generic device dao 2024-07-23 19:35:34 +05:30
Lasantha Dharmakeerthi
8f6d213154 Fix issues related to new devices and stats 2024-07-23 13:28:08 +00:00
Rajitha Kumara
c480512f10 Fix issues related to new devices and stats 2024-07-23 18:48:20 +05:30
Lasantha Dharmakeerthi
d4c9f94bd9 Validate billing cost 2024-07-23 06:38:07 +00:00
osh.silva
3112fd92a6 Validate billing cost 2024-07-23 11:59:13 +05:30
Nipuni Kavindya
f585e37d61 Fix build failure
Co-authored-by: Nipuni Kavindya <nipuni@entgra.io>
Co-committed-by: Nipuni Kavindya <nipuni@entgra.io>
2024-07-23 03:51:33 +00:00
Rajitha Kumara
40c12875ac Improve APPM subscription data retrieving logic
Co-authored-by: Rajitha Kumara <rajitha@entgra.io>
Co-committed-by: Rajitha Kumara <rajitha@entgra.io>
2024-07-22 20:44:09 +00:00
Lasantha Dharmakeerthi
d53ab7cea2 Fix space in getAppCount query 2024-07-22 04:35:24 +00:00
prathabanKavin
fa400f8995 Fix space in getAppCount query 2024-07-22 09:56:37 +05:30
Lasantha Dharmakeerthi
ac9c7b1a38 Fix stream corrupted exception for profile type operations 2024-07-21 21:23:28 +00:00
navodzoysa
71eae764ce Fix stream corrupted exception for profile type operations 2024-07-22 02:07:16 +05:30
Lasantha Dharmakeerthi
3d281de94a Sync with master 2024-07-18 16:27:43 +00:00
Lasantha Dharmakeerthi
a7ed2a2423 Fix devices not loading in web apps 2024-07-18 16:21:22 +00:00
7b0f12b890 Fix devices not loading in web apps 2024-07-18 13:45:39 +05:30
Lasantha Dharmakeerthi
9f809d04a4 Fix devices not loading for web apps 2024-07-18 07:37:59 +00:00
8a8846be5a Fix devices not loading in web apps 2024-07-18 12:26:19 +05:30
30f685cce8 Merge pull request 'Fix: Send EVENT_REVOKE when a group is removed from a geofence' (#454) from waruni/device-mgt-core:geofence-revoke-fix into master
Reviewed-on: https://repository.entgra.net/community/device-mgt-core/pulls/454
2024-07-17 09:01:37 +00:00
waruni
7be828a556 Add EVENT REVOKE operation for groupIds to delete 2024-07-17 11:52:35 +05:30
Oshani Silva
8b6eee0a97 Add fix for group subscription table
Co-authored-by: Oshani Silva <oshani@entgra.io>
Co-committed-by: Oshani Silva <oshani@entgra.io>
2024-07-17 05:42:24 +00:00
tcdlpds
211ed7a489 Sync with master 2024-07-16 18:49:54 +05:30
tcdlpds
3d5f4004d0 Sync with master 2024-07-16 17:56:15 +05:30
Jenkins
e062bf79dc [maven-release-plugin] prepare for next development iteration 2024-07-16 08:04:47 +05:30
Jenkins
6d1414d09f [maven-release-plugin] prepare release v5.2.0 2024-07-16 08:04:39 +05:30
subodhinie
0ca4d025ee Add Windows device operation scope: os-updates-info (#406)
Co-authored-by: Subodhinie <subodhinie@entgra.io>
Reviewed-on: https://repository.entgra.net/community/device-mgt-core/pulls/406
Co-authored-by: subodhinie <subodhinie@entgra.io>
Co-committed-by: subodhinie <subodhinie@entgra.io>
2024-07-15 11:07:55 +00:00
Lasantha Dharmakeerthi
22cbc529f6 Add default case in CategorizedSubscriptionResult constructor 2024-07-15 09:42:59 +00:00
nipuni
7496415ab3 Add default case in CategorizedSubscriptionResult constructor. 2024-07-15 13:24:45 +05:30
Lasantha Dharmakeerthi
08e9625373 Fix searching issue in installation details in app store 2024-07-15 07:26:50 +00:00
nipuni
9561e003bf Fix filtering by device name not working with all and device subscriptions 2024-07-15 09:14:20 +05:30
nipuni
f0fafde0d2 Merge branch 'master' of https://repository.entgra.net/community/device-mgt-core into #11464
# Conflicts:
#	components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/SubscriptionManagerImpl.java
#	components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/EnrollmentDAO.java
#	components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/GroupDAO.java
#	components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/AbstractEnrollmentDAOImpl.java
#	components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/AbstractGroupDAOImpl.java
#	components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/service/DeviceManagementProviderService.java
#	components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/service/DeviceManagementProviderServiceImpl.java
#	components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/service/GroupManagementProviderService.java
#	components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/service/GroupManagementProviderServiceImpl.java
2024-07-13 21:36:24 +05:30
nipuni
22f8497952 Fix Search is not working in installation details in app store 2024-07-13 21:05:41 +05:30
290952ae53 Merge pull request 'Add capability to search policies by device type' (#339) from ashvini/device-mgt-core:Improvement#10585 into master
Reviewed-on: https://repository.entgra.net/community/device-mgt-core/pulls/339
2024-07-12 06:14:38 +00:00
ashvini
8a82d1666c Add capability to search policies by device type
Resolve comments

Resolve comments

Remove unnecessary changes
2024-07-12 09:20:35 +05:30
Lasantha Dharmakeerthi
3342bc8cc6 Add policy type conversion from BLOB to Text DB scripts 2024-07-11 18:51:02 +00:00
020c397769 Merge pull request 'Fix same device data loading for subscriptions' (#450) from prathabanKavin/device-mgt-core:devicelinkrejectfix into master
Reviewed-on: https://repository.entgra.net/community/device-mgt-core/pulls/450
2024-07-11 18:36:36 +00:00
prathabanKavin
11bca0f4ae Remove unnecessary logs 2024-07-11 23:57:14 +05:30
prathabanKavin
de1d79f27c Fix same device data loading for subscriptions 2024-07-11 23:53:34 +05:30
2006d7e97d Add policy type conversion from BLOB to Text DB scripts 2024-07-11 23:33:16 +05:30
Lasantha Dharmakeerthi
cbbac7e37a Add policy content store as Json 2024-07-11 10:29:56 +00:00
090c5d22df Merge pull request 'Fix deleted,removed devices appearing in subscription table' (#447) from prathabanKavin/device-mgt-core:removeddevicefix into master
Reviewed-on: https://repository.entgra.net/community/device-mgt-core/pulls/447
2024-07-11 08:02:37 +00:00
3c31c9d432 Merge branch 'master' into removeddevicefix 2024-07-11 07:07:09 +00:00
prathabanKavin
1a1df97253 Resolve comments 2024-07-11 12:32:39 +05:30
Lasantha Dharmakeerthi
2ac2b0fc37 Add configuration to delete Tenant Application artifacts 2024-07-11 06:03:47 +00:00
03457250fa Merge pull request 'Add Microsoft Store integration for Windows devices' (#443) from navodzoysa/device-mgt-core:issue-10635/store-integration into master
Reviewed-on: https://repository.entgra.net/community/device-mgt-core/pulls/443
2024-07-11 05:49:51 +00:00
faefad1505 Merge pull request 'Fix user, role app installations failing' (#445) from prathabanKavin/device-mgt-core:uuserrolefix into master
Reviewed-on: https://repository.entgra.net/community/device-mgt-core/pulls/445
2024-07-11 05:23:08 +00:00
ashvini
e1a47c68fb Get TenantMgtAdminService as an osgi service
Resolve comments

Remove source reference

Change error messages

Make changes in code

Add license

Resolve comments

Add java doc comments

Resolve comments

Resolve comment
2024-07-11 10:49:47 +05:30
prathabanKavin
953f72afdc Filter devices according to their devicetype 2024-07-11 07:56:34 +05:30
navodzoysa
d566cf966a Add Microsoft Store integration for Windows devices 2024-07-11 02:02:22 +05:30
prathabanKavin
68a4de92d6 Fix all,device,group removed devices 2024-07-11 00:52:53 +05:30
prathabanKavin
f9cea050ae Fix user,role removed devices 2024-07-11 00:52:49 +05:30
Lasantha Dharmakeerthi
9f8f25d310 Fix issues with adding operation log of a subscription 2024-07-10 18:28:11 +00:00
nipuni
7c90b43485 Fix issues with adding operation log of a subscription 2024-07-10 21:30:45 +05:30
Lasantha Dharmakeerthi
541853df30 Add App publishing improvements 2024-07-10 10:26:44 +00:00
Rajitha Kumara
2eb73213f3 Add requested changes 2024-07-10 15:26:19 +05:30
Rajitha Kumara
1576ef86d0 App publishing improvements 2024-07-10 15:26:19 +05:30
Lasantha Dharmakeerthi
d43bc1c5a4 Fix issues in device renaming functionality 2024-07-10 07:25:12 +00:00
nipuni
61a21edb9d Fix Device renaming is not working issue#11452 2024-07-10 12:34:44 +05:30
Lasantha Dharmakeerthi
3be202812e Fix jaxb dependency issue 2024-07-10 06:56:19 +00:00
ashvini
8e33eebbf6 Add tenant application artifact deletion configuration
Fix code errors

Remove spaces

Refactor code
2024-07-10 11:46:24 +05:30
cd43a6a812 Merge branch 'master' into uuserrolefix 2024-07-10 04:32:14 +00:00
prathabanKavin
9a99b5804f Fix user, role app installations failing 2024-07-10 09:54:26 +05:30
Lasantha Dharmakeerthi
3b672c74b4 Migrate from legacy FCM APIs to HTTP v1 2024-07-09 12:31:48 +00:00
Rajitha Kumara
c9763c8a1b Fix jaxb dependency issue 2024-07-09 10:21:26 +05:30
529d1aec01 Add doc comments 2024-07-05 21:05:07 +05:30
23d31fd38c Fix code review suggestions 2024-07-05 20:56:03 +05:30
nipuni
7a8c63f31f Merge branch 'master' of https://repository.entgra.net/community/device-mgt-core into #11349 2024-07-05 13:18:07 +05:30
Lasantha Dharmakeerthi
a78b979e53 Sync with master 2024-07-04 10:17:50 +00:00
tcdlpds
dc3a9e868b Merge branch 'master' of https://repository.entgra.net/community/device-mgt-core into apim420 2024-07-04 15:11:05 +05:30
Lasantha Dharmakeerthi
99e7d12ab7 Fix issues with device name,status not loading 2024-07-04 09:40:06 +00:00
prathabanKavin
d1ed100f2f Fix device status,name not loading 2024-07-04 10:42:29 +05:30
tcdlpds
898a12dc31 Merge branch 'master' of https://repository.entgra.net/community/device-mgt-core into apim420 2024-07-04 08:12:03 +05:30
Nipuni Kavindya
c51b3c49fa Add backend implementation to get devices not in a group
Purpose:
https://roadmap.entgra.net/issues/11349
Co-authored-by: Nipuni Kavindya <nipuni@entgra.io>
Co-committed-by: Nipuni Kavindya <nipuni@entgra.io>
2024-07-04 02:38:06 +00:00
nipuni
fd67b39a46 Merge branch 'master' of https://repository.entgra.net/community/device-mgt-core into #11349
# Conflicts:
#	components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/service/DeviceManagementProviderService.java
#	components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/service/DeviceManagementProviderServiceImpl.java
2024-07-03 16:02:15 +05:30
tcdlpds
c99194299a Merge branch 'master' of https://repository.entgra.net/community/device-mgt-core into apim420 2024-07-02 20:03:02 +05:30
builder
15afde08ac [maven-release-plugin] prepare for next development iteration 2024-07-02 12:30:47 +05:30
tcdlpds
92a49e71c1 Sync with master 2024-07-02 01:24:18 +05:30
nipuni
fc269dba22 Add backend implementation to get devices not in a group. 2024-06-28 12:03:24 +05:30
c38aea743b Add missing license headers 2024-06-25 17:36:22 +05:30
b1d3503e8b Add improvements to Google API token generation in FCM 2024-06-25 17:36:03 +05:30
Rajitha Kumara
aafa824f08 Migrate from legacy FCM APIs to HTTP v1 2024-06-25 17:35:56 +05:30
5c73277c32 Add FCM changes 2024-06-25 17:35:51 +05:30
tcdlpds
4b92df7638 Fix merge conflicts 2024-06-24 11:54:11 +05:30
Lasantha Dharmakeerthi
9a3791bfee Fix issue when string parsing in proxy 2024-06-23 17:37:39 +00:00
Rajitha Kumara
1352168d5e Change method names into meaningfull names 2024-06-19 11:46:28 +05:30
Rajitha Kumara
665b013a96 Fix issue when string parsing in proxy 2024-06-19 11:20:26 +05:30
Lasantha Dharmakeerthi
13daf3963a Fix remote share authorization issue 2024-06-10 09:56:13 +00:00
Lasantha Dharmakeerthi
82cbf32e9c Sync with master Branch 2024-06-10 09:20:55 +00:00
tcdlpds
d3e48edeef Merge branch 'master' of https://repository.entgra.net/community/device-mgt-core into apim420 2024-06-10 14:35:41 +05:30
tcdlpds
0548dbdc3a Merge branch 'master' of https://repository.entgra.net/community/device-mgt-core into apim420 2024-06-10 02:25:25 +05:30
tcdlpds
ae8a170421 Fix merge conflicts 2024-06-09 14:26:28 +05:30
Rajitha Kumara
694e601a4b Fix remote share authorization issue 2024-05-31 11:36:50 +05:30
Lasantha Dharmakeerthi
f2ac7aa9c2 Fix SQL issue in app uninstall feature 2024-05-22 06:40:57 +00:00
tcdlpds
f4fe3b8d82 Fix SQL issue in app uninstall feature 2024-05-22 12:08:57 +05:30
Lasantha Dharmakeerthi
5c03b3befc Merge with master 2024-05-16 07:51:31 +00:00
tcdlpds
3106b23d31 Merge branch 'master' of https://repository.entgra.net/community/device-mgt-core into apim420 2024-05-16 12:18:09 +05:30
Lasantha Dharmakeerthi
bb2c1d8906 Fix tenant-mgt build failure 2024-05-07 10:16:08 +00:00
Rajitha Kumara
faab9c8632 Update dependency list 2024-05-07 13:50:23 +05:30
Rajitha Kumara
0b06ed6e03 Fix conflicts 2024-05-07 10:03:43 +05:30
Rajitha Kumara
ce2e57c6d0 Fix tenant-mgt build failure 2024-05-07 09:24:45 +05:30
Lasantha Dharmakeerthi
7ffc54dbde Fix build failure 2024-05-07 03:13:14 +00:00
tcdlpds
6ac4774001 Fix build failure 2024-05-07 08:32:25 +05:30
Lasantha Dharmakeerthi
f06387fc4b Fix build failure 2024-05-06 11:54:07 +00:00
tcdlpds
63a3c3eab3 Fix build failure 2024-05-06 10:07:00 +05:30
Lasantha Dharmakeerthi
9ff29f14ea Fix server starting issue with latest WUM 2024-04-30 18:44:30 +00:00
tcdlpds
8cf830b7c8 Fix server starting issue with latest WUM 2024-05-01 00:10:58 +05:30
Lasantha Dharmakeerthi
1282a2d270 Synced with APIM 420 2024-04-22 02:48:27 +00:00
Rajitha Kumara
177b8cc831 Sync with master 2024-04-21 19:44:18 +05:30
Rajitha Kumara
d1661e3f6d Sync with master 2024-04-21 18:59:40 +05:30
e1519fa2a8 Add policy content store as Json 2024-03-24 15:11:53 +05:30
Lasantha Dharmakeerthi
635da5c18a Sync with master branch 2024-03-10 05:49:33 +00:00
pasindu
f03cae09fe Sync with master branch 2024-03-09 08:23:08 +05:30
Lasantha Dharmakeerthi
202b9b7016 Upgrade versions of dependencies 2024-03-07 10:40:03 +00:00
tcdlpds
4e4ff9c960 Improve dependencies 2024-03-07 16:06:45 +05:30
tcdlpds
e67630feeb Upgrade wso2 tomcat version 2024-03-07 12:55:27 +05:30
Lasantha Dharmakeerthi
1c514d4edf Fix import issues in certificate management core 2024-03-05 10:44:31 +00:00
pasindu
58989472c9 Fix import issues in certificate management core 2024-03-05 10:56:30 +05:30
Lasantha Dharmakeerthi
3765528843 Restore osgi.framework version 2024-02-28 06:03:39 +00:00
pasindu
3fea1ae32c Restore osgi.framework version 2024-02-28 10:32:54 +05:30
Lasantha Dharmakeerthi
8a74de0235 Fix OSGI issues 2024-02-27 18:36:26 +00:00
pasindu
6b79abeaeb Fix Osgi issues 2024-02-27 09:57:30 +05:30
Lasantha Dharmakeerthi
f8d2ffe5f8 Fix API invoking issue via invoker 2024-02-20 12:50:38 +00:00
tcdlpds
fdf5c62204 Fix scope issue with code grant type 2024-02-20 15:39:33 +05:30
tcdlpds
b6c4cb66f5 Improve logger dependencies 2024-02-20 15:39:33 +05:30
Lasantha Dharmakeerthi
4b39d46bc2 Sync with master 2024-02-20 06:30:11 +00:00
pasindu
de1de88e4a Sync with master 2024-02-20 11:42:05 +05:30
Lasantha Dharmakeerthi
2ecfc5c274 Add minor fixes in application registration flow 2024-02-15 10:58:28 +00:00
pasindu
47bc27a36d Minor fixes in application registration flow 2024-02-15 16:26:57 +05:30
Lasantha Dharmakeerthi
6022d12a96 Sync apim420 branch with master 2024-02-08 10:23:49 +00:00
pasindu
e67dcd5ca2 Sync with master 2024-02-08 13:26:20 +05:30
pasindu
14554ba161 Fix sql issues 2024-02-08 13:25:44 +05:30
pasindu
1a9782c3f3 Fix dependency issues 2024-02-06 14:58:39 +05:30
pasindu
d938195373 Fix osgi reference addings in Service components 2024-02-06 07:30:05 +05:30
pasindu
67975ea5f8 Merge branch 'master' of ssh://repository.entgra.net:222/community/device-mgt-core into apim420 2024-02-05 19:54:01 +05:30
Lasantha Dharmakeerthi
d57c0a2ab1 Fix user scopes payload issue 2024-02-02 18:28:04 +00:00
pasindu
f7f0a4a2a4 Fix user scopes payload issue 2024-02-02 23:46:47 +05:30
Lasantha Dharmakeerthi
ce18849691 Fix Role Management Service logger issues 2024-02-01 19:33:32 +00:00
pasindu
86f78f0a86 Fix Role Management Service loger issues 2024-02-01 21:31:24 +05:30
Lasantha Dharmakeerthi
00d79ae6d9 Fix custom log printing issue 2024-02-01 10:30:13 +00:00
tcdlpds
94905d020d Fix custom log printing issue 2024-02-01 15:55:46 +05:30
tcdlpds
51199fbb70 Merge branch 'apim420' of https://repository.entgra.net/community/device-mgt-core into apim420 2024-02-01 01:50:08 +05:30
tcdlpds
e2f2237b2d Fix log class loading issue 2024-02-01 01:49:49 +05:30
Lasantha Dharmakeerthi
c55508c35d Fix UI issue from interceptor side 2024-01-22 10:47:07 +00:00
pasindu
cc21c661ae Fix UI issue from interceptor side 2024-01-22 12:57:45 +05:30
Lasantha Dharmakeerthi
55d9a735f8 Fix JITEnrollmentCallbackHandler bugs after httpclient update 2024-01-19 06:39:50 +00:00
pasindu
5ad0734b7b Fix import issue in webapp publisher 2024-01-19 11:53:10 +05:30
pasindu
1d0a087734 Fix JITEnrollmentCallbackHandler bugs after httpclient update 2024-01-18 10:41:34 +05:30
Lasantha Dharmakeerthi
aba133503d Sync with master branch 2024-01-18 04:45:13 +00:00
pasindu
c48944b20a Resolve conflicts when syncing with master 2024-01-18 09:54:36 +05:30
pasindu
6a12911487 Sync with master 2024-01-17 18:13:15 +05:30
Lasantha Dharmakeerthi
9a84a15368 Http Client update bug fixes. 2024-01-12 03:47:12 +00:00
pasindu
b8e8450108 Http update fixes 2024-01-11 09:40:09 +05:30
Lasantha Dharmakeerthi
cac6982d6b Sync with master 2024-01-07 03:10:56 +00:00
pasindu
54ca87c9db Need to fix http client update 2024-01-07 07:38:13 +05:30
pasindu
122f3f16f1 Sync with master 2024-01-06 23:31:49 +05:30
Lasantha Dharmakeerthi
1013831507 Add APIM devportal API integration 2024-01-06 15:11:51 +00:00
tcdlpds
56033e2e3a Fix build failure 2024-01-05 07:22:52 +05:30
tcdlpds
8bf027f2b3 Fix invoker handler 2024-01-04 02:13:47 +05:30
tcdlpds
7007558623 Fix OTP request handler 2024-01-04 01:31:38 +05:30
tcdlpds
8c841dfc2e Fix login handler 2024-01-01 00:27:07 +05:30
tcdlpds
66eac3c744 Fix compilation issues in user handler 2023-12-11 08:11:37 +05:30
tcdlpds
db3555f59e Upgrade 2023-11-21 01:57:17 +05:30
Lasantha Dharmakeerthi
717667126c revert 52b2cccf9f
revert Upgrade apache http client version
2023-11-20 20:20:39 +00:00
tcdlpds
2d9352a788 Upgrade with latest http client 2023-11-21 01:41:04 +05:30
tcdlpds
d4f9472e48 Fix build failure 2023-11-14 23:06:12 +05:30
tcdlpds
fb859f046d Add upstream changes 2023-11-14 22:13:49 +05:30
tcdlpds
1bc89dd3e4 Fix conflicts 2023-11-14 22:02:12 +05:30
tcdlpds
52b2cccf9f Upgrade apache http client version 2023-11-14 21:40:42 +05:30
Lasantha Dharmakeerthi
7376ff0476 Merge pull request 'Sync with upstream apim420' (#21) from sync-upstream into apim420
Reviewed-on: https://repository.entgra.net/tcdlpds/device-mgt-core/pulls/21
2023-10-24 18:40:56 +00:00
pasindu
66bc7e88bd Sync with upstream 2023-10-24 18:47:29 +05:30
Lasantha Dharmakeerthi
0dd57b8dd5 Fix sso login app creation payload and remove unused methods 2023-10-24 07:58:05 +00:00
Lasantha Dharmakeerthi
bfae0e0de8 Sync apim420 branch with master branch
Reviewed-on: https://repository.entgra.net/community/device-mgt-core/pulls/261
2023-10-24 07:56:51 +00:00
pasindu
c7494bcd81 Merge branch 'master' of ssh://repository.entgra.net:222/community/device-mgt-core into apim420 2023-10-23 18:09:19 +05:30
pasindu
26a2950f85 Fix webapp publisher issues 2023-10-23 18:06:41 +05:30
pasindu
383eed95e8 Merge branch 'master' of ssh://repository.entgra.net:222/community/device-mgt-core into sync-master 2023-10-23 12:45:44 +05:30
pasindu
a46ab4c355 Merge branch 'master' of ssh://repository.entgra.net:222/community/device-mgt-core into apim420 2023-10-20 00:43:12 +05:30
pasindu
518bc7271a Merge branch 'master' of ssh://repository.entgra.net:222/community/device-mgt-core into apim420 2023-10-19 14:34:14 +05:30
pasindu
e128a2479f Clear unused method 2023-09-27 15:37:35 +05:30
pasindu
144170c4c9 Fix sso loging app creation payload 2023-09-27 15:10:51 +05:30
Lasantha Dharmakeerthi
6b2d77f33e Improvements in App registration flow 2023-09-25 04:08:19 +00:00
pasindu
cc6bbf1435 Improvements in App registration 2023-09-22 10:25:29 +05:30
tcdlpds
ac0ba00707 Remove unnecessary sources 2023-09-20 09:37:58 +05:30
tcdlpds
500fa0df98 Add improvements to app registering logic 2023-09-20 09:30:16 +05:30
tcdlpds
088642e7ce Improve API app registration 2023-09-19 13:22:28 +05:30
tcdlpds
317af213be Merge branch 'apim420' of https://repository.entgra.net/tcdlpds/device-mgt-core into apim420 2023-09-14 17:45:00 +05:30
Lasantha Dharmakeerthi
b3a0d8e931 Fix grant type update method 2023-09-14 11:20:21 +00:00
pasindu
bb879f52ce Fix grant type update method 2023-09-14 14:10:17 +05:30
tcdlpds
43ef843db5 Merge branch 'apim420' of https://repository.entgra.net/tcdlpds/device-mgt-core into apim420 2023-09-14 11:23:38 +05:30
tcdlpds
5848d68c63 Add app updating intial changes 2023-09-14 11:23:29 +05:30
Lasantha Dharmakeerthi
870603ee16 Implement method for updateGrantType rest call 2023-09-13 07:21:54 +00:00
pasindu
907d4b0316 Implement method for updateGrantType rest call 2023-09-13 12:20:37 +05:30
tcdlpds
7e65d9f980 Fix access token validating issue 2023-09-12 00:02:07 +05:30
tcdlpds
da1f9d2437 Fix admin user details getting issue 2023-08-09 07:34:00 +05:30
tcdlpds
f117e40fc9 Fix SSO related issues 2023-08-06 23:38:02 +05:30
Dharmakeerthi Lasantha
a17c5c27ab Fix test case failure 2023-08-02 07:56:01 +05:30
Dharmakeerthi Lasantha
046c1faf77 Merge branch 'apim420' of https://repository.entgra.net/tcdlpds/device-mgt-core into apim420 2023-07-31 11:40:53 +05:30
Dharmakeerthi Lasantha
938190deca Merge branch 'apim420' of https://repository.entgra.net/community/device-mgt-core into apim420 2023-07-31 11:40:04 +05:30
Lasantha Dharmakeerthi
0333082716 Sync with master branch 2023-07-31 06:09:15 +00:00
Dharmakeerthi Lasantha
8289db1af8 Merge branch 'master' of https://repository.entgra.net/community/device-mgt-core into sync-master 2023-07-31 11:29:17 +05:30
Lasantha Dharmakeerthi
b0f1964760 Implement map application keys using dcr response 2023-07-31 02:52:50 +00:00
pasindu
2d296a3453 Implement map application keys using dcr response 2023-07-26 14:26:43 +05:30
Amalka Subasinghe
d021b43086 Merge pull request 'Fix test cases failing issue' (#183) from tcdlpds/device-mgt-core:sync-master into apim420
Reviewed-on: https://repository.entgra.net/community/device-mgt-core/pulls/183
2023-07-26 07:54:57 +00:00
Lasantha Dharmakeerthi
b0d5fc29d5 Fix JWT token generation. 2023-07-26 03:13:56 +00:00
pasindu
7dfcb418f4 Fix jwt token generation 2023-07-26 08:35:23 +05:30
Dharmakeerthi Lasantha
fe58a16d17 sync with upstream apim420 2023-07-26 07:32:55 +05:30
Lasantha Dharmakeerthi
04b4142ece Merge pull request 'Revert "Fixes in JWT token generation and sync with upstream apim420 branch"' (#14) from revert into apim420
Reviewed-on: https://repository.entgra.net/tcdlpds/device-mgt-core/pulls/14
2023-07-26 02:01:41 +00:00
Dharmakeerthi Lasantha
8215186061 Revert "Fixes in JWT token generation and sync with upstream apim420 branch"
This reverts commit d567209c11, reversing
changes made to 437c0e642d.
2023-07-26 07:29:08 +05:30
Lasantha Dharmakeerthi
d567209c11 Fixes in JWT token generation and sync with upstream apim420 branch 2023-07-25 14:50:27 +00:00
pasindu
8ea4932019 Fixes in JWT token generation 2023-07-25 18:29:40 +05:30
Dharmakeerthi Lasantha
83780c6a0c Add improvements to APIM application creating logic 2023-07-25 18:29:34 +05:30
Dharmakeerthi Lasantha
8880ef99db Improve APIM application key generate method 2023-07-25 18:27:09 +05:30
Dharmakeerthi Lasantha
2125519aa6 Add todo Comments 2023-07-25 18:25:13 +05:30
Dharmakeerthi Lasantha
da4f3f1456 Add API integration 2023-07-25 18:18:42 +05:30
Dharmakeerthi Lasantha
52fd8c4b89 Add Application key generating logic 2023-07-25 18:05:16 +05:30
Dharmakeerthi Lasantha
29a8dd5fde Add API app registering refactored code 2023-07-25 18:05:14 +05:30
Dharmakeerthi Lasantha
958f4e43d6 Add Consumer REST API integration 2023-07-25 17:57:21 +05:30
Pasindu Rupasinghe
b7f077e639 Implement service for consumer rest APIs
Co-authored-by: Pasindu Rupasinghe <pasindu@entgra.io>
Co-committed-by: Pasindu Rupasinghe <pasindu@entgra.io>
2023-07-25 17:52:48 +05:30
Dharmakeerthi Lasantha
ac3e144437 Fix OSGI service unbinding issue 2023-07-25 17:33:02 +05:30
Dharmakeerthi Lasantha
f2243ebd0e Fix formatting issue 2023-07-25 17:33:02 +05:30
navodzoysa
f72166895f Fix class not found error in analytics component 2023-07-25 17:33:01 +05:30
prathabanKavin
8b967cee4c Add missing ios scopes in mdm-ui-config 2023-07-25 17:30:50 +05:30
Dharmakeerthi Lasantha
dc6bbdd282 Improve functionality and fix formatting issues 2023-07-25 17:30:47 +05:30
Dharmakeerthi Lasantha
ef2838414a Fix build failure 2023-07-25 17:29:15 +05:30
Dharmakeerthi Lasantha
087a9fe728 Fix dependency importing issue 2023-07-25 17:29:14 +05:30
Thilina Sandaruwan
b765c8ded3 Grouping Improvements (#169)
Purpose

After deleting a role, delete relevant records from DM_ROLE_GROUP_MAP table
Related tickets: https://roadmap.entgra.net/issues/9528 and https://roadmap.entgra.net/issues/9529

Co-authored-by: ThilinaPremachandra <thilina@entgra.io>
Reviewed-on: https://repository.entgra.net/community/device-mgt-core/pulls/169
Co-authored-by: Thilina Sandaruwan <thilina@entgra.io>
Co-committed-by: Thilina Sandaruwan <thilina@entgra.io>
2023-07-25 17:24:39 +05:30
rajitha
a1ae369fe5 Fix realm service unbinding issues 2023-07-25 17:19:22 +05:30
rajitha
3dc567fcfe Fix transaction initiating issue 2023-07-25 17:19:22 +05:30
ThilinaPremachandra
b682e77d34 fix: group assigned role issue 2023-07-25 17:19:21 +05:30
ThilinaPremachandra
0581151248 add: super-tenant admin check 2023-07-25 17:17:51 +05:30
ThilinaPremachandra
fde6de94bb fix: sub tenants grouping issue 2023-07-25 17:17:51 +05:30
5d9938d7be Add footer config template
## Purpose
* Fixes https://roadmap.entgra.net/issues/10180

## Description
* cdm-config.xml.j2, cdm-config.xml templates are updated from hardcoded values to retrieve values from deployment.toml
* server_name, server_version and current_year are added as variables

* **Usage:** change deployment.toml values when a new version released. This will update the footer

## Related PRs
* https://repository.entgra.net/proprietary/product-uem/pulls/15

Co-authored-by: prathabanKavin <kavinprathaban025@gmail.com>
Reviewed-on: https://repository.entgra.net/community/device-mgt-core/pulls/160
Co-authored-by: Kavin Prathaban <kavin@entgra.io>
Co-committed-by: Kavin Prathaban <kavin@entgra.io>
2023-07-25 17:17:51 +05:30
navodzoysa
d90c5c459a Remove reserved_user when fetching users 2023-07-25 17:17:51 +05:30
Nishan Sangeeth
1844db87d8 Improve app visibility restricting functionality
Co-authored-by: Nishan Sangeeth <nishan@entgra.io>
Co-committed-by: Nishan Sangeeth <nishan@entgra.io>
2023-07-25 17:17:50 +05:30
nishan
50beae1bf8 Remove the user has role validation 2023-07-25 17:11:26 +05:30
nishan
da6f7158cf add api for get visible roles 2023-07-25 17:11:24 +05:30
Thilina Sandaruwan
0ce7cd954c HierarchicalGrouping (#153)
Goals
Complete hierarchical grouping task
https://roadmap.entgra.net/issues/9528 and https://roadmap.entgra.net/issues/9529

Approach
Fix the encountered issues

Co-authored-by: ThilinaPremachandra <thilina@entgra.io>
Co-authored-by: Pahansith Gunathilake <pahansith@entgra.io>
Reviewed-on: https://repository.entgra.net/community/device-mgt-core/pulls/153
Co-authored-by: Thilina Sandaruwan <thilina@entgra.io>
Co-committed-by: Thilina Sandaruwan <thilina@entgra.io>
2023-07-25 17:09:26 +05:30
rajitha
729f1fd85f Update invite link 2023-07-25 17:09:26 +05:30
prathabanKavin
5a8bcf6711 Add device enrolment log for modifyenrolment 2023-07-25 17:09:26 +05:30
navodzoysa
f9b9f76a3c Fix skip app release error 2023-07-25 17:09:26 +05:30
e979130e55 Fix missing imports 2023-07-25 17:09:24 +05:30
469c4988c5 Remove unnecessary logs 2023-07-25 17:05:08 +05:30
rajitha
6299d0fd83 Add otp token 2023-07-25 17:05:06 +05:30
inoshperera
2dd804f1a8 Add the logic to save device id to certificate DB
partialy fixes https://roadmap.entgra.net/issues/10145
2023-07-25 17:01:57 +05:30
9a55a83af4 Add OTP based remote session implementation 2023-07-25 16:57:08 +05:30
84563078d3 Add tenant based storing and loading SCEP certificates 2023-07-25 16:51:31 +05:30
inoshperera
a603a69f3e OTP for enrollment with Mutual TLS
Fixes https://roadmap.entgra.net/issues/10093
2023-07-25 16:46:18 +05:30
1e252dd67f Fix issue with Nginx not recognizing the SCEP client certificate (#105)
Co-authored-by: Pahansith <pahansith@entgra.io>
Reviewed-on: https://repository.entgra.net/community/device-mgt-core/pulls/105
Co-authored-by: Pahansith Gunathilake <pahansith@entgra.io>
Co-committed-by: Pahansith Gunathilake <pahansith@entgra.io>
2023-07-25 16:43:09 +05:30
inoshperera
19048ef341 Add SCEP support
fixes https://roadmap.entgra.net/issues/10042
2023-07-25 16:39:25 +05:30
Oshani Silva
8b928a4aca Remove unwanted check in billing logic
Co-authored-by: Oshani Silva <oshani@entgra.io>
Co-committed-by: Oshani Silva <oshani@entgra.io>
2023-07-25 16:30:50 +05:30
inoshperera
cfe7e520ab iOS user enrollment support
Fixes https://roadmap.entgra.net/issues/10149
2023-07-25 16:28:51 +05:30
navodzoysa
c6cc0f9a67 Fix incorrect clear app scope 2023-07-25 16:28:51 +05:30
navodzoysa
566942694c Remove apim_reserved_user when fetching users 2023-07-25 16:28:51 +05:30
builder
48801a3b8e [maven-release-plugin] prepare for next development iteration 2023-07-25 16:28:51 +05:30
builder
4c1963a32b [maven-release-plugin] prepare release v5.0.26 2023-07-25 16:28:51 +05:30
ThilinaPremachandra
ae13169377 add rollback 2023-07-25 16:28:51 +05:30
ThilinaPremachandra
4a239887cb add try with resources 2023-07-25 16:28:49 +05:30
ThilinaPremachandra
7d05446a38 add error log 2023-07-25 16:20:25 +05:30
ThilinaPremachandra
cd9d127a5e remove unnecessary variable, change error msg 2023-07-25 16:20:25 +05:30
ThilinaPremachandra
13545f1c7c remove unnecessary code lines 2023-07-25 16:20:25 +05:30
ThilinaPremachandra
d842fc4085 remove unnecessary imports, fixes line issues 2023-07-25 16:20:21 +05:30
ThilinaPremachandra
32e5456f21 fixes line issues 2023-07-25 16:18:38 +05:30
ThilinaPremachandra
88356c57aa Add hierarchical grouping feature 2023-07-25 16:18:36 +05:30
ThilinaPremachandra
ce4276c93a pom.xml updated by pull 2023-07-25 15:59:47 +05:30
7ad3a0e21b Add custom loggers (#136)
* Fixes https://roadmap.entgra.net/issues/10117

* Added custom logs for below cases:
1. Device connectivity events
2. Policy payload change events
3. Device enrollment history events
4. App install events

**1. Device connectivity logs** - logs for newly added operations and calls for pending operations

Pattern :
{DateTime} {LogLevel} - {ActionTag} {OperationCode} {DeviceId} {DeviceType} {TenantDomain} {TenantId} {UserName} - log_message

```
[2023-06-15 00:12:09,093]  INFO - [ADD_OPERATION] [DEVICE_LOCATION] [97] [android] [carbon.super] [-1234] [admin]- Operation added
[2023-06-15 00:12:10,344]  INFO - [PENDING_OPERATION] [DEVICE_LOCATION] [675c60a9d31492d6] [android] [carbon.super] [-1234] [admin]- Device Connected
[2023-06-15 00:13:49,755]  INFO - [ADD_OPERATION] [DEVICE_LOCK] [97] [android] [carbon.super] [-1234] [admin]- Operation added
[2023-06-15 00:13:56,513]  INFO - [ADD_OPERATION] [DEVICE_MUTE] [97] [android] [carbon.super] [-1234] [admin]- Operation added
[2023-06-15 00:14:23,839]  INFO - [PENDING_OPERATION] [DEVICE_MUTE]
[2023-06-15 00:15:12,549]  INFO - [ADD_OPERATION] [INSTALL_APPLICATION] [97] [android] [carbon.super] [-1234] [admin]- Operation added
[2023-06-15 00:15:29,703]  INFO - [PENDING_OPERATION] [INSTALL_APPLICATION] [675c60a9d31492d6] [android] [carbon.super] [-1234] [admin]- Device Connected
```
**2. Policy payload change events** - logs for creating policy, updating policy, deleting policy, change policy priorities and apply changes to device logs

Pattern :
{DateTime} {LogLevel} - {ActionTag} {PolicyName} {TenantDomain} {TenantId} {Payload} {UserName} - log_message

```
[2023-06-15 00:15:53,264]  INFO - [UPDATE_POLICY] [passcodeios] [carbon.super] [-1234] [{"policyPayloadVersion":"2.0","id":33,"priorityId":1,"profile":{"profileId":33,"profileName":"passcodeios","tenantId":0,"deviceType":"ios","updatedDate":"Jun 15, 2023 12:15:53 AM","profileFeaturesList":[{"id":33,"featureCode":"PASSCODE_POLICY","profileId":0,"deviceType":"ios","content":"{\"forcePIN\":true,\"allowSimple\":true,\"requireAlphanumeric\":true,\"minLength\":7.0,\"minComplexChars\":4.0,\"pinHistory\":\"\"}","correctiveActions":[]}]},"policyName":"passcodeios","generic":false,"roles":["ANY"],"devices":[],"users":[],"active":false,"updated":false,"description":"test","compliance":"enforce","tenantId":-1234,"profileId":33,"policyType":"GENERAL"}] [admin] - Policy updated
[2023-06-15 00:34:38,980]  INFO - [ADD_POLICY] [application management policy] [carbon.super] [-1234] [{"policyPayloadVersion":"2.0","id":65,"priorityId":0,"profile":{"profileId":65,"profileName":"application management policy","tenantId":0,"deviceType":"windows","createdDate":"Jun 15, 2023 12:34:38 AM","updatedDate":"Jun 15, 2023 12:34:38 AM","profileFeaturesList":[{"id":65,"featureCode":"ALLOW_ALL_TRUSTED_APPS","profileId":0,"deviceType":"windows","content":"{\"enabled\":true}","correctiveActions":[]},{"id":73,"featureCode":"RESTRICT_APP_TO_SYSTEM_VOLUME","profileId":0,"deviceType":"windows","content":"{\"enabled\":false}","correctiveActions":[]}]},"policyName":"application management policy","generic":false,"roles":["ANY"],"devices":[],"users":[],"active":false,"updated":false,"description":"test","compliance":"enforce","tenantId":-1234,"profileId":0,"policyType":"GENERAL"}] [admin] - Policy created
[2023-06-15 00:35:05,420]  INFO - [DELETE_POLICY] [passcodeios] [carbon.super] [-1234] [{"policyPayloadVersion":"2.0","id":33,"priorityId":1,"profile":{"profileId":33,"profileName":"passcodeios","tenantId":-1234,"deviceType":"ios","createdDate":"Jun 13, 2023 10:24:30 PM","updatedDate":"Jun 15, 2023 12:15:53 AM","profileFeaturesList":[{"id":33,"featureCode":"PASSCODE_POLICY","profileId":33,"deviceType":"ios","content":"{\"forcePIN\":true,\"allowSimple\":true,\"requireAlphanumeric\":true,\"minLength\":7.0,\"minComplexChars\":4.0,\"pinHistory\":\"\"}","correctiveActions":[]}]},"policyName":"passcodeios","generic":false,"roles":["ANY"],"devices":[],"users":[],"active":false,"updated":true,"description":"test","compliance":"enforce","policyCriterias":[],"tenantId":-1234,"profileId":33,"deviceGroups":[],"policyType":"GENERAL"}] [admin] - Policy deleted
[2023-06-15 00:35:12,768]  INFO - [UPDATE_POLICY_PRIORITIES] [] [carbon.super] [-1234] [[{"id":65,"priorityId":1,"generic":false,"active":false,"updated":false,"tenantId":0,"profileId":0},{"id":34,"priorityId":2,"generic":false,"active":false,"updated":false,"tenantId":0,"profileId":0}]] [admin] - Policy priorities updated
[2023-06-15 00:35:25,395]  INFO - [PUBLISH_CHANGES] [] [carbon.super] [-1234] [] [admin] - Apply changes to device
```
**3. Device enrollment history events** - logs for device enrollment and dis-enrollment

Pattern :
{DateTime} {LogLevel} - {DeviceId} {DeviceType} {Owner} {Ownership} {TenantId} {TenantDomain} {UserName} - log_message

```
[2023-06-15 00:12:09,078]  INFO - [97] [android] [admin] [BYOD] [-1234] [carbon.super] [admin] - Device enrolled successfully
[2023-06-15 00:47:36,278]  INFO - [97] [android] [admin] [BYOD] [-1234] [carbon.super] [admin] - Device disenrolled successfully
```

**4. App install events** - logs for app installation and uninstallation

Pattern :
{DateTime} {LogLevel} - {AppId} {AppName} {AppType} {SubType} {Action} {Device} {TenantId} {TenantDomain} {UserName} - log_message

```
[2023-06-15 00:15:12,550]  INFO - [1] [Calculator] [PUBLIC] [DEVICE] [install] [deviceId {id='675c60a9d31492d6', type='android'}] [-1234] [carbon.super] [admin] - App install triggered
[2023-06-15 00:46:24,454]  INFO - [2] [Sololearn] [ENTERPRISE] [DEVICE] [install] [deviceId {id='675c60a9d31492d6', type='android'}] [-1234] [carbon.super] [admin] - App install triggered
[2023-06-15 00:46:40,498]  INFO - [3] [Engineering] [WEB_CLIP] [DEVICE] [install] [deviceId {id='675c60a9d31492d6', type='android'}] [-1234] [carbon.super] [admin] - Web app install triggered
```

* https://repository.entgra.net/proprietary/product-uem/pulls/6

Co-authored-by: prathabanKavin <kavinprathaban025@gmail.com>
Co-authored-by: Pahansith Gunathilake <pahansith@entgra.io>
Reviewed-on: https://repository.entgra.net/community/device-mgt-core/pulls/136
Co-authored-by: Kavin Prathaban <kavin@entgra.io>
Co-committed-by: Kavin Prathaban <kavin@entgra.io>
2023-07-25 15:59:45 +05:30
navodzoysa
74e06047f1 Fix class def not found in grafana component 2023-07-25 15:45:15 +05:30
navodzoysa
effc35d52d Update admin credentials in webapp-auth-config template 2023-07-25 15:45:15 +05:30
Amalka Subasinghe
5b85778d27 fixed operation template unit tests 2023-07-25 15:45:15 +05:30
Amalka Subasinghe
80b42315d7 operation template related unit test fixes 2023-07-25 15:45:15 +05:30
Amalka Subasinghe
be6db5c5d5 fixed unit tests 2023-07-25 15:45:15 +05:30
Amalka Subasinghe
f63a6ee65b fixed unit tests 2023-07-25 15:45:15 +05:30
Amalka Subasinghe
ce37fdb4be fixed unit tests 2023-07-25 15:45:15 +05:30
Amalka Subasinghe
c286fec27b fixed unit tests 2023-07-25 15:45:15 +05:30
Amalka Subasinghe
da8fa5b895 fixed unit tests 2023-07-25 15:45:15 +05:30
Amalka Subasinghe
bc66555a04 fixed unit tests 2023-07-25 15:45:15 +05:30
Amalka Subasinghe
c855b707e7 fixed mockito dependency issue 2023-07-25 15:45:15 +05:30
Amalka Subasinghe
defb0aed04 fixed unit tests in analytics-mgt 2023-07-25 15:45:15 +05:30
Amalka Subasinghe
5b6b11dc8c fixed unit tests of application-mgt 2023-07-25 15:45:15 +05:30
Dharmakeerthi Lasantha
74041070f9 Fix class def not found issue 2023-07-24 20:22:54 +05:30
Dharmakeerthi Lasantha
349bb0a3dc Fix test case failure 2023-07-24 18:33:00 +05:30
Dharmakeerthi Lasantha
5098c652ca Merge branch 'apim420' of https://repository.entgra.net/community/device-mgt-core into sync-master 2023-07-18 09:22:28 +05:30
Amalka Subasinghe
bfe9746d70 Merge branch 'apim420' of https://repository.entgra.net/community/device-mgt-core into apim420 2023-07-18 09:20:19 +05:30
Dharmakeerthi Lasantha
1d94fb7de1 Fix test case failing 2023-07-18 09:16:25 +05:30
Amalka Subasinghe
95413f96de Merge pull request 'Fix OSGI service unbinding issue' (#177) from tcdlpds/device-mgt-core:sync-master into apim420
Reviewed-on: https://repository.entgra.net/community/device-mgt-core/pulls/177
2023-07-13 07:06:02 +00:00
Dharmakeerthi Lasantha
2cfa73206d Fix OSGI service unbinding issue 2023-07-13 07:54:34 +05:30
Amalka Subasinghe
b249b2435f Merge pull request 'Sync with the master branch' (#172) from tcdlpds/device-mgt-core:sync-master into apim420
Reviewed-on: https://repository.entgra.net/community/device-mgt-core/pulls/172
2023-07-12 03:46:53 +00:00
Dharmakeerthi Lasantha
a66d6389f9 Fix formatting issue 2023-07-12 00:39:31 +05:30
Dharmakeerthi Lasantha
fe4011cc7e Sync with master 2023-07-12 00:08:41 +05:30
Dharmakeerthi Lasantha
3bf6f7dd75 Improve functionality and fix formatting issues 2023-07-12 00:05:02 +05:30
Dharmakeerthi Lasantha
78aee58c1a Fix build failure 2023-07-11 12:13:53 +05:30
Dharmakeerthi Lasantha
11efc83b06 Fix dependency importing issue 2023-07-11 11:43:26 +05:30
Dharmakeerthi Lasantha
816ade11e6 Sync with master 2023-07-11 11:28:31 +05:30
Amalka Subasinghe
2e5579fdc2 fixed operation template unit tests 2023-07-07 11:16:53 +05:30
Amalka Subasinghe
013df183cd operation template related unit test fixes 2023-07-07 11:11:31 +05:30
Amalka Subasinghe
b7c0a8fb9b fixed unit tests 2023-07-06 17:06:48 +05:30
Amalka Subasinghe
edcf235ff8 fixed unit tests 2023-07-06 14:54:56 +05:30
Amalka Subasinghe
9352382406 fixed unit tests 2023-07-06 14:50:32 +05:30
Amalka Subasinghe
78f9f746d8 fixed unit tests 2023-07-06 14:26:32 +05:30
Amalka Subasinghe
9759520157 fixed unit tests 2023-07-06 14:22:21 +05:30
Amalka Subasinghe
b08f3fcc49 fixed unit tests 2023-07-06 13:15:02 +05:30
Amalka Subasinghe
1c4ee6cacc fixed mockito dependency issue 2023-07-06 10:40:38 +05:30
Amalka Subasinghe
9f19c1d1c1 fixed unit tests in analytics-mgt 2023-07-06 10:35:43 +05:30
Dharmakeerthi Lasantha
437c0e642d Merge branch 'apim420' of https://repository.entgra.net/community/device-mgt-core into apim420 2023-07-04 23:49:24 +05:30
Amalka Subasinghe
204b5d956b fixed unit tests of application-mgt 2023-07-04 16:54:32 +05:30
Amalka Subasinghe
2ff6e2e529 updated jackson-databind version 2023-06-30 12:02:53 +05:30
Amalka Subasinghe
1c3cd7cd2f fixed webapp deploying failure 2023-06-30 12:02:17 +05:30
Amalka Subasinghe
86c114f52f Merge pull request 'Remove Capp Deploying service' (#159) from tcdlpds/device-mgt-core:cron-fix into apim420
Reviewed-on: https://repository.entgra.net/community/device-mgt-core/pulls/159
2023-06-29 13:06:19 +00:00
Dharmakeerthi Lasantha
35ee44f799 Remove Capp Deploying service 2023-06-29 15:47:08 +05:30
Amalka Subasinghe
bfc38eeff0 Merge pull request 'Fix Cron Expression defining issue' (#157) from tcdlpds/device-mgt-core:cron-fix into apim420
Reviewed-on: https://repository.entgra.net/community/device-mgt-core/pulls/157
2023-06-29 03:51:39 +00:00
Dharmakeerthi Lasantha
e7062b37b2 Fix Cron Expression defining issue 2023-06-28 18:59:30 +05:30
Dharmakeerthi Lasantha
1e9b38440b Improve subscription filtering logic 2023-06-28 09:33:27 +05:30
Lasantha Dharmakeerthi
ab681eb915 Fix consumer REST calls 2023-06-23 04:44:33 +00:00
pasindu
c455bfe187 Fix consumer REST calls 2023-06-22 15:57:35 +05:30
Dharmakeerthi Lasantha
342e201c4c Add improvements to APIM application creating logic 2023-06-20 09:39:49 +05:30
Pasindu Rupasinghe
cb2fb990e7 Get ApiApplicationInfo and access token into single object
Co-authored-by: Pasindu Rupasinghe <pasindu@entgra.io>
Co-committed-by: Pasindu Rupasinghe <pasindu@entgra.io>
2023-06-19 12:00:20 +00:00
Lasantha Dharmakeerthi
438f06ef45 Fix getApplication method with Rest api calls 2023-06-19 02:52:08 +00:00
pasindu
da1485d04f Fix getApplication method with Rest api calls 2023-06-19 08:02:41 +05:30
Dharmakeerthi Lasantha
bfaeb1778f Add JWT support 2023-06-16 08:03:11 +05:30
Lasantha Dharmakeerthi
82b7513c01 Improvements in consumer rest APIs 2023-06-15 05:31:15 +00:00
pasindu
43ef801ac3 Improvements in consumer rest apis 2023-06-15 10:28:22 +05:30
Pasindu Rupasinghe
7dfcc0e33c Get token separately for REST calls
Co-authored-by: Pasindu Rupasinghe <pasindu@entgra.io>
Co-committed-by: Pasindu Rupasinghe <pasindu@entgra.io>
2023-06-15 02:50:59 +00:00
Dharmakeerthi Lasantha
d40dccc240 Add improvements to token generation for devices 2023-06-14 12:37:10 +05:30
Dharmakeerthi Lasantha
253157ba1a Merge branch 'apim420' of https://repository.entgra.net/community/device-mgt-core into apim420 2023-06-14 01:46:46 +05:30
Dharmakeerthi Lasantha
1edaa8a2a5 Improve API key generating method 2023-06-13 08:48:22 +05:30
Lasantha Dharmakeerthi
ad537f3461 Fix application key generation method 2023-06-13 02:55:27 +00:00
pasindu
7826e5c285 Fix key generation method 2023-06-13 07:32:32 +05:30
Dharmakeerthi Lasantha
730f3aaa07 Improve API publishing functionality 2023-06-13 04:06:04 +05:30
Dharmakeerthi Lasantha
840ba3755a Merge branch 'apim420' of https://repository.entgra.net/tcdlpds/device-mgt-core into apim420 2023-06-12 16:29:12 +05:30
Dharmakeerthi Lasantha
af17e4fa8e Improve APIM application key generate method 2023-06-12 16:27:38 +05:30
Lasantha Dharmakeerthi
7a6f6b8672 Fix version issues in REST APIs 2023-06-12 09:57:54 +00:00
pasindu
3b8405e72e Fix version issues in REST APIs 2023-06-12 14:37:00 +05:30
Amalka Subasinghe
46ee81e78d updated from master 2023-06-12 12:19:20 +05:30
Dharmakeerthi Lasantha
a09d72c33c Add todo Comments 2023-06-10 11:43:27 +05:30
Dharmakeerthi Lasantha
0927dfc835 sync with upstream 2023-06-09 14:44:08 +05:30
Dharmakeerthi Lasantha
f741df7c4b Add ToDos 2023-06-09 14:12:30 +05:30
Dharmakeerthi Lasantha
c227969a61 Improve the functionality 2023-06-09 05:06:01 +05:30
Dharmakeerthi Lasantha
189a572d31 Improve functionality 2023-06-09 04:51:05 +05:30
Lasantha Dharmakeerthi
49fafb3b37 Get API Application registration to single method and fix generateApplicationKeys method 2023-06-08 22:53:18 +00:00
pasindu
94e1df617a Get apiApplication registration to single method and fix generateApplicationKeys 2023-06-09 03:07:42 +05:30
Dharmakeerthi Lasantha
d251253948 Improve application key generating functionality 2023-06-08 06:02:23 +05:30
Lasantha Dharmakeerthi
bbcadf19d0 Modify generateAndRetrieveApplicationKeys method 2023-06-07 23:35:15 +00:00
pasindu
0e62245064 modify generateAndRetrieveApplicationKeys method 2023-06-07 23:24:13 +05:30
Dharmakeerthi Lasantha
6bf6adf2b5 Add API integration 2023-06-07 20:58:48 +05:30
Lasantha Dharmakeerthi
f587e2a38f Improvements in consumer rest APIS 2023-06-07 06:40:13 +00:00
pasindu
c53c8f3d63 minor fix 2023-06-07 10:43:34 +05:30
pasindu
45d98d5e49 Improve get all api method to accept header params 2023-06-07 07:57:18 +05:30
pasindu
a8d45ee41a Create methods for consumer api app creation and get details of app 2023-06-07 07:57:18 +05:30
pasindu
a513c13037 Improvements in consumer rest apis 2023-06-07 07:57:18 +05:30
Dharmakeerthi Lasantha
c46a459e6d Add Application key generating logic 2023-06-06 17:03:33 +05:30
Amalka Subasinghe
541e517b46 updated from master branch 2023-06-06 14:00:08 +05:30
Amalka Subasinghe
3470c58705 updated apim420 2023-06-06 12:44:48 +05:30
Amalka Subasinghe
1bb571acde fixing dependency issues when installing on apim420 2023-06-06 12:42:33 +05:30
Dharmakeerthi Lasantha
2d37dcb340 Add API app registering refactored code 2023-06-06 11:17:29 +05:30
Dharmakeerthi Lasantha
22f4da908f Add Consumer REST API integration 2023-06-01 17:13:51 +05:30
Pasindu Rupasinghe
c98237dc6f Implement service for consumer rest APIs
Co-authored-by: Pasindu Rupasinghe <pasindu@entgra.io>
Co-committed-by: Pasindu Rupasinghe <pasindu@entgra.io>
2023-06-01 09:50:58 +00:00
Dharmakeerthi Lasantha
c3d23c3cfa Merge branch 'master' of https://repository.entgra.net/community/device-mgt-core into apim420 2023-06-01 15:01:51 +05:30
Dharmakeerthi Lasantha
6e0fe2e26e Integrate with APIM dev-portal APIs 2023-06-01 08:52:26 +05:30
Amalka Subasinghe
b5012d9681 Merge pull request 'Update copyright' (#127) from tcdlpds/device-mgt-core:apim420 into apim420
Reviewed-on: https://repository.entgra.net/community/device-mgt-core/pulls/127
2023-05-30 03:40:31 +00:00
Dharmakeerthi Lasantha
36f7d9ea9b Sync with master 2023-05-28 23:54:31 +05:30
Amalka Subasinghe
073762c9db updated versions for apim 420 and jdk 17 2023-05-26 11:46:35 +05:30
1120 changed files with 22501 additions and 28753 deletions

15
.github/stale.yml vendored
View File

@ -1,15 +0,0 @@
# Number of days of inactivity before an issue becomes stale
daysUntilStale: 10
# Don't close isssues or pulls
daysUntilClose: false
# Issues with these labels will never be considered stale
exemptLabels:
- Resolution/Postponed
# Label to use when marking an issue as stale
staleLabel: Resolution/Stale
# Comment to post when marking an issue as stale. Set to `false` to disable
markComment: >
This issue has been automatically marked as stale because it has not had
recent activity.
# Comment to post when closing a stale issue. Set to `false` to disable
closeComment: false

View File

@ -1,28 +0,0 @@
image: charithag/docker-mvn-jdk8:latest
variables:
MAVEN_CLI_OPTS: "-s .m2/settings.xml --batch-mode"
MAVEN_OPTS: "-Dmaven.repo.local=.m2/repository"
cache:
paths:
- .m2/repository/
- target/
build:
stage: build
script:
- mvn $MAVEN_CLI_OPTS clean install -Dmaven.test.skip=true
test:
stage: test
script:
- mvn $MAVEN_CLI_OPTS test
deploy:
stage: deploy
script:
- mvn $MAVEN_CLI_OPTS deploy -Dmaven.test.skip=true
only:
- master@entgra/carbon-device-mgt
- kernel-4.6.x@entgra/carbon-device-mgt

View File

@ -1,8 +0,0 @@
language: java
jdk:
- oraclejdk8
cache:
directories:
- .autoconf
- $HOME/.m2
script: mvn clean install

127
Jenkinsfile vendored Normal file
View File

@ -0,0 +1,127 @@
pipeline {
agent {
label 'node-agent'
}
environment {
def isPendingUpstreamDependenciesExists = false
def triggeredViaPush = false
JAVA_HOME = '/usr/lib/jvm/java-11-openjdk'
PATH = "${JAVA_HOME}/bin:${env.PATH}"
}
stages {
stage('Initialize Variables') {
steps {
script {
// Define swaggerEndPoint as a global variable
swaggerEndPoint = {
def matcher = (env.CHANGE_URL =~ /^(?<host>https?:\/\/(?:www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b)(?<path>[-a-zA-Z0-9()@:%_\+.~#?&\/=]*)$/)
matcher.find()
return matcher.group('host') + '/api/v1/repos' + matcher.group('path')
}
echo "Swagger Endpoint: ${swaggerEndPoint.call()}"
}
}
}
stage('Tool Versioning') {
steps {
script {
sh 'java -version'
sh 'node --version'
sh 'npm --version'
sh 'jq --version'
}
}
}
stage('Check Environment Variables') {
steps {
script {
echo "CHANGE_ID: ${env.CHANGE_ID}"
echo "CHANGE_URL: ${env.CHANGE_URL}"
echo "CHANGE_AUTHOR: ${env.CHANGE_AUTHOR}"
echo "CHANGE_BRANCH: ${env.CHANGE_BRANCH}"
echo "JAVA_HOME: ${JAVA_HOME}"
echo "PATH: ${PATH}"
}
}
}
stage('Fetch Pending Upstream Dependencies') {
steps {
script {
if (env.CHANGE_ID) {
def url = swaggerEndPoint.call()
echo "Fetching from URL: ${url}"
withCredentials([usernamePassword(credentialsId: 'entgra-gitea-credentials', passwordVariable: 'password', usernameVariable: 'username')]) {
def response = sh(script: """curl -X GET "${url}" -H 'accept: application/json' -u \$username:\$password""", returnStdout: true).trim()
echo "API Response: ${response}"
isPendingUpstreamDependenciesExists = sh(script: "echo '${response}' | jq 'contains({\"labels\": [{ \"name\": \"pending upstream\"}]})'", returnStdout: true).trim().toBoolean()
}
} else {
echo '[Jenkinsfile] Triggered via a push request.'
echo '[Jenkinsfile] Skipping dependency checking.'
triggeredViaPush = true
}
}
}
}
stage('Execute Test Suites') {
steps {
script {
if (!isPendingUpstreamDependenciesExists) {
echo '[Jenkinsfile] Pending upstream dependencies do not exist.'
echo '[Jenkinsfile] Entering testing phase.'
try {
checkout scm
withCredentials([usernamePassword(credentialsId: 'builder2-deployer-nexus', passwordVariable: 'password', usernameVariable: 'username')]) {
sh """/opt/scripts/run-test.sh -u \$username -p \$password"""
}
currentBuild.result = 'SUCCESS'
message = 'Tests approved'
} catch (error) {
currentBuild.result = 'FAILURE'
message = 'Tests cannot be approved'
}
} else {
echo '[Jenkinsfile] Pending upstream dependencies exist.'
echo '[Jenkinsfile] Entering waiting phase.'
currentBuild.result = 'NOT_BUILT'
message = 'PR waiting due to pending upstream dependencies'
}
}
}
}
stage('Report Job Status') {
steps {
script {
if (true) {
withCredentials([usernamePassword(credentialsId: 'entgra-gitea-credentials', passwordVariable: 'password', usernameVariable: 'username')]) {
def url = swaggerEndPoint.call() + '/reviews'
echo "[Jenkinsfile] Notifying pull request build status to ${url}"
def response = sh(script: """curl -X POST "${url}" -H 'accept: application/json' -H 'Content-Type: application/json' -u \$username:\$password -d '{ "body": "${message}" }'""", returnStdout: true).trim()
echo "API Response: ${response}"
}
}
def committerEmail = sh(
script: 'git --no-pager show -s --format=\'%ae\'',
returnStdout: true
).trim()
if (currentBuild.result == 'FAILURE') {
emailext(
subject: "${currentBuild.result}: Job ${env.JOB_NAME} [${env.BUILD_NUMBER}]",
body: 'Hi, Please find below.\n<pre>${BUILD_LOG_REGEX, regex="BUILD FAILURE", linesAfter=30, showTruncatedLines=false, escapeHtml=true}</pre>' + "Find more at : ${env.BUILD_URL}",
to: triggeredViaPush ? '$DEFAULT_RECIPIENTS' : committerEmail
)
}
}
}
}
}
}

View File

@ -22,26 +22,19 @@
<parent> <parent>
<groupId>io.entgra.device.mgt.core</groupId> <groupId>io.entgra.device.mgt.core</groupId>
<artifactId>grafana-mgt</artifactId> <artifactId>grafana-mgt</artifactId>
<version>5.1.0</version> <version>6.0.1-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.api</artifactId> <artifactId>io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.api</artifactId>
<packaging>war</packaging> <packaging>war</packaging>
<name>Entgra - Grafana Proxy API</name> <name>Entgra Device Management - Grafana Proxy API</name>
<description>Entgra - Grafana Proxy API</description> <description>Entgra Device Management - Grafana Proxy API</description>
<url>http://entgra.io</url> <url>http://entgra.io</url>
<build> <build>
<plugins> <plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin> <plugin>
<artifactId>maven-war-plugin</artifactId> <artifactId>maven-war-plugin</artifactId>
<configuration> <configuration>
@ -61,7 +54,6 @@
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-antrun-plugin</artifactId> <artifactId>maven-antrun-plugin</artifactId>
<version>1.7</version>
<executions> <executions>
<execution> <execution>
<phase>compile</phase> <phase>compile</phase>
@ -97,9 +89,8 @@
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.apache.cxf</groupId> <groupId>org.apache.cxf.wso2</groupId>
<artifactId>cxf-bundle</artifactId> <artifactId>cxf-bundle</artifactId>
<version>3.0.0-milestone2</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency> <dependency>
@ -133,8 +124,8 @@
</exclusions> </exclusions>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.wso2.carbon</groupId> <groupId>org.ops4j.pax.logging</groupId>
<artifactId>org.wso2.carbon.logging</artifactId> <artifactId>pax-logging-api</artifactId>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<dependency> <dependency>
@ -299,7 +290,7 @@
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.powermock</groupId> <groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito</artifactId> <artifactId>powermock-api-mockito2</artifactId>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency> <dependency>
@ -333,6 +324,11 @@
<artifactId>io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.common</artifactId> <artifactId>io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.common</artifactId>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<dependency>
<groupId>io.entgra.device.mgt.core</groupId>
<artifactId>io.entgra.device.mgt.core.application.mgt.common</artifactId>
<scope>provided</scope>
</dependency>
</dependencies> </dependencies>
</project> </project>

View File

@ -18,25 +18,12 @@
package io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.api; package io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.api;
import com.google.gson.JsonObject; import com.google.gson.JsonObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.Extension;
import io.swagger.annotations.ExtensionProperty;
import io.swagger.annotations.Info;
import io.swagger.annotations.SwaggerDefinition;
import io.swagger.annotations.Tag;
import io.entgra.device.mgt.core.apimgt.annotations.Scope; import io.entgra.device.mgt.core.apimgt.annotations.Scope;
import io.entgra.device.mgt.core.apimgt.annotations.Scopes; import io.entgra.device.mgt.core.apimgt.annotations.Scopes;
import javax.ws.rs.Consumes; import io.swagger.annotations.*;
import javax.ws.rs.GET;
import javax.ws.rs.POST; import javax.ws.rs.*;
import javax.ws.rs.Path; import javax.ws.rs.core.*;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
@SwaggerDefinition( @SwaggerDefinition(
info = @Info( info = @Info(

View File

@ -18,12 +18,7 @@
package io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.api.addons; package io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.api.addons;
import javax.servlet.Filter; import javax.servlet.*;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import java.io.IOException; import java.io.IOException;

View File

@ -28,11 +28,7 @@ import org.apache.cxf.message.MessageContentsList;
import org.apache.cxf.phase.AbstractPhaseInterceptor; import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase; import org.apache.cxf.phase.Phase;
import javax.validation.ConstraintViolation; import javax.validation.*;
import javax.validation.ConstraintViolationException;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import javax.validation.executable.ExecutableValidator; import javax.validation.executable.ExecutableValidator;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.util.List; import java.util.List;

View File

@ -29,9 +29,9 @@ import io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core.bean.GrafanaPa
import io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core.config.GrafanaConfiguration; import io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core.config.GrafanaConfiguration;
import io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core.config.GrafanaConfigurationManager; import io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core.config.GrafanaConfigurationManager;
import io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core.exception.MaliciousQueryAttempt; import io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core.exception.MaliciousQueryAttempt;
import io.entgra.device.mgt.core.device.mgt.common.exceptions.DBConnectionException;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import io.entgra.device.mgt.core.device.mgt.common.exceptions.DBConnectionException;
import javax.ws.rs.Consumes; import javax.ws.rs.Consumes;
import javax.ws.rs.GET; import javax.ws.rs.GET;

View File

@ -27,6 +27,8 @@ import io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core.config.Grafana
import io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core.exception.GrafanaEnvVariablesNotDefined; import io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core.exception.GrafanaEnvVariablesNotDefined;
import io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core.util.GrafanaConstants; import io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core.util.GrafanaConstants;
import io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core.util.GrafanaUtil; import io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core.util.GrafanaUtil;
import io.entgra.device.mgt.core.device.mgt.core.common.util.HttpUtil;
import io.entgra.device.mgt.core.device.mgt.core.report.mgt.Constants;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpResponse; import org.apache.http.HttpResponse;
@ -37,8 +39,6 @@ import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.StringEntity; import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.client.HttpClients;
import io.entgra.device.mgt.core.device.mgt.core.common.util.HttpUtil;
import io.entgra.device.mgt.core.device.mgt.core.report.mgt.Constants;
import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MediaType;

View File

@ -22,15 +22,15 @@
<parent> <parent>
<groupId>io.entgra.device.mgt.core</groupId> <groupId>io.entgra.device.mgt.core</groupId>
<artifactId>grafana-mgt</artifactId> <artifactId>grafana-mgt</artifactId>
<version>5.1.0</version> <version>6.0.1-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.common</artifactId> <artifactId>io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.common</artifactId>
<packaging>bundle</packaging> <packaging>bundle</packaging>
<name>Entgra - Grafana API Handler Common</name> <name>Entgra Device Management - Grafana API Handler Common</name>
<description>Entgra - Grafana API Handler Common</description> <description>Entgra Device Management - Grafana API Handler Common</description>
<url>http://entgra.io</url> <url>http://entgra.io</url>
<build> <build>
@ -45,15 +45,10 @@
<Bundle-Name>${project.artifactId}</Bundle-Name> <Bundle-Name>${project.artifactId}</Bundle-Name>
<Bundle-Version>${io.entgra.device.mgt.core.version}</Bundle-Version> <Bundle-Version>${io.entgra.device.mgt.core.version}</Bundle-Version>
<Bundle-Description>Grafana Management Common Bundle</Bundle-Description> <Bundle-Description>Grafana Management Common Bundle</Bundle-Description>
<Import-Package />
<Export-Package> <Export-Package>
io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.common.* io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.common.*
</Export-Package> </Export-Package>
<Import-Package>
javax.xml.bind.annotation; version="${javax.xml.bind.imp.pkg.version}",
com.fasterxml.jackson.annotation;version="${jackson-annotations.version}",
io.swagger.annotations; version="${swagger.annotations.version}"; resolution:=optional,
com.google.gson
</Import-Package>
</instructions> </instructions>
</configuration> </configuration>
</plugin> </plugin>

View File

@ -17,7 +17,7 @@
*/ */
package io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.common.exception; package io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.common.exception;
public class GrafanaManagementException extends Exception{ public class GrafanaManagementException extends Exception {
private static final long serialVersionUID = -3922279312829079297L; private static final long serialVersionUID = -3922279312829079297L;

View File

@ -22,23 +22,19 @@
<parent> <parent>
<groupId>io.entgra.device.mgt.core</groupId> <groupId>io.entgra.device.mgt.core</groupId>
<artifactId>grafana-mgt</artifactId> <artifactId>grafana-mgt</artifactId>
<version>5.1.0</version> <version>6.0.1-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core</artifactId> <artifactId>io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core</artifactId>
<packaging>bundle</packaging> <packaging>bundle</packaging>
<name>Entgra - Grafana API Handler Core</name> <name>Entgra Device Management - Grafana API Handler Core</name>
<description>Entgra - Grafana API Handler Core</description> <description>Entgra Device Management - Grafana API Handler Core</description>
<url>http://entgra.io</url> <url>http://entgra.io</url>
<build> <build>
<plugins> <plugins>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-scr-plugin</artifactId>
</plugin>
<plugin> <plugin>
<groupId>org.jacoco</groupId> <groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId> <artifactId>jacoco-maven-plugin</artifactId>
@ -77,15 +73,47 @@
<Bundle-Description>Grafana API Management Core Bundle</Bundle-Description> <Bundle-Description>Grafana API Management Core Bundle</Bundle-Description>
<Private-Package>io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core.internal</Private-Package> <Private-Package>io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core.internal</Private-Package>
<Import-Package> <Import-Package>
io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.common.*, com.google.common.cache;version="[32.1,33)";resolution:=optional,
javax.xml.parsers;version="${javax.xml.parsers.import.pkg.version}";resolution:=optional, com.google.gson;version="[2.9,3)",
javax.xml.bind.annotation, io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.common.exception;version="${io.entgra.device.mgt.core.version.range}",
javax.xml.bind, io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core.bean,
org.apache.commons.lang, io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core.config,
org.wso2.carbon, io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core.config.xml.bean,
io.entgra.device.mgt.core.device.mgt.common.*, io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core.exception,
io.entgra.device.mgt.core.device.mgt.core.* io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core.service,
io.entgra.device.mgt.core.application.mgt.core.* io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core.service.bean,
io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core.service.cache,
io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core.service.impl,
io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core.sql.connection,
io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core.sql.query,
io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core.sql.query.encoder,
io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core.util,
io.entgra.device.mgt.core.application.mgt.common.exception;version="${io.entgra.device.mgt.core.version.range}",
io.entgra.device.mgt.core.application.mgt.core.config;version="${io.entgra.device.mgt.core.version.range}",
io.entgra.device.mgt.core.application.mgt.core.util;version="${io.entgra.device.mgt.core.version.range}",
io.entgra.device.mgt.core.device.mgt.common.exceptions;version="${io.entgra.device.mgt.core.version.range}",
io.entgra.device.mgt.core.device.mgt.core.common.util;version="${io.entgra.device.mgt.core.version.range}",
io.entgra.device.mgt.core.device.mgt.core.config;version="${io.entgra.device.mgt.core.version.range}",
io.entgra.device.mgt.core.device.mgt.core.config.datasource;version="${io.entgra.device.mgt.core.version.range}",
io.entgra.device.mgt.core.device.mgt.core.dao;version="${io.entgra.device.mgt.core.version.range}",
io.entgra.device.mgt.core.device.mgt.core.report.mgt.config;version="${io.entgra.device.mgt.core.version.range}",
io.entgra.device.mgt.core.device.mgt.core.report.mgt.dao.common;version="${io.entgra.device.mgt.core.version.range}",
javax.xml.bind;version="[0.0,1)",
javax.xml.bind.annotation;version="[0.0,1)",
javax.xml.parsers,
org.apache.commons.codec.binary;version="[1.4,2)",
org.apache.commons.lang;version="[2.6,3)",
org.apache.commons.lang3;version="[3.11,4)",
org.apache.commons.logging;version="[1.2,2)",
org.apache.http;version="[4.4,5)",
org.apache.http.client,
org.apache.http.client.methods,
org.apache.http.impl.client,
org.apache.juli.logging;version="[9.0,10)",
org.osgi.framework.*;version="${imp.package.version.osgi.framework}",
org.osgi.service.*;version="${imp.package.version.osgi.service}",
org.w3c.dom,org.wso2.carbon.context;version="[4.8,5)",
org.wso2.carbon.utils;version="[4.8,5)"
</Import-Package> </Import-Package>
<Export-Package> <Export-Package>
!io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core.internal, !io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core.internal,
@ -103,28 +131,31 @@
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>org.eclipse.osgi</groupId> <groupId>org.apache.felix</groupId>
<artifactId>org.eclipse.osgi</artifactId> <artifactId>org.apache.felix.scr.ds-annotations</artifactId>
</dependency> <scope>provided</scope>
<dependency>
<groupId>org.eclipse.osgi</groupId>
<artifactId>org.eclipse.osgi.services</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.wso2.orbit.org.scannotation</groupId> <groupId>io.entgra.org.scannotation</groupId>
<artifactId>scannotation</artifactId> <artifactId>scannotation</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>io.entgra.device.mgt.core</groupId> <groupId>io.entgra.device.mgt.core</groupId>
<artifactId>io.entgra.device.mgt.core.device.mgt.common</artifactId> <artifactId>io.entgra.device.mgt.core.device.mgt.common</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>io.entgra.device.mgt.core</groupId>
<artifactId>io.entgra.device.mgt.core.application.mgt.common</artifactId>
<scope>provided</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.wso2.carbon</groupId> <groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.utils</artifactId> <artifactId>org.wso2.carbon.utils</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.wso2.carbon</groupId> <groupId>org.ops4j.pax.logging</groupId>
<artifactId>org.wso2.carbon.logging</artifactId> <artifactId>pax-logging-api</artifactId>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<dependency> <dependency>
@ -139,6 +170,12 @@
<dependency> <dependency>
<groupId>io.entgra.device.mgt.core</groupId> <groupId>io.entgra.device.mgt.core</groupId>
<artifactId>io.entgra.device.mgt.core.device.mgt.core</artifactId> <artifactId>io.entgra.device.mgt.core.device.mgt.core</artifactId>
<exclusions>
<exclusion>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
</exclusion>
</exclusions>
</dependency> </dependency>
<dependency> <dependency>
<groupId>io.entgra.device.mgt.core</groupId> <groupId>io.entgra.device.mgt.core</groupId>
@ -147,17 +184,22 @@
<dependency> <dependency>
<groupId>org.apache.httpcomponents.wso2</groupId> <groupId>org.apache.httpcomponents.wso2</groupId>
<artifactId>httpclient</artifactId> <artifactId>httpclient</artifactId>
<version>4.1.1.wso2v1</version>
<scope>compile</scope> <scope>compile</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.apache.httpcomponents</groupId> <groupId>org.apache.httpcomponents.client5</groupId>
<artifactId>httpclient</artifactId> <artifactId>httpclient5</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>io.entgra.device.mgt.core</groupId> <groupId>io.entgra.device.mgt.core</groupId>
<artifactId>io.entgra.device.mgt.core.identity.jwt.client.extension</artifactId> <artifactId>io.entgra.device.mgt.core.identity.jwt.client.extension</artifactId>
<scope>provided</scope> <scope>provided</scope>
<exclusions>
<exclusion>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
</exclusion>
</exclusions>
</dependency> </dependency>
<dependency> <dependency>
<groupId>javax.ws.rs</groupId> <groupId>javax.ws.rs</groupId>
@ -173,7 +215,7 @@
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.powermock</groupId> <groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito</artifactId> <artifactId>powermock-api-mockito2</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.wso2.carbon</groupId> <groupId>org.wso2.carbon</groupId>
@ -191,8 +233,8 @@
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.h2database.wso2</groupId> <groupId>org.wso2.orbit.com.h2database</groupId>
<artifactId>h2-database-engine</artifactId> <artifactId>h2</artifactId>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency> <dependency>
@ -221,7 +263,7 @@
<artifactId>org.wso2.carbon.registry.core</artifactId> <artifactId>org.wso2.carbon.registry.core</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.apache.tomcat.wso2</groupId> <groupId>org.wso2.orbit.org.apache.tomcat</groupId>
<artifactId>jdbc-pool</artifactId> <artifactId>jdbc-pool</artifactId>
</dependency> </dependency>
<dependency> <dependency>
@ -240,14 +282,6 @@
<groupId>org.apache.ws.commons.axiom.wso2</groupId> <groupId>org.apache.ws.commons.axiom.wso2</groupId>
<artifactId>axiom</artifactId> <artifactId>axiom</artifactId>
</dependency> </dependency>
<!--dependency>
<groupId>org.apache.ws.commons.axiom.wso2</groupId>
<artifactId>axiom-impl</artifactId>
</dependency>
<dependency>
<groupId>org.apache.ws.commons.axiom.wso2</groupId>
<artifactId>axiom</artifactId>
</dependency-->
<dependency> <dependency>
<groupId>org.apache.axis2.wso2</groupId> <groupId>org.apache.axis2.wso2</groupId>
<artifactId>axis2</artifactId> <artifactId>axis2</artifactId>
@ -257,11 +291,11 @@
<artifactId>org.wso2.carbon.identity.oauth.stub</artifactId> <artifactId>org.wso2.carbon.identity.oauth.stub</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.wso2.tomcat</groupId> <groupId>org.wso2.orbit.org.apache.tomcat</groupId>
<artifactId>tomcat</artifactId> <artifactId>tomcat</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.wso2.tomcat</groupId> <groupId>org.wso2.orbit.org.apache.tomcat</groupId>
<artifactId>tomcat-servlet-api</artifactId> <artifactId>tomcat-servlet-api</artifactId>
</dependency> </dependency>
@ -276,23 +310,19 @@
<groupId>commons-collections.wso2</groupId> <groupId>commons-collections.wso2</groupId>
<artifactId>commons-collections</artifactId> <artifactId>commons-collections</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>io.entgra.device.mgt.core</groupId> <groupId>io.entgra.device.mgt.core</groupId>
<artifactId>io.entgra.device.mgt.core.transport.mgt.email.sender.core</artifactId> <artifactId>io.entgra.device.mgt.core.transport.mgt.email.sender.core</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>mysql</groupId> <groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId> <artifactId>mysql-connector-java</artifactId>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.google.code.gson</groupId> <groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId> <artifactId>gson</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>io.swagger</groupId> <groupId>io.swagger</groupId>
<artifactId>swagger-annotations</artifactId> <artifactId>swagger-annotations</artifactId>
@ -321,9 +351,12 @@
<dependency> <dependency>
<groupId>com.google.guava</groupId> <groupId>com.google.guava</groupId>
<artifactId>guava</artifactId> <artifactId>guava</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.orbit.javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<scope>provided</scope>
</dependency> </dependency>
</dependencies> </dependencies>
</project> </project>

View File

@ -26,15 +26,19 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.osgi.framework.BundleContext; import org.osgi.framework.BundleContext;
import org.osgi.service.component.ComponentContext; import org.osgi.service.component.ComponentContext;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Deactivate;
/** @Component(
* @scr.component name="io.entgra.analytics.mgt.grafana.proxy.grafanamanagementservicecomponent" immediate="true" name = "io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core.internal.GrafanaManagementServiceComponent",
*/ immediate = true)
public class GrafanaManagementServiceComponent { public class GrafanaManagementServiceComponent {
private static Log log = LogFactory.getLog(GrafanaManagementServiceComponent.class); private static Log log = LogFactory.getLog(GrafanaManagementServiceComponent.class);
@SuppressWarnings("unused") @SuppressWarnings("unused")
@Activate
protected void activate(ComponentContext componentContext) { protected void activate(ComponentContext componentContext) {
try { try {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
@ -59,6 +63,7 @@ public class GrafanaManagementServiceComponent {
} }
@SuppressWarnings("unused") @SuppressWarnings("unused")
@Deactivate
protected void deactivate(ComponentContext componentContext) { protected void deactivate(ComponentContext componentContext) {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("De-activating Grafana Management Service Component"); log.debug("De-activating Grafana Management Service Component");

View File

@ -22,14 +22,14 @@
<parent> <parent>
<groupId>io.entgra.device.mgt.core</groupId> <groupId>io.entgra.device.mgt.core</groupId>
<artifactId>analytics-mgt</artifactId> <artifactId>analytics-mgt</artifactId>
<version>5.1.0</version> <version>6.0.1-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>grafana-mgt</artifactId> <artifactId>grafana-mgt</artifactId>
<packaging>pom</packaging> <packaging>pom</packaging>
<name>Entgra - Grafana API Handler Component</name> <name>Entgra Device Management - Grafana API Handler Component</name>
<url>http://entgra.io</url> <url>http://entgra.io</url>

View File

@ -19,16 +19,16 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent> <parent>
<artifactId>io.entgra.device.mgt.core.parent</artifactId> <artifactId>device-mgt-core</artifactId>
<groupId>io.entgra.device.mgt.core</groupId> <groupId>io.entgra.device.mgt.core</groupId>
<version>5.1.0</version> <version>6.0.1-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath> <relativePath>../../pom.xml</relativePath>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>analytics-mgt</artifactId> <artifactId>analytics-mgt</artifactId>
<packaging>pom</packaging> <packaging>pom</packaging>
<name>Entgra - Analytics Management Component</name> <name>Entgra Device Management - Analytics Management Component</name>
<url>http://entgra.io</url> <url>http://entgra.io</url>
<modules> <modules>

View File

@ -20,19 +20,25 @@
<parent> <parent>
<artifactId>apimgt-extensions</artifactId> <artifactId>apimgt-extensions</artifactId>
<groupId>io.entgra.device.mgt.core</groupId> <groupId>io.entgra.device.mgt.core</groupId>
<version>5.1.0</version> <version>6.0.1-SNAPSHOT</version>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>io.entgra.device.mgt.core.apimgt.analytics.extension</artifactId> <artifactId>io.entgra.device.mgt.core.apimgt.analytics.extension</artifactId>
<packaging>bundle</packaging> <packaging>bundle</packaging>
<name>Entgra - API mgt analytics extension</name> <name>Entgra Device Management - API mgt analytics extension</name>
<url>http://wso2.org</url> <url>https://entgra.io</url>
<dependencies> <dependencies>
<dependency>
<groupId>org.apache.felix</groupId>
<artifactId>org.apache.felix.scr.ds-annotations</artifactId>
<scope>provided</scope>
</dependency>
<dependency> <dependency>
<groupId>org.wso2.carbon</groupId> <groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.core</artifactId> <artifactId>org.wso2.carbon.core</artifactId>
<scope>provided</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.wso2.carbon</groupId> <groupId>org.wso2.carbon</groupId>
@ -40,8 +46,7 @@
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.apache.velocity</groupId> <groupId>org.apache.velocity</groupId>
<artifactId>velocity</artifactId> <artifactId>velocity-engine-core</artifactId>
<version>1.7</version>
</dependency> </dependency>
</dependencies> </dependencies>
@ -56,10 +61,6 @@
</excludes> </excludes>
</configuration> </configuration>
</plugin> </plugin>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-scr-plugin</artifactId>
</plugin>
<plugin> <plugin>
<groupId>org.apache.felix</groupId> <groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId> <artifactId>maven-bundle-plugin</artifactId>
@ -71,13 +72,12 @@
<Bundle-Version>${io.entgra.device.mgt.core.version}</Bundle-Version> <Bundle-Version>${io.entgra.device.mgt.core.version}</Bundle-Version>
<Bundle-Description>API Management Application Bundle</Bundle-Description> <Bundle-Description>API Management Application Bundle</Bundle-Description>
<Private-Package>io.entgra.device.mgt.core.apimgt.application.extension.internal</Private-Package> <Private-Package>io.entgra.device.mgt.core.apimgt.application.extension.internal</Private-Package>
<Import-Packages> <Import-Package>
io.entgra.device.mgt.core.apimgt.analytics.extension.dto,
org.apache.velocity, org.apache.velocity,
org.apache.velocity.app, org.apache.velocity.app,
org.apache.velocity.context, org.apache.velocity.context,
org.wso2.carbon.utils;version="[4.6,5)" org.wso2.carbon.utils;version="[4.8,5)"
</Import-Packages> </Import-Package>
<Export-Package> <Export-Package>
io.entgra.device.mgt.core.apimgt.analytics.extension.* io.entgra.device.mgt.core.apimgt.analytics.extension.*
</Export-Package> </Export-Package>

View File

@ -27,16 +27,11 @@ import io.entgra.device.mgt.core.apimgt.analytics.extension.exception.EventStrea
import org.apache.velocity.Template; import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext; import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine; import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants; import org.apache.velocity.runtime.RuntimeConstants;
import org.wso2.carbon.utils.CarbonUtils; import org.wso2.carbon.utils.CarbonUtils;
import org.wso2.carbon.utils.multitenancy.MultitenantConstants; import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
import java.io.File; import java.io.*;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
public class AnalyticsArtifactsDeployer { public class AnalyticsArtifactsDeployer {

View File

@ -22,45 +22,22 @@
<parent> <parent>
<artifactId>apimgt-extensions</artifactId> <artifactId>apimgt-extensions</artifactId>
<groupId>io.entgra.device.mgt.core</groupId> <groupId>io.entgra.device.mgt.core</groupId>
<version>5.1.0</version> <version>6.0.1-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>io.entgra.device.mgt.core.apimgt.annotations</artifactId> <artifactId>io.entgra.device.mgt.core.apimgt.annotations</artifactId>
<packaging>bundle</packaging> <packaging>bundle</packaging>
<name>WSO2 Carbon - API Management Annotations</name> <name>Entgra Device Management - API Management Annotations</name>
<description>WSO2 Carbon - API Management Custom Annotation Module</description> <description>Entgra Device Management - API Management Custom Annotation Module</description>
<url>http://wso2.org</url> <url>https://entgra.io</url>
<dependencies>
<dependency>
<groupId>org.eclipse.osgi</groupId>
<artifactId>org.eclipse.osgi</artifactId>
</dependency>
<dependency>
<groupId>org.eclipse.osgi</groupId>
<artifactId>org.eclipse.osgi.services</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.logging</artifactId>
</dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>jsr311-api</artifactId>
</dependency>
</dependencies>
<build> <build>
<plugins> <plugins>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-scr-plugin</artifactId>
</plugin>
<plugin> <plugin>
<groupId>org.apache.felix</groupId> <groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId> <artifactId>maven-bundle-plugin</artifactId>
<version>1.4.0</version>
<extensions>true</extensions> <extensions>true</extensions>
<configuration> <configuration>
<instructions> <instructions>
@ -68,21 +45,10 @@
<Bundle-Name>${project.artifactId}</Bundle-Name> <Bundle-Name>${project.artifactId}</Bundle-Name>
<Bundle-Version>${io.entgra.device.mgt.core.version}</Bundle-Version> <Bundle-Version>${io.entgra.device.mgt.core.version}</Bundle-Version>
<Bundle-Description>API Management Extentions - Custom Annotations</Bundle-Description> <Bundle-Description>API Management Extentions - Custom Annotations</Bundle-Description>
<Import-Package />
<Export-Package> <Export-Package>
io.entgra.device.mgt.core.apimgt.annotations.* io.entgra.device.mgt.core.apimgt.annotations.*
</Export-Package> </Export-Package>
<Import-Package>
org.osgi.framework.*;version="${imp.package.version.osgi.framework}",
org.osgi.service.*;version="${imp.package.version.osgi.service}",
org.apache.commons.logging,
javax.servlet,
javax.xml.*,
javax.xml.parsers;version="${javax.xml.parsers.import.pkg.version}";resolution:=optional,
org.apache.commons.lang
</Import-Package>
<Embed-Dependency>
scribe;scope=compile|runtime;inline=false;
</Embed-Dependency>
</instructions> </instructions>
</configuration> </configuration>
</plugin> </plugin>

View File

@ -21,16 +21,16 @@
<parent> <parent>
<artifactId>apimgt-extensions</artifactId> <artifactId>apimgt-extensions</artifactId>
<groupId>io.entgra.device.mgt.core</groupId> <groupId>io.entgra.device.mgt.core</groupId>
<version>5.1.0</version> <version>6.0.1-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>io.entgra.device.mgt.core.apimgt.application.extension.api</artifactId> <artifactId>io.entgra.device.mgt.core.apimgt.application.extension.api</artifactId>
<packaging>war</packaging> <packaging>war</packaging>
<name>WSO2 Carbon - API Application Management API</name> <name>Entgra Device Management - API Application Management API</name>
<description>This module provides capability to create api manager application.</description> <description>This module provides capability to create api manager application.</description>
<url>http://wso2.org</url> <url>https://entgra.io</url>
<dependencies> <dependencies>
<dependency> <dependency>
@ -164,16 +164,8 @@
<build> <build>
<plugins> <plugins>
<plugin> <plugin>
<artifactId>maven-compiler-plugin</artifactId> <groupId>org.apache.maven.plugins</groupId>
<configuration>
<encoding>UTF-8</encoding>
<source>${wso2.maven.compiler.source}</source>
<target>${wso2.maven.compiler.target}</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId> <artifactId>maven-war-plugin</artifactId>
<version>2.2</version>
<configuration> <configuration>
<warName>${project.artifactId}</warName> <warName>${project.artifactId}</warName>
</configuration> </configuration>

View File

@ -18,18 +18,18 @@
package io.entgra.device.mgt.core.apimgt.application.extension.api; package io.entgra.device.mgt.core.apimgt.application.extension.api;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import io.entgra.device.mgt.core.apimgt.application.extension.APIManagementProviderService; import io.entgra.device.mgt.core.apimgt.application.extension.APIManagementProviderService;
import io.entgra.device.mgt.core.apimgt.application.extension.api.util.APIUtil; import io.entgra.device.mgt.core.apimgt.application.extension.api.util.APIUtil;
import io.entgra.device.mgt.core.apimgt.application.extension.api.util.RegistrationProfile; import io.entgra.device.mgt.core.apimgt.application.extension.api.util.RegistrationProfile;
import io.entgra.device.mgt.core.apimgt.application.extension.constants.ApiApplicationConstants; import io.entgra.device.mgt.core.apimgt.application.extension.constants.ApiApplicationConstants;
import io.entgra.device.mgt.core.apimgt.application.extension.dto.ApiApplicationKey; import io.entgra.device.mgt.core.apimgt.application.extension.dto.ApiApplicationKey;
import io.entgra.device.mgt.core.apimgt.application.extension.exception.APIManagerException; import io.entgra.device.mgt.core.apimgt.application.extension.exception.APIManagerException;
import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.base.MultitenantConstants; import org.wso2.carbon.base.MultitenantConstants;
import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext;
import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException;
import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.api.UserStoreException;
import javax.ws.rs.POST; import javax.ws.rs.POST;
@ -64,7 +64,8 @@ public class ApiApplicationRegistrationServiceImpl implements ApiApplicationRegi
ApiApplicationKey apiApplicationKey = apiManagementProviderService.generateAndRetrieveApplicationKeys( ApiApplicationKey apiApplicationKey = apiManagementProviderService.generateAndRetrieveApplicationKeys(
applicationName, APIUtil.getDefaultTags(), applicationName, APIUtil.getDefaultTags(),
ApiApplicationConstants.DEFAULT_TOKEN_TYPE, username, false, ApiApplicationConstants.DEFAULT_TOKEN_TYPE, username, false,
ApiApplicationConstants.DEFAULT_VALIDITY_PERIOD); ApiApplicationConstants.DEFAULT_VALIDITY_PERIOD, PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm()
.getRealmConfiguration().getAdminPassword(), null, null, null, false);
return Response.status(Response.Status.CREATED).entity(apiApplicationKey.toString()).build(); return Response.status(Response.Status.CREATED).entity(apiApplicationKey.toString()).build();
} catch (APIManagerException e) { } catch (APIManagerException e) {
String msg = "Error occurred while registering an application '" + applicationName + "'"; String msg = "Error occurred while registering an application '" + applicationName + "'";
@ -110,7 +111,9 @@ public class ApiApplicationRegistrationServiceImpl implements ApiApplicationRegi
ApiApplicationKey apiApplicationKey = apiManagementProviderService.generateAndRetrieveApplicationKeys( ApiApplicationKey apiApplicationKey = apiManagementProviderService.generateAndRetrieveApplicationKeys(
applicationName, registrationProfile.getTags(), applicationName, registrationProfile.getTags(),
ApiApplicationConstants.DEFAULT_TOKEN_TYPE, username, ApiApplicationConstants.DEFAULT_TOKEN_TYPE, username,
registrationProfile.isAllowedToAllDomains(), validityPeriod); registrationProfile.isAllowedToAllDomains(), validityPeriod,
registrationProfile.getPassword(), null, registrationProfile.getSupportedGrantTypes(),
registrationProfile.getCallbackUrl(), false);
return Response.status(Response.Status.CREATED).entity(apiApplicationKey.toString()).build(); return Response.status(Response.Status.CREATED).entity(apiApplicationKey.toString()).build();
} }
} }
@ -122,7 +125,9 @@ public class ApiApplicationRegistrationServiceImpl implements ApiApplicationRegi
ApiApplicationKey apiApplicationKey = apiManagementProviderService.generateAndRetrieveApplicationKeys( ApiApplicationKey apiApplicationKey = apiManagementProviderService.generateAndRetrieveApplicationKeys(
applicationName, registrationProfile.getTags(), applicationName, registrationProfile.getTags(),
ApiApplicationConstants.DEFAULT_TOKEN_TYPE, registrationProfile.getUsername(), ApiApplicationConstants.DEFAULT_TOKEN_TYPE, registrationProfile.getUsername(),
registrationProfile.isAllowedToAllDomains(), validityPeriod); registrationProfile.isAllowedToAllDomains(), validityPeriod,
registrationProfile.getPassword(), null, registrationProfile.getSupportedGrantTypes(),
registrationProfile.getCallbackUrl(), false);
return Response.status(Response.Status.CREATED).entity(apiApplicationKey.toString()).build(); return Response.status(Response.Status.CREATED).entity(apiApplicationKey.toString()).build();
} }
} catch (APIManagerException e) { } catch (APIManagerException e) {

View File

@ -17,20 +17,15 @@
*/ */
package io.entgra.device.mgt.core.apimgt.application.extension.api.filter; package io.entgra.device.mgt.core.apimgt.application.extension.api.filter;
import io.entgra.device.mgt.core.apimgt.application.extension.api.util.APIUtil;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import io.entgra.device.mgt.core.apimgt.application.extension.api.util.APIUtil;
import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.user.api.UserRealm; import org.wso2.carbon.user.api.UserRealm;
import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.utils.multitenancy.MultitenantUtils; import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
import javax.servlet.Filter; import javax.servlet.*;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBContext;

View File

@ -18,13 +18,13 @@
package io.entgra.device.mgt.core.apimgt.application.extension.api.util; package io.entgra.device.mgt.core.apimgt.application.extension.api.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import io.entgra.device.mgt.core.apimgt.application.extension.APIManagementProviderService; import io.entgra.device.mgt.core.apimgt.application.extension.APIManagementProviderService;
import org.wso2.carbon.base.MultitenantConstants;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException;
import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService; import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.base.MultitenantConstants;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.registry.api.Resource; import org.wso2.carbon.registry.api.Resource;
import org.wso2.carbon.registry.core.Registry; import org.wso2.carbon.registry.core.Registry;
import org.wso2.carbon.registry.core.exceptions.RegistryException; import org.wso2.carbon.registry.core.exceptions.RegistryException;

View File

@ -22,6 +22,7 @@ import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlRootElement;
import java.util.ArrayList;
/** /**
* DTO class to be used when registering an ApiM application. * DTO class to be used when registering an ApiM application.
@ -43,6 +44,10 @@ public class RegistrationProfile {
@XmlElement(required = false) @XmlElement(required = false)
private String validityPeriod; private String validityPeriod;
private String callbackUrl;
private ArrayList<String> supportedGrantTypes;
public String getApplicationName() { public String getApplicationName() {
return applicationName; return applicationName;
} }
@ -90,4 +95,20 @@ public class RegistrationProfile {
public void setPassword(String password) { public void setPassword(String password) {
this.password = password; this.password = password;
} }
public String getCallbackUrl() {
return callbackUrl;
}
public void setCallbackUrl(String callbackUrl) {
this.callbackUrl = callbackUrl;
}
public ArrayList<String> getSupportedGrantTypes() {
return supportedGrantTypes;
}
public void setSupportedGrantTypes(ArrayList<String> supportedGrantTypes) {
this.supportedGrantTypes = supportedGrantTypes;
}
} }

View File

@ -22,37 +22,42 @@
<parent> <parent>
<artifactId>apimgt-extensions</artifactId> <artifactId>apimgt-extensions</artifactId>
<groupId>io.entgra.device.mgt.core</groupId> <groupId>io.entgra.device.mgt.core</groupId>
<version>5.1.0</version> <version>6.0.1-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>io.entgra.device.mgt.core.apimgt.application.extension</artifactId> <artifactId>io.entgra.device.mgt.core.apimgt.application.extension</artifactId>
<packaging>bundle</packaging> <packaging>bundle</packaging>
<name>WSO2 Carbon - API Application Management</name> <name>Entgra Device Management - API Application Management</name>
<description>This module provides capability to create api manager application.</description> <description>This module provides capability to create api manager application.</description>
<url>http://wso2.org</url> <url>https://entgra.io</url>
<dependencies> <dependencies>
<dependency>
<groupId>org.apache.felix</groupId>
<artifactId>org.apache.felix.scr.ds-annotations</artifactId>
<scope>provided</scope>
</dependency>
<dependency> <dependency>
<groupId>org.wso2.carbon</groupId> <groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.registry.core</artifactId> <artifactId>org.wso2.carbon.registry.core</artifactId>
<scope>provided</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.wso2.carbon</groupId> <groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.core</artifactId> <artifactId>org.wso2.carbon.core</artifactId>
<scope>provided</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.wso2.carbon</groupId> <groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.utils</artifactId> <artifactId>org.wso2.carbon.utils</artifactId>
</dependency> <scope>provided</scope>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.logging</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.wso2.carbon.apimgt</groupId> <groupId>org.wso2.carbon.apimgt</groupId>
<artifactId>org.wso2.carbon.apimgt.api</artifactId> <artifactId>org.wso2.carbon.apimgt.api</artifactId>
<scope>provided</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.wso2.carbon.apimgt</groupId> <groupId>org.wso2.carbon.apimgt</groupId>
@ -62,16 +67,33 @@
<dependency> <dependency>
<groupId>com.googlecode.json-simple.wso2</groupId> <groupId>com.googlecode.json-simple.wso2</groupId>
<artifactId>json-simple</artifactId> <artifactId>json-simple</artifactId>
<scope>provided</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.wso2.carbon.registry</groupId> <groupId>org.wso2.carbon.registry</groupId>
<artifactId>org.wso2.carbon.registry.indexing</artifactId> <artifactId>org.wso2.carbon.registry.indexing</artifactId>
<scope>provided</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>io.entgra.device.mgt.core</groupId> <groupId>io.entgra.device.mgt.core</groupId>
<artifactId>io.entgra.device.mgt.core.identity.jwt.client.extension</artifactId> <artifactId>io.entgra.device.mgt.core.identity.jwt.client.extension</artifactId>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<dependency>
<groupId>io.entgra.device.mgt.core</groupId>
<artifactId>io.entgra.device.mgt.core.apimgt.extension.rest.api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>io.entgra.device.mgt.core</groupId>
<artifactId>io.entgra.device.mgt.core.device.mgt.common</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<scope>provided</scope>
</dependency>
</dependencies> </dependencies>
<build> <build>
@ -85,10 +107,6 @@
</excludes> </excludes>
</configuration> </configuration>
</plugin> </plugin>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-scr-plugin</artifactId>
</plugin>
<plugin> <plugin>
<groupId>org.apache.felix</groupId> <groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId> <artifactId>maven-bundle-plugin</artifactId>
@ -100,32 +118,35 @@
<Bundle-Version>${io.entgra.device.mgt.core.version}</Bundle-Version> <Bundle-Version>${io.entgra.device.mgt.core.version}</Bundle-Version>
<Bundle-Description>API Management Application Bundle</Bundle-Description> <Bundle-Description>API Management Application Bundle</Bundle-Description>
<Private-Package>io.entgra.device.mgt.core.apimgt.application.extension.internal</Private-Package> <Private-Package>io.entgra.device.mgt.core.apimgt.application.extension.internal</Private-Package>
<Import-Packages> <Import-Package>
org.apache.commons.lang;version="[2.6,3)",
org.apache.commons.logging;version="[1.2,2)",
org.json.simple,
org.osgi.framework.*;version="${imp.package.version.osgi.framework}",
org.osgi.service.*;version="${imp.package.version.osgi.service}",
org.wso2.carbon.apimgt.api;version="${carbon.api.mgt.version.range}",
org.wso2.carbon.apimgt.api.dto;version="${carbon.api.mgt.version.range}",
org.wso2.carbon.apimgt.api.model;version="${carbon.api.mgt.version.range}",
io.entgra.device.mgt.core.apimgt.application.extension.bean, io.entgra.device.mgt.core.apimgt.application.extension.bean,
io.entgra.device.mgt.core.apimgt.application.extension.dto, io.entgra.device.mgt.core.apimgt.application.extension.dto,
io.entgra.device.mgt.core.apimgt.application.extension.exception, io.entgra.device.mgt.core.apimgt.application.extension.exception,
org.wso2.carbon.apimgt.impl;version="${carbon.api.mgt.version.range}", io.entgra.device.mgt.core.apimgt.extension.rest.api;version="${io.entgra.device.mgt.core.version.range}",
org.wso2.carbon.apimgt.impl.utils;version="${carbon.api.mgt.version.range}", io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer;version="${io.entgra.device.mgt.core.version.range}",
org.wso2.carbon.context;version="${carbon.kernel.version.range}", io.entgra.device.mgt.core.apimgt.extension.rest.api.dto;version="${io.entgra.device.mgt.core.version.range}",
io.entgra.device.mgt.core.identity.jwt.client.extension, io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions;version="${io.entgra.device.mgt.core.version.range}",
io.entgra.device.mgt.core.identity.jwt.client.extension.dto, io.entgra.device.mgt.core.device.mgt.common.exceptions;version="${io.entgra.device.mgt.core.version.range}",
io.entgra.device.mgt.core.identity.jwt.client.extension.exception, io.entgra.device.mgt.core.device.mgt.common.metadata.mgt;version="${io.entgra.device.mgt.core.version.range}",
io.entgra.device.mgt.core.identity.jwt.client.extension.service, io.entgra.device.mgt.core.identity.jwt.client.extension;version="${io.entgra.device.mgt.core.version.range}",
org.wso2.carbon.registry.core.exceptions;version="[1.0,2)", io.entgra.device.mgt.core.identity.jwt.client.extension.dto;version="${io.entgra.device.mgt.core.version.range}",
io.entgra.device.mgt.core.identity.jwt.client.extension.exception;version="${io.entgra.device.mgt.core.version.range}",
io.entgra.device.mgt.core.identity.jwt.client.extension.service;version="${io.entgra.device.mgt.core.version.range}",
org.apache.commons.lang;version="[2.6,3)",
org.apache.commons.logging;version="[1.2,2)",
org.json.simple;version="[1.1,2)",
org.osgi.framework;version="${imp.package.version.osgi.framework}",
org.osgi.service.component;version="${imp.package.version.osgi.service}",
org.wso2.carbon.apimgt.api;version="[9.28,10)",
org.wso2.carbon.apimgt.impl;version="[9.28,10)",
org.wso2.carbon.apimgt.impl.utils;version="[9.28,10)",
org.wso2.carbon.context;version="[4.8,5)",org.wso2.carbon.registry.core.exceptions;version="[1.0,2)",
org.wso2.carbon.registry.core.service;version="[1.0,2)", org.wso2.carbon.registry.core.service;version="[1.0,2)",
org.wso2.carbon.registry.indexing.service;version="${carbon.registry.imp.pkg.version.range}", org.wso2.carbon.registry.indexing.service;version="[4.8,5)",
org.wso2.carbon.user.api;version="[1.0,2)", org.wso2.carbon.user.api;version="[1.0,2)",
org.wso2.carbon.user.core.service;version="${carbon.kernel.version.range}", org.wso2.carbon.user.core.service;version="[4.8,5)",
org.wso2.carbon.user.core.tenant;version="${carbon.kernel.version.range}" org.wso2.carbon.user.core.tenant;version="[4.8,5)"
</Import-Packages> </Import-Package>
<Export-Package> <Export-Package>
!io.entgra.device.mgt.core.apimgt.application.extension.internal, !io.entgra.device.mgt.core.apimgt.application.extension.internal,
io.entgra.device.mgt.core.apimgt.application.extension.* io.entgra.device.mgt.core.apimgt.application.extension.*

View File

@ -22,6 +22,8 @@ import io.entgra.device.mgt.core.apimgt.application.extension.dto.ApiApplication
import io.entgra.device.mgt.core.apimgt.application.extension.exception.APIManagerException; import io.entgra.device.mgt.core.apimgt.application.extension.exception.APIManagerException;
import io.entgra.device.mgt.core.identity.jwt.client.extension.dto.AccessTokenInfo; import io.entgra.device.mgt.core.identity.jwt.client.extension.dto.AccessTokenInfo;
import java.util.ArrayList;
/** /**
* This comprise on operation that is been done with api manager from CDMF. This service needs to be implemented in APIM. * This comprise on operation that is been done with api manager from CDMF. This service needs to be implemented in APIM.
*/ */
@ -33,27 +35,14 @@ public interface APIManagementProviderService {
*/ */
boolean isTierLoaded(); boolean isTierLoaded();
/** ApiApplicationKey generateAndRetrieveApplicationKeys(String applicationName, String[] tags,
* Generate and retreive application keys. if the application does exist then String keyType, String username,
* create it and subscribe to apis that are grouped with the tags. boolean isAllowedAllDomains,
* String validityTime,
* @param apiApplicationName name of the application. String password, String accessToken,
* @param tags tags of the apis that application needs to be subscribed. ArrayList<String> supportedGrantTypes,
* @param keyType of the application. String callbackUrl,
* @param username to whom the application is created boolean isMappingRequired) throws APIManagerException;
* @param isAllowedAllDomains application is allowed to all the tenants
* @param validityTime validity period of the application
* @return consumerkey and secrete of the created application.
* @throws APIManagerException
*/
ApiApplicationKey generateAndRetrieveApplicationKeys(String apiApplicationName, String tags[],
String keyType, String username, boolean isAllowedAllDomains,
String validityTime) throws APIManagerException;
/**
* Remove APIM Application.
*/
void removeAPIApplication(String applicationName, String username) throws APIManagerException;
/** /**
* To get access token for given scopes and for the given validity period * To get access token for given scopes and for the given validity period

View File

@ -18,42 +18,47 @@
package io.entgra.device.mgt.core.apimgt.application.extension; package io.entgra.device.mgt.core.apimgt.application.extension;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.apimgt.api.APIAdmin;
import org.wso2.carbon.apimgt.api.APIConsumer;
import org.wso2.carbon.apimgt.api.APIManagementException;
import org.wso2.carbon.apimgt.api.dto.KeyManagerConfigurationDTO;
import org.wso2.carbon.apimgt.api.model.API;
import org.wso2.carbon.apimgt.api.model.APIKey;
import org.wso2.carbon.apimgt.api.model.ApiTypeWrapper;
import org.wso2.carbon.apimgt.api.model.Application;
import org.wso2.carbon.apimgt.api.model.SubscribedAPI;
import org.wso2.carbon.apimgt.api.model.Subscriber;
import io.entgra.device.mgt.core.apimgt.application.extension.bean.APIRegistrationProfile; import io.entgra.device.mgt.core.apimgt.application.extension.bean.APIRegistrationProfile;
import io.entgra.device.mgt.core.apimgt.application.extension.constants.ApiApplicationConstants;
import io.entgra.device.mgt.core.apimgt.application.extension.dto.ApiApplicationKey; import io.entgra.device.mgt.core.apimgt.application.extension.dto.ApiApplicationKey;
import io.entgra.device.mgt.core.apimgt.application.extension.exception.APIManagerException; import io.entgra.device.mgt.core.apimgt.application.extension.exception.APIManagerException;
import io.entgra.device.mgt.core.apimgt.application.extension.internal.APIApplicationManagerExtensionDataHolder; import io.entgra.device.mgt.core.apimgt.application.extension.internal.APIApplicationManagerExtensionDataHolder;
import io.entgra.device.mgt.core.apimgt.application.extension.util.APIManagerUtil; import io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer.APIInfo;
import org.wso2.carbon.apimgt.impl.APIAdminImpl; import io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer.ApplicationKey;
import org.wso2.carbon.apimgt.impl.APIConstants; import io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer.KeyManager;
import org.wso2.carbon.apimgt.impl.APIManagerFactory; import io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer.Subscription;
import org.wso2.carbon.apimgt.impl.utils.APIUtil; import io.entgra.device.mgt.core.device.mgt.common.exceptions.MetadataKeyAlreadyExistsException;
import org.wso2.carbon.context.PrivilegedCarbonContext; import io.entgra.device.mgt.core.device.mgt.common.exceptions.MetadataManagementException;
import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.Metadata;
import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.MetadataManagementService;
import io.entgra.device.mgt.core.identity.jwt.client.extension.JWTClient; import io.entgra.device.mgt.core.identity.jwt.client.extension.JWTClient;
import io.entgra.device.mgt.core.identity.jwt.client.extension.dto.AccessTokenInfo; import io.entgra.device.mgt.core.identity.jwt.client.extension.dto.AccessTokenInfo;
import io.entgra.device.mgt.core.identity.jwt.client.extension.exception.JWTClientException; import io.entgra.device.mgt.core.identity.jwt.client.extension.exception.JWTClientException;
import io.entgra.device.mgt.core.identity.jwt.client.extension.service.JWTClientManagerService; import io.entgra.device.mgt.core.identity.jwt.client.extension.service.JWTClientManagerService;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.APIApplicationServices;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.ConsumerRESTAPIServices;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIApplicationKey;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.ApiApplicationInfo;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.APIServicesException;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.BadRequestException;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.UnexpectedResponseException;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.apimgt.api.APIManagementException;
import org.wso2.carbon.apimgt.impl.APIConstants;
import org.wso2.carbon.apimgt.impl.APIManagerFactory;
import org.wso2.carbon.apimgt.impl.utils.APIUtil;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.utils.multitenancy.MultitenantConstants; import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashSet; import java.util.Arrays;
import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Objects;
import java.util.Optional;
/** /**
* This class represents an implementation of APIManagementProviderService. * This class represents an implementation of APIManagementProviderService.
@ -62,6 +67,7 @@ public class APIManagementProviderServiceImpl implements APIManagementProviderSe
private static final Log log = LogFactory.getLog(APIManagementProviderServiceImpl.class); private static final Log log = LogFactory.getLog(APIManagementProviderServiceImpl.class);
public static final APIManagerFactory API_MANAGER_FACTORY = APIManagerFactory.getInstance(); public static final APIManagerFactory API_MANAGER_FACTORY = APIManagerFactory.getInstance();
private static final String UNLIMITED_TIER = "Unlimited";
@Override @Override
public boolean isTierLoaded() { public boolean isTierLoaded() {
@ -79,219 +85,235 @@ public class APIManagementProviderServiceImpl implements APIManagementProviderSe
} }
@Override @Override
public void removeAPIApplication(String applicationName, String username) throws APIManagerException { public synchronized ApiApplicationKey generateAndRetrieveApplicationKeys(String applicationName, String[] tags,
String keyType, String username,
boolean isAllowedAllDomains,
String validityTime,
String password, String accessToken,
ArrayList<String> supportedGrantTypes,
String callbackUrl,
boolean isMappingRequired)
throws APIManagerException {
try { ApiApplicationInfo apiApplicationInfo = new ApiApplicationInfo();
APIConsumer apiConsumer = API_MANAGER_FACTORY.getAPIConsumer(username); if (StringUtils.isEmpty(accessToken)) {
Application application = apiConsumer.getApplicationsByName(username, applicationName, ""); apiApplicationInfo = getApplicationInfo(username, password);
if (application != null) { } else {
apiConsumer.removeApplication(application, username); apiApplicationInfo.setAccess_token(accessToken);
}
} catch (APIManagementException e) {
throw new APIManagerException("Failed to remove api application : " + applicationName, e);
} }
ConsumerRESTAPIServices consumerRESTAPIServices =
APIApplicationManagerExtensionDataHolder.getInstance().getConsumerRESTAPIServices();
try {
Map<String, String> headerParams = new HashMap<>();
if (!"carbon.super".equals(PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(true))) {
headerParams.put("X-WSO2-Tenant", "carbon.super");
}
Map<String, APIInfo> uniqueApiSet = new HashMap<>();
if (tags != null) {
for (String tag : tags) {
Map<String, String> queryParams = new HashMap<>();
queryParams.put("tag", tag);
APIInfo[] apiInfos = consumerRESTAPIServices.getAllApis(apiApplicationInfo, queryParams, headerParams);
Arrays.stream(apiInfos).forEach(apiInfo -> uniqueApiSet.putIfAbsent(apiInfo.getName(), apiInfo));
}
}
List<APIInfo> uniqueApiList = new ArrayList<>(uniqueApiSet.values());
io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer.Application[] applications =
consumerRESTAPIServices.getAllApplications(apiApplicationInfo, applicationName);
if (applications.length == 0) {
return handleNewAPIApplication(applicationName, uniqueApiList, apiApplicationInfo, keyType,
validityTime, supportedGrantTypes, callbackUrl, isMappingRequired);
} else {
if (applications.length == 1) {
Optional<io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer.Application> applicationOpt =
Arrays.stream(applications).findFirst();
io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer.Application application =
applicationOpt.get();
MetadataManagementService metadataManagementService = APIApplicationManagerExtensionDataHolder.getInstance().getMetadataManagementService();
Metadata metaData = metadataManagementService.retrieveMetadata(applicationName);
if (metaData == null) {
// Todo add a comment
consumerRESTAPIServices.deleteApplication(apiApplicationInfo, application.getApplicationId());
return handleNewAPIApplication(applicationName, uniqueApiList, apiApplicationInfo, keyType,
validityTime, supportedGrantTypes, callbackUrl, isMappingRequired);
} else {
Subscription[] subscriptions = consumerRESTAPIServices.getAllSubscriptions(apiApplicationInfo, application.getApplicationId());
for (Subscription subscription : subscriptions) {
uniqueApiList.removeIf(apiInfo -> Objects.equals(apiInfo.getId(), subscription.getApiInfo().getId()));
}
if (!uniqueApiList.isEmpty()) {
addSubscriptions(application, uniqueApiList, apiApplicationInfo);
}
String[] metaValues = metaData.getMetaValue().split(":");
if (metaValues.length != 2) {
String msg = "Found invalid Meta value for meta key: " + applicationName + ". Meta Value: "
+ metaData.getMetaValue();
log.error(msg);
throw new APIManagerException(msg);
}
String applicationId = metaValues[0];
String keyMappingId = metaValues[1];
ApplicationKey applicationKey = consumerRESTAPIServices.getKeyDetails(apiApplicationInfo, applicationId, keyMappingId);
ApiApplicationKey apiApplicationKey = new ApiApplicationKey();
apiApplicationKey.setConsumerKey(applicationKey.getConsumerKey());
apiApplicationKey.setConsumerSecret(applicationKey.getConsumerSecret());
return apiApplicationKey;
}
} else {
String msg = "Found more than one application for application name: " + applicationName;
log.error(msg);
throw new APIManagerException(msg);
}
}
} catch (APIServicesException e) {
String msg = "Error occurred while processing the response of APIM REST endpoints.";
log.error(msg, e);
throw new APIManagerException(msg, e);
} catch (BadRequestException e) {
String msg = "Provided incorrect payload when invoking APIM REST endpoints.";
log.error(msg, e);
throw new APIManagerException(msg, e);
} catch (UnexpectedResponseException e) {
String msg = "Error occurred while invoking APIM REST endpoints.";
log.error(msg, e);
throw new APIManagerException(msg, e);
} catch (MetadataManagementException e) {
String msg = "Error occurred while getting meta data for meta key: " + applicationName;
log.error(msg, e);
throw new APIManagerException(msg, e);
}
}
private ApiApplicationKey handleNewAPIApplication(String applicationName, List<APIInfo> uniqueApiList,
ApiApplicationInfo apiApplicationInfo, String keyType, String validityTime,
ArrayList<String> supportedGrantTypes, String callbackUrl,
boolean isMappingRequired) throws APIManagerException {
ConsumerRESTAPIServices consumerRESTAPIServices =
APIApplicationManagerExtensionDataHolder.getInstance().getConsumerRESTAPIServices();
io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer.Application application = new io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer.Application();
application.setName(applicationName);
application.setThrottlingPolicy(UNLIMITED_TIER);
try {
application = consumerRESTAPIServices.createApplication(apiApplicationInfo, application);
addSubscriptions(application, uniqueApiList, apiApplicationInfo);
KeyManager[] keyManagers = consumerRESTAPIServices.getAllKeyManagers(apiApplicationInfo);
KeyManager keyManager;
if (keyManagers.length == 1) {
keyManager = keyManagers[0];
} else {
String msg =
"Found invalid number of key managers. No of key managers found from the APIM: " + keyManagers.length;
log.error(msg);
throw new APIManagerException(msg);
}
ApplicationKey applicationKey;
if (isMappingRequired) {
// If we need to get opaque token instead of the JWT token, we have to do the mapping. Therefore, if
// it is a requirement then we have to call the method with enabling the flag.
APIApplicationServices apiApplicationServices = APIApplicationManagerExtensionDataHolder.getInstance()
.getApiApplicationServices();
APIApplicationKey apiApplicationKey = apiApplicationServices.createAndRetrieveApplicationCredentials(
"ClientForMapping",
"client_credentials password refresh_token urn:ietf:params:oauth:grant-type:jwt-bearer");
apiApplicationInfo.setClientId(apiApplicationKey.getClientId());
apiApplicationInfo.setClientSecret(apiApplicationKey.getClientSecret());
applicationKey = consumerRESTAPIServices.mapApplicationKeys(apiApplicationInfo, application,
keyManager.getName(), keyType);
} else {
applicationKey = consumerRESTAPIServices.generateApplicationKeys(apiApplicationInfo, application.getApplicationId(),
keyManager.getName(), validityTime, keyType);
}
if (supportedGrantTypes != null || StringUtils.isNotEmpty(callbackUrl)) {
applicationKey = consumerRESTAPIServices.updateGrantType(apiApplicationInfo, application.getApplicationId(),
applicationKey.getKeyMappingId(), keyManager.getName(), supportedGrantTypes, callbackUrl);
}
ApiApplicationKey apiApplicationKey = new ApiApplicationKey();
apiApplicationKey.setConsumerKey(applicationKey.getConsumerKey());
apiApplicationKey.setConsumerSecret(applicationKey.getConsumerSecret());
Metadata metaData = new Metadata();
metaData.setMetaKey(applicationName);
String metaValue = application.getApplicationId() + ":" + applicationKey.getKeyMappingId();
metaData.setMetaValue(metaValue);
MetadataManagementService metadataManagementService = APIApplicationManagerExtensionDataHolder.getInstance().getMetadataManagementService();
metadataManagementService.createMetadata(metaData);
return apiApplicationKey;
} catch (MetadataKeyAlreadyExistsException e) {
String msg = "Since meta key:" + applicationName + " already exists, meta data creating process failed.";
log.error(msg, e);
throw new APIManagerException(msg, e);
} catch (MetadataManagementException e) {
String msg = "Error occurred while creating meta data for meta key: " + applicationName;
log.error(msg, e);
throw new APIManagerException(msg, e);
} catch (BadRequestException e) {
String msg = "Provided incorrect payload when invoking APIM REST endpoints to handle new API application.";
log.error(msg, e);
throw new APIManagerException(msg, e);
} catch (UnexpectedResponseException e) {
String msg = "Error occurred while invoking APIM REST endpoints to handle new API application.";
log.error(msg, e);
throw new APIManagerException(msg, e);
} catch (APIServicesException e) {
String msg = "Error occurred while processing the response of APIM REST endpoints to handle new API application.";
log.error(msg, e);
throw new APIManagerException(msg, e);
}
} }
/** /**
* {@inheritDoc} * This method can be used to add a new subscriptions providing the ids of the APIs and the applications.
*
* @param application {@link io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer.Application}
* @param apiInfos {@link List<APIInfo>}
* @param apiApplicationInfo {@link ApiApplicationInfo}
* @throws BadRequestException if incorrect data provided to call subscribing REST API.
* @throws UnexpectedResponseException if error occurred while processing the subscribing REST API.
* @throws APIServicesException if error occurred while invoking the subscribing REST API.
*/ */
@Override private void addSubscriptions(
public synchronized ApiApplicationKey generateAndRetrieveApplicationKeys(String applicationName, String tags[], io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer.Application application,
String keyType, String username, boolean isAllowedAllDomains, String validityTime) List<APIInfo> apiInfos, ApiApplicationInfo apiApplicationInfo)
throws APIManagerException { throws BadRequestException, UnexpectedResponseException, APIServicesException {
String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(); ConsumerRESTAPIServices consumerRESTAPIServices =
if (StringUtils.isEmpty(username)) { APIApplicationManagerExtensionDataHolder.getInstance().getConsumerRESTAPIServices();
username = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername() + "@" + tenantDomain;
}
try {
APIConsumer apiConsumer = API_MANAGER_FACTORY.getAPIConsumer(username);
Application application = apiConsumer.getApplicationsByName(username, applicationName, "");
int applicationId = 0; List<Subscription> subscriptionList = new ArrayList<>();
Subscriber subscriber = null; apiInfos.forEach(apiInfo -> {
if (application == null) { Subscription subscription = new Subscription();
subscriber = apiConsumer.getSubscriber(username); subscription.setApiId(apiInfo.getId());
if (subscriber == null) { subscription.setApplicationId(application.getApplicationId());
// create subscriber subscription.setThrottlingPolicy(UNLIMITED_TIER);
apiConsumer.addSubscriber(username, ""); subscription.setRequestedThrottlingPolicy(UNLIMITED_TIER);
subscriber = apiConsumer.getSubscriber(username); subscriptionList.add(subscription);
} });
//create application
application = new Application(applicationName, subscriber);
application.setTier(ApiApplicationConstants.DEFAULT_TIER);
application.setGroupId("");
application.setTokenType("OAUTH");
apiConsumer.addApplication(application, username);
application = apiConsumer.getApplicationsByName(username, applicationName, "");
} else {
subscriber = apiConsumer.getSubscriber(username);
}
Set<SubscribedAPI> subscribedAPIs = consumerRESTAPIServices.createSubscriptions(apiApplicationInfo, subscriptionList);
apiConsumer.getSubscribedAPIs(subscriber, applicationName, "");
log.info("Already subscribed API count: " + subscribedAPIs.size());
// subscribe to apis.
Set<String> tempApiIds = new HashSet<>();
APIConsumer apiConsumerAPIPublishedTenant = apiConsumer;
if (tags != null && tags.length > 0) {
for (String tag : tags) {
boolean startedTenantFlow = false;
Set<API> apisWithTag = apiConsumer.getAPIsWithTag(tag, tenantDomain);
/**
* From APIM 4.0.0, APIs published in the super tenant can only be listed by
* APIConsumer, only if the APIConsumer belongs to the super tenant. So we
* are starting tenant flow if we are not already in super tenant(child
* tenant starting to create OAuth app).
*/
if (apisWithTag == null || apisWithTag.size() == 0) {
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME,
true);
try {
String superAdminUsername = PrivilegedCarbonContext
.getThreadLocalCarbonContext().getUserRealm().getRealmConfiguration().getAdminUserName();
apiConsumerAPIPublishedTenant = API_MANAGER_FACTORY.getAPIConsumer(superAdminUsername);
} catch (UserStoreException e) {
throw new APIManagerException("Failed to create api application for " +
"tenant: " + tenantDomain +
". Caused by to inability to get super tenant username", e);
}
apisWithTag = apiConsumerAPIPublishedTenant.getAPIsWithTag(tag, MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
startedTenantFlow = true;
}
Set<ApiTypeWrapper> apiTypeWrapperList = new HashSet<>();
if (apisWithTag != null && apisWithTag.size() > 0) {
for (API apiInfo : apisWithTag) {
String id = apiInfo.getId().getProviderName().replace("@", "-AT-")
+ "-" + apiInfo.getId().getName() + "-" + apiInfo.getId().getVersion();
boolean subscriptionExist = false;
if (subscribedAPIs.size() > 0) {
for (SubscribedAPI subscribedAPI : subscribedAPIs) {
if (String.valueOf(subscribedAPI.getApiId().toString()).equals(id)) {
subscriptionExist = true;
break;
}
}
}
if (!subscriptionExist && !tempApiIds.contains(id)) {
ApiTypeWrapper apiTypeWrapper;
if (startedTenantFlow) {
/**
* This mean APIs were not found in the child tenant, so all
* calls to get info about APIs need to be to super tenant.
*/
apiTypeWrapper = apiConsumerAPIPublishedTenant.getAPIorAPIProductByUUID(
apiInfo.getUuid(), MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
} else {
/**
* Ideally, in all usecases of IoT server, tenant domain here
* will be carbon.super. This block is kept to make sure in
* the future, if there are some APIs published to a specific
* tenant only.
*/
apiTypeWrapper = apiConsumerAPIPublishedTenant.getAPIorAPIProductByUUID(
apiInfo.getUuid(), tenantDomain);
}
apiTypeWrapper.setTier(ApiApplicationConstants.DEFAULT_TIER);
apiTypeWrapperList.add(apiTypeWrapper);
tempApiIds.add(id);
}
}
if (startedTenantFlow) {
PrivilegedCarbonContext.endTenantFlow();
}
/** This is done in a redundant loop instead of doing in the same loop
* that populates apiTypeWrapperList because in a tenanted scenario,
* apiConsumerAPIPublishedTenant will belong to super tenant. So super
* tenant flow need to end before starting subscription to avoid adding
* subscriptions inside super tenant when we are trying to create an
* Oauth app for a child tenant.
*/
for (ApiTypeWrapper apiTypeWrapper : apiTypeWrapperList) {
apiConsumer.addSubscription(apiTypeWrapper, username, application);
}
}
}
}
//end of subscription
List<APIKey> applicationKeys = application.getKeys();
if (applicationKeys != null) {
for (APIKey applicationKey : applicationKeys) {
if (keyType.equals(applicationKey.getType())) {
if (applicationKey.getConsumerKey() != null && !applicationKey.getConsumerKey().isEmpty()) {
ApiApplicationKey apiApplicationKey = new ApiApplicationKey();
apiApplicationKey.setConsumerKey(applicationKey.getConsumerKey());
apiApplicationKey.setConsumerSecret(applicationKey.getConsumerSecret());
return apiApplicationKey;
}
}
}
}
List<String> allowedDomains = new ArrayList<>();
if (isAllowedAllDomains) {
allowedDomains.add(ApiApplicationConstants.ALLOWED_DOMAINS);
} else {
allowedDomains.add(APIManagerUtil.getTenantDomain());
}
APIAdmin apiAdmin = new APIAdminImpl();
String keyManagerId = null;
try {
List<KeyManagerConfigurationDTO> keyManagerConfigurations = apiAdmin
.getKeyManagerConfigurationsByTenant(tenantDomain);
if (keyManagerConfigurations != null) {
for (KeyManagerConfigurationDTO keyManagerConfigurationDTO : keyManagerConfigurations) {
keyManagerId = keyManagerConfigurationDTO.getUuid();
}
}
String applicationAccessTokenExpiryTime = "N/A";
if (!StringUtils.isEmpty(validityTime)) {
applicationAccessTokenExpiryTime = validityTime;
}
String jsonString = "{\"grant_types\":\"refresh_token,access_token," +
"urn:ietf:params:oauth:grant-type:saml2-bearer," +
"password,client_credentials,iwa:ntlm,urn:ietf:params:oauth:grant-type:jwt-bearer\"," +
"\"additionalProperties\":\"{\\\"application_access_token_expiry_time\\\":\\\"" + applicationAccessTokenExpiryTime + "\\\"," +
"\\\"user_access_token_expiry_time\\\":\\\"N\\/A\\\"," +
"\\\"refresh_token_expiry_time\\\":\\\"N\\/A\\\"," +
"\\\"id_token_expiry_time\\\":\\\"N\\/A\\\"}\"," +
"\"username\":\"" + username + "\"}";
Map<String, Object> keyDetails = apiConsumer
.requestApprovalForApplicationRegistration(username, applicationName, keyType, "",
allowedDomains.toArray(new String[allowedDomains.size()]), validityTime, "default", "",
jsonString, keyManagerId, tenantDomain);
if (keyDetails != null) {
ApiApplicationKey apiApplicationKey = new ApiApplicationKey();
apiApplicationKey.setConsumerKey((String) keyDetails.get("consumerKey"));
apiApplicationKey.setConsumerSecret((String) keyDetails.get("consumerSecret"));
return apiApplicationKey;
}
throw new APIManagerException("Failed to generate keys for tenant: " + tenantDomain);
} catch (APIManagementException e) {
throw new APIManagerException("Failed to create api application for tenant: " + tenantDomain, e);
}
} catch (APIManagementException e) {
throw new APIManagerException("Failed to create api application for tenant: " + tenantDomain, e);
}
} }
@Override @Override
public AccessTokenInfo getAccessToken(String scopes, String[] tags, String applicationName, String tokenType, public AccessTokenInfo getAccessToken(String scopes, String[] tags, String applicationName, String tokenType,
String validityPeriod, String username) throws APIManagerException { String validityPeriod, String username) throws APIManagerException {
try { try {
String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(true); String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(true);
ApiApplicationKey clientCredentials = getClientCredentials(tenantDomain, tags, applicationName, tokenType, ApiApplicationKey clientCredentials = getClientCredentials(tenantDomain, tags, applicationName, tokenType,
@ -317,11 +339,10 @@ public class APIManagementProviderServiceImpl implements APIManagementProviderSe
JWTClientManagerService jwtClientManagerService = APIApplicationManagerExtensionDataHolder.getInstance() JWTClientManagerService jwtClientManagerService = APIApplicationManagerExtensionDataHolder.getInstance()
.getJwtClientManagerService(); .getJwtClientManagerService();
JWTClient jwtClient = jwtClientManagerService.getJWTClient(); JWTClient jwtClient = jwtClientManagerService.getJWTClient();
AccessTokenInfo accessTokenForAdmin = jwtClient
return jwtClient
.getAccessToken(clientCredentials.getConsumerKey(), clientCredentials.getConsumerSecret(), username, .getAccessToken(clientCredentials.getConsumerKey(), clientCredentials.getConsumerSecret(), username,
scopes); scopes);
return accessTokenForAdmin;
} catch (JWTClientException e) { } catch (JWTClientException e) {
String msg = "JWT Error occurred while registering Application to get access token."; String msg = "JWT Error occurred while registering Application to get access token.";
log.error(msg, e); log.error(msg, e);
@ -338,18 +359,19 @@ public class APIManagementProviderServiceImpl implements APIManagementProviderSe
} }
/** /**
* Get Client credentials * Get Client credentials of application belongs to tenant admin
* @param tenantDomain Tenant Domain *
* @param tags Tags * @param tenantDomain Tenant Domain
* @param tags Tags
* @param applicationName Application Name * @param applicationName Application Name
* @param tokenType Token Type * @param tokenType Token Type
* @param validityPeriod Validity Period * @param validityPeriod Validity Period
* @return {@link ApiApplicationKey} * @return {@link ApiApplicationKey}
* @throws APIManagerException if error occurred while generating access token * @throws APIManagerException if error occurred while generating access token
* @throws UserStoreException if error ocurred while getting admin username. * @throws UserStoreException if error occurred while getting admin username.
*/ */
private ApiApplicationKey getClientCredentials(String tenantDomain, String[] tags, String applicationName, private ApiApplicationKey getClientCredentials(String tenantDomain, String[] tags, String applicationName,
String tokenType, String validityPeriod) throws APIManagerException, UserStoreException { String tokenType, String validityPeriod) throws APIManagerException, UserStoreException {
APIRegistrationProfile registrationProfile = new APIRegistrationProfile(); APIRegistrationProfile registrationProfile = new APIRegistrationProfile();
registrationProfile.setAllowedToAllDomains(false); registrationProfile.setAllowedToAllDomains(false);
@ -357,7 +379,6 @@ public class APIManagementProviderServiceImpl implements APIManagementProviderSe
registrationProfile.setTags(tags); registrationProfile.setTags(tags);
registrationProfile.setApplicationName(applicationName); registrationProfile.setApplicationName(applicationName);
ApiApplicationKey info = null;
if (tenantDomain == null || tenantDomain.isEmpty()) { if (tenantDomain == null || tenantDomain.isEmpty()) {
tenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME; tenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
} }
@ -368,14 +389,49 @@ public class APIManagementProviderServiceImpl implements APIManagementProviderSe
PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm().getRealmConfiguration() PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm().getRealmConfiguration()
.getAdminUserName()); .getAdminUserName());
if (registrationProfile.getUsername() == null || registrationProfile.getUsername().isEmpty()) { return generateAndRetrieveApplicationKeys(registrationProfile.getApplicationName(),
info = generateAndRetrieveApplicationKeys(registrationProfile.getApplicationName(), registrationProfile.getTags(), tokenType, PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm()
registrationProfile.getTags(), tokenType, null, .getRealmConfiguration().getAdminUserName(),
registrationProfile.isAllowedToAllDomains(), validityPeriod); registrationProfile.isAllowedToAllDomains(), validityPeriod, PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm()
} .getRealmConfiguration().getAdminPassword(), null, null, null, false);
} finally { } finally {
PrivilegedCarbonContext.endTenantFlow(); PrivilegedCarbonContext.endTenantFlow();
} }
return info; }
private ApiApplicationInfo getApplicationInfo(String username, String password)
throws APIManagerException {
APIApplicationServices apiApplicationServices = APIApplicationManagerExtensionDataHolder.getInstance()
.getApiApplicationServices();
APIApplicationKey apiApplicationKey;
io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.AccessTokenInfo accessTokenInfo;
try {
if (username == null || password == null) {
apiApplicationKey = apiApplicationServices.createAndRetrieveApplicationCredentials(
"ClientForConsumerRestCalls",
"client_credentials password refresh_token urn:ietf:params:oauth:grant-type:jwt-bearer");
} else {
apiApplicationKey = apiApplicationServices.createAndRetrieveApplicationCredentialsWithUser(
"ClientForConsumerRestCalls",
username, password,
"client_credentials password refresh_token urn:ietf:params:oauth:grant-type:jwt-bearer");
}
accessTokenInfo = apiApplicationServices.generateAccessTokenFromRegisteredApplication(
apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret());
} catch (APIServicesException e) {
String errorMsg = "Error occurred while generating the API application";
log.error(errorMsg, e);
throw new APIManagerException(errorMsg, e);
}
ApiApplicationInfo applicationInfo = new ApiApplicationInfo();
applicationInfo.setClientId(apiApplicationKey.getClientId());
applicationInfo.setClientSecret(apiApplicationKey.getClientSecret());
applicationInfo.setAccess_token(accessTokenInfo.getAccess_token());
applicationInfo.setRefresh_token(accessTokenInfo.getRefresh_token());
return applicationInfo;
} }
} }

View File

@ -18,8 +18,8 @@
package io.entgra.device.mgt.core.apimgt.application.extension.dto; package io.entgra.device.mgt.core.apimgt.application.extension.dto;
import org.json.simple.JSONObject;
import io.entgra.device.mgt.core.apimgt.application.extension.constants.ApiApplicationConstants; import io.entgra.device.mgt.core.apimgt.application.extension.constants.ApiApplicationConstants;
import org.json.simple.JSONObject;
/** /**
* This holds api application consumer key and secret. * This holds api application consumer key and secret.

View File

@ -18,6 +18,9 @@
package io.entgra.device.mgt.core.apimgt.application.extension.internal; package io.entgra.device.mgt.core.apimgt.application.extension.internal;
import io.entgra.device.mgt.core.apimgt.application.extension.APIManagementProviderService; import io.entgra.device.mgt.core.apimgt.application.extension.APIManagementProviderService;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.APIApplicationServices;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.ConsumerRESTAPIServices;
import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.MetadataManagementService;
import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext;
import io.entgra.device.mgt.core.identity.jwt.client.extension.service.JWTClientManagerService; import io.entgra.device.mgt.core.identity.jwt.client.extension.service.JWTClientManagerService;
import org.wso2.carbon.registry.core.service.TenantRegistryLoader; import org.wso2.carbon.registry.core.service.TenantRegistryLoader;
@ -35,6 +38,9 @@ public class APIApplicationManagerExtensionDataHolder {
private TenantRegistryLoader tenantRegistryLoader; private TenantRegistryLoader tenantRegistryLoader;
private TenantIndexingLoader indexLoader; private TenantIndexingLoader indexLoader;
private JWTClientManagerService jwtClientManagerService; private JWTClientManagerService jwtClientManagerService;
private ConsumerRESTAPIServices consumerRESTAPIServices;
private APIApplicationServices apiApplicationServices;
private MetadataManagementService metadataManagementService;
private APIApplicationManagerExtensionDataHolder() { private APIApplicationManagerExtensionDataHolder() {
} }
@ -104,4 +110,28 @@ public class APIApplicationManagerExtensionDataHolder {
public void setJwtClientManagerService(JWTClientManagerService jwtClientManagerService) { public void setJwtClientManagerService(JWTClientManagerService jwtClientManagerService) {
this.jwtClientManagerService = jwtClientManagerService; this.jwtClientManagerService = jwtClientManagerService;
} }
public ConsumerRESTAPIServices getConsumerRESTAPIServices() {
return consumerRESTAPIServices;
}
public void setConsumerRESTAPIServices(ConsumerRESTAPIServices consumerRESTAPIServices) {
this.consumerRESTAPIServices = consumerRESTAPIServices;
}
public APIApplicationServices getApiApplicationServices() {
return apiApplicationServices;
}
public void setApiApplicationServices(APIApplicationServices apiApplicationServices) {
this.apiApplicationServices = apiApplicationServices;
}
public MetadataManagementService getMetadataManagementService() {
return metadataManagementService;
}
public void setMetadataManagementService(MetadataManagementService metadataManagementService) {
this.metadataManagementService = metadataManagementService;
}
} }

View File

@ -17,42 +17,28 @@
*/ */
package io.entgra.device.mgt.core.apimgt.application.extension.internal; package io.entgra.device.mgt.core.apimgt.application.extension.internal;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.APIApplicationServices;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.ConsumerRESTAPIServices;
import io.entgra.device.mgt.core.apimgt.application.extension.APIManagementProviderService;
import io.entgra.device.mgt.core.apimgt.application.extension.APIManagementProviderServiceImpl;
import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.MetadataManagementService;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.osgi.framework.BundleContext; import org.osgi.framework.BundleContext;
import org.osgi.service.component.ComponentContext;; import org.osgi.service.component.ComponentContext;
import io.entgra.device.mgt.core.apimgt.application.extension.APIManagementProviderService; import org.osgi.service.component.annotations.*;
import io.entgra.device.mgt.core.apimgt.application.extension.APIManagementProviderServiceImpl;
import org.wso2.carbon.registry.core.service.TenantRegistryLoader; import org.wso2.carbon.registry.core.service.TenantRegistryLoader;
import org.wso2.carbon.registry.indexing.service.TenantIndexingLoader; import org.wso2.carbon.registry.indexing.service.TenantIndexingLoader;
import org.wso2.carbon.user.core.service.RealmService; import org.wso2.carbon.user.core.service.RealmService;
/** @Component(
* @scr.component name="io.entgra.device.mgt.core.apimgt.application.extension.internal.APIApplicationManagerExtensionServiceComponent" name = "io.entgra.device.mgt.core.apimgt.application.extension.internal.APIApplicationManagerExtensionServiceComponent",
* @scr.reference name="tenant.registryloader" immediate = true)
* interface="org.wso2.carbon.registry.core.service.TenantRegistryLoader"
* cardinality="1..1"
* policy="dynamic"
* bind="setTenantRegistryLoader"
* unbind="unsetTenantRegistryLoader"
* @scr.reference name="tenant.indexloader"
* interface="org.wso2.carbon.registry.indexing.service.TenantIndexingLoader"
* cardinality="1..1"
* policy="dynamic"
* bind="setIndexLoader"
* unbind="unsetIndexLoader"
* @scr.reference name="realm.service"
* immediate="true"
* interface="org.wso2.carbon.user.core.service.RealmService"
* cardinality="1..1"
* policy="dynamic"
* bind="setRealmService"
* unbind="unsetRealmService"
*/
public class APIApplicationManagerExtensionServiceComponent { public class APIApplicationManagerExtensionServiceComponent {
private static final Log log = LogFactory.getLog(APIApplicationManagerExtensionServiceComponent.class); private static final Log log = LogFactory.getLog(APIApplicationManagerExtensionServiceComponent.class);
@Activate
protected void activate(ComponentContext componentContext) { protected void activate(ComponentContext componentContext) {
try { try {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
@ -67,10 +53,17 @@ public class APIApplicationManagerExtensionServiceComponent {
} }
} }
@Deactivate
protected void deactivate(ComponentContext componentContext) { protected void deactivate(ComponentContext componentContext) {
//do nothing //do nothing
} }
@Reference(
name = "tenant.registry.loader",
service = org.wso2.carbon.registry.core.service.TenantRegistryLoader.class,
cardinality = ReferenceCardinality.MANDATORY,
policy = ReferencePolicy.DYNAMIC,
unbind = "unsetTenantRegistryLoader")
protected void setTenantRegistryLoader(TenantRegistryLoader tenantRegistryLoader) { protected void setTenantRegistryLoader(TenantRegistryLoader tenantRegistryLoader) {
APIApplicationManagerExtensionDataHolder.getInstance().setTenantRegistryLoader(tenantRegistryLoader); APIApplicationManagerExtensionDataHolder.getInstance().setTenantRegistryLoader(tenantRegistryLoader);
} }
@ -79,6 +72,12 @@ public class APIApplicationManagerExtensionServiceComponent {
APIApplicationManagerExtensionDataHolder.getInstance().setTenantRegistryLoader(null); APIApplicationManagerExtensionDataHolder.getInstance().setTenantRegistryLoader(null);
} }
@Reference(
name = "tenant.index.loader",
service = org.wso2.carbon.registry.indexing.service.TenantIndexingLoader.class,
cardinality = ReferenceCardinality.MANDATORY,
policy = ReferencePolicy.DYNAMIC,
unbind = "unsetIndexLoader")
protected void setIndexLoader(TenantIndexingLoader indexLoader) { protected void setIndexLoader(TenantIndexingLoader indexLoader) {
if (indexLoader != null && log.isDebugEnabled()) { if (indexLoader != null && log.isDebugEnabled()) {
log.debug("IndexLoader service initialized"); log.debug("IndexLoader service initialized");
@ -95,6 +94,12 @@ public class APIApplicationManagerExtensionServiceComponent {
* *
* @param realmService An instance of RealmService * @param realmService An instance of RealmService
*/ */
@Reference(
name = "realm.service",
service = org.wso2.carbon.user.core.service.RealmService.class,
cardinality = ReferenceCardinality.MANDATORY,
policy = ReferencePolicy.DYNAMIC,
unbind = "unsetRealmService")
protected void setRealmService(RealmService realmService) { protected void setRealmService(RealmService realmService) {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Setting Realm Service"); log.debug("Setting Realm Service");
@ -113,4 +118,95 @@ public class APIApplicationManagerExtensionServiceComponent {
} }
APIApplicationManagerExtensionDataHolder.getInstance().setRealmService(null); APIApplicationManagerExtensionDataHolder.getInstance().setRealmService(null);
} }
/**
* Sets APIM Consumer REST API service.
*
* @param consumerRESTAPIServices An instance of ConsumerRESTAPIServices
*/
@Reference(
name = "APIM.consumer.service",
service = io.entgra.device.mgt.core.apimgt.extension.rest.api.ConsumerRESTAPIServices.class,
cardinality = ReferenceCardinality.MANDATORY,
policy = ReferencePolicy.DYNAMIC,
unbind = "unsetConsumerRESTAPIServices")
protected void setConsumerRESTAPIServices(ConsumerRESTAPIServices consumerRESTAPIServices) {
if (log.isDebugEnabled()) {
log.debug("Setting APIM Consumer REST API Service");
}
APIApplicationManagerExtensionDataHolder.getInstance().setConsumerRESTAPIServices(consumerRESTAPIServices);
}
/**
* Unset APIM Consumer REST API service
*
* @param consumerRESTAPIServices An instance of ConsumerRESTAPIServices
*/
protected void unsetConsumerRESTAPIServices(ConsumerRESTAPIServices consumerRESTAPIServices) {
if (log.isDebugEnabled()) {
log.debug("Unsetting APIM Consumer REST API Service");
}
APIApplicationManagerExtensionDataHolder.getInstance().setConsumerRESTAPIServices(null);
}
/**
* Sets DCR REST API service.
*
* @param apiApplicationServices An instance of APIApplicationServices
*/
@Reference(
name = "APIM.application.service",
service = io.entgra.device.mgt.core.apimgt.extension.rest.api.APIApplicationServices.class,
cardinality = ReferenceCardinality.MANDATORY,
policy = ReferencePolicy.DYNAMIC,
unbind = "unsetAPIApplicationServices")
protected void setAPIApplicationServices(APIApplicationServices apiApplicationServices) {
if (log.isDebugEnabled()) {
log.debug("Setting DCR REST API Service");
}
APIApplicationManagerExtensionDataHolder.getInstance().setApiApplicationServices(apiApplicationServices);
}
/**
* Unset DCR REST API service
*
* @param apiApplicationServices An instance of APIApplicationServices
*/
protected void unsetAPIApplicationServices(APIApplicationServices apiApplicationServices) {
if (log.isDebugEnabled()) {
log.debug("Unsetting DCR REST API Service");
}
APIApplicationManagerExtensionDataHolder.getInstance().setApiApplicationServices(null);
}
/**
* Sets Meta Data Mgt service.
*
* @param metadataManagementService An instance of MetadataManagementService
*/
@Reference(
name = "meta.data.mgt.service",
service = io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.MetadataManagementService.class,
cardinality = ReferenceCardinality.MANDATORY,
policy = ReferencePolicy.DYNAMIC,
unbind = "unsetAMetaMgtServices")
protected void setMetaMgtServices(MetadataManagementService metadataManagementService) {
if (log.isDebugEnabled()) {
log.debug("Setting Meta data mgt Service");
}
APIApplicationManagerExtensionDataHolder.getInstance().setMetadataManagementService(metadataManagementService);
}
/**
* Unset Meta Data Mgt service
*
* @param metadataManagementService An instance of MetadataManagementService
*/
protected void unsetAMetaMgtServices(MetadataManagementService metadataManagementService) {
if (log.isDebugEnabled()) {
log.debug("Unsetting Meta Data mgt Service");
}
APIApplicationManagerExtensionDataHolder.getInstance().setMetadataManagementService(null);
}
} }

View File

@ -17,10 +17,10 @@
*/ */
package io.entgra.device.mgt.core.apimgt.application.extension.util; package io.entgra.device.mgt.core.apimgt.application.extension.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import io.entgra.device.mgt.core.apimgt.application.extension.exception.APIManagerException; import io.entgra.device.mgt.core.apimgt.application.extension.exception.APIManagerException;
import io.entgra.device.mgt.core.apimgt.application.extension.internal.APIApplicationManagerExtensionDataHolder; import io.entgra.device.mgt.core.apimgt.application.extension.internal.APIApplicationManagerExtensionDataHolder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.base.MultitenantConstants; import org.wso2.carbon.base.MultitenantConstants;
import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.registry.core.exceptions.RegistryException; import org.wso2.carbon.registry.core.exceptions.RegistryException;

View File

@ -22,26 +22,31 @@
<parent> <parent>
<artifactId>apimgt-extensions</artifactId> <artifactId>apimgt-extensions</artifactId>
<groupId>io.entgra.device.mgt.core</groupId> <groupId>io.entgra.device.mgt.core</groupId>
<version>5.1.0</version> <version>6.0.1-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>io.entgra.device.mgt.core.apimgt.extension.rest.api</artifactId> <artifactId>io.entgra.device.mgt.core.apimgt.extension.rest.api</artifactId>
<packaging>bundle</packaging> <packaging>bundle</packaging>
<name>Entgra - Device Management Extension for APIM REST API</name> <name>Entgra Device Management - Device Management Extension for APIM REST API</name>
<description>Entgra - Device Management Extension for APIM REST API</description> <description>Entgra Device Management - Device Management Extension for APIM REST API</description>
<url>https://entgra.io</url> <url>https://entgra.io</url>
<dependencies> <dependencies>
<dependency>
<groupId>org.apache.felix</groupId>
<artifactId>org.apache.felix.scr.ds-annotations</artifactId>
<scope>provided</scope>
</dependency>
<dependency> <dependency>
<groupId>commons-httpclient.wso2</groupId> <groupId>commons-httpclient.wso2</groupId>
<artifactId>commons-httpclient</artifactId> <artifactId>commons-httpclient</artifactId>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.wso2.carbon</groupId> <groupId>org.ops4j.pax.logging</groupId>
<artifactId>org.wso2.carbon.logging</artifactId> <artifactId>pax-logging-api</artifactId>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<dependency> <dependency>
@ -54,17 +59,6 @@
<artifactId>org.wso2.carbon.core</artifactId> <artifactId>org.wso2.carbon.core</artifactId>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<dependency>
<groupId>org.eclipse.osgi</groupId>
<artifactId>org.eclipse.osgi</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.eclipse.osgi</groupId>
<artifactId>org.eclipse.osgi.services</artifactId>
<scope>provided</scope>
</dependency>
<dependency> <dependency>
<groupId>org.json.wso2</groupId> <groupId>org.json.wso2</groupId>
<artifactId>json</artifactId> <artifactId>json</artifactId>
@ -92,14 +86,9 @@
<build> <build>
<plugins> <plugins>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-scr-plugin</artifactId>
</plugin>
<plugin> <plugin>
<groupId>org.apache.felix</groupId> <groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId> <artifactId>maven-bundle-plugin</artifactId>
<version>5.1.7</version>
<extensions>true</extensions> <extensions>true</extensions>
<configuration> <configuration>
<instructions> <instructions>

View File

@ -24,7 +24,11 @@ import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.APIService
public interface APIApplicationServices { public interface APIApplicationServices {
APIApplicationKey createAndRetrieveApplicationCredentials() throws APIServicesException; APIApplicationKey createAndRetrieveApplicationCredentials(String clientName, String grantType)
throws APIServicesException;
APIApplicationKey createAndRetrieveApplicationCredentialsWithUser(String clientName, String username, String password, String grantType)
throws APIServicesException;
AccessTokenInfo generateAccessTokenFromRegisteredApplication(String clientId, String clientSecret) throws APIServicesException; AccessTokenInfo generateAccessTokenFromRegisteredApplication(String clientId, String clientSecret) throws APIServicesException;

View File

@ -19,20 +19,15 @@
package io.entgra.device.mgt.core.apimgt.extension.rest.api; package io.entgra.device.mgt.core.apimgt.extension.rest.api;
import com.google.gson.Gson; import com.google.gson.Gson;
import org.json.JSONObject;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.util.HttpsTrustManagerUtils;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIApplicationKey;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.constants.Constants; import io.entgra.device.mgt.core.apimgt.extension.rest.api.constants.Constants;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIApplicationKey;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.AccessTokenInfo; import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.AccessTokenInfo;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.APIServicesException; import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.APIServicesException;
import okhttp3.MediaType; import io.entgra.device.mgt.core.apimgt.extension.rest.api.util.HttpsTrustManagerUtils;
import okhttp3.OkHttpClient; import okhttp3.*;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.RequestBody;
import okhttp3.Credentials;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.json.JSONObject;
import org.wso2.carbon.apimgt.impl.APIConstants; import org.wso2.carbon.apimgt.impl.APIConstants;
import org.wso2.carbon.apimgt.impl.APIManagerConfiguration; import org.wso2.carbon.apimgt.impl.APIManagerConfiguration;
import org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder; import org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder;
@ -51,7 +46,7 @@ public class APIApplicationServicesImpl implements APIApplicationServices {
getAPIManagerConfigurationService().getAPIManagerConfiguration(); getAPIManagerConfigurationService().getAPIManagerConfiguration();
@Override @Override
public APIApplicationKey createAndRetrieveApplicationCredentials() throws APIServicesException { public APIApplicationKey createAndRetrieveApplicationCredentials(String clientName, String grantType) throws APIServicesException {
String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(); String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
String serverUser = getScopePublishUserName(tenantDomain); String serverUser = getScopePublishUserName(tenantDomain);
String serverPassword = getScopePublishUserPassword(tenantDomain); String serverPassword = getScopePublishUserPassword(tenantDomain);
@ -60,8 +55,8 @@ public class APIApplicationServicesImpl implements APIApplicationServices {
JSONObject jsonObject = new JSONObject(); JSONObject jsonObject = new JSONObject();
jsonObject.put("callbackUrl", Constants.EMPTY_STRING); jsonObject.put("callbackUrl", Constants.EMPTY_STRING);
jsonObject.put("clientName", Constants.CLIENT_NAME); jsonObject.put("clientName", clientName);
jsonObject.put("grantType", Constants.GRANT_TYPE); jsonObject.put("grantType", grantType);
jsonObject.put("owner", serverUser); jsonObject.put("owner", serverUser);
jsonObject.put("saasApp", true); jsonObject.put("saasApp", true);
@ -83,6 +78,35 @@ public class APIApplicationServicesImpl implements APIApplicationServices {
} }
} }
@Override
public APIApplicationKey createAndRetrieveApplicationCredentialsWithUser(String clientName, String username, String password, String grantType)
throws APIServicesException {
String applicationEndpoint = config.getFirstProperty(Constants.DCR_END_POINT);
JSONObject jsonObject = new JSONObject();
jsonObject.put("callbackUrl", Constants.EMPTY_STRING);
jsonObject.put("clientName", clientName);
jsonObject.put("grantType", grantType);
jsonObject.put("owner", username);
jsonObject.put("saasApp", true);
RequestBody requestBody = RequestBody.Companion.create(jsonObject.toString(), JSON);
Request request = new Request.Builder()
.url(applicationEndpoint)
.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Credentials.basic(username, password))
.post(requestBody)
.build();
try {
Response response = client.newCall(request).execute();
return gson.fromJson(response.body().string(), APIApplicationKey.class);
} catch (IOException e) {
msg = "Error occurred while processing the response";
log.error(msg, e);
throw new APIServicesException(e);
}
}
@Override @Override
public AccessTokenInfo generateAccessTokenFromRegisteredApplication(String consumerKey, String consumerSecret) public AccessTokenInfo generateAccessTokenFromRegisteredApplication(String consumerKey, String consumerSecret)
throws APIServicesException { throws APIServicesException {

View File

@ -0,0 +1,72 @@
/*
* Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.entgra.device.mgt.core.apimgt.extension.rest.api;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer.*;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.ApiApplicationInfo;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.APIServicesException;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.BadRequestException;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.UnexpectedResponseException;
import java.util.List;
import java.util.Map;
public interface ConsumerRESTAPIServices {
Application[] getAllApplications(ApiApplicationInfo apiApplicationInfo, String appName)
throws APIServicesException, BadRequestException, UnexpectedResponseException;
Application getDetailsOfAnApplication(ApiApplicationInfo apiApplicationInfo, String applicationId)
throws APIServicesException, BadRequestException, UnexpectedResponseException;
Application createApplication(ApiApplicationInfo apiApplicationInfo, Application application)
throws APIServicesException, BadRequestException, UnexpectedResponseException;
Boolean deleteApplication(ApiApplicationInfo apiApplicationInfo, String applicationId)
throws APIServicesException, BadRequestException, UnexpectedResponseException;
Subscription[] getAllSubscriptions(ApiApplicationInfo apiApplicationInfo, String applicationId)
throws APIServicesException, BadRequestException, UnexpectedResponseException;
APIInfo[] getAllApis(ApiApplicationInfo apiApplicationInfo, Map<String, String> queryParams, Map<String, String> headerParams)
throws APIServicesException, BadRequestException, UnexpectedResponseException;
Subscription createSubscription(ApiApplicationInfo apiApplicationInfo, Subscription subscriptions)
throws APIServicesException, BadRequestException, UnexpectedResponseException;
Subscription[] createSubscriptions(ApiApplicationInfo apiApplicationInfo, List<Subscription> subscriptions)
throws APIServicesException, BadRequestException, UnexpectedResponseException;
ApplicationKey generateApplicationKeys(ApiApplicationInfo apiApplicationInfo, String applicationId, String keyManager,
String validityTime, String keyType)
throws APIServicesException, BadRequestException, UnexpectedResponseException;
ApplicationKey mapApplicationKeys(ApiApplicationInfo apiApplicationInfo, Application application, String keyManager, String keyType)
throws APIServicesException, BadRequestException, UnexpectedResponseException;
ApplicationKey getKeyDetails(ApiApplicationInfo apiApplicationInfo, String applicationId, String keyMapId)
throws APIServicesException, BadRequestException, UnexpectedResponseException;
ApplicationKey updateGrantType(ApiApplicationInfo apiApplicationInfo, String applicationId, String keyMapId, String keyManager,
List<String> supportedGrantTypes, String callbackUrl)
throws APIServicesException, BadRequestException, UnexpectedResponseException;
KeyManager[] getAllKeyManagers(ApiApplicationInfo apiApplicationInfo)
throws APIServicesException, BadRequestException, UnexpectedResponseException;
}

View File

@ -0,0 +1,674 @@
/*
* Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.entgra.device.mgt.core.apimgt.extension.rest.api;
import com.google.gson.Gson;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer.*;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.constants.Constants;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.AccessTokenInfo;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.ApiApplicationInfo;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.APIServicesException;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.BadRequestException;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.UnexpectedResponseException;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.util.HttpsTrustManagerUtils;
import okhttp3.*;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.IOException;
import java.util.List;
import java.util.Map;
public class ConsumerRESTAPIServicesImpl implements ConsumerRESTAPIServices {
private static final Log log = LogFactory.getLog(ConsumerRESTAPIServicesImpl.class);
private static final OkHttpClient client = new OkHttpClient(HttpsTrustManagerUtils.getSSLClient().newBuilder());
private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
private static final Gson gson = new Gson();
private static final String host = System.getProperty(Constants.IOT_CORE_HOST);
private static final String port = System.getProperty(Constants.IOT_CORE_HTTPS_PORT);
private static final String endPointPrefix = Constants.HTTPS_PROTOCOL + Constants.SCHEME_SEPARATOR + host
+ Constants.COLON + port;
@Override
public Application[] getAllApplications(ApiApplicationInfo apiApplicationInfo, String appName)
throws APIServicesException, BadRequestException, UnexpectedResponseException {
String getAllApplicationsUrl = endPointPrefix + Constants.APPLICATIONS_API + "?query=" + appName;
Request.Builder builder = new Request.Builder();
builder.url(getAllApplicationsUrl);
builder.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER
+ apiApplicationInfo.getAccess_token());
builder.get();
Request request = builder.build();
try {
Response response = client.newCall(request).execute();
if (HttpStatus.SC_OK == response.code()) {
JSONArray applicationList = (JSONArray) new JSONObject(response.body().string()).get("list");
return gson.fromJson(applicationList.toString(), Application[].class);
} else if (HttpStatus.SC_UNAUTHORIZED == response.code()) {
APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl();
AccessTokenInfo refreshedAccessToken = apiApplicationServices.
generateAccessTokenFromRefreshToken(apiApplicationInfo.getRefresh_token(),
apiApplicationInfo.getClientId(), apiApplicationInfo.getClientSecret());
ApiApplicationInfo refreshedApiApplicationInfo = returnApplicationInfo(apiApplicationInfo, refreshedAccessToken);
return getAllApplications(refreshedApiApplicationInfo, appName);
//TODO: max attempt count
} else if (HttpStatus.SC_BAD_REQUEST == response.code()) {
String msg = "Bad Request, Invalid request";
log.error(msg);
throw new BadRequestException(msg);
} else {
String msg = "Response : " + response.code() + response.body();
throw new UnexpectedResponseException(msg);
}
} catch (IOException e) {
String msg = "Error occurred while processing the response";
log.error(msg, e);
throw new APIServicesException(msg, e);
}
}
@Override
public Application getDetailsOfAnApplication(ApiApplicationInfo apiApplicationInfo, String applicationId)
throws APIServicesException, BadRequestException, UnexpectedResponseException {
String getDetailsOfAPPUrl = endPointPrefix + Constants.APPLICATIONS_API + Constants.SLASH + applicationId;
Request.Builder builder = new Request.Builder();
builder.url(getDetailsOfAPPUrl);
builder.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER
+ apiApplicationInfo.getAccess_token());
builder.get();
Request request = builder.build();
try {
Response response = client.newCall(request).execute();
if (HttpStatus.SC_OK == response.code()) {
return gson.fromJson(response.body().string(), Application.class);
} else if (HttpStatus.SC_UNAUTHORIZED == response.code()) {
APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl();
AccessTokenInfo refreshedAccessToken = apiApplicationServices.
generateAccessTokenFromRefreshToken(apiApplicationInfo.getRefresh_token(),
apiApplicationInfo.getClientId(), apiApplicationInfo.getClientSecret());
ApiApplicationInfo refreshedApiApplicationInfo = returnApplicationInfo(apiApplicationInfo, refreshedAccessToken);
return getDetailsOfAnApplication(refreshedApiApplicationInfo, applicationId);
//TODO: max attempt count
} else if (HttpStatus.SC_BAD_REQUEST == response.code()) {
String msg = "Bad Request, Invalid request";
log.error(msg);
throw new BadRequestException(msg);
} else {
String msg = "Response : " + response.code() + response.body();
throw new UnexpectedResponseException(msg);
}
} catch (IOException e) {
String msg = "Error occurred while processing the response";
log.error(msg, e);
throw new APIServicesException(msg, e);
}
}
@Override
public Application createApplication(ApiApplicationInfo apiApplicationInfo, Application application)
throws APIServicesException, BadRequestException, UnexpectedResponseException {
String getAllScopesUrl = endPointPrefix + Constants.APPLICATIONS_API;
JSONArray groups = new JSONArray();
JSONArray subscriptionScope = new JSONArray();
if (application.getGroups() != null && application.getSubscriptionScopes() != null) {
for (String string : application.getGroups()) {
groups.put(string);
}
for (Scopes string : application.getSubscriptionScopes()) {
subscriptionScope.put(string);
}
}
JSONObject applicationInfo = new JSONObject();
applicationInfo.put("name", application.getName());
applicationInfo.put("throttlingPolicy", application.getThrottlingPolicy());
applicationInfo.put("description", application.getDescription());
applicationInfo.put("tokenType", application.getTokenType());
applicationInfo.put("groups", groups);
applicationInfo.put("attributes", new JSONObject());
applicationInfo.put("subscriptionScopes", subscriptionScope);
RequestBody requestBody = RequestBody.create(JSON, applicationInfo.toString());
Request.Builder builder = new Request.Builder();
builder.url(getAllScopesUrl);
builder.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER
+ apiApplicationInfo.getAccess_token());
builder.post(requestBody);
Request request = builder.build();
try {
Response response = client.newCall(request).execute();
if (HttpStatus.SC_CREATED == response.code()) {
return gson.fromJson(response.body().string(), Application.class);
} else if (HttpStatus.SC_UNAUTHORIZED == response.code()) {
APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl();
AccessTokenInfo refreshedAccessToken = apiApplicationServices.
generateAccessTokenFromRefreshToken(apiApplicationInfo.getRefresh_token(),
apiApplicationInfo.getClientId(), apiApplicationInfo.getClientSecret());
ApiApplicationInfo refreshedApiApplicationInfo = returnApplicationInfo(apiApplicationInfo, refreshedAccessToken);
return createApplication(refreshedApiApplicationInfo, application);
//TODO: max attempt count
} else if (HttpStatus.SC_BAD_REQUEST == response.code()) {
String msg = "Bad Request, Invalid request body";
log.error(msg);
throw new BadRequestException(msg);
} else {
String msg = "Response : " + response.code() + response.body();
throw new UnexpectedResponseException(msg);
}
} catch (IOException e) {
String msg = "Error occurred while processing the response";
log.error(msg, e);
throw new APIServicesException(msg, e);
}
}
@Override
public Boolean deleteApplication(ApiApplicationInfo apiApplicationInfo, String applicationId)
throws APIServicesException, BadRequestException, UnexpectedResponseException {
String deleteScopesUrl = endPointPrefix + Constants.APPLICATIONS_API + Constants.SLASH + applicationId;
Request.Builder builder = new Request.Builder();
builder.url(deleteScopesUrl);
builder.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER
+ apiApplicationInfo.getAccess_token());
builder.delete();
Request request = builder.build();
try {
Response response = client.newCall(request).execute();
if (HttpStatus.SC_OK == response.code()) {
return true;
} else if (HttpStatus.SC_UNAUTHORIZED == response.code()) {
APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl();
AccessTokenInfo refreshedAccessToken = apiApplicationServices.
generateAccessTokenFromRefreshToken(apiApplicationInfo.getRefresh_token(),
apiApplicationInfo.getClientId(), apiApplicationInfo.getClientSecret());
ApiApplicationInfo refreshedApiApplicationInfo = returnApplicationInfo(apiApplicationInfo, refreshedAccessToken);
return deleteApplication(refreshedApiApplicationInfo, applicationId);
//TODO: max attempt count
} else if (HttpStatus.SC_BAD_REQUEST == response.code()) {
String msg = "Bad Request, Invalid request body";
log.error(msg);
throw new BadRequestException(msg);
} else {
String msg = "Response : " + response.code() + response.body();
throw new UnexpectedResponseException(msg);
}
} catch (IOException e) {
String msg = "Error occurred while processing the response";
log.error(msg, e);
throw new APIServicesException(msg, e);
}
}
@Override
public Subscription[] getAllSubscriptions(ApiApplicationInfo apiApplicationInfo, String applicationId)
throws APIServicesException, BadRequestException, UnexpectedResponseException {
String getAllScopesUrl = endPointPrefix + Constants.SUBSCRIPTION_API + "?applicationId=" + applicationId + "&limit=1000";
Request.Builder builder = new Request.Builder();
builder.url(getAllScopesUrl);
builder.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER
+ apiApplicationInfo.getAccess_token());
builder.get();
Request request = builder.build();
try {
Response response = client.newCall(request).execute();
if (HttpStatus.SC_OK == response.code()) {
JSONArray subscriptionList = (JSONArray) new JSONObject(response.body().string()).get("list");
return gson.fromJson(subscriptionList.toString(), Subscription[].class);
} else if (HttpStatus.SC_UNAUTHORIZED == response.code()) {
APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl();
AccessTokenInfo refreshedAccessToken = apiApplicationServices.
generateAccessTokenFromRefreshToken(apiApplicationInfo.getRefresh_token(),
apiApplicationInfo.getClientId(), apiApplicationInfo.getClientSecret());
ApiApplicationInfo refreshedApiApplicationInfo = returnApplicationInfo(apiApplicationInfo, refreshedAccessToken);
return getAllSubscriptions(refreshedApiApplicationInfo, applicationId);
//TODO: max attempt count
} else if (HttpStatus.SC_BAD_REQUEST == response.code()) {
String msg = "Bad Request, Invalid request";
log.error(msg);
throw new BadRequestException(msg);
} else {
String msg = "Response : " + response.code() + response.body();
throw new UnexpectedResponseException(msg);
}
} catch (IOException e) {
String msg = "Error occurred while processing the response";
log.error(msg, e);
throw new APIServicesException(msg, e);
}
}
@Override
public APIInfo[] getAllApis(ApiApplicationInfo apiApplicationInfo, Map<String, String> queryParams, Map<String, String> headerParams)
throws APIServicesException, BadRequestException, UnexpectedResponseException {
StringBuilder getAPIsURL = new StringBuilder(endPointPrefix + Constants.DEV_PORTAL_API);
for (Map.Entry<String, String> query : queryParams.entrySet()) {
getAPIsURL.append(Constants.AMPERSAND).append(query.getKey()).append(Constants.EQUAL).append(query.getValue());
}
Request.Builder builder = new Request.Builder();
builder.url(getAPIsURL.toString());
builder.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER
+ apiApplicationInfo.getAccess_token());
for (Map.Entry<String, String> header : headerParams.entrySet()) {
builder.addHeader(header.getKey(), header.getValue());
}
builder.get();
Request request = builder.build();
try {
Response response = client.newCall(request).execute();
if (HttpStatus.SC_OK == response.code()) {
JSONArray apiList = (JSONArray) new JSONObject(response.body().string()).get("list");
return gson.fromJson(apiList.toString(), APIInfo[].class);
} else if (HttpStatus.SC_UNAUTHORIZED == response.code()) {
APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl();
AccessTokenInfo refreshedAccessToken = apiApplicationServices.
generateAccessTokenFromRefreshToken(apiApplicationInfo.getRefresh_token(),
apiApplicationInfo.getClientId(), apiApplicationInfo.getClientSecret());
ApiApplicationInfo refreshedApiApplicationInfo = returnApplicationInfo(apiApplicationInfo, refreshedAccessToken);
return getAllApis(refreshedApiApplicationInfo, queryParams, headerParams);
//TODO: max attempt count
} else if (HttpStatus.SC_BAD_REQUEST == response.code()) {
String msg = "Bad Request, Invalid request";
log.error(msg);
throw new BadRequestException(msg);
} else {
String msg = "Response : " + response.code() + response.body();
throw new UnexpectedResponseException(msg);
}
} catch (IOException e) {
String msg = "Error occurred while processing the response";
log.error(msg, e);
throw new APIServicesException(msg, e);
}
}
@Override
public Subscription createSubscription(ApiApplicationInfo apiApplicationInfo, Subscription subscriptions)
throws APIServicesException, BadRequestException, UnexpectedResponseException {
String createSubscriptionUrl = endPointPrefix + Constants.SUBSCRIPTION_API;
JSONObject subscriptionObject = new JSONObject();
subscriptionObject.put("applicationId", subscriptions.getApplicationId());
subscriptionObject.put("apiId", subscriptions.getApiId());
subscriptionObject.put("throttlingPolicy", subscriptions.getThrottlingPolicy());
subscriptionObject.put("requestedThrottlingPolicy", subscriptions.getRequestedThrottlingPolicy());
RequestBody requestBody = RequestBody.create(JSON, subscriptionObject.toString());
Request.Builder builder = new Request.Builder();
builder.url(createSubscriptionUrl);
builder.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER
+ apiApplicationInfo.getAccess_token());
builder.post(requestBody);
Request request = builder.build();
try {
Response response = client.newCall(request).execute();
if (HttpStatus.SC_CREATED == response.code()) {
return gson.fromJson(response.body().string(), Subscription.class);
} else if (HttpStatus.SC_UNAUTHORIZED == response.code()) {
APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl();
AccessTokenInfo refreshedAccessToken = apiApplicationServices.
generateAccessTokenFromRefreshToken(apiApplicationInfo.getRefresh_token(),
apiApplicationInfo.getClientId(), apiApplicationInfo.getClientSecret());
ApiApplicationInfo refreshedApiApplicationInfo = returnApplicationInfo(apiApplicationInfo, refreshedAccessToken);
return createSubscription(refreshedApiApplicationInfo, subscriptions);
//TODO: max attempt count
} else if (HttpStatus.SC_BAD_REQUEST == response.code()) {
String msg = "Bad Request, Invalid request body";
log.error(msg);
throw new BadRequestException(msg);
} else {
String msg = "Response : " + response.code() + response.body();
throw new UnexpectedResponseException(msg);
}
} catch (IOException e) {
String msg = "Error occurred while processing the response";
log.error(msg, e);
throw new APIServicesException(msg, e);
}
}
@Override
public Subscription[] createSubscriptions(ApiApplicationInfo apiApplicationInfo, List<Subscription> subscriptions)
throws APIServicesException, BadRequestException, UnexpectedResponseException {
String createSubscriptionsUrl = endPointPrefix + Constants.SUBSCRIPTION_API + "/multiple";
String subscriptionsList = gson.toJson(subscriptions);
RequestBody requestBody = RequestBody.create(JSON, subscriptionsList);
Request.Builder builder = new Request.Builder();
builder.url(createSubscriptionsUrl);
builder.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER
+ apiApplicationInfo.getAccess_token());
builder.post(requestBody);
Request request = builder.build();
try {
Response response = client.newCall(request).execute();
if (HttpStatus.SC_OK == response.code()) {
return gson.fromJson(response.body().string(), Subscription[].class);
} else if (HttpStatus.SC_UNAUTHORIZED == response.code()) {
APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl();
AccessTokenInfo refreshedAccessToken = apiApplicationServices.
generateAccessTokenFromRefreshToken(apiApplicationInfo.getRefresh_token(),
apiApplicationInfo.getClientId(), apiApplicationInfo.getClientSecret());
ApiApplicationInfo refreshedApiApplicationInfo = returnApplicationInfo(apiApplicationInfo, refreshedAccessToken);
return createSubscriptions(refreshedApiApplicationInfo, subscriptions);
} else if (HttpStatus.SC_BAD_REQUEST == response.code()) {
String msg = "Bad Request, Invalid request body";
log.error(msg);
throw new BadRequestException(msg);
} else {
String msg = "Response : " + response.code() + response.body();
throw new UnexpectedResponseException(msg);
}
} catch (IOException e) {
String msg = "Error occurred while processing the response";
log.error(msg, e);
throw new APIServicesException(msg, e);
}
}
@Override
public ApplicationKey generateApplicationKeys(ApiApplicationInfo apiApplicationInfo, String applicationId, String keyManager,
String validityTime, String keyType)
throws APIServicesException, BadRequestException, UnexpectedResponseException {
String generateApplicationKeysUrl = endPointPrefix + Constants.APPLICATIONS_API + Constants.SLASH +
applicationId + "/generate-keys";
JSONArray grantTypesToBeSupported = new JSONArray();
grantTypesToBeSupported.put("password");
grantTypesToBeSupported.put("client_credentials");
JSONArray scopes = new JSONArray();
scopes.put("am_application_scope");
scopes.put("default");
JSONObject keyInfo = new JSONObject();
keyInfo.put("keyType", keyType);
keyInfo.put("keyManager", keyManager);
keyInfo.put("grantTypesToBeSupported", grantTypesToBeSupported);
keyInfo.put("callbackUrl", "");
keyInfo.put("scopes", scopes);
keyInfo.put("validityTime", 3600);
keyInfo.put("additionalProperties", new JSONObject());
RequestBody requestBody = RequestBody.create(JSON, keyInfo.toString());
Request.Builder builder = new Request.Builder();
builder.url(generateApplicationKeysUrl);
builder.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER
+ apiApplicationInfo.getAccess_token());
builder.post(requestBody);
Request request = builder.build();
try {
Response response = client.newCall(request).execute();
if (HttpStatus.SC_OK == response.code()) {
return gson.fromJson(response.body().string(), ApplicationKey.class);
} else if (HttpStatus.SC_UNAUTHORIZED == response.code()) {
APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl();
AccessTokenInfo refreshedAccessToken = apiApplicationServices.
generateAccessTokenFromRefreshToken(apiApplicationInfo.getRefresh_token(),
apiApplicationInfo.getClientId(), apiApplicationInfo.getClientSecret());
ApiApplicationInfo refreshedApiApplicationInfo = returnApplicationInfo(apiApplicationInfo, refreshedAccessToken);
return generateApplicationKeys(refreshedApiApplicationInfo, applicationId, keyManager, validityTime, keyType);
//TODO: max attempt count
} else if (HttpStatus.SC_BAD_REQUEST == response.code()) {
String msg = "Bad Request, Invalid request body";
log.error(msg);
throw new BadRequestException(msg);
} else {
String msg = "Response : " + response.code() + response.body();
throw new UnexpectedResponseException(msg);
}
} catch (IOException e) {
String msg = "Error occurred while processing the response";
log.error(msg, e);
throw new APIServicesException(msg, e);
}
}
@Override
public ApplicationKey mapApplicationKeys(ApiApplicationInfo apiApplicationInfo, Application application, String keyManager, String keyType)
throws APIServicesException, BadRequestException, UnexpectedResponseException {
String getAllScopesUrl = endPointPrefix + Constants.APPLICATIONS_API + Constants.SLASH +
application.getApplicationId() + "/map-keys";
JSONObject payload = new JSONObject();
payload.put("consumerKey", apiApplicationInfo.getClientId());
payload.put("consumerSecret", apiApplicationInfo.getClientSecret());
payload.put("keyManager", keyManager);
payload.put("keyType", keyType);
RequestBody requestBody = RequestBody.create(JSON, payload.toString());
Request.Builder builder = new Request.Builder();
builder.url(getAllScopesUrl);
builder.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER
+ apiApplicationInfo.getAccess_token());
builder.post(requestBody);
Request request = builder.build();
try {
Response response = client.newCall(request).execute();
if (HttpStatus.SC_OK == response.code()) {
return gson.fromJson(response.body().string(), ApplicationKey.class);
} else if (HttpStatus.SC_UNAUTHORIZED == response.code()) {
APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl();
AccessTokenInfo refreshedAccessToken = apiApplicationServices.
generateAccessTokenFromRefreshToken(apiApplicationInfo.getRefresh_token(),
apiApplicationInfo.getClientId(), apiApplicationInfo.getClientSecret());
ApiApplicationInfo refreshedApiApplicationInfo = returnApplicationInfo(apiApplicationInfo, refreshedAccessToken);
return mapApplicationKeys(refreshedApiApplicationInfo, application, keyManager, keyType);
//TODO: max attempt count
} else if (HttpStatus.SC_BAD_REQUEST == response.code()) {
String msg = "Bad Request, Invalid request body";
log.error(msg);
throw new BadRequestException(msg);
} else {
String msg = "Response : " + response.code() + response.body();
throw new UnexpectedResponseException(msg);
}
} catch (IOException e) {
String msg = "Error occurred while processing the response";
log.error(msg, e);
throw new APIServicesException(msg, e);
}
}
@Override
public ApplicationKey getKeyDetails(ApiApplicationInfo apiApplicationInfo, String applicationId, String keyMapId)
throws APIServicesException, BadRequestException, UnexpectedResponseException {
String getKeyDetails = endPointPrefix + Constants.APPLICATIONS_API + Constants.SLASH + applicationId + "/oauth-keys/" + keyMapId;
Request.Builder builder = new Request.Builder();
builder.url(getKeyDetails);
builder.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER
+ apiApplicationInfo.getAccess_token());
builder.get();
Request request = builder.build();
try {
Response response = client.newCall(request).execute();
if (HttpStatus.SC_OK == response.code()) {
return gson.fromJson(response.body().string(), ApplicationKey.class);
} else if (HttpStatus.SC_UNAUTHORIZED == response.code()) {
APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl();
AccessTokenInfo refreshedAccessToken = apiApplicationServices.
generateAccessTokenFromRefreshToken(apiApplicationInfo.getRefresh_token(),
apiApplicationInfo.getClientId(), apiApplicationInfo.getClientSecret());
ApiApplicationInfo refreshedApiApplicationInfo = returnApplicationInfo(apiApplicationInfo, refreshedAccessToken);
return getKeyDetails(refreshedApiApplicationInfo, applicationId, keyMapId);
//TODO: max attempt count
} else if (HttpStatus.SC_BAD_REQUEST == response.code()) {
String msg = "Bad Request, Invalid request";
log.error(msg);
throw new BadRequestException(msg);
} else {
String msg = "Response : " + response.code() + response.body();
throw new UnexpectedResponseException(msg);
}
} catch (IOException e) {
String msg = "Error occurred while processing the response";
log.error(msg, e);
throw new APIServicesException(msg, e);
}
}
@Override
public ApplicationKey updateGrantType(ApiApplicationInfo apiApplicationInfo, String applicationId, String keyMapId, String keyManager,
List<String> supportedGrantTypes, String callbackUrl)
throws APIServicesException, BadRequestException, UnexpectedResponseException {
String getKeyDetails = endPointPrefix + Constants.APPLICATIONS_API + Constants.SLASH + applicationId + "/oauth-keys/" + keyMapId;
Request.Builder builder = new Request.Builder();
builder.url(getKeyDetails);
builder.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER
+ apiApplicationInfo.getAccess_token());
JSONArray supportedGrantTypeList = new JSONArray();
for (String string : supportedGrantTypes) {
supportedGrantTypeList.put(string);
}
JSONObject payload = new JSONObject();
payload.put("keyMappingId", keyMapId);
payload.put("keyManager", keyManager);
payload.put("supportedGrantTypes", supportedGrantTypeList);
payload.put("callbackUrl", (callbackUrl != null ? callbackUrl : ""));
payload.put("additionalProperties", new JSONObject());
RequestBody requestBody = RequestBody.create(JSON, payload.toString());
builder.put(requestBody);
Request request = builder.build();
try {
Response response = client.newCall(request).execute();
if (HttpStatus.SC_OK == response.code()) {
return gson.fromJson(response.body().string(), ApplicationKey.class);
} else if (HttpStatus.SC_UNAUTHORIZED == response.code()) {
APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl();
AccessTokenInfo refreshedAccessToken = apiApplicationServices.
generateAccessTokenFromRefreshToken(apiApplicationInfo.getRefresh_token(),
apiApplicationInfo.getClientId(), apiApplicationInfo.getClientSecret());
ApiApplicationInfo refreshedApiApplicationInfo = returnApplicationInfo(apiApplicationInfo, refreshedAccessToken);
return updateGrantType(refreshedApiApplicationInfo, applicationId, keyMapId, keyManager, supportedGrantTypes, callbackUrl);
//TODO: max attempt count
} else if (HttpStatus.SC_BAD_REQUEST == response.code()) {
String msg = "Bad Request, Invalid request";
log.error(msg);
throw new BadRequestException(msg);
} else {
String msg = "Response : " + response.code() + response.body();
throw new UnexpectedResponseException(msg);
}
} catch (IOException e) {
String msg = "Error occurred while processing the response";
log.error(msg, e);
throw new APIServicesException(msg, e);
}
}
@Override
public KeyManager[] getAllKeyManagers(ApiApplicationInfo apiApplicationInfo)
throws APIServicesException, BadRequestException, UnexpectedResponseException {
String getAllKeyManagersUrl = endPointPrefix + Constants.KEY_MANAGERS_API;
Request.Builder builder = new Request.Builder();
builder.url(getAllKeyManagersUrl);
builder.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER
+ apiApplicationInfo.getAccess_token());
builder.get();
Request request = builder.build();
try {
Response response = client.newCall(request).execute();
if (HttpStatus.SC_OK == response.code()) {
JSONArray keyManagerList = (JSONArray) new JSONObject(response.body().string()).get("list");
return gson.fromJson(keyManagerList.toString(), KeyManager[].class);
} else if (HttpStatus.SC_UNAUTHORIZED == response.code()) {
APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl();
AccessTokenInfo refreshedAccessToken = apiApplicationServices.
generateAccessTokenFromRefreshToken(apiApplicationInfo.getRefresh_token(),
apiApplicationInfo.getClientId(), apiApplicationInfo.getClientSecret());
ApiApplicationInfo refreshedApiApplicationInfo = returnApplicationInfo(apiApplicationInfo, refreshedAccessToken);
return getAllKeyManagers(refreshedApiApplicationInfo);
//TODO: max attempt count
} else if (HttpStatus.SC_BAD_REQUEST == response.code()) {
String msg = "Bad Request, Invalid request";
log.error(msg);
throw new BadRequestException(msg);
} else {
String msg = "Response : " + response.code() + response.body();
throw new UnexpectedResponseException(msg);
}
} catch (IOException e) {
String msg = "Error occurred while processing the response";
log.error(msg, e);
throw new APIServicesException(msg, e);
}
}
private ApiApplicationInfo returnApplicationInfo(ApiApplicationInfo apiApplicationInfo, AccessTokenInfo refreshedToken) {
ApiApplicationInfo applicationInfo = new ApiApplicationInfo();
applicationInfo.setClientId(apiApplicationInfo.getClientId());
applicationInfo.setClientSecret(apiApplicationInfo.getClientSecret());
applicationInfo.setAccess_token(refreshedToken.getAccess_token());
applicationInfo.setRefresh_token(refreshedToken.getRefresh_token());
return applicationInfo;
}
}

View File

@ -24,7 +24,6 @@ import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.AccessTokenInfo;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.APIServicesException; import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.APIServicesException;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.BadRequestException; import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.BadRequestException;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.UnexpectedResponseException; import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.UnexpectedResponseException;
import org.json.JSONObject;
import java.util.List; import java.util.List;

View File

@ -0,0 +1,176 @@
/*
* Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
/**
* This class represents the Consumer API Information.
*/
public class APIInfo {
private String id;
private String name;
private String description;
private String context;
private String version;
private String provider;
private String lifeCycleStatus;
private String thumbnailUri;
private String avgRating;
private List<String> throttlingPolicies;
private JSONObject advertiseInfo;
private JSONObject businessInformation;
private boolean isSubscriptionAvailable;
private String monetizationLabel;
private String gatewayVendor;
private List<String> additionalProperties;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getContext() {
return context;
}
public void setContext(String context) {
this.context = context;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getProvider() {
return provider;
}
public void setProvider(String provider) {
this.provider = provider;
}
public String getLifeCycleStatus() {
return lifeCycleStatus;
}
public void setLifeCycleStatus(String lifeCycleStatus) {
this.lifeCycleStatus = lifeCycleStatus;
}
public String getThumbnailUri() {
return thumbnailUri;
}
public void setThumbnailUri(String thumbnailUri) {
this.thumbnailUri = thumbnailUri;
}
public String getAvgRating() {
return avgRating;
}
public void setAvgRating(String avgRating) {
this.avgRating = avgRating;
}
public List<String> getThrottlingPolicies() {
return throttlingPolicies;
}
public void setThrottlingPolicies(List<String> throttlingPolicies) {
this.throttlingPolicies = throttlingPolicies;
}
public JSONObject getAdvertiseInfo() {
return advertiseInfo;
}
public void setAdvertiseInfo(JSONObject advertiseInfo) {
this.advertiseInfo = advertiseInfo;
}
public JSONObject getBusinessInformation() {
return businessInformation;
}
public void setBusinessInformation(JSONObject businessInformation) {
this.businessInformation = businessInformation;
}
public boolean isSubscriptionAvailable() {
return isSubscriptionAvailable;
}
public void setSubscriptionAvailable(boolean subscriptionAvailable) {
isSubscriptionAvailable = subscriptionAvailable;
}
public String getMonetizationLabel() {
return monetizationLabel;
}
public void setMonetizationLabel(String monetizationLabel) {
this.monetizationLabel = monetizationLabel;
}
public String getGatewayVendor() {
return gatewayVendor;
}
public void setGatewayVendor(String gatewayVendor) {
this.gatewayVendor = gatewayVendor;
}
public List<String> getAdditionalProperties() {
return additionalProperties;
}
public void setAdditionalProperties(List<String> additionalProperties) {
this.additionalProperties = additionalProperties;
}
}

View File

@ -0,0 +1,45 @@
/*
* Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer;
/**
* This class represents the Consumer API Key Information.
*/
public class APIKey {
private String apikey;
private int validityTime;
public String getApikey() {
return apikey;
}
public void setApikey(String apikey) {
this.apikey = apikey;
}
public int getValidityTime() {
return validityTime;
}
public void setValidityTime(int validityTime) {
this.validityTime = validityTime;
}
}

View File

@ -0,0 +1,148 @@
/*
* Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer;
import org.wso2.carbon.apimgt.api.model.APIKey;
import java.util.List;
import java.util.Map;
/**
* This class represents the Consumer Application Information.
*/
public class Application {
private String applicationId;
private String name;
private String throttlingPolicy;
private String description;
private String tokenType;
private String status;
private List<String> groups;
private int subscriptionCount;
private List<String> keys;
private Map<String, String> attributes;
private List<Scopes> subscriptionScopes;
private String owner;
private boolean hashEnabled;
public String getApplicationId() {
return applicationId;
}
public void setApplicationId(String applicationId) {
this.applicationId = applicationId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getThrottlingPolicy() {
return throttlingPolicy;
}
public void setThrottlingPolicy(String throttlingPolicy) {
this.throttlingPolicy = throttlingPolicy;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getTokenType() {
return tokenType;
}
public void setTokenType(String tokenType) {
this.tokenType = tokenType;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public List<String> getGroups() {
return groups;
}
public void setGroups(List<String> groups) {
this.groups = groups;
}
public int getSubscriptionCount() {
return subscriptionCount;
}
public void setSubscriptionCount(int subscriptionCount) {
this.subscriptionCount = subscriptionCount;
}
public List<String> getKeys() {
return keys;
}
public void setKeys(List<String> keys) {
this.keys = keys;
}
public Map<String, String> getAttributes() {
return attributes;
}
public void setAttributes(Map<String, String> attributes) {
this.attributes = attributes;
}
public List<Scopes> getSubscriptionScopes() {
return subscriptionScopes;
}
public void setSubscriptionScopes(List<Scopes> subscriptionScopes) {
this.subscriptionScopes = subscriptionScopes;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
public boolean isHashEnabled() {
return hashEnabled;
}
public void setHashEnabled(boolean hashEnabled) {
this.hashEnabled = hashEnabled;
}
}

View File

@ -0,0 +1,110 @@
/*
* Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer;
import io.apicurio.datamodels.asyncapi.v2.visitors.Aai20Traverser;
import java.util.List;
/**
* This class represents the Consumer Application configuration Information.
*/
public class ApplicationConfigurations {
private String name;
private String label;
private String type;
private boolean required;
private boolean mask;
private boolean multiple;
private String tooltip;
private List<String> values;
private String defaults;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public boolean isRequired() {
return required;
}
public void setRequired(boolean required) {
this.required = required;
}
public boolean isMask() {
return mask;
}
public void setMask(boolean mask) {
this.mask = mask;
}
public boolean isMultiple() {
return multiple;
}
public void setMultiple(boolean multiple) {
this.multiple = multiple;
}
public String getTooltip() {
return tooltip;
}
public void setTooltip(String tooltip) {
this.tooltip = tooltip;
}
public List<String> getValues() {
return values;
}
public void setValues(List<String> values) {
this.values = values;
}
public String getDefaults() {
return defaults;
}
public void setDefaults(String defaults) {
this.defaults = defaults;
}
}

View File

@ -0,0 +1,26 @@
package io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer;
import java.util.ArrayList;
public class ApplicationGrantTypeUpdater {
private String callbackUrl;
private ArrayList<String> supportedGrantTypes;
public String getCallbackUrl() {
return callbackUrl;
}
public void setCallbackUrl(String callbackUrl) {
this.callbackUrl = callbackUrl;
}
public ArrayList<String> getSupportedGrantTypes() {
return supportedGrantTypes;
}
public void setSupportedGrantTypes(ArrayList<String> supportedGrantTypes) {
this.supportedGrantTypes = supportedGrantTypes;
}
}

View File

@ -0,0 +1,138 @@
/*
* Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer;
import org.json.JSONObject;
import java.util.List;
/**
* This class represents the Consumer Application key Information.
*/
public class ApplicationKey {
private String keyMappingId;
private String keyManager;
private String consumerKey;
private String consumerSecret;
private List<String> supportedGrantTypes;
private String callbackUrl;
private String keyState;
private String keyType;
private String mode;
private String groupId;
private JSONObject token;
private JSONObject additionalProperties;
public String getKeyMappingId() {
return keyMappingId;
}
public void setKeyMappingId(String keyMappingId) {
this.keyMappingId = keyMappingId;
}
public String getKeyManager() {
return keyManager;
}
public void setKeyManager(String keyManager) {
this.keyManager = keyManager;
}
public String getConsumerKey() {
return consumerKey;
}
public void setConsumerKey(String consumerKey) {
this.consumerKey = consumerKey;
}
public String getConsumerSecret() {
return consumerSecret;
}
public void setConsumerSecret(String consumerSecret) {
this.consumerSecret = consumerSecret;
}
public List<String> getSupportedGrantTypes() {
return supportedGrantTypes;
}
public void setSupportedGrantTypes(List<String> supportedGrantTypes) {
this.supportedGrantTypes = supportedGrantTypes;
}
public String getCallbackUrl() {
return callbackUrl;
}
public void setCallbackUrl(String callbackUrl) {
this.callbackUrl = callbackUrl;
}
public String getKeyState() {
return keyState;
}
public void setKeyState(String keyState) {
this.keyState = keyState;
}
public String getKeyType() {
return keyType;
}
public void setKeyType(String keyType) {
this.keyType = keyType;
}
public String getMode() {
return mode;
}
public void setMode(String mode) {
this.mode = mode;
}
public String getGroupId() {
return groupId;
}
public void setGroupId(String groupId) {
this.groupId = groupId;
}
public JSONObject getToken() {
return token;
}
public void setToken(JSONObject token) {
this.token = token;
}
public JSONObject getAdditionalProperties() {
return additionalProperties;
}
public void setAdditionalProperties(JSONObject additionalProperties) {
this.additionalProperties = additionalProperties;
}
}

View File

@ -0,0 +1,184 @@
/*
* Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer;
import org.json.JSONObject;
import java.util.List;
/**
* This class represents the Consumer Key manager Information.
*/
public class KeyManager {
private String id;
private String name;
private String type;
private String displayName;
private String description;
private boolean enabled;
private List<String> availableGrantTypes;
private String tokenEndpoint;
private String revokeEndpoint;
private String userInfoEndpoint;
private String enableTokenGeneration;
private String enableTokenEncryption;
private String enableTokenHashing;
private String enableOAuthAppCreation;
private String enableMapOAuthConsumerApps;
private List<ApplicationConfigurations> applicationConfiguration;
private JSONObject additionalProperties;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public List<String> getAvailableGrantTypes() {
return availableGrantTypes;
}
public void setAvailableGrantTypes(List<String> availableGrantTypes) {
this.availableGrantTypes = availableGrantTypes;
}
public String getTokenEndpoint() {
return tokenEndpoint;
}
public void setTokenEndpoint(String tokenEndpoint) {
this.tokenEndpoint = tokenEndpoint;
}
public String getRevokeEndpoint() {
return revokeEndpoint;
}
public void setRevokeEndpoint(String revokeEndpoint) {
this.revokeEndpoint = revokeEndpoint;
}
public String getUserInfoEndpoint() {
return userInfoEndpoint;
}
public void setUserInfoEndpoint(String userInfoEndpoint) {
this.userInfoEndpoint = userInfoEndpoint;
}
public String getEnableTokenGeneration() {
return enableTokenGeneration;
}
public void setEnableTokenGeneration(String enableTokenGeneration) {
this.enableTokenGeneration = enableTokenGeneration;
}
public String getEnableTokenEncryption() {
return enableTokenEncryption;
}
public void setEnableTokenEncryption(String enableTokenEncryption) {
this.enableTokenEncryption = enableTokenEncryption;
}
public String getEnableTokenHashing() {
return enableTokenHashing;
}
public void setEnableTokenHashing(String enableTokenHashing) {
this.enableTokenHashing = enableTokenHashing;
}
public String getEnableOAuthAppCreation() {
return enableOAuthAppCreation;
}
public void setEnableOAuthAppCreation(String enableOAuthAppCreation) {
this.enableOAuthAppCreation = enableOAuthAppCreation;
}
public String getEnableMapOAuthConsumerApps() {
return enableMapOAuthConsumerApps;
}
public void setEnableMapOAuthConsumerApps(String enableMapOAuthConsumerApps) {
this.enableMapOAuthConsumerApps = enableMapOAuthConsumerApps;
}
public List<ApplicationConfigurations> getApplicationConfiguration() {
return applicationConfiguration;
}
public void setApplicationConfiguration(List<ApplicationConfigurations> applicationConfiguration) {
this.applicationConfiguration = applicationConfiguration;
}
public JSONObject getAdditionalProperties() {
return additionalProperties;
}
public void setAdditionalProperties(JSONObject additionalProperties) {
this.additionalProperties = additionalProperties;
}
}

View File

@ -0,0 +1,65 @@
/*
* Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer;
import java.util.List;
/**
* This class represents the scope data.
*/
public class Scopes {
private String key;
private String name;
private List<String> roles;
private String description;
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<String> getRoles() {
return roles;
}
public void setRoles(List<String> roles) {
this.roles = roles;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}

View File

@ -0,0 +1,106 @@
/*
* Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer;
import org.json.JSONObject;
public class Subscription {
private String subscriptionId;
private String applicationId;
private String apiId;
private APIInfo apiInfo;
private JSONObject applicationInfo;
private String throttlingPolicy;
private String requestedThrottlingPolicy;
private String status;
private String redirectionParams;
public String getSubscriptionId() {
return subscriptionId;
}
public void setSubscriptionId(String subscriptionId) {
this.subscriptionId = subscriptionId;
}
public String getApplicationId() {
return applicationId;
}
public void setApplicationId(String applicationId) {
this.applicationId = applicationId;
}
public String getApiId() {
return apiId;
}
public void setApiId(String apiId) {
this.apiId = apiId;
}
public APIInfo getApiInfo() {
return apiInfo;
}
public void setApiInfo(APIInfo apiInfo) {
this.apiInfo = apiInfo;
}
public JSONObject getApplicationInfo() {
return applicationInfo;
}
public void setApplicationInfo(JSONObject applicationInfo) {
this.applicationInfo = applicationInfo;
}
public String getThrottlingPolicy() {
return throttlingPolicy;
}
public void setThrottlingPolicy(String throttlingPolicy) {
this.throttlingPolicy = throttlingPolicy;
}
public String getRequestedThrottlingPolicy() {
return requestedThrottlingPolicy;
}
public void setRequestedThrottlingPolicy(String requestedThrottlingPolicy) {
this.requestedThrottlingPolicy = requestedThrottlingPolicy;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getRedirectionParams() {
return redirectionParams;
}
public void setRedirectionParams(String redirectionParams) {
this.redirectionParams = redirectionParams;
}
}

View File

@ -24,17 +24,20 @@ public final class Constants {
} }
public static final String EMPTY_STRING = ""; public static final String EMPTY_STRING = "";
public static final String CLIENT_NAME = "rest_api_publisher_code"; public static final String AMPERSAND = "&";
public static final String SLASH = "/";
public static final String EQUAL = "=";
public static final String SERVER_USER = "WorkflowConfigurations.ServerUser"; public static final String SERVER_USER = "WorkflowConfigurations.ServerUser";
public static final String SERVER_PASSWORD = "WorkflowConfigurations.ServerPassword"; public static final String SERVER_PASSWORD = "WorkflowConfigurations.ServerPassword";
public static final String GRANT_TYPE = "client_credentials password refresh_token";
public static final String REFRESH_TOKEN_GRANT_TYPE_PARAM_NAME = "refresh_token"; public static final String REFRESH_TOKEN_GRANT_TYPE_PARAM_NAME = "refresh_token";
public static final String OAUTH_EXPIRES_IN = "expires_in"; public static final String OAUTH_EXPIRES_IN = "expires_in";
public static final String OAUTH_TOKEN_SCOPE = "scope"; public static final String OAUTH_TOKEN_SCOPE = "scope";
public static final String OAUTH_TOKEN_TYPE = "token_type"; public static final String OAUTH_TOKEN_TYPE = "token_type";
public static final String REFRESH_TOKEN_GRANT_TYPE = "refresh_token"; public static final String REFRESH_TOKEN_GRANT_TYPE = "refresh_token";
public static final String SCOPE_PARAM_NAME = "scope"; public static final String SCOPE_PARAM_NAME = "scope";
public static final String SCOPES = "apim:api_create apim:api_view apim:shared_scope_manage apim:api_import_export apim:api_publish"; public static final String SCOPES = "apim:api_create apim:api_view apim:shared_scope_manage apim:api_import_export " +
"apim:api_publish apim:admin apim:api_key apim:app_import_export apim:app_manage apim:store_settings " +
"apim:sub_alert_manage apim:sub_manage apim:subscribe openid";
public static final String DCR_END_POINT = "WorkflowConfigurations.DCREndPoint"; public static final String DCR_END_POINT = "WorkflowConfigurations.DCREndPoint";
public static final String TOKE_END_POINT = "WorkflowConfigurations.TokenEndPoint"; public static final String TOKE_END_POINT = "WorkflowConfigurations.TokenEndPoint";
public static final String ADAPTER_CONF_KEEP_ALIVE = "keepAlive"; public static final String ADAPTER_CONF_KEEP_ALIVE = "keepAlive";
@ -61,14 +64,16 @@ public final class Constants {
public static final String SPACE = " "; public static final String SPACE = " ";
public static final String IOT_CORE_HOST = "iot.core.host"; public static final String IOT_CORE_HOST = "iot.core.host";
public static final String IOT_CORE_HTTPS_PORT = "iot.core.https.port"; public static final String IOT_CORE_HTTPS_PORT = "iot.core.https.port";
public static final String GET_ALL_SCOPES = "/api/am/publisher/v2/scopes?limit=1000"; public static final String GET_ALL_SCOPES = "/api/am/publisher/v4/scopes?limit=1000";
public static final String SCOPE_API_ENDPOINT = "/api/am/publisher/v2/scopes/"; public static final String SCOPE_API_ENDPOINT = "/api/am/publisher/v4/scopes/";
public static final String API_ENDPOINT = "/api/am/publisher/v2/apis/"; public static final String API_ENDPOINT = "/api/am/publisher/v4/apis/";
public static final String GET_ALL_APIS = "/api/am/publisher/v2/apis?limit=1000"; public static final String GET_ALL_APIS = "/api/am/publisher/v4/apis?limit=1000";
public static final String APPLICATIONS_API = "/api/am/devportal/v3/applications";
public static final String SUBSCRIPTION_API = "/api/am/devportal/v3/subscriptions";
public static final String DEV_PORTAL_API = "/api/am/devportal/v3/apis?limit=1000";
public static final String KEY_MANAGERS_API = "/api/am/devportal/v3/key-managers";
public static final String SCOPE_PUBLISH_RESERVED_USER_NAME = "scope_publish_reserved_user"; public static final String SCOPE_PUBLISH_RESERVED_USER_NAME = "scope_publish_reserved_user";
public static final String SCOPE_PUBLISH_RESERVED_USER_PASSWORD = "&gKfyE8E4rUY4Q"; public static final String SCOPE_PUBLISH_RESERVED_USER_PASSWORD = "&gKfyE8E4rUY4Q";
public static final String ADMIN_ROLE_KEY = "admin"; public static final String ADMIN_ROLE_KEY = "admin";
public static final String PERM_SCOPE_MAPPING_META_KEY = "perm-scope-mapping"; public static final String PERM_SCOPE_MAPPING_META_KEY = "perm-scope-mapping";
} }

View File

@ -0,0 +1,61 @@
/*
* Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.entgra.device.mgt.core.apimgt.extension.rest.api.dto;
/**
* This holds the API application client information and token information.
*/
public class ApiApplicationInfo {
private String clientId;
private String clientSecret;
private String refresh_token;
private String access_token;
public String getClientId() {
return clientId;
}
public void setClientId(String clientId) {
this.clientId = clientId;
}
public String getClientSecret() {
return clientSecret;
}
public void setClientSecret(String clientSecret) {
this.clientSecret = clientSecret;
}
public String getRefresh_token() {
return refresh_token;
}
public void setRefresh_token(String refresh_token) {
this.refresh_token = refresh_token;
}
public String getAccess_token() {
return access_token;
}
public void setAccess_token(String access_token) {
this.access_token = access_token;
}
}

View File

@ -20,28 +20,25 @@ package io.entgra.device.mgt.core.apimgt.extension.rest.api.internal;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.APIApplicationServices; import io.entgra.device.mgt.core.apimgt.extension.rest.api.APIApplicationServices;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.APIApplicationServicesImpl; import io.entgra.device.mgt.core.apimgt.extension.rest.api.APIApplicationServicesImpl;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.ConsumerRESTAPIServices;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.ConsumerRESTAPIServicesImpl;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.PublisherRESTAPIServices; import io.entgra.device.mgt.core.apimgt.extension.rest.api.PublisherRESTAPIServices;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.PublisherRESTAPIServicesImpl; import io.entgra.device.mgt.core.apimgt.extension.rest.api.PublisherRESTAPIServicesImpl;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.osgi.framework.BundleContext; import org.osgi.framework.BundleContext;
import org.osgi.service.component.ComponentContext; import org.osgi.service.component.ComponentContext;
import org.osgi.service.component.annotations.*;
import org.wso2.carbon.apimgt.impl.APIManagerConfigurationService; import org.wso2.carbon.apimgt.impl.APIManagerConfigurationService;
/** @Component(
* @scr.component name="internal.io.entgra.device.mgt.core.apimgt.extension.rest.api.PublisherRESTAPIServiceComponent" name = "io.entgra.device.mgt.core.apimgt.extension.rest.api.internal.APIManagerServiceComponent",
* immediate="true" immediate = true)
* @scr.reference name="user.apimanagerconfigurationservice.default"
* interface="org.wso2.carbon.apimgt.impl.APIManagerConfigurationService"
* cardinality="1..1"
* policy="dynamic"
* bind="setAPIManagerConfigurationService"
* unbind="unsetAPIManagerConfigurationService"
*/
public class APIManagerServiceComponent { public class APIManagerServiceComponent {
private static Log log = LogFactory.getLog(APIManagerServiceComponent.class); private static Log log = LogFactory.getLog(APIManagerServiceComponent.class);
@Activate
protected void activate(ComponentContext componentContext) { protected void activate(ComponentContext componentContext) {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Initializing publisher API extension bundle"); log.debug("Initializing publisher API extension bundle");
@ -57,6 +54,10 @@ public class APIManagerServiceComponent {
bundleContext.registerService(PublisherRESTAPIServices.class.getName(), publisherRESTAPIServices, null); bundleContext.registerService(PublisherRESTAPIServices.class.getName(), publisherRESTAPIServices, null);
APIManagerServiceDataHolder.getInstance().setPublisherRESTAPIServices(publisherRESTAPIServices); APIManagerServiceDataHolder.getInstance().setPublisherRESTAPIServices(publisherRESTAPIServices);
ConsumerRESTAPIServices consumerRESTAPIServices = new ConsumerRESTAPIServicesImpl();
bundleContext.registerService(ConsumerRESTAPIServices.class.getName(), consumerRESTAPIServices, null);
APIManagerServiceDataHolder.getInstance().setConsumerRESTAPIServices(consumerRESTAPIServices);
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("API Application bundle has been successfully initialized"); log.debug("API Application bundle has been successfully initialized");
} }
@ -64,11 +65,17 @@ public class APIManagerServiceComponent {
log.error("Error occurred while initializing API Application bundle", e); log.error("Error occurred while initializing API Application bundle", e);
} }
} }
@Deactivate
protected void deactivate(ComponentContext componentContext) { protected void deactivate(ComponentContext componentContext) {
//do nothing //do nothing
} }
@Reference(
name = "apim.configuration.service",
service = org.wso2.carbon.apimgt.impl.APIManagerConfigurationService.class,
cardinality = ReferenceCardinality.MANDATORY,
policy = ReferencePolicy.DYNAMIC,
unbind = "unsetAPIManagerConfigurationService")
protected void setAPIManagerConfigurationService(APIManagerConfigurationService apiManagerConfigurationService) { protected void setAPIManagerConfigurationService(APIManagerConfigurationService apiManagerConfigurationService) {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Setting API Manager Configuration Service"); log.debug("Setting API Manager Configuration Service");

View File

@ -20,6 +20,7 @@ package io.entgra.device.mgt.core.apimgt.extension.rest.api.internal;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.APIApplicationServices; import io.entgra.device.mgt.core.apimgt.extension.rest.api.APIApplicationServices;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.PublisherRESTAPIServices; import io.entgra.device.mgt.core.apimgt.extension.rest.api.PublisherRESTAPIServices;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.ConsumerRESTAPIServices;
import org.wso2.carbon.apimgt.impl.APIManagerConfigurationService; import org.wso2.carbon.apimgt.impl.APIManagerConfigurationService;
import org.wso2.carbon.user.core.service.RealmService; import org.wso2.carbon.user.core.service.RealmService;
import org.wso2.carbon.user.core.tenant.TenantManager; import org.wso2.carbon.user.core.tenant.TenantManager;
@ -34,6 +35,8 @@ public class APIManagerServiceDataHolder {
private static APIManagerServiceDataHolder thisInstance = new APIManagerServiceDataHolder(); private static APIManagerServiceDataHolder thisInstance = new APIManagerServiceDataHolder();
private ConsumerRESTAPIServices consumerRESTAPIServices;
private APIManagerServiceDataHolder() { private APIManagerServiceDataHolder() {
} }
@ -60,6 +63,7 @@ public class APIManagerServiceDataHolder {
return apiManagerConfigurationService; return apiManagerConfigurationService;
} }
public PublisherRESTAPIServices getPublisherRESTAPIServices() { public PublisherRESTAPIServices getPublisherRESTAPIServices() {
return publisherRESTAPIServices; return publisherRESTAPIServices;
} }
@ -90,4 +94,12 @@ public class APIManagerServiceDataHolder {
} }
this.tenantManager = realmService.getTenantManager(); this.tenantManager = realmService.getTenantManager();
} }
public ConsumerRESTAPIServices getConsumerRESTAPIServices() {
return consumerRESTAPIServices;
}
public void setConsumerRESTAPIServices(ConsumerRESTAPIServices consumerRESTAPIServices) {
this.consumerRESTAPIServices = consumerRESTAPIServices;
}
} }

View File

@ -25,30 +25,12 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.base.ServerConfiguration; import org.wso2.carbon.base.ServerConfiguration;
import javax.net.ssl.SSLContext; import javax.net.ssl.*;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import javax.net.ssl.SSLSession;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.HostnameVerifier;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.net.Proxy; import java.net.*;
import java.net.ProxySelector; import java.security.*;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.net.URI;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.SecureRandom;
import java.security.cert.CertificateException; import java.security.cert.CertificateException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;

View File

@ -21,26 +21,20 @@
<parent> <parent>
<artifactId>apimgt-extensions</artifactId> <artifactId>apimgt-extensions</artifactId>
<groupId>io.entgra.device.mgt.core</groupId> <groupId>io.entgra.device.mgt.core</groupId>
<version>5.1.0</version> <version>6.0.1-SNAPSHOT</version>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>io.entgra.device.mgt.core.apimgt.keymgt.extension.api</artifactId> <artifactId>io.entgra.device.mgt.core.apimgt.keymgt.extension.api</artifactId>
<packaging>war</packaging> <packaging>war</packaging>
<name>WSO2 Carbon - API Key Management API</name> <name>Entgra Device Management - API Key Management API</name>
<description>This module extends the API manager's key management apis.</description> <description>This module extends the API manager's key management apis.</description>
<url>http://wso2.org</url> <url>https://entgra.io</url>
<build> <build>
<plugins> <plugins>
<plugin> <plugin>
<artifactId>maven-compiler-plugin</artifactId> <groupId>org.apache.maven.plugins</groupId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId> <artifactId>maven-war-plugin</artifactId>
<configuration> <configuration>
<packagingExcludes>WEB-INF/lib/*cxf*.jar</packagingExcludes> <packagingExcludes>WEB-INF/lib/*cxf*.jar</packagingExcludes>

View File

@ -22,6 +22,7 @@ import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlRootElement;
import java.util.ArrayList;
@XmlRootElement @XmlRootElement
@ -32,6 +33,8 @@ public class DCRRequest {
@XmlElement(required = true) @XmlElement(required = true)
private String username; private String username;
@XmlElement(required = true) @XmlElement(required = true)
private String password;
@XmlElement(required = true)
private String grantTypes; private String grantTypes;
@XmlElement @XmlElement
private String callBackUrl; private String callBackUrl;
@ -43,6 +46,10 @@ public class DCRRequest {
@XmlElement @XmlElement
private int validityPeriod; private int validityPeriod;
private String callbackUrl;
private ArrayList<String> supportedGrantTypes;
public String getApplicationName() { public String getApplicationName() {
return applicationName; return applicationName;
} }
@ -98,4 +105,24 @@ public class DCRRequest {
public void setValidityPeriod(int validityPeriod) { public void setValidityPeriod(int validityPeriod) {
this.validityPeriod = validityPeriod; this.validityPeriod = validityPeriod;
} }
public String getPassword() { return password; }
public void setPassword(String password) { this.password = password; }
public String getCallbackUrl() {
return callbackUrl;
}
public void setCallbackUrl(String callbackUrl) {
this.callbackUrl = callbackUrl;
}
public ArrayList<String> getSupportedGrantTypes() {
return supportedGrantTypes;
}
public void setSupportedGrantTypes(ArrayList<String> supportedGrantTypes) {
this.supportedGrantTypes = supportedGrantTypes;
}
} }

View File

@ -18,12 +18,7 @@
package io.entgra.device.mgt.core.apimgt.keymgt.extension.api; package io.entgra.device.mgt.core.apimgt.keymgt.extension.api;
import javax.ws.rs.Consumes; import javax.ws.rs.*;
import javax.ws.rs.FormParam;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;

View File

@ -27,13 +27,9 @@ import io.entgra.device.mgt.core.apimgt.keymgt.extension.exception.KeyMgtExcepti
import io.entgra.device.mgt.core.apimgt.keymgt.extension.service.KeyMgtService; import io.entgra.device.mgt.core.apimgt.keymgt.extension.service.KeyMgtService;
import io.entgra.device.mgt.core.apimgt.keymgt.extension.service.KeyMgtServiceImpl; import io.entgra.device.mgt.core.apimgt.keymgt.extension.service.KeyMgtServiceImpl;
import io.entgra.device.mgt.core.device.mgt.common.exceptions.UnAuthorizedException; import io.entgra.device.mgt.core.device.mgt.common.exceptions.UnAuthorizedException;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import javax.ws.rs.Consumes; import javax.ws.rs.*;
import javax.ws.rs.FormParam;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
import java.util.Base64; import java.util.Base64;
@ -51,7 +47,9 @@ public class KeyManagerServiceImpl implements KeyManagerService {
try { try {
KeyMgtService keyMgtService = new KeyMgtServiceImpl(); KeyMgtService keyMgtService = new KeyMgtServiceImpl();
DCRResponse resp = keyMgtService.dynamicClientRegistration(dcrRequest.getApplicationName(), dcrRequest.getUsername(), DCRResponse resp = keyMgtService.dynamicClientRegistration(dcrRequest.getApplicationName(), dcrRequest.getUsername(),
dcrRequest.getGrantTypes(), dcrRequest.getCallBackUrl(), dcrRequest.getTags(), dcrRequest.getIsSaasApp(), dcrRequest.getValidityPeriod()); dcrRequest.getGrantTypes(), dcrRequest.getCallBackUrl(), dcrRequest.getTags(),
dcrRequest.getIsSaasApp(), dcrRequest.getValidityPeriod(), dcrRequest.getPassword(),
dcrRequest.getSupportedGrantTypes(), dcrRequest.getCallbackUrl());
return Response.status(Response.Status.CREATED).entity(gson.toJson(resp)).build(); return Response.status(Response.Status.CREATED).entity(gson.toJson(resp)).build();
} catch (KeyMgtException e) { } catch (KeyMgtException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();

View File

@ -19,9 +19,9 @@
<beans xmlns="http://www.springframework.org/schema/beans" <beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jaxrs="http://cxf.apache.org/jaxrs" xmlns:cxf="http://cxf.apache.org/core" xmlns:jaxrs="http://cxf.apache.org/jaxrs"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd http://cxf.apache.org/core http://cxf.apache.org/schemas/core.xsd"> http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd">
<jaxrs:server id="services" address="/"> <jaxrs:server id="services" address="/">
<jaxrs:serviceBeans> <jaxrs:serviceBeans>

View File

@ -21,18 +21,23 @@
<parent> <parent>
<artifactId>apimgt-extensions</artifactId> <artifactId>apimgt-extensions</artifactId>
<groupId>io.entgra.device.mgt.core</groupId> <groupId>io.entgra.device.mgt.core</groupId>
<version>5.1.0</version> <version>6.0.1-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>io.entgra.device.mgt.core.apimgt.keymgt.extension</artifactId> <artifactId>io.entgra.device.mgt.core.apimgt.keymgt.extension</artifactId>
<packaging>bundle</packaging> <packaging>bundle</packaging>
<name>WSO2 Carbon - API Key Management</name> <name>Entgra Device Management - API Key Management</name>
<description>This module extends the API manager's key management.</description> <description>This module extends the API manager's key management.</description>
<url>http://wso2.org</url> <url>https://entgra.io</url>
<dependencies> <dependencies>
<dependency>
<groupId>org.apache.felix</groupId>
<artifactId>org.apache.felix.scr.ds-annotations</artifactId>
<scope>provided</scope>
</dependency>
<dependency> <dependency>
<groupId>commons-codec.wso2</groupId> <groupId>commons-codec.wso2</groupId>
<artifactId>commons-codec</artifactId> <artifactId>commons-codec</artifactId>
@ -50,18 +55,18 @@
<groupId>io.entgra.device.mgt.core</groupId> <groupId>io.entgra.device.mgt.core</groupId>
<artifactId>io.entgra.device.mgt.core.device.mgt.common</artifactId> <artifactId>io.entgra.device.mgt.core.device.mgt.common</artifactId>
</dependency> </dependency>
<dependency>
<groupId>io.entgra.device.mgt.core</groupId>
<artifactId>io.entgra.device.mgt.core.apimgt.extension.rest.api</artifactId>
<!-- <scope>provided</scope>-->
</dependency>
</dependencies> </dependencies>
<build> <build>
<plugins> <plugins>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-scr-plugin</artifactId>
</plugin>
<plugin> <plugin>
<groupId>org.apache.felix</groupId> <groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId> <artifactId>maven-bundle-plugin</artifactId>
<version>5.1.7</version>
<extensions>true</extensions> <extensions>true</extensions>
<configuration> <configuration>
<instructions> <instructions>
@ -70,12 +75,41 @@
<Bundle-Version>${io.entgra.device.mgt.core.version}</Bundle-Version> <Bundle-Version>${io.entgra.device.mgt.core.version}</Bundle-Version>
<Bundle-Description>API Management Application Bundle</Bundle-Description> <Bundle-Description>API Management Application Bundle</Bundle-Description>
<Private-Package>io.entgra.device.mgt.core.apimgt.keymgt.extension.internal</Private-Package> <Private-Package>io.entgra.device.mgt.core.apimgt.keymgt.extension.internal</Private-Package>
<Import-Packages> <Import-Package>
io.entgra.device.mgt.core.apimgt.application.extension, com.google.gson;version="[2.9,3)",
io.entgra.device.mgt.core.apimgt.application.extension.*, io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.*;version="${io.entgra.device.mgt.core.version.range}",
io.entgra.device.mgt.core.device.mgt.common.*, io.entgra.device.mgt.core.device.mgt.common.permission.mgt;version="${io.entgra.device.mgt.core.version.range}",
io.entgra.device.mgt.core.device.mgt.core.* io.entgra.device.mgt.core.device.mgt.core.config;version="${io.entgra.device.mgt.core.version.range}",
</Import-Packages> io.entgra.device.mgt.core.device.mgt.core.config.keymanager;version="${io.entgra.device.mgt.core.version.range}",
io.entgra.device.mgt.core.device.mgt.core.permission.mgt;version="${io.entgra.device.mgt.core.version.range}",
javax.cache;version="[1.0,2)",
javax.net.ssl,okhttp3;version="[4.9,5)",
org.apache.commons.lang;version="[2.4,3)",
org.apache.commons.logging;version="[1.2,2)",
org.json;version="[3.0,4)",
org.osgi.framework.*;version="${imp.package.version.osgi.framework}",
org.osgi.service.*;version="${imp.package.version.osgi.service}",
org.wso2.carbon.apimgt.api;version="[9.28,10)",
org.wso2.carbon.apimgt.api.model;version="[9.28,10)",
org.wso2.carbon.apimgt.api.model.subscription;version="[9.28,10)",
org.wso2.carbon.apimgt.impl;version="[9.28,10)",
org.wso2.carbon.apimgt.impl.caching;version="[9.28,10)",
org.wso2.carbon.apimgt.impl.dto;version="[9.28,10)",
org.wso2.carbon.apimgt.impl.factory;version="[9.28,10)",
org.wso2.carbon.apimgt.impl.jwt;version="[9.28,10)",
org.wso2.carbon.apimgt.impl.utils;version="[9.28,10)",
org.wso2.carbon.apimgt.keymgt;version="[9.28,10)",
org.wso2.carbon.apimgt.keymgt.handlers;version="[9.28,10)",
org.wso2.carbon.apimgt.keymgt.model;version="[9.28,10)",
org.wso2.carbon.apimgt.keymgt.model.entity;version="[9.28,10)",
org.wso2.carbon.apimgt.keymgt.service;version="[9.28,10)",
io.entgra.device.mgt.core.apimgt.extension.rest.api,
org.wso2.carbon.context;version="[4.8,5)",
org.wso2.carbon.user.api;version="[1.0,2)",
org.wso2.carbon.user.core.service;version="[4.8,5)",
org.wso2.carbon.user.core.tenant;version="[4.8,5)",
org.wso2.carbon.utils.multitenancy;version="[4.8,5)"
</Import-Package>
<Export-Package> <Export-Package>
!io.entgra.device.mgt.core.apimgt.keymgt.extension.internal, !io.entgra.device.mgt.core.apimgt.keymgt.extension.internal,
io.entgra.device.mgt.core.apimgt.keymgt.extension.* io.entgra.device.mgt.core.apimgt.keymgt.extension.*

View File

@ -18,6 +18,7 @@
package io.entgra.device.mgt.core.apimgt.keymgt.extension; package io.entgra.device.mgt.core.apimgt.keymgt.extension;
import org.osgi.service.component.annotations.Component;
import org.wso2.carbon.apimgt.api.model.ConfigurationDto; import org.wso2.carbon.apimgt.api.model.ConfigurationDto;
import org.wso2.carbon.apimgt.impl.APIConstants; import org.wso2.carbon.apimgt.impl.APIConstants;
import org.wso2.carbon.apimgt.impl.DefaultKeyManagerConnectorConfiguration; import org.wso2.carbon.apimgt.impl.DefaultKeyManagerConnectorConfiguration;
@ -27,9 +28,10 @@ import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
/** @Component(
* @scr.component name="io.entgra.device.mgt.core.apimgt.keymgt.extension.customKeyManagerConfigComponent" immediate="true" name = "io.entgra.device.mgt.core.apimgt.keymgt.extension.KeyManagerConnectorConfiguration",
*/ service = DefaultKeyManagerConnectorConfiguration.class,
immediate = true)
public class KeyManagerConnectorConfiguration extends DefaultKeyManagerConnectorConfiguration { public class KeyManagerConnectorConfiguration extends DefaultKeyManagerConnectorConfiguration {
@Override @Override

View File

@ -17,6 +17,10 @@
*/ */
package io.entgra.device.mgt.core.apimgt.keymgt.extension; package io.entgra.device.mgt.core.apimgt.keymgt.extension;
import io.entgra.device.mgt.core.device.mgt.common.permission.mgt.Permission;
import io.entgra.device.mgt.core.device.mgt.common.permission.mgt.PermissionManagementException;
import io.entgra.device.mgt.core.device.mgt.common.permission.mgt.PermissionManagerService;
import io.entgra.device.mgt.core.device.mgt.core.permission.mgt.PermissionManagerServiceImpl;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
@ -36,22 +40,12 @@ import org.wso2.carbon.apimgt.keymgt.model.SubscriptionDataStore;
import org.wso2.carbon.apimgt.keymgt.model.entity.API; import org.wso2.carbon.apimgt.keymgt.model.entity.API;
import org.wso2.carbon.apimgt.keymgt.service.TokenValidationContext; import org.wso2.carbon.apimgt.keymgt.service.TokenValidationContext;
import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext;
import io.entgra.device.mgt.core.device.mgt.common.permission.mgt.Permission;
import io.entgra.device.mgt.core.device.mgt.common.permission.mgt.PermissionManagementException;
import io.entgra.device.mgt.core.device.mgt.common.permission.mgt.PermissionManagerService;
import io.entgra.device.mgt.core.device.mgt.core.permission.mgt.PermissionManagerServiceImpl;
import org.wso2.carbon.user.api.UserRealm; import org.wso2.carbon.user.api.UserRealm;
import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.user.core.service.RealmService; import org.wso2.carbon.user.core.service.RealmService;
import org.wso2.carbon.utils.multitenancy.MultitenantUtils; import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
import java.util.ArrayList; import java.util.*;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.StringTokenizer;
public class KeyValidationHandler extends DefaultKeyValidationHandler { public class KeyValidationHandler extends DefaultKeyValidationHandler {

View File

@ -28,5 +28,9 @@ public class KeyMgtException extends Exception {
public KeyMgtException(String errorMessage) { public KeyMgtException(String errorMessage) {
super(errorMessage); super(errorMessage);
} }
public KeyMgtException(String errorMessage, Exception e) {
super(errorMessage, e);
}
} }

View File

@ -18,12 +18,16 @@
package io.entgra.device.mgt.core.apimgt.keymgt.extension.internal; package io.entgra.device.mgt.core.apimgt.keymgt.extension.internal;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.APIApplicationServices;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.ConsumerRESTAPIServices;
import io.entgra.device.mgt.core.apimgt.keymgt.extension.service.KeyMgtService; import io.entgra.device.mgt.core.apimgt.keymgt.extension.service.KeyMgtService;
public class KeyMgtDataHolder { public class KeyMgtDataHolder {
private static final KeyMgtDataHolder thisInstance = new KeyMgtDataHolder(); private static final KeyMgtDataHolder thisInstance = new KeyMgtDataHolder();
private KeyMgtService keyMgtService; private KeyMgtService keyMgtService;
private ConsumerRESTAPIServices consumerRESTAPIServices;
private APIApplicationServices apiApplicationServices;
public static KeyMgtDataHolder getInstance() { public static KeyMgtDataHolder getInstance() {
return thisInstance; return thisInstance;
@ -37,4 +41,20 @@ public class KeyMgtDataHolder {
this.keyMgtService = keyMgtService; this.keyMgtService = keyMgtService;
} }
public ConsumerRESTAPIServices getConsumerRESTAPIServices() {
return consumerRESTAPIServices;
}
public void setConsumerRESTAPIServices(ConsumerRESTAPIServices consumerRESTAPIServices) {
this.consumerRESTAPIServices = consumerRESTAPIServices;
}
public APIApplicationServices getApiApplicationServices() {
return apiApplicationServices;
}
public void setApiApplicationServices(APIApplicationServices apiApplicationServices) {
this.apiApplicationServices = apiApplicationServices;
}
} }

View File

@ -18,21 +18,25 @@
package io.entgra.device.mgt.core.apimgt.keymgt.extension.internal; package io.entgra.device.mgt.core.apimgt.keymgt.extension.internal;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.APIApplicationServices;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.ConsumerRESTAPIServices;
import io.entgra.device.mgt.core.apimgt.keymgt.extension.service.KeyMgtService;
import io.entgra.device.mgt.core.apimgt.keymgt.extension.service.KeyMgtServiceImpl;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.osgi.framework.BundleContext; import org.osgi.framework.BundleContext;
import org.osgi.service.component.ComponentContext; import org.osgi.service.component.ComponentContext;
import io.entgra.device.mgt.core.apimgt.keymgt.extension.service.KeyMgtService; import org.osgi.service.component.annotations.*;
import io.entgra.device.mgt.core.apimgt.keymgt.extension.service.KeyMgtServiceImpl;
/** @Component(
* @scr.component name="io.entgra.device.mgt.core.apimgt.keymgt.extension.keyMgtServiceComponent" immediate="true" name = "io.entgra.device.mgt.core.apimgt.keymgt.extension.internal.KeyMgtServiceComponent",
*/ immediate = true)
public class KeyMgtServiceComponent { public class KeyMgtServiceComponent {
private static final Log log = LogFactory.getLog(KeyMgtServiceComponent.class); private static final Log log = LogFactory.getLog(KeyMgtServiceComponent.class);
@SuppressWarnings("unused") @SuppressWarnings("unused")
@Activate
protected void activate(ComponentContext componentContext) { protected void activate(ComponentContext componentContext) {
try { try {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
@ -54,9 +58,70 @@ public class KeyMgtServiceComponent {
} }
@SuppressWarnings("unused") @SuppressWarnings("unused")
@Deactivate
protected void deactivate(ComponentContext componentContext) { protected void deactivate(ComponentContext componentContext) {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("De-activating Key Management Service Component"); log.debug("De-activating Key Management Service Component");
} }
} }
/**
* Sets APIM Consumer REST API service.
*
* @param consumerRESTAPIServices An instance of ConsumerRESTAPIServices
*/
@Reference(
name = "APIM.consumer.service",
service = io.entgra.device.mgt.core.apimgt.extension.rest.api.ConsumerRESTAPIServices.class,
cardinality = ReferenceCardinality.MANDATORY,
policy = ReferencePolicy.DYNAMIC,
unbind = "unsetConsumerRESTAPIServices")
protected void setConsumerRESTAPIServices(ConsumerRESTAPIServices consumerRESTAPIServices) {
if (log.isDebugEnabled()) {
log.debug("Setting APIM Consumer REST API Service");
}
KeyMgtDataHolder.getInstance().setConsumerRESTAPIServices(consumerRESTAPIServices);
}
/**
* Unset APIM Consumer REST API service
*
* @param consumerRESTAPIServices An instance of ConsumerRESTAPIServices
*/
protected void unsetConsumerRESTAPIServices(ConsumerRESTAPIServices consumerRESTAPIServices) {
if (log.isDebugEnabled()) {
log.debug("Unsetting APIM Consumer REST API Service");
}
KeyMgtDataHolder.getInstance().setConsumerRESTAPIServices(null);
}
/**
* Sets DCR REST API service.
*
* @param apiApplicationServices An instance of APIApplicationServices
*/
@Reference(
name = "APIM.application.service",
service = io.entgra.device.mgt.core.apimgt.extension.rest.api.APIApplicationServices.class,
cardinality = ReferenceCardinality.MANDATORY,
policy = ReferencePolicy.DYNAMIC,
unbind = "unsetAPIApplicationServices")
protected void setAPIApplicationServices(APIApplicationServices apiApplicationServices) {
if (log.isDebugEnabled()) {
log.debug("Setting DCR REST API Service");
}
KeyMgtDataHolder.getInstance().setApiApplicationServices(apiApplicationServices);
}
/**
* Unset DCR REST API service
*
* @param apiApplicationServices An instance of APIApplicationServices
*/
protected void unsetAPIApplicationServices(APIApplicationServices apiApplicationServices) {
if (log.isDebugEnabled()) {
log.debug("Unsetting DCR REST API Service");
}
KeyMgtDataHolder.getInstance().setApiApplicationServices(null);
}
} }

View File

@ -24,6 +24,8 @@ import io.entgra.device.mgt.core.apimgt.keymgt.extension.TokenResponse;
import io.entgra.device.mgt.core.apimgt.keymgt.extension.exception.BadRequestException; import io.entgra.device.mgt.core.apimgt.keymgt.extension.exception.BadRequestException;
import io.entgra.device.mgt.core.apimgt.keymgt.extension.exception.KeyMgtException; import io.entgra.device.mgt.core.apimgt.keymgt.extension.exception.KeyMgtException;
import java.util.List;
public interface KeyMgtService { public interface KeyMgtService {
/*** /***
@ -35,11 +37,13 @@ public interface KeyMgtService {
* @param callBackUrl callback url of the application * @param callBackUrl callback url of the application
* @param tags api tags for api subscription of the application * @param tags api tags for api subscription of the application
* @param isSaasApp if the application is a saas app * @param isSaasApp if the application is a saas app
* @param password Password of the owner
* @return @{@link DCRResponse} DCR Response object with client credentials * @return @{@link DCRResponse} DCR Response object with client credentials
* @throws KeyMgtException if any error occurs during DCR process * @throws KeyMgtException if any error occurs during DCR process
*/ */
DCRResponse dynamicClientRegistration(String clientName, String owner, String grantTypes, String callBackUrl, DCRResponse dynamicClientRegistration(String clientName, String owner, String grantTypes, String callBackUrl,
String[] tags, boolean isSaasApp, int validityPeriod) throws KeyMgtException; String[] tags, boolean isSaasApp, int validityPeriod, String password,
List<String> supportedGrantTypes, String callbackUrl) throws KeyMgtException;
/*** /***
* This method will handle the access token requests * This method will handle the access token requests

View File

@ -19,6 +19,17 @@
package io.entgra.device.mgt.core.apimgt.keymgt.extension.service; package io.entgra.device.mgt.core.apimgt.keymgt.extension.service;
import com.google.gson.Gson; import com.google.gson.Gson;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.ConsumerRESTAPIServices;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.ApiApplicationInfo;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.APIServicesException;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.UnexpectedResponseException;
import io.entgra.device.mgt.core.apimgt.keymgt.extension.*;
import io.entgra.device.mgt.core.apimgt.keymgt.extension.exception.BadRequestException;
import io.entgra.device.mgt.core.apimgt.keymgt.extension.exception.KeyMgtException;
import io.entgra.device.mgt.core.apimgt.keymgt.extension.internal.KeyMgtDataHolder;
import io.entgra.device.mgt.core.device.mgt.core.config.DeviceConfigurationManager;
import io.entgra.device.mgt.core.device.mgt.core.config.DeviceManagementConfig;
import io.entgra.device.mgt.core.device.mgt.core.config.keymanager.KeyManagerConfigurations;
import okhttp3.Credentials; import okhttp3.Credentials;
import okhttp3.FormBody; import okhttp3.FormBody;
import okhttp3.MediaType; import okhttp3.MediaType;
@ -29,23 +40,10 @@ import okhttp3.Response;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.json.JSONObject; import org.json.JSONObject;
import org.wso2.carbon.apimgt.api.APIConsumer;
import org.wso2.carbon.apimgt.api.APIManagementException; import org.wso2.carbon.apimgt.api.APIManagementException;
import org.wso2.carbon.apimgt.api.model.Application; import org.wso2.carbon.apimgt.api.model.Application;
import org.wso2.carbon.apimgt.impl.APIManagerFactory;
import org.wso2.carbon.apimgt.impl.utils.APIUtil; import org.wso2.carbon.apimgt.impl.utils.APIUtil;
import io.entgra.device.mgt.core.apimgt.keymgt.extension.DCRResponse;
import io.entgra.device.mgt.core.apimgt.keymgt.extension.KeyManagerPayload;
import io.entgra.device.mgt.core.apimgt.keymgt.extension.KeyMgtConstants;
import io.entgra.device.mgt.core.apimgt.keymgt.extension.OAuthApplication;
import io.entgra.device.mgt.core.apimgt.keymgt.extension.TokenRequest;
import io.entgra.device.mgt.core.apimgt.keymgt.extension.TokenResponse;
import io.entgra.device.mgt.core.apimgt.keymgt.extension.exception.BadRequestException;
import io.entgra.device.mgt.core.apimgt.keymgt.extension.exception.KeyMgtException;
import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext;
import io.entgra.device.mgt.core.device.mgt.core.config.DeviceConfigurationManager;
import io.entgra.device.mgt.core.device.mgt.core.config.DeviceManagementConfig;
import io.entgra.device.mgt.core.device.mgt.core.config.keymanager.KeyManagerConfigurations;
import org.wso2.carbon.user.api.UserRealm; import org.wso2.carbon.user.api.UserRealm;
import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.user.api.UserStoreManager; import org.wso2.carbon.user.api.UserStoreManager;
@ -77,7 +75,8 @@ public class KeyMgtServiceImpl implements KeyMgtService {
String subTenantUserUsername, subTenantUserPassword, keyManagerName, msg = null; String subTenantUserUsername, subTenantUserPassword, keyManagerName, msg = null;
public DCRResponse dynamicClientRegistration(String clientName, String owner, String grantTypes, String callBackUrl, public DCRResponse dynamicClientRegistration(String clientName, String owner, String grantTypes, String callBackUrl,
String[] tags, boolean isSaasApp, int validityPeriod) throws KeyMgtException { String[] tags, boolean isSaasApp, int validityPeriod,
String password, List<String> supportedGrantTypes, String callbackUrl) throws KeyMgtException {
if (owner == null) { if (owner == null) {
PrivilegedCarbonContext threadLocalCarbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext(); PrivilegedCarbonContext threadLocalCarbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
@ -98,20 +97,21 @@ public class KeyMgtServiceImpl implements KeyMgtService {
.getTenantManager().getTenantId(tenantDomain); .getTenantManager().getTenantId(tenantDomain);
} catch (UserStoreException e) { } catch (UserStoreException e) {
msg = "Error while loading tenant configuration"; msg = "Error while loading tenant configuration";
log.error(msg); log.error(msg, e);
throw new KeyMgtException(msg); throw new KeyMgtException(msg, e);
} }
kmConfig = getKeyManagerConfig(); kmConfig = getKeyManagerConfig();
if (KeyMgtConstants.SUPER_TENANT.equals(tenantDomain)) { if (KeyMgtConstants.SUPER_TENANT.equals(tenantDomain)) {
OAuthApplication dcrApplication = createOauthApplication(clientName, kmConfig.getAdminUsername(), tags, validityPeriod); OAuthApplication dcrApplication = createOauthApplication(clientName, kmConfig.getAdminUsername(), tags,
validityPeriod, kmConfig.getAdminPassword(), supportedGrantTypes, callbackUrl);
return new DCRResponse(dcrApplication.getClientId(), dcrApplication.getClientSecret()); return new DCRResponse(dcrApplication.getClientId(), dcrApplication.getClientSecret());
} else { } else {
// super-tenant admin dcr and token generation // super-tenant admin dcr and token generation
OAuthApplication superTenantOauthApp = createOauthApplication( OAuthApplication superTenantOauthApp = createOauthApplication(
KeyMgtConstants.RESERVED_OAUTH_APP_NAME_PREFIX + KeyMgtConstants.SUPER_TENANT, KeyMgtConstants.RESERVED_OAUTH_APP_NAME_PREFIX + KeyMgtConstants.SUPER_TENANT,
kmConfig.getAdminUsername(), null, validityPeriod); kmConfig.getAdminUsername(), null, validityPeriod, kmConfig.getAdminPassword(), null, null);
String superAdminAccessToken = createAccessToken(superTenantOauthApp); String superAdminAccessToken = createAccessToken(superTenantOauthApp);
// create new key manager for the tenant, under super-tenant space // create new key manager for the tenant, under super-tenant space
@ -127,18 +127,20 @@ public class KeyMgtServiceImpl implements KeyMgtService {
.getRealmProperty("reserved_tenant_user_password"); .getRealmProperty("reserved_tenant_user_password");
} catch (UserStoreException e) { } catch (UserStoreException e) {
msg = "Error while loading user realm configuration"; msg = "Error while loading user realm configuration";
log.error(msg); log.error(msg, e);
throw new KeyMgtException(msg); throw new KeyMgtException(msg, e);
} }
createUserIfNotExists(subTenantUserUsername, subTenantUserPassword); createUserIfNotExists(subTenantUserUsername, subTenantUserPassword);
// DCR for the requesting user // DCR for the requesting user
OAuthApplication dcrApplication = createOauthApplication(clientName, owner, tags, validityPeriod); OAuthApplication dcrApplication = createOauthApplication(clientName, owner, tags, validityPeriod,
password, null, null);
String requestingUserAccessToken = createAccessToken(dcrApplication); String requestingUserAccessToken = createAccessToken(dcrApplication);
// get application id // get application id
Application application = getApplication(clientName, owner); io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer.Application application =
String applicationUUID = application.getUUID(); getApplication(clientName, requestingUserAccessToken);
String applicationUUID = application.getApplicationId();
// do app key mapping // do app key mapping
mapApplicationKeys(dcrApplication.getClientId(), dcrApplication.getClientSecret(), keyManagerName, mapApplicationKeys(dcrApplication.getClientId(), dcrApplication.getClientSecret(), keyManagerName,
@ -238,16 +240,16 @@ public class KeyMgtServiceImpl implements KeyMgtService {
} }
} catch (APIManagementException e) { } catch (APIManagementException e) {
msg = "Error occurred while retrieving application"; msg = "Error occurred while retrieving application";
log.error(msg); log.error(msg, e);
throw new KeyMgtException(msg); throw new KeyMgtException(msg, e);
} catch (IOException e) { } catch (IOException e) {
msg = "Error occurred while mapping application keys"; msg = "Error occurred while mapping application keys";
log.error(msg); log.error(msg, e);
throw new KeyMgtException(msg); throw new KeyMgtException(msg, e);
} catch (UserStoreException e) { } catch (UserStoreException e) {
msg = "Error occurred while fetching tenant id"; msg = "Error occurred while fetching tenant id";
log.error(msg); log.error(msg, e);
throw new KeyMgtException(msg); throw new KeyMgtException(msg, e);
} }
} }
@ -284,7 +286,8 @@ public class KeyMgtServiceImpl implements KeyMgtService {
client.newCall(request).execute(); client.newCall(request).execute();
} catch (IOException e) { } catch (IOException e) {
msg = "Error occurred while mapping application keys"; msg = "Error occurred while mapping application keys";
throw new KeyMgtException(msg); log.error(msg, e);
throw new KeyMgtException(msg, e);
} }
} }
@ -310,8 +313,8 @@ public class KeyMgtServiceImpl implements KeyMgtService {
} }
} catch (UserStoreException e) { } catch (UserStoreException e) {
msg = "Error when trying to fetch tenant details"; msg = "Error when trying to fetch tenant details";
log.error(msg); log.error(msg, e);
throw new KeyMgtException(msg); throw new KeyMgtException(msg, e);
} }
} }
@ -323,8 +326,11 @@ public class KeyMgtServiceImpl implements KeyMgtService {
* @return @{@link OAuthApplication} OAuth application object * @return @{@link OAuthApplication} OAuth application object
* @throws KeyMgtException if any error occurs while creating response object * @throws KeyMgtException if any error occurs while creating response object
*/ */
private OAuthApplication createOauthApplication (String clientName, String owner, String[] tags, int validityPeriod) throws KeyMgtException { private OAuthApplication createOauthApplication (String clientName, String owner, String[] tags,
String oauthAppCreationPayloadStr = createOauthAppCreationPayload(clientName, owner, tags, validityPeriod); int validityPeriod, String ownerPassword,
List<String> supportedGrantTypes, String callbackUrl) throws KeyMgtException {
String oauthAppCreationPayloadStr = createOauthAppCreationPayload(clientName, owner, tags, validityPeriod,
ownerPassword, supportedGrantTypes, callbackUrl);
RequestBody oauthAppCreationPayload = RequestBody.Companion.create(oauthAppCreationPayloadStr, JSON); RequestBody oauthAppCreationPayload = RequestBody.Companion.create(oauthAppCreationPayloadStr, JSON);
kmConfig = getKeyManagerConfig(); kmConfig = getKeyManagerConfig();
String dcrEndpoint = kmConfig.getServerUrl() + KeyMgtConstants.DCR_ENDPOINT; String dcrEndpoint = kmConfig.getServerUrl() + KeyMgtConstants.DCR_ENDPOINT;
@ -347,8 +353,9 @@ public class KeyMgtServiceImpl implements KeyMgtService {
Response response = client.newCall(request).execute(); Response response = client.newCall(request).execute();
return gson.fromJson(response.body().string(), OAuthApplication.class); return gson.fromJson(response.body().string(), OAuthApplication.class);
} catch (IOException e) { } catch (IOException e) {
msg = "Error occurred while processing the response"; msg = "Error occurred while processing the response." ;
throw new KeyMgtException(msg); log.error(msg, e);
throw new KeyMgtException(msg, e);
} }
} }
@ -379,7 +386,8 @@ public class KeyMgtServiceImpl implements KeyMgtService {
return jsonObject.getString("access_token"); return jsonObject.getString("access_token");
} catch (IOException e) { } catch (IOException e) {
msg = "Error occurred while reading access token from response"; msg = "Error occurred while reading access token from response";
throw new KeyMgtException(msg); log.error(msg, e);
throw new KeyMgtException(msg, e);
} }
} }
@ -418,8 +426,8 @@ public class KeyMgtServiceImpl implements KeyMgtService {
client.newCall(request).execute(); client.newCall(request).execute();
} catch (IOException e) { } catch (IOException e) {
msg = "Error occurred while invoking create key manager endpoint"; msg = "Error occurred while invoking create key manager endpoint";
log.error(msg); log.error(msg, e);
throw new KeyMgtException(msg); throw new KeyMgtException(msg, e);
} }
} }
@ -427,28 +435,52 @@ public class KeyMgtServiceImpl implements KeyMgtService {
* Retrieves an application by name and owner * Retrieves an application by name and owner
* *
* @param applicationName name of the application * @param applicationName name of the application
* @param owner owner of the application * @param accessToken Access Token
* @return @{@link Application} Application object * @return @{@link Application} Application object
* @throws KeyMgtException if any error occurs while retrieving the application * @throws KeyMgtException if any error occurs while retrieving the application
*/ */
private Application getApplication(String applicationName, String owner) throws KeyMgtException { private io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer.Application getApplication(String applicationName, String accessToken) throws KeyMgtException {
ApiApplicationInfo apiApplicationInfo = new ApiApplicationInfo();
apiApplicationInfo.setAccess_token(accessToken);
try { try {
APIManagerFactory apiManagerFactory = APIManagerFactory.getInstance(); ConsumerRESTAPIServices consumerRESTAPIServices =
APIConsumer apiConsumer = apiManagerFactory.getAPIConsumer(owner); KeyMgtDataHolder.getInstance().getConsumerRESTAPIServices();
return apiConsumer.getApplicationsByName(owner, applicationName, ""); io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer.Application[] applications =
} catch (APIManagementException e) { consumerRESTAPIServices.getAllApplications(apiApplicationInfo, applicationName);
if (applications.length == 1) {
return applications[0];
} else {
String msg =
"Found invalid number of applications. No of applications found from the APIM: " + applications.length;
log.error(msg);
throw new KeyMgtException(msg);
}
} catch (io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.BadRequestException e) {
msg = "Error while trying to retrieve the application"; msg = "Error while trying to retrieve the application";
log.error(msg); log.error(msg, e);
throw new KeyMgtException(msg); throw new KeyMgtException(msg, e);
} catch (UnexpectedResponseException e) {
msg = "Received invalid response for the API applications retrieving REST API call.";
log.error(msg, e);
throw new KeyMgtException(msg, e);
} catch (APIServicesException e) {
msg = "Error occurred while processing the API Response.";
log.error(msg, e);
throw new KeyMgtException(msg, e);
} }
} }
private String createOauthAppCreationPayload(String clientName, String owner, String[] tags, int validityPeriod) { private String createOauthAppCreationPayload(String clientName, String owner, String[] tags, int validityPeriod,
String password, List<String> supportedGrantTypes, String callbackUrl) {
JSONObject jsonObject = new JSONObject(); JSONObject jsonObject = new JSONObject();
jsonObject.put("applicationName", clientName); jsonObject.put("applicationName", clientName);
jsonObject.put("username", owner); jsonObject.put("username", owner);
jsonObject.put("tags", tags); jsonObject.put("tags", tags);
jsonObject.put("validityPeriod", validityPeriod); jsonObject.put("validityPeriod", validityPeriod);
jsonObject.put("password", password);
jsonObject.put("supportedGrantTypes", supportedGrantTypes);
jsonObject.put("callbackUrl", callbackUrl);
return jsonObject.toString(); return jsonObject.toString();
} }

View File

@ -22,41 +22,43 @@
<parent> <parent>
<artifactId>apimgt-extensions</artifactId> <artifactId>apimgt-extensions</artifactId>
<groupId>io.entgra.device.mgt.core</groupId> <groupId>io.entgra.device.mgt.core</groupId>
<version>5.1.0</version> <version>6.0.1-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>io.entgra.device.mgt.core.apimgt.webapp.publisher</artifactId> <artifactId>io.entgra.device.mgt.core.apimgt.webapp.publisher</artifactId>
<packaging>bundle</packaging> <packaging>bundle</packaging>
<name>WSO2 Carbon - API Management Webapp Publisher</name> <name>Entgra Device Management - API Management Webapp Publisher</name>
<description>WSO2 Carbon - API Management Webapp Publisher</description> <description>Entgra Device Management - API Management Webapp Publisher</description>
<url>http://wso2.org</url> <url>https://entgra.io</url>
<dependencies> <dependencies>
<dependency>
<groupId>org.apache.felix</groupId>
<artifactId>org.apache.felix.scr.ds-annotations</artifactId>
<scope>provided</scope>
</dependency>
<dependency> <dependency>
<groupId>org.powermock</groupId> <groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito</artifactId> <artifactId>powermock-api-mockito2</artifactId>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.eclipse.osgi</groupId> <groupId>org.mockito</groupId>
<artifactId>org.eclipse.osgi</artifactId> <artifactId>mockito-core</artifactId>
</dependency> <scope>test</scope>
<dependency>
<groupId>org.eclipse.osgi</groupId>
<artifactId>org.eclipse.osgi.services</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.testng</groupId> <groupId>org.testng</groupId>
<artifactId>testng</artifactId> <artifactId>testng</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.wso2.tomcat</groupId> <groupId>org.wso2.orbit.org.apache.tomcat</groupId>
<artifactId>tomcat</artifactId> <artifactId>tomcat</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.wso2.tomcat</groupId> <groupId>org.wso2.orbit.org.apache.tomcat</groupId>
<artifactId>tomcat-servlet-api</artifactId> <artifactId>tomcat-servlet-api</artifactId>
</dependency> </dependency>
<dependency> <dependency>
@ -64,8 +66,9 @@
<artifactId>org.wso2.carbon.core</artifactId> <artifactId>org.wso2.carbon.core</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.wso2.carbon</groupId> <groupId>org.ops4j.pax.logging</groupId>
<artifactId>org.wso2.carbon.logging</artifactId> <artifactId>pax-logging-api</artifactId>
<scope>provided</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.wso2.carbon</groupId> <groupId>org.wso2.carbon</groupId>
@ -80,7 +83,7 @@
<artifactId>gson</artifactId> <artifactId>gson</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.wso2.orbit.org.scannotation</groupId> <groupId>io.entgra.org.scannotation</groupId>
<artifactId>scannotation</artifactId> <artifactId>scannotation</artifactId>
</dependency> </dependency>
<dependency> <dependency>
@ -118,8 +121,8 @@
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.h2database.wso2</groupId> <groupId>org.wso2.orbit.com.h2database</groupId>
<artifactId>h2-database-engine</artifactId> <artifactId>h2</artifactId>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency> <dependency>
@ -134,19 +137,19 @@
<groupId>io.entgra.device.mgt.core</groupId> <groupId>io.entgra.device.mgt.core</groupId>
<artifactId>io.entgra.device.mgt.core.device.mgt.core</artifactId> <artifactId>io.entgra.device.mgt.core.device.mgt.core</artifactId>
</dependency> </dependency>
<dependency>
<groupId>org.wso2.orbit.javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<scope>provided</scope>
</dependency>
</dependencies> </dependencies>
<build> <build>
<plugins> <plugins>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-scr-plugin</artifactId>
</plugin>
<plugin> <plugin>
<groupId>org.apache.felix</groupId> <groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId> <artifactId>maven-bundle-plugin</artifactId>
<version>1.4.0</version>
<extensions>true</extensions> <extensions>true</extensions>
<configuration> <configuration>
<instructions> <instructions>
@ -161,53 +164,45 @@
io.entgra.device.mgt.core.apimgt.webapp.publisher.* io.entgra.device.mgt.core.apimgt.webapp.publisher.*
</Export-Package> </Export-Package>
<Import-Package> <Import-Package>
com.google.gson;version="[2.3,2.8.6)", com.google.gson;version="[2.9,3)",
com.google.gson.reflect;version="[2.3,2.8.6)", com.google.gson.reflect;version="[2.9,3)",
io.swagger.annotations, io.entgra.device.mgt.core.apimgt.annotations;version="${io.entgra.device.mgt.core.version.range}",
javax.servlet;version="2.6",
javax.xml,
javax.xml.bind,
javax.xml.bind.annotation,
javax.xml.parsers,
org.apache.catalina;version="9.0",
org.apache.catalina.core;version="9.0",
org.apache.commons.logging;version="1.2",
org.osgi.framework.*;version="${imp.package.version.osgi.framework}",
org.osgi.service.*;version="${imp.package.version.osgi.service}",
org.scannotation;version="1.0",
org.scannotation.archiveiterator;version="1.0",
org.w3c.dom,
io.entgra.device.mgt.core.apimgt.extension.rest.api.*, io.entgra.device.mgt.core.apimgt.extension.rest.api.*,
io.entgra.device.mgt.core.apimgt.annotations,
org.wso2.carbon.apimgt.api,
org.wso2.carbon.apimgt.api.model,
org.wso2.carbon.apimgt.impl,
org.wso2.carbon.apimgt.impl.utils,
io.entgra.device.mgt.core.apimgt.webapp.publisher,
io.entgra.device.mgt.core.apimgt.webapp.publisher.config, io.entgra.device.mgt.core.apimgt.webapp.publisher.config,
io.entgra.device.mgt.core.apimgt.webapp.publisher.dto, io.entgra.device.mgt.core.apimgt.webapp.publisher.dto,
io.entgra.device.mgt.core.apimgt.webapp.publisher.exception, io.entgra.device.mgt.core.apimgt.webapp.publisher.exception,
io.entgra.device.mgt.core.apimgt.webapp.publisher.lifecycle.listener,
io.entgra.device.mgt.core.apimgt.webapp.publisher.lifecycle.util,
io.entgra.device.mgt.core.device.mgt.common.exceptions, io.entgra.device.mgt.core.device.mgt.common.exceptions,
io.entgra.device.mgt.core.device.mgt.common.permission.mgt,
io.entgra.device.mgt.core.device.mgt.common.metadata.mgt, io.entgra.device.mgt.core.device.mgt.common.metadata.mgt,
io.entgra.device.mgt.core.device.mgt.core.config, io.entgra.device.mgt.core.device.mgt.core.config,
io.entgra.device.mgt.core.device.mgt.core.config.permission, io.entgra.device.mgt.core.device.mgt.core.config.permission,
org.wso2.carbon.base;version="1.0", io.swagger.annotations;version="[1.6,2)",
org.wso2.carbon.context;version="4.6", javax.servlet;version="[2.6,3)",
org.wso2.carbon;version="4.6", javax.xml.bind;version="[0.0,1)",
org.wso2.carbon.core;version="4.6", javax.xml.bind.annotation;version="[0.0,1)",
org.wso2.carbon.core.util;version="4.6", javax.xml.parsers;version="${javax.xml.parsers.import.pkg.version}",
org.wso2.carbon.registry.core.service;version="1.0", org.apache.catalina;version="${catalina.version.range}",
org.wso2.carbon.user.api;version="1.0", org.apache.catalina.core;version="${catalina.version.range}",
org.wso2.carbon.user.core.service;version="4.6", org.apache.commons.lang;version="[2.6,3)",
org.wso2.carbon.user.core.tenant;version="4.6", org.apache.commons.logging;version="[1.2,2)",
org.wso2.carbon.utils;version="4.6", org.json;version="[3.0,4)",
org.wso2.carbon.utils.multitenancy;version="4.6", org.osgi.framework.*;version="${imp.package.version.osgi.framework}",
org.apache.commons.lang, org.osgi.service.*;version="${imp.package.version.osgi.service}",
org.json, org.scannotation;version="[1.0,2)",
io.entgra.device.mgt.core.device.mgt.common.permission.mgt, org.scannotation.archiveiterator;version="[1.0,2)",
io.entgra.device.mgt.core.device.mgt.core.permission.mgt org.w3c.dom,
org.wso2.carbon.apimgt.api;version="[9.28,10)",
org.wso2.carbon.apimgt.api.model;version="[9.28,10)",
org.wso2.carbon.apimgt.impl;version="[9.28,10)",
org.wso2.carbon.apimgt.impl.utils;version="[9.28,10)",
org.wso2.carbon.context;version="[4.8,5)",
org.wso2.carbon.core;version="[4.8,5)",
org.wso2.carbon.core.util;version="[4.8,5)",
org.wso2.carbon.registry.core.service,
org.wso2.carbon.user.api,
org.wso2.carbon.user.core.service;version="[4.8,5)",
org.wso2.carbon.user.core.tenant;version="[4.8,5)",
org.wso2.carbon.utils;version="[4.8,5)"
</Import-Package> </Import-Package>
<Embed-Dependency> <Embed-Dependency>
jsr311-api;scope=compile|runtime;inline=false jsr311-api;scope=compile|runtime;inline=false

View File

@ -68,8 +68,6 @@ import org.wso2.carbon.user.core.tenant.Tenant;
import org.wso2.carbon.user.core.tenant.TenantSearchResult; import org.wso2.carbon.user.core.tenant.TenantSearchResult;
import org.wso2.carbon.utils.CarbonUtils; import org.wso2.carbon.utils.CarbonUtils;
import org.wso2.carbon.utils.multitenancy.MultitenantConstants; import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
import io.entgra.device.mgt.core.device.mgt.core.permission.mgt.PermissionUtils;
import io.entgra.device.mgt.core.device.mgt.common.permission.mgt.PermissionManagementException; import io.entgra.device.mgt.core.device.mgt.common.permission.mgt.PermissionManagementException;
import java.io.BufferedReader; import java.io.BufferedReader;
@ -82,13 +80,12 @@ import java.nio.file.Paths;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
import java.util.Date;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.Date;
/** /**
* This class represents the concrete implementation of the APIPublisherService that corresponds to providing all * This class represents the concrete implementation of the APIPublisherService that corresponds to providing all
@ -158,7 +155,9 @@ public class APIPublisherServiceImpl implements APIPublisherService {
try { try {
APIPublisherUtils.createScopePublishUserIfNotExists(tenantDomain); APIPublisherUtils.createScopePublishUserIfNotExists(tenantDomain);
apiApplicationKey = apiApplicationServices.createAndRetrieveApplicationCredentials(); apiApplicationKey = apiApplicationServices.createAndRetrieveApplicationCredentials(
"ClientForPublisherRestCalls",
"client_credentials password refresh_token");
accessTokenInfo = apiApplicationServices.generateAccessTokenFromRegisteredApplication( accessTokenInfo = apiApplicationServices.generateAccessTokenFromRegisteredApplication(
apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret());
} catch (APIServicesException e) { } catch (APIServicesException e) {
@ -188,19 +187,8 @@ public class APIPublisherServiceImpl implements APIPublisherService {
String apiUuid = apiIdentifier.getUUID(); String apiUuid = apiIdentifier.getUUID();
if (!apiFound) { if (!apiFound) {
// add new scopes as shared scopes // add new scopes as shared scopes
for (ApiScope apiScope : apiConfig.getScopes()) { addNewSharedScope(apiConfig.getScopes(), publisherRESTAPIServices, apiApplicationKey,
if (!publisherRESTAPIServices.isSharedScopeNameExists(apiApplicationKey, accessTokenInfo, accessTokenInfo);
apiScope.getKey())) {
Scope scope = new Scope();
scope.setDisplayName(apiScope.getName());
scope.setDescription(apiScope.getDescription());
scope.setName(apiScope.getKey());
List<String> bindings = new ArrayList<>(apiScope.getRoles());
bindings.add(ADMIN_ROLE_KEY);
scope.setBindings(bindings);
publisherRESTAPIServices.addNewSharedScope(apiApplicationKey, accessTokenInfo, scope);
}
}
APIInfo api = getAPI(apiConfig, true); APIInfo api = getAPI(apiConfig, true);
APIInfo createdAPI = publisherRESTAPIServices.addAPI(apiApplicationKey, accessTokenInfo, api); APIInfo createdAPI = publisherRESTAPIServices.addAPI(apiApplicationKey, accessTokenInfo, api);
apiUuid = createdAPI.getId(); apiUuid = createdAPI.getId();
@ -240,7 +228,6 @@ public class APIPublisherServiceImpl implements APIPublisherService {
} }
} else { } else {
if (WebappPublisherConfig.getInstance().isEnabledUpdateApi()) { if (WebappPublisherConfig.getInstance().isEnabledUpdateApi()) {
// With 4.x to 5.x upgrade // With 4.x to 5.x upgrade
// - there cannot be same local scope assigned in 2 different APIs // - there cannot be same local scope assigned in 2 different APIs
// - local scopes will be deprecated in the future, so need to move all scopes as shared scopes // - local scopes will be deprecated in the future, so need to move all scopes as shared scopes
@ -255,52 +242,18 @@ public class APIPublisherServiceImpl implements APIPublisherService {
// 1. add new scopes as shared scopes // 1. add new scopes as shared scopes
// 2. update the API adding scopes for the URI Templates // 2. update the API adding scopes for the URI Templates
Set<ApiScope> scopesToMoveAsSharedScopes = new HashSet<>(); // It is guaranteed that there is no local scope if we update from 5.0.0 to the most
for (ApiScope apiScope : apiConfig.getScopes()) { // recent version. Therefore, if the scope is not already available as a shared scope,
// if the scope is not available as shared scope, and it is assigned to an API as a local scope // new scopes must be added as shared scopes. Additionally, it is necessary to
// need remove the local scope and add as a shared scope // upgrade to 5.0.0 first before updating from 5.0.0 to the most recent version if we
if (!publisherRESTAPIServices.isSharedScopeNameExists(apiApplicationKey, accessTokenInfo, // are updating from a version that is older than 5.0.0.
apiScope.getKey())) {
if (apiProvider.isScopeKeyAssignedLocally(apiIdentifier, apiScope.getKey(), tenantId)) {
// collect scope to move as shared scopes
scopesToMoveAsSharedScopes.add(apiScope);
} else {
// if new scope add as shared scope
Scope scope = new Scope();
scope.setName(apiScope.getKey());
scope.setDescription(apiScope.getDescription());
scope.setDisplayName(apiScope.getName());
List<String> bindings = new ArrayList<>(apiScope.getRoles());
bindings.add(ADMIN_ROLE_KEY);
scope.setBindings(bindings);
publisherRESTAPIServices.addNewSharedScope(apiApplicationKey, accessTokenInfo, scope);
} addNewSharedScope(apiConfig.getScopes(), publisherRESTAPIServices, apiApplicationKey,
} accessTokenInfo);
}
// Get existing API // Get existing API
APIInfo existingAPI = publisherRESTAPIServices.getApi(apiApplicationKey, accessTokenInfo, APIInfo existingAPI = publisherRESTAPIServices.getApi(apiApplicationKey, accessTokenInfo,
apiUuid); apiUuid);
if (scopesToMoveAsSharedScopes.size() > 0) {
// update API to remove local scopes
APIInfo api = getAPI(apiConfig, false);
api.setLifeCycleStatus(existingAPI.getLifeCycleStatus());
publisherRESTAPIServices.updateApi(apiApplicationKey, accessTokenInfo, api);
for (ApiScope apiScope : scopesToMoveAsSharedScopes) {
Scope scope = new Scope();
scope.setName(apiScope.getKey());
scope.setDescription(apiScope.getDescription());
scope.setDisplayName(apiScope.getName());
List<String> bindings = new ArrayList<>(apiScope.getRoles());
bindings.add(ADMIN_ROLE_KEY);
scope.setBindings(bindings);
publisherRESTAPIServices.addNewSharedScope(apiApplicationKey, accessTokenInfo, scope);
}
}
existingAPI = publisherRESTAPIServices.getApi(apiApplicationKey, accessTokenInfo, apiUuid);
APIInfo api = getAPI(apiConfig, true); APIInfo api = getAPI(apiConfig, true);
api.setLifeCycleStatus(existingAPI.getLifeCycleStatus()); api.setLifeCycleStatus(existingAPI.getLifeCycleStatus());
api.setId(apiUuid); api.setId(apiUuid);
@ -453,6 +406,34 @@ public class APIPublisherServiceImpl implements APIPublisherService {
} }
} }
/**
* Add new Shared Scopes
*
* @param apiScopes set of API scopes
* @param publisherRESTAPIServices {@link PublisherRESTAPIServices}
* @param apiApplicationKey API application Key
* @param accessTokenInfo Details of access token
* @throws BadRequestException if invalid payload receives to add new shared scopes.
* @throws UnexpectedResponseException if the response is not either 200 or 400.
* @throws APIServicesException if error occurred while processing the response.
*/
private void addNewSharedScope(Set<ApiScope> apiScopes, PublisherRESTAPIServices publisherRESTAPIServices,
APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo) throws BadRequestException, UnexpectedResponseException, APIServicesException {
for (ApiScope apiScope : apiScopes) {
if (!publisherRESTAPIServices.isSharedScopeNameExists(apiApplicationKey, accessTokenInfo,
apiScope.getKey())) {
Scope scope = new Scope();
scope.setName(apiScope.getKey());
scope.setDescription(apiScope.getDescription());
scope.setDisplayName(apiScope.getName());
List<String> bindings = new ArrayList<>(apiScope.getRoles());
bindings.add(ADMIN_ROLE_KEY);
scope.setBindings(bindings);
publisherRESTAPIServices.addNewSharedScope(apiApplicationKey, accessTokenInfo, scope);
}
}
}
@Override @Override
public void addDefaultScopesIfNotExist() throws APIManagerPublisherException { public void addDefaultScopesIfNotExist() throws APIManagerPublisherException {
WebappPublisherConfig config = WebappPublisherConfig.getInstance(); WebappPublisherConfig config = WebappPublisherConfig.getInstance();
@ -471,7 +452,9 @@ public class APIPublisherServiceImpl implements APIPublisherService {
APIPublisherUtils.createScopePublishUserIfNotExists(tenantDomain); APIPublisherUtils.createScopePublishUserIfNotExists(tenantDomain);
APIApplicationKey apiApplicationKey = APIApplicationKey apiApplicationKey =
apiApplicationServices.createAndRetrieveApplicationCredentials(); apiApplicationServices.createAndRetrieveApplicationCredentials(
"ClientForPublisherRestCalls", "client_credentials password refresh_token"
);
AccessTokenInfo accessTokenInfo = AccessTokenInfo accessTokenInfo =
apiApplicationServices.generateAccessTokenFromRegisteredApplication( apiApplicationServices.generateAccessTokenFromRegisteredApplication(
apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret());
@ -526,7 +509,8 @@ public class APIPublisherServiceImpl implements APIPublisherService {
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true); PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
try { try {
APIPublisherUtils.createScopePublishUserIfNotExists(tenantDomain); APIPublisherUtils.createScopePublishUserIfNotExists(tenantDomain);
apiApplicationKey = apiApplicationServices.createAndRetrieveApplicationCredentials(); apiApplicationKey = apiApplicationServices.createAndRetrieveApplicationCredentials("ClientForPublisherRestCalls",
"client_credentials password refresh_token");
accessTokenInfo = apiApplicationServices.generateAccessTokenFromRegisteredApplication( accessTokenInfo = apiApplicationServices.generateAccessTokenFromRegisteredApplication(
apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret());
} catch (APIServicesException e) { } catch (APIServicesException e) {
@ -621,7 +605,7 @@ public class APIPublisherServiceImpl implements APIPublisherService {
// add permission if not exist // add permission if not exist
try { try {
PermissionUtils.putPermission(permission); PermissionUtils.putPermission(permission);
} catch(PermissionManagementException e) { } catch (PermissionManagementException e) {
log.error("Error when adding permission ", e); log.error("Error when adding permission ", e);
} }
} }
@ -667,7 +651,10 @@ public class APIPublisherServiceImpl implements APIPublisherService {
AccessTokenInfo accessTokenInfo; AccessTokenInfo accessTokenInfo;
try { try {
APIPublisherUtils.createScopePublishUserIfNotExists(tenantDomain); APIPublisherUtils.createScopePublishUserIfNotExists(tenantDomain);
apiApplicationKey = apiApplicationServices.createAndRetrieveApplicationCredentials(); apiApplicationKey = apiApplicationServices.createAndRetrieveApplicationCredentials(
"ClientForPublisherRestCalls",
"client_credentials password refresh_token"
);
accessTokenInfo = apiApplicationServices.generateAccessTokenFromRegisteredApplication( accessTokenInfo = apiApplicationServices.generateAccessTokenFromRegisteredApplication(
apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret());
} catch (APIServicesException e) { } catch (APIServicesException e) {
@ -853,7 +840,9 @@ public class APIPublisherServiceImpl implements APIPublisherService {
scope.setName(apiUriTemplate.getScope().getKey()); scope.setName(apiUriTemplate.getScope().getKey());
scope.setDisplayName(apiUriTemplate.getScope().getName()); scope.setDisplayName(apiUriTemplate.getScope().getName());
scope.setDescription(apiUriTemplate.getScope().getDescription()); scope.setDescription(apiUriTemplate.getScope().getDescription());
scope.setBindings(apiUriTemplate.getScope().getRoles()); List<String> bindings = new ArrayList<>(apiUriTemplate.getScope().getRoles());
bindings.add(ADMIN_ROLE_KEY);
scope.setBindings(bindings);
JSONObject scopeObject = new JSONObject(); JSONObject scopeObject = new JSONObject();
scopeObject.put("scope", new JSONObject(gson.toJson(scope))); scopeObject.put("scope", new JSONObject(gson.toJson(scope)));

View File

@ -18,23 +18,40 @@
package io.entgra.device.mgt.core.apimgt.webapp.publisher; package io.entgra.device.mgt.core.apimgt.webapp.publisher;
import org.apache.commons.logging.Log; import com.google.gson.Gson;
import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.apimgt.extension.rest.api.constants.Constants;
import io.entgra.device.mgt.core.apimgt.webapp.publisher.dto.ApiScope;
import io.entgra.device.mgt.core.apimgt.webapp.publisher.exception.APIManagerPublisherException; import io.entgra.device.mgt.core.apimgt.webapp.publisher.exception.APIManagerPublisherException;
import io.entgra.device.mgt.core.apimgt.webapp.publisher.internal.APIPublisherDataHolder; import io.entgra.device.mgt.core.apimgt.webapp.publisher.internal.APIPublisherDataHolder;
import io.entgra.device.mgt.core.device.mgt.common.exceptions.MetadataKeyAlreadyExistsException;
import io.entgra.device.mgt.core.device.mgt.common.exceptions.MetadataManagementException;
import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.Metadata;
import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.MetadataManagementService;
import io.entgra.device.mgt.core.device.mgt.core.config.DeviceConfigurationManager;
import io.entgra.device.mgt.core.device.mgt.core.config.DeviceManagementConfig;
import io.entgra.device.mgt.core.device.mgt.core.config.permission.DefaultPermission;
import io.entgra.device.mgt.core.device.mgt.core.config.permission.DefaultPermissions;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.core.ServerStartupObserver; import org.wso2.carbon.core.ServerStartupObserver;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Stack; import java.util.Stack;
public class APIPublisherStartupHandler implements ServerStartupObserver { public class APIPublisherStartupHandler implements ServerStartupObserver {
private static final Log log = LogFactory.getLog(APIPublisherStartupHandler.class); private static final Log log = LogFactory.getLog(APIPublisherStartupHandler.class);
private static int retryTime = 2000;
private static final int CONNECTION_RETRY_FACTOR = 2; private static final int CONNECTION_RETRY_FACTOR = 2;
private static final int MAX_RETRY_COUNT = 5; private static final int MAX_RETRY_COUNT = 5;
private static Stack<APIConfig> failedAPIsStack = new Stack<>(); private static final Gson gson = new Gson();
private static final Stack<APIConfig> failedAPIsStack = new Stack<>();
private static int retryTime = 2000;
private static Stack<APIConfig> currentAPIsStack; private static Stack<APIConfig> currentAPIsStack;
private final List<String> publishedAPIs = new ArrayList<>();
private APIPublisherService publisher; private APIPublisherService publisher;
@Override @Override
@ -44,71 +61,97 @@ public class APIPublisherStartupHandler implements ServerStartupObserver {
@Override @Override
public void completedServerStartup() { public void completedServerStartup() {
String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
APIPublisherDataHolder.getInstance().setServerStarted(true); APIPublisherDataHolder.getInstance().setServerStarted(true);
currentAPIsStack = APIPublisherDataHolder.getInstance().getUnpublishedApis(); currentAPIsStack = APIPublisherDataHolder.getInstance().getUnpublishedApis();
Thread t = new Thread(new Runnable() { Thread t = new Thread(() -> {
@Override if (log.isDebugEnabled()) {
public void run() { log.debug("Server has just started, hence started publishing unpublished APIs");
if (log.isDebugEnabled()) { log.debug("Total number of unpublished APIs: "
log.debug("Server has just started, hence started publishing unpublished APIs"); + APIPublisherDataHolder.getInstance().getUnpublishedApis().size());
log.debug("Total number of unpublished APIs: " }
+ APIPublisherDataHolder.getInstance().getUnpublishedApis().size()); publisher = APIPublisherDataHolder.getInstance().getApiPublisherService();
} int retryCount = 0;
publisher = APIPublisherDataHolder.getInstance().getApiPublisherService(); while (retryCount < MAX_RETRY_COUNT && (!failedAPIsStack.isEmpty() || !currentAPIsStack.isEmpty())) {
int retryCount = 0; if (retryCount > 0) {
while (retryCount < MAX_RETRY_COUNT && (!failedAPIsStack.isEmpty() || !currentAPIsStack.isEmpty())) {
try { try {
retryTime = retryTime * CONNECTION_RETRY_FACTOR; retryTime = retryTime * CONNECTION_RETRY_FACTOR;
Thread.sleep(retryTime); Thread.sleep(retryTime);
} catch (InterruptedException te) { } catch (InterruptedException te) {
//do nothing. //do nothing.
} }
Stack<APIConfig> failedApis;
if (!APIPublisherDataHolder.getInstance().getUnpublishedApis().isEmpty()) {
publishAPIs(currentAPIsStack, failedAPIsStack);
failedApis = failedAPIsStack;
} else {
publishAPIs(failedAPIsStack, currentAPIsStack);
failedApis = currentAPIsStack;
}
retryCount++;
if (retryCount == MAX_RETRY_COUNT && !failedApis.isEmpty()) {
StringBuilder error = new StringBuilder();
error.append("Error occurred while publishing API ['");
while (!failedApis.isEmpty()) {
APIConfig api = failedApis.pop();
error.append(api.getName() + ",");
}
error.append("']");
log.error(error.toString());
}
} }
Stack<APIConfig> failedApis;
try { if (!currentAPIsStack.isEmpty()) {
publisher.updateScopeRoleMapping(); publishAPIs(currentAPIsStack, failedAPIsStack);
publisher.addDefaultScopesIfNotExist(); failedApis = failedAPIsStack;
} catch (APIManagerPublisherException e) { } else {
log.error("failed to update scope role mapping.", e); publishAPIs(failedAPIsStack, currentAPIsStack);
failedApis = currentAPIsStack;
} }
retryCount++;
// execute after api publishing if (retryCount == MAX_RETRY_COUNT && !failedApis.isEmpty()) {
for (PostApiPublishingObsever observer : APIPublisherDataHolder.getInstance().getPostApiPublishingObseverList()) { StringBuilder error = new StringBuilder();
if (log.isDebugEnabled()) { error.append("Error occurred while publishing API ['");
log.debug("Executing " + observer.getClass().getName()); while (!failedApis.isEmpty()) {
APIConfig api = failedApis.pop();
error.append(api.getName() + ",");
} }
observer.execute(); error.append("']");
log.info(error.toString());
} }
log.info("Finish executing PostApiPublishingObsevers");
} }
try {
publisher.updateScopeRoleMapping();
publisher.addDefaultScopesIfNotExist();
} catch (APIManagerPublisherException e) {
log.error("failed to update scope role mapping.", e);
}
try {
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
updateScopeMetadataEntryWithDefaultScopes();
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
log.info("Successfully published : [" + publishedAPIs + "]. " +
"and failed : [" + failedAPIsStack + "] " +
"Total successful count : [" + publishedAPIs.size() + "]. " +
"Failed count : [" + failedAPIsStack.size() + "]");
// execute after api publishing
for (PostApiPublishingObsever observer : APIPublisherDataHolder.getInstance().getPostApiPublishingObseverList()) {
if (log.isDebugEnabled()) {
log.debug("Executing " + observer.getClass().getName());
}
observer.execute();
}
log.info("Finish executing PostApiPublishingObsevers");
}); });
t.start(); t.start();
log.info("Starting API publishing procedure");
} }
/**
* Publish apis provided by the API stack, if failed while publishing, then failed API will be added to
* the failed API stack
*
* @param apis Stack of APIs to publish
* @param failedStack Stack to record failed APIs
*/
private void publishAPIs(Stack<APIConfig> apis, Stack<APIConfig> failedStack) { private void publishAPIs(Stack<APIConfig> apis, Stack<APIConfig> failedStack) {
while (!apis.isEmpty()) { while (!apis.isEmpty()) {
APIConfig api = apis.pop(); APIConfig api = apis.pop();
try { try {
publisher.publishAPI(api); publisher.publishAPI(api);
for (ApiScope scope : api.getScopes()) {
APIPublisherDataHolder.getInstance().getPermScopeMapping().putIfAbsent(scope.getPermissions(), scope.getKey());
}
publishedAPIs.add(api.getName());
log.info("Successfully published API [" + api.getName() + "]");
} catch (APIManagerPublisherException e) { } catch (APIManagerPublisherException e) {
log.error("failed to publish api.", e); log.error("failed to publish api.", e);
failedStack.push(api); failedStack.push(api);
@ -116,4 +159,47 @@ public class APIPublisherStartupHandler implements ServerStartupObserver {
} }
} }
/**
* Update permission scope mapping entry with default scopes if perm-scope-mapping entry exists, otherwise this function
* will create that entry and update the value with default permissions.
*/
private void updateScopeMetadataEntryWithDefaultScopes() {
Map<String, String> permScopeMap = APIPublisherDataHolder.getInstance().getPermScopeMapping();
Metadata permScopeMapping;
MetadataManagementService metadataManagementService = APIPublisherDataHolder.getInstance().getMetadataManagementService();
DeviceManagementConfig deviceManagementConfig = DeviceConfigurationManager.getInstance().getDeviceManagementConfig();
DefaultPermissions defaultPermissions = deviceManagementConfig.getDefaultPermissions();
try {
permScopeMapping = metadataManagementService.retrieveMetadata(Constants.PERM_SCOPE_MAPPING_META_KEY);
boolean entryAlreadyExists = permScopeMapping != null;
if (permScopeMap == null || permScopeMap.isEmpty()) {
permScopeMap = entryAlreadyExists ? gson.fromJson(permScopeMapping.getMetaValue(), HashMap.class) :
new HashMap<>();
}
for (DefaultPermission defaultPermission : defaultPermissions.getDefaultPermissions()) {
permScopeMap.putIfAbsent(defaultPermission.getName(), defaultPermission.getScopeMapping().getKey());
}
permScopeMapping = new Metadata();
permScopeMapping.setMetaKey(Constants.PERM_SCOPE_MAPPING_META_KEY);
permScopeMapping.setMetaValue(gson.toJson(permScopeMap));
if (entryAlreadyExists) {
metadataManagementService.updateMetadata(permScopeMapping);
} else {
metadataManagementService.createMetadata(permScopeMapping);
}
APIPublisherDataHolder.getInstance().setPermScopeMapping(permScopeMap);
log.info(Constants.PERM_SCOPE_MAPPING_META_KEY + "entry updated successfully");
} catch (MetadataKeyAlreadyExistsException e) {
log.error("Metadata entry already exists for " + Constants.PERM_SCOPE_MAPPING_META_KEY);
} catch (MetadataManagementException e) {
log.error("Error encountered while updating permission scope mapping metadata with default scopes");
}
}
} }

View File

@ -23,26 +23,34 @@ import com.google.gson.JsonArray;
import com.google.gson.JsonElement; import com.google.gson.JsonElement;
import com.google.gson.JsonObject; import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken; import com.google.gson.reflect.TypeToken;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import io.entgra.device.mgt.core.apimgt.annotations.Scope; import io.entgra.device.mgt.core.apimgt.annotations.Scope;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.constants.Constants;
import io.entgra.device.mgt.core.apimgt.webapp.publisher.config.APIResource; import io.entgra.device.mgt.core.apimgt.webapp.publisher.config.APIResource;
import io.entgra.device.mgt.core.apimgt.webapp.publisher.config.APIResourceConfiguration; import io.entgra.device.mgt.core.apimgt.webapp.publisher.config.APIResourceConfiguration;
import io.entgra.device.mgt.core.apimgt.webapp.publisher.config.WebappPublisherConfig; import io.entgra.device.mgt.core.apimgt.webapp.publisher.config.WebappPublisherConfig;
import io.entgra.device.mgt.core.apimgt.webapp.publisher.dto.ApiScope; import io.entgra.device.mgt.core.apimgt.webapp.publisher.dto.ApiScope;
import io.entgra.device.mgt.core.apimgt.webapp.publisher.dto.ApiUriTemplate; import io.entgra.device.mgt.core.apimgt.webapp.publisher.dto.ApiUriTemplate;
import io.entgra.device.mgt.core.apimgt.webapp.publisher.internal.APIPublisherDataHolder;
import io.entgra.device.mgt.core.apimgt.webapp.publisher.lifecycle.util.AnnotationProcessor; import io.entgra.device.mgt.core.apimgt.webapp.publisher.lifecycle.util.AnnotationProcessor;
import io.entgra.device.mgt.core.device.mgt.common.exceptions.MetadataManagementException;
import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.Metadata;
import org.apache.catalina.core.StandardContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.base.MultitenantConstants; import org.wso2.carbon.base.MultitenantConstants;
import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.core.util.Utils; import org.wso2.carbon.core.util.Utils;
import org.wso2.carbon.user.api.TenantManager;
import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.api.UserStoreException;
import javax.servlet.ServletContext; import javax.servlet.ServletContext;
import java.io.IOException;
import java.util.*; import java.util.*;
public class APIPublisherUtil { public class APIPublisherUtil {
public static final String API_VERSION_PARAM = "{version}"; public static final String API_VERSION_PARAM = "{version}";
public static final String PROPERTY_PROFILE = "profile";
private static final Log log = LogFactory.getLog(APIPublisherUtil.class); private static final Log log = LogFactory.getLog(APIPublisherUtil.class);
private static final String DEFAULT_API_VERSION = "1.0.0"; private static final String DEFAULT_API_VERSION = "1.0.0";
private static final String API_CONFIG_DEFAULT_VERSION = "1.0.0"; private static final String API_CONFIG_DEFAULT_VERSION = "1.0.0";
@ -53,10 +61,10 @@ public class APIPublisherUtil {
private static final String PARAM_MANAGED_API_IS_SECURED = "managed-api-isSecured"; private static final String PARAM_MANAGED_API_IS_SECURED = "managed-api-isSecured";
private static final String PARAM_SHARED_WITH_ALL_TENANTS = "isSharedWithAllTenants"; private static final String PARAM_SHARED_WITH_ALL_TENANTS = "isSharedWithAllTenants";
private static final String PARAM_PROVIDER_TENANT_DOMAIN = "providerTenantDomain"; private static final String PARAM_PROVIDER_TENANT_DOMAIN = "providerTenantDomain";
private static final String NON_SECURED_RESOURCES = "nonSecuredEndPoints"; private static final String NON_SECURED_RESOURCES = "nonSecuredEndPoints";
private static final String AUTH_TYPE_NON_SECURED = "None"; private static final String AUTH_TYPE_NON_SECURED = "None";
private static final String PARAM_IS_DEFAULT = "isDefault"; private static final String PARAM_IS_DEFAULT = "isDefault";
private static final Gson gson = new Gson();
public static String getServerBaseUrl() { public static String getServerBaseUrl() {
WebappPublisherConfig webappPublisherConfig = WebappPublisherConfig.getInstance(); WebappPublisherConfig webappPublisherConfig = WebappPublisherConfig.getInstance();
@ -255,7 +263,7 @@ public class APIPublisherUtil {
policy = null; policy = null;
} }
apiConfig.setPolicy(policy); apiConfig.setPolicy(policy);
setResourceAuthTypes(servletContext, apiConfig);
return apiConfig; return apiConfig;
} }
@ -318,7 +326,7 @@ public class APIPublisherUtil {
} }
} }
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("API swagger definition: " + swaggerDefinition.toString()); log.debug("API swagger definition: " + swaggerDefinition);
} }
return swaggerDefinition.toString(); return swaggerDefinition.toString();
} }
@ -336,8 +344,7 @@ public class APIPublisherUtil {
String fullPaath = ""; String fullPaath = "";
if (!template.getUriTemplate().equals(AnnotationProcessor.WILD_CARD)) { if (!template.getUriTemplate().equals(AnnotationProcessor.WILD_CARD)) {
fullPaath = apiConfig.getContext() + template.getUriTemplate(); fullPaath = apiConfig.getContext() + template.getUriTemplate();
} } else {
else {
fullPaath = apiConfig.getContext(); fullPaath = apiConfig.getContext();
} }
for (String context : resourcesList) { for (String context : resourcesList) {
@ -349,4 +356,73 @@ public class APIPublisherUtil {
} }
apiConfig.setUriTemplates(templates); apiConfig.setUriTemplates(templates);
} }
/**
* This method will extract and retrieve the API resource configuration by processing the API resources
* @param standardContext {@link StandardContext}
* @param servletContext {@link ServletContext}
* @return Extracted {@link APIResourceConfiguration} list describing from the servlet context
* @throws IOException Throws when error occurred while processing the swagger annotations
* @throws ClassNotFoundException Throws when error occurred while extracting api configurations
*/
public static List<APIResourceConfiguration> getAPIResourceConfiguration(StandardContext standardContext, ServletContext servletContext)
throws IOException, ClassNotFoundException {
List<APIResourceConfiguration> apiResourceConfigurations = new ArrayList<>();
String profile = System.getProperty(PROPERTY_PROFILE);
if (WebappPublisherConfig.getInstance().getProfiles().getProfile().contains(profile.toLowerCase())) {
AnnotationProcessor annotationProcessor = new AnnotationProcessor(standardContext);
Set<String> annotatedSwaggerAPIClasses = annotationProcessor.
scanStandardContext(io.swagger.annotations.SwaggerDefinition.class.getName());
apiResourceConfigurations = annotationProcessor.extractAPIInfo(servletContext,
annotatedSwaggerAPIClasses);
}
return apiResourceConfigurations;
}
/**
* This method can use to publish the apis after the server startup complete.
*
* @param apiConfig {@link APIConfig} Contains API definition
*/
public static void publishAPIAfterServerStartup(APIConfig apiConfig) {
APIPublisherDataHolder apiPublisherDataHolder = APIPublisherDataHolder.getInstance();
if (!apiPublisherDataHolder.isServerStarted()) {
if (log.isDebugEnabled()) {
log.debug("Abort publishing the API [" + apiConfig.getName() + "]. Server still starting");
}
throw new IllegalStateException("Server starting procedure is still not completed");
}
TenantManager tenantManager = apiPublisherDataHolder.getTenantManager();
if (tenantManager == null) {
throw new IllegalStateException("Tenant manager service not initialized properly");
}
try {
if (tenantManager.isTenantActive(tenantManager.getTenantId(apiConfig.getTenantDomain()))) {
APIPublisherService apiPublisherService = apiPublisherDataHolder.getApiPublisherService();
if (apiPublisherService == null) {
throw new IllegalStateException("API Publisher service is not initialized properly");
}
apiPublisherService.publishAPI(apiConfig);
for (ApiScope scope : apiConfig.getScopes()) {
apiPublisherDataHolder.getPermScopeMapping().putIfAbsent(scope.getPermissions(), scope.getKey());
}
Metadata permScopeMapping = new Metadata();
permScopeMapping.setMetaKey(Constants.PERM_SCOPE_MAPPING_META_KEY);
permScopeMapping.setMetaValue(gson.toJson(apiPublisherDataHolder.getPermScopeMapping()));
try {
apiPublisherDataHolder.getMetadataManagementService().updateMetadata(permScopeMapping);
} catch (MetadataManagementException e) {
log.error("Error encountered while updating the " + Constants.PERM_SCOPE_MAPPING_META_KEY + "entry");
}
} else {
log.error("Can't find an active tenant under tenant domain " + apiConfig.getTenantDomain());
}
} catch (Throwable e) {
log.error("Error occurred while publishing API '" + apiConfig.getName() + "' with the context '" +
apiConfig.getContext() + "' and version '" + apiConfig.getVersion() + "'", e);
}
}
} }

View File

@ -18,10 +18,10 @@
package io.entgra.device.mgt.core.apimgt.webapp.publisher.config; package io.entgra.device.mgt.core.apimgt.webapp.publisher.config;
import org.w3c.dom.Document;
import io.entgra.device.mgt.core.apimgt.webapp.publisher.InvalidConfigurationStateException; import io.entgra.device.mgt.core.apimgt.webapp.publisher.InvalidConfigurationStateException;
import io.entgra.device.mgt.core.apimgt.webapp.publisher.WebappPublisherConfigurationFailedException; import io.entgra.device.mgt.core.apimgt.webapp.publisher.WebappPublisherConfigurationFailedException;
import io.entgra.device.mgt.core.apimgt.webapp.publisher.WebappPublisherUtil; import io.entgra.device.mgt.core.apimgt.webapp.publisher.WebappPublisherUtil;
import org.w3c.dom.Document;
import org.wso2.carbon.utils.CarbonUtils; import org.wso2.carbon.utils.CarbonUtils;
import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBContext;

View File

@ -33,6 +33,7 @@ import org.wso2.carbon.user.core.service.RealmService;
import org.wso2.carbon.user.core.tenant.TenantManager; import org.wso2.carbon.user.core.tenant.TenantManager;
import org.wso2.carbon.utils.ConfigurationContextService; import org.wso2.carbon.utils.ConfigurationContextService;
import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.Stack; import java.util.Stack;
import java.util.List; import java.util.List;
@ -48,7 +49,7 @@ public class APIPublisherDataHolder {
private RegistryService registryService; private RegistryService registryService;
private boolean isServerStarted; private boolean isServerStarted;
private Stack<APIConfig> unpublishedApis = new Stack<>(); private Stack<APIConfig> unpublishedApis = new Stack<>();
private Map<String, String> permScopeMapping; private Map<String, String> permScopeMapping = new HashMap<>();
private APIApplicationServices apiApplicationServices; private APIApplicationServices apiApplicationServices;
private PublisherRESTAPIServices publisherRESTAPIServices; private PublisherRESTAPIServices publisherRESTAPIServices;
private MetadataManagementService metadataManagementService; private MetadataManagementService metadataManagementService;

View File

@ -29,55 +29,21 @@ import io.entgra.device.mgt.core.apimgt.webapp.publisher.APIPublisherService;
import io.entgra.device.mgt.core.apimgt.webapp.publisher.APIPublisherServiceImpl; import io.entgra.device.mgt.core.apimgt.webapp.publisher.APIPublisherServiceImpl;
import io.entgra.device.mgt.core.apimgt.webapp.publisher.APIPublisherStartupHandler; import io.entgra.device.mgt.core.apimgt.webapp.publisher.APIPublisherStartupHandler;
import io.entgra.device.mgt.core.apimgt.webapp.publisher.config.WebappPublisherConfig; import io.entgra.device.mgt.core.apimgt.webapp.publisher.config.WebappPublisherConfig;
import org.osgi.service.component.annotations.*;
import org.wso2.carbon.core.ServerStartupObserver; import org.wso2.carbon.core.ServerStartupObserver;
import org.wso2.carbon.registry.core.service.RegistryService; import org.wso2.carbon.registry.core.service.RegistryService;
import org.wso2.carbon.user.core.service.RealmService; import org.wso2.carbon.user.core.service.RealmService;
import java.util.HashMap; import java.util.HashMap;
/** @Component(
* @scr.component name="io.entgra.device.mgt.core.apimgt.webapp.publisher" immediate="true" name = "io.entgra.device.mgt.core.apimgt.webapp.publisher.internal.APIPublisherServiceComponent",
* @scr.reference name="user.realmservice.default" immediate = true)
* interface="org.wso2.carbon.user.core.service.RealmService"
* cardinality="1..1"
* policy="dynamic"
* bind="setRealmService"
* unbind="unsetRealmService"
* @scr.reference name="registry.service"
* interface="org.wso2.carbon.registry.core.service.RegistryService"
* cardinality="1..1"
* policy="dynamic"
* bind="setRegistryService"
* unbind="unsetRegistryService"
* @scr.reference name="APIM.application.service"
* interface="io.entgra.device.mgt.core.apimgt.extension.rest.api.APIApplicationServices"
* cardinality="1..1"
* policy="dynamic"
* bind="setAPIApplicationServices"
* unbind="unsetAPIApplicationServices"
* @scr.reference name="APIM.publisher.service"
* interface="io.entgra.device.mgt.core.apimgt.extension.rest.api.PublisherRESTAPIServices"
* cardinality="1..1"
* policy="dynamic"
* bind="setPublisherRESTAPIServices"
* unbind="unsetPublisherRESTAPIServices"
* @scr.reference name="io.entgra.meta.mgt"
* interface="io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.MetadataManagementService"
* cardinality="0..1"
* policy="dynamic"
* bind="setMetaDataMgtService"
* unbind="unsetMetaDataMgtService"
* @scr.reference name="postApiPublishingObsever"
* interface="io.entgra.device.mgt.core.apimgt.webapp.publisher.PostApiPublishingObsever"
* cardinality="0..n"
* policy="dynamic"
* bind="setPostApiPublishingObsever"
* unbind="unsetPostApiPublishingObsever"
*/
public class APIPublisherServiceComponent { public class APIPublisherServiceComponent {
private static Log log = LogFactory.getLog(APIPublisherServiceComponent.class); private static Log log = LogFactory.getLog(APIPublisherServiceComponent.class);
@Activate
protected void activate(ComponentContext componentContext) { protected void activate(ComponentContext componentContext) {
try { try {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
@ -102,6 +68,7 @@ public class APIPublisherServiceComponent {
} }
} }
@Deactivate
protected void deactivate(ComponentContext componentContext) { protected void deactivate(ComponentContext componentContext) {
//do nothing //do nothing
} }
@ -119,6 +86,12 @@ public class APIPublisherServiceComponent {
bundleContext.registerService(ServerStartupObserver.class, new APIPublisherStartupHandler(), null); bundleContext.registerService(ServerStartupObserver.class, new APIPublisherStartupHandler(), null);
} }
@Reference(
name = "user.realmservice.default",
service = org.wso2.carbon.user.core.service.RealmService.class,
cardinality = ReferenceCardinality.MANDATORY,
policy = ReferencePolicy.DYNAMIC,
unbind = "unsetRealmService")
protected void setRealmService(RealmService realmService) { protected void setRealmService(RealmService realmService) {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Setting Realm Service"); log.debug("Setting Realm Service");
@ -133,6 +106,12 @@ public class APIPublisherServiceComponent {
APIPublisherDataHolder.getInstance().setRealmService(null); APIPublisherDataHolder.getInstance().setRealmService(null);
} }
@Reference(
name = "registry.service",
service = org.wso2.carbon.registry.core.service.RegistryService.class,
cardinality = ReferenceCardinality.MANDATORY,
policy = ReferencePolicy.DYNAMIC,
unbind = "unsetRegistryService")
protected void setRegistryService(RegistryService registryService) { protected void setRegistryService(RegistryService registryService) {
if (registryService != null && log.isDebugEnabled()) { if (registryService != null && log.isDebugEnabled()) {
log.debug("Registry service initialized"); log.debug("Registry service initialized");
@ -144,6 +123,12 @@ public class APIPublisherServiceComponent {
APIPublisherDataHolder.getInstance().setRegistryService(null); APIPublisherDataHolder.getInstance().setRegistryService(null);
} }
@Reference(
name = "APIM.application.service",
service = io.entgra.device.mgt.core.apimgt.extension.rest.api.APIApplicationServices.class,
cardinality = ReferenceCardinality.MANDATORY,
policy = ReferencePolicy.DYNAMIC,
unbind = "unsetAPIApplicationServices")
protected void setAPIApplicationServices(APIApplicationServices apiApplicationServices) { protected void setAPIApplicationServices(APIApplicationServices apiApplicationServices) {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Setting DCR REST API Service"); log.debug("Setting DCR REST API Service");
@ -158,6 +143,12 @@ public class APIPublisherServiceComponent {
APIPublisherDataHolder.getInstance().setApiApplicationServices(null); APIPublisherDataHolder.getInstance().setApiApplicationServices(null);
} }
@Reference(
name = "APIM.publisher.service",
service = io.entgra.device.mgt.core.apimgt.extension.rest.api.PublisherRESTAPIServices.class,
cardinality = ReferenceCardinality.MANDATORY,
policy = ReferencePolicy.DYNAMIC,
unbind = "unsetPublisherRESTAPIServices")
protected void setPublisherRESTAPIServices(PublisherRESTAPIServices publisherRESTAPIServices) { protected void setPublisherRESTAPIServices(PublisherRESTAPIServices publisherRESTAPIServices) {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Setting APIM Publisher REST API Service"); log.debug("Setting APIM Publisher REST API Service");
@ -172,6 +163,12 @@ public class APIPublisherServiceComponent {
APIPublisherDataHolder.getInstance().setPublisherRESTAPIServices(null); APIPublisherDataHolder.getInstance().setPublisherRESTAPIServices(null);
} }
@Reference(
name = "io.entgra.meta.mgt",
service = io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.MetadataManagementService.class,
cardinality = ReferenceCardinality.OPTIONAL,
policy = ReferencePolicy.DYNAMIC,
unbind = "unsetMetaDataMgtService")
protected void setMetaDataMgtService(MetadataManagementService metadataManagementService) { protected void setMetaDataMgtService(MetadataManagementService metadataManagementService) {
if (metadataManagementService != null && log.isDebugEnabled()) { if (metadataManagementService != null && log.isDebugEnabled()) {
log.debug("Meta data mgt mgt service initialized"); log.debug("Meta data mgt mgt service initialized");
@ -183,6 +180,12 @@ public class APIPublisherServiceComponent {
APIPublisherDataHolder.getInstance().setMetadataManagementService(null); APIPublisherDataHolder.getInstance().setMetadataManagementService(null);
} }
@Reference(
name = "postApiPublishingObsever",
service = io.entgra.device.mgt.core.apimgt.webapp.publisher.PostApiPublishingObsever.class,
cardinality = ReferenceCardinality.MULTIPLE,
policy = ReferencePolicy.DYNAMIC,
unbind = "unsetPostApiPublishingObsever")
protected void setPostApiPublishingObsever(PostApiPublishingObsever postApiPublishingObsever) { protected void setPostApiPublishingObsever(PostApiPublishingObsever postApiPublishingObsever) {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Setting PostApiPublishingObsever"); log.debug("Setting PostApiPublishingObsever");

View File

@ -17,137 +17,58 @@
*/ */
package io.entgra.device.mgt.core.apimgt.webapp.publisher.lifecycle.listener; package io.entgra.device.mgt.core.apimgt.webapp.publisher.lifecycle.listener;
import com.google.gson.Gson; import io.entgra.device.mgt.core.apimgt.webapp.publisher.APIConfig;
import io.entgra.device.mgt.core.apimgt.webapp.publisher.dto.ApiScope; import io.entgra.device.mgt.core.apimgt.webapp.publisher.APIPublisherUtil;
import io.entgra.device.mgt.core.device.mgt.common.exceptions.MetadataManagementException; import io.entgra.device.mgt.core.apimgt.webapp.publisher.config.APIResourceConfiguration;
import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.Metadata; import io.entgra.device.mgt.core.apimgt.webapp.publisher.config.WebappPublisherConfig;
import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.MetadataManagementService; import io.entgra.device.mgt.core.apimgt.webapp.publisher.internal.APIPublisherDataHolder;
import io.entgra.device.mgt.core.device.mgt.core.config.DeviceConfigurationManager;
import io.entgra.device.mgt.core.device.mgt.core.config.DeviceManagementConfig;
import io.entgra.device.mgt.core.device.mgt.core.config.permission.DefaultPermission;
import io.entgra.device.mgt.core.device.mgt.core.config.permission.DefaultPermissions;
import org.apache.catalina.Lifecycle; import org.apache.catalina.Lifecycle;
import org.apache.catalina.LifecycleEvent; import org.apache.catalina.LifecycleEvent;
import org.apache.catalina.LifecycleListener; import org.apache.catalina.LifecycleListener;
import org.apache.catalina.core.StandardContext; import org.apache.catalina.core.StandardContext;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import io.entgra.device.mgt.core.apimgt.webapp.publisher.APIConfig;
import io.entgra.device.mgt.core.apimgt.webapp.publisher.APIPublisherService;
import io.entgra.device.mgt.core.apimgt.webapp.publisher.APIPublisherUtil;
import io.entgra.device.mgt.core.apimgt.webapp.publisher.config.APIResourceConfiguration;
import io.entgra.device.mgt.core.apimgt.webapp.publisher.config.WebappPublisherConfig;
import io.entgra.device.mgt.core.apimgt.webapp.publisher.internal.APIPublisherDataHolder;
import io.entgra.device.mgt.core.apimgt.webapp.publisher.lifecycle.util.AnnotationProcessor;
import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.api.UserStoreException;
import javax.servlet.ServletContext; import javax.servlet.ServletContext;
import java.io.IOException; import java.io.IOException;
import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.Set;
@SuppressWarnings("unused") @SuppressWarnings("unused")
public class APIPublisherLifecycleListener implements LifecycleListener { public class APIPublisherLifecycleListener implements LifecycleListener {
public static final String PROFILE_DEFAULT = "default";
private static final Log log = LogFactory.getLog(APIPublisherLifecycleListener.class); private static final Log log = LogFactory.getLog(APIPublisherLifecycleListener.class);
private static final String PARAM_MANAGED_API_ENABLED = "managed-api-enabled"; private static final String PARAM_MANAGED_API_ENABLED = "managed-api-enabled";
public static final String PROPERTY_PROFILE = "profile";
public static final String PROFILE_DT_WORKER = "dtWorker";
public static final String PROFILE_DEFAULT = "default";
@Override @Override
public void lifecycleEvent(LifecycleEvent lifecycleEvent) { public void lifecycleEvent(LifecycleEvent lifecycleEvent) {
if (Lifecycle.AFTER_START_EVENT.equals(lifecycleEvent.getType()) ) { if (Lifecycle.AFTER_START_EVENT.equals(lifecycleEvent.getType())) {
if (WebappPublisherConfig.getInstance()
.isPublished()) { APIPublisherDataHolder apiPublisherDataHolder = APIPublisherDataHolder.getInstance();
StandardContext context = (StandardContext) lifecycleEvent.getLifecycle(); StandardContext context = (StandardContext) lifecycleEvent.getLifecycle();
ServletContext servletContext = context.getServletContext(); ServletContext servletContext = context.getServletContext();
String param = servletContext.getInitParameter(PARAM_MANAGED_API_ENABLED); String param = servletContext.getInitParameter(PARAM_MANAGED_API_ENABLED);
boolean isManagedApi = (param != null && !param.isEmpty()) && Boolean.parseBoolean(param); boolean isManagedApi = (param != null && !param.isEmpty()) && Boolean.parseBoolean(param);
if (isManagedApi) {
if (WebappPublisherConfig.getInstance().isPublished() || WebappPublisherConfig.getInstance().isEnabledUpdateApi()) {
String profile = System.getProperty(PROPERTY_PROFILE);
if (WebappPublisherConfig.getInstance().getProfiles().getProfile().contains(profile.toLowerCase())
&& isManagedApi) {
try { try {
AnnotationProcessor annotationProcessor = new AnnotationProcessor(context); List<APIResourceConfiguration> apiResourceConfigurations =
Set<String> annotatedSwaggerAPIClasses = annotationProcessor. APIPublisherUtil.getAPIResourceConfiguration(context, servletContext);
scanStandardContext(io.swagger.annotations.SwaggerDefinition.class.getName());
List<APIResourceConfiguration> apiDefinitions = annotationProcessor.extractAPIInfo(servletContext,
annotatedSwaggerAPIClasses);
APIPublisherDataHolder apiPublisherDataHolder = APIPublisherDataHolder.getInstance(); if (WebappPublisherConfig.getInstance().isPublished()) {
MetadataManagementService metadataManagementService = for (APIResourceConfiguration apiDefinition : apiResourceConfigurations) {
apiPublisherDataHolder.getMetadataManagementService(); APIConfig apiConfig = APIPublisherUtil.buildApiConfig(servletContext, apiDefinition);
Metadata metadata = metadataManagementService.retrieveMetadata("perm-scope-mapping"); if (apiPublisherDataHolder.isServerStarted()) {
if (metadata != null) { APIPublisherUtil.publishAPIAfterServerStartup(apiConfig);
HashMap<String, String> permScopeMapping =
new Gson().fromJson(metadata.getMetaValue().toString(), HashMap.class);
apiPublisherDataHolder.setPermScopeMapping(permScopeMapping);
}
Map<String, String> permScopeMap = apiPublisherDataHolder.getPermScopeMapping();
for (APIResourceConfiguration apiDefinition : apiDefinitions) {
APIConfig apiConfig = APIPublisherUtil.buildApiConfig(servletContext, apiDefinition);
for (ApiScope scope : apiConfig.getScopes()) {
permScopeMap.put(scope.getPermissions(), scope.getKey());
}
APIPublisherUtil.setResourceAuthTypes(servletContext,apiConfig);
try {
int tenantId = APIPublisherDataHolder.getInstance().getTenantManager().
getTenantId(apiConfig.getTenantDomain());
boolean isTenantActive = APIPublisherDataHolder.getInstance().
getTenantManager().isTenantActive(tenantId);
if (isTenantActive) {
boolean isServerStarted = APIPublisherDataHolder.getInstance().isServerStarted();
if (isServerStarted) {
APIPublisherService apiPublisherService =
APIPublisherDataHolder.getInstance().getApiPublisherService();
if (apiPublisherService == null) {
throw new IllegalStateException(
"API Publisher service is not initialized properly");
}
apiPublisherService.publishAPI(apiConfig);
} else {
if (log.isDebugEnabled()) {
log.debug("Server has not started yet. Hence adding API '" +
apiConfig.getName() + "' to the queue");
}
APIPublisherDataHolder.getInstance().getUnpublishedApis().push(apiConfig);
}
} else { } else {
log.error("No tenant [" + apiConfig.getTenantDomain() + "] " + apiPublisherDataHolder.getUnpublishedApis().push(apiConfig);
"found when publishing the Web app");
} }
} catch (Throwable e) {
log.error("Error occurred while publishing API '" + apiConfig.getName() +
"' with the context '" + apiConfig.getContext() +
"' and version '" + apiConfig.getVersion() + "'", e);
} }
} }
Metadata existingMetaData = metadataManagementService.retrieveMetadata("perm-scope" +
"-mapping");
if (existingMetaData != null) {
existingMetaData.setMetaValue(new Gson().toJson(permScopeMap));
metadataManagementService.updateMetadata(existingMetaData);
} else {
Metadata newMetaData = new Metadata();
newMetaData.setMetaKey("perm-scope-mapping");
DeviceManagementConfig deviceManagementConfig = DeviceConfigurationManager.getInstance().getDeviceManagementConfig();
DefaultPermissions defaultPermissions = deviceManagementConfig.getDefaultPermissions();
for (DefaultPermission defaultPermission : defaultPermissions.getDefaultPermissions()) {
permScopeMap.put(defaultPermission.getName(), defaultPermission.getScopeMapping().getKey());
}
newMetaData.setMetaValue(new Gson().toJson(permScopeMap));
metadataManagementService.createMetadata(newMetaData);
}
apiPublisherDataHolder.setPermScopeMapping(permScopeMap);
} catch (IOException e) { } catch (IOException e) {
log.error("Error encountered while discovering annotated classes", e); log.error("Error encountered while discovering annotated classes", e);
} catch (ClassNotFoundException e) { } catch (ClassNotFoundException e) {
@ -160,24 +81,6 @@ public class APIPublisherLifecycleListener implements LifecycleListener {
log.error("Failed to Publish api from " + servletContext.getContextPath(), e); log.error("Failed to Publish api from " + servletContext.getContextPath(), e);
} }
} }
} else {
APIPublisherDataHolder apiPublisherDataHolder = APIPublisherDataHolder.getInstance();
MetadataManagementService metadataManagementService =
apiPublisherDataHolder.getMetadataManagementService();
try {
Metadata existingMetaData = metadataManagementService.retrieveMetadata("perm-scope" +
"-mapping");
if (existingMetaData != null) {
existingMetaData.setMetaValue(new Gson().toJson(apiPublisherDataHolder.getPermScopeMapping()
));
metadataManagementService.updateMetadata(existingMetaData);
} else {
log.error("Couldn't find 'perm-scope-mapping' Meta entry while API publishing has been turned" +
" off.");
}
} catch (MetadataManagementException e) {
log.error("Failed to Load Meta-Mgt data.", e);
}
} }
} }
} }

View File

@ -20,27 +20,18 @@ package io.entgra.device.mgt.core.apimgt.webapp.publisher.lifecycle.util;
import io.entgra.device.mgt.core.apimgt.annotations.Scope; import io.entgra.device.mgt.core.apimgt.annotations.Scope;
import io.entgra.device.mgt.core.apimgt.annotations.Scopes; import io.entgra.device.mgt.core.apimgt.annotations.Scopes;
import io.entgra.device.mgt.core.apimgt.webapp.publisher.APIPublisherUtil;
import io.entgra.device.mgt.core.apimgt.webapp.publisher.config.APIResource;
import io.entgra.device.mgt.core.apimgt.webapp.publisher.config.APIResourceConfiguration;
import io.entgra.device.mgt.core.apimgt.webapp.publisher.dto.ApiScope;
import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.SwaggerDefinition; import io.swagger.annotations.SwaggerDefinition;
import org.apache.catalina.core.StandardContext; import org.apache.catalina.core.StandardContext;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import io.entgra.device.mgt.core.apimgt.webapp.publisher.APIPublisherUtil;
import io.entgra.device.mgt.core.apimgt.webapp.publisher.config.APIResource;
import io.entgra.device.mgt.core.apimgt.webapp.publisher.config.APIResourceConfiguration;
import io.entgra.device.mgt.core.apimgt.webapp.publisher.dto.ApiScope;
import javax.servlet.ServletContext; import javax.servlet.ServletContext;
import javax.ws.rs.Consumes; import javax.ws.rs.*;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.HEAD;
import javax.ws.rs.HttpMethod;
import javax.ws.rs.OPTIONS;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.lang.annotation.Annotation; import java.lang.annotation.Annotation;

View File

@ -18,7 +18,6 @@
package io.entgra.device.mgt.core.apimgt.webapp.publisher.lifecycle.util; package io.entgra.device.mgt.core.apimgt.webapp.publisher.lifecycle.util;
import org.scannotation.archiveiterator.*; import org.scannotation.archiveiterator.*;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.net.URL; import java.net.URL;

View File

@ -17,6 +17,13 @@
*/ */
package io.entgra.device.mgt.core.apimgt.webapp.publisher; package io.entgra.device.mgt.core.apimgt.webapp.publisher;
import io.entgra.device.mgt.core.apimgt.webapp.publisher.config.WebappPublisherConfig;
import io.entgra.device.mgt.core.apimgt.webapp.publisher.dto.ApiScope;
import io.entgra.device.mgt.core.apimgt.webapp.publisher.exception.APIManagerPublisherException;
import io.entgra.device.mgt.core.apimgt.webapp.publisher.internal.APIPublisherDataHolder;
import io.entgra.device.mgt.core.apimgt.webapp.publisher.utils.MockAPICollectionApi;
import io.entgra.device.mgt.core.apimgt.webapp.publisher.utils.MockAPIIndividualApi;
import io.entgra.device.mgt.core.apimgt.webapp.publisher.utils.TestUtils;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.mockito.Mockito; import org.mockito.Mockito;
@ -32,13 +39,6 @@ import org.wso2.carbon.apimgt.integration.generated.client.publisher.api.APIIndi
import org.wso2.carbon.apimgt.integration.generated.client.publisher.model.API; import org.wso2.carbon.apimgt.integration.generated.client.publisher.model.API;
import org.wso2.carbon.apimgt.integration.generated.client.publisher.model.APIInfo; import org.wso2.carbon.apimgt.integration.generated.client.publisher.model.APIInfo;
import org.wso2.carbon.apimgt.integration.generated.client.publisher.model.APIList; import org.wso2.carbon.apimgt.integration.generated.client.publisher.model.APIList;
import io.entgra.device.mgt.core.apimgt.webapp.publisher.config.WebappPublisherConfig;
import io.entgra.device.mgt.core.apimgt.webapp.publisher.dto.ApiScope;
import io.entgra.device.mgt.core.apimgt.webapp.publisher.exception.APIManagerPublisherException;
import io.entgra.device.mgt.core.apimgt.webapp.publisher.internal.APIPublisherDataHolder;
import io.entgra.device.mgt.core.apimgt.webapp.publisher.utils.MockAPICollectionApi;
import io.entgra.device.mgt.core.apimgt.webapp.publisher.utils.MockAPIIndividualApi;
import io.entgra.device.mgt.core.apimgt.webapp.publisher.utils.TestUtils;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.util.*; import java.util.*;

View File

@ -17,9 +17,6 @@
*/ */
package io.entgra.device.mgt.core.apimgt.webapp.publisher; package io.entgra.device.mgt.core.apimgt.webapp.publisher;
import org.testng.Assert;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import io.entgra.device.mgt.core.apimgt.webapp.publisher.config.APIResource; import io.entgra.device.mgt.core.apimgt.webapp.publisher.config.APIResource;
import io.entgra.device.mgt.core.apimgt.webapp.publisher.config.APIResourceConfiguration; import io.entgra.device.mgt.core.apimgt.webapp.publisher.config.APIResourceConfiguration;
import io.entgra.device.mgt.core.apimgt.webapp.publisher.config.WebappPublisherConfig; import io.entgra.device.mgt.core.apimgt.webapp.publisher.config.WebappPublisherConfig;
@ -28,6 +25,9 @@ import io.entgra.device.mgt.core.apimgt.webapp.publisher.dto.ApiUriTemplate;
import io.entgra.device.mgt.core.apimgt.webapp.publisher.exception.APIManagerPublisherException; import io.entgra.device.mgt.core.apimgt.webapp.publisher.exception.APIManagerPublisherException;
import io.entgra.device.mgt.core.apimgt.webapp.publisher.utils.MockServletContext; import io.entgra.device.mgt.core.apimgt.webapp.publisher.utils.MockServletContext;
import io.entgra.device.mgt.core.apimgt.webapp.publisher.utils.TestUtils; import io.entgra.device.mgt.core.apimgt.webapp.publisher.utils.TestUtils;
import org.testng.Assert;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.registry.core.exceptions.RegistryException; import org.wso2.carbon.registry.core.exceptions.RegistryException;
import org.wso2.carbon.registry.core.jdbc.realm.InMemoryRealmService; import org.wso2.carbon.registry.core.jdbc.realm.InMemoryRealmService;
@ -36,14 +36,11 @@ import org.wso2.carbon.user.api.UserRealm;
import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.api.UserStoreException;
import javax.servlet.ServletContext; import javax.servlet.ServletContext;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
import static io.entgra.device.mgt.core.apimgt.webapp.publisher.APIPublisherUtil.buildApiConfig; import static io.entgra.device.mgt.core.apimgt.webapp.publisher.APIPublisherUtil.*;
import static io.entgra.device.mgt.core.apimgt.webapp.publisher.APIPublisherUtil.getApiEndpointUrl;
import static io.entgra.device.mgt.core.apimgt.webapp.publisher.APIPublisherUtil.setResourceAuthTypes;
/** /**
* This is the test class for {@link APIPublisherUtil} * This is the test class for {@link APIPublisherUtil}

View File

@ -17,12 +17,13 @@
*/ */
package io.entgra.device.mgt.core.apimgt.webapp.publisher; package io.entgra.device.mgt.core.apimgt.webapp.publisher;
import io.entgra.device.mgt.core.apimgt.webapp.publisher.internal.APIPublisherDataHolder;
import io.entgra.device.mgt.core.apimgt.webapp.publisher.utils.MockAPIIndividualApi;
import io.entgra.device.mgt.core.identity.jwt.client.extension.exception.JWTClientException;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.mockito.Mockito; import org.mockito.Mockito;
import org.testng.annotations.BeforeSuite; import org.testng.annotations.BeforeSuite;
import io.entgra.device.mgt.core.apimgt.webapp.publisher.internal.APIPublisherDataHolder;
import io.entgra.device.mgt.core.apimgt.webapp.publisher.utils.MockAPIIndividualApi;
import org.wso2.carbon.base.MultitenantConstants; import org.wso2.carbon.base.MultitenantConstants;
import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.context.internal.OSGiDataHolder; import org.wso2.carbon.context.internal.OSGiDataHolder;
@ -33,7 +34,6 @@ import org.wso2.carbon.registry.core.jdbc.realm.InMemoryRealmService;
import org.wso2.carbon.registry.core.service.RegistryService; import org.wso2.carbon.registry.core.service.RegistryService;
import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.user.core.service.RealmService; import org.wso2.carbon.user.core.service.RealmService;
import io.entgra.device.mgt.core.identity.jwt.client.extension.exception.JWTClientException;
import java.io.File; import java.io.File;
import java.io.InputStream; import java.io.InputStream;

View File

@ -27,7 +27,7 @@
<EveryOneRoleName>everyone</EveryOneRoleName> <EveryOneRoleName>everyone</EveryOneRoleName>
<ReadOnly>false</ReadOnly> <ReadOnly>false</ReadOnly>
<MaxUserNameListLength>500</MaxUserNameListLength> <MaxUserNameListLength>500</MaxUserNameListLength>
<Property name="url">jdbc:h2:target/databasetest/CARBON_TEST</Property> <Property name="url">jdbc:h2:./target/databasetest/CARBON_TEST</Property>
<Property name="driverName">org.h2.Driver</Property> <Property name="driverName">org.h2.Driver</Property>
<Property name="maxActive">50</Property> <Property name="maxActive">50</Property>
<Property name="maxWait">60000</Property> <Property name="maxWait">60000</Property>

View File

@ -1,142 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
~
~ Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>apimgt-extensions</artifactId>
<groupId>io.entgra.device.mgt.core</groupId>
<version>5.0.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>org.wso2.carbon.apimgt.handlers</artifactId>
<packaging>bundle</packaging>
<name>WSO2 Carbon - API Security Handler Component</name>
<description>WSO2 Carbon - API Management Security Handler Module</description>
<url>http://wso2.org</url>
<dependencies>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.logging</artifactId>
</dependency>
<dependency>
<groupId>org.apache.synapse</groupId>
<artifactId>synapse-core</artifactId>
</dependency>
<dependency>
<groupId>org.apache.ws.security.wso2</groupId>
<artifactId>wss4j</artifactId>
</dependency>
<dependency>
<groupId>io.entgra.device.mgt.core</groupId>
<artifactId>io.entgra.device.mgt.core.certificate.mgt.core</artifactId>
</dependency>
<dependency>
<groupId>org.json.wso2</groupId>
<artifactId>json</artifactId>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-scr-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<version>1.4.0</version>
<extensions>true</extensions>
<configuration>
<instructions>
<Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
<Bundle-Name>${project.artifactId}</Bundle-Name>
<Bundle-Version>${io.entgra.device.mgt.core.version}</Bundle-Version>
<Bundle-Description>WSO2 Carbon - API Security Handler Component</Bundle-Description>
<Import-Package>
org.apache.axiom.*,
javax.security.cert.*,
javax.xml.parsers;version="${javax.xml.parsers.import.pkg.version}";resolution:=optional,
javax.xml.*,
org.apache.axis2.*,
org.apache.commons.*,
org.apache.http.*,
org.apache.http.util,
org.apache.ws.*;version="${org.apache.ws.security.wso2.version}",
org.json,
org.wso2.carbon.utils,
org.wso2.carbon.context,
com.google.gson,
org.w3c.dom,
org.apache.synapse,
org.apache.synapse.core.axis2,
org.apache.synapse.rest,
io.entgra.device.mgt.core.certificate.mgt.core.*
</Import-Package>
</instructions>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<suiteXmlFiles>
<suiteXmlFile>src/test/resources/testng.xml</suiteXmlFile>
</suiteXmlFiles>
</configuration>
</plugin>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<configuration>
<destFile>${basedir}/target/coverage-reports/jacoco-unit.exec</destFile>
</configuration>
<executions>
<execution>
<id>jacoco-initialize</id>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>jacoco-site</id>
<phase>test</phase>
<goals>
<goal>report</goal>
</goals>
<configuration>
<dataFile>${basedir}/target/coverage-reports/jacoco-unit.exec</dataFile>
<outputDirectory>${basedir}/target/coverage-reports/site</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

View File

@ -1,33 +0,0 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import io.entgra.device.mgt.core.device.mgt.api.jaxrs..carbon.apimgt.handlers;
/**
* Error handling class for the apimgt handler.
*/
public class APIMCertificateMGTException extends Exception{
private static final long serialVersionUID = -37676242646464497L;
public APIMCertificateMGTException(String msg, Exception nestedEx) {
super(msg, nestedEx);
}
}

View File

@ -1,235 +0,0 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.apimgt.handlers;
import com.google.gson.Gson;
import org.apache.axis2.context.MessageContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.synapse.core.axis2.Axis2MessageContext;
import org.apache.synapse.rest.AbstractHandler;
import org.wso2.carbon.apimgt.handlers.beans.Certificate;
import org.wso2.carbon.apimgt.handlers.beans.ValidationResponce;
import org.wso2.carbon.apimgt.handlers.config.IOTServerConfiguration;
import org.wso2.carbon.apimgt.handlers.invoker.RESTInvoker;
import org.wso2.carbon.apimgt.handlers.invoker.RESTResponse;
import org.wso2.carbon.apimgt.handlers.utils.AuthConstants;
import org.wso2.carbon.apimgt.handlers.utils.Utils;
import io.entgra.device.mgt.core.certificate.mgt.core.dto.CertificateResponse;
import io.entgra.device.mgt.core.certificate.mgt.core.exception.KeystoreException;
import io.entgra.device.mgt.core.certificate.mgt.core.impl.CertificateGenerator;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import javax.security.cert.CertificateEncodingException;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;
/**
* Synapse gateway handler for API authentication.
*/
public class AuthenticationHandler extends AbstractHandler {
private static final Log log = LogFactory.getLog(AuthenticationHandler.class);
private RESTInvoker restInvoker;
private static final String X_JWT_ASSERTION = "X-JWT-Assertion";
private static final String JWTTOKEN = "JWTToken";
private static final String AUTHORIZATION = "Authorization";
private static final String BEARER = "Basic ";
private static final String CONTENT_TYPE = "Content-Type";
private static final boolean USE_INTERNAL_CERT_VERIFIER = true;
private IOTServerConfiguration iotServerConfiguration;
/**
* Setting up configurations at the constructor
*/
public AuthenticationHandler() {
log.info("Engaging API Security Handler..........");
restInvoker = new RESTInvoker();
this.iotServerConfiguration = Utils.initConfig();
}
/**
* Handling the message and checking the security.
*
* @param messageContext Request message context.
* @return Boolean value of the result of the processing the request.
*/
@Override
public boolean handleRequest(org.apache.synapse.MessageContext messageContext) {
org.apache.axis2.context.MessageContext axisMC = ((Axis2MessageContext) messageContext).getAxis2MessageContext();
String ctxPath = messageContext.getTo().getAddress().trim();
if (log.isDebugEnabled()) {
log.debug("Authentication handler invoked by: " + ctxPath);
}
Map<String, String> headers = (Map<String, String>) axisMC.getProperty(MessageContext.TRANSPORT_HEADERS);
try {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
RESTResponse response = null;
if (headers.containsKey(AuthConstants.MDM_SIGNATURE)) {
String mdmSignature = headers.get(AuthConstants.MDM_SIGNATURE);
if (log.isDebugEnabled()) {
log.debug("Verify Cert:\n" + mdmSignature);
}
URI certVerifyUrl = new URI(iotServerConfiguration.getVerificationEndpoint() + "ios");
Map<String, String> certVerifyHeaders = this.setHeaders();
Certificate certificate = new Certificate();
certificate.setPem(mdmSignature);
certificate.setTenantId(tenantId);
certificate.setSerial("");
Gson gson = new Gson();
String certVerifyContent = gson.toJson(certificate);
response = restInvoker.invokePOST(certVerifyUrl, certVerifyHeaders, certVerifyContent);
String str = response.getContent();
if (log.isDebugEnabled()) {
log.debug("Verify response:" + response.getContent());
log.debug("Response String : " + str);
}
if (response.getHttpStatus() == 200 && str.contains(JWTTOKEN)) {
ValidationResponce validationResponce = gson.fromJson(str, ValidationResponce.class);
headers.put(X_JWT_ASSERTION, validationResponce.getJWTToken());
} else {
return false;
}
} else if (headers.containsKey(AuthConstants.PROXY_MUTUAL_AUTH_HEADER)) {
String subjectDN = headers.get(AuthConstants.PROXY_MUTUAL_AUTH_HEADER);
if (log.isDebugEnabled()) {
log.debug("Verify subject DN: " + subjectDN);
}
if (USE_INTERNAL_CERT_VERIFIER) {
CertificateResponse certificateResponse = Utils.getCertificateManagementService()
.verifySubjectDN(subjectDN);
if (certificateResponse != null && certificateResponse.getCommonName() != null
&& !certificateResponse.getCommonName().isEmpty()) {
return true;
}
} else {
String deviceType = this.getDeviceType(messageContext.getTo().getAddress().trim());
URI certVerifyUrl = new URI(iotServerConfiguration.getVerificationEndpoint() + deviceType);
Map<String, String> certVerifyHeaders = this.setHeaders();
Certificate certificate = new Certificate();
certificate.setPem(subjectDN);
certificate.setTenantId(tenantId);
certificate.setSerial(AuthConstants.PROXY_MUTUAL_AUTH_HEADER);
Gson gson = new Gson();
String certVerifyContent = gson.toJson(certificate);
response = restInvoker.invokePOST(certVerifyUrl, certVerifyHeaders, certVerifyContent);
if (log.isDebugEnabled()) {
log.debug("Verify response:" + response.getContent());
}
}
} else if (headers.containsKey(AuthConstants.MUTUAL_AUTH_HEADER)) {
javax.security.cert.X509Certificate[] certs =
(javax.security.cert.X509Certificate[]) axisMC.getProperty(AuthConstants.CLIENT_CERTIFICATE);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
ByteArrayInputStream bais = new ByteArrayInputStream(certs[0].getEncoded());
X509Certificate x509 = (X509Certificate) cf.generateCertificate(bais);
bais.close();
if (x509 != null) {
headers.put(AuthConstants.PROXY_MUTUAL_AUTH_HEADER, CertificateGenerator.getCommonName(x509));
return true;
}
} else if (headers.containsKey(AuthConstants.ENCODED_PEM)) {
String encodedPem = headers.get(AuthConstants.ENCODED_PEM);
if (log.isDebugEnabled()) {
log.debug("Verify Cert:\n" + encodedPem);
}
String deviceType = this.getDeviceType(messageContext.getTo().getAddress().trim());
URI certVerifyUrl = new URI(iotServerConfiguration.getVerificationEndpoint() + deviceType);
Map<String, String> certVerifyHeaders = this.setHeaders();
Certificate certificate = new Certificate();
certificate.setPem(encodedPem);
certificate.setTenantId(tenantId);
certificate.setSerial("");
Gson gson = new Gson();
String certVerifyContent = gson.toJson(certificate);
response = restInvoker.invokePOST(certVerifyUrl, certVerifyHeaders, certVerifyContent);
if (log.isDebugEnabled()) {
log.debug("Verify response:" + response.getContent());
}
} else {
log.warn("Unauthorized request for api: " + ctxPath);
return false;
}
if (response != null && !response.getContent().contains("invalid")) {
return true;
}
log.warn("Unauthorized request for api: " + ctxPath);
return false;
} catch (IOException e) {
log.error("Error while processing certificate.", e);
return false;
} catch (URISyntaxException e) {
log.error("Error while processing certificate.", e);
return false;
} catch (CertificateException e) {
log.error("Certificate issue occurred when generating converting PEM to x509Certificate", e);
return false;
} catch (CertificateEncodingException e) {
log.error("Error while attempting to encode certificate.", e);
return false;
} catch (KeystoreException e) {
log.error("Error while attempting to validate certificate.", e);
return false;
}
}
@Override
public boolean handleResponse(org.apache.synapse.MessageContext messageContext) {
return true;
}
private String getDeviceType(String url) {
StringTokenizer parts = new StringTokenizer(url, "/");
while (parts.hasMoreElements()) {
if (parts.nextElement().equals("device-mgt")) {
return (String) parts.nextElement();
}
}
return null;
}
private Map<String, String> setHeaders() {
Map<String, String> map = new HashMap<>();
String accessToken = Utils.getBase64EncodedToken(iotServerConfiguration);
map.put(AUTHORIZATION, BEARER + accessToken);
map.put(CONTENT_TYPE, "application/json");
return map;
}
}

View File

@ -1,58 +0,0 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.apimgt.handlers.beans;
/**
* This class keeps the certificate data.
*/
public class Certificate {
// public key of the certificate
private String pem;
// Tenant id
private int tenantId;
// Serial of the certificate.
private String serial;
public String getPem() {
return pem;
}
public void setPem(String pem) {
this.pem = pem;
}
public int getTenantId() {
return tenantId;
}
public void setTenantId(int tenantId) {
this.tenantId = tenantId;
}
public String getSerial() {
return serial;
}
public void setSerial(String serial) {
this.serial = serial;
}
}

View File

@ -1,88 +0,0 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.apimgt.handlers.beans;
/**
* This class holds the DCR endpoints data to create an application.
*/
public class DCR {
private String callbackUrl;
private String owner;
private String clientName;
private String grantType;
private String tokenScope;
private boolean isSaasApp;
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
public String getClientName() {
return clientName;
}
public void setClientName(String clientName) {
this.clientName = clientName;
}
public String getGrantType() {
return grantType;
}
public void setGrantType(String grantType) {
this.grantType = grantType;
}
public String getTokenScope() {
return tokenScope;
}
public void setTokenScope(String tokenScope) {
this.tokenScope = tokenScope;
}
public boolean getIsSaasApp() {
return isSaasApp;
}
public void setIsSaasApp(boolean isSaasApp) {
this.isSaasApp = isSaasApp;
}
public String getCallbackUrl() {
return callbackUrl;
}
public void setCallbackUrl(String callbackUrl) {
this.callbackUrl = callbackUrl;
}
public String toJSON() {
return "{\"callbackUrl\": \"" + callbackUrl + "\",\"clientName\": \"" + clientName + "\", \"tokenScope\": " +
"\"" + tokenScope + "\", \"owner\": \"" + owner + "\"," + "\"grantType\": \"" + grantType +
"\", \"saasApp\" :" + isSaasApp + " }\n";
}
}

View File

@ -1,64 +0,0 @@
/*
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.apimgt.handlers.beans;
/**
* This class holds the data returned from the backend after the certificate was authenticated.
*/
public class ValidationResponce {
private String JWTToken; // X-JWT-Assertion
private String deviceId;
private String deviceType;
private int tenantId;
public String getJWTToken() {
return JWTToken;
}
public void setJWTToken(String JWTToken) {
this.JWTToken = JWTToken;
}
public String getDeviceId() {
return deviceId;
}
public void setDeviceId(String deviceId) {
this.deviceId = deviceId;
}
public String getDeviceType() {
return deviceType;
}
public void setDeviceType(String deviceType) {
this.deviceType = deviceType;
}
public int getTenantId() {
return tenantId;
}
public void setTenantId(int tenantId) {
this.tenantId = tenantId;
}
}

View File

@ -1,122 +0,0 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.apimgt.handlers.config;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlValue;
import java.util.List;
/**
* This class initialize the iot-api-config.xml and hold the values, in order to be read from the relevant classes. This
* get initialized at the start of the server when apis get loaded.
*/
@XmlRootElement(name = "ServerConfiguration")
public class IOTServerConfiguration {
private String hostname;
private String verificationEndpoint;
private String username;
private String password;
private String dynamicClientRegistrationEndpoint;
private String oauthTokenEndpoint;
private List<ContextPath> apis;
@XmlElement(name = "Hostname", required = true)
public String getHostname() {
return hostname;
}
public void setHostname(String hostname) {
this.hostname = hostname;
}
@XmlElement(name = "VerificationEndpoint", required = true)
public String getVerificationEndpoint() {
return verificationEndpoint;
}
public void setVerificationEndpoint(String verificationEndpoint) {
this.verificationEndpoint = verificationEndpoint;
}
@XmlElement(name = "Username", required = true)
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
@XmlElement(name = "Password", required = true)
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@XmlElement(name = "DynamicClientRegistrationEndpoint", required = true)
public String getDynamicClientRegistrationEndpoint() {
return dynamicClientRegistrationEndpoint;
}
public void setDynamicClientRegistrationEndpoint(String dynamicClientRegistrationEndpoint) {
this.dynamicClientRegistrationEndpoint = dynamicClientRegistrationEndpoint;
}
@XmlElement(name = "OauthTokenEndpoint", required = true)
public String getOauthTokenEndpoint() {
return oauthTokenEndpoint;
}
public void setOauthTokenEndpoint(String oauthTokenEndpoint) {
this.oauthTokenEndpoint = oauthTokenEndpoint;
}
@XmlElementWrapper(name="APIS")
@XmlElement(name = "ContextPath", required = true)
public List<ContextPath> getApis() {
return apis;
}
public void setApis(List<ContextPath> apis) {
this.apis = apis;
}
@XmlRootElement(name = "ContextPath")
public static class ContextPath {
private String contextPath;
@XmlValue()
public String getContextPath() {
return contextPath;
}
public void setContextPath(String contextPath) {
this.contextPath = contextPath;
}
}
}

View File

@ -1,110 +0,0 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.apimgt.handlers.invoker;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.*;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.net.URI;
import java.util.Map;
import java.util.Set;
public class RESTInvoker {
private static final Log log = LogFactory.getLog(RESTInvoker.class);
private CloseableHttpClient client = null;
public RESTInvoker() {
configureHttpClient();
}
private void configureHttpClient() {
int connectionTimeout = 120000;
int socketTimeout = 120000;
int maxTotalConnectionsPerRoute = 100;
int maxTotalConnections = 100;
RequestConfig defaultRequestConfig = RequestConfig.custom()
.setExpectContinueEnabled(true)
.setConnectTimeout(connectionTimeout)
.setSocketTimeout(socketTimeout)
.build();
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
connectionManager.setDefaultMaxPerRoute(maxTotalConnectionsPerRoute);
connectionManager.setMaxTotal(maxTotalConnections);
client = HttpClients.custom()
.setConnectionManager(connectionManager)
.setDefaultRequestConfig(defaultRequestConfig)
.build();
if (log.isDebugEnabled()) {
log.debug("REST client initialized with " +
"maxTotalConnection = " + maxTotalConnections +
"maxConnectionsPerRoute = " + maxTotalConnectionsPerRoute +
"connectionTimeout = " + connectionTimeout);
}
}
public RESTResponse invokePOST(URI uri, Map<String, String> requestHeaders, String payload) throws IOException {
HttpPost httpPost = null;
CloseableHttpResponse response = null;
int httpStatus;
String output;
try {
httpPost = new HttpPost(uri);
httpPost.setEntity(new StringEntity(payload));
if (requestHeaders != null && !requestHeaders.isEmpty()) {
Set<String> keys = requestHeaders.keySet();
for (String header : keys) {
httpPost.setHeader(header, requestHeaders.get(header));
}
}
response = sendReceiveRequest(httpPost);
output = IOUtils.toString(response.getEntity().getContent());
httpStatus = response.getStatusLine().getStatusCode();
if (log.isDebugEnabled()) {
log.debug("Invoked POST " + uri.toString() +
" - Input payload: " + payload + " - Response message: " + output);
}
EntityUtils.consume(response.getEntity());
} finally {
if (response != null) {
IOUtils.closeQuietly(response);
}
if (httpPost != null) {
httpPost.releaseConnection();
}
}
return new RESTResponse(output, httpStatus);
}
private CloseableHttpResponse sendReceiveRequest(HttpRequestBase requestBase)
throws IOException {
return client.execute(requestBase);
}
}

View File

@ -1,57 +0,0 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.apimgt.handlers.invoker;
/**
* RESTResponse class holds the data retrieved from the HTTP invoke response.
*/
public class RESTResponse {
private String content;
private int httpStatus;
/**
* Constructor
*
* @param content from the REST invoke response
* @param httpStatus from the REST invoke response
*/
RESTResponse(String content, int httpStatus) {
this.content = content;
this.httpStatus = httpStatus;
}
/**
* Get contents of the REST invoke response
*
* @return contents of the REST invoke response
*/
public String getContent() {
return content;
}
/**
* Get the HTTP Status code from REST invoke response
*
* @return int HTTP status code
*/
public int getHttpStatus() {
return httpStatus;
}
}

View File

@ -1,40 +0,0 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.apimgt.handlers.utils;
/**
* This initializes the constance.
*/
public class AuthConstants {
public static final String MDM_SIGNATURE = "mdm-signature";
public static final String PROXY_MUTUAL_AUTH_HEADER = "proxy-mutual-auth-header";
public static final String MUTUAL_AUTH_HEADER = "mutual-auth-header";
public static final String ONE_TIME_TOKEN_HEADER = "one-time-token";
public static final String ENCODED_PEM = "encoded-pem";
public static final String CALLBACK_URL = "";
public static final String CLIENT_NAME = "IOT-API-MANAGER";
public static final String GRANT_TYPE = "refresh_token password client_credentials";
public static final String TOKEN_SCOPE = "default";
public static final String CONTENT_TYPE_HEADER = "Content-Type";
public static final String CONTENT_TYPE = "application/json";
public static final String AUTHORIZATION_HEADER = "Authorization";
public static final String BASIC_AUTH_PREFIX = "Basic ";
public static final String CLIENT_ID = "clientId";
public static final String CLIENT_SECRET = "clientSecret";
public static final String CLIENT_CERTIFICATE = "ssl.client.auth.cert.X509";
}

View File

@ -1,205 +0,0 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.apimgt.handlers.utils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ws.security.util.Base64;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.wso2.carbon.apimgt.handlers.APIMCertificateMGTException;
import org.wso2.carbon.apimgt.handlers.beans.DCR;
import org.wso2.carbon.apimgt.handlers.config.IOTServerConfiguration;
import org.wso2.carbon.apimgt.handlers.invoker.RESTInvoker;
import org.wso2.carbon.apimgt.handlers.invoker.RESTResponse;
import io.entgra.device.mgt.core.certificate.mgt.core.service.CertificateManagementService;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.utils.CarbonUtils;
import javax.xml.XMLConstants;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Contains util methods for synapse gateway authentication handler
*/
public class Utils {
private static final Log log = LogFactory.getLog(Utils.class);
private static final String IOT_APIS_CONFIG_FILE = "iot-api-config.xml";
private static String clientId;
private static String clientSecret;
/**
* This method initializes the iot-api-config.xml file.
*
* @return IoTServerConfiguration Object based on the configuration file.
*/
public static IOTServerConfiguration initConfig() {
return initConfig(CarbonUtils.getCarbonConfigDirPath() + File.separator + IOT_APIS_CONFIG_FILE);
}
/**
* This methods initialized the iot-api-config.xml from provided path.
*
* @param path The actual file path of iot-api-config.xml
* @return The instance of the IOTServerConfiguration based on the configuration.
*/
public static IOTServerConfiguration initConfig(String path) {
try {
File file = new File(path);
Document doc = Utils.convertToDocument(file);
JAXBContext fileContext = JAXBContext.newInstance(IOTServerConfiguration.class);
Unmarshaller unmarshaller = fileContext.createUnmarshaller();
IOTServerConfiguration iotServerConfiguration = (IOTServerConfiguration) unmarshaller.unmarshal(
doc);
iotServerConfiguration.setHostname(replaceProperties(iotServerConfiguration.getHostname()));
iotServerConfiguration.setVerificationEndpoint(
replaceProperties(iotServerConfiguration.getVerificationEndpoint()));
iotServerConfiguration.setDynamicClientRegistrationEndpoint(
replaceProperties(iotServerConfiguration.getDynamicClientRegistrationEndpoint()));
iotServerConfiguration.setOauthTokenEndpoint(
replaceProperties(iotServerConfiguration.getOauthTokenEndpoint()));
return iotServerConfiguration;
} catch (JAXBException | APIMCertificateMGTException e) {
log.error("Error occurred while initializing Data Source config", e);
return null;
}
}
/**
* This method gets the values from system variables and sets to xml.
*/
private static String replaceProperties(String text) {
String regex = "\\$\\{(.*?)\\}";
Pattern pattern = Pattern.compile(regex);
Matcher matchPattern = pattern.matcher(text);
while (matchPattern.find()) {
String sysPropertyName = matchPattern.group(1);
String sysPropertyValue = System.getProperty(sysPropertyName);
if (sysPropertyValue != null && !sysPropertyName.isEmpty()) {
text = text.replaceAll("\\$\\{(" + sysPropertyName + ")\\}", sysPropertyValue);
}
}
return text;
}
/**
* This class build the iot-api-config.xml file.
*
* @param file The file object of iot-api-config.xml.
* @return Document instance of the file
* @throws APIMCertificateMGTException
*/
private static Document convertToDocument(File file) throws APIMCertificateMGTException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
try {
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
DocumentBuilder docBuilder = factory.newDocumentBuilder();
return docBuilder.parse(file);
} catch (Exception e) {
throw new APIMCertificateMGTException("Error occurred while parsing file, while converting " +
"to a org.w3c.dom.Document", e);
}
}
/**
* This method is used to get the base64 encoded token.
*
* @param iotServerConfiguration Instance of the IoTsererConfiguration.
* @return Access token will be returned.
*/
public static String getBase64EncodedToken(IOTServerConfiguration iotServerConfiguration) {
return Base64.encode((iotServerConfiguration.getUsername() + ":" + iotServerConfiguration.getPassword()).
getBytes());
}
/**
* This method register an application to get the client key and secret.
*
* @param iotServerConfiguration Instance of the IoTServerConfiguration.
* @throws APIMCertificateMGTException
*/
private static void getClientSecretes(IOTServerConfiguration iotServerConfiguration, RESTInvoker restInvoker)
throws APIMCertificateMGTException {
try {
String username = iotServerConfiguration.getUsername();
String password = iotServerConfiguration.getPassword();
DCR dcr = new DCR();
dcr.setOwner(iotServerConfiguration.getUsername());
dcr.setClientName(AuthConstants.CLIENT_NAME);
dcr.setGrantType(AuthConstants.GRANT_TYPE);
dcr.setTokenScope(AuthConstants.TOKEN_SCOPE);
dcr.setCallbackUrl(AuthConstants.CALLBACK_URL);
dcr.setIsSaasApp(true);
String dcrContent = dcr.toJSON();
Map<String, String> dcrHeaders = new HashMap<>();
String basicAuth = Base64.encode((username + ":" + password).getBytes());
dcrHeaders.put(AuthConstants.CONTENT_TYPE_HEADER, AuthConstants.CONTENT_TYPE);
dcrHeaders.put(AuthConstants.AUTHORIZATION_HEADER, AuthConstants.BASIC_AUTH_PREFIX + basicAuth);
URI dcrUrl = new URI(iotServerConfiguration.getDynamicClientRegistrationEndpoint());
RESTResponse response = restInvoker.invokePOST(dcrUrl, dcrHeaders, dcrContent);
if (log.isDebugEnabled()) {
log.debug("DCR response :" + response.getContent());
}
JSONObject jsonResponse = new JSONObject(response.getContent());
clientId = jsonResponse.getString(AuthConstants.CLIENT_ID);
clientSecret = jsonResponse.getString(AuthConstants.CLIENT_SECRET);
} catch (JSONException e) {
throw new APIMCertificateMGTException("Error occurred while converting the json to object", e);
} catch (IOException | URISyntaxException e) {
throw new APIMCertificateMGTException("Error occurred while trying to call DCR endpoint", e);
}
}
public static CertificateManagementService getCertificateManagementService() {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
CertificateManagementService certificateManagementService = (CertificateManagementService)
ctx.getOSGiService(CertificateManagementService.class, null);
if (certificateManagementService == null) {
String msg = "CertificateManagementAdminServiceImpl Management service not initialized.";
log.error(msg);
throw new IllegalStateException(msg);
}
return certificateManagementService;
}
}

View File

@ -1,40 +0,0 @@
<?xml version="1.0" encoding="ISO-8859-1"?>
<!--
~ Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
~
~ Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<ServerConfiguration>
<!-- IoT server host name, this is referred from APIM gateway to call to IoT server for certificate validation-->
<Hostname>https://${iot.core.host}:${iot.core.https.port}/</Hostname>
<!--End point to verify the certificate-->
<VerificationEndpoint>https://${iot.core.host}:${iot.core.https.port}/api/certificate-mgt/v1.0/admin/certificates/verify/</VerificationEndpoint>
<!--Admin username/password - this is to use for oauth token generation-->
<Username>admin</Username>
<Password>admin</Password>
<!--Dynamic client registration endpoint-->
<DynamicClientRegistrationEndpoint>https://${iot.keymanager.host}:${iot.keymanager.https.port}/client-registration/v0.12/register</DynamicClientRegistrationEndpoint>
<!--Oauth token endpoint-->
<OauthTokenEndpoint>https://${iot.keymanager.host}:${iot.keymanager.https.port}/oauth2/token</OauthTokenEndpoint>
<APIS>
<ContextPath>/services</ContextPath>
</APIS>
</ServerConfiguration>

View File

@ -1,296 +0,0 @@
/*
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.carbon.apimgt.handlers;
import com.google.gson.Gson;
import junit.framework.Assert;
import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMDocument;
import org.apache.axiom.soap.SOAPEnvelope;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.context.ConfigurationContext;
import org.apache.axis2.engine.AxisConfiguration;
import org.apache.http.ProtocolVersion;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.entity.BasicHttpEntity;
import org.apache.http.message.BasicStatusLine;
import org.apache.synapse.MessageContext;
import org.apache.synapse.config.SynapseConfigUtils;
import org.apache.synapse.config.SynapseConfiguration;
import org.apache.synapse.core.SynapseEnvironment;
import org.apache.synapse.core.axis2.Axis2MessageContext;
import org.apache.synapse.core.axis2.Axis2SynapseEnvironment;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.wso2.carbon.apimgt.handlers.beans.ValidationResponce;
import org.wso2.carbon.apimgt.handlers.invoker.RESTInvoker;
import org.wso2.carbon.apimgt.handlers.mock.MockClient;
import org.wso2.carbon.apimgt.handlers.mock.MockHttpResponse;
import org.wso2.carbon.apimgt.handlers.utils.AuthConstants;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import javax.security.cert.X509Certificate;
/**
* This testcase will focus on covering the methods of {@link AuthenticationHandler}
*/
public class AuthenticationHandlerTest extends BaseAPIHandlerTest {
private AuthenticationHandler handler;
private SynapseConfiguration synapseConfiguration;
private MockClient mockClient;
@BeforeClass
public void initTest() {
TestUtils.setSystemProperties();
this.handler = new AuthenticationHandler();
this.synapseConfiguration = new SynapseConfiguration();
}
@Test(description = "Handle request with empty transport headers")
public void testHandleRequestWithEmptyTransportHeader() throws Exception {
boolean response = this.handler.handleRequest(createSynapseMessageContext("<empty/>", this.synapseConfiguration,
new HashMap<>(), "https://test.com/testservice"));
Assert.assertFalse(response);
}
@Test(description = "Handle request with without device type",
dependsOnMethods = "testHandleRequestWithEmptyTransportHeader")
public void testHandleRequestWithoutDeviceType() throws Exception {
HashMap<String, String> transportHeaders = new HashMap<>();
transportHeaders.put(AuthConstants.MDM_SIGNATURE, "some cert");
boolean response = this.handler.handleRequest(createSynapseMessageContext("<empty/>", this.synapseConfiguration,
transportHeaders, "https://test.com/testservice"));
Assert.assertFalse(response);
}
@Test(description = "Handle request with device type URI with MDM ceritificate",
dependsOnMethods = "testHandleRequestWithoutDeviceType")
public void testHandleSuccessfulRequestMDMCertificate() throws Exception {
HashMap<String, String> transportHeaders = new HashMap<>();
transportHeaders.put(AuthConstants.MDM_SIGNATURE, "some cert");
setMockClient();
this.mockClient.setResponse(getValidationResponse());
boolean response = this.handler.handleRequest(createSynapseMessageContext("<empty/>", this.synapseConfiguration,
transportHeaders, "https://test.com/testservice/device-mgt/testdevice"));
Assert.assertTrue(response);
this.mockClient.reset();
}
@Test(description = "Handle request with device type URI with Mutual Auth Header",
dependsOnMethods = "testHandleSuccessfulRequestMDMCertificate")
public void testHandleSuccessRequestMutualAuthHeader() throws Exception {
HashMap<String, String> transportHeaders = new HashMap<>();
transportHeaders.put(AuthConstants.MUTUAL_AUTH_HEADER, "Test Header");
setMockClient();
this.mockClient.setResponse(getValidationResponse());
MessageContext messageContext = createSynapseMessageContext("<empty/>", this.synapseConfiguration,
transportHeaders, "https://test.com/testservice/device-mgt/testdevice");
org.apache.axis2.context.MessageContext axisMC = ((Axis2MessageContext) messageContext).getAxis2MessageContext();
String certStr = getContent(TestUtils.getAbsolutePathOfConfig("ra_cert.pem"));
X509Certificate cert = X509Certificate.getInstance(new ByteArrayInputStream(certStr.
getBytes(StandardCharsets.UTF_8.name())));
axisMC.setProperty(AuthConstants.CLIENT_CERTIFICATE, new X509Certificate[]{cert});
boolean response = this.handler.handleRequest(messageContext);
Assert.assertTrue(response);
this.mockClient.reset();
}
@Test(description = "Handle request with device type URI with Encoded Pem",
dependsOnMethods = "testHandleSuccessRequestMutualAuthHeader")
public void testHandleSuccessRequestEncodedPem() throws Exception {
HashMap<String, String> transportHeaders = new HashMap<>();
transportHeaders.put(AuthConstants.ENCODED_PEM, "encoded pem");
setMockClient();
this.mockClient.setResponse(getValidationResponse());
MessageContext messageContext = createSynapseMessageContext("<empty/>", this.synapseConfiguration,
transportHeaders, "https://test.com/testservice/device-mgt/testdevice");
boolean response = this.handler.handleRequest(messageContext);
Assert.assertTrue(response);
this.mockClient.reset();
}
@Test(description = "Handle request with device type URI with Encoded Pem with invalid response",
dependsOnMethods = "testHandleSuccessRequestEncodedPem")
public void testHandleSuccessRequestEncodedPemInvalidResponse() throws Exception {
HashMap<String, String> transportHeaders = new HashMap<>();
transportHeaders.put(AuthConstants.ENCODED_PEM, "encoded pem");
setMockClient();
this.mockClient.setResponse(getInvalidResponse());
MessageContext messageContext = createSynapseMessageContext("<empty/>", this.synapseConfiguration,
transportHeaders, "https://test.com/testservice/device-mgt/testdevice");
boolean response = this.handler.handleRequest(messageContext);
Assert.assertFalse(response);
this.mockClient.reset();
}
@Test(description = "Handle request with cert management exception ",
dependsOnMethods = "testHandleSuccessRequestEncodedPem")
public void testHandleRequestWithCertMgmtException() throws Exception {
HashMap<String, String> transportHeaders = new HashMap<>();
transportHeaders.put(AuthConstants.ENCODED_PEM, "encoded pem");
setMockClient();
this.mockClient.setResponse(null);
MessageContext messageContext = createSynapseMessageContext("<empty/>", this.synapseConfiguration,
transportHeaders, "https://test.com/testservice/device-mgt/testdevice");
boolean response = this.handler.handleRequest(messageContext);
Assert.assertFalse(response);
this.mockClient.reset();
}
@Test(description = "Handle request with IO exception",
dependsOnMethods = "testHandleRequestWithCertMgmtException")
public void testHandleRequestWithIOException() throws Exception {
HashMap<String, String> transportHeaders = new HashMap<>();
transportHeaders.put(AuthConstants.ENCODED_PEM, "encoded pem");
setMockClient();
this.mockClient.setResponse(null);
MessageContext messageContext = createSynapseMessageContext("<empty/>", this.synapseConfiguration,
transportHeaders, "https://test.com/testservice/device-mgt/testdevice");
boolean response = this.handler.handleRequest(messageContext);
Assert.assertFalse(response);
this.mockClient.reset();
}
@Test(description = "Handle request with URI exception",
dependsOnMethods = "testHandleRequestWithIOException")
public void testHandleRequestWithURIException() throws Exception {
TestUtils.resetSystemProperties();
HashMap<String, String> transportHeaders = new HashMap<>();
transportHeaders.put(AuthConstants.MDM_SIGNATURE, "some cert");
AuthenticationHandler handler = new AuthenticationHandler();
boolean response = handler.handleRequest(createSynapseMessageContext("<empty/>", this.synapseConfiguration,
transportHeaders, "https://test.com/testservice/device-mgt/testdevice"));
Assert.assertFalse(response);
TestUtils.setSystemProperties();
}
@Test(description = "Handle response")
public void testHandleResponse() throws Exception {
boolean response = this.handler.handleResponse(null);
Assert.assertTrue(response);
}
private static MessageContext createSynapseMessageContext(
String payload, SynapseConfiguration config, HashMap<String, String> transportHeaders,
String address) throws Exception {
org.apache.axis2.context.MessageContext mc =
new org.apache.axis2.context.MessageContext();
AxisConfiguration axisConfig = config.getAxisConfiguration();
if (axisConfig == null) {
axisConfig = new AxisConfiguration();
config.setAxisConfiguration(axisConfig);
}
ConfigurationContext cfgCtx = new ConfigurationContext(axisConfig);
SynapseEnvironment env = new Axis2SynapseEnvironment(cfgCtx, config);
MessageContext synMc = new Axis2MessageContext(mc, config, env);
SOAPEnvelope envelope =
OMAbstractFactory.getSOAP11Factory().getDefaultEnvelope();
OMDocument omDoc =
OMAbstractFactory.getSOAP11Factory().createOMDocument();
omDoc.addChild(envelope);
envelope.getBody().addChild(SynapseConfigUtils.stringToOM(payload));
synMc.setEnvelope(envelope);
synMc.setTo(new EndpointReference(address));
org.apache.axis2.context.MessageContext axis2MessageContext =
((Axis2MessageContext) synMc).getAxis2MessageContext();
axis2MessageContext.setProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS, transportHeaders);
return synMc;
}
private void setMockClient() throws NoSuchFieldException, IllegalAccessException {
Field restInvokerField = this.handler.getClass().getDeclaredField("restInvoker");
restInvokerField.setAccessible(true);
RESTInvoker restInvoker = (RESTInvoker) restInvokerField.get(this.handler);
Field clientField = restInvoker.getClass().getDeclaredField("client");
clientField.setAccessible(true);
this.mockClient = new MockClient();
clientField.set(restInvoker, this.mockClient);
}
private CloseableHttpResponse getDCRResponse() throws IOException {
CloseableHttpResponse mockDCRResponse = new MockHttpResponse();
String dcrResponseFile = TestUtils.getAbsolutePathOfConfig("dcr-response.json");
BasicHttpEntity responseEntity = new BasicHttpEntity();
responseEntity.setContent(new ByteArrayInputStream(getContent(dcrResponseFile).
getBytes(StandardCharsets.UTF_8.name())));
responseEntity.setContentType(TestUtils.CONTENT_TYPE);
mockDCRResponse.setEntity(responseEntity);
mockDCRResponse.setStatusLine(new BasicStatusLine(new ProtocolVersion("http", 1, 0), 200, "OK"));
return mockDCRResponse;
}
private CloseableHttpResponse getAccessTokenReponse() throws IOException {
CloseableHttpResponse mockDCRResponse = new MockHttpResponse();
String dcrResponseFile = TestUtils.getAbsolutePathOfConfig("accesstoken-response.json");
BasicHttpEntity responseEntity = new BasicHttpEntity();
responseEntity.setContent(new ByteArrayInputStream(getContent(dcrResponseFile).
getBytes(StandardCharsets.UTF_8.name())));
responseEntity.setContentType(TestUtils.CONTENT_TYPE);
mockDCRResponse.setEntity(responseEntity);
mockDCRResponse.setStatusLine(new BasicStatusLine(new ProtocolVersion("http", 1, 0), 200, "OK"));
return mockDCRResponse;
}
private CloseableHttpResponse getValidationResponse() throws UnsupportedEncodingException {
ValidationResponce response = new ValidationResponce();
response.setDeviceId("1234");
response.setDeviceType("testdevice");
response.setJWTToken("1234567788888888");
response.setTenantId(-1234);
Gson gson = new Gson();
String jsonReponse = gson.toJson(response);
CloseableHttpResponse mockDCRResponse = new MockHttpResponse();
BasicHttpEntity responseEntity = new BasicHttpEntity();
responseEntity.setContent(new ByteArrayInputStream(jsonReponse.getBytes(StandardCharsets.UTF_8.name())));
responseEntity.setContentType(TestUtils.CONTENT_TYPE);
mockDCRResponse.setEntity(responseEntity);
mockDCRResponse.setStatusLine(new BasicStatusLine(new ProtocolVersion("http", 1, 0), 200, "OK"));
return mockDCRResponse;
}
private CloseableHttpResponse getInvalidResponse() throws UnsupportedEncodingException {
CloseableHttpResponse mockDCRResponse = new MockHttpResponse();
BasicHttpEntity responseEntity = new BasicHttpEntity();
responseEntity.setContent(new ByteArrayInputStream("invalid response".getBytes(StandardCharsets.UTF_8.name())));
responseEntity.setContentType(TestUtils.CONTENT_TYPE);
mockDCRResponse.setEntity(responseEntity);
mockDCRResponse.setStatusLine(new BasicStatusLine(new ProtocolVersion("http", 1, 0), 400, "Bad Request"));
return mockDCRResponse;
}
private String getContent(String filePath) throws IOException {
FileReader fileReader = new FileReader(filePath);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String content = "";
String line;
while ((line = bufferedReader.readLine()) != null) {
content += line + "\n";
}
bufferedReader.close();
return content;
}
}

View File

@ -1,60 +0,0 @@
/*
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.carbon.apimgt.handlers;
import org.testng.annotations.BeforeSuite;
import org.wso2.carbon.base.MultitenantConstants;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import java.io.File;
/**
* This is the base test case for API Handler tests.
*/
public class BaseAPIHandlerTest {
@BeforeSuite
public void init() {
setUpCarbonHome();
}
private void setUpCarbonHome() {
if (System.getProperty("carbon.home") == null) {
File file = new File("src/test/resources/carbon-home");
if (file.exists()) {
System.setProperty("carbon.home", file.getAbsolutePath());
}
file = new File("carbon-home");
if (file.exists()) {
System.setProperty("carbon.home", file.getAbsolutePath());
}
file = new File("../../resources/carbon-home");
if (file.exists()) {
System.setProperty("carbon.home", file.getAbsolutePath());
}
file = new File("../../../resources/carbon-home");
if (file.exists()) {
System.setProperty("carbon.home", file.getAbsolutePath());
}
}
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(MultitenantConstants
.SUPER_TENANT_DOMAIN_NAME);
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(MultitenantConstants.SUPER_TENANT_ID);
}
}

View File

@ -1,97 +0,0 @@
/*
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.carbon.apimgt.handlers;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.wso2.carbon.apimgt.handlers.config.IOTServerConfiguration;
import org.wso2.carbon.apimgt.handlers.utils.Utils;
import java.io.File;
/**
* This class validates the behaviour of {@link IOTServerConfiguration}
*/
public class IOTServerConfigurationTest extends BaseAPIHandlerTest {
private static final String CONFIG_DIR = "carbon-home" + File.separator + "repository" + File.separator +
"conf" + File.separator;
@BeforeClass
public void initTest(){
TestUtils.resetSystemProperties();
}
@Test(description = "Validating the IoT Server configuration initialization without system properties")
public void initConfigWithoutSystemProps() {
IOTServerConfiguration serverConfiguration = Utils.initConfig();
Assert.assertTrue(serverConfiguration != null);
Assert.assertEquals(serverConfiguration.getHostname(), "https://${iot.core.host}:${iot.core.https.port}/");
Assert.assertEquals(serverConfiguration.getVerificationEndpoint(),
"https://${iot.core.host}:${iot.core.https.port}/api/certificate-mgt/v1.0/admin/certificates/verify/");
Assert.assertEquals(serverConfiguration.getUsername(), "testuser");
Assert.assertEquals(serverConfiguration.getPassword(), "testuserpwd");
Assert.assertEquals(serverConfiguration.getDynamicClientRegistrationEndpoint(),
"https://${iot.keymanager.host}:${iot.keymanager.https.port}/client-registration/v0.12/register");
Assert.assertEquals(serverConfiguration.getOauthTokenEndpoint(),
"https://${iot.keymanager.host}:${iot.keymanager.https.port}/oauth2/token");
Assert.assertEquals(serverConfiguration.getApis().size(), 1);
Assert.assertEquals(serverConfiguration.getApis().get(0).getContextPath(), "/services");
}
@Test(description = "Initializing IoT server config with invalid configuration",
dependsOnMethods = "initConfigWithoutSystemProps")
public void initConfigWithInvalidConfig() {
IOTServerConfiguration serverConfig = Utils.initConfig(TestUtils.getAbsolutePathOfConfig(CONFIG_DIR
+ "iot-api-config-invalid.xml"));
Assert.assertEquals(serverConfig, null);
}
@Test(description = "Initializing IoT server config with invalid xml",
dependsOnMethods = "initConfigWithInvalidConfig")
public void initConfigWithInvalidXMLConfig() {
IOTServerConfiguration serverConfig = Utils.initConfig(TestUtils.getAbsolutePathOfConfig(CONFIG_DIR +
"iot-api-config-invalid-xml.xml"));
Assert.assertEquals(serverConfig, null);
}
@Test(description = "Initializing IoT server config with system configs",
dependsOnMethods = "initConfigWithInvalidXMLConfig")
public void initConfigWithSystemProps() {
TestUtils.setSystemProperties();
IOTServerConfiguration serverConfiguration = Utils.initConfig();
Assert.assertTrue(serverConfiguration != null);
Assert.assertEquals(serverConfiguration.getHostname(), "https://" + TestUtils.IOT_CORE_HOST + ":"
+ TestUtils.IOT_CORE_HTTPS_PORT
+ "/");
Assert.assertEquals(serverConfiguration.getVerificationEndpoint(),
"https://" + TestUtils.IOT_CORE_HOST + ":" + TestUtils.IOT_CORE_HTTPS_PORT +
"/api/certificate-mgt/v1.0/admin/certificates/" +
"verify/");
Assert.assertEquals(serverConfiguration.getUsername(), "testuser");
Assert.assertEquals(serverConfiguration.getPassword(), "testuserpwd");
Assert.assertEquals(serverConfiguration.getDynamicClientRegistrationEndpoint(),
"https://" + TestUtils.IOT_KEYMANAGER_HOST + ":" + TestUtils.IOT_KEYMANAGER_PORT
+ "/client-registration/v0.12/register");
Assert.assertEquals(serverConfiguration.getOauthTokenEndpoint(),
"https://" + TestUtils.IOT_KEYMANAGER_HOST + ":" + TestUtils.IOT_KEYMANAGER_PORT
+ "/oauth2/token");
Assert.assertEquals(serverConfiguration.getApis().size(), 1);
Assert.assertEquals(serverConfiguration.getApis().get(0).getContextPath(), "/services");
}
}

View File

@ -1,61 +0,0 @@
/*
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.carbon.apimgt.handlers;
import org.testng.Assert;
import java.io.File;
import java.net.URL;
/**
* Utils class which provides utility methods for other testcases.
*/
public class TestUtils {
static final String IOT_CORE_HOST = "iot.core.wso2.com";
static final String IOT_CORE_HTTPS_PORT = "9443";
static final String IOT_KEYMANAGER_HOST = "iot.keymanager.wso2.com";
static final String IOT_KEYMANAGER_PORT = "9443";
static final String CONTENT_TYPE = "application/json";
private static final String IOT_HOST_PROPERTY = "iot.core.host";
private static final String IOT_PORT_PROPERTY = "iot.core.https.port";
private static final String IOT_KEY_MANAGER_HOST_PROPERTY = "iot.keymanager.host";
private static final String IOT_KEY_MANAGER_PORT_PROPERTY = "iot.keymanager.https.port";
static String getAbsolutePathOfConfig(String configFilePath) {
ClassLoader classLoader = TestUtils.class.getClassLoader();
URL invalidConfig = classLoader.getResource(configFilePath);
Assert.assertTrue(invalidConfig != null);
File file = new File(invalidConfig.getFile());
return file.getAbsolutePath();
}
static void setSystemProperties() {
System.setProperty(IOT_HOST_PROPERTY, IOT_CORE_HOST);
System.setProperty(IOT_PORT_PROPERTY, IOT_CORE_HTTPS_PORT);
System.setProperty(IOT_KEY_MANAGER_HOST_PROPERTY, IOT_KEYMANAGER_HOST);
System.setProperty(IOT_KEY_MANAGER_PORT_PROPERTY, IOT_KEYMANAGER_PORT);
}
static void resetSystemProperties() {
System.clearProperty(IOT_HOST_PROPERTY);
System.clearProperty(IOT_PORT_PROPERTY);
System.clearProperty(IOT_KEY_MANAGER_HOST_PROPERTY);
System.clearProperty(IOT_KEY_MANAGER_PORT_PROPERTY);
}
}

View File

@ -1,76 +0,0 @@
/*
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.carbon.apimgt.handlers.mock;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HttpContext;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* Mock implementation for CloseableHttpClient to be used in test cases.
*/
public class MockClient extends CloseableHttpClient {
private List<CloseableHttpResponse> responses = new ArrayList<>();
private int responseCount = 0;
@Override
protected CloseableHttpResponse doExecute(HttpHost httpHost, HttpRequest httpRequest, HttpContext httpContext)
throws IOException {
if (this.responseCount < this.responses.size()) {
this.responseCount++;
CloseableHttpResponse response = this.responses.get(this.responseCount - 1);
if (response == null) {
throw new IOException("test exception");
}
return response;
} else {
return new MockHttpResponse();
}
}
@Override
public void close() throws IOException {
}
@Override
public HttpParams getParams() {
return null;
}
@Override
public ClientConnectionManager getConnectionManager() {
return null;
}
public void setResponse(CloseableHttpResponse reponse) {
this.responses.add(reponse);
}
public void reset() {
this.responses.clear();
this.responseCount = 0;
}
}

View File

@ -1,178 +0,0 @@
/*
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.carbon.apimgt.handlers.mock;
import org.apache.http.Header;
import org.apache.http.HeaderIterator;
import org.apache.http.HttpEntity;
import org.apache.http.ProtocolVersion;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.params.HttpParams;
import java.io.IOException;
import java.util.Locale;
/**
* Mock http response to be used in the test cases.
*
*/
public class MockHttpResponse implements CloseableHttpResponse {
private HttpEntity httpEntity;
private StatusLine statusLine;
@Override
public void close() throws IOException {
}
@Override
public StatusLine getStatusLine() {
return this.statusLine;
}
@Override
public void setStatusLine(StatusLine statusLine) {
this.statusLine = statusLine;
}
@Override
public void setStatusLine(ProtocolVersion protocolVersion, int i) {
}
@Override
public void setStatusLine(ProtocolVersion protocolVersion, int i, String s) {
}
@Override
public void setStatusCode(int i) throws IllegalStateException {
}
@Override
public void setReasonPhrase(String s) throws IllegalStateException {
}
@Override
public HttpEntity getEntity() {
return this.httpEntity;
}
@Override
public void setEntity(HttpEntity httpEntity) {
this.httpEntity = httpEntity;
}
@Override
public Locale getLocale() {
return null;
}
@Override
public void setLocale(Locale locale) {
}
@Override
public ProtocolVersion getProtocolVersion() {
return null;
}
@Override
public boolean containsHeader(String s) {
return false;
}
@Override
public Header[] getHeaders(String s) {
return new Header[0];
}
@Override
public Header getFirstHeader(String s) {
return null;
}
@Override
public Header getLastHeader(String s) {
return null;
}
@Override
public Header[] getAllHeaders() {
return new Header[0];
}
@Override
public void addHeader(Header header) {
}
@Override
public void addHeader(String s, String s1) {
}
@Override
public void setHeader(Header header) {
}
@Override
public void setHeader(String s, String s1) {
}
@Override
public void setHeaders(Header[] headers) {
}
@Override
public void removeHeader(Header header) {
}
@Override
public void removeHeaders(String s) {
}
@Override
public HeaderIterator headerIterator() {
return null;
}
@Override
public HeaderIterator headerIterator(String s) {
return null;
}
@Override
public HttpParams getParams() {
return null;
}
@Override
public void setParams(HttpParams httpParams) {
}
}

View File

@ -1,7 +0,0 @@
{
"scope": "API_SUBSCRIBER_SCOPE",
"token_type": "Bearer",
"expires_in": 3600,
"refresh_token": "33c3be152ebf0030b3fb76f2c1f80bf8",
"access_token": "292ff0fd256814536baca0926f483c8d"
}

View File

@ -1,658 +0,0 @@
<?xml version="1.0" encoding="ISO-8859-1"?>
<!--
~ Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
~
~ Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<!--
This is the main server configuration file
${carbon.home} represents the carbon.home system property.
Other system properties can be specified in a similar manner.
-->
<Server xmlns="http://wso2.org/projects/carbon/carbon.xml">
<!--
Product Name
-->
<Name>${product.name}</Name>
<!--
machine readable unique key to identify each product
-->
<ServerKey>${product.key}</ServerKey>
<!--
Product Version
-->
<Version>${product.version}</Version>
<!--
Host name or IP address of the machine hosting this server
e.g. www.wso2.org, 192.168.1.10
This is will become part of the End Point Reference of the
services deployed on this server instance.
-->
<!--HostName>www.wso2.org</HostName-->
<!--
Host name to be used for the Carbon management console
-->
<!--MgtHostName>mgt.wso2.org</MgtHostName-->
<!--
The URL of the back end server. This is where the admin services are hosted and
will be used by the clients in the front end server.
This is required only for the Front-end server. This is used when seperating BE server from FE server
-->
<ServerURL>local:/${carbon.context}/services/</ServerURL>
<!--
<ServerURL>https://${carbon.local.ip}:${carbon.management.port}${carbon.context}/services/</ServerURL>
-->
<!--
The URL of the index page. This is where the user will be redirected after signing in to the
carbon server.
-->
<!-- IndexPageURL>/carbon/admin/index.jsp</IndexPageURL-->
<!--
For cApp deployment, we have to identify the roles that can be acted by the current server.
The following property is used for that purpose. Any number of roles can be defined here.
Regular expressions can be used in the role.
Ex : <Role>.*</Role> means this server can act any role
-->
<ServerRoles>
<Role>${default.server.role}</Role>
</ServerRoles>
<!-- uncommnet this line to subscribe to a bam instance automatically -->
<!--<BamServerURL>https://bamhost:bamport/services/</BamServerURL>-->
<!--
The fully qualified name of the server
-->
<Package>org.wso2.carbon</Package>
<!--
Webapp context root of WSO2 Carbon management console.
-->
<WebContextRoot>/</WebContextRoot>
<!--
Proxy context path is a useful parameter to add a proxy path when a Carbon server is fronted by reverse proxy. In addtion
to the proxy host and proxy port this parameter allows you add a path component to external URLs. e.g.
URL of the Carbon server -> https://10.100.1.1:9443/carbon
URL of the reverse proxy -> https://prod.abc.com/appserver/carbon
appserver - proxy context path. This specially required whenever you are generating URLs to displace in
Carbon UI components.
-->
<!--
<MgtProxyContextPath></MgtProxyContextPath>
<ProxyContextPath></ProxyContextPath>
-->
<!-- In-order to get the registry http Port from the back-end when the default http transport is not the same-->
<!--RegistryHttpPort>9763</RegistryHttpPort-->
<!--
Number of items to be displayed on a management console page. This is used at the
backend server for pagination of various items.
-->
<ItemsPerPage>15</ItemsPerPage>
<!-- The endpoint URL of the cloud instance management Web service -->
<!--<InstanceMgtWSEndpoint>https://ec2.amazonaws.com/</InstanceMgtWSEndpoint>-->
<!--
Ports used by this server
-->
<Ports>
<!-- Ports offset. This entry will set the value of the ports defined below to
the define value + Offset.
e.g. Offset=2 and HTTPS port=9443 will set the effective HTTPS port to 9445
-->
<Offset>0</Offset>
<!-- The JMX Ports -->
<JMX>
<!--The port RMI registry is exposed-->
<RMIRegistryPort>9999</RMIRegistryPort>
<!--The port RMI server should be exposed-->
<RMIServerPort>11111</RMIServerPort>
</JMX>
<!-- Embedded LDAP server specific ports -->
<EmbeddedLDAP>
<!-- Port which embedded LDAP server runs -->
<LDAPServerPort>10389</LDAPServerPort>
<!-- Port which KDC (Kerberos Key Distribution Center) server runs -->
<KDCServerPort>8000</KDCServerPort>
</EmbeddedLDAP>
<!--
Override datasources JNDIproviderPort defined in bps.xml and datasources.properties files
-->
<!--<JNDIProviderPort>2199</JNDIProviderPort>-->
<!--Override receive port of thrift based entitlement service.-->
<ThriftEntitlementReceivePort>10500</ThriftEntitlementReceivePort>
</Ports>
<!--
JNDI Configuration
-->
<JNDI>
<!--
The fully qualified name of the default initial context factory
-->
<DefaultInitialContextFactory>org.wso2.carbon.tomcat.jndi.CarbonJavaURLContextFactory</DefaultInitialContextFactory>
<!--
The restrictions that are done to various JNDI Contexts in a Multi-tenant environment
-->
<Restrictions>
<!--
Contexts that will be available only to the super-tenant
-->
<!-- <SuperTenantOnly>
<UrlContexts>
<UrlContext>
<Scheme>foo</Scheme>
</UrlContext>
<UrlContext>
<Scheme>bar</Scheme>
</UrlContext>
</UrlContexts>
</SuperTenantOnly> -->
<!--
Contexts that are common to all tenants
-->
<AllTenants>
<UrlContexts>
<UrlContext>
<Scheme>java</Scheme>
</UrlContext>
<!-- <UrlContext>
<Scheme>foo</Scheme>
</UrlContext> -->
</UrlContexts>
</AllTenants>
<!--
All other contexts not mentioned above will be available on a per-tenant basis
(i.e. will not be shared among tenants)
-->
</Restrictions>
</JNDI>
<!--
Property to determine if the server is running an a cloud deployment environment.
This property should only be used to determine deployment specific details that are
applicable only in a cloud deployment, i.e when the server deployed *-as-a-service.
-->
<IsCloudDeployment>false</IsCloudDeployment>
<!--
Property to determine whether usage data should be collected for metering purposes
-->
<EnableMetering>false</EnableMetering>
<!-- The Max time a thread should take for execution in seconds -->
<MaxThreadExecutionTime>600</MaxThreadExecutionTime>
<!--
A flag to enable or disable Ghost Deployer. By default this is set to false. That is
because the Ghost Deployer works only with the HTTP/S transports. If you are using
other transports, don't enable Ghost Deployer.
-->
<GhostDeployment>
<Enabled>false</Enabled>
</GhostDeployment>
<!--
Eager loading or lazy loading is a design pattern commonly used in computer programming which
will initialize an object upon creation or load on-demand. In carbon, lazy loading is used to
load tenant when a request is received only. Similarly Eager loading is used to enable load
existing tenants after carbon server starts up. Using this feature, you will be able to include
or exclude tenants which are to be loaded when server startup.
We can enable only one LoadingPolicy at a given time.
1. Tenant Lazy Loading
This is the default behaviour and enabled by default. With this policy, tenants are not loaded at
server startup, but loaded based on-demand (i.e when a request is received for a tenant).
The default tenant idle time is 30 minutes.
2. Tenant Eager Loading
This is by default not enabled. It can be be enabled by un-commenting the <EagerLoading> section.
The eager loading configurations supported are as below. These configurations can be given as the
value for <Include> element with eager loading.
(i)Load all tenants when server startup - *
(ii)Load all tenants except foo.com & bar.com - *,!foo.com,!bar.com
(iii)Load only foo.com & bar.com to be included - foo.com,bar.com
-->
<Tenant>
<LoadingPolicy>
<LazyLoading>
<IdleTime>30</IdleTime>
</LazyLoading>
<!-- <EagerLoading>
<Include>*,!foo.com,!bar.com</Include>
</EagerLoading>-->
</LoadingPolicy>
</Tenant>
<!--
Caching related configurations
-->
<Cache>
<!-- Default cache timeout in minutes -->
<DefaultCacheTimeout>15</DefaultCacheTimeout>
</Cache>
<!--
Axis2 related configurations
-->
<Axis2Config>
<!--
Location of the Axis2 Services & Modules repository
This can be a directory in the local file system, or a URL.
e.g.
1. /home/wso2wsas/repository/ - An absolute path
2. repository - In this case, the path is relative to CARBON_HOME
3. file:///home/wso2wsas/repository/
4. http://wso2wsas/repository/
-->
<RepositoryLocation>${carbon.home}/repository/deployment/server/</RepositoryLocation>
<!--
Deployment update interval in seconds. This is the interval between repository listener
executions.
-->
<DeploymentUpdateInterval>15</DeploymentUpdateInterval>
<!--
Location of the main Axis2 configuration descriptor file, a.k.a. axis2.xml file
This can be a file on the local file system, or a URL
e.g.
1. /home/repository/axis2.xml - An absolute path
2. conf/axis2.xml - In this case, the path is relative to CARBON_HOME
3. file:///home/carbon/repository/axis2.xml
4. http://repository/conf/axis2.xml
-->
<ConfigurationFile>${carbon.home}/repository/conf/axis2/axis2.xml</ConfigurationFile>
<!--
ServiceGroupContextIdleTime, which will be set in ConfigurationContex
for multiple clients which are going to access the same ServiceGroupContext
Default Value is 30 Sec.
-->
<ServiceGroupContextIdleTime>30000</ServiceGroupContextIdleTime>
<!--
This repository location is used to crete the client side configuration
context used by the server when calling admin services.
-->
<ClientRepositoryLocation>${carbon.home}/repository/deployment/client/</ClientRepositoryLocation>
<!-- This axis2 xml is used in createing the configuration context by the FE server
calling to BE server -->
<clientAxis2XmlLocation>${carbon.home}/repository/conf/axis2/axis2_client.xml</clientAxis2XmlLocation>
<!-- If this parameter is set, the ?wsdl on an admin service will not give the admin service wsdl. -->
<HideAdminServiceWSDLs>true</HideAdminServiceWSDLs>
<!--WARNING-Use With Care! Uncommenting bellow parameter would expose all AdminServices in HTTP transport.
With HTTP transport your credentials and data routed in public channels are vulnerable for sniffing attacks.
Use bellow parameter ONLY if your communication channels are confirmed to be secured by other means -->
<!--HttpAdminServices>*</HttpAdminServices-->
</Axis2Config>
<!--
The default user roles which will be created when the server
is started up for the first time.
-->
<ServiceUserRoles>
<Role>
<Name>admin</Name>
<Description>Default Administrator Role</Description>
</Role>
<Role>
<Name>user</Name>
<Description>Default User Role</Description>
</Role>
</ServiceUserRoles>
<!--
Enable following config to allow Emails as usernames.
-->
<!--EnableEmailUserName>true</EnableEmailUserName-->
<!--
Security configurations
-->
<Security>
<!--
KeyStore which will be used for encrypting/decrypting passwords
and other sensitive information.
-->
<KeyStore>
<!-- Keystore file location-->
<Location>${carbon.home}/repository/resources/security/wso2carbon.jks</Location>
<!-- Keystore type (JKS/PKCS12 etc.)-->
<Type>JKS</Type>
<!-- Keystore password-->
<Password>wso2carbon</Password>
<!-- Private Key alias-->
<KeyAlias>wso2carbon</KeyAlias>
<!-- Private Key password-->
<KeyPassword>wso2carbon</KeyPassword>
</KeyStore>
<!--
System wide trust-store which is used to maintain the certificates of all
the trusted parties.
-->
<TrustStore>
<!-- trust-store file location -->
<Location>${carbon.home}/repository/resources/security/client-truststore.jks</Location>
<!-- trust-store type (JKS/PKCS12 etc.) -->
<Type>JKS</Type>
<!-- trust-store password -->
<Password>wso2carbon</Password>
</TrustStore>
<!--
The Authenticator configuration to be used at the JVM level. We extend the
java.net.Authenticator to make it possible to authenticate to given servers and
proxies.
-->
<NetworkAuthenticatorConfig>
<!--
Below is a sample configuration for a single authenticator. Please note that
all child elements are mandatory. Not having some child elements would lead to
exceptions at runtime.
-->
<!-- <Credential> -->
<!--
the pattern that would match a subset of URLs for which this authenticator
would be used
-->
<!-- <Pattern>regularExpression</Pattern> -->
<!--
the type of this authenticator. Allowed values are:
1. server
2. proxy
-->
<!-- <Type>proxy</Type> -->
<!-- the username used to log in to server/proxy -->
<!-- <Username>username</Username> -->
<!-- the password used to log in to server/proxy -->
<!-- <Password>password</Password> -->
<!-- </Credential> -->
</NetworkAuthenticatorConfig>
<!--
The Tomcat realm to be used for hosted Web applications. Allowed values are;
1. UserManager
2. Memory
If this is set to 'UserManager', the realm will pick users & roles from the system's
WSO2 User Manager. If it is set to 'memory', the realm will pick users & roles from
CARBON_HOME/repository/conf/tomcat/tomcat-users.xml
-->
<TomcatRealm>UserManager</TomcatRealm>
<!--Option to disable storing of tokens issued by STS-->
<DisableTokenStore>false</DisableTokenStore>
<!--
Security token store class name. If this is not set, default class will be
org.wso2.carbon.security.util.SecurityTokenStore
-->
<!--TokenStoreClassName>org.wso2.carbon.identity.sts.store.DBTokenStore</TokenStoreClassName-->
</Security>
<!--
The temporary work directory
-->
<WorkDirectory>${carbon.home}/tmp/work</WorkDirectory>
<!--
House-keeping configuration
-->
<HouseKeeping>
<!--
true - Start House-keeping thread on server startup
false - Do not start House-keeping thread on server startup.
The user will run it manually as and when he wishes.
-->
<AutoStart>true</AutoStart>
<!--
The interval in *minutes*, between house-keeping runs
-->
<Interval>10</Interval>
<!--
The maximum time in *minutes*, temp files are allowed to live
in the system. Files/directories which were modified more than
"MaxTempFileLifetime" minutes ago will be removed by the
house-keeping task
-->
<MaxTempFileLifetime>30</MaxTempFileLifetime>
</HouseKeeping>
<!--
Configuration for handling different types of file upload & other file uploading related
config parameters.
To map all actions to a particular FileUploadExecutor, use
<Action>*</Action>
-->
<FileUploadConfig>
<!--
The total file upload size limit in MB
-->
<TotalFileSizeLimit>100</TotalFileSizeLimit>
<Mapping>
<Actions>
<Action>keystore</Action>
<Action>certificate</Action>
<Action>*</Action>
</Actions>
<Class>org.wso2.carbon.ui.transports.fileupload.AnyFileUploadExecutor</Class>
</Mapping>
<Mapping>
<Actions>
<Action>jarZip</Action>
</Actions>
<Class>org.wso2.carbon.ui.transports.fileupload.JarZipUploadExecutor</Class>
</Mapping>
<Mapping>
<Actions>
<Action>dbs</Action>
</Actions>
<Class>org.wso2.carbon.ui.transports.fileupload.DBSFileUploadExecutor</Class>
</Mapping>
<Mapping>
<Actions>
<Action>tools</Action>
</Actions>
<Class>org.wso2.carbon.ui.transports.fileupload.ToolsFileUploadExecutor</Class>
</Mapping>
<Mapping>
<Actions>
<Action>toolsAny</Action>
</Actions>
<Class>org.wso2.carbon.ui.transports.fileupload.ToolsAnyFileUploadExecutor</Class>
</Mapping>
</FileUploadConfig>
<!--
Processors which process special HTTP GET requests such as ?wsdl, ?policy etc.
In order to plug in a processor to handle a special request, simply add an entry to this
section.
The value of the Item element is the first parameter in the query string(e.g. ?wsdl)
which needs special processing
The value of the Class element is a class which implements
org.wso2.carbon.transport.HttpGetRequestProcessor
-->
<HttpGetRequestProcessors>
<Processor>
<Item>info</Item>
<Class>org.wso2.carbon.core.transports.util.InfoProcessor</Class>
</Processor>
<Processor>
<Item>wsdl</Item>
<Class>org.wso2.carbon.core.transports.util.Wsdl11Processor</Class>
</Processor>
<Processor>
<Item>wsdl2</Item>
<Class>org.wso2.carbon.core.transports.util.Wsdl20Processor</Class>
</Processor>
<Processor>
<Item>xsd</Item>
<Class>org.wso2.carbon.core.transports.util.XsdProcessor</Class>
</Processor>
</HttpGetRequestProcessors>
<!-- Deployment Synchronizer Configuration. t Enabled value to true when running with "svn based" dep sync.
In master nodes you need to set both AutoCommit and AutoCheckout to true
and in worker nodes set only AutoCheckout to true.
-->
<DeploymentSynchronizer>
<Enabled>false</Enabled>
<AutoCommit>false</AutoCommit>
<AutoCheckout>true</AutoCheckout>
<RepositoryType>svn</RepositoryType>
<SvnUrl>http://svnrepo.example.com/repos/</SvnUrl>
<SvnUser>username</SvnUser>
<SvnPassword>password</SvnPassword>
<SvnUrlAppendTenantId>true</SvnUrlAppendTenantId>
</DeploymentSynchronizer>
<!-- Deployment Synchronizer Configuration. Uncomment the following section when running with "registry based" dep sync.
In master nodes you need to set both AutoCommit and AutoCheckout to true
and in worker nodes set only AutoCheckout to true.
-->
<!--<DeploymentSynchronizer>
<Enabled>true</Enabled>
<AutoCommit>false</AutoCommit>
<AutoCheckout>true</AutoCheckout>
</DeploymentSynchronizer>-->
<!-- Mediation persistence configurations. Only valid if mediation features are available i.e. ESB -->
<!--<MediationConfig>
<LoadFromRegistry>false</LoadFromRegistry>
<SaveToFile>false</SaveToFile>
<Persistence>enabled</Persistence>
<RegistryPersistence>enabled</RegistryPersistence>
</MediationConfig>-->
<!--
Server intializing code, specified as implementation classes of org.wso2.carbon.core.ServerInitializer.
This code will be run when the Carbon server is initialized
-->
<ServerInitializers>
<!--<Initializer></Initializer>-->
</ServerInitializers>
<!--
Indicates whether the Carbon Servlet is required by the system, and whether it should be
registered
-->
<RequireCarbonServlet>${require.carbon.servlet}</RequireCarbonServlet>
<!--
Carbon H2 OSGI Configuration
By default non of the servers start.
name="web" - Start the web server with the H2 Console
name="webPort" - The port (default: 8082)
name="webAllowOthers" - Allow other computers to connect
name="webSSL" - Use encrypted (HTTPS) connections
name="tcp" - Start the TCP server
name="tcpPort" - The port (default: 9092)
name="tcpAllowOthers" - Allow other computers to connect
name="tcpSSL" - Use encrypted (SSL) connections
name="pg" - Start the PG server
name="pgPort" - The port (default: 5435)
name="pgAllowOthers" - Allow other computers to connect
name="trace" - Print additional trace information; for all servers
name="baseDir" - The base directory for H2 databases; for all servers
-->
<!--H2DatabaseConfiguration>
<property name="web" />
<property name="webPort">8082</property>
<property name="webAllowOthers" />
<property name="webSSL" />
<property name="tcp" />
<property name="tcpPort">9092</property>
<property name="tcpAllowOthers" />
<property name="tcpSSL" />
<property name="pg" />
<property name="pgPort">5435</property>
<property name="pgAllowOthers" />
<property name="trace" />
<property name="baseDir">${carbon.home}</property>
</H2DatabaseConfiguration-->
<!--Disabling statistics reporter by default-->
<StatisticsReporterDisabled>true</StatisticsReporterDisabled>
<!-- Enable accessing Admin Console via HTTP -->
<!-- EnableHTTPAdminConsole>true</EnableHTTPAdminConsole -->
<!--
Default Feature Repository of WSO2 Carbon.
-->
<FeatureRepository>
<RepositoryName>default repository</RepositoryName>
<RepositoryURL>${p2.repo.url}</RepositoryURL>
</FeatureRepository>
<!--
Configure API Management
-->
<APIManagement>
<!--Uses the embedded API Manager by default. If you want to use an external
API Manager instance to manage APIs, configure below externalAPIManager-->
<Enabled>true</Enabled>
<!--Uncomment and configure API Gateway and
Publisher URLs to use external API Manager instance-->
<!--ExternalAPIManager>
<APIGatewayURL>http://localhost:8281</APIGatewayURL>
<APIPublisherURL>http://localhost:8281/publisher</APIPublisherURL>
</ExternalAPIManager-->
<LoadAPIContextsInServerStartup>true</LoadAPIContextsInServerStartup>
</APIManagement>
</Server>

View File

@ -1,40 +0,0 @@
<?xml version="1.0" encoding="ISO-8859-1"?>
<!--
~ Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
~
~ Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<ServerConfig>
<!-- IoT server host name, this is referred from APIM gateway to call to IoT server for certificate validation-->
<Hostname>https://${iot.core.host}:${iot.core.https.port}/</Hostname>
<!--End point to verify the certificate-->
<VerificationEndpoint>https://${iot.core.host}:${iot.core.https.port}/api/certificate-mgt/v1.0/admin/certificates/verify/</VerificationEndpoint>
<!--Admin username/password - this is to use for oauth token generation-->
<Username>testuser</Username>
<Password>testuserpwd</Password>
<!--Dynamic client registration endpoint-->
<DynamicClientRegistrationEndpoint>https://${iot.keymanager.host}:${iot.keymanager.https.port}/client-registration/v0.12/register</DynamicClientRegistrationEndpoint>
<!--Oauth token endpoint-->
<OauthTokenEndpoint>https://${iot.keymanager.host}:${iot.keymanager.https.port}/oauth2/token</OauthTokenEndpoint>
<APIS>
<ContextPath>/services</ContextPath>
</APIS>
</ServerConfig

View File

@ -1,40 +0,0 @@
<?xml version="1.0" encoding="ISO-8859-1"?>
<!--
~ Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
~
~ Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<ServerConfig>
<!-- IoT server host name, this is referred from APIM gateway to call to IoT server for certificate validation-->
<Hostname>https://${iot.core.host}:${iot.core.https.port}/</Hostname>
<!--End point to verify the certificate-->
<VerificationEndpoint>https://${iot.core.host}:${iot.core.https.port}/api/certificate-mgt/v1.0/admin/certificates/verify/</VerificationEndpoint>
<!--Admin username/password - this is to use for oauth token generation-->
<Username>testuser</Username>
<Password>testuserpwd</Password>
<!--Dynamic client registration endpoint-->
<DynamicClientRegistrationEndpoint>https://${iot.keymanager.host}:${iot.keymanager.https.port}/client-registration/v0.12/register</DynamicClientRegistrationEndpoint>
<!--Oauth token endpoint-->
<OauthTokenEndpoint>https://${iot.keymanager.host}:${iot.keymanager.https.port}/oauth2/token</OauthTokenEndpoint>
<APIS>
<ContextPath>/services</ContextPath>
</APIS>
</ServerConfig>

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