From 4b637f387bd5ddc2f0c6cb2a439e48f8a0e2df56 Mon Sep 17 00:00:00 2001 From: Reshmi V Nair <54312456+reshmi-nair@users.noreply.github.com> Date: Mon, 22 Nov 2021 18:20:36 +0530 Subject: [PATCH] Merging Release 4.4.0 to master (#991) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * SB-26939:Backward compatibility issue (#965) * SB-26939:Backward compatibility issue * Issue #SB-000 feat:merge rel-4.3 to rel-4.4 (#971) * Issue #SB-000 feat:code refactoring (#972) * Issue #SB-000 feat:code refactoring * Log issue fix (#973) * Issue #SB-000 feat:code refactoring * SB-26474 Support for multiple Consent Statuses (#974) * SB-26474 Support for multiple Consent Statuses * SB-26138 Revoke consent when user migrates from Custodian to State tenant (#975) * SB-26138 Revoke consent when migrates from Custodian to State tenant * Issue #SB-000 feat: added request context to Auth Verifier class (#976) * Issue #SB-000 feat: added request context to Auth Verifier clas * Issue #SB-000 feat: added request context to Auth Verifier clas * Issue #SB-000 feat: added request context to Auth Verifier clas * Issue #SB-000 feat: added request context to Auth Verifier clas * Issue #SB-000 feat: added request context to Auth Verifier clas * Issue #SB-000 feat: added request context to Auth Verifier clas * Issue #SB-000 feat: added request context to Auth Verifier clas * Issue #SB-000 feat: added request context to Auth Verifier clas * Issue #SB-000 feat: added request context to Auth Verifier clas * Issue #SB-000 feat: added request context to Auth Verifier clas * SB-26640 Ability for users to be able to select multiple sub-roles - api changes (#977) * SB-26640 Ability for users to be able to select multiple sub-roles - backend changes * Issue #SB-26822 feat:removed printing email to log (#978) * Issue #SB-000 feat:removed printing email to log * SB-27373 All versions of create API is allowing to create users with multiple user-types (#979) * SB-27372 All versions of create API is allowing to create users with multiple user-types * SB-27372 Add test cases * SB-27372 Fixed test cases * SB-27415 feat:fixing email subject issue (#980) * Issue #SB-27415 feat:fixing email subject issue * SB-27483 : Removed duplicates from userProfileTypes (#982) * Issue #SB-27483 feat: Removed duplicates from userProfileTypes * Issue #SB-27483 feat: Removed duplicates from userProfileTypes (#985) * Issue #SB-27483 feat: Removed duplicates from userProfileTypes * Issue #SB-27483 feat: Removed duplicates from userProfileTypes * SB-27483 : Remove userProfiles update from user v2/v1 update API (#986) * Issue #SB-27483 feat: Removed duplicates from userProfileTypes * Issue #SB-27483 feat: Removed duplicates from userProfileTypes * Issue #SB-27483 feat: Removed duplicates from userProfileTypes * SB-27485 New v3 upadte API is allowing to give subtype for teacher, s… (#987) * SB-27485 New v3 upadte API is allowing to give subtype for teacher, student and parent * SB-27485 Fixing testcase issues * SB-27485 New v3 upadte API is allowing to give subtype for teacher, student and parent (#988) * SB-27485 New v3 upadte API is allowing to give subtype for teacher, student and parent * SB-27485 Fixing testcase issues * SB-27485 New v3 upadte API is allowing to give subtype for teacher, student and parent * SB-27485 [Update API] New v3 upadte API is allowing to give subtype for teacher, student and parent * SB-27485 [Update API] New v3 upadte API is allowing to give subtype for teacher, student and parent (#989) * SB-27485 [Update API] New v3 upadte API is allowing to give subtype for teacher, student and parent * SB-27641: Revert learner feed service (#990) * SB-27641: Revert learner feed service #990 Co-authored-by: sknirmalkar89 <59080585+sknirmalkar89@users.noreply.github.com> Co-authored-by: AMIT KUMAR <amit.kumar@tarento.com> --- .github/pull_request_template.md | 33 ++ .github/workflows/jira-description-action.yml | 16 + .../app/controllers/BaseController.java | 5 +- .../otp/validator/OtpRequestValidator.java | 10 +- .../usermanagement/UserController.java | 23 +- .../UserConsentRequestValidator.java | 3 +- controller/app/modules/OnRequestHandler.java | 118 +++-- controller/app/util/PrintEntryExitLog.java | 13 +- controller/app/util/RequestInterceptor.java | 14 +- controller/conf/application.conf | 266 +++++++++- controller/conf/routes | 1 + .../test/controllers/BaseApplicationTest.java | 4 +- .../BulkUploadControllerTest.java | 12 +- .../healthmanager/HealthControllerTest.java | 3 +- .../location/LocationControllerTest.java | 3 +- .../EmailServiceControllerTest.java | 12 +- .../validator/OtpRequestValidatorTest.java | 19 + .../storage/FileStorageControllerTest.java | 3 +- .../controllers/sync/SyncControllerTest.java | 6 +- .../usermanagement/UserControllerTest.java | 11 + .../test/util/RequestInterceptorTest.java | 43 +- .../org/sunbird/actor/core/BaseActor.java | 3 +- .../cassandraimpl/CassandraDACImpl.java | 2 +- .../cassandraimpl/CassandraOperationImpl.java | 2 +- .../common/CassandraPropertyReader.java | 2 +- .../org/sunbird/common/CassandraUtil.java | 2 +- .../CassandraConnectionManagerImpl.java | 4 +- .../resources/cassandratablecolumn.properties | 3 +- .../sunbird/common/ElasticSearchHelper.java | 6 +- .../common/ElasticSearchRestHighImpl.java | 2 +- .../org/sunbird/helper/ConnectionManager.java | 2 +- .../sms/providerimpl/Msg91SmsProvider.java | 2 +- .../providerimpl/NICGatewaySmsProvider.java | 2 +- .../sunbird/notification/utils/JsonUtil.java | 2 +- .../notification/utils/PropertiesCache.java | 2 +- .../notification/utils/SmsTemplateUtil.java | 4 +- .../auth/verifier/AccessTokenValidator.java | 98 +++- .../org/sunbird/auth/verifier/CryptoUtil.java | 19 +- .../org/sunbird/auth/verifier/KeyManager.java | 6 +- .../sunbird/azure/AzureConnectionManager.java | 2 +- .../org/sunbird/azure/AzureFileUtility.java | 2 +- .../sunbird/azure/CloudServiceFactory.java | 4 +- .../impl/DefaultDecryptionServiceImpl.java | 2 +- .../org/sunbird/exception/ResponseCode.java | 1 + .../sunbird/exception/ResponseMessage.java | 2 + .../java/org/sunbird/http/HttpClientUtil.java | 72 ++- .../main/java/org/sunbird/keys/JsonKey.java | 11 +- .../org/sunbird/mail/SendgridConnection.java | 2 +- .../sunbird/operations/ActorOperations.java | 1 + .../sso/KeyCloakConnectionProvider.java | 4 +- .../sso/KeycloakBruteForceAttackUtil.java | 2 +- .../sso/KeycloakRequiredActionLinkUtil.java | 5 +- .../java/org/sunbird/sso/KeycloakUtil.java | 2 +- .../telemetry/util/TelemetryGenerator.java | 4 +- .../telemetry/util/TelemetryWriter.java | 10 +- .../validator/TelemetryObjectValidatorV3.java | 4 +- .../java/org/sunbird/url/URLShortnerImpl.java | 6 +- .../org/sunbird/validator/PhoneValidator.java | 2 +- .../resources/externalresource.properties | 2 +- .../verifier/AccessTokenValidatorTest.java | 57 ++- .../sunbird/auth/verifier/CryptoUtilTest.java | 11 +- .../sunbird/actor/BackgroundJobManager.java | 5 +- .../org/sunbird/actor/feed/UserFeedActor.java | 16 +- .../sunbird/actor/location/LocationActor.java | 23 +- .../location/LocationBackgroundActor.java | 2 +- .../validator/LocationRequestValidator.java | 78 ++- .../actor/notes/NotesManagementActor.java | 2 +- .../BackGroundNotificationActor.java | 12 +- .../actor/notification/EmailServiceActor.java | 9 +- .../notification/SendNotificationActor.java | 2 +- .../OrganisationBackgroundActor.java | 4 +- .../OrganisationManagementActor.java | 4 +- .../OrganisationRequestValidator.java | 482 +++++++++--------- .../java/org/sunbird/actor/otp/OTPActor.java | 57 +-- .../org/sunbird/actor/otp/SendOTPActor.java | 22 +- .../actor/role/FetchUserRoleActor.java | 3 +- .../org/sunbird/actor/role/UserRoleActor.java | 2 +- .../actor/role/UserRoleBackgroundActor.java | 3 +- .../actor/search/SearchHandlerActor.java | 8 +- .../actor/sync/EsSyncBackgroundActor.java | 6 +- .../systemsettings/SystemSettingsActor.java | 2 +- .../TenantPreferenceManagementActor.java | 2 +- .../actor/user/IdentifierFreeUpActor.java | 4 +- .../sunbird/actor/user/ManagedUserActor.java | 86 ++-- .../actor/user/ResetPasswordActor.java | 4 +- .../actor/user/SSOUserCreateActor.java | 36 +- .../actor/user/SSUUserCreateActor.java | 83 ++- .../actor/user/TenantMigrationActor.java | 45 +- .../actor/user/UserBackgroundJobActor.java | 10 +- .../org/sunbird/actor/user/UserBaseActor.java | 29 +- .../user/UserExternalIdManagementActor.java | 2 +- .../sunbird/actor/user/UserMergeActor.java | 19 +- .../user/UserOnboardingNotificationActor.java | 2 +- .../actor/user/UserOrgManagementActor.java | 2 +- .../actor/user/UserProfileReadActor.java | 6 +- .../actor/user/UserProfileUpdateActor.java | 3 +- .../UserSelfDeclarationManagementActor.java | 4 +- .../sunbird/actor/user/UserStatusActor.java | 4 +- .../org/sunbird/actor/user/UserTnCActor.java | 7 +- .../org/sunbird/actor/user/UserTypeActor.java | 3 - .../sunbird/actor/user/UserUpdateActor.java | 112 +++- .../user/validator/UserRequestValidator.java | 102 +++- .../UserTenantMigrationRequestValidator.java | 28 - .../actor/userconsent/UserConsentActor.java | 8 +- .../location/impl/LocationClientImpl.java | 4 +- .../org/impl/OrganisationClientImpl.java | 2 +- .../impl/SystemSettingClientImpl.java | 2 +- .../client/user/impl/UserClientImpl.java | 5 +- .../impl/BulkUploadProcessDaoImpl.java | 7 +- .../impl/BulkUploadProcessTaskDaoImpl.java | 14 +- .../sunbird/dao/feed/impl/FeedDaoImpl.java | 6 +- .../dao/location/impl/LocationDaoImpl.java | 8 +- .../sunbird/dao/notes/impl/NotesDaoImpl.java | 6 +- .../impl/EmailTemplateDaoImpl.java | 8 +- .../dao/organisation/impl/OrgDaoImpl.java | 8 +- .../organisation/impl/OrgExternalDaoImpl.java | 2 +- .../org/sunbird/dao/otp/impl/OTPDaoImpl.java | 5 +- .../dao/ratelimit/RateLimitDaoImpl.java | 2 +- .../sunbird/dao/role/impl/RoleDaoImpl.java | 2 +- .../dao/role/impl/RoleGroupDaoImpl.java | 46 +- .../impl/SystemSettingDaoImpl.java | 7 +- .../impl/TenantPreferenceDaoImpl.java | 45 +- .../dao/urlaction/impl/UrlActionDaoImpl.java | 11 +- .../sunbird/dao/user/impl/UserDaoImpl.java | 8 +- .../impl/UserExternalIdentityDaoImpl.java | 4 +- .../dao/user/impl/UserLookupDaoImpl.java | 9 +- .../sunbird/dao/user/impl/UserOrgDaoImpl.java | 5 +- .../dao/user/impl/UserRoleDaoImpl.java | 6 +- .../user/impl/UserSelfDeclarationDaoImpl.java | 13 +- .../userconsent/impl/UserConsentDaoImpl.java | 6 +- .../java/org/sunbird/model/user/User.java | 18 + .../sunbird/service/feed/IFeedService.java | 6 +- .../service/feed/impl/FeedServiceImpl.java | 66 +-- .../service/location/LocationServiceImpl.java | 2 +- .../sunbird/service/notes/NotesService.java | 4 +- .../notification/NotificationService.java | 12 +- .../impl/OrgExternalServiceImpl.java | 4 +- .../organisation/impl/OrgServiceImpl.java | 10 +- .../org/sunbird/service/otp/OTPService.java | 4 +- .../service/ratelimit/RateLimitService.java | 4 +- .../ratelimit/RateLimitServiceImpl.java | 66 +-- .../service/role/RoleGroupService.java | 2 +- .../org/sunbird/service/role/RoleService.java | 6 +- .../systemsettings/SystemSettingsService.java | 19 +- .../TenantPreferenceService.java | 84 +-- .../service/urlaction/UrlActionService.java | 11 +- .../service/user/ResetPasswordService.java | 2 +- .../user/ShadowUserMigrationService.java | 10 +- .../service/user/UserProfileReadService.java | 121 +++-- .../service/user/impl/SSOUserServiceImpl.java | 21 +- .../user/impl/TenantMigrationServiceImpl.java | 6 +- .../impl/UserExternalIdentityServiceImpl.java | 5 +- .../user/impl/UserLookUpServiceImpl.java | 4 +- .../service/user/impl/UserOrgServiceImpl.java | 4 +- .../user/impl/UserRoleServiceImpl.java | 6 +- .../impl/UserSelfDeclarationServiceImpl.java | 17 +- .../service/user/impl/UserServiceImpl.java | 31 +- .../userconsent/UserConsentService.java | 2 +- .../impl/UserConsentServiceImpl.java | 9 +- .../org/sunbird/util/AdminUtilHandler.java | 2 +- .../org/sunbird/util/FormApiUtilHandler.java | 2 +- .../org/sunbird/util/SMSTemplateProvider.java | 4 +- .../org/sunbird/util/SearchTelemetryUtil.java | 62 --- .../java/org/sunbird/util/UserUtility.java | 2 +- .../src/main/java/org/sunbird/util/Util.java | 8 +- .../util/bulkupload/UserUploadUtil.java | 111 ---- .../util/contentstore/ContentStoreUtil.java | 2 +- .../java/org/sunbird/util/feed/FeedUtil.java | 10 +- .../java/org/sunbird/util/otp/OTPUtil.java | 70 +-- .../util/ratelimit/OtpRateLimiter.java | 2 +- .../org/sunbird/util/ratelimit/RateLimit.java | 2 +- .../org/sunbird/util/search/FuzzyMatcher.java | 2 +- .../util/search/FuzzySearchManager.java | 2 +- .../sunbird/util/user/SchedulerManager.java | 2 +- .../java/org/sunbird/util/user/UserUtil.java | 69 +-- .../actor/location/LocationActorTest.java | 25 +- .../LocationRequestValidatorTest.java | 36 +- .../actor/notes/NotesManagementActorTest.java | 14 +- .../notification/EmailServiceActorTest.java | 3 + .../actor/user/ManagedUserActorTest.java | 36 +- .../actor/user/SSOUserCreateActorTest.java | 27 +- .../actor/user/TenantMigrationActorTest.java | 46 +- .../sunbird/actor/user/UserFeedActorTest.java | 17 +- .../user/UserManagementActorTestBase.java | 31 +- .../actor/user/UserMergeActorTest.java | 30 +- .../actor/user/UserUpdateActorTest.java | 70 ++- .../validator/UserRequestValidatorTest.java | 93 ++++ .../dao/ratelimit/RateLimitDaoTest.java | 63 +-- .../impl/UserConsentDaoImplTest.java | 2 +- .../feed/impl/FeedServiceImplTest.java | 33 +- .../ratelimit/RateLimitServiceTest.java | 131 ++--- .../org/sunbird/util/otp/OTPUtilTest.java | 181 +++++-- 192 files changed, 2560 insertions(+), 1759 deletions(-) create mode 100644 .github/pull_request_template.md create mode 100644 .github/workflows/jira-description-action.yml create mode 100644 controller/test/controllers/otp/validator/OtpRequestValidatorTest.java delete mode 100644 service/src/main/java/org/sunbird/actor/user/validator/UserTenantMigrationRequestValidator.java delete mode 100644 service/src/main/java/org/sunbird/util/SearchTelemetryUtil.java delete mode 100644 service/src/main/java/org/sunbird/util/bulkupload/UserUploadUtil.java diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 000000000..9bb04d789 --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,33 @@ +Please include a summary of the change and which issue is fixed. Please also include relevant motivation and context. List any dependencies that are required for this change. + +### Type of change + +Please choose appropriate options. + +- [ ] Bug fix (non-breaking change which fixes an issue) +- [ ] New feature (non-breaking change which adds functionality) +- [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected) +- [ ] Enhancement (additive changes to improve performance) +- [ ] This change requires a documentation update + +### How Has This Been Tested? + +Please describe the tests that you ran to verify your changes in the below checkboxes. Provide instructions so we can reproduce. Please also list any relevant details for your test configuration + +- [ ] Ran Test A +- [ ] Ran Test B + +**Test Configuration**: +* Software versions: +* Hardware versions: + +### Checklist: + +- [ ] My code follows the style guidelines of this project +- [ ] I have performed a self-review of my own code +- [ ] I have commented my code, particularly in hard-to-understand areas +- [ ] I have made corresponding changes to the documentation +- [ ] My changes generate no new warnings +- [ ] I have added tests that prove my fix is effective or that my feature works +- [ ] New and existing unit tests pass locally with my changes +- [ ] Any dependent changes have been merged and published in downstream modules diff --git a/.github/workflows/jira-description-action.yml b/.github/workflows/jira-description-action.yml new file mode 100644 index 000000000..76d3fa771 --- /dev/null +++ b/.github/workflows/jira-description-action.yml @@ -0,0 +1,16 @@ +name: jira-description-action +on: + pull_request_target: + types: [opened, labeled] +jobs: + add-jira-description: + runs-on: ubuntu-latest + steps: + - uses: project-sunbird/jira-description-action@v0.4.0 + name: jira-description-action + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + jira-token: ${{ secrets.JIRA_TOKEN }} + jira-base-url: ${{ secrets.JIRA_BASE_URL }} + fail-when-jira-issue-not-found: ${{ secrets.FAIL_WHEN_JIRA_ISSUE_NOT_FOUND }} + use: both diff --git a/controller/app/controllers/BaseController.java b/controller/app/controllers/BaseController.java index c768374a1..3c83de232 100644 --- a/controller/app/controllers/BaseController.java +++ b/controller/app/controllers/BaseController.java @@ -58,9 +58,9 @@ import util.Common; */ public class BaseController extends Controller { - private static LoggerUtil logger = new LoggerUtil(BaseController.class); + private static final LoggerUtil logger = new LoggerUtil(BaseController.class); - private static ObjectMapper objectMapper = new ObjectMapper(); + private static final ObjectMapper objectMapper = new ObjectMapper(); public static final int AKKA_WAIT_TIME = 30; private static final String version = "v1"; protected Timeout timeout = new Timeout(AKKA_WAIT_TIME, TimeUnit.SECONDS); @@ -838,7 +838,6 @@ public class BaseController extends Controller { public void setContextData(Http.Request httpReq, org.sunbird.request.Request reqObj) { try { String context = Common.getFromRequest(httpReq, Attrs.CONTEXT); - logger.info("Request Context Info : " + context); Map<String, Object> requestInfo = objectMapper.readValue(context, new TypeReference<>() {}); reqObj.setRequestId(Common.getFromRequest(httpReq, Attrs.X_REQUEST_ID)); reqObj.getContext().putAll((Map<String, Object>) requestInfo.get(JsonKey.CONTEXT)); diff --git a/controller/app/controllers/otp/validator/OtpRequestValidator.java b/controller/app/controllers/otp/validator/OtpRequestValidator.java index a610e98e9..9e08a1f90 100644 --- a/controller/app/controllers/otp/validator/OtpRequestValidator.java +++ b/controller/app/controllers/otp/validator/OtpRequestValidator.java @@ -16,6 +16,12 @@ import org.sunbird.validator.BaseRequestValidator; public class OtpRequestValidator extends BaseRequestValidator { + private final List<String> allowedTemplate = + Arrays.asList( + JsonKey.RESET_PASSWORD_TEMPLATE_ID, + JsonKey.WARD_LOGIN_OTP_TEMPLATE_ID, + JsonKey.CONTACT_UPDATE_TEMPLATE_ID); + public void validateGenerateOtpRequest(Request otpRequest) { commonValidation(otpRequest, false); validateTemplateId(otpRequest); @@ -23,9 +29,7 @@ public class OtpRequestValidator extends BaseRequestValidator { private void validateTemplateId(Request otpRequest) { String templateId = (String) otpRequest.getRequest().get(JsonKey.TEMPLATE_ID); - if (StringUtils.isNotBlank(templateId) - && !templateId.equalsIgnoreCase(JsonKey.TEMPLATE_ID_VALUE) - && !templateId.equalsIgnoreCase(JsonKey.WARD_LOGIN_OTP_TEMPLATE_ID)) { + if (StringUtils.isNotBlank(templateId) && !allowedTemplate.contains(templateId)) { throw new ProjectCommonException( ResponseCode.invalidIdentifier.getErrorCode(), ProjectUtil.formatMessage( diff --git a/controller/app/controllers/usermanagement/UserController.java b/controller/app/controllers/usermanagement/UserController.java index 4b3b4fdbd..d88036c76 100644 --- a/controller/app/controllers/usermanagement/UserController.java +++ b/controller/app/controllers/usermanagement/UserController.java @@ -203,7 +203,28 @@ public class UserController extends BaseController { true, httpRequest); } - + public CompletionStage<Result> updateUserV3(Http.Request httpRequest) { + return handleRequest( + userUpdateActor, + ActorOperations.UPDATE_USER_V3.getValue(), + httpRequest.body().asJson(), + req -> { + Request request = (Request) req; + request + .getContext() + .put(JsonKey.USER_ID, Common.getFromRequest(httpRequest, Attrs.USER_ID)); + new UserRequestValidator().validateUpdateUserRequestV3(request); + request + .getContext() + .put(JsonKey.IS_AUTH_REQ, Common.getFromRequest(httpRequest, Attrs.IS_AUTH_REQ)); + + return null; + }, + null, + null, + true, + httpRequest); + } public CompletionStage<Result> getUserByIdV3(String userId, Http.Request httpRequest) { return handleGetUserProfileV3( ActorOperations.GET_USER_PROFILE_V3.getValue(), diff --git a/controller/app/controllers/usermanagement/validator/UserConsentRequestValidator.java b/controller/app/controllers/usermanagement/validator/UserConsentRequestValidator.java index 9ef9ae83f..6681017df 100644 --- a/controller/app/controllers/usermanagement/validator/UserConsentRequestValidator.java +++ b/controller/app/controllers/usermanagement/validator/UserConsentRequestValidator.java @@ -12,7 +12,8 @@ public class UserConsentRequestValidator extends BaseRequestValidator { enum CONSENT_STATUS { ACTIVE, - REVOKED; + REVOKED, + DELETED; } /** * This method will validate the mandatory param in the read request. diff --git a/controller/app/modules/OnRequestHandler.java b/controller/app/modules/OnRequestHandler.java index 25cbb3ba9..6d2988948 100644 --- a/controller/app/modules/OnRequestHandler.java +++ b/controller/app/modules/OnRequestHandler.java @@ -3,6 +3,14 @@ package modules; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import controllers.BaseController; +import java.lang.reflect.Method; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.WeakHashMap; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionStage; import org.apache.commons.lang3.StringUtils; import org.sunbird.exception.ProjectCommonException; import org.sunbird.exception.ResponseCode; @@ -19,21 +27,12 @@ import play.mvc.Http; import play.mvc.Result; import play.mvc.Results; import util.Attrs; -import util.Common; import util.RequestInterceptor; -import java.lang.reflect.Method; -import java.util.Map; -import java.util.Optional; -import java.util.UUID; -import java.util.WeakHashMap; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.CompletionStage; - public class OnRequestHandler implements ActionCreator { - private static LoggerUtil logger = new LoggerUtil(OnRequestHandler.class); - private ObjectMapper mapper = new ObjectMapper(); + private static final LoggerUtil logger = new LoggerUtil(OnRequestHandler.class); + private final ObjectMapper mapper = new ObjectMapper(); public static boolean isServiceHealthy = true; @Override @@ -54,16 +53,24 @@ public class OnRequestHandler implements ActionCreator { request.getHeaders(); CompletionStage<Result> result = checkForServiceHealth(request); if (result != null) return result; + // call method to set all the required params for the telemetry event(log)... + Map<String, Object> requestContext = getRequestContext(request); + request = updateRequestId(request, requestContext, requestId); // From 3.0.0 checking user access-token and managed-by from the request header - Map userAuthentication = RequestInterceptor.verifyRequestData(request); + Map userAuthentication = RequestInterceptor.verifyRequestData(request, requestContext); String message = (String) userAuthentication.get(JsonKey.USER_ID); + updateActorIdAndType(requestContext, request, message); + try { + request = request.addAttr(Attrs.CONTEXT, mapper.writeValueAsString(requestContext)); + } catch (Exception e) { + logger.error("Exception while parsing request context.", e); + ProjectCommonException.throwServerErrorException(ResponseCode.SERVER_ERROR); + } if (userAuthentication.get(JsonKey.MANAGED_FOR) != null) { request = request.addAttr( Attrs.MANAGED_FOR, (String) userAuthentication.get(JsonKey.MANAGED_FOR)); } - // call method to set all the required params for the telemetry event(log)... - request = initializeRequestInfo(request, message, requestId); if (!JsonKey.USER_UNAUTH_STATES.contains(message)) { request = request.addAttr(Attrs.USER_ID, message); request = request.addAttr(Attrs.IS_AUTH_REQ, "false"); @@ -75,8 +82,7 @@ public class OnRequestHandler implements ActionCreator { } result = delegate.call(request); } else if (JsonKey.UNAUTHORIZED.equals(message)) { - result = - onDataValidationError(request, message, ResponseCode.UNAUTHORIZED.getResponseCode()); + result = onDataValidationError(request, ResponseCode.UNAUTHORIZED.getResponseCode()); } else { result = delegate.call(request); } @@ -85,6 +91,39 @@ public class OnRequestHandler implements ActionCreator { }; } + private void updateActorIdAndType( + Map<String, Object> reqContext, Http.Request request, String userId) { + if (!JsonKey.USER_UNAUTH_STATES.contains(userId)) { + ((Map) reqContext.get(JsonKey.CONTEXT)).put(JsonKey.ACTOR_ID, userId); + ((Map) reqContext.get(JsonKey.CONTEXT)) + .put(JsonKey.ACTOR_TYPE, StringUtils.capitalize(JsonKey.USER)); + } else { + Optional<String> optionalConsumerId = request.header(HeaderParam.X_Consumer_ID.getName()); + String consumerId; + if (optionalConsumerId.isPresent()) { + consumerId = optionalConsumerId.get(); + } else { + consumerId = JsonKey.DEFAULT_CONSUMER_ID; + } + ((Map) reqContext.get(JsonKey.CONTEXT)).put(JsonKey.ACTOR_ID, consumerId); + ((Map) reqContext.get(JsonKey.CONTEXT)) + .put(JsonKey.ACTOR_TYPE, StringUtils.capitalize(JsonKey.CONSUMER)); + } + } + + private Http.Request updateRequestId( + Http.Request request, Map<String, Object> reqContext, String requestId) { + Optional<String> optionalTraceId = request.header(HeaderParam.X_REQUEST_ID.getName()); + if (optionalTraceId.isPresent()) { + ((Map) reqContext.get(JsonKey.CONTEXT)).put(JsonKey.X_REQUEST_ID, optionalTraceId.get()); + request = request.addAttr(Attrs.X_REQUEST_ID, optionalTraceId.get()); + } else { + request = request.addAttr(Attrs.X_REQUEST_ID, requestId); + ((Map) reqContext.get(JsonKey.CONTEXT)).put(JsonKey.X_REQUEST_ID, requestId); + } + return request; + } + public CompletionStage<Result> checkForServiceHealth(Http.Request request) { if (Boolean.parseBoolean((ProjectUtil.getConfigValue(JsonKey.SUNBIRD_HEALTH_CHECK_ENABLE))) && !request.path().endsWith(JsonKey.HEALTH)) { @@ -103,18 +142,17 @@ public class OnRequestHandler implements ActionCreator { * send some key in header. * * @param request Request - * @param errorMessage String * @return CompletionStage<Result> */ - public CompletionStage<Result> onDataValidationError( - Http.Request request, String errorMessage, int responseCode) { - String context = Common.getFromRequest(request, Attrs.CONTEXT); - logger.info("onDataValidationError: Data error found with context info : "+context +" , Error Msg: " + errorMessage); - Response resp = BaseController.createFailureResponse(request, ResponseCode.unAuthorized, ResponseCode.UNAUTHORIZED); + public CompletionStage<Result> onDataValidationError(Http.Request request, int responseCode) { + Response resp = + BaseController.createFailureResponse( + request, ResponseCode.unAuthorized, ResponseCode.UNAUTHORIZED); return CompletableFuture.completedFuture(Results.status(responseCode, Json.toJson(resp))); } - private Http.Request initializeRequestInfo(Http.Request request, String userId, String requestId) { + private Map<String, Object> getRequestContext(Http.Request request) { + Map<String, Object> requestContext = new HashMap<>(); try { String actionMethod = request.method(); String url = request.uri(); @@ -172,41 +210,15 @@ public class OnRequestHandler implements ActionCreator { if (optionalTraceEnabled.isPresent()) { reqContext.put(JsonKey.X_TRACE_ENABLED, optionalTraceEnabled.get()); } - - Optional<String> optionalTraceId = request.header(HeaderParam.X_REQUEST_ID.getName()); - if (optionalTraceId.isPresent()) { - reqContext.put(JsonKey.X_REQUEST_ID, optionalTraceId.get()); - request = request.addAttr(Attrs.X_REQUEST_ID, optionalTraceId.get()); - } else { - request = request.addAttr(Attrs.X_REQUEST_ID, requestId); - reqContext.put(JsonKey.X_REQUEST_ID, requestId); - } - if (!JsonKey.USER_UNAUTH_STATES.contains(userId)) { - reqContext.put(JsonKey.ACTOR_ID, userId); - reqContext.put(JsonKey.ACTOR_TYPE, StringUtils.capitalize(JsonKey.USER)); - } else { - Optional<String> optionalConsumerId = request.header(HeaderParam.X_Consumer_ID.getName()); - String consumerId; - if (optionalConsumerId.isPresent()) { - consumerId = optionalConsumerId.get(); - } else { - consumerId = JsonKey.DEFAULT_CONSUMER_ID; - } - reqContext.put(JsonKey.ACTOR_ID, consumerId); - reqContext.put(JsonKey.ACTOR_TYPE, StringUtils.capitalize(JsonKey.CONSUMER)); - } - Map<String, Object> map = new WeakHashMap<>(); - map.put(JsonKey.CONTEXT, reqContext); - Map<String, Object> additionalInfo = new WeakHashMap<>(); + requestContext.put(JsonKey.CONTEXT, reqContext); + Map<String, Object> additionalInfo = new HashMap<>(); additionalInfo.put(JsonKey.URL, url); additionalInfo.put(JsonKey.METHOD, methodName); - map.put(JsonKey.ADDITIONAL_INFO, additionalInfo); - - request = request.addAttr(Attrs.CONTEXT, mapper.writeValueAsString(map)); + requestContext.put(JsonKey.ADDITIONAL_INFO, additionalInfo); } catch (Exception ex) { ProjectCommonException.throwServerErrorException(ResponseCode.SERVER_ERROR); } - return request; + return requestContext; } private String getEnv(Http.Request request) { diff --git a/controller/app/util/PrintEntryExitLog.java b/controller/app/util/PrintEntryExitLog.java index adde8350e..7935212c0 100644 --- a/controller/app/util/PrintEntryExitLog.java +++ b/controller/app/util/PrintEntryExitLog.java @@ -9,7 +9,6 @@ import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; - import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.MapUtils; import org.apache.commons.lang3.SerializationUtils; @@ -30,9 +29,10 @@ import org.sunbird.util.ProjectUtil; public class PrintEntryExitLog { - private static LoggerUtil logger = new LoggerUtil(PrintEntryExitLog.class); - private static LogMaskServiceImpl logMaskService = new LogMaskServiceImpl(); - private static ObjectMapper objectMapper = new ObjectMapper(); + private static final LoggerUtil logger = new LoggerUtil(PrintEntryExitLog.class); + private static final LogMaskServiceImpl logMaskService = new LogMaskServiceImpl(); + private static final DataMaskingService service = new DefaultDataMaskServiceImpl(); + private static final ObjectMapper objectMapper = new ObjectMapper(); public static void printEntryLog(Request request) { try { @@ -157,9 +157,8 @@ public class PrintEntryExitLog { private static String maskPIIData(String logString) { try { - DataMaskingService service = new DefaultDataMaskServiceImpl(); StringBuilder builder = new StringBuilder(logString); - //Mask Email + // Mask Email StringBuilder emailRegex = new StringBuilder(ProjectUtil.EMAIL_PATTERN); emailRegex.deleteCharAt(emailRegex.length() - 1); emailRegex.deleteCharAt(0); @@ -170,7 +169,7 @@ public class PrintEntryExitLog { String tempStr = emailMatcher.group(); builder.replace(emailMatcher.start(), emailMatcher.end(), service.maskEmail(tempStr)); } - //Mask Phone + // Mask Phone String PHONE_PATTERN = "[0-9]{10}"; Pattern phonePattern = Pattern.compile(PHONE_PATTERN); Matcher phoneMatcher = phonePattern.matcher(logString); diff --git a/controller/app/util/RequestInterceptor.java b/controller/app/util/RequestInterceptor.java index 39e7b45e6..7922f2ccc 100644 --- a/controller/app/util/RequestInterceptor.java +++ b/controller/app/util/RequestInterceptor.java @@ -24,9 +24,10 @@ import play.mvc.Http; */ public class RequestInterceptor { - private static LoggerUtil logger = new LoggerUtil(RequestInterceptor.class); + private static final LoggerUtil logger = new LoggerUtil(RequestInterceptor.class); public static List<String> restrictedUriList = null; - private static ConcurrentHashMap<String, Short> apiHeaderIgnoreMap = new ConcurrentHashMap<>(); + private static final ConcurrentHashMap<String, Short> apiHeaderIgnoreMap = + new ConcurrentHashMap<>(); private RequestInterceptor() {} @@ -120,7 +121,7 @@ public class RequestInterceptor { * @return User or Client ID for authenticated request. For unauthenticated requests, UNAUTHORIZED * is returned release-3.0.0 on-wards validating managedBy token. */ - public static Map verifyRequestData(Http.Request request) { + public static Map verifyRequestData(Http.Request request, Map<String, Object> requestContext) { Map userAuthentication = new HashMap<String, String>(); userAuthentication.put(JsonKey.USER_ID, JsonKey.UNAUTHORIZED); userAuthentication.put(JsonKey.MANAGED_FOR, null); @@ -131,7 +132,7 @@ public class RequestInterceptor { if (!isRequestInExcludeList(request.path()) && !isRequestPrivate(request.path())) { // The API must be invoked with either access token or client token. if (accessToken.isPresent()) { - clientId = AccessTokenValidator.verifyUserToken(accessToken.get()); + clientId = AccessTokenValidator.verifyUserToken(accessToken.get(), requestContext); if (!JsonKey.USER_UNAUTH_STATES.contains(clientId)) { // Now we have some valid token, next verify if the token is matching the request. String requestedForUserID = getUserRequestedFor(request); @@ -143,7 +144,7 @@ public class RequestInterceptor { if (StringUtils.isNotEmpty(managedAccessToken)) { String managedFor = AccessTokenValidator.verifyManagedUserToken( - managedAccessToken, clientId, requestedForUserID); + managedAccessToken, clientId, requestedForUserID, requestContext); if (!JsonKey.USER_UNAUTH_STATES.contains(managedFor)) { managedForId = managedFor; } else { @@ -163,7 +164,8 @@ public class RequestInterceptor { if (accessToken.isPresent()) { String clientAccessTokenId = null; try { - clientAccessTokenId = AccessTokenValidator.verifyUserToken(accessToken.get()); + clientAccessTokenId = + AccessTokenValidator.verifyUserToken(accessToken.get(), requestContext); if (JsonKey.UNAUTHORIZED.equalsIgnoreCase(clientAccessTokenId)) { clientAccessTokenId = null; } diff --git a/controller/conf/application.conf b/controller/conf/application.conf index aed2a86f0..cc9821971 100644 --- a/controller/conf/application.conf +++ b/controller/conf/application.conf @@ -97,8 +97,8 @@ akka { executor = "fork-join-executor" fork-join-executor { parallelism-min = 8 - parallelism-factor = 8.0 - parallelism-max = 32 + parallelism-factor = 32.0 + parallelism-max = 64 } # Throughput for default Dispatcher, set to 1 for as fair as possible throughput = 1 @@ -110,107 +110,179 @@ akka { nr-of-instances = 5 dispatcher = brr-usr-dispatcher } + "/background_job_manager_actor/*" + { + dispatcher = akka.actor.brr-usr-dispatcher + } "/user_role_background_actor" { router = smallest-mailbox-pool nr-of-instances = 5 dispatcher = brr-usr-dispatcher } + "/user_role_background_actor/*" + { + dispatcher = akka.actor.brr-usr-dispatcher + } "/org_background_actor" { router = smallest-mailbox-pool nr-of-instances = 5 dispatcher = brr-usr-dispatcher } + "/org_background_actor/*" + { + dispatcher = akka.actor.brr-usr-dispatcher + } "/es_sync_background_actor" { router = smallest-mailbox-pool nr-of-instances = 15 dispatcher = brr-usr-dispatcher } + "/es_sync_background_actor/*" + { + dispatcher = akka.actor.brr-usr-dispatcher + } "/email_service_actor" { router = smallest-mailbox-pool nr-of-instances = 5 dispatcher = notification-dispatcher } + "/email_service_actor/*" + { + dispatcher = akka.actor.notification-dispatcher + } "/user_profile_read_actor" { router = smallest-mailbox-pool - nr-of-instances = 15 + nr-of-instances = 20 dispatcher = most-used-one-dispatcher } + "/user_profile_read_actor/*" + { + dispatcher = akka.actor.most-used-one-dispatcher + } "/check_user_exist_actor" { router = smallest-mailbox-pool - nr-of-instances = 10 + nr-of-instances = 15 dispatcher = most-used-one-dispatcher } + "/check_user_exist_actor/*" + { + dispatcher = akka.actor.most-used-one-dispatcher + } "/user_type_actor" { router = smallest-mailbox-pool nr-of-instances = 2 - dispatcher = rr-usr-dispatcher + dispatcher = brr-usr-dispatcher } + "/user_type_actor/*" + { + dispatcher = akka.actor.brr-usr-dispatcher + } "/user_status_actor" { router = smallest-mailbox-pool nr-of-instances = 2 - dispatcher = rr-usr-dispatcher + dispatcher = brr-usr-dispatcher } + "/user_status_actor/*" + { + dispatcher = akka.actor.brr-usr-dispatcher + } "/user_role_actor" { router = smallest-mailbox-pool - nr-of-instances = 5 + nr-of-instances = 10 dispatcher = most-used-two-dispatcher } + "/user_role_actor/*" + { + dispatcher = akka.actor.most-used-two-dispatcher + } "/fetch_user_role_actor" { router = smallest-mailbox-pool nr-of-instances = 20 dispatcher = most-used-two-dispatcher } + "/fetch_user_role_actor/*" + { + dispatcher = akka.actor.most-used-two-dispatcher + } "/user_external_identity_management_actor" { router = smallest-mailbox-pool nr-of-instances = 5 dispatcher = rr-usr-dispatcher } + "/user_external_identity_management_actor/*" + { + dispatcher = akka.actor.rr-usr-dispatcher + } "/user_self_declaration_management_actor" { router = smallest-mailbox-pool nr-of-instances = 2 dispatcher = rr-usr-dispatcher } + "/user_self_declaration_management_actor/*" + { + dispatcher = akka.actor.rr-usr-dispatcher + } "/user_org_management_actor" { router = smallest-mailbox-pool nr-of-instances = 5 dispatcher = rr-usr-dispatcher } + "/user_org_management_actor/*" + { + dispatcher = akka.actor.rr-usr-dispatcher + } "/user_on_boarding_notification_actor" { router = smallest-mailbox-pool nr-of-instances = 2 - dispatcher = rr-usr-dispatcher + dispatcher = brr-usr-dispatcher + } + "/user_on_boarding_notification_actor/*" + { + dispatcher = akka.actor.brr-usr-dispatcher } "/user_background_job_actor" { router = smallest-mailbox-pool - nr-of-instances = 15 + nr-of-instances = 5 dispatcher = most-used-two-dispatcher } + "/user_background_job_actor/*" + { + dispatcher = akka.actor.most-used-two-dispatcher + } "/user_profile_update_actor" { router = smallest-mailbox-pool - nr-of-instances = 5 + nr-of-instances = 15 dispatcher = most-used-two-dispatcher } + "/user_profile_update_actor/*" + { + dispatcher = akka.actor.most-used-two-dispatcher + } "/user_login_actor" { router = smallest-mailbox-pool nr-of-instances = 2 - dispatcher = rr-usr-dispatcher + dispatcher = brr-usr-dispatcher + } + "/user_login_actor/*" + { + dispatcher = akka.actor.brr-usr-dispatcher } "/org_management_actor" { @@ -218,17 +290,29 @@ akka { nr-of-instances = 5 dispatcher = rr-usr-dispatcher } + "/org_management_actor/*" + { + dispatcher = akka.actor.rr-usr-dispatcher + } "/search_handler_actor" { router = smallest-mailbox-pool nr-of-instances = 25 dispatcher = most-used-one-dispatcher } + "/search_handler_actor/*" + { + dispatcher = akka.actor.most-used-one-dispatcher + } "/bulk_upload_management_actor" { router = smallest-mailbox-pool nr-of-instances = 1 - dispatcher = rr-usr-dispatcher + dispatcher = brr-usr-dispatcher + } + "/bulk_upload_management_actor/*" + { + dispatcher = akka.actor.brr-usr-dispatcher } "/es_sync_actor" { @@ -236,17 +320,29 @@ akka { nr-of-instances = 15 dispatcher = rr-usr-dispatcher } + "/es_sync_actor/*" + { + dispatcher = akka.actor.rr-usr-dispatcher + } "/file_upload_service_actor" { router = smallest-mailbox-pool nr-of-instances = 1 - dispatcher = rr-usr-dispatcher + dispatcher = brr-usr-dispatcher + } + "/file_upload_service_actor/*" + { + dispatcher = akka.actor.brr-usr-dispatcher } "/notes_management_actor" { router = smallest-mailbox-pool nr-of-instances = 1 - dispatcher = rr-usr-dispatcher + dispatcher = brr-usr-dispatcher + } + "/notes_management_actor/*" + { + dispatcher = akka.actor.brr-usr-dispatcher } "/tenant_preference_actor" { @@ -254,41 +350,69 @@ akka { nr-of-instances = 1 dispatcher = rr-usr-dispatcher } + "/tenant_preference_actor/*" + { + dispatcher = akka.actor.rr-usr-dispatcher + } "/health_actor" { router = smallest-mailbox-pool nr-of-instances = 5 dispatcher = health-check-dispatcher } + "/health_actor/*" + { + dispatcher = akka.actor.health-check-dispatcher + } "/location_actor" { router = smallest-mailbox-pool nr-of-instances = 5 dispatcher = rr-usr-dispatcher } + "/location_actor/*" + { + dispatcher = akka.actor.rr-usr-dispatcher + } "/location_background_actor" { router = smallest-mailbox-pool nr-of-instances = 5 dispatcher = brr-usr-dispatcher } + "/location_background_actor/*" + { + dispatcher = akka.actor.brr-usr-dispatcher + } "/location_bulk_upload_actor" { router = smallest-mailbox-pool nr-of-instances = 2 - dispatcher = rr-usr-dispatcher + dispatcher = brr-usr-dispatcher + } + "/location_bulk_upload_actor/*" + { + dispatcher = akka.actor.brr-usr-dispatcher } "/org_bulk_upload_actor" { router = smallest-mailbox-pool nr-of-instances = 2 - dispatcher = rr-usr-dispatcher + dispatcher = brr-usr-dispatcher + } + "/org_bulk_upload_actor/*" + { + dispatcher = akka.actor.brr-usr-dispatcher } "/user_bulk_upload_actor" { router = smallest-mailbox-pool nr-of-instances = 2 - dispatcher = rr-usr-dispatcher + dispatcher = brr-usr-dispatcher + } + "/user_bulk_upload_actor/*" + { + dispatcher = akka.actor.brr-usr-dispatcher } "/system_settings_actor" { @@ -296,47 +420,79 @@ akka { nr-of-instances = 15 dispatcher = most-used-two-dispatcher } + "/system_settings_actor/*" + { + dispatcher = akka.actor.most-used-two-dispatcher + } "/user_tnc_actor" { router = smallest-mailbox-pool nr-of-instances = 15 dispatcher = most-used-two-dispatcher } + "/user_tnc_actor/*" + { + dispatcher = akka.actor.most-used-two-dispatcher + } "/location_bulk_upload_background_job_actor" { router = smallest-mailbox-pool nr-of-instances = 2 dispatcher = brr-usr-dispatcher } + "/location_bulk_upload_background_job_actor/*" + { + dispatcher = akka.actor.brr-usr-dispatcher + } "/org_bulk_upload_background_job_actor" { router = smallest-mailbox-pool nr-of-instances = 2 dispatcher = brr-usr-dispatcher } + "/org_bulk_upload_background_job_actor/*" + { + dispatcher = akka.actor.brr-usr-dispatcher + } "/user_bulk_upload_background_job_actor" { router = smallest-mailbox-pool nr-of-instances = 2 dispatcher = brr-usr-dispatcher } + "/user_bulk_upload_background_job_actor/*" + { + dispatcher = akka.actor.brr-usr-dispatcher + } "/otp_actor" { router = smallest-mailbox-pool - nr-of-instances = 10 + nr-of-instances = 15 dispatcher = notification-dispatcher } + "/otp_actor/*" + { + dispatcher = akka.actor.notification-dispatcher + } "/send_otp_actor" { router = smallest-mailbox-pool - nr-of-instances = 5 + nr-of-instances = 15 dispatcher = notification-dispatcher } + "/send_otp_actor/*" + { + dispatcher = akka.actor.notification-dispatcher + } "/tenant_migration_actor" { router = smallest-mailbox-pool nr-of-instances = 3 - dispatcher = rr-usr-dispatcher + dispatcher = brr-usr-dispatcher + } + "/tenant_migration_actor/*" + { + dispatcher = akka.actor.brr-usr-dispatcher } "/identifier_free_up_actor" { @@ -344,90 +500,150 @@ akka { nr-of-instances = 15 dispatcher = most-used-two-dispatcher } + "/identifier_free_up_actor/*" + { + dispatcher = akka.actor.most-used-two-dispatcher + } "/reset_password_actor" { router = smallest-mailbox-pool nr-of-instances = 15 dispatcher = most-used-one-dispatcher } + "/reset_password_actor/*" + { + dispatcher = akka.actor.most-used-one-dispatcher + } "/user_merge_actor" { router = smallest-mailbox-pool nr-of-instances = 2 - dispatcher = rr-usr-dispatcher + dispatcher = brr-usr-dispatcher + } + "/user_merge_actor/*" + { + dispatcher = akka.actor.brr-usr-dispatcher } "/user_feed_actor" { router = smallest-mailbox-pool - nr-of-instances = 15 + nr-of-instances = 20 dispatcher = most-used-two-dispatcher } + "/user_feed_actor/*" + { + dispatcher = akka.actor.most-used-two-dispatcher + } "/search_telemetry_actor" { router = smallest-mailbox-pool nr-of-instances = 2 dispatcher = brr-usr-dispatcher } + "/search_telemetry_actor/*" + { + dispatcher = akka.actor.brr-usr-dispatcher + } "/user_telemetry_actor" { router = smallest-mailbox-pool nr-of-instances = 2 dispatcher = brr-usr-dispatcher } + "/user_telemetry_actor/*" + { + dispatcher = akka.actor.brr-usr-dispatcher + } "/send_notification_actor" { router = smallest-mailbox-pool nr-of-instances = 10 dispatcher = notification-dispatcher } + "/send_notification_actor/*" + { + dispatcher = akka.actor.notification-dispatcher + } "/background_notification_actor" { router = smallest-mailbox-pool nr-of-instances = 10 dispatcher = notification-dispatcher } + "/background_notification_actor/*" + { + dispatcher = akka.actor.notification-dispatcher + } "/tenant_migration_actor" { router = smallest-mailbox-pool nr-of-instances = 3 dispatcher = brr-usr-dispatcher } + "/tenant_migration_actor/*" + { + dispatcher = akka.actor.brr-usr-dispatcher + } "/user_consent_actor" { router = smallest-mailbox-pool nr-of-instances = 3 dispatcher = rr-usr-dispatcher } + "/user_consent_actor/*" + { + dispatcher = akka.actor.rr-usr-dispatcher + } "/user_lookup_actor" { router = smallest-mailbox-pool nr-of-instances = 25 dispatcher = most-used-one-dispatcher } + "/user_lookup_actor/*" + { + dispatcher = akka.actor.most-used-one-dispatcher + } "/user_update_actor" { router = smallest-mailbox-pool nr-of-instances = 20 dispatcher = most-used-one-dispatcher } + "/user_update_actor/*" + { + dispatcher = akka.actor.most-used-one-dispatcher + } "/managed_user_actor" { router = smallest-mailbox-pool nr-of-instances = 5 dispatcher = most-used-one-dispatcher } + "/managed_user_actor/*" + { + dispatcher = akka.actor.most-used-one-dispatcher + } "/ssu_user_create_actor" { router = smallest-mailbox-pool - nr-of-instances = 10 + nr-of-instances = 15 dispatcher = most-used-one-dispatcher } + "/ssu_user_create_actor/*" + { + dispatcher = akka.actor.most-used-one-dispatcher + } "/sso_user_create_actor" { router = smallest-mailbox-pool - nr-of-instances = 10 + nr-of-instances = 15 dispatcher = most-used-one-dispatcher } + "/sso_user_create_actor/*" + { + dispatcher = akka.actor.most-used-one-dispatcher + } } } } @@ -510,7 +726,7 @@ play.server { ## WS (HTTP Client) # ~~~~~ -libraryDependencies += javaWs +libraryDependencies += javaWs ## Cache # https://www.playframework.com/documentation/latest/JavaCache diff --git a/controller/conf/routes b/controller/conf/routes index 8913fdefd..0655f3ddf 100644 --- a/controller/conf/routes +++ b/controller/conf/routes @@ -17,6 +17,7 @@ POST /v2/user/signup @controllers.usermanagement.User PATCH /v1/user/update @controllers.usermanagement.UserController.updateUser(request: play.mvc.Http.Request) PATCH /v2/user/update @controllers.usermanagement.UserController.updateUserV2(request: play.mvc.Http.Request) +PATCH /v3/user/update @controllers.usermanagement.UserController.updateUserV3(request: play.mvc.Http.Request) GET /v1/user/read/:uid @controllers.usermanagement.UserController.getUserByIdV3(uid:String, request: play.mvc.Http.Request) GET /v2/user/read/:uid @controllers.usermanagement.UserController.getUserByIdV3(uid:String, request: play.mvc.Http.Request) diff --git a/controller/test/controllers/BaseApplicationTest.java b/controller/test/controllers/BaseApplicationTest.java index 831e0adaa..7a6e22030 100644 --- a/controller/test/controllers/BaseApplicationTest.java +++ b/controller/test/controllers/BaseApplicationTest.java @@ -64,7 +64,7 @@ public abstract class BaseApplicationTest { Helpers.start(application); mockStatic(RequestInterceptor.class); mockStatic(TelemetryWriter.class); - PowerMockito.when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + PowerMockito.when(RequestInterceptor.verifyRequestData(Mockito.anyObject(), Mockito.anyMap())) .thenReturn(userAuthentication); mockStatic(OnRequestHandler.class); } catch (Exception e) { @@ -89,7 +89,7 @@ public abstract class BaseApplicationTest { Helpers.start(application); mockStatic(RequestInterceptor.class); mockStatic(TelemetryWriter.class); - PowerMockito.when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + PowerMockito.when(RequestInterceptor.verifyRequestData(Mockito.anyObject(), Mockito.anyMap())) .thenReturn(userAuthentication); mockStatic(OnRequestHandler.class); } catch (Exception e) { diff --git a/controller/test/controllers/bulkapimanagement/BulkUploadControllerTest.java b/controller/test/controllers/bulkapimanagement/BulkUploadControllerTest.java index 6de78ded3..b770ea17b 100644 --- a/controller/test/controllers/bulkapimanagement/BulkUploadControllerTest.java +++ b/controller/test/controllers/bulkapimanagement/BulkUploadControllerTest.java @@ -54,7 +54,8 @@ public class BulkUploadControllerTest extends BaseApplicationTest { Map userAuthentication = new HashMap<String, String>(); userAuthentication.put(JsonKey.USER_ID, "uuiuhcf784508 8y8c79-fhh"); PowerMockito.mockStatic(RequestInterceptor.class); - when(RequestInterceptor.verifyRequestData(Mockito.anyObject())).thenReturn(userAuthentication); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject(), Mockito.anyMap())) + .thenReturn(userAuthentication); Map<String, Object> requestMap = new HashMap<>(); Map<String, Object> innerMap = new HashMap<>(); innerMap.put(JsonKey.DATA, "sampleStream".getBytes(Charset.defaultCharset())); @@ -73,7 +74,8 @@ public class BulkUploadControllerTest extends BaseApplicationTest { Map userAuthentication = new HashMap<String, String>(); userAuthentication.put(JsonKey.USER_ID, "uuiuhcf784508 8y8c79-fhh"); PowerMockito.mockStatic(RequestInterceptor.class); - when(RequestInterceptor.verifyRequestData(Mockito.anyObject())).thenReturn(userAuthentication); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject(), Mockito.anyMap())) + .thenReturn(userAuthentication); Map<String, Object> requestMap = new HashMap<>(); Map<String, Object> innerMap = new HashMap<>(); innerMap.put(JsonKey.DATA, "sampleStream".getBytes(Charset.defaultCharset())); @@ -99,7 +101,8 @@ public class BulkUploadControllerTest extends BaseApplicationTest { Map userAuthentication = new HashMap<String, String>(); userAuthentication.put(JsonKey.USER_ID, "uuiuhcf784508 8y8c79-fhh"); PowerMockito.mockStatic(RequestInterceptor.class); - when(RequestInterceptor.verifyRequestData(Mockito.anyObject())).thenReturn(userAuthentication); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject(), Mockito.anyMap())) + .thenReturn(userAuthentication); Map<String, Object> requestMap = new HashMap<>(); Map<String, Object> innerMap = new HashMap<>(); innerMap.put(JsonKey.DATA, "sampleStream".getBytes(Charset.defaultCharset())); @@ -118,7 +121,8 @@ public class BulkUploadControllerTest extends BaseApplicationTest { Map userAuthentication = new HashMap<String, String>(); userAuthentication.put(JsonKey.USER_ID, "uuiuhcf784508 8y8c79-fhh"); PowerMockito.mockStatic(RequestInterceptor.class); - when(RequestInterceptor.verifyRequestData(Mockito.anyObject())).thenReturn(userAuthentication); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject(), Mockito.anyMap())) + .thenReturn(userAuthentication); Map<String, Object> requestMap = new HashMap<>(); Map<String, Object> innerMap = new HashMap<>(); innerMap.put(JsonKey.DATA, "sampleStream".getBytes(Charset.defaultCharset())); diff --git a/controller/test/controllers/healthmanager/HealthControllerTest.java b/controller/test/controllers/healthmanager/HealthControllerTest.java index 0eb5b19aa..c7263f359 100644 --- a/controller/test/controllers/healthmanager/HealthControllerTest.java +++ b/controller/test/controllers/healthmanager/HealthControllerTest.java @@ -52,7 +52,8 @@ public class HealthControllerTest extends BaseApplicationTest { Map userAuthentication = new HashMap<String, String>(); userAuthentication.put(JsonKey.USER_ID, "uuiuhcf784508 8y8c79-fhh"); PowerMockito.mockStatic(RequestInterceptor.class); - when(RequestInterceptor.verifyRequestData(Mockito.anyObject())).thenReturn(userAuthentication); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject(), Mockito.anyMap())) + .thenReturn(userAuthentication); RequestBuilder req = new RequestBuilder().uri("/v1/health").method("GET"); // req.headers(headerMap); Result result = Helpers.route(application, req); diff --git a/controller/test/controllers/location/LocationControllerTest.java b/controller/test/controllers/location/LocationControllerTest.java index 7dc388fa8..dfc339e74 100644 --- a/controller/test/controllers/location/LocationControllerTest.java +++ b/controller/test/controllers/location/LocationControllerTest.java @@ -59,7 +59,8 @@ public class LocationControllerTest extends BaseApplicationTest { public void testCreateLocation() { Map userAuthentication = new HashMap<String, String>(); userAuthentication.put(JsonKey.USER_ID, "uuiuhcf784508 8y8c79-fhh"); - when(RequestInterceptor.verifyRequestData(Mockito.anyObject())).thenReturn(userAuthentication); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject(), Mockito.anyMap())) + .thenReturn(userAuthentication); Map<String, Object> requestMap = new HashMap<>(); Map<String, Object> locationData = new HashMap<>(); locationData.put(JsonKey.NAME, LOCATION_NAME); diff --git a/controller/test/controllers/notificationservice/EmailServiceControllerTest.java b/controller/test/controllers/notificationservice/EmailServiceControllerTest.java index 1e4f0a200..56385c979 100644 --- a/controller/test/controllers/notificationservice/EmailServiceControllerTest.java +++ b/controller/test/controllers/notificationservice/EmailServiceControllerTest.java @@ -54,7 +54,8 @@ public class EmailServiceControllerTest extends BaseApplicationTest { Map userAuthentication = new HashMap<String, String>(); userAuthentication.put(JsonKey.USER_ID, "uuiuhcf784508 8y8c79-fhh"); PowerMockito.mockStatic(RequestInterceptor.class); - when(RequestInterceptor.verifyRequestData(Mockito.anyObject())).thenReturn(userAuthentication); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject(), Mockito.anyMap())) + .thenReturn(userAuthentication); Map<String, Object> requestMap = new HashMap<>(); Map<String, Object> innerMap = new HashMap<>(); innerMap.put(JsonKey.ORG_NAME, "org123"); @@ -82,7 +83,8 @@ public class EmailServiceControllerTest extends BaseApplicationTest { Map userAuthentication = new HashMap<String, String>(); userAuthentication.put(JsonKey.USER_ID, "uuiuhcf784508 8y8c79-fhh"); PowerMockito.mockStatic(RequestInterceptor.class); - when(RequestInterceptor.verifyRequestData(Mockito.anyObject())).thenReturn(userAuthentication); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject(), Mockito.anyMap())) + .thenReturn(userAuthentication); Map<String, Object> requestMap = new HashMap<>(); Map<String, Object> innerMap = new HashMap<>(); innerMap.put(JsonKey.ORG_NAME, "org123"); @@ -110,7 +112,8 @@ public class EmailServiceControllerTest extends BaseApplicationTest { Map userAuthentication = new HashMap<String, String>(); userAuthentication.put(JsonKey.USER_ID, "uuiuhcf784508 8y8c79-fhh"); PowerMockito.mockStatic(RequestInterceptor.class); - when(RequestInterceptor.verifyRequestData(Mockito.anyObject())).thenReturn(userAuthentication); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject(), Mockito.anyMap())) + .thenReturn(userAuthentication); Map<String, Object> requestMap = new HashMap<>(); Map<String, Object> innerMap = new HashMap<>(); innerMap.put(JsonKey.ORG_NAME, "org123"); @@ -134,7 +137,8 @@ public class EmailServiceControllerTest extends BaseApplicationTest { Map userAuthentication = new HashMap<String, String>(); userAuthentication.put(JsonKey.USER_ID, "uuiuhcf784508 8y8c79-fhh"); PowerMockito.mockStatic(RequestInterceptor.class); - when(RequestInterceptor.verifyRequestData(Mockito.anyObject())).thenReturn(userAuthentication); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject(), Mockito.anyMap())) + .thenReturn(userAuthentication); Map<String, Object> requestMap = new HashMap<>(); Map<String, Object> innerMap = new HashMap<>(); innerMap.put(JsonKey.ORG_NAME, "org123"); diff --git a/controller/test/controllers/otp/validator/OtpRequestValidatorTest.java b/controller/test/controllers/otp/validator/OtpRequestValidatorTest.java new file mode 100644 index 000000000..507dc8f01 --- /dev/null +++ b/controller/test/controllers/otp/validator/OtpRequestValidatorTest.java @@ -0,0 +1,19 @@ +package controllers.otp.validator; + +import org.junit.Test; +import org.sunbird.exception.ProjectCommonException; +import org.sunbird.keys.JsonKey; +import org.sunbird.request.Request; + +public class OtpRequestValidatorTest { + + @Test(expected = ProjectCommonException.class) + public void testValidateGenerateOtpRequest() { + Request otpRequest = new Request(); + otpRequest.getRequest().put(JsonKey.KEY, "xyz@xyz.com"); + otpRequest.getRequest().put(JsonKey.TYPE, "email"); + otpRequest.getRequest().put(JsonKey.TEMPLATE_ID, "invalidTemplateID"); + OtpRequestValidator otpRequestValidator = new OtpRequestValidator(); + otpRequestValidator.validateGenerateOtpRequest(otpRequest); + } +} diff --git a/controller/test/controllers/storage/FileStorageControllerTest.java b/controller/test/controllers/storage/FileStorageControllerTest.java index b0730044c..bc5e83105 100644 --- a/controller/test/controllers/storage/FileStorageControllerTest.java +++ b/controller/test/controllers/storage/FileStorageControllerTest.java @@ -53,7 +53,8 @@ public class FileStorageControllerTest extends BaseApplicationTest { Map userAuthentication = new HashMap<String, String>(); userAuthentication.put(JsonKey.USER_ID, "uuiuhcf784508 8y8c79-fhh"); PowerMockito.mockStatic(RequestInterceptor.class); - when(RequestInterceptor.verifyRequestData(Mockito.anyObject())).thenReturn(userAuthentication); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject(), Mockito.anyMap())) + .thenReturn(userAuthentication); Map<String, Object> requestMap = new HashMap<>(); Map<String, Object> innerMap = new HashMap<>(); innerMap.put(JsonKey.DATA, "uploadFILEData".getBytes()); diff --git a/controller/test/controllers/sync/SyncControllerTest.java b/controller/test/controllers/sync/SyncControllerTest.java index 6b4b4cfc6..f4905cab5 100644 --- a/controller/test/controllers/sync/SyncControllerTest.java +++ b/controller/test/controllers/sync/SyncControllerTest.java @@ -54,7 +54,8 @@ public class SyncControllerTest extends BaseApplicationTest { Map userAuthentication = new HashMap<String, String>(); userAuthentication.put(JsonKey.USER_ID, "uuiuhcf784508 8y8c79-fhh"); PowerMockito.mockStatic(RequestInterceptor.class); - when(RequestInterceptor.verifyRequestData(Mockito.anyObject())).thenReturn(userAuthentication); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject(), Mockito.anyMap())) + .thenReturn(userAuthentication); Map<String, Object> requestMap = new HashMap<>(); Map<String, Object> innerMap = new HashMap<>(); innerMap.put(JsonKey.OBJECT_TYPE, JsonKey.ORGANISATION); @@ -74,7 +75,8 @@ public class SyncControllerTest extends BaseApplicationTest { Map userAuthentication = new HashMap<String, String>(); userAuthentication.put(JsonKey.USER_ID, "uuiuhcf784508 8y8c79-fhh"); PowerMockito.mockStatic(RequestInterceptor.class); - when(RequestInterceptor.verifyRequestData(Mockito.anyObject())).thenReturn(userAuthentication); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject(), Mockito.anyMap())) + .thenReturn(userAuthentication); Map<String, Object> requestMap = new HashMap<>(); Map<String, Object> innerMap = new HashMap<>(); innerMap.put(JsonKey.OBJECT_TYPE, "invalidObject"); diff --git a/controller/test/controllers/usermanagement/UserControllerTest.java b/controller/test/controllers/usermanagement/UserControllerTest.java index 5ba088980..69525969b 100644 --- a/controller/test/controllers/usermanagement/UserControllerTest.java +++ b/controller/test/controllers/usermanagement/UserControllerTest.java @@ -261,6 +261,17 @@ public class UserControllerTest extends BaseApplicationTest { assertTrue(getResponseStatus(result) == 200); } + @Test + public void testUpdateUserV3Success() throws Exception { + Result result = + performTest( + "/v3/user/update", + "PATCH", + (Map) createOrUpdateUserRequest(null, phoneNumber, userId, true, null)); + assertEquals(getResponseCode(result), ResponseCode.success.getErrorCode().toLowerCase()); + assertTrue(getResponseStatus(result) == 200); + } + @Test public void testUpdateUserFailureWithInvalidPhoneNumber() { Result result = diff --git a/controller/test/util/RequestInterceptorTest.java b/controller/test/util/RequestInterceptorTest.java index 9afbfd725..24646282a 100644 --- a/controller/test/util/RequestInterceptorTest.java +++ b/controller/test/util/RequestInterceptorTest.java @@ -7,6 +7,7 @@ import static org.powermock.api.mockito.PowerMockito.when; import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.fasterxml.jackson.databind.node.ObjectNode; +import java.util.HashMap; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; @@ -47,7 +48,9 @@ public class RequestInterceptorTest { "eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICIyZUNvWGlZRHFDbHRaX1F1ZXNRMEhtNkNYVF91emJiN2d3bXlMZXhsN1JnIn0.eyJqdGkiOiIwMTVmNmRlOC1jODRiLTRkNmUtOGRkYy1mNzZmNTk3NTViNjgiLCJleHAiOjE1OTQxMDg0MjUsIm5iZiI6MCwiaWF0IjoxNTk0MDIyMDI1LCJpc3MiOiJodHRwczovL3N0YWdpbmcubnRwLm5ldC5pbi9hdXRoL3JlYWxtcy9zdW5iaXJkIiwiYXVkIjoiYWRtaW4tY2xpIiwic3ViIjoiZjo5MzFhOWRjOS00NTk0LTQ4MzktYWExNi1jZjBjYWMwOTYzODE6M2Y0YmYzMTEtOTNkMy00ODY3LTgxMGMtZGViMDYzYjQzNzg5IiwidHlwIjoiQmVhcmVyIiwiYXpwIjoiYWRtaW4tY2xpIiwiYXV0aF90aW1lIjowLCJzZXNzaW9uX3N0YXRlIjoiZGFmYzU0YmUtNmZkOS00MDRlLTljYzctN2FkYzYxYzVjYzI1IiwiYWNyIjoiMSIsImFsbG93ZWQtb3JpZ2lucyI6W10sInJlYWxtX2FjY2VzcyI6eyJyb2xlcyI6WyJ1bWFfYXV0aG9yaXphdGlvbiJdfSwicmVzb3VyY2VfYWNjZXNzIjp7fSwibmFtZSI6Ik5hdjIiLCJwcmVmZXJyZWRfdXNlcm5hbWUiOiJuYXYyMzMzNyIsImdpdmVuX25hbWUiOiJOYXYyIiwiZW1haWwiOiJuYXYyQHlvcG1haWwuY29tIn0.HAG5Uv7F7J82HCmNsM9NjzMKEW_65nsJX-P_SC5XNfSoz9w5FkQQ4Xlx9elw5vbvtG9UU5Jn5TDMRGAnjdCZ-FMgMv0BLGy3uRKq6Xu6drf6oN9kYMIgTGYuf946EX3pelXQtL6kXwi5_OQ6OQT7Ie94l525BEn09SkeiKJsUrrxShLMlCaX3ERt83MwNdxLkuJ0tI8Jx22leksaf8cxGteC3iF31eLVxIe3ioIexUpbbTI-zBZHHURX_5tAIZvq91kV7Laibngqg4RDluaBltmbBWufFBPAYHqwFRvhix2E78t3d6cb7mx4xRNDrbTJCxHQCL2kE-VXkPGBDEHa3g"); ; assertEquals( - (String) RequestInterceptor.verifyRequestData(requestBuilder.build()).get(JsonKey.USER_ID), + (String) + RequestInterceptor.verifyRequestData(requestBuilder.build(), new HashMap<>()) + .get(JsonKey.USER_ID), "Anonymous"); } @@ -75,12 +78,15 @@ public class RequestInterceptorTest { "eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICIyZUNvWGlZRHFDbHRaX1F1ZXNRMEhtNkNYVF91emJiN2d3bXlMZXhsN1JnIn0.eyJqdGkiOiIwMTVmNmRlOC1jODRiLTRkNmUtOGRkYy1mNzZmNTk3NTViNjgiLCJleHAiOjE1OTQxMDg0MjUsIm5iZiI6MCwiaWF0IjoxNTk0MDIyMDI1LCJpc3MiOiJodHRwczovL3N0YWdpbmcubnRwLm5ldC5pbi9hdXRoL3JlYWxtcy9zdW5iaXJkIiwiYXVkIjoiYWRtaW4tY2xpIiwic3ViIjoiZjo5MzFhOWRjOS00NTk0LTQ4MzktYWExNi1jZjBjYWMwOTYzODE6M2Y0YmYzMTEtOTNkMy00ODY3LTgxMGMtZGViMDYzYjQzNzg5IiwidHlwIjoiQmVhcmVyIiwiYXpwIjoiYWRtaW4tY2xpIiwiYXV0aF90aW1lIjowLCJzZXNzaW9uX3N0YXRlIjoiZGFmYzU0YmUtNmZkOS00MDRlLTljYzctN2FkYzYxYzVjYzI1IiwiYWNyIjoiMSIsImFsbG93ZWQtb3JpZ2lucyI6W10sInJlYWxtX2FjY2VzcyI6eyJyb2xlcyI6WyJ1bWFfYXV0aG9yaXphdGlvbiJdfSwicmVzb3VyY2VfYWNjZXNzIjp7fSwibmFtZSI6Ik5hdjIiLCJwcmVmZXJyZWRfdXNlcm5hbWUiOiJuYXYyMzMzNyIsImdpdmVuX25hbWUiOiJOYXYyIiwiZW1haWwiOiJuYXYyQHlvcG1haWwuY29tIn0.HAG5Uv7F7J82HCmNsM9NjzMKEW_65nsJX-P_SC5XNfSoz9w5FkQQ4Xlx9elw5vbvtG9UU5Jn5TDMRGAnjdCZ-FMgMv0BLGy3uRKq6Xu6drf6oN9kYMIgTGYuf946EX3pelXQtL6kXwi5_OQ6OQT7Ie94l525BEn09SkeiKJsUrrxShLMlCaX3ERt83MwNdxLkuJ0tI8Jx22leksaf8cxGteC3iF31eLVxIe3ioIexUpbbTI-zBZHHURX_5tAIZvq91kV7Laibngqg4RDluaBltmbBWufFBPAYHqwFRvhix2E78t3d6cb7mx4xRNDrbTJCxHQCL2kE-VXkPGBDEHa3g") .bodyJson(requestNode); Http.Request req = requestBuilder.build(); - when(tokenValidator.verifyUserToken(Mockito.anyString())).thenReturn("authorized-user"); + when(tokenValidator.verifyUserToken(Mockito.anyString(), Mockito.anyMap())) + .thenReturn("authorized-user"); when(tokenValidator.verifyManagedUserToken( - Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyMap())) .thenReturn("authorized-user"); assertEquals( - (String) RequestInterceptor.verifyRequestData(requestBuilder.build()).get(JsonKey.USER_ID), + (String) + RequestInterceptor.verifyRequestData(requestBuilder.build(), new HashMap<>()) + .get(JsonKey.USER_ID), "authorized-user"); } @@ -93,16 +99,18 @@ public class RequestInterceptorTest { userNode.put(JsonKey.USER_ID, "56c2d9a3-fae9-4341-9862-4eeeead2e9a1"); requestNode.put(JsonKey.REQUEST, userNode); Http.RequestBuilder requestBuilder = - Helpers.fakeRequest(Helpers.POST, "http://localhost:9000/v1/group/create") - .bodyJson(requestNode); + Helpers.fakeRequest(Helpers.POST, "http://localhost:9000/v1/group/create") + .bodyJson(requestNode); Http.Request req = requestBuilder.build(); - when(tokenValidator.verifyUserToken(Mockito.anyString())).thenReturn("authorized-user"); + when(tokenValidator.verifyUserToken(Mockito.anyString(), Mockito.anyMap())) + .thenReturn("authorized-user"); when(tokenValidator.verifyManagedUserToken( - Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn("authorized-user"); + Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyMap())) + .thenReturn("authorized-user"); assertEquals( - RequestInterceptor.verifyRequestData(requestBuilder.build()).get(JsonKey.USER_ID), - JsonKey.UNAUTHORIZED); + RequestInterceptor.verifyRequestData(requestBuilder.build(), new HashMap<>()) + .get(JsonKey.USER_ID), + JsonKey.UNAUTHORIZED); } @Test @@ -124,12 +132,15 @@ public class RequestInterceptorTest { "x-authenticated-for", "eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICIyZUNvWGlZRHFDbHRaX1F1ZXNRMEhtNkNYVF91emJiN2d3bXlMZXhsN1JnIn0.eyJqdGkiOiIwMTVmNmRlOC1jODRiLTRkNmUtOGRkYy1mNzZmNTk3NTViNjgiLCJleHAiOjE1OTQxMDg0MjUsIm5iZiI6MCwiaWF0IjoxNTk0MDIyMDI1LCJpc3MiOiJodHRwczovL3N0YWdpbmcubnRwLm5ldC5pbi9hdXRoL3JlYWxtcy9zdW5iaXJkIiwiYXVkIjoiYWRtaW4tY2xpIiwic3ViIjoiZjo5MzFhOWRjOS00NTk0LTQ4MzktYWExNi1jZjBjYWMwOTYzODE6M2Y0YmYzMTEtOTNkMy00ODY3LTgxMGMtZGViMDYzYjQzNzg5IiwidHlwIjoiQmVhcmVyIiwiYXpwIjoiYWRtaW4tY2xpIiwiYXV0aF90aW1lIjowLCJzZXNzaW9uX3N0YXRlIjoiZGFmYzU0YmUtNmZkOS00MDRlLTljYzctN2FkYzYxYzVjYzI1IiwiYWNyIjoiMSIsImFsbG93ZWQtb3JpZ2lucyI6W10sInJlYWxtX2FjY2VzcyI6eyJyb2xlcyI6WyJ1bWFfYXV0aG9yaXphdGlvbiJdfSwicmVzb3VyY2VfYWNjZXNzIjp7fSwibmFtZSI6Ik5hdjIiLCJwcmVmZXJyZWRfdXNlcm5hbWUiOiJuYXYyMzMzNyIsImdpdmVuX25hbWUiOiJOYXYyIiwiZW1haWwiOiJuYXYyQHlvcG1haWwuY29tIn0.HAG5Uv7F7J82HCmNsM9NjzMKEW_65nsJX-P_SC5XNfSoz9w5FkQQ4Xlx9elw5vbvtG9UU5Jn5TDMRGAnjdCZ-FMgMv0BLGy3uRKq6Xu6drf6oN9kYMIgTGYuf946EX3pelXQtL6kXwi5_OQ6OQT7Ie94l525BEn09SkeiKJsUrrxShLMlCaX3ERt83MwNdxLkuJ0tI8Jx22leksaf8cxGteC3iF31eLVxIe3ioIexUpbbTI-zBZHHURX_5tAIZvq91kV7Laibngqg4RDluaBltmbBWufFBPAYHqwFRvhix2E78t3d6cb7mx4xRNDrbTJCxHQCL2kE-VXkPGBDEHa3g"); Http.Request req = requestBuilder.build(); - when(tokenValidator.verifyUserToken(Mockito.anyString())).thenReturn("authorized-user"); + when(tokenValidator.verifyUserToken(Mockito.anyString(), Mockito.anyMap())) + .thenReturn("authorized-user"); when(tokenValidator.verifyManagedUserToken( - Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyMap())) .thenReturn("authorized-user"); assertEquals( - (String) RequestInterceptor.verifyRequestData(requestBuilder.build()).get(JsonKey.USER_ID), + (String) + RequestInterceptor.verifyRequestData(requestBuilder.build(), new HashMap<>()) + .get(JsonKey.USER_ID), "authorized-user"); } @@ -143,7 +154,9 @@ public class RequestInterceptorTest { "eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICIyZUNvWGlZRHFDbHRaX1F1ZXNRMEhtNkNYVF91emJiN2d3bXlMZXhsN1JnIn0.eyJqdGkiOiIwMTVmNmRlOC1jODRiLTRkNmUtOGRkYy1mNzZmNTk3NTViNjgiLCJleHAiOjE1OTQxMDg0MjUsIm5iZiI6MCwiaWF0IjoxNTk0MDIyMDI1LCJpc3MiOiJodHRwczovL3N0YWdpbmcubnRwLm5ldC5pbi9hdXRoL3JlYWxtcy9zdW5iaXJkIiwiYXVkIjoiYWRtaW4tY2xpIiwic3ViIjoiZjo5MzFhOWRjOS00NTk0LTQ4MzktYWExNi1jZjBjYWMwOTYzODE6M2Y0YmYzMTEtOTNkMy00ODY3LTgxMGMtZGViMDYzYjQzNzg5IiwidHlwIjoiQmVhcmVyIiwiYXpwIjoiYWRtaW4tY2xpIiwiYXV0aF90aW1lIjowLCJzZXNzaW9uX3N0YXRlIjoiZGFmYzU0YmUtNmZkOS00MDRlLTljYzctN2FkYzYxYzVjYzI1IiwiYWNyIjoiMSIsImFsbG93ZWQtb3JpZ2lucyI6W10sInJlYWxtX2FjY2VzcyI6eyJyb2xlcyI6WyJ1bWFfYXV0aG9yaXphdGlvbiJdfSwicmVzb3VyY2VfYWNjZXNzIjp7fSwibmFtZSI6Ik5hdjIiLCJwcmVmZXJyZWRfdXNlcm5hbWUiOiJuYXYyMzMzNyIsImdpdmVuX25hbWUiOiJOYXYyIiwiZW1haWwiOiJuYXYyQHlvcG1haWwuY29tIn0.HAG5Uv7F7J82HCmNsM9NjzMKEW_65nsJX-P_SC5XNfSoz9w5FkQQ4Xlx9elw5vbvtG9UU5Jn5TDMRGAnjdCZ-FMgMv0BLGy3uRKq6Xu6drf6oN9kYMIgTGYuf946EX3pelXQtL6kXwi5_OQ6OQT7Ie94l525BEn09SkeiKJsUrrxShLMlCaX3ERt83MwNdxLkuJ0tI8Jx22leksaf8cxGteC3iF31eLVxIe3ioIexUpbbTI-zBZHHURX_5tAIZvq91kV7Laibngqg4RDluaBltmbBWufFBPAYHqwFRvhix2E78t3d6cb7mx4xRNDrbTJCxHQCL2kE-VXkPGBDEHa3g"); Http.Request req = requestBuilder.build(); assertEquals( - (String) RequestInterceptor.verifyRequestData(requestBuilder.build()).get(JsonKey.USER_ID), + (String) + RequestInterceptor.verifyRequestData(requestBuilder.build(), new HashMap<>()) + .get(JsonKey.USER_ID), JsonKey.UNAUTHORIZED); } } diff --git a/core/actor-core/src/main/java/org/sunbird/actor/core/BaseActor.java b/core/actor-core/src/main/java/org/sunbird/actor/core/BaseActor.java index 7d53a05fb..020d18bc2 100644 --- a/core/actor-core/src/main/java/org/sunbird/actor/core/BaseActor.java +++ b/core/actor-core/src/main/java/org/sunbird/actor/core/BaseActor.java @@ -7,7 +7,7 @@ import org.sunbird.logging.LoggerUtil; import org.sunbird.request.Request; public abstract class BaseActor extends UntypedAbstractActor { - public LoggerUtil logger = new LoggerUtil(this.getClass()); + public final LoggerUtil logger = new LoggerUtil(this.getClass()); public abstract void onReceive(Request request) throws Throwable; @@ -16,7 +16,6 @@ public abstract class BaseActor extends UntypedAbstractActor { if (message instanceof Request) { Request request = (Request) message; String operation = request.getOperation(); - logger.debug(request.getRequestContext(), "onReceive called for operation: " + operation); try { onReceive(request); } catch (Exception e) { diff --git a/core/cassandra-utils/src/main/java/org/sunbird/cassandraimpl/CassandraDACImpl.java b/core/cassandra-utils/src/main/java/org/sunbird/cassandraimpl/CassandraDACImpl.java index f6d77ca95..89ee7cf67 100644 --- a/core/cassandra-utils/src/main/java/org/sunbird/cassandraimpl/CassandraDACImpl.java +++ b/core/cassandra-utils/src/main/java/org/sunbird/cassandraimpl/CassandraDACImpl.java @@ -22,7 +22,7 @@ import org.sunbird.request.RequestContext; import org.sunbird.response.Response; public class CassandraDACImpl extends CassandraOperationImpl { - private LoggerUtil logger = new LoggerUtil(CassandraDACImpl.class); + private final LoggerUtil logger = new LoggerUtil(CassandraDACImpl.class); public Response getRecords( String keySpace, diff --git a/core/cassandra-utils/src/main/java/org/sunbird/cassandraimpl/CassandraOperationImpl.java b/core/cassandra-utils/src/main/java/org/sunbird/cassandraimpl/CassandraOperationImpl.java index 1475f9e35..34e58f02a 100644 --- a/core/cassandra-utils/src/main/java/org/sunbird/cassandraimpl/CassandraOperationImpl.java +++ b/core/cassandra-utils/src/main/java/org/sunbird/cassandraimpl/CassandraOperationImpl.java @@ -45,7 +45,7 @@ import org.sunbird.response.Response; public abstract class CassandraOperationImpl implements CassandraOperation { protected CassandraConnectionManager connectionManager; - private LoggerUtil logger = new LoggerUtil(CassandraOperationImpl.class); + private final LoggerUtil logger = new LoggerUtil(CassandraOperationImpl.class); public CassandraOperationImpl() { connectionManager = CassandraConnectionMngrFactory.getInstance(); diff --git a/core/cassandra-utils/src/main/java/org/sunbird/common/CassandraPropertyReader.java b/core/cassandra-utils/src/main/java/org/sunbird/common/CassandraPropertyReader.java index 26988a8de..da5d23047 100644 --- a/core/cassandra-utils/src/main/java/org/sunbird/common/CassandraPropertyReader.java +++ b/core/cassandra-utils/src/main/java/org/sunbird/common/CassandraPropertyReader.java @@ -12,7 +12,7 @@ import org.sunbird.logging.LoggerUtil; * @author Amit Kumar */ public class CassandraPropertyReader { - private static LoggerUtil logger = new LoggerUtil(CassandraPropertyReader.class); + private static final LoggerUtil logger = new LoggerUtil(CassandraPropertyReader.class); private final Properties properties = new Properties(); private final String[] fileName = { diff --git a/core/cassandra-utils/src/main/java/org/sunbird/common/CassandraUtil.java b/core/cassandra-utils/src/main/java/org/sunbird/common/CassandraUtil.java index bff257b63..9bddc6e76 100644 --- a/core/cassandra-utils/src/main/java/org/sunbird/common/CassandraUtil.java +++ b/core/cassandra-utils/src/main/java/org/sunbird/common/CassandraUtil.java @@ -32,7 +32,7 @@ import org.sunbird.util.ProjectUtil; * @author Amit Kumar */ public final class CassandraUtil { - private static LoggerUtil logger = new LoggerUtil(CassandraUtil.class); + private static final LoggerUtil logger = new LoggerUtil(CassandraUtil.class); private static final CassandraPropertyReader propertiesCache = CassandraPropertyReader.getInstance(); diff --git a/core/cassandra-utils/src/main/java/org/sunbird/helper/CassandraConnectionManagerImpl.java b/core/cassandra-utils/src/main/java/org/sunbird/helper/CassandraConnectionManagerImpl.java index de0b2c89e..1c4d2a6bf 100644 --- a/core/cassandra-utils/src/main/java/org/sunbird/helper/CassandraConnectionManagerImpl.java +++ b/core/cassandra-utils/src/main/java/org/sunbird/helper/CassandraConnectionManagerImpl.java @@ -17,10 +17,10 @@ import org.sunbird.logging.LoggerUtil; import org.sunbird.util.ProjectUtil; public class CassandraConnectionManagerImpl implements CassandraConnectionManager { - private static LoggerUtil logger = new LoggerUtil(CassandraConnectionManagerImpl.class); + private static final LoggerUtil logger = new LoggerUtil(CassandraConnectionManagerImpl.class); private static Cluster cluster; - private static Map<String, Session> cassandraSessionMap = new ConcurrentHashMap<>(2); + private static final Map<String, Session> cassandraSessionMap = new ConcurrentHashMap<>(2); static { registerShutDownHook(); diff --git a/core/cassandra-utils/src/main/resources/cassandratablecolumn.properties b/core/cassandra-utils/src/main/resources/cassandratablecolumn.properties index e946ad13d..82dc79b2a 100644 --- a/core/cassandra-utils/src/main/resources/cassandratablecolumn.properties +++ b/core/cassandra-utils/src/main/resources/cassandratablecolumn.properties @@ -154,4 +154,5 @@ profileusertype=profileUserType profilelocation=profileLocation attemptedcount=attemptedCount hashtagid=hashTagId -associationtype=associationType \ No newline at end of file +associationtype=associationType +profileusertypes=profileUserTypes \ No newline at end of file diff --git a/core/es-utils/src/main/java/org/sunbird/common/ElasticSearchHelper.java b/core/es-utils/src/main/java/org/sunbird/common/ElasticSearchHelper.java index d5318b346..64dfbf687 100644 --- a/core/es-utils/src/main/java/org/sunbird/common/ElasticSearchHelper.java +++ b/core/es-utils/src/main/java/org/sunbird/common/ElasticSearchHelper.java @@ -51,7 +51,7 @@ import scala.concurrent.Future; * @author mayank:github.com/iostream04 */ public class ElasticSearchHelper { - private static LoggerUtil logger = new LoggerUtil(ElasticSearchHelper.class); + private static final LoggerUtil logger = new LoggerUtil(ElasticSearchHelper.class); public static final String LTE = "<="; public static final String LT = "<"; public static final String GTE = ">="; @@ -61,10 +61,8 @@ public class ElasticSearchHelper { public static final String ENDS_WITH = "endsWith"; public static final String SOFT_MODE = "soft"; public static final String RAW_APPEND = ".raw"; - protected static Map<String, Boolean> indexMap = new HashMap<>(); - protected static Map<String, Boolean> typeMap = new HashMap<>(); protected static final String ES_CONFIG_FILE = "elasticsearch.conf"; - private static Config config = ConfigUtil.getConfig(ES_CONFIG_FILE); + private static final Config config = ConfigUtil.getConfig(ES_CONFIG_FILE); public static final int WAIT_TIME = 5; public static Timeout timeout = new Timeout(WAIT_TIME, TimeUnit.SECONDS); public static final List<String> upsertResults = diff --git a/core/es-utils/src/main/java/org/sunbird/common/ElasticSearchRestHighImpl.java b/core/es-utils/src/main/java/org/sunbird/common/ElasticSearchRestHighImpl.java index a9c599711..3a1ff90f8 100644 --- a/core/es-utils/src/main/java/org/sunbird/common/ElasticSearchRestHighImpl.java +++ b/core/es-utils/src/main/java/org/sunbird/common/ElasticSearchRestHighImpl.java @@ -54,7 +54,7 @@ import scala.concurrent.Promise; */ public class ElasticSearchRestHighImpl implements ElasticSearchService { private static final String ERROR = "ERROR"; - private static LoggerUtil logger = new LoggerUtil(ElasticSearchRestHighImpl.class); + private static final LoggerUtil logger = new LoggerUtil(ElasticSearchRestHighImpl.class); /** * This method will put a new data entry inside Elastic search. identifier value becomes _id diff --git a/core/es-utils/src/main/java/org/sunbird/helper/ConnectionManager.java b/core/es-utils/src/main/java/org/sunbird/helper/ConnectionManager.java index df48c575a..af41874f4 100644 --- a/core/es-utils/src/main/java/org/sunbird/helper/ConnectionManager.java +++ b/core/es-utils/src/main/java/org/sunbird/helper/ConnectionManager.java @@ -18,7 +18,7 @@ import org.sunbird.logging.LoggerUtil; * @author Manzarul */ public class ConnectionManager { - private static LoggerUtil logger = new LoggerUtil(ConnectionManager.class); + private static final LoggerUtil logger = new LoggerUtil(ConnectionManager.class); private static RestHighLevelClient restClient = null; private static List<String> host = new ArrayList<>(); diff --git a/core/notification-utils/src/main/java/org/sunbird/notification/sms/providerimpl/Msg91SmsProvider.java b/core/notification-utils/src/main/java/org/sunbird/notification/sms/providerimpl/Msg91SmsProvider.java index e8e955a68..ab313129c 100644 --- a/core/notification-utils/src/main/java/org/sunbird/notification/sms/providerimpl/Msg91SmsProvider.java +++ b/core/notification-utils/src/main/java/org/sunbird/notification/sms/providerimpl/Msg91SmsProvider.java @@ -23,7 +23,7 @@ import org.sunbird.notification.utils.PropertiesCache; import org.sunbird.request.RequestContext; public class Msg91SmsProvider implements ISmsProvider { - private static LoggerUtil logger = new LoggerUtil(Msg91SmsProvider.class); + private static final LoggerUtil logger = new LoggerUtil(Msg91SmsProvider.class); private static String baseUrl = null; private static String getUrl = null; diff --git a/core/notification-utils/src/main/java/org/sunbird/notification/sms/providerimpl/NICGatewaySmsProvider.java b/core/notification-utils/src/main/java/org/sunbird/notification/sms/providerimpl/NICGatewaySmsProvider.java index 2cf9ab1f4..d23c9e11f 100644 --- a/core/notification-utils/src/main/java/org/sunbird/notification/sms/providerimpl/NICGatewaySmsProvider.java +++ b/core/notification-utils/src/main/java/org/sunbird/notification/sms/providerimpl/NICGatewaySmsProvider.java @@ -14,7 +14,7 @@ import org.sunbird.notification.utils.PropertiesCache; import org.sunbird.request.RequestContext; public class NICGatewaySmsProvider implements ISmsProvider { - private static LoggerUtil logger = new LoggerUtil(NICGatewaySmsProvider.class); + private static final LoggerUtil logger = new LoggerUtil(NICGatewaySmsProvider.class); private static String baseUrl = null; private static String senderId = null; diff --git a/core/notification-utils/src/main/java/org/sunbird/notification/utils/JsonUtil.java b/core/notification-utils/src/main/java/org/sunbird/notification/utils/JsonUtil.java index a524b5b61..ee58e1e8d 100644 --- a/core/notification-utils/src/main/java/org/sunbird/notification/utils/JsonUtil.java +++ b/core/notification-utils/src/main/java/org/sunbird/notification/utils/JsonUtil.java @@ -7,7 +7,7 @@ import org.sunbird.logging.LoggerUtil; import org.sunbird.request.RequestContext; public class JsonUtil { - private static LoggerUtil logger = new LoggerUtil(JsonUtil.class); + private static final LoggerUtil logger = new LoggerUtil(JsonUtil.class); public static String toJson(Object object, RequestContext context) { ObjectMapper mapper = new ObjectMapper(); diff --git a/core/notification-utils/src/main/java/org/sunbird/notification/utils/PropertiesCache.java b/core/notification-utils/src/main/java/org/sunbird/notification/utils/PropertiesCache.java index 9064fbd15..6154bf98a 100644 --- a/core/notification-utils/src/main/java/org/sunbird/notification/utils/PropertiesCache.java +++ b/core/notification-utils/src/main/java/org/sunbird/notification/utils/PropertiesCache.java @@ -6,7 +6,7 @@ import java.util.Properties; import org.sunbird.logging.LoggerUtil; public class PropertiesCache { - private static LoggerUtil logger = new LoggerUtil(PropertiesCache.class); + private static final LoggerUtil logger = new LoggerUtil(PropertiesCache.class); private final String fileName = "configuration.properties"; private final Properties configProp = new Properties(); private static PropertiesCache instance; diff --git a/core/notification-utils/src/main/java/org/sunbird/notification/utils/SmsTemplateUtil.java b/core/notification-utils/src/main/java/org/sunbird/notification/utils/SmsTemplateUtil.java index e794d51cd..2042e64f0 100644 --- a/core/notification-utils/src/main/java/org/sunbird/notification/utils/SmsTemplateUtil.java +++ b/core/notification-utils/src/main/java/org/sunbird/notification/utils/SmsTemplateUtil.java @@ -12,8 +12,8 @@ import org.sunbird.logging.LoggerUtil; import org.sunbird.response.Response; public class SmsTemplateUtil { - private static LoggerUtil logger = new LoggerUtil(SmsTemplateUtil.class); - private static CassandraOperation cassandraOperation = ServiceFactory.getInstance(); + private static final LoggerUtil logger = new LoggerUtil(SmsTemplateUtil.class); + private static final CassandraOperation cassandraOperation = ServiceFactory.getInstance(); public static Map<String, Map<String, String>> getSmsTemplateConfigMap() { Response response = diff --git a/core/platform-common/src/main/java/org/sunbird/auth/verifier/AccessTokenValidator.java b/core/platform-common/src/main/java/org/sunbird/auth/verifier/AccessTokenValidator.java index 331139f12..2adf0b867 100755 --- a/core/platform-common/src/main/java/org/sunbird/auth/verifier/AccessTokenValidator.java +++ b/core/platform-common/src/main/java/org/sunbird/auth/verifier/AccessTokenValidator.java @@ -11,12 +11,13 @@ import org.sunbird.keys.JsonKey; import org.sunbird.logging.LoggerUtil; public class AccessTokenValidator { - private static LoggerUtil logger = new LoggerUtil(AccessTokenValidator.class); - private static ObjectMapper mapper = new ObjectMapper(); - private static String sso_url = System.getenv(JsonKey.SUNBIRD_SSO_URL); - private static String realm = System.getenv(JsonKey.SUNBIRD_SSO_RELAM); + private static final LoggerUtil logger = new LoggerUtil(AccessTokenValidator.class); + private static final ObjectMapper mapper = new ObjectMapper(); + private static final String sso_url = System.getenv(JsonKey.SUNBIRD_SSO_URL); + private static final String realm = System.getenv(JsonKey.SUNBIRD_SSO_RELAM); - private static Map<String, Object> validateToken(String token) throws JsonProcessingException { + private static Map<String, Object> validateToken(String token, Map<String, Object> requestContext) + throws JsonProcessingException { String[] tokenElements = token.split("\\."); String header = tokenElements[0]; String body = tokenElements[1]; @@ -30,12 +31,14 @@ public class AccessTokenValidator { payLoad, decodeFromBase64(signature), KeyManager.getPublicKey(keyId).getPublicKey(), - JsonKey.SHA_256_WITH_RSA); + JsonKey.SHA_256_WITH_RSA, + requestContext); if (isValid) { Map<String, Object> tokenBody = mapper.readValue(new String(decodeFromBase64(body)), Map.class); boolean isExp = isExpired((Integer) tokenBody.get("exp")); if (isExp) { + logger.info("Token is expired " + token + ", request context data :" + requestContext); return Collections.EMPTY_MAP; } return tokenBody; @@ -53,10 +56,13 @@ public class AccessTokenValidator { * @return */ public static String verifyManagedUserToken( - String managedEncToken, String requestedByUserId, String requestedForUserId) { + String managedEncToken, + String requestedByUserId, + String requestedForUserId, + Map<String, Object> requestContext) { String managedFor = JsonKey.UNAUTHORIZED; try { - Map<String, Object> payload = validateToken(managedEncToken); + Map<String, Object> payload = validateToken(managedEncToken, requestContext); if (MapUtils.isNotEmpty(payload)) { String parentId = (String) payload.get(JsonKey.PARENT_ID); String muaId = (String) payload.get(JsonKey.SUB); @@ -68,7 +74,9 @@ public class AccessTokenValidator { + " requestedByUserID: " + requestedByUserId + " requestedForUserId: " - + requestedForUserId); + + requestedForUserId + + " request context data : " + + requestContext); boolean isValid = parentId.equalsIgnoreCase(requestedByUserId) && muaId.equalsIgnoreCase(requestedForUserId); @@ -77,17 +85,25 @@ public class AccessTokenValidator { } } } catch (Exception ex) { - logger.error("Exception in verifyManagedUserToken: Token : "+managedEncToken, ex); + logger.error( + "Exception in verifyManagedUserToken: Token : " + + managedEncToken + + ", request context data :" + + requestContext, + ex); } return managedFor; } - public static String verifyUserToken(String token) { + public static String verifyUserToken(String token, Map<String, Object> requestContext) { String userId = JsonKey.UNAUTHORIZED; try { - Map<String, Object> payload = validateToken(token); - - logger.info("learner access token validateToken() :" + payload.toString()); + Map<String, Object> payload = validateToken(token, requestContext); + logger.debug( + "learner access token validateToken() :" + + payload.toString() + + ", request context data : " + + requestContext); if (MapUtils.isNotEmpty(payload) && checkIss((String) payload.get("iss"))) { userId = (String) payload.get(JsonKey.SUB); if (StringUtils.isNotBlank(userId)) { @@ -96,10 +112,54 @@ public class AccessTokenValidator { } } } catch (Exception ex) { - logger.error("Exception in verifyUserAccessToken: Token : "+token, ex); + logger.error( + "Exception in verifyUserAccessToken: Token : " + + token + + ", request context data : " + + requestContext, + ex); } if (JsonKey.UNAUTHORIZED.equalsIgnoreCase(userId)) { - logger.info("verifyUserAccessToken: Invalid User Token: "+token); + logger.info( + "verifyUserAccessToken: Invalid User Token: " + + token + + ", request context data : " + + requestContext); + } + return userId; + } + + public static String verifySourceUserToken( + String token, String url, Map<String, Object> requestContext) { + String userId = JsonKey.UNAUTHORIZED; + try { + Map<String, Object> payload = validateToken(token, requestContext); + logger.debug( + "learner source access token validateToken() :" + + payload.toString() + + ", request context data : " + + requestContext); + if (MapUtils.isNotEmpty(payload) && checkSourceIss((String) payload.get("iss"), url)) { + userId = (String) payload.get(JsonKey.SUB); + if (StringUtils.isNotBlank(userId)) { + int pos = userId.lastIndexOf(":"); + userId = userId.substring(pos + 1); + } + } + } catch (Exception ex) { + logger.error( + "Exception in verifySourceUserToken: Token : " + + token + + ", request context data : " + + requestContext, + ex); + } + if (JsonKey.UNAUTHORIZED.equalsIgnoreCase(userId)) { + logger.info( + "verifySourceUserToken: Invalid source user Token: " + + token + + ", request context data : " + + requestContext); } return userId; } @@ -109,6 +169,12 @@ public class AccessTokenValidator { return (realmUrl.equalsIgnoreCase(iss)); } + private static boolean checkSourceIss(String iss, String url) { + String ssoUrl = (url != null ? url : sso_url); + String realmUrl = ssoUrl + "realms/" + realm; + return (realmUrl.equalsIgnoreCase(iss)); + } + private static boolean isExpired(Integer expiration) { return (Time.currentTime() > expiration); } diff --git a/core/platform-common/src/main/java/org/sunbird/auth/verifier/CryptoUtil.java b/core/platform-common/src/main/java/org/sunbird/auth/verifier/CryptoUtil.java index 283318983..3460c1792 100755 --- a/core/platform-common/src/main/java/org/sunbird/auth/verifier/CryptoUtil.java +++ b/core/platform-common/src/main/java/org/sunbird/auth/verifier/CryptoUtil.java @@ -1,20 +1,24 @@ package org.sunbird.auth.verifier; -import org.sunbird.logging.LoggerUtil; - import java.nio.charset.Charset; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.PublicKey; import java.security.Signature; import java.security.SignatureException; +import java.util.Map; +import org.sunbird.logging.LoggerUtil; public class CryptoUtil { private static final Charset US_ASCII = Charset.forName("US-ASCII"); - private static LoggerUtil logger = new LoggerUtil(CryptoUtil.class); + private static final LoggerUtil logger = new LoggerUtil(CryptoUtil.class); public static boolean verifyRSASign( - String payLoad, byte[] signature, PublicKey key, String algorithm) { + String payLoad, + byte[] signature, + PublicKey key, + String algorithm, + Map<String, Object> requestContext) { Signature sign; try { sign = Signature.getInstance(algorithm); @@ -22,7 +26,12 @@ public class CryptoUtil { sign.update(payLoad.getBytes(US_ASCII)); return sign.verify(signature); } catch (NoSuchAlgorithmException | InvalidKeyException | SignatureException e) { - logger.error("verifyRSASign: Exception occurred while token verification: "+e.getMessage() , e); + logger.error( + "verifyRSASign: Exception occurred while token verification: " + + e.getMessage() + + ", request context data :" + + requestContext, + e); return false; } } diff --git a/core/platform-common/src/main/java/org/sunbird/auth/verifier/KeyManager.java b/core/platform-common/src/main/java/org/sunbird/auth/verifier/KeyManager.java index 5a5ba30d0..939df1fc9 100644 --- a/core/platform-common/src/main/java/org/sunbird/auth/verifier/KeyManager.java +++ b/core/platform-common/src/main/java/org/sunbird/auth/verifier/KeyManager.java @@ -18,10 +18,10 @@ import org.sunbird.util.PropertiesCache; public class KeyManager { - private static LoggerUtil logger = new LoggerUtil(KeyManager.class); - private static PropertiesCache propertiesCache = PropertiesCache.getInstance(); + private static final LoggerUtil logger = new LoggerUtil(KeyManager.class); + private static final PropertiesCache propertiesCache = PropertiesCache.getInstance(); - private static Map<String, KeyData> keyMap = new HashMap<>(); + private static final Map<String, KeyData> keyMap = new HashMap<>(); public static void init() { String basePath = propertiesCache.getProperty(JsonKey.ACCESS_TOKEN_PUBLICKEY_BASEPATH); diff --git a/core/platform-common/src/main/java/org/sunbird/azure/AzureConnectionManager.java b/core/platform-common/src/main/java/org/sunbird/azure/AzureConnectionManager.java index 864538e71..9f030953d 100644 --- a/core/platform-common/src/main/java/org/sunbird/azure/AzureConnectionManager.java +++ b/core/platform-common/src/main/java/org/sunbird/azure/AzureConnectionManager.java @@ -22,7 +22,7 @@ import org.sunbird.util.ProjectUtil; */ public class AzureConnectionManager { - private static LoggerUtil logger = new LoggerUtil(AzureConnectionManager.class); + private static final LoggerUtil logger = new LoggerUtil(AzureConnectionManager.class); private static String accountName = ""; private static String accountKey = ""; private static String storageAccountString; diff --git a/core/platform-common/src/main/java/org/sunbird/azure/AzureFileUtility.java b/core/platform-common/src/main/java/org/sunbird/azure/AzureFileUtility.java index b04effefc..cff1fd558 100644 --- a/core/platform-common/src/main/java/org/sunbird/azure/AzureFileUtility.java +++ b/core/platform-common/src/main/java/org/sunbird/azure/AzureFileUtility.java @@ -21,7 +21,7 @@ import org.sunbird.request.RequestContext; /** @author Manzarul */ public class AzureFileUtility { - private static LoggerUtil logger = new LoggerUtil(AzureFileUtility.class); + private static final LoggerUtil logger = new LoggerUtil(AzureFileUtility.class); private static final String DEFAULT_CONTAINER = "default"; diff --git a/core/platform-common/src/main/java/org/sunbird/azure/CloudServiceFactory.java b/core/platform-common/src/main/java/org/sunbird/azure/CloudServiceFactory.java index 154222a9d..6e2a825af 100644 --- a/core/platform-common/src/main/java/org/sunbird/azure/CloudServiceFactory.java +++ b/core/platform-common/src/main/java/org/sunbird/azure/CloudServiceFactory.java @@ -11,8 +11,8 @@ import java.util.Map; */ public class CloudServiceFactory { - private static Map<String, CloudService> factory = new HashMap<>(); - private static List<String> allowedServiceNames = Arrays.asList("Azure", "Amazon S3"); + private static final Map<String, CloudService> factory = new HashMap<>(); + private static final List<String> allowedServiceNames = Arrays.asList("Azure", "Amazon S3"); private CloudServiceFactory() {} diff --git a/core/platform-common/src/main/java/org/sunbird/datasecurity/impl/DefaultDecryptionServiceImpl.java b/core/platform-common/src/main/java/org/sunbird/datasecurity/impl/DefaultDecryptionServiceImpl.java index 06a8f30bb..a30d51d64 100644 --- a/core/platform-common/src/main/java/org/sunbird/datasecurity/impl/DefaultDecryptionServiceImpl.java +++ b/core/platform-common/src/main/java/org/sunbird/datasecurity/impl/DefaultDecryptionServiceImpl.java @@ -18,7 +18,7 @@ import org.sunbird.request.RequestContext; import org.sunbird.util.ProjectUtil; public class DefaultDecryptionServiceImpl implements DecryptionService { - private static LoggerUtil logger = new LoggerUtil(DefaultDecryptionServiceImpl.class); + private static final LoggerUtil logger = new LoggerUtil(DefaultDecryptionServiceImpl.class); private static String sunbird_encryption = ""; diff --git a/core/platform-common/src/main/java/org/sunbird/exception/ResponseCode.java b/core/platform-common/src/main/java/org/sunbird/exception/ResponseCode.java index f2ec17cc0..109d8a450 100644 --- a/core/platform-common/src/main/java/org/sunbird/exception/ResponseCode.java +++ b/core/platform-common/src/main/java/org/sunbird/exception/ResponseCode.java @@ -61,6 +61,7 @@ public enum ResponseCode { ResponseMessage.Key.ERROR_ATTRIBUTE_CONFLICT, ResponseMessage.Message.ERROR_ATTRIBUTE_CONFLICT), rolesRequired(ResponseMessage.Key.ROLES_MISSING, ResponseMessage.Message.ROLES_MISSING), + profileUserTypesRequired(ResponseMessage.Key.PROFILE_USER_TYPES_MISSING, ResponseMessage.Message.PROFILE_USER_TYPES_MISSING), emptyRolesProvided( ResponseMessage.Key.EMPTY_ROLES_PROVIDED, ResponseMessage.Message.EMPTY_ROLES_PROVIDED), contentTypeRequiredError( diff --git a/core/platform-common/src/main/java/org/sunbird/exception/ResponseMessage.java b/core/platform-common/src/main/java/org/sunbird/exception/ResponseMessage.java index 18ec57606..a7a970ad4 100644 --- a/core/platform-common/src/main/java/org/sunbird/exception/ResponseMessage.java +++ b/core/platform-common/src/main/java/org/sunbird/exception/ResponseMessage.java @@ -47,6 +47,7 @@ public interface ResponseMessage { String DATA_TYPE_ERROR = "Data type of {0} should be {1}."; String ERROR_ATTRIBUTE_CONFLICT = "Either pass attribute {0} or {1} but not both."; String ROLES_MISSING = "user role is required."; + String PROFILE_USER_TYPES_MISSING = "User type is required."; String EMPTY_ROLES_PROVIDED = "Roles cannot be empty."; String CHANNEL_REG_FAILED = "Channel Registration failed."; String SLUG_IS_NOT_UNIQUE = @@ -215,6 +216,7 @@ public interface ResponseMessage { String DATA_TYPE_ERROR = "DATA_TYPE_ERROR"; String ERROR_ATTRIBUTE_CONFLICT = "ERROR_ATTRIBUTE_CONFLICT"; String ROLES_MISSING = "ROLES_REQUIRED_ERROR"; + String PROFILE_USER_TYPES_MISSING = "PROFILE_USER_TYPES_REQUIRED_ERROR"; String EMPTY_ROLES_PROVIDED = "EMPTY_ROLES_PROVIDED"; String CONTENT_TYPE_ERROR = "CONTENT_TYPE_ERROR"; String INVALID_PROPERTY_ERROR = "INVALID_PROPERTY_ERROR"; diff --git a/core/platform-common/src/main/java/org/sunbird/http/HttpClientUtil.java b/core/platform-common/src/main/java/org/sunbird/http/HttpClientUtil.java index 655463360..e5707e390 100644 --- a/core/platform-common/src/main/java/org/sunbird/http/HttpClientUtil.java +++ b/core/platform-common/src/main/java/org/sunbird/http/HttpClientUtil.java @@ -26,7 +26,7 @@ import org.sunbird.logging.LoggerUtil; import org.sunbird.request.RequestContext; public class HttpClientUtil { - private static LoggerUtil logger = new LoggerUtil(HttpClientUtil.class); + private static final LoggerUtil logger = new LoggerUtil(HttpClientUtil.class); private static CloseableHttpClient httpclient = null; private static HttpClientUtil httpClientUtil; @@ -82,14 +82,15 @@ public class HttpClientUtil { response = httpclient.execute(httpGet); return getResponse(response, context, "GET"); } catch (Exception ex) { - logger.error(context,"Exception occurred while calling get method", ex); + logger.error(context, "Exception occurred while calling get method", ex); return ""; } finally { closeResponse(response, context, "GET"); } } - public static String post(String requestURL, String params, Map<String, String> headers, RequestContext context) { + public static String post( + String requestURL, String params, Map<String, String> headers, RequestContext context) { CloseableHttpResponse response = null; try { HttpPost httpPost = new HttpPost(requestURL); @@ -104,7 +105,7 @@ public class HttpClientUtil { response = httpclient.execute(httpPost); return getResponse(response, context, "POST"); } catch (Exception ex) { - logger.error(context,"Exception occurred while calling Post method", ex); + logger.error(context, "Exception occurred while calling Post method", ex); return ""; } finally { closeResponse(response, context, "POST"); @@ -112,7 +113,10 @@ public class HttpClientUtil { } public static String postFormData( - String requestURL, Map<String, String> params, Map<String, String> headers, RequestContext context) { + String requestURL, + Map<String, String> params, + Map<String, String> headers, + RequestContext context) { CloseableHttpResponse response = null; try { HttpPost httpPost = new HttpPost(requestURL); @@ -133,14 +137,15 @@ public class HttpClientUtil { response = httpclient.execute(httpPost); return getResponse(response, context, "postFormData"); } catch (Exception ex) { - logger.error(context,"Exception occurred while calling postFormData method", ex); + logger.error(context, "Exception occurred while calling postFormData method", ex); return ""; } finally { closeResponse(response, context, "postFormData"); } } - public static String patch(String requestURL, String params, Map<String, String> headers, RequestContext context) { + public static String patch( + String requestURL, String params, Map<String, String> headers, RequestContext context) { CloseableHttpResponse response = null; try { HttpPatch httpPatch = new HttpPatch(requestURL); @@ -155,14 +160,15 @@ public class HttpClientUtil { response = httpclient.execute(httpPatch); return getResponse(response, context, "PATCH"); } catch (Exception ex) { - logger.error(context,"Exception occurred while calling patch method", ex); + logger.error(context, "Exception occurred while calling patch method", ex); return ""; } finally { closeResponse(response, context, "PATCH"); } } - public static String delete(String requestURL, Map<String, String> headers, RequestContext context) { + public static String delete( + String requestURL, Map<String, String> headers, RequestContext context) { CloseableHttpResponse response = null; try { HttpDelete httpDelete = new HttpDelete(requestURL); @@ -174,25 +180,31 @@ public class HttpClientUtil { response = httpclient.execute(httpDelete); return getResponse(response, context, "DELETE"); } catch (Exception ex) { - logger.error(context,"Exception occurred while calling delete method", ex); + logger.error(context, "Exception occurred while calling delete method", ex); return ""; } finally { closeResponse(response, context, "DELETE"); } } - - private static String getResponse(CloseableHttpResponse response, RequestContext context, String method) throws IOException { + private static String getResponse( + CloseableHttpResponse response, RequestContext context, String method) throws IOException { int status = response.getStatusLine().getStatusCode(); if (status >= 200 && status < 300) { HttpEntity httpEntity = response.getEntity(); StatusLine sl = response.getStatusLine(); - logger.debug(context, - "Response from "+method+" call : " + sl.getStatusCode() + " - " + sl.getReasonPhrase()); + logger.debug( + context, + "Response from " + + method + + " call : " + + sl.getStatusCode() + + " - " + + sl.getReasonPhrase()); if (null != httpEntity) { byte[] bytes = EntityUtils.toByteArray(httpEntity); String resp = new String(bytes); - logger.info(context,"Got response from "+method+" call : " + resp); + logger.info(context, "Got response from " + method + " call : " + resp); return resp; } else { return ""; @@ -203,32 +215,36 @@ public class HttpClientUtil { } } - private static void getErrorResponse(CloseableHttpResponse response, String method, RequestContext context) { + private static void getErrorResponse( + CloseableHttpResponse response, String method, RequestContext context) { try { HttpEntity httpEntity = response.getEntity(); byte[] bytes = EntityUtils.toByteArray(httpEntity); StatusLine sl = response.getStatusLine(); String resp = new String(bytes); - logger.info(context, - "Response from : " - + method - + " call " - + resp - + " status " - + sl.getStatusCode() - + " - " - + sl.getReasonPhrase()); + logger.info( + context, + "Response from : " + + method + + " call " + + resp + + " status " + + sl.getStatusCode() + + " - " + + sl.getReasonPhrase()); } catch (Exception ex) { - logger.error(context, "Exception occurred while fetching response for method "+method, ex); + logger.error(context, "Exception occurred while fetching response for method " + method, ex); } } - private static void closeResponse(CloseableHttpResponse response, RequestContext context, String method) { + private static void closeResponse( + CloseableHttpResponse response, RequestContext context, String method) { if (null != response) { try { response.close(); } catch (Exception ex) { - logger.error(context,"Exception occurred while closing "+method+" response object", ex); + logger.error( + context, "Exception occurred while closing " + method + " response object", ex); } } } diff --git a/core/platform-common/src/main/java/org/sunbird/keys/JsonKey.java b/core/platform-common/src/main/java/org/sunbird/keys/JsonKey.java index 6f1e4f740..5c9ed8eff 100644 --- a/core/platform-common/src/main/java/org/sunbird/keys/JsonKey.java +++ b/core/platform-common/src/main/java/org/sunbird/keys/JsonKey.java @@ -358,6 +358,7 @@ public final class JsonKey { public static final String SET_PW_LINK = "setPasswordLink"; public static final String SUNBIRD_URL_SHORTNER_ENABLE = "sunbird_url_shortner_enable"; public static final String USER_PROFILE_CONFIG = "userProfileConfig"; + public static final String PROFILE_USERTYPES = "profileUserTypes"; public static final String PROFILE_USERTYPE = "profileUserType"; public static final String PROFILE_LOCATION = "profileLocation"; public static final String BATCH_START_DATE = "batchStartDate"; @@ -471,7 +472,7 @@ public final class JsonKey { public static final String CATEGORY = "category"; public static final String TEMPLATE_ID = "templateId"; public static final String TEMPLATE_OPTIONS = "templateOptions"; - public static final String TEMPLATE_ID_VALUE = "resetPasswordWithOtp"; + public static final String RESET_PASSWORD_TEMPLATE_ID = "resetPasswordWithOtp"; public static final String VERSION_3 = "v3"; public static final String VERSION_4 = "v4"; public static final String WARD_LOGIN_OTP_TEMPLATE_ID = "wardLoginOTP"; @@ -536,6 +537,8 @@ public final class JsonKey { public static final String CONSENT_OBJECTID = "objectId"; public static final String CONSENT_CONSUMERTYPE = "consumerType"; public static final String CONSENT_OBJECTTYPE = "objectType"; + public static final String CONSENT_OBJECTTYPE_ORG = "Organisation"; + public static final String CONSENT_STATUS_REVOKED = "REVOKED"; // user consent req-response attributes listing - ended // user consent table columns listing - started public static final String CONSENT_CONSUMER_ID = "consumer_id"; @@ -593,6 +596,12 @@ public final class JsonKey { public static final String NIC = "NIC"; public static final String SMS_GATEWAY_PROVIDER = "sms_gateway_provider"; public static final String WELCOME_SMS_TEMPLATE = "welcomeSmsTemplate"; + public static final String EMAIL_VERIFICATION_SUBJECT = "OTP to verify Email"; + public static final String CONTACT_UPDATE_TEMPLATE_ID = "otpContactUpdateTemplate"; + public static final String OTP_CONTACT_UPDATE_TEMPLATE_EMAIL = "otpContactUpdateTemplateEmail"; + public static final String OTP_CONTACT_UPDATE_TEMPLATE_SMS = "otpContactUpdateTemplateSms"; + public static final String CONTACT_DETAILS_UPDATE_VERIFICATION_SUBJECT = + "OTP to edit Diksha Profile"; private JsonKey() {} } diff --git a/core/platform-common/src/main/java/org/sunbird/mail/SendgridConnection.java b/core/platform-common/src/main/java/org/sunbird/mail/SendgridConnection.java index 9ac84a24f..7f2cb3904 100644 --- a/core/platform-common/src/main/java/org/sunbird/mail/SendgridConnection.java +++ b/core/platform-common/src/main/java/org/sunbird/mail/SendgridConnection.java @@ -11,7 +11,7 @@ import org.sunbird.util.PropertiesCache; public class SendgridConnection { - public LoggerUtil logger = new LoggerUtil(SendgridConnection.class); + public final LoggerUtil logger = new LoggerUtil(SendgridConnection.class); private Properties props = null; private String host; diff --git a/core/platform-common/src/main/java/org/sunbird/operations/ActorOperations.java b/core/platform-common/src/main/java/org/sunbird/operations/ActorOperations.java index 748c09e55..4bb1591f9 100644 --- a/core/platform-common/src/main/java/org/sunbird/operations/ActorOperations.java +++ b/core/platform-common/src/main/java/org/sunbird/operations/ActorOperations.java @@ -11,6 +11,7 @@ public enum ActorOperations { CREATE_SSO_USER("createSSOUser"), UPDATE_USER("updateUser"), UPDATE_USER_V2("updateUserV2"), + UPDATE_USER_V3("updateUserV3"), GET_USER_PROFILE_V3("getUserProfileV3"), GET_USER_PROFILE_V4("getUserProfileV4"), GET_USER_PROFILE_V5("getUserProfileV5"), diff --git a/core/platform-common/src/main/java/org/sunbird/sso/KeyCloakConnectionProvider.java b/core/platform-common/src/main/java/org/sunbird/sso/KeyCloakConnectionProvider.java index 2e26a1510..3b2b99371 100644 --- a/core/platform-common/src/main/java/org/sunbird/sso/KeyCloakConnectionProvider.java +++ b/core/platform-common/src/main/java/org/sunbird/sso/KeyCloakConnectionProvider.java @@ -15,10 +15,10 @@ import org.sunbird.util.PropertiesCache; */ public class KeyCloakConnectionProvider { - private static LoggerUtil logger = new LoggerUtil(KeyCloakConnectionProvider.class); + private static final LoggerUtil logger = new LoggerUtil(KeyCloakConnectionProvider.class); private static Keycloak keycloak; - private static PropertiesCache cache = PropertiesCache.getInstance(); + private static final PropertiesCache cache = PropertiesCache.getInstance(); public static String SSO_URL = null; public static String SSO_REALM = null; public static String CLIENT_ID = null; diff --git a/core/platform-common/src/main/java/org/sunbird/sso/KeycloakBruteForceAttackUtil.java b/core/platform-common/src/main/java/org/sunbird/sso/KeycloakBruteForceAttackUtil.java index 833b10268..cb9e62359 100644 --- a/core/platform-common/src/main/java/org/sunbird/sso/KeycloakBruteForceAttackUtil.java +++ b/core/platform-common/src/main/java/org/sunbird/sso/KeycloakBruteForceAttackUtil.java @@ -12,7 +12,7 @@ import org.sunbird.request.RequestContext; import org.sunbird.util.ProjectUtil; public class KeycloakBruteForceAttackUtil { - private static LoggerUtil logger = new LoggerUtil(KeycloakBruteForceAttackUtil.class); + private static final LoggerUtil logger = new LoggerUtil(KeycloakBruteForceAttackUtil.class); private KeycloakBruteForceAttackUtil() {} diff --git a/core/platform-common/src/main/java/org/sunbird/sso/KeycloakRequiredActionLinkUtil.java b/core/platform-common/src/main/java/org/sunbird/sso/KeycloakRequiredActionLinkUtil.java index 7d7588d59..b56420f5a 100644 --- a/core/platform-common/src/main/java/org/sunbird/sso/KeycloakRequiredActionLinkUtil.java +++ b/core/platform-common/src/main/java/org/sunbird/sso/KeycloakRequiredActionLinkUtil.java @@ -18,7 +18,7 @@ import org.sunbird.util.ProjectUtil; * @author Amit Kumar */ public class KeycloakRequiredActionLinkUtil { - private static LoggerUtil logger = new LoggerUtil(KeycloakRequiredActionLinkUtil.class); + private static final LoggerUtil logger = new LoggerUtil(KeycloakRequiredActionLinkUtil.class); public static final String VERIFY_EMAIL = "VERIFY_EMAIL"; public static final String UPDATE_PASSWORD = "UPDATE_PASSWORD"; private static final String CLIENT_ID = "clientId"; @@ -94,7 +94,8 @@ public class KeycloakRequiredActionLinkUtil { + "realms/" + ProjectUtil.getConfigValue(JsonKey.SUNBIRD_SSO_RELAM) + SUNBIRD_KEYCLOAK_REQD_ACTION_LINK; - String response = HttpClientUtil.post(url, mapper.writeValueAsString(request), headers, context); + String response = + HttpClientUtil.post(url, mapper.writeValueAsString(request), headers, context); logger.info(context, "KeycloakRequiredActionLinkUtil:generateLink: Response = " + response); diff --git a/core/platform-common/src/main/java/org/sunbird/sso/KeycloakUtil.java b/core/platform-common/src/main/java/org/sunbird/sso/KeycloakUtil.java index fcf16cf97..0ec7fe55e 100644 --- a/core/platform-common/src/main/java/org/sunbird/sso/KeycloakUtil.java +++ b/core/platform-common/src/main/java/org/sunbird/sso/KeycloakUtil.java @@ -12,7 +12,7 @@ import org.sunbird.request.RequestContext; import org.sunbird.util.ProjectUtil; public class KeycloakUtil { - private static LoggerUtil logger = new LoggerUtil(KeycloakUtil.class); + private static final LoggerUtil logger = new LoggerUtil(KeycloakUtil.class); private KeycloakUtil() {} diff --git a/core/platform-common/src/main/java/org/sunbird/telemetry/util/TelemetryGenerator.java b/core/platform-common/src/main/java/org/sunbird/telemetry/util/TelemetryGenerator.java index ceb3cb72a..60d53c607 100644 --- a/core/platform-common/src/main/java/org/sunbird/telemetry/util/TelemetryGenerator.java +++ b/core/platform-common/src/main/java/org/sunbird/telemetry/util/TelemetryGenerator.java @@ -25,9 +25,9 @@ import org.sunbird.util.ProjectUtil; * @author Arvind */ public class TelemetryGenerator { - private static LoggerUtil logger = new LoggerUtil(TelemetryGenerator.class); + private static final LoggerUtil logger = new LoggerUtil(TelemetryGenerator.class); - private static ObjectMapper mapper = new ObjectMapper(); + private static final ObjectMapper mapper = new ObjectMapper(); private TelemetryGenerator() {} diff --git a/core/platform-common/src/main/java/org/sunbird/telemetry/util/TelemetryWriter.java b/core/platform-common/src/main/java/org/sunbird/telemetry/util/TelemetryWriter.java index 79cd8a826..90abbff99 100644 --- a/core/platform-common/src/main/java/org/sunbird/telemetry/util/TelemetryWriter.java +++ b/core/platform-common/src/main/java/org/sunbird/telemetry/util/TelemetryWriter.java @@ -15,11 +15,13 @@ import org.sunbird.telemetry.validator.TelemetryObjectValidatorV3; public class TelemetryWriter { - private static TelemetryDataAssembler telemetryDataAssembler = TelemetryAssemblerFactory.get(); - private static TelemetryObjectValidator telemetryObjectValidator = + private static final TelemetryDataAssembler telemetryDataAssembler = + TelemetryAssemblerFactory.get(); + private static final TelemetryObjectValidator telemetryObjectValidator = new TelemetryObjectValidatorV3(); - private static LoggerUtil logger = new LoggerUtil(TelemetryWriter.class); - private static Logger telemetryEventLogger = LoggerFactory.getLogger("TelemetryEventLogger"); + private static final LoggerUtil logger = new LoggerUtil(TelemetryWriter.class); + private static final Logger telemetryEventLogger = + LoggerFactory.getLogger("TelemetryEventLogger"); public static void write(Request request) { try { diff --git a/core/platform-common/src/main/java/org/sunbird/telemetry/validator/TelemetryObjectValidatorV3.java b/core/platform-common/src/main/java/org/sunbird/telemetry/validator/TelemetryObjectValidatorV3.java index e5dce15a6..a41ca1139 100644 --- a/core/platform-common/src/main/java/org/sunbird/telemetry/validator/TelemetryObjectValidatorV3.java +++ b/core/platform-common/src/main/java/org/sunbird/telemetry/validator/TelemetryObjectValidatorV3.java @@ -13,9 +13,9 @@ import org.sunbird.telemetry.util.TelemetryEvents; /** @author arvind */ public class TelemetryObjectValidatorV3 implements TelemetryObjectValidator { - private static LoggerUtil logger = new LoggerUtil(TelemetryObjectValidatorV3.class); + private static final LoggerUtil logger = new LoggerUtil(TelemetryObjectValidatorV3.class); - ObjectMapper mapper = new ObjectMapper(); + private final ObjectMapper mapper = new ObjectMapper(); @Override public boolean validateAudit(String jsonString) { diff --git a/core/platform-common/src/main/java/org/sunbird/url/URLShortnerImpl.java b/core/platform-common/src/main/java/org/sunbird/url/URLShortnerImpl.java index f748a5fc1..a0b986d5f 100644 --- a/core/platform-common/src/main/java/org/sunbird/url/URLShortnerImpl.java +++ b/core/platform-common/src/main/java/org/sunbird/url/URLShortnerImpl.java @@ -14,7 +14,7 @@ import org.sunbird.util.PropertiesCache; /** @author Amit Kumar */ public class URLShortnerImpl implements URLShortner { - private static LoggerUtil logger = new LoggerUtil(URLShortnerImpl.class); + private static final LoggerUtil logger = new LoggerUtil(URLShortnerImpl.class); private static String resUrl = null; private static final String SUNBIRD_WEB_URL = "sunbird_web_url"; @@ -25,7 +25,7 @@ public class URLShortnerImpl implements URLShortner { try { flag = Boolean.parseBoolean(ProjectUtil.getConfigValue(JsonKey.SUNBIRD_URL_SHORTNER_ENABLE)); } catch (Exception ex) { - logger.error(context,"Exception occurred while parsing sunbird_url_shortner_enable key", ex); + logger.error(context, "Exception occurred while parsing sunbird_url_shortner_enable key", ex); } if (flag) { String baseUrl = PropertiesCache.getInstance().getProperty("sunbird_url_shortner_base_url"); @@ -44,7 +44,7 @@ public class URLShortnerImpl implements URLShortner { Map<String, String> dataMap = (Map<String, String>) map.get("data"); return dataMap.get("url"); } catch (IOException | ClassCastException e) { - logger.error(context,"Exception occurred while parsing " + e.getMessage(), e); + logger.error(context, "Exception occurred while parsing " + e.getMessage(), e); } } } diff --git a/core/platform-common/src/main/java/org/sunbird/validator/PhoneValidator.java b/core/platform-common/src/main/java/org/sunbird/validator/PhoneValidator.java index a96891e44..4e0fe12b4 100644 --- a/core/platform-common/src/main/java/org/sunbird/validator/PhoneValidator.java +++ b/core/platform-common/src/main/java/org/sunbird/validator/PhoneValidator.java @@ -13,7 +13,7 @@ import org.sunbird.util.PropertiesCache; * @author Amit Kumar */ public class PhoneValidator { - private static LoggerUtil logger = new LoggerUtil(PhoneValidator.class); + private static final LoggerUtil logger = new LoggerUtil(PhoneValidator.class); private PhoneValidator() {} diff --git a/core/platform-common/src/main/resources/externalresource.properties b/core/platform-common/src/main/resources/externalresource.properties index 99d574c8a..0c5199b12 100644 --- a/core/platform-common/src/main/resources/externalresource.properties +++ b/core/platform-common/src/main/resources/externalresource.properties @@ -36,7 +36,7 @@ sunbird_otp_allowed_attempt=2 #Telemetry producer related info telemetry_pdata_id=local.sunbird.learning.service telemetry_pdata_pid=learning-service -telemetry_pdata_ver=4.1.0 +telemetry_pdata_ver=4.4.0 #elastic search top n result count for telemetry searchTopN=5 ekstep.channel.update.api.url=/channel/v3/update diff --git a/core/platform-common/src/test/java/org/sunbird/auth/verifier/AccessTokenValidatorTest.java b/core/platform-common/src/test/java/org/sunbird/auth/verifier/AccessTokenValidatorTest.java index f3e320c8d..4ca9bf41b 100644 --- a/core/platform-common/src/test/java/org/sunbird/auth/verifier/AccessTokenValidatorTest.java +++ b/core/platform-common/src/test/java/org/sunbird/auth/verifier/AccessTokenValidatorTest.java @@ -60,11 +60,44 @@ public class AccessTokenValidatorTest { .thenReturn(mapper.writeValueAsString(payload).getBytes()); Mockito.when( CryptoUtil.verifyRSASign( - Mockito.anyString(), Mockito.any(), Mockito.any(), Mockito.any())) + Mockito.anyString(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.anyMap())) .thenReturn(true); String userId = AccessTokenValidator.verifyUserToken( - "eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICI5emhhVnZDbl81OEtheHpldHBzYXNZQ2lEallkemJIX3U2LV93SDk4SEc0In0.eyJqdGkiOiI5ZmQzNzgzYy01YjZmLTQ3OWQtYmMzYy0yZWEzOGUzZmRmYzgiLCJleHAiOjE1MDUxMTQyNDYsIm5iZiI6MCwiaWF0IjoxNTA1MTEzNjQ2LCJpc3MiOiJodHRwOi8vbG9jYWxob3N0OjgwODAvYXV0aC9yZWFsbXMvbWFzdGVyIiwiYXVkIjoic2VjdXJpdHktYWRtaW4tY29uc29sZSIsInN1YiI6ImIzYTZkMTY4LWJjZmQtNDE2MS1hYzVmLTljZjYyODIyNzlmMyIsInR5cCI6IkJlYXJlciIsImF6cCI6InNlY3VyaXR5LWFkbWluLWNvbnNvbGUiLCJub25jZSI6ImMxOGVlMDM2LTAyMWItNGVlZC04NWVhLTc0MjMyYzg2ZmI4ZSIsImF1dGhfdGltZSI6MTUwNTExMzY0Niwic2Vzc2lvbl9zdGF0ZSI6ImRiZTU2NDlmLTY4MDktNDA3NS05Njk5LTVhYjIyNWMwZTkyMiIsImFjciI6IjEiLCJhbGxvd2VkLW9yaWdpbnMiOltdLCJyZXNvdXJjZV9hY2Nlc3MiOnt9LCJuYW1lIjoiTWFuemFydWwgaGFxdWUiLCJwcmVmZXJyZWRfdXNlcm5hbWUiOiJ0ZXN0MTIzNDU2NyIsImdpdmVuX25hbWUiOiJNYW56YXJ1bCBoYXF1ZSIsImVtYWlsIjoidGVzdDEyM0B0LmNvbSJ9.Xdjqe16MSkiR94g-Uj_pVZ2L3gnIdKpkJ6aB82W_w_c3yEmx1mXYBdkxe4zMz3ks4OX_PWwSFEbJECHcnujUwF6Ula0xtXTfuESB9hFyiWHtVAhuh5UlCCwPnsihv5EqK6u-Qzo0aa6qZOiQK3Zo7FLpnPUDxn4yHyo3mRZUiWf76KTl8PhSMoXoWxcR2vGW0b-cPixILTZPV0xXUZoozCui70QnvTgOJDWqr7y80EWDkS4Ptn-QM3q2nJlw63mZreOG3XTdraOlcKIP5vFK992dyyHlYGqWVzigortS9Ah4cprFVuLlX8mu1cQvqHBtW-0Dq_JlcTMaztEnqvJ6XA"); + "eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICI5emhhVnZDbl81OEtheHpldHBzYXNZQ2lEallkemJIX3U2LV93SDk4SEc0In0.eyJqdGkiOiI5ZmQzNzgzYy01YjZmLTQ3OWQtYmMzYy0yZWEzOGUzZmRmYzgiLCJleHAiOjE1MDUxMTQyNDYsIm5iZiI6MCwiaWF0IjoxNTA1MTEzNjQ2LCJpc3MiOiJodHRwOi8vbG9jYWxob3N0OjgwODAvYXV0aC9yZWFsbXMvbWFzdGVyIiwiYXVkIjoic2VjdXJpdHktYWRtaW4tY29uc29sZSIsInN1YiI6ImIzYTZkMTY4LWJjZmQtNDE2MS1hYzVmLTljZjYyODIyNzlmMyIsInR5cCI6IkJlYXJlciIsImF6cCI6InNlY3VyaXR5LWFkbWluLWNvbnNvbGUiLCJub25jZSI6ImMxOGVlMDM2LTAyMWItNGVlZC04NWVhLTc0MjMyYzg2ZmI4ZSIsImF1dGhfdGltZSI6MTUwNTExMzY0Niwic2Vzc2lvbl9zdGF0ZSI6ImRiZTU2NDlmLTY4MDktNDA3NS05Njk5LTVhYjIyNWMwZTkyMiIsImFjciI6IjEiLCJhbGxvd2VkLW9yaWdpbnMiOltdLCJyZXNvdXJjZV9hY2Nlc3MiOnt9LCJuYW1lIjoiTWFuemFydWwgaGFxdWUiLCJwcmVmZXJyZWRfdXNlcm5hbWUiOiJ0ZXN0MTIzNDU2NyIsImdpdmVuX25hbWUiOiJNYW56YXJ1bCBoYXF1ZSIsImVtYWlsIjoidGVzdDEyM0B0LmNvbSJ9.Xdjqe16MSkiR94g-Uj_pVZ2L3gnIdKpkJ6aB82W_w_c3yEmx1mXYBdkxe4zMz3ks4OX_PWwSFEbJECHcnujUwF6Ula0xtXTfuESB9hFyiWHtVAhuh5UlCCwPnsihv5EqK6u-Qzo0aa6qZOiQK3Zo7FLpnPUDxn4yHyo3mRZUiWf76KTl8PhSMoXoWxcR2vGW0b-cPixILTZPV0xXUZoozCui70QnvTgOJDWqr7y80EWDkS4Ptn-QM3q2nJlw63mZreOG3XTdraOlcKIP5vFK992dyyHlYGqWVzigortS9Ah4cprFVuLlX8mu1cQvqHBtW-0Dq_JlcTMaztEnqvJ6XA", + new HashMap<>()); + assertNotNull(userId); + } + + @Test + public void verifySourceUserAccessToken() throws JsonProcessingException { + PowerMockito.mockStatic(CryptoUtil.class); + PowerMockito.mockStatic(Base64Util.class); + PowerMockito.mockStatic(KeyManager.class); + PropertiesCache propertiesCache = mock(PropertiesCache.class); + PowerMockito.when(propertiesCache.getProperty(Mockito.anyString())).thenReturn("anyString"); + KeyData keyData = PowerMockito.mock(KeyData.class); + Mockito.when(KeyManager.getPublicKey(Mockito.anyString())).thenReturn(keyData); + PublicKey publicKey = PowerMockito.mock(PublicKey.class); + Mockito.when(keyData.getPublicKey()).thenReturn(publicKey); + Map<String, Object> payload = new HashMap<>(); + int expTime = Time.currentTime() + 3600000; + payload.put("exp", expTime); + payload.put("iss", "urlrealms/master"); + payload.put("kid", "kid"); + payload.put("sub", "f:ca00376d-395f-aee687d7c8ad:10cca27c-2a13-443c-9e2b-c7d9589c1f5f"); + ObjectMapper mapper = new ObjectMapper(); + Mockito.when(Base64Util.decode(Mockito.any(String.class), Mockito.anyInt())) + .thenReturn(mapper.writeValueAsString(payload).getBytes()); + Mockito.when( + CryptoUtil.verifyRSASign( + Mockito.anyString(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.anyMap())) + .thenReturn(true); + String userId = + AccessTokenValidator.verifySourceUserToken( + "eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICI5emhhVnZDbl81OEtheHpldHBzYXNZQ2lEallkemJIX3U2LV93SDk4SEc0In0.eyJqdGkiOiI5ZmQzNzgzYy01YjZmLTQ3OWQtYmMzYy0yZWEzOGUzZmRmYzgiLCJleHAiOjE1MDUxMTQyNDYsIm5iZiI6MCwiaWF0IjoxNTA1MTEzNjQ2LCJpc3MiOiJodHRwOi8vbG9jYWxob3N0OjgwODAvYXV0aC9yZWFsbXMvbWFzdGVyIiwiYXVkIjoic2VjdXJpdHktYWRtaW4tY29uc29sZSIsInN1YiI6ImIzYTZkMTY4LWJjZmQtNDE2MS1hYzVmLTljZjYyODIyNzlmMyIsInR5cCI6IkJlYXJlciIsImF6cCI6InNlY3VyaXR5LWFkbWluLWNvbnNvbGUiLCJub25jZSI6ImMxOGVlMDM2LTAyMWItNGVlZC04NWVhLTc0MjMyYzg2ZmI4ZSIsImF1dGhfdGltZSI6MTUwNTExMzY0Niwic2Vzc2lvbl9zdGF0ZSI6ImRiZTU2NDlmLTY4MDktNDA3NS05Njk5LTVhYjIyNWMwZTkyMiIsImFjciI6IjEiLCJhbGxvd2VkLW9yaWdpbnMiOltdLCJyZXNvdXJjZV9hY2Nlc3MiOnt9LCJuYW1lIjoiTWFuemFydWwgaGFxdWUiLCJwcmVmZXJyZWRfdXNlcm5hbWUiOiJ0ZXN0MTIzNDU2NyIsImdpdmVuX25hbWUiOiJNYW56YXJ1bCBoYXF1ZSIsImVtYWlsIjoidGVzdDEyM0B0LmNvbSJ9.Xdjqe16MSkiR94g-Uj_pVZ2L3gnIdKpkJ6aB82W_w_c3yEmx1mXYBdkxe4zMz3ks4OX_PWwSFEbJECHcnujUwF6Ula0xtXTfuESB9hFyiWHtVAhuh5UlCCwPnsihv5EqK6u-Qzo0aa6qZOiQK3Zo7FLpnPUDxn4yHyo3mRZUiWf76KTl8PhSMoXoWxcR2vGW0b-cPixILTZPV0xXUZoozCui70QnvTgOJDWqr7y80EWDkS4Ptn-QM3q2nJlw63mZreOG3XTdraOlcKIP5vFK992dyyHlYGqWVzigortS9Ah4cprFVuLlX8mu1cQvqHBtW-0Dq_JlcTMaztEnqvJ6XA", + "url", + new HashMap<>()); assertNotNull(userId); } @@ -86,11 +119,12 @@ public class AccessTokenValidatorTest { .thenReturn(mapper.writeValueAsString(payload).getBytes()); Mockito.when( CryptoUtil.verifyRSASign( - Mockito.anyString(), Mockito.any(), Mockito.any(), Mockito.any())) + Mockito.anyString(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.anyMap())) .thenReturn(false); String userId = AccessTokenValidator.verifyUserToken( - "eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICI5emhhVnZDbl81OEtheHpldHBzYXNZQ2lEallkemJIX3U2LV93SDk4SEc0In0.eyJqdGkiOiI5ZmQzNzgzYy01YjZmLTQ3OWQtYmMzYy0yZWEzOGUzZmRmYzgiLCJleHAiOjE1MDUxMTQyNDYsIm5iZiI6MCwiaWF0IjoxNTA1MTEzNjQ2LCJpc3MiOiJodHRwOi8vbG9jYWxob3N0OjgwODAvYXV0aC9yZWFsbXMvbWFzdGVyIiwiYXVkIjoic2VjdXJpdHktYWRtaW4tY29uc29sZSIsInN1YiI6ImIzYTZkMTY4LWJjZmQtNDE2MS1hYzVmLTljZjYyODIyNzlmMyIsInR5cCI6IkJlYXJlciIsImF6cCI6InNlY3VyaXR5LWFkbWluLWNvbnNvbGUiLCJub25jZSI6ImMxOGVlMDM2LTAyMWItNGVlZC04NWVhLTc0MjMyYzg2ZmI4ZSIsImF1dGhfdGltZSI6MTUwNTExMzY0Niwic2Vzc2lvbl9zdGF0ZSI6ImRiZTU2NDlmLTY4MDktNDA3NS05Njk5LTVhYjIyNWMwZTkyMiIsImFjciI6IjEiLCJhbGxvd2VkLW9yaWdpbnMiOltdLCJyZXNvdXJjZV9hY2Nlc3MiOnt9LCJuYW1lIjoiTWFuemFydWwgaGFxdWUiLCJwcmVmZXJyZWRfdXNlcm5hbWUiOiJ0ZXN0MTIzNDU2NyIsImdpdmVuX25hbWUiOiJNYW56YXJ1bCBoYXF1ZSIsImVtYWlsIjoidGVzdDEyM0B0LmNvbSJ9.Xdjqe16MSkiR94g-Uj_pVZ2L3gnIdKpkJ6aB82W_w_c3yEmx1mXYBdkxe4zMz3ks4OX_PWwSFEbJECHcnujUwF6Ula0xtXTfuESB9hFyiWHtVAhuh5UlCCwPnsihv5EqK6u-Qzo0aa6qZOiQK3Zo7FLpnPUDxn4yHyo3mRZUiWf76KTl8PhSMoXoWxcR2vGW0b-cPixILTZPV0xXUZoozCui70QnvTgOJDWqr7y80EWDkS4Ptn-QM3q2nJlw63mZreOG3XTdraOlcKIP5vFK992dyyHlYGqWVzigortS9Ah4cprFVuLlX8mu1cQvqHBtW-0Dq_JlcTMaztEnqvJ6XA"); + "eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICI5emhhVnZDbl81OEtheHpldHBzYXNZQ2lEallkemJIX3U2LV93SDk4SEc0In0.eyJqdGkiOiI5ZmQzNzgzYy01YjZmLTQ3OWQtYmMzYy0yZWEzOGUzZmRmYzgiLCJleHAiOjE1MDUxMTQyNDYsIm5iZiI6MCwiaWF0IjoxNTA1MTEzNjQ2LCJpc3MiOiJodHRwOi8vbG9jYWxob3N0OjgwODAvYXV0aC9yZWFsbXMvbWFzdGVyIiwiYXVkIjoic2VjdXJpdHktYWRtaW4tY29uc29sZSIsInN1YiI6ImIzYTZkMTY4LWJjZmQtNDE2MS1hYzVmLTljZjYyODIyNzlmMyIsInR5cCI6IkJlYXJlciIsImF6cCI6InNlY3VyaXR5LWFkbWluLWNvbnNvbGUiLCJub25jZSI6ImMxOGVlMDM2LTAyMWItNGVlZC04NWVhLTc0MjMyYzg2ZmI4ZSIsImF1dGhfdGltZSI6MTUwNTExMzY0Niwic2Vzc2lvbl9zdGF0ZSI6ImRiZTU2NDlmLTY4MDktNDA3NS05Njk5LTVhYjIyNWMwZTkyMiIsImFjciI6IjEiLCJhbGxvd2VkLW9yaWdpbnMiOltdLCJyZXNvdXJjZV9hY2Nlc3MiOnt9LCJuYW1lIjoiTWFuemFydWwgaGFxdWUiLCJwcmVmZXJyZWRfdXNlcm5hbWUiOiJ0ZXN0MTIzNDU2NyIsImdpdmVuX25hbWUiOiJNYW56YXJ1bCBoYXF1ZSIsImVtYWlsIjoidGVzdDEyM0B0LmNvbSJ9.Xdjqe16MSkiR94g-Uj_pVZ2L3gnIdKpkJ6aB82W_w_c3yEmx1mXYBdkxe4zMz3ks4OX_PWwSFEbJECHcnujUwF6Ula0xtXTfuESB9hFyiWHtVAhuh5UlCCwPnsihv5EqK6u-Qzo0aa6qZOiQK3Zo7FLpnPUDxn4yHyo3mRZUiWf76KTl8PhSMoXoWxcR2vGW0b-cPixILTZPV0xXUZoozCui70QnvTgOJDWqr7y80EWDkS4Ptn-QM3q2nJlw63mZreOG3XTdraOlcKIP5vFK992dyyHlYGqWVzigortS9Ah4cprFVuLlX8mu1cQvqHBtW-0Dq_JlcTMaztEnqvJ6XA", + new HashMap<>()); assertEquals("Unauthorized", userId); } @@ -112,11 +146,12 @@ public class AccessTokenValidatorTest { .thenReturn(mapper.writeValueAsString(payload).getBytes()); Mockito.when( CryptoUtil.verifyRSASign( - Mockito.anyString(), Mockito.any(), Mockito.any(), Mockito.any())) + Mockito.anyString(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.anyMap())) .thenReturn(true); String userId = AccessTokenValidator.verifyUserToken( - "eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICI5emhhVnZDbl81OEtheHpldHBzYXNZQ2lEallkemJIX3U2LV93SDk4SEc0In0.eyJqdGkiOiI5ZmQzNzgzYy01YjZmLTQ3OWQtYmMzYy0yZWEzOGUzZmRmYzgiLCJleHAiOjE1MDUxMTQyNDYsIm5iZiI6MCwiaWF0IjoxNTA1MTEzNjQ2LCJpc3MiOiJodHRwOi8vbG9jYWxob3N0OjgwODAvYXV0aC9yZWFsbXMvbWFzdGVyIiwiYXVkIjoic2VjdXJpdHktYWRtaW4tY29uc29sZSIsInN1YiI6ImIzYTZkMTY4LWJjZmQtNDE2MS1hYzVmLTljZjYyODIyNzlmMyIsInR5cCI6IkJlYXJlciIsImF6cCI6InNlY3VyaXR5LWFkbWluLWNvbnNvbGUiLCJub25jZSI6ImMxOGVlMDM2LTAyMWItNGVlZC04NWVhLTc0MjMyYzg2ZmI4ZSIsImF1dGhfdGltZSI6MTUwNTExMzY0Niwic2Vzc2lvbl9zdGF0ZSI6ImRiZTU2NDlmLTY4MDktNDA3NS05Njk5LTVhYjIyNWMwZTkyMiIsImFjciI6IjEiLCJhbGxvd2VkLW9yaWdpbnMiOltdLCJyZXNvdXJjZV9hY2Nlc3MiOnt9LCJuYW1lIjoiTWFuemFydWwgaGFxdWUiLCJwcmVmZXJyZWRfdXNlcm5hbWUiOiJ0ZXN0MTIzNDU2NyIsImdpdmVuX25hbWUiOiJNYW56YXJ1bCBoYXF1ZSIsImVtYWlsIjoidGVzdDEyM0B0LmNvbSJ9.Xdjqe16MSkiR94g-Uj_pVZ2L3gnIdKpkJ6aB82W_w_c3yEmx1mXYBdkxe4zMz3ks4OX_PWwSFEbJECHcnujUwF6Ula0xtXTfuESB9hFyiWHtVAhuh5UlCCwPnsihv5EqK6u-Qzo0aa6qZOiQK3Zo7FLpnPUDxn4yHyo3mRZUiWf76KTl8PhSMoXoWxcR2vGW0b-cPixILTZPV0xXUZoozCui70QnvTgOJDWqr7y80EWDkS4Ptn-QM3q2nJlw63mZreOG3XTdraOlcKIP5vFK992dyyHlYGqWVzigortS9Ah4cprFVuLlX8mu1cQvqHBtW-0Dq_JlcTMaztEnqvJ6XA"); + "eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICI5emhhVnZDbl81OEtheHpldHBzYXNZQ2lEallkemJIX3U2LV93SDk4SEc0In0.eyJqdGkiOiI5ZmQzNzgzYy01YjZmLTQ3OWQtYmMzYy0yZWEzOGUzZmRmYzgiLCJleHAiOjE1MDUxMTQyNDYsIm5iZiI6MCwiaWF0IjoxNTA1MTEzNjQ2LCJpc3MiOiJodHRwOi8vbG9jYWxob3N0OjgwODAvYXV0aC9yZWFsbXMvbWFzdGVyIiwiYXVkIjoic2VjdXJpdHktYWRtaW4tY29uc29sZSIsInN1YiI6ImIzYTZkMTY4LWJjZmQtNDE2MS1hYzVmLTljZjYyODIyNzlmMyIsInR5cCI6IkJlYXJlciIsImF6cCI6InNlY3VyaXR5LWFkbWluLWNvbnNvbGUiLCJub25jZSI6ImMxOGVlMDM2LTAyMWItNGVlZC04NWVhLTc0MjMyYzg2ZmI4ZSIsImF1dGhfdGltZSI6MTUwNTExMzY0Niwic2Vzc2lvbl9zdGF0ZSI6ImRiZTU2NDlmLTY4MDktNDA3NS05Njk5LTVhYjIyNWMwZTkyMiIsImFjciI6IjEiLCJhbGxvd2VkLW9yaWdpbnMiOltdLCJyZXNvdXJjZV9hY2Nlc3MiOnt9LCJuYW1lIjoiTWFuemFydWwgaGFxdWUiLCJwcmVmZXJyZWRfdXNlcm5hbWUiOiJ0ZXN0MTIzNDU2NyIsImdpdmVuX25hbWUiOiJNYW56YXJ1bCBoYXF1ZSIsImVtYWlsIjoidGVzdDEyM0B0LmNvbSJ9.Xdjqe16MSkiR94g-Uj_pVZ2L3gnIdKpkJ6aB82W_w_c3yEmx1mXYBdkxe4zMz3ks4OX_PWwSFEbJECHcnujUwF6Ula0xtXTfuESB9hFyiWHtVAhuh5UlCCwPnsihv5EqK6u-Qzo0aa6qZOiQK3Zo7FLpnPUDxn4yHyo3mRZUiWf76KTl8PhSMoXoWxcR2vGW0b-cPixILTZPV0xXUZoozCui70QnvTgOJDWqr7y80EWDkS4Ptn-QM3q2nJlw63mZreOG3XTdraOlcKIP5vFK992dyyHlYGqWVzigortS9Ah4cprFVuLlX8mu1cQvqHBtW-0Dq_JlcTMaztEnqvJ6XA", + new HashMap<>()); assertEquals("Unauthorized", userId); } @@ -143,13 +178,14 @@ public class AccessTokenValidatorTest { Mockito.when( CryptoUtil.verifyRSASign( - Mockito.anyString(), Mockito.any(), Mockito.any(), Mockito.any())) + Mockito.anyString(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.anyMap())) .thenReturn(true); String userId = AccessTokenValidator.verifyManagedUserToken( "eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICI5emhhVnZDbl81OEtheHpldHBzYXNZQ2lEallkemJIX3U2LV93SDk4SEc0In0.eyJqdGkiOiI5ZmQzNzgzYy01YjZmLTQ3OWQtYmMzYy0yZWEzOGUzZmRmYzgiLCJleHAiOjE1MDUxMTQyNDYsIm5iZiI6MCwiaWF0IjoxNTA1MTEzNjQ2LCJpc3MiOiJodHRwOi8vbG9jYWxob3N0OjgwODAvYXV0aC9yZWFsbXMvbWFzdGVyIiwiYXVkIjoic2VjdXJpdHktYWRtaW4tY29uc29sZSIsInN1YiI6ImIzYTZkMTY4LWJjZmQtNDE2MS1hYzVmLTljZjYyODIyNzlmMyIsInR5cCI6IkJlYXJlciIsImF6cCI6InNlY3VyaXR5LWFkbWluLWNvbnNvbGUiLCJub25jZSI6ImMxOGVlMDM2LTAyMWItNGVlZC04NWVhLTc0MjMyYzg2ZmI4ZSIsImF1dGhfdGltZSI6MTUwNTExMzY0Niwic2Vzc2lvbl9zdGF0ZSI6ImRiZTU2NDlmLTY4MDktNDA3NS05Njk5LTVhYjIyNWMwZTkyMiIsImFjciI6IjEiLCJhbGxvd2VkLW9yaWdpbnMiOltdLCJyZXNvdXJjZV9hY2Nlc3MiOnt9LCJuYW1lIjoiTWFuemFydWwgaGFxdWUiLCJwcmVmZXJyZWRfdXNlcm5hbWUiOiJ0ZXN0MTIzNDU2NyIsImdpdmVuX25hbWUiOiJNYW56YXJ1bCBoYXF1ZSIsImVtYWlsIjoidGVzdDEyM0B0LmNvbSJ9.Xdjqe16MSkiR94g-Uj_pVZ2L3gnIdKpkJ6aB82W_w_c3yEmx1mXYBdkxe4zMz3ks4OX_PWwSFEbJECHcnujUwF6Ula0xtXTfuESB9hFyiWHtVAhuh5UlCCwPnsihv5EqK6u-Qzo0aa6qZOiQK3Zo7FLpnPUDxn4yHyo3mRZUiWf76KTl8PhSMoXoWxcR2vGW0b-cPixILTZPV0xXUZoozCui70QnvTgOJDWqr7y80EWDkS4Ptn-QM3q2nJlw63mZreOG3XTdraOlcKIP5vFK992dyyHlYGqWVzigortS9Ah4cprFVuLlX8mu1cQvqHBtW-0Dq_JlcTMaztEnqvJ6XA", "386c7960-7f85-4a24-8131-a8aba519ce7d", - "386c7960-7f85-4a24-8131-a8aba519ce7e"); + "386c7960-7f85-4a24-8131-a8aba519ce7e", + new HashMap<>()); assertNotNull(userId); } @@ -175,13 +211,14 @@ public class AccessTokenValidatorTest { Mockito.when( CryptoUtil.verifyRSASign( - Mockito.anyString(), Mockito.any(), Mockito.any(), Mockito.any())) + Mockito.anyString(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.anyMap())) .thenReturn(true); try { AccessTokenValidator.verifyManagedUserToken( "eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICI5emhhVnZDbl81OEtheHpldHBzYXNZQ2lEallkemJIX3U2LV93SDk4SEc0In0.eyJqdGkiOiI5ZmQzNzgzYy01YjZmLTQ3OWQtYmMzYy0yZWEzOGUzZmRmYzgiLCJleHAiOjE1MDUxMTQyNDYsIm5iZiI6MCwiaWF0IjoxNTA1MTEzNjQ2LCJpc3MiOiJodHRwOi8vbG9jYWxob3N0OjgwODAvYXV0aC9yZWFsbXMvbWFzdGVyIiwiYXVkIjoic2VjdXJpdHktYWRtaW4tY29uc29sZSIsInN1YiI6ImIzYTZkMTY4LWJjZmQtNDE2MS1hYzVmLTljZjYyODIyNzlmMyIsInR5cCI6IkJlYXJlciIsImF6cCI6InNlY3VyaXR5LWFkbWluLWNvbnNvbGUiLCJub25jZSI6ImMxOGVlMDM2LTAyMWItNGVlZC04NWVhLTc0MjMyYzg2ZmI4ZSIsImF1dGhfdGltZSI6MTUwNTExMzY0Niwic2Vzc2lvbl9zdGF0ZSI6ImRiZTU2NDlmLTY4MDktNDA3NS05Njk5LTVhYjIyNWMwZTkyMiIsImFjciI6IjEiLCJhbGxvd2VkLW9yaWdpbnMiOltdLCJyZXNvdXJjZV9hY2Nlc3MiOnt9LCJuYW1lIjoiTWFuemFydWwgaGFxdWUiLCJwcmVmZXJyZWRfdXNlcm5hbWUiOiJ0ZXN0MTIzNDU2NyIsImdpdmVuX25hbWUiOiJNYW56YXJ1bCBoYXF1ZSIsImVtYWlsIjoidGVzdDEyM0B0LmNvbSJ9.Xdjqe16MSkiR94g-Uj_pVZ2L3gnIdKpkJ6aB82W_w_c3yEmx1mXYBdkxe4zMz3ks4OX_PWwSFEbJECHcnujUwF6Ula0xtXTfuESB9hFyiWHtVAhuh5UlCCwPnsihv5EqK6u-Qzo0aa6qZOiQK3Zo7FLpnPUDxn4yHyo3mRZUiWf76KTl8PhSMoXoWxcR2vGW0b-cPixILTZPV0xXUZoozCui70QnvTgOJDWqr7y80EWDkS4Ptn-QM3q2nJlw63mZreOG3XTdraOlcKIP5vFK992dyyHlYGqWVzigortS9Ah4cprFVuLlX8mu1cQvqHBtW-0Dq_JlcTMaztEnqvJ6XA", "386c7960-7f85-4a24-8131-a8aba519ce7d", - "386c7960-7f85-4a24-8131-a8aba519ce7e"); + "386c7960-7f85-4a24-8131-a8aba519ce7e", + new HashMap<>()); } catch (Exception e) { assertNotNull(e); } diff --git a/core/platform-common/src/test/java/org/sunbird/auth/verifier/CryptoUtilTest.java b/core/platform-common/src/test/java/org/sunbird/auth/verifier/CryptoUtilTest.java index eb3407ee8..f62aa0226 100644 --- a/core/platform-common/src/test/java/org/sunbird/auth/verifier/CryptoUtilTest.java +++ b/core/platform-common/src/test/java/org/sunbird/auth/verifier/CryptoUtilTest.java @@ -1,5 +1,6 @@ package org.sunbird.auth.verifier; +import java.util.HashMap; import org.junit.Assert; import org.junit.Test; import org.sunbird.keys.JsonKey; @@ -8,12 +9,14 @@ public class CryptoUtilTest { @Test public void verifyRSASignTest() { - String payLoad = "eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICI5emhhVnZDbl81OEtheHpldHBzYXNZQ2lEallkemJIX3U2LV93SDk4SEc0In0.eyJqdGkiOiI5ZmQzNzgzYy01YjZmLTQ3OWQtYmMzYy0yZWEzOGUzZmRmYzgiLCJleHAiOjE1MDUxMTQyNDYsIm5iZiI6MCwiaWF0IjoxNTA1MTEzNjQ2LCJpc3MiOiJodHRwOi8vbG9jYWxob3N0OjgwODAvYXV0aC9yZWFsbXMvbWFzdGVyIiwiYXVkIjoic2VjdXJpdHktYWRtaW4tY29uc29sZSIsInN1YiI6ImIzYTZkMTY4LWJjZmQtNDE2MS1hYzVmLTljZjYyODIyNzlmMyIsInR5cCI6IkJlYXJlciIsImF6cCI6InNlY3VyaXR5LWFkbWluLWNvbnNvbGUiLCJub25jZSI6ImMxOGVlMDM2LTAyMWItNGVlZC04NWVhLTc0MjMyYzg2ZmI4ZSIsImF1dGhfdGltZSI6MTUwNTExMzY0Niwic2Vzc2lvbl9zdGF0ZSI6ImRiZTU2NDlmLTY4MDktNDA3NS05Njk5LTVhYjIyNWMwZTkyMiIsImFjciI6IjEiLCJhbGxvd2VkLW9yaWdpbnMiOltdLCJyZXNvdXJjZV9hY2Nlc3MiOnt9LCJuYW1lIjoiTWFuemFydWwgaGFxdWUiLCJwcmVmZXJyZWRfdXNlcm5hbWUiOiJ0ZXN0MTIzNDU2NyIsImdpdmVuX25hbWUiOiJNYW56YXJ1bCBoYXF1ZSIsImVtYWlsIjoidGVzdDEyM0B0LmNvbSJ9"; - String data = "Xdjqe16MSkiR94g-Uj_pVZ2L3gnIdKpkJ6aB82W_w_c3yEmx1mXYBdkxe4zMz3ks4OX_PWwSFEbJECHcnujUwF6Ula0xtXTfuESB9hFyiWHtVAhuh5UlCCwPnsihv5EqK6u-Qzo0aa6qZOiQK3Zo7FLpnPUDxn4yHyo3mRZUiWf76KTl8PhSMoXoWxcR2vGW0b-cPixILTZPV0xXUZoozCui70QnvTgOJDWqr7y80EWDkS4Ptn-QM3q2nJlw63mZreOG3XTdraOlcKIP5vFK992dyyHlYGqWVzigortS9Ah4cprFVuLlX8mu1cQvqHBtW-0Dq_JlcTMaztEnqvJ6XA"; + String payLoad = + "eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICI5emhhVnZDbl81OEtheHpldHBzYXNZQ2lEallkemJIX3U2LV93SDk4SEc0In0.eyJqdGkiOiI5ZmQzNzgzYy01YjZmLTQ3OWQtYmMzYy0yZWEzOGUzZmRmYzgiLCJleHAiOjE1MDUxMTQyNDYsIm5iZiI6MCwiaWF0IjoxNTA1MTEzNjQ2LCJpc3MiOiJodHRwOi8vbG9jYWxob3N0OjgwODAvYXV0aC9yZWFsbXMvbWFzdGVyIiwiYXVkIjoic2VjdXJpdHktYWRtaW4tY29uc29sZSIsInN1YiI6ImIzYTZkMTY4LWJjZmQtNDE2MS1hYzVmLTljZjYyODIyNzlmMyIsInR5cCI6IkJlYXJlciIsImF6cCI6InNlY3VyaXR5LWFkbWluLWNvbnNvbGUiLCJub25jZSI6ImMxOGVlMDM2LTAyMWItNGVlZC04NWVhLTc0MjMyYzg2ZmI4ZSIsImF1dGhfdGltZSI6MTUwNTExMzY0Niwic2Vzc2lvbl9zdGF0ZSI6ImRiZTU2NDlmLTY4MDktNDA3NS05Njk5LTVhYjIyNWMwZTkyMiIsImFjciI6IjEiLCJhbGxvd2VkLW9yaWdpbnMiOltdLCJyZXNvdXJjZV9hY2Nlc3MiOnt9LCJuYW1lIjoiTWFuemFydWwgaGFxdWUiLCJwcmVmZXJyZWRfdXNlcm5hbWUiOiJ0ZXN0MTIzNDU2NyIsImdpdmVuX25hbWUiOiJNYW56YXJ1bCBoYXF1ZSIsImVtYWlsIjoidGVzdDEyM0B0LmNvbSJ9"; + String data = + "Xdjqe16MSkiR94g-Uj_pVZ2L3gnIdKpkJ6aB82W_w_c3yEmx1mXYBdkxe4zMz3ks4OX_PWwSFEbJECHcnujUwF6Ula0xtXTfuESB9hFyiWHtVAhuh5UlCCwPnsihv5EqK6u-Qzo0aa6qZOiQK3Zo7FLpnPUDxn4yHyo3mRZUiWf76KTl8PhSMoXoWxcR2vGW0b-cPixILTZPV0xXUZoozCui70QnvTgOJDWqr7y80EWDkS4Ptn-QM3q2nJlw63mZreOG3XTdraOlcKIP5vFK992dyyHlYGqWVzigortS9Ah4cprFVuLlX8mu1cQvqHBtW-0Dq_JlcTMaztEnqvJ6XA"; byte[] signature = Base64Util.decode(data, 11); - //PublicKey key = KeyManager.getPublicKey("keyId").getPublicKey(); + // PublicKey key = KeyManager.getPublicKey("keyId").getPublicKey(); String algorithm = JsonKey.SHA_256_WITH_RSA; - Boolean bool = CryptoUtil.verifyRSASign(payLoad, signature, null, algorithm); + Boolean bool = CryptoUtil.verifyRSASign(payLoad, signature, null, algorithm, new HashMap<>()); Assert.assertNotNull(bool); } } diff --git a/service/src/main/java/org/sunbird/actor/BackgroundJobManager.java b/service/src/main/java/org/sunbird/actor/BackgroundJobManager.java index d2a395ad4..53277813e 100644 --- a/service/src/main/java/org/sunbird/actor/BackgroundJobManager.java +++ b/service/src/main/java/org/sunbird/actor/BackgroundJobManager.java @@ -19,8 +19,8 @@ import org.sunbird.util.ProjectUtil; import scala.concurrent.Future; public class BackgroundJobManager extends BaseActor { - private ElasticSearchService esService = EsClientFactory.getInstance(JsonKey.REST); - private UserService userService = UserServiceImpl.getInstance(); + private final ElasticSearchService esService = EsClientFactory.getInstance(JsonKey.REST); + private final UserService userService = UserServiceImpl.getInstance(); @Override public void onReceive(Request request) throws Throwable { @@ -36,7 +36,6 @@ public class BackgroundJobManager extends BaseActor { } } - @SuppressWarnings("unchecked") private void updateUserOrgInfoToEs(Request actorMessage) { Map<String, Object> orgMap = (Map<String, Object>) actorMessage.getRequest().get(JsonKey.USER); Future<Map<String, Object>> resultF = diff --git a/service/src/main/java/org/sunbird/actor/feed/UserFeedActor.java b/service/src/main/java/org/sunbird/actor/feed/UserFeedActor.java index 8b3f767f0..87516f4d3 100644 --- a/service/src/main/java/org/sunbird/actor/feed/UserFeedActor.java +++ b/service/src/main/java/org/sunbird/actor/feed/UserFeedActor.java @@ -1,7 +1,8 @@ package org.sunbird.actor.feed; -import com.fasterxml.jackson.databind.ObjectMapper; import java.util.*; + +import com.fasterxml.jackson.databind.ObjectMapper; import org.sunbird.actor.core.BaseActor; import org.sunbird.keys.JsonKey; import org.sunbird.model.user.Feed; @@ -17,9 +18,8 @@ import org.sunbird.util.Util; public class UserFeedActor extends BaseActor { - IFeedService feedService = FeedFactory.getInstance(); + private final IFeedService feedService = FeedFactory.getInstance(); ObjectMapper mapper = new ObjectMapper(); - @Override public void onReceive(Request request) throws Throwable { Util.initializeContext(request, TelemetryEnvKey.USER); @@ -70,7 +70,7 @@ public class UserFeedActor extends BaseActor { feedList.sort(Comparator.comparing(Feed::getCreatedOn)); Feed delRecord = feedList.get(0); feedService.delete( - delRecord.getId(), delRecord.getUserId(), delRecord.getCategory(), context); + delRecord.getId(), delRecord.getUserId(), delRecord.getCategory(), context); } } @@ -78,10 +78,10 @@ public class UserFeedActor extends BaseActor { Response feedDeleteResponse = new Response(); Map<String, Object> deleteRequest = request.getRequest(); feedService.delete( - (String) deleteRequest.get(JsonKey.FEED_ID), - (String) deleteRequest.get(JsonKey.USER_ID), - (String) deleteRequest.get(JsonKey.CATEGORY), - context); + (String) deleteRequest.get(JsonKey.FEED_ID), + (String) deleteRequest.get(JsonKey.USER_ID), + (String) deleteRequest.get(JsonKey.CATEGORY), + context); feedDeleteResponse.getResult().put(JsonKey.RESPONSE, JsonKey.SUCCESS); sender().tell(feedDeleteResponse, self()); } diff --git a/service/src/main/java/org/sunbird/actor/location/LocationActor.java b/service/src/main/java/org/sunbird/actor/location/LocationActor.java index 9ef3b496b..c127ff3b0 100644 --- a/service/src/main/java/org/sunbird/actor/location/LocationActor.java +++ b/service/src/main/java/org/sunbird/actor/location/LocationActor.java @@ -24,7 +24,9 @@ import org.sunbird.util.Util; public class LocationActor extends BaseLocationActor { - private LocationService locationService = LocationServiceImpl.getInstance(); + private final LocationService locationService = LocationServiceImpl.getInstance(); + private final LocationRequestValidator locationRequestValidator = new LocationRequestValidator(); + private final ObjectMapper mapper = new ObjectMapper(); @Inject @Named("location_background_actor") @@ -66,17 +68,16 @@ public class LocationActor extends BaseLocationActor { private void createLocation(Request request) { try { - ObjectMapper mapper = new ObjectMapper(); UpsertLocationRequest locationRequest = ProjectUtil.convertToRequestPojo(request, UpsertLocationRequest.class); - validateUpsertLocnReq(locationRequest, JsonKey.CREATE); + validateUpsertLocnReq(locationRequest, JsonKey.CREATE, request.getRequestContext()); // put unique identifier in request for Id String id = ProjectUtil.generateUniqueId(); locationRequest.setId(id); Location location = mapper.convertValue(locationRequest, Location.class); Response response = locationService.createLocation(location, request.getRequestContext()); sender().tell(response, self()); - logger.info(request.getRequestContext(), "Insert location data to ES"); + logger.debug(request.getRequestContext(), "Insert location data to ES"); saveDataToES( mapper.convertValue(location, Map.class), JsonKey.INSERT, request.getRequestContext()); generateTelemetryForLocation( @@ -89,14 +90,13 @@ public class LocationActor extends BaseLocationActor { private void updateLocation(Request request) { try { - ObjectMapper mapper = new ObjectMapper(); UpsertLocationRequest locationRequest = ProjectUtil.convertToRequestPojo(request, UpsertLocationRequest.class); - validateUpsertLocnReq(locationRequest, JsonKey.UPDATE); + validateUpsertLocnReq(locationRequest, JsonKey.UPDATE, request.getRequestContext()); Location location = mapper.convertValue(locationRequest, Location.class); Response response = locationService.updateLocation(location, request.getRequestContext()); sender().tell(response, self()); - logger.info(request.getRequestContext(), "Update location data to ES"); + logger.debug(request.getRequestContext(), "Update location data to ES"); saveDataToES( mapper.convertValue(location, Map.class), JsonKey.UPDATE, request.getRequestContext()); generateTelemetryForLocation( @@ -127,10 +127,10 @@ public class LocationActor extends BaseLocationActor { private void deleteLocation(Request request) { try { String locationId = (String) request.getRequest().get(JsonKey.LOCATION_ID); - LocationRequestValidator.isLocationHasChild(locationId); + locationRequestValidator.isLocationHasChild(locationId, request.getRequestContext()); Response response = locationService.deleteLocation(locationId, request.getRequestContext()); sender().tell(response, self()); - logger.info(request.getRequestContext(), "Delete location data from ES"); + logger.debug(request.getRequestContext(), "Delete location data from ES"); deleteDataFromES(locationId, request.getRequestContext()); generateTelemetryForLocation( locationId, new HashMap<>(), JsonKey.DELETE, request.getContext()); @@ -165,10 +165,11 @@ public class LocationActor extends BaseLocationActor { } } - private void validateUpsertLocnReq(UpsertLocationRequest locationRequest, String operation) { + private void validateUpsertLocnReq( + UpsertLocationRequest locationRequest, String operation, RequestContext context) { if (StringUtils.isNotEmpty(locationRequest.getType())) { LocationRequestValidator.isValidLocationType(locationRequest.getType()); } - LocationRequestValidator.isValidParentIdAndCode(locationRequest, operation); + locationRequestValidator.isValidParentIdAndCode(locationRequest, operation, context); } } diff --git a/service/src/main/java/org/sunbird/actor/location/LocationBackgroundActor.java b/service/src/main/java/org/sunbird/actor/location/LocationBackgroundActor.java index bef3f103e..ae3ff3d63 100644 --- a/service/src/main/java/org/sunbird/actor/location/LocationBackgroundActor.java +++ b/service/src/main/java/org/sunbird/actor/location/LocationBackgroundActor.java @@ -9,7 +9,7 @@ import org.sunbird.util.ProjectUtil; public class LocationBackgroundActor extends BaseLocationActor { - private ElasticSearchService esService = EsClientFactory.getInstance(JsonKey.REST); + private final ElasticSearchService esService = EsClientFactory.getInstance(JsonKey.REST); @Override public void onReceive(Request request) throws Throwable { diff --git a/service/src/main/java/org/sunbird/actor/location/validator/LocationRequestValidator.java b/service/src/main/java/org/sunbird/actor/location/validator/LocationRequestValidator.java index 5c15b2210..16c645e6b 100644 --- a/service/src/main/java/org/sunbird/actor/location/validator/LocationRequestValidator.java +++ b/service/src/main/java/org/sunbird/actor/location/validator/LocationRequestValidator.java @@ -9,8 +9,6 @@ import org.apache.commons.lang3.StringUtils; import org.sunbird.common.ElasticSearchHelper; import org.sunbird.common.factory.EsClientFactory; import org.sunbird.common.inf.ElasticSearchService; -import org.sunbird.dao.location.LocationDao; -import org.sunbird.dao.location.impl.LocationDaoImpl; import org.sunbird.dto.SearchDTO; import org.sunbird.exception.ProjectCommonException; import org.sunbird.exception.ResponseCode; @@ -27,13 +25,13 @@ import scala.concurrent.Future; /** @author Amit Kumar */ public class LocationRequestValidator extends BaseLocationRequestValidator { - private static LocationDao locationDao = new LocationDaoImpl(); - protected static List<List<String>> locationTypeGroupList = new ArrayList<>(); - protected static List<String> typeList = new ArrayList<>(); - private static ObjectMapper mapper = new ObjectMapper(); - private static ElasticSearchService esUtil = EsClientFactory.getInstance(JsonKey.REST); - private static Map<String, Integer> orderMap = new HashMap<>(); - private LocationService locationService = new LocationServiceImpl(); + private final ElasticSearchService esUtil = EsClientFactory.getInstance(JsonKey.REST); + private final LocationService locationService = new LocationServiceImpl(); + private final ObjectMapper mapper = new ObjectMapper(); + + private static final Map<String, Integer> orderMap = new HashMap<>(); + private static final List<List<String>> locationTypeGroupList = new ArrayList<>(); + private static final List<String> typeList = new ArrayList<>(); static { List<String> subTypeList = @@ -99,8 +97,8 @@ public class LocationRequestValidator extends BaseLocationRequestValidator { * @param opType type of location. * @return boolean If parent id and code are valid return true else false. */ - public static boolean isValidParentIdAndCode( - UpsertLocationRequest locationRequest, String opType) { + public boolean isValidParentIdAndCode( + UpsertLocationRequest locationRequest, String opType, RequestContext context) { String type = locationRequest.getType(); if (StringUtils.isNotEmpty(type)) { List<String> locationTypeList = getLocationSubTypeListForType(type); @@ -133,9 +131,9 @@ public class LocationRequestValidator extends BaseLocationRequestValidator { } } if (StringUtils.isNotEmpty(locationRequest.getCode())) { - isValidLocationCode(locationRequest, opType); + isValidLocationCode(locationRequest, opType, context); } - validateParentIDAndParentCode(locationRequest, opType); + validateParentIDAndParentCode(locationRequest, opType, context); return true; } @@ -148,12 +146,12 @@ public class LocationRequestValidator extends BaseLocationRequestValidator { return (new ArrayList<>()); } - private static void validateParentIDAndParentCode( - UpsertLocationRequest locationRequest, String opType) { + private void validateParentIDAndParentCode( + UpsertLocationRequest locationRequest, String opType, RequestContext context) { String parentCode = locationRequest.getParentCode(); String parentId = locationRequest.getParentId(); if (StringUtils.isNotEmpty(parentCode)) { - Map<String, Object> map = getLocation(parentCode); + Map<String, Object> map = getLocation(parentCode, context); parentId = (String) map.get(JsonKey.ID); locationRequest.setParentId((String) map.get(JsonKey.ID)); } @@ -162,11 +160,12 @@ public class LocationRequestValidator extends BaseLocationRequestValidator { if (StringUtils.isNotEmpty(parentCode)) { operation = GeoLocationJsonKey.PARENT_CODE; } - Map<String, Object> parentLocation = getLocationById(parentId, operation); + Map<String, Object> parentLocation = getLocationById(parentId, operation, context); validateParentLocationType( mapper.convertValue(parentLocation, UpsertLocationRequest.class), locationRequest, - opType); + opType, + context); } } @@ -178,14 +177,17 @@ public class LocationRequestValidator extends BaseLocationRequestValidator { * @param location represents child location request object. * @return boolean If child location has valid hierarchy with parent return true otherwise false. */ - private static boolean validateParentLocationType( - UpsertLocationRequest parentLocation, UpsertLocationRequest location, String opType) { + private boolean validateParentLocationType( + UpsertLocationRequest parentLocation, + UpsertLocationRequest location, + String opType, + RequestContext context) { int levelLimit = 1; String parentType = parentLocation.getType(); String currentLocType = location.getType(); Map<String, Object> locn = null; if (opType.equalsIgnoreCase(JsonKey.UPDATE)) { - locn = getLocationById(location.getId(), JsonKey.LOCATION_ID); + locn = getLocationById(location.getId(), JsonKey.LOCATION_ID, context); currentLocType = (String) locn.get(GeoLocationJsonKey.LOCATION_TYPE); } Map<String, Integer> currentLocTypeoOrdermap = @@ -223,9 +225,9 @@ public class LocationRequestValidator extends BaseLocationRequestValidator { * @param id * @return Map<String, Object> location details */ - private static Map<String, Object> getLocationById(String id, String parameter) { + private Map<String, Object> getLocationById(String id, String parameter, RequestContext context) { Future<Map<String, Object>> locationF = - esUtil.getDataByIdentifier(ProjectUtil.EsType.location.getTypeName(), id, null); + esUtil.getDataByIdentifier(ProjectUtil.EsType.location.getTypeName(), id, context); Map<String, Object> location = (Map<String, Object>) ElasticSearchHelper.getResponseFromFuture(locationF); if (MapUtils.isEmpty(location)) { @@ -243,16 +245,13 @@ public class LocationRequestValidator extends BaseLocationRequestValidator { * @param code Value of location code we are looking for. * @return location details Map<String, Object> */ - private static Map<String, Object> getLocation(String code) { + private Map<String, Object> getLocation(String code, RequestContext context) { Map<String, Object> filters = new HashMap<>(); filters.put(GeoLocationJsonKey.CODE, code); Map<String, Object> map = new HashMap<>(); map.put(JsonKey.FILTERS, filters); List<Map<String, Object>> locationMapList = - getESSearchResult( - map, - ProjectUtil.EsIndex.sunbird.getIndexName(), - ProjectUtil.EsType.location.getTypeName()); + getESSearchResult(map, ProjectUtil.EsType.location.getTypeName(), context); if (CollectionUtils.isNotEmpty(locationMapList)) { return locationMapList.get(0); } else { @@ -270,8 +269,8 @@ public class LocationRequestValidator extends BaseLocationRequestValidator { * @param locationId * @return boolean */ - public static boolean isLocationHasChild(String locationId) { - Map<String, Object> location = getLocationById(locationId, JsonKey.LOCATION_ID); + public boolean isLocationHasChild(String locationId, RequestContext context) { + Map<String, Object> location = getLocationById(locationId, JsonKey.LOCATION_ID, context); Map<String, Integer> locTypeoOrdermap = getLocationTypeOrderMap( ((String) location.get(GeoLocationJsonKey.LOCATION_TYPE)).toLowerCase()); @@ -287,10 +286,7 @@ public class LocationRequestValidator extends BaseLocationRequestValidator { Map<String, Object> map = new HashMap<>(); map.put(JsonKey.FILTERS, filters); List<Map<String, Object>> locationMapList = - getESSearchResult( - map, - ProjectUtil.EsIndex.sunbird.getIndexName(), - ProjectUtil.EsType.location.getTypeName()); + getESSearchResult(map, ProjectUtil.EsType.location.getTypeName(), context); if (CollectionUtils.isNotEmpty(locationMapList)) { throw new ProjectCommonException( ResponseCode.invalidLocationDeleteRequest.getErrorCode(), @@ -301,25 +297,23 @@ public class LocationRequestValidator extends BaseLocationRequestValidator { return true; } - public static List<Map<String, Object>> getESSearchResult( - Map<String, Object> searchQueryMap, String esIndex, String esType) { + public List<Map<String, Object>> getESSearchResult( + Map<String, Object> searchQueryMap, String esType, RequestContext context) { SearchDTO searchDto = ElasticSearchHelper.createSearchDTO(searchQueryMap); - Future<Map<String, Object>> resultF = esUtil.search(searchDto, esType, null); + Future<Map<String, Object>> resultF = esUtil.search(searchDto, esType, context); Map<String, Object> result = (Map<String, Object>) ElasticSearchHelper.getResponseFromFuture(resultF); return (List<Map<String, Object>>) result.get(JsonKey.CONTENT); } - public static boolean isValidLocationCode(UpsertLocationRequest locationRequest, String opType) { + public boolean isValidLocationCode( + UpsertLocationRequest locationRequest, String opType, RequestContext context) { Map<String, Object> filters = new HashMap<>(); filters.put(GeoLocationJsonKey.CODE, locationRequest.getCode()); Map<String, Object> map = new HashMap<>(); map.put(JsonKey.FILTERS, filters); List<Map<String, Object>> locationMapList = - getESSearchResult( - map, - ProjectUtil.EsIndex.sunbird.getIndexName(), - ProjectUtil.EsType.location.getTypeName()); + getESSearchResult(map, ProjectUtil.EsType.location.getTypeName(), context); if (!locationMapList.isEmpty()) { if (opType.equalsIgnoreCase(JsonKey.CREATE)) { throw new ProjectCommonException( diff --git a/service/src/main/java/org/sunbird/actor/notes/NotesManagementActor.java b/service/src/main/java/org/sunbird/actor/notes/NotesManagementActor.java index cfc08be23..991a6de03 100644 --- a/service/src/main/java/org/sunbird/actor/notes/NotesManagementActor.java +++ b/service/src/main/java/org/sunbird/actor/notes/NotesManagementActor.java @@ -19,7 +19,7 @@ import org.sunbird.util.Util; public class NotesManagementActor extends BaseActor { - private NotesService notesService = new NotesService(); + private final NotesService notesService = new NotesService(); @Override public void onReceive(Request request) throws Throwable { diff --git a/service/src/main/java/org/sunbird/actor/notification/BackGroundNotificationActor.java b/service/src/main/java/org/sunbird/actor/notification/BackGroundNotificationActor.java index 65b42d401..d0c14f7b9 100644 --- a/service/src/main/java/org/sunbird/actor/notification/BackGroundNotificationActor.java +++ b/service/src/main/java/org/sunbird/actor/notification/BackGroundNotificationActor.java @@ -10,6 +10,13 @@ import org.sunbird.request.Request; import org.sunbird.util.ProjectUtil; public class BackGroundNotificationActor extends BaseActor { + + private final ObjectMapper mapper = new ObjectMapper(); + private final String notification_service_base_url = + System.getenv("notification_service_base_url"); + private final String NOTIFICATION_SERVICE_URL = + notification_service_base_url + "/v1/notification/send"; + @Override public void onReceive(Request request) throws Throwable { callNotificationService(request); @@ -21,9 +28,6 @@ public class BackGroundNotificationActor extends BaseActor { reqObj.getRequestContext(), "BackGroundNotificationActor:callNotificationService :: Method called."); try { - ObjectMapper mapper = new ObjectMapper(); - String notification_service_base_url = System.getenv("notification_service_base_url"); - String NOTIFICATION_SERVICE_URL = notification_service_base_url + "/v1/notification/send"; logger.debug( reqObj.getRequestContext(), "BackGroundNotificationActor:callNotificationService :: calling notification service URL :" @@ -39,7 +43,7 @@ public class BackGroundNotificationActor extends BaseActor { ProjectUtil.setTraceIdInHeader(headers, reqObj.getRequestContext()); String response = HttpClientUtil.post(NOTIFICATION_SERVICE_URL, json, headers, reqObj.getRequestContext()); - logger.info( + logger.debug( reqObj.getRequestContext(), "BackGroundNotificationActor:callNotificationService :: Response =" + response); } catch (Exception ex) { diff --git a/service/src/main/java/org/sunbird/actor/notification/EmailServiceActor.java b/service/src/main/java/org/sunbird/actor/notification/EmailServiceActor.java index d40c1fc91..ae4f9bcdf 100644 --- a/service/src/main/java/org/sunbird/actor/notification/EmailServiceActor.java +++ b/service/src/main/java/org/sunbird/actor/notification/EmailServiceActor.java @@ -21,9 +21,10 @@ import org.sunbird.util.ProjectUtil; public class EmailServiceActor extends BaseActor { - private NotificationService notificationService = new NotificationService(); - private SendgridConnection connection = new SendgridConnection(); - private String resetInterval = ProjectUtil.getConfigValue("sendgrid_connection_reset_interval"); + private final NotificationService notificationService = new NotificationService(); + private final SendgridConnection connection = new SendgridConnection(); + private final String resetInterval = + ProjectUtil.getConfigValue("sendgrid_connection_reset_interval"); private volatile long timer; @Override @@ -77,7 +78,7 @@ public class EmailServiceActor extends BaseActor { notificationService.validateAndGetEmailList( userIds, emails, recipientSearchQuery, requestContext); notificationService.updateFirstNameAndOrgNameInEmailContext( - userIds, emails, request, requestContext); + userIds, emailList, request, requestContext); if (CollectionUtils.isNotEmpty(emailList)) { String template = diff --git a/service/src/main/java/org/sunbird/actor/notification/SendNotificationActor.java b/service/src/main/java/org/sunbird/actor/notification/SendNotificationActor.java index 77b04ceb6..86ccd7396 100644 --- a/service/src/main/java/org/sunbird/actor/notification/SendNotificationActor.java +++ b/service/src/main/java/org/sunbird/actor/notification/SendNotificationActor.java @@ -15,7 +15,7 @@ import org.sunbird.service.notification.NotificationService; public class SendNotificationActor extends BaseActor { - private NotificationService notificationService = new NotificationService(); + private final NotificationService notificationService = new NotificationService(); @Inject @Named("background_notification_actor") diff --git a/service/src/main/java/org/sunbird/actor/organisation/OrganisationBackgroundActor.java b/service/src/main/java/org/sunbird/actor/organisation/OrganisationBackgroundActor.java index 4d3a940ed..704ec9c92 100644 --- a/service/src/main/java/org/sunbird/actor/organisation/OrganisationBackgroundActor.java +++ b/service/src/main/java/org/sunbird/actor/organisation/OrganisationBackgroundActor.java @@ -18,7 +18,8 @@ import org.sunbird.util.ProjectUtil; import org.sunbird.util.PropertiesCache; public class OrganisationBackgroundActor extends BaseActor { - private ElasticSearchService esService = EsClientFactory.getInstance(JsonKey.REST); + private final ElasticSearchService esService = EsClientFactory.getInstance(JsonKey.REST); + private final ObjectMapper mapper = new ObjectMapper(); @Override public void onReceive(Request request) throws Throwable { @@ -49,7 +50,6 @@ public class OrganisationBackgroundActor extends BaseActor { List<Map<String, Object>> orgLocationList = new ArrayList<>(); if (StringUtils.isNotBlank(orgLocation)) { try { - ObjectMapper mapper = new ObjectMapper(); orgLocationList = mapper.readValue(orgLocation, List.class); } catch (Exception e) { logger.info( diff --git a/service/src/main/java/org/sunbird/actor/organisation/OrganisationManagementActor.java b/service/src/main/java/org/sunbird/actor/organisation/OrganisationManagementActor.java index fa2f7d31e..7f63dbc2c 100644 --- a/service/src/main/java/org/sunbird/actor/organisation/OrganisationManagementActor.java +++ b/service/src/main/java/org/sunbird/actor/organisation/OrganisationManagementActor.java @@ -32,8 +32,8 @@ import org.sunbird.util.Util; import org.sunbird.validator.EmailValidator; public class OrganisationManagementActor extends BaseActor { - private OrgService orgService = OrgServiceImpl.getInstance(); - private OrganisationRequestValidator orgValidator = new OrganisationRequestValidator(); + private final OrgService orgService = OrgServiceImpl.getInstance(); + private final OrganisationRequestValidator orgValidator = new OrganisationRequestValidator(); @Inject @Named("org_background_actor") diff --git a/service/src/main/java/org/sunbird/actor/organisation/validator/OrganisationRequestValidator.java b/service/src/main/java/org/sunbird/actor/organisation/validator/OrganisationRequestValidator.java index e7d23d37d..953b530d9 100644 --- a/service/src/main/java/org/sunbird/actor/organisation/validator/OrganisationRequestValidator.java +++ b/service/src/main/java/org/sunbird/actor/organisation/validator/OrganisationRequestValidator.java @@ -1,5 +1,10 @@ package org.sunbird.actor.organisation.validator; +import java.text.MessageFormat; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang3.StringUtils; @@ -19,276 +24,267 @@ import org.sunbird.service.organisation.impl.OrgServiceImpl; import org.sunbird.util.ProjectUtil; import org.sunbird.util.Slug; -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - public class OrganisationRequestValidator { - private static LoggerUtil logger = new LoggerUtil(OrganisationRequestValidator.class); - private OrgService orgService = OrgServiceImpl.getInstance(); - private LocationService locationService = new LocationServiceImpl(); - private LocationRequestValidator validator = new LocationRequestValidator(); + private final LoggerUtil logger = new LoggerUtil(OrganisationRequestValidator.class); + private final OrgService orgService = OrgServiceImpl.getInstance(); + private final LocationService locationService = new LocationServiceImpl(); + private final LocationRequestValidator validator = new LocationRequestValidator(); - public void validateExternalId(Map<String, Object> request, RequestContext context){ - String channel = (String) request.get(JsonKey.CHANNEL); - String passedExternalId = (String) request.get(JsonKey.EXTERNAL_ID); - if (StringUtils.isNotBlank(passedExternalId)) { - passedExternalId = passedExternalId.toLowerCase(); - if (!validateChannelExternalIdUniqueness( - channel, passedExternalId, null, context)) { - ProjectCommonException.throwClientErrorException( - ResponseCode.errorDuplicateEntry, - MessageFormat.format( - ResponseCode.errorDuplicateEntry.getErrorMessage(), - passedExternalId, - JsonKey.EXTERNAL_ID)); - } - request.put(JsonKey.EXTERNAL_ID, passedExternalId); - request.put(JsonKey.PROVIDER, StringUtils.lowerCase(channel)); - } else { - request.remove(JsonKey.EXTERNAL_ID); - request.remove(JsonKey.PROVIDER); - } - } - public void validateSlug(Map<String, Object> request, RequestContext context){ - Boolean isTenant = (Boolean) request.get(JsonKey.IS_TENANT); - String slug = Slug.makeSlug((String) request.getOrDefault(JsonKey.CHANNEL, ""), true); - if (null != isTenant && isTenant) { - String orgId = orgService.getOrgIdFromSlug(slug, context); - if (StringUtils.isBlank(orgId)) { - request.put(JsonKey.SLUG, slug); - } else { - ProjectCommonException.throwClientErrorException(ResponseCode.slugIsNotUnique); - } - } else { - request.put(JsonKey.SLUG, slug); - } - } - public void channelMandatoryValidation(Map<String, Object> request) { - if (StringUtils.isBlank((String) request.get(JsonKey.CHANNEL))) { - throw new ProjectCommonException( - ResponseCode.mandatoryParamsMissing.getErrorCode(), - MessageFormat.format( - ResponseCode.mandatoryParamsMissing.getErrorMessage(), JsonKey.CHANNEL), - ResponseCode.CLIENT_ERROR.getResponseCode()); - } + public void validateExternalId(Map<String, Object> request, RequestContext context) { + String channel = (String) request.get(JsonKey.CHANNEL); + String passedExternalId = (String) request.get(JsonKey.EXTERNAL_ID); + if (StringUtils.isNotBlank(passedExternalId)) { + passedExternalId = passedExternalId.toLowerCase(); + if (!validateChannelExternalIdUniqueness(channel, passedExternalId, null, context)) { + ProjectCommonException.throwClientErrorException( + ResponseCode.errorDuplicateEntry, + MessageFormat.format( + ResponseCode.errorDuplicateEntry.getErrorMessage(), + passedExternalId, + JsonKey.EXTERNAL_ID)); + } + request.put(JsonKey.EXTERNAL_ID, passedExternalId); + request.put(JsonKey.PROVIDER, StringUtils.lowerCase(channel)); + } else { + request.remove(JsonKey.EXTERNAL_ID); + request.remove(JsonKey.PROVIDER); } + } - public void validateOrgRequest(Map<String, Object> req, RequestContext context) { - String orgId = (String) req.get(JsonKey.ORGANISATION_ID); - String provider = (String) req.get(JsonKey.PROVIDER); - String externalId = (String) req.get(JsonKey.EXTERNAL_ID); - if (StringUtils.isBlank(orgId)) { - if (StringUtils.isBlank(provider) || StringUtils.isBlank(externalId)) { - throw new ProjectCommonException( - ResponseCode.invalidRequestData.getErrorCode(), - ResponseCode.invalidRequestData.getErrorMessage(), - ResponseCode.CLIENT_ERROR.getResponseCode()); - } else { - // fetch orgid from database on basis of source and external id and put orgid - // into request . - OrgExternalServiceImpl orgExtService = new OrgExternalServiceImpl(); - String organisationId = - orgExtService.getOrgIdFromOrgExternalIdAndProvider( - (String) req.get(JsonKey.EXTERNAL_ID), (String) req.get(JsonKey.PROVIDER), context); - if (StringUtils.isEmpty(organisationId)) { - throw new ProjectCommonException( - ResponseCode.invalidRequestData.getErrorCode(), - ResponseCode.invalidRequestData.getErrorMessage(), - ResponseCode.CLIENT_ERROR.getResponseCode()); - } - req.put(JsonKey.ORGANISATION_ID, organisationId); - } - } + public void validateSlug(Map<String, Object> request, RequestContext context) { + Boolean isTenant = (Boolean) request.get(JsonKey.IS_TENANT); + String slug = Slug.makeSlug((String) request.getOrDefault(JsonKey.CHANNEL, ""), true); + if (null != isTenant && isTenant) { + String orgId = orgService.getOrgIdFromSlug(slug, context); + if (StringUtils.isBlank(orgId)) { + request.put(JsonKey.SLUG, slug); + } else { + ProjectCommonException.throwClientErrorException(ResponseCode.slugIsNotUnique); + } + } else { + request.put(JsonKey.SLUG, slug); } + } - public void validateOrgType(String orgType, String operation) { - if (StringUtils.isBlank(orgType) && operation.equalsIgnoreCase(JsonKey.CREATE)) { - throw new ProjectCommonException( - ResponseCode.mandatoryParamsMissing.getErrorCode(), - MessageFormat.format( - ResponseCode.mandatoryParamsMissing.getErrorMessage(), JsonKey.ORG_TYPE), - ResponseCode.CLIENT_ERROR.getResponseCode()); - } + public void channelMandatoryValidation(Map<String, Object> request) { + if (StringUtils.isBlank((String) request.get(JsonKey.CHANNEL))) { + throw new ProjectCommonException( + ResponseCode.mandatoryParamsMissing.getErrorCode(), + MessageFormat.format( + ResponseCode.mandatoryParamsMissing.getErrorMessage(), JsonKey.CHANNEL), + ResponseCode.CLIENT_ERROR.getResponseCode()); + } + } - List<String> orgTypeList = new ArrayList<>(); - for (OrgTypeEnum type : OrgTypeEnum.values()) { - orgTypeList.add(type.getType()); + public void validateOrgRequest(Map<String, Object> req, RequestContext context) { + String orgId = (String) req.get(JsonKey.ORGANISATION_ID); + String provider = (String) req.get(JsonKey.PROVIDER); + String externalId = (String) req.get(JsonKey.EXTERNAL_ID); + if (StringUtils.isBlank(orgId)) { + if (StringUtils.isBlank(provider) || StringUtils.isBlank(externalId)) { + throw new ProjectCommonException( + ResponseCode.invalidRequestData.getErrorCode(), + ResponseCode.invalidRequestData.getErrorMessage(), + ResponseCode.CLIENT_ERROR.getResponseCode()); + } else { + // fetch orgid from database on basis of source and external id and put orgid + // into request . + OrgExternalServiceImpl orgExtService = new OrgExternalServiceImpl(); + String organisationId = + orgExtService.getOrgIdFromOrgExternalIdAndProvider( + (String) req.get(JsonKey.EXTERNAL_ID), (String) req.get(JsonKey.PROVIDER), context); + if (StringUtils.isEmpty(organisationId)) { + throw new ProjectCommonException( + ResponseCode.invalidRequestData.getErrorCode(), + ResponseCode.invalidRequestData.getErrorMessage(), + ResponseCode.CLIENT_ERROR.getResponseCode()); } + req.put(JsonKey.ORGANISATION_ID, organisationId); + } + } + } - if (StringUtils.isNotBlank(orgType) && !orgTypeList.contains(orgType)) { - throw new ProjectCommonException( - ResponseCode.invalidValue.getErrorCode(), - MessageFormat.format( - ResponseCode.invalidValue.getErrorMessage(), JsonKey.ORG_TYPE, orgType, orgTypeList), - ResponseCode.CLIENT_ERROR.getResponseCode()); - } + public void validateOrgType(String orgType, String operation) { + if (StringUtils.isBlank(orgType) && operation.equalsIgnoreCase(JsonKey.CREATE)) { + throw new ProjectCommonException( + ResponseCode.mandatoryParamsMissing.getErrorCode(), + MessageFormat.format( + ResponseCode.mandatoryParamsMissing.getErrorMessage(), JsonKey.ORG_TYPE), + ResponseCode.CLIENT_ERROR.getResponseCode()); } - public void isTenantIdValid(String id, RequestContext context) { - Map<String, Object> orgDbMap = orgService.getOrgById(id, context); - boolean isValid = MapUtils.isNotEmpty(orgDbMap) && (boolean) orgDbMap.get(JsonKey.IS_TENANT); + List<String> orgTypeList = new ArrayList<>(); + for (OrgTypeEnum type : OrgTypeEnum.values()) { + orgTypeList.add(type.getType()); + } - if (!isValid) { - logger.info( - "OrganisationManagementActor: no root org found with Id: " - + id); - throw new ProjectCommonException( - ResponseCode.invalidRequestData.getErrorCode(), - ResponseCode.invalidOrgId.getErrorMessage(), - ResponseCode.CLIENT_ERROR.getResponseCode()); - } + if (StringUtils.isNotBlank(orgType) && !orgTypeList.contains(orgType)) { + throw new ProjectCommonException( + ResponseCode.invalidValue.getErrorCode(), + MessageFormat.format( + ResponseCode.invalidValue.getErrorMessage(), JsonKey.ORG_TYPE, orgType, orgTypeList), + ResponseCode.CLIENT_ERROR.getResponseCode()); } + } + public void isTenantIdValid(String id, RequestContext context) { + Map<String, Object> orgDbMap = orgService.getOrgById(id, context); + boolean isValid = MapUtils.isNotEmpty(orgDbMap) && (boolean) orgDbMap.get(JsonKey.IS_TENANT); - public void validateOrgLocation(Map<String, Object> request, RequestContext context) { - List<String> locList = new ArrayList<>(); - List<Map<String, String>> orgLocationList = - (List<Map<String, String>>) request.get(JsonKey.ORG_LOCATION); - if (CollectionUtils.isEmpty(orgLocationList)) { - // Request is from org upload - List<String> locCodeList = (List<String>) request.get(JsonKey.LOCATION_CODE); - if (CollectionUtils.isNotEmpty(locCodeList)) { - locList = - validator.getValidatedLocationIds(locCodeList, context); - request.remove(JsonKey.LOCATION_CODE); - } else { - return; - } - } else { - // If request orglocation is a list of map , which has location id - List<String> finalLocList = getLocationCodeorIdList(orgLocationList, JsonKey.ID); - // If request orglocation is a list of map , which has location code - if (CollectionUtils.isEmpty(finalLocList)) { - finalLocList = getLocationCodeorIdList(orgLocationList, JsonKey.CODE); - if (CollectionUtils.isNotEmpty(finalLocList)) { - locList = - validator.getValidatedLocationIds(finalLocList, context); - } - }else{ - locList = finalLocList; - } - } - List<String> locationIdsList = - validator.getHierarchyLocationIds(locList, context); - List<Map<String, String>> newOrgLocationList = new ArrayList<>(); - List<Location> locationList = locationService.locationSearch(JsonKey.ID, locationIdsList, context); - locationList - .stream() - .forEach( - location -> { - Map<String, String> map = new HashMap<>(); - map.put(JsonKey.ID, location.getId()); - map.put(JsonKey.TYPE, location.getType()); - newOrgLocationList.add(map); - }); - request.put(JsonKey.ORG_LOCATION, newOrgLocationList); - } - public List<String> getLocationCodeorIdList(List<Map<String, String>> orgLocationList, String key){ - List<String> finalLocList = new ArrayList<>(); - orgLocationList - .stream() - .forEach( - loc -> { - if (loc.containsKey(key)) { - finalLocList.add(loc.get(key)); - } - }); - return finalLocList; + if (!isValid) { + logger.info("OrganisationManagementActor: no root org found with Id: " + id); + throw new ProjectCommonException( + ResponseCode.invalidRequestData.getErrorCode(), + ResponseCode.invalidOrgId.getErrorMessage(), + ResponseCode.CLIENT_ERROR.getResponseCode()); } + } - public boolean validateChannelUniqueness( - String channel, String orgId, Boolean isTenant, RequestContext context) { - if (StringUtils.isNotBlank(channel)) { - Map<String, Object> filters = new HashMap<>(); - filters.put(JsonKey.CHANNEL, channel); - filters.put(JsonKey.IS_TENANT, true); - return validateChannelUniqueness(filters, orgId, isTenant, context); + public void validateOrgLocation(Map<String, Object> request, RequestContext context) { + List<String> locList = new ArrayList<>(); + List<Map<String, String>> orgLocationList = + (List<Map<String, String>>) request.get(JsonKey.ORG_LOCATION); + if (CollectionUtils.isEmpty(orgLocationList)) { + // Request is from org upload + List<String> locCodeList = (List<String>) request.get(JsonKey.LOCATION_CODE); + if (CollectionUtils.isNotEmpty(locCodeList)) { + locList = validator.getValidatedLocationIds(locCodeList, context); + request.remove(JsonKey.LOCATION_CODE); + } else { + return; + } + } else { + // If request orglocation is a list of map , which has location id + List<String> finalLocList = getLocationCodeorIdList(orgLocationList, JsonKey.ID); + // If request orglocation is a list of map , which has location code + if (CollectionUtils.isEmpty(finalLocList)) { + finalLocList = getLocationCodeorIdList(orgLocationList, JsonKey.CODE); + if (CollectionUtils.isNotEmpty(finalLocList)) { + locList = validator.getValidatedLocationIds(finalLocList, context); } - return (orgId == null); + } else { + locList = finalLocList; + } } + List<String> locationIdsList = validator.getHierarchyLocationIds(locList, context); + List<Map<String, String>> newOrgLocationList = new ArrayList<>(); + List<Location> locationList = + locationService.locationSearch(JsonKey.ID, locationIdsList, context); + locationList + .stream() + .forEach( + location -> { + Map<String, String> map = new HashMap<>(); + map.put(JsonKey.ID, location.getId()); + map.put(JsonKey.TYPE, location.getType()); + newOrgLocationList.add(map); + }); + request.put(JsonKey.ORG_LOCATION, newOrgLocationList); + } - private boolean validateChannelUniqueness( - Map<String, Object> filters, String orgId, Boolean isTenant, RequestContext context) { - if (MapUtils.isNotEmpty(filters)) { - List<Map<String, Object>> list = orgService.organisationSearch(filters, context); - if (CollectionUtils.isEmpty(list)) { - if (StringUtils.isBlank(orgId)) { - return true; - } else { - if (isTenant) { - return true; - } else { - return false; - } - } - } else { - if (StringUtils.isBlank(orgId)) { - return false; - } else { - Map<String, Object> data = list.get(0); - String id = (String) data.get(JsonKey.ID); - if (isTenant) { - return id.equalsIgnoreCase(orgId); - } else { - // for suborg channel should be valid - return true; - } - } - } - } - return true; + public List<String> getLocationCodeorIdList( + List<Map<String, String>> orgLocationList, String key) { + List<String> finalLocList = new ArrayList<>(); + orgLocationList + .stream() + .forEach( + loc -> { + if (loc.containsKey(key)) { + finalLocList.add(loc.get(key)); + } + }); + return finalLocList; + } + + public boolean validateChannelUniqueness( + String channel, String orgId, Boolean isTenant, RequestContext context) { + if (StringUtils.isNotBlank(channel)) { + Map<String, Object> filters = new HashMap<>(); + filters.put(JsonKey.CHANNEL, channel); + filters.put(JsonKey.IS_TENANT, true); + return validateChannelUniqueness(filters, orgId, isTenant, context); } + return (orgId == null); + } - public boolean validateChannelExternalIdUniqueness( - String channel, String externalId, String orgId, RequestContext context) { - OrgExternalServiceImpl orgExternalService = new OrgExternalServiceImpl(); - if (StringUtils.isNotBlank(channel) && StringUtils.isNotBlank(externalId)) { - String orgIdFromDb = - orgExternalService.getOrgIdFromOrgExternalIdAndProvider( - StringUtils.lowerCase(externalId), StringUtils.lowerCase(channel), context); - if (StringUtils.isEmpty(orgIdFromDb)) { - return true; - } else { - if (orgId == null) { - return false; - } - return orgIdFromDb.equalsIgnoreCase(orgId); - } + private boolean validateChannelUniqueness( + Map<String, Object> filters, String orgId, Boolean isTenant, RequestContext context) { + if (MapUtils.isNotEmpty(filters)) { + List<Map<String, Object>> list = orgService.organisationSearch(filters, context); + if (CollectionUtils.isEmpty(list)) { + if (StringUtils.isBlank(orgId)) { + return true; + } else { + if (isTenant) { + return true; + } else { + return false; + } } - return false; + } else { + if (StringUtils.isBlank(orgId)) { + return false; + } else { + Map<String, Object> data = list.get(0); + String id = (String) data.get(JsonKey.ID); + if (isTenant) { + return id.equalsIgnoreCase(orgId); + } else { + // for suborg channel should be valid + return true; + } + } + } } + return true; + } - public void validateChannel(Map<String, Object> req, RequestContext context) { - String channel = (String) req.get(JsonKey.CHANNEL); - if (!req.containsKey(JsonKey.IS_TENANT) || !(Boolean) req.get(JsonKey.IS_TENANT)) { - Map<String, Object> rootOrg = orgService.getRootOrgFromChannel(channel, context); - if (MapUtils.isEmpty(rootOrg)) { - logger.info( - context, "OrganisationManagementActor:validateChannel: Invalid channel = " + channel); - throw new ProjectCommonException( - ResponseCode.invalidChannel.getErrorCode(), - ResponseCode.invalidChannel.getErrorMessage(), - ResponseCode.CLIENT_ERROR.getResponseCode()); - } - Object status = rootOrg.get(JsonKey.STATUS); - if (null != status && 1 != (Integer) status) { - ProjectCommonException.throwClientErrorException( - ResponseCode.errorInactiveOrg, - ProjectUtil.formatMessage( - ResponseCode.errorInactiveOrg.getErrorMessage(), JsonKey.CHANNEL, channel)); - } - } else if (!validateChannelUniqueness((String) req.get(JsonKey.CHANNEL), null, null, context)) { - logger.info( - context, "OrganisationManagementActor:validateChannel: Channel validation failed"); - throw new ProjectCommonException( - ResponseCode.channelUniquenessInvalid.getErrorCode(), - ResponseCode.channelUniquenessInvalid.getErrorMessage(), - ResponseCode.CLIENT_ERROR.getResponseCode()); + public boolean validateChannelExternalIdUniqueness( + String channel, String externalId, String orgId, RequestContext context) { + OrgExternalServiceImpl orgExternalService = new OrgExternalServiceImpl(); + if (StringUtils.isNotBlank(channel) && StringUtils.isNotBlank(externalId)) { + String orgIdFromDb = + orgExternalService.getOrgIdFromOrgExternalIdAndProvider( + StringUtils.lowerCase(externalId), StringUtils.lowerCase(channel), context); + if (StringUtils.isEmpty(orgIdFromDb)) { + return true; + } else { + if (orgId == null) { + return false; } + return orgIdFromDb.equalsIgnoreCase(orgId); + } } + return false; + } + public void validateChannel(Map<String, Object> req, RequestContext context) { + String channel = (String) req.get(JsonKey.CHANNEL); + if (!req.containsKey(JsonKey.IS_TENANT) || !(Boolean) req.get(JsonKey.IS_TENANT)) { + Map<String, Object> rootOrg = orgService.getRootOrgFromChannel(channel, context); + if (MapUtils.isEmpty(rootOrg)) { + logger.info( + context, "OrganisationManagementActor:validateChannel: Invalid channel = " + channel); + throw new ProjectCommonException( + ResponseCode.invalidChannel.getErrorCode(), + ResponseCode.invalidChannel.getErrorMessage(), + ResponseCode.CLIENT_ERROR.getResponseCode()); + } + Object status = rootOrg.get(JsonKey.STATUS); + if (null != status && 1 != (Integer) status) { + ProjectCommonException.throwClientErrorException( + ResponseCode.errorInactiveOrg, + ProjectUtil.formatMessage( + ResponseCode.errorInactiveOrg.getErrorMessage(), JsonKey.CHANNEL, channel)); + } + } else if (!validateChannelUniqueness((String) req.get(JsonKey.CHANNEL), null, null, context)) { + logger.info( + context, "OrganisationManagementActor:validateChannel: Channel validation failed"); + throw new ProjectCommonException( + ResponseCode.channelUniquenessInvalid.getErrorCode(), + ResponseCode.channelUniquenessInvalid.getErrorMessage(), + ResponseCode.CLIENT_ERROR.getResponseCode()); + } + } } diff --git a/service/src/main/java/org/sunbird/actor/otp/OTPActor.java b/service/src/main/java/org/sunbird/actor/otp/OTPActor.java index e7dfcbba2..06cbd7576 100644 --- a/service/src/main/java/org/sunbird/actor/otp/OTPActor.java +++ b/service/src/main/java/org/sunbird/actor/otp/OTPActor.java @@ -8,7 +8,6 @@ import javax.inject.Named; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang3.StringUtils; import org.sunbird.actor.core.BaseActor; -import org.sunbird.datasecurity.impl.LogMaskServiceImpl; import org.sunbird.exception.ProjectCommonException; import org.sunbird.exception.ResponseCode; import org.sunbird.keys.JsonKey; @@ -29,12 +28,9 @@ import org.sunbird.util.ratelimit.RateLimiter; public class OTPActor extends BaseActor { - private OTPService otpService = new OTPService(); + private final OTPService otpService = new OTPService(); + private final RateLimitService rateLimitService = new RateLimitServiceImpl(); private static final String SUNBIRD_OTP_ALLOWED_ATTEMPT = "sunbird_otp_allowed_attempt"; - private static final String REMAINING_ATTEMPT = "remainingAttempt"; - private static final String MAX_ALLOWED_ATTEMPT = "maxAllowedAttempt"; - private RateLimitService rateLimitService = new RateLimitServiceImpl(); - private LogMaskServiceImpl logMaskService = new LogMaskServiceImpl(); @Inject @Named("send_otp_actor") @@ -56,7 +52,6 @@ public class OTPActor extends BaseActor { logger.debug(request.getRequestContext(), "OTPActor:generateOTP method call start."); String type = (String) request.getRequest().get(JsonKey.TYPE); String key = (String) request.getRequest().get(JsonKey.KEY); - String userId = (String) request.getRequest().get(JsonKey.USER_ID); if (StringUtils.isNotBlank(userId)) { key = otpService.getEmailPhoneByUserId(userId, type, request.getRequestContext()); @@ -66,11 +61,12 @@ public class OTPActor extends BaseActor { "OTPActor:generateOTP:getEmailPhoneByUserId: called for userId = " + userId + " ,key = " - + maskId(key, type)); + + OTPUtil.maskId(key, type)); } rateLimitService.throttleByKey( key, + type, new RateLimiter[] {OtpRateLimiter.HOUR, OtpRateLimiter.DAY}, request.getRequestContext()); @@ -82,22 +78,22 @@ public class OTPActor extends BaseActor { logger.info( request.getRequestContext(), "OTPActor:generateOTP: new otp generated for Key = " - + maskId(key, type) + + OTPUtil.maskId(key, type) + " & OTP = " - + maskOTP(otp)); + + OTPUtil.maskOTP(otp)); otpService.insertOTPDetails(type, key, otp, request.getRequestContext()); } else { otp = (String) details.get(JsonKey.OTP); logger.info( request.getRequestContext(), "OTPActor:generateOTP: Re-issuing otp for Key = " - + maskId(key, type) + + OTPUtil.maskId(key, type) + " & OTP = " - + maskOTP(otp)); + + OTPUtil.maskOTP(otp)); } logger.info( request.getRequestContext(), - "OTPActor:sendOTP : Calling SendOTPActor for Key = " + maskId(key, type)); + "OTPActor:sendOTP : Calling SendOTPActor for Key = " + OTPUtil.maskId(key, type)); sendOTP(request, otp, key, request.getRequestContext()); Response response = new Response(); @@ -119,7 +115,7 @@ public class OTPActor extends BaseActor { "OTPActor:verifyOTP:getEmailPhoneByUserId: called for userId = " + userId + " ,key = " - + maskId(key, type)); + + OTPUtil.maskId(key, type)); } Map<String, Object> otpDetails = otpService.getOTPDetails(type, key, request.getRequestContext()); @@ -128,7 +124,7 @@ public class OTPActor extends BaseActor { logger.info( request.getRequestContext(), "OTP_VALIDATION_FAILED:OTPActor:verifyOTP: Details not found for Key = " - + maskId(key, type) + + OTPUtil.maskId(key, type) + " type = " + type); ProjectCommonException.throwClientErrorException(ResponseCode.errorInvalidOTP); @@ -138,11 +134,11 @@ public class OTPActor extends BaseActor { logger.info( request.getRequestContext(), "OTP_VALIDATION_FAILED : OTPActor:verifyOTP: Mismatch for Key = " - + maskId(key, type) + + OTPUtil.maskId(key, type) + " otpInRequest = " - + maskOTP(otpInRequest) + + OTPUtil.maskOTP(otpInRequest) + " otpInDB = " - + maskOTP(otpInDB)); + + OTPUtil.maskOTP(otpInDB)); ProjectCommonException.throwClientErrorException(ResponseCode.errorInvalidOTP); } @@ -150,7 +146,7 @@ public class OTPActor extends BaseActor { logger.info( request.getRequestContext(), "OTP_VALIDATION_SUCCESS:OTPActor:verifyOTP: Verified successfully Key = " - + maskId(key, type)); + + OTPUtil.maskId(key, type)); otpService.deleteOtp(type, key, request.getRequestContext()); Response response = new Response(); response.put(JsonKey.RESPONSE, JsonKey.SUCCESS); @@ -159,11 +155,11 @@ public class OTPActor extends BaseActor { logger.info( request.getRequestContext(), "OTP_VALIDATION_FAILED: OTPActor:verifyOTP: Incorrect OTP Key = " - + maskId(key, type) + + OTPUtil.maskId(key, type) + " otpInRequest = " - + maskOTP(otpInRequest) + + OTPUtil.maskOTP(otpInRequest) + " otpInDB = " - + maskOTP(otpInDB)); + + OTPUtil.maskOTP(otpInDB)); handleMismatchOtp(type, key, otpDetails, request.getRequestContext()); } } @@ -174,7 +170,7 @@ public class OTPActor extends BaseActor { logger.info( context, "OTPActor:handleMismatchOtp: Key = " - + maskId(key, type) + + OTPUtil.maskId(key, type) + ",remaining attempt is " + remainingCount); int attemptedCount = (int) otpDetails.get(JsonKey.ATTEMPTED_COUNT); @@ -193,11 +189,13 @@ public class OTPActor extends BaseActor { ClientErrorResponse response = new ClientErrorResponse(); response.setException(ex); + String MAX_ALLOWED_ATTEMPT = "maxAllowedAttempt"; response .getResult() .put( MAX_ALLOWED_ATTEMPT, Integer.parseInt(ProjectUtil.getConfigValue(SUNBIRD_OTP_ALLOWED_ATTEMPT))); + String REMAINING_ATTEMPT = "remainingAttempt"; response.getResult().put(REMAINING_ATTEMPT, remainingCount); sender().tell(response, self()); } @@ -236,17 +234,4 @@ public class OTPActor extends BaseActor { return null; } } - - private String maskOTP(String otp) { - return logMaskService.maskOTP(otp); - } - - private String maskId(String id, String type) { - if (JsonKey.EMAIL.equalsIgnoreCase(type)) { - return logMaskService.maskEmail(id); - } else if (JsonKey.PHONE.equalsIgnoreCase(type)) { - return logMaskService.maskPhone(id); - } - return ""; - } } diff --git a/service/src/main/java/org/sunbird/actor/otp/SendOTPActor.java b/service/src/main/java/org/sunbird/actor/otp/SendOTPActor.java index 77ae18c14..6d53218a7 100644 --- a/service/src/main/java/org/sunbird/actor/otp/SendOTPActor.java +++ b/service/src/main/java/org/sunbird/actor/otp/SendOTPActor.java @@ -5,7 +5,6 @@ import java.util.HashMap; import java.util.Map; import javax.inject.Inject; import javax.inject.Named; -import org.apache.commons.lang3.StringUtils; import org.sunbird.actor.core.BaseActor; import org.sunbird.datasecurity.impl.LogMaskServiceImpl; import org.sunbird.keys.JsonKey; @@ -16,7 +15,7 @@ import org.sunbird.response.Response; import org.sunbird.util.otp.OTPUtil; public class SendOTPActor extends BaseActor { - private LogMaskServiceImpl logMaskService = new LogMaskServiceImpl(); + private final LogMaskServiceImpl logMaskService = new LogMaskServiceImpl(); @Inject @Named("email_service_actor") @@ -35,7 +34,7 @@ public class SendOTPActor extends BaseActor { String type = (String) request.getRequest().get(JsonKey.TYPE); String key = (String) request.getRequest().get(JsonKey.KEY); String otp = (String) request.getRequest().get(JsonKey.OTP); - String template = (String) request.getRequest().get(JsonKey.TEMPLATE_ID); + String templateId = (String) request.getRequest().get(JsonKey.TEMPLATE_ID); if (JsonKey.EMAIL.equalsIgnoreCase(type) || JsonKey.PREV_USED_EMAIL.equalsIgnoreCase(type) || JsonKey.RECOVERY_EMAIL.equalsIgnoreCase(type)) { @@ -46,14 +45,14 @@ public class SendOTPActor extends BaseActor { + logMaskService.maskEmail(key) + " or userId " + userId); - sendOTPViaEmail(key, otp, userId, template, request.getRequestContext()); + sendOTPViaEmail(key, otp, templateId, request.getRequestContext()); } else if (JsonKey.PHONE.equalsIgnoreCase(type) || JsonKey.PREV_USED_PHONE.equalsIgnoreCase(type) || JsonKey.RECOVERY_PHONE.equalsIgnoreCase(type)) { logger.info( request.getRequestContext(), "SendOTPActor:sendOTP : Sending OTP via sms for Key = " + logMaskService.maskPhone(key)); - sendOTPViaSMS(key, otp, template, request.getRequestContext()); + sendOTPViaSMS(key, otp, templateId, request.getRequestContext()); } else { logger.info(request.getRequestContext(), "SendOTPActor:sendOTP : No Email/Phone provided."); } @@ -62,20 +61,13 @@ public class SendOTPActor extends BaseActor { sender().tell(response, self()); } - private void sendOTPViaEmail( - String key, String otp, String otpType, String template, RequestContext context) { + private void sendOTPViaEmail(String key, String otp, String templateId, RequestContext context) { Map<String, Object> emailTemplateMap = new HashMap<>(); emailTemplateMap.put(JsonKey.EMAIL, key); emailTemplateMap.put(JsonKey.OTP, otp); emailTemplateMap.put(JsonKey.OTP_EXPIRATION_IN_MINUTES, OTPUtil.getOTPExpirationInMinutes()); - emailTemplateMap.put(JsonKey.TEMPLATE_ID, template); - Request emailRequest; - if (StringUtils.isBlank(otpType)) { - emailRequest = OTPUtil.getRequestToSendOTPViaEmail(emailTemplateMap, context); - } else { - emailRequest = - OTPUtil.getRequestToSendOTPViaEmail(emailTemplateMap, JsonKey.RESET_PASSWORD, context); - } + emailTemplateMap.put(JsonKey.TEMPLATE_ID, templateId); + Request emailRequest = OTPUtil.getRequestToSendOTPViaEmail(emailTemplateMap, context); emailRequest.setRequestContext(context); logger.info( context, diff --git a/service/src/main/java/org/sunbird/actor/role/FetchUserRoleActor.java b/service/src/main/java/org/sunbird/actor/role/FetchUserRoleActor.java index b6affe550..344979cb0 100644 --- a/service/src/main/java/org/sunbird/actor/role/FetchUserRoleActor.java +++ b/service/src/main/java/org/sunbird/actor/role/FetchUserRoleActor.java @@ -12,12 +12,11 @@ import org.sunbird.service.user.impl.UserRoleServiceImpl; public class FetchUserRoleActor extends BaseActor { - private UserRoleService userRoleService = UserRoleServiceImpl.getInstance(); + private final UserRoleService userRoleService = UserRoleServiceImpl.getInstance(); @Override public void onReceive(Request request) throws Throwable { String operation = request.getOperation(); - switch (operation) { case "getUserRolesById": getUserRolesById(request); diff --git a/service/src/main/java/org/sunbird/actor/role/UserRoleActor.java b/service/src/main/java/org/sunbird/actor/role/UserRoleActor.java index 80641f2cf..913cc2602 100644 --- a/service/src/main/java/org/sunbird/actor/role/UserRoleActor.java +++ b/service/src/main/java/org/sunbird/actor/role/UserRoleActor.java @@ -20,7 +20,7 @@ import org.sunbird.util.Util; public class UserRoleActor extends UserBaseActor { - private UserRoleService userRoleService = UserRoleServiceImpl.getInstance(); + private final UserRoleService userRoleService = UserRoleServiceImpl.getInstance(); @Inject @Named("user_role_background_actor") diff --git a/service/src/main/java/org/sunbird/actor/role/UserRoleBackgroundActor.java b/service/src/main/java/org/sunbird/actor/role/UserRoleBackgroundActor.java index 3b1ce53cd..73ec22b6e 100644 --- a/service/src/main/java/org/sunbird/actor/role/UserRoleBackgroundActor.java +++ b/service/src/main/java/org/sunbird/actor/role/UserRoleBackgroundActor.java @@ -12,6 +12,8 @@ import org.sunbird.service.user.impl.UserRoleServiceImpl; public class UserRoleBackgroundActor extends BaseActor { + private final UserRoleService userRoleService = UserRoleServiceImpl.getInstance(); + @Override public void onReceive(Request request) throws Throwable { String operation = request.getOperation(); @@ -31,7 +33,6 @@ public class UserRoleBackgroundActor extends BaseActor { if (type.equals(JsonKey.USER)) { result.put(JsonKey.ROLES, roles); } - UserRoleService userRoleService = UserRoleServiceImpl.getInstance(); userRoleService.updateUserRoleToES( (String) result.get(JsonKey.USER_ID), result, actorMessage.getRequestContext()); } diff --git a/service/src/main/java/org/sunbird/actor/search/SearchHandlerActor.java b/service/src/main/java/org/sunbird/actor/search/SearchHandlerActor.java index 1ff87e54a..9f2c4c356 100644 --- a/service/src/main/java/org/sunbird/actor/search/SearchHandlerActor.java +++ b/service/src/main/java/org/sunbird/actor/search/SearchHandlerActor.java @@ -38,8 +38,8 @@ import scala.concurrent.Future; public class SearchHandlerActor extends BaseActor { - private OrgService orgService = OrgServiceImpl.getInstance(); - private UserService userService = UserServiceImpl.getInstance(); + private final OrgService orgService = OrgServiceImpl.getInstance(); + private final UserService userService = UserServiceImpl.getInstance(); @Inject @Named("search_telemetry_actor") @@ -80,12 +80,12 @@ public class SearchHandlerActor extends BaseActor { if (MapUtils.isNotEmpty(filterMap)) { if (StringUtils.isNotBlank((CharSequence) filterMap.get(JsonKey.USER_TYPE))) { filterMap.put( - JsonKey.PROFILE_USERTYPE + "." + JsonKey.TYPE, filterMap.get(JsonKey.USER_TYPE)); + JsonKey.PROFILE_USERTYPES + "." + JsonKey.TYPE, filterMap.get(JsonKey.USER_TYPE)); filterMap.remove(JsonKey.USER_TYPE); } if (StringUtils.isNotBlank((CharSequence) filterMap.get(JsonKey.USER_SUB_TYPE))) { filterMap.put( - JsonKey.PROFILE_USERTYPE + "." + JsonKey.SUB_TYPE, + JsonKey.PROFILE_USERTYPES + "." + JsonKey.SUB_TYPE, filterMap.get(JsonKey.USER_SUB_TYPE)); filterMap.remove(JsonKey.USER_SUB_TYPE); } diff --git a/service/src/main/java/org/sunbird/actor/sync/EsSyncBackgroundActor.java b/service/src/main/java/org/sunbird/actor/sync/EsSyncBackgroundActor.java index c2f653d64..dcbc43261 100644 --- a/service/src/main/java/org/sunbird/actor/sync/EsSyncBackgroundActor.java +++ b/service/src/main/java/org/sunbird/actor/sync/EsSyncBackgroundActor.java @@ -21,9 +21,9 @@ import org.sunbird.util.ProjectUtil; public class EsSyncBackgroundActor extends BaseActor { - private OrgService orgService = OrgServiceImpl.getInstance(); - private LocationService locationService = LocationServiceImpl.getInstance(); - private UserService userService = UserServiceImpl.getInstance(); + private final OrgService orgService = OrgServiceImpl.getInstance(); + private final LocationService locationService = LocationServiceImpl.getInstance(); + private final UserService userService = UserServiceImpl.getInstance(); @Override public void onReceive(Request request) throws Throwable { diff --git a/service/src/main/java/org/sunbird/actor/systemsettings/SystemSettingsActor.java b/service/src/main/java/org/sunbird/actor/systemsettings/SystemSettingsActor.java index dc91ff174..1ff4f2ba3 100644 --- a/service/src/main/java/org/sunbird/actor/systemsettings/SystemSettingsActor.java +++ b/service/src/main/java/org/sunbird/actor/systemsettings/SystemSettingsActor.java @@ -11,7 +11,7 @@ import org.sunbird.service.systemsettings.SystemSettingsService; public class SystemSettingsActor extends BaseActor { - private SystemSettingsService service = new SystemSettingsService(); + private final SystemSettingsService service = new SystemSettingsService(); @Override public void onReceive(Request request) throws Throwable { diff --git a/service/src/main/java/org/sunbird/actor/tenantpreference/TenantPreferenceManagementActor.java b/service/src/main/java/org/sunbird/actor/tenantpreference/TenantPreferenceManagementActor.java index cc9bca702..3305d2ffe 100644 --- a/service/src/main/java/org/sunbird/actor/tenantpreference/TenantPreferenceManagementActor.java +++ b/service/src/main/java/org/sunbird/actor/tenantpreference/TenantPreferenceManagementActor.java @@ -11,7 +11,7 @@ import org.sunbird.service.tenantpreference.TenantPreferenceService; public class TenantPreferenceManagementActor extends BaseActor { - private TenantPreferenceService preferenceService = new TenantPreferenceService(); + private final TenantPreferenceService preferenceService = new TenantPreferenceService(); @Override public void onReceive(Request request) throws Throwable { diff --git a/service/src/main/java/org/sunbird/actor/user/IdentifierFreeUpActor.java b/service/src/main/java/org/sunbird/actor/user/IdentifierFreeUpActor.java index 838bf495c..e3ba44810 100644 --- a/service/src/main/java/org/sunbird/actor/user/IdentifierFreeUpActor.java +++ b/service/src/main/java/org/sunbird/actor/user/IdentifierFreeUpActor.java @@ -25,8 +25,8 @@ import org.sunbird.service.user.impl.UserServiceImpl; */ public class IdentifierFreeUpActor extends BaseActor { - private UserService userService = UserServiceImpl.getInstance(); - private UserLookUpServiceImpl userLookUp = new UserLookUpServiceImpl(); + private final UserService userService = UserServiceImpl.getInstance(); + private final UserLookUpServiceImpl userLookUp = new UserLookUpServiceImpl(); @Override public void onReceive(Request request) { diff --git a/service/src/main/java/org/sunbird/actor/user/ManagedUserActor.java b/service/src/main/java/org/sunbird/actor/user/ManagedUserActor.java index fdf81adf0..aec5afab8 100644 --- a/service/src/main/java/org/sunbird/actor/user/ManagedUserActor.java +++ b/service/src/main/java/org/sunbird/actor/user/ManagedUserActor.java @@ -1,52 +1,40 @@ package org.sunbird.actor.user; -import akka.actor.ActorRef; -import akka.dispatch.Mapper; -import akka.pattern.Patterns; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; -import javax.inject.Inject; -import javax.inject.Named; import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.lang.StringUtils; import org.apache.commons.lang3.BooleanUtils; import org.sunbird.actor.user.validator.UserCreateRequestValidator; -import org.sunbird.cassandra.CassandraOperation; -import org.sunbird.client.user.UserClient; -import org.sunbird.client.user.impl.UserClientImpl; -import org.sunbird.common.factory.EsClientFactory; -import org.sunbird.common.inf.ElasticSearchService; +import org.sunbird.common.ElasticSearchHelper; +import org.sunbird.dto.SearchDTO; import org.sunbird.exception.ProjectCommonException; -import org.sunbird.helper.ServiceFactory; import org.sunbird.keys.JsonKey; import org.sunbird.model.location.Location; import org.sunbird.request.Request; import org.sunbird.request.RequestContext; import org.sunbird.response.Response; +import org.sunbird.service.user.AssociationMechanism; import org.sunbird.service.user.UserLookupService; +import org.sunbird.service.user.UserOrgService; import org.sunbird.service.user.UserService; import org.sunbird.service.user.impl.UserLookUpServiceImpl; +import org.sunbird.service.user.impl.UserOrgServiceImpl; import org.sunbird.service.user.impl.UserServiceImpl; import org.sunbird.telemetry.dto.TelemetryEnvKey; import org.sunbird.util.*; import org.sunbird.util.user.UserUtil; -import scala.concurrent.Future; public class ManagedUserActor extends UserBaseActor { - private CassandraOperation cassandraOperation = ServiceFactory.getInstance(); - private UserClient userClient = UserClientImpl.getInstance(); - private UserService userService = UserServiceImpl.getInstance(); - private UserLookupService userLookupService = UserLookUpServiceImpl.getInstance(); - private ElasticSearchService esUtil = EsClientFactory.getInstance(JsonKey.REST); - private Util.DbInfo userOrgDb = Util.dbInfoMap.get(JsonKey.USER_ORG_DB); - protected UserCreateRequestValidator userCreateRequestValidator = - new UserCreateRequestValidator(); - @Inject - @Named("search_handler_actor") - private ActorRef searchHandlerActor; + private final UserService userService = UserServiceImpl.getInstance(); + private final UserOrgService userOrgService = UserOrgServiceImpl.getInstance(); + private final UserLookupService userLookupService = UserLookUpServiceImpl.getInstance(); + private final UserCreateRequestValidator userCreateRequestValidator = + new UserCreateRequestValidator(); @Override public void onReceive(Request request) throws Throwable { @@ -157,25 +145,11 @@ public class ManagedUserActor extends UserBaseActor { } if ("kafka".equalsIgnoreCase(ProjectUtil.getConfigValue("sunbird_user_create_sync_type"))) { writeDataToKafka(esResponse); - sender().tell(response, self()); } else { - Future<Response> future = - esUtil - .save( - ProjectUtil.EsType.user.getTypeName(), - (String) esResponse.get(JsonKey.USER_ID), - esResponse, - actorMessage.getRequestContext()) - .map( - new Mapper<>() { - @Override - public Response apply(String parameter) { - return response; - } - }, - context().dispatcher()); - Patterns.pipe(future, getContext().dispatcher()).to(sender()); + userService.saveUserToES( + (String) esResponse.get(JsonKey.USER_ID), esResponse, actorMessage.getRequestContext()); } + sender().tell(response, sender()); generateUserTelemetry(userMap, actorMessage, userId, JsonKey.CREATE); } @@ -191,12 +165,16 @@ public class ManagedUserActor extends UserBaseActor { } } - private Map<String, Object> saveUserOrgInfo(Map<String, Object> userMap, RequestContext context) { - Map<String, Object> userOrgMap = UserUtil.createUserOrgRequestData(userMap); - cassandraOperation.insertRecord( - userOrgDb.getKeySpace(), userOrgDb.getTableName(), userOrgMap, context); - - return userOrgMap; + private void saveUserOrgInfo(Map<String, Object> userMap, RequestContext context) { + Map<String, Object> userOrgMap = new HashMap<>(); + userOrgMap.put(JsonKey.ID, ProjectUtil.getUniqueIdFromTimestamp(1)); + userOrgMap.put(JsonKey.HASHTAGID, userMap.get(JsonKey.ROOT_ORG_ID)); + userOrgMap.put(JsonKey.USER_ID, userMap.get(JsonKey.USER_ID)); + userOrgMap.put(JsonKey.ORGANISATION_ID, userMap.get(JsonKey.ROOT_ORG_ID)); + userOrgMap.put(JsonKey.ORG_JOIN_DATE, ProjectUtil.getFormattedDate()); + userOrgMap.put(JsonKey.IS_DELETED, false); + userOrgMap.put(JsonKey.ASSOCIATION_TYPE, AssociationMechanism.SELF_DECLARATION); + userOrgService.registerUserToOrg(userOrgMap, context); } /** @@ -210,9 +188,21 @@ public class ManagedUserActor extends UserBaseActor { String uuid = (String) request.get(JsonKey.ID); boolean withTokens = Boolean.valueOf((String) request.get(JsonKey.WITH_TOKENS)); - + Map<String, Object> searchRequestMap = new HashMap<>(); + Map<String, Object> filters = new HashMap<>(); + filters.put(JsonKey.MANAGED_BY, request.get(JsonKey.ID)); + searchRequestMap.put(JsonKey.FILTERS, filters); + + String sortByField = (String) request.get(JsonKey.SORTBY); + if (StringUtils.isNotEmpty(sortByField)) { + String order = (String) request.get(JsonKey.ORDER); + Map<String, Object> sortBy = new HashMap<>(); + sortBy.put(sortByField, StringUtils.isEmpty(order) ? "asc" : order); + searchRequestMap.put(JsonKey.SORT_BY, sortBy); + } + SearchDTO searchDTO = ElasticSearchHelper.createSearchDTO(searchRequestMap); Map<String, Object> searchResult = - userClient.searchManagedUser(searchHandlerActor, request, request.getRequestContext()); + userService.searchUser(searchDTO, request.getRequestContext()); List<Map<String, Object>> userList = (List) searchResult.get(JsonKey.CONTENT); List<Map<String, Object>> activeUserList = null; diff --git a/service/src/main/java/org/sunbird/actor/user/ResetPasswordActor.java b/service/src/main/java/org/sunbird/actor/user/ResetPasswordActor.java index 985c77c5b..eff9c2dca 100644 --- a/service/src/main/java/org/sunbird/actor/user/ResetPasswordActor.java +++ b/service/src/main/java/org/sunbird/actor/user/ResetPasswordActor.java @@ -23,8 +23,8 @@ import org.sunbird.util.Util; public class ResetPasswordActor extends BaseActor { - private UserService userService = UserServiceImpl.getInstance(); - private ResetPasswordService resetPasswordService = new ResetPasswordService(); + private final UserService userService = UserServiceImpl.getInstance(); + private final ResetPasswordService resetPasswordService = new ResetPasswordService(); @Override public void onReceive(Request request) throws Throwable { diff --git a/service/src/main/java/org/sunbird/actor/user/SSOUserCreateActor.java b/service/src/main/java/org/sunbird/actor/user/SSOUserCreateActor.java index 61544f3fc..718c18b69 100644 --- a/service/src/main/java/org/sunbird/actor/user/SSOUserCreateActor.java +++ b/service/src/main/java/org/sunbird/actor/user/SSOUserCreateActor.java @@ -1,8 +1,6 @@ package org.sunbird.actor.user; import akka.actor.ActorRef; -import akka.dispatch.Mapper; -import akka.pattern.Patterns; import com.fasterxml.jackson.databind.ObjectMapper; import java.util.HashMap; import java.util.List; @@ -13,8 +11,6 @@ import javax.inject.Named; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.sunbird.actor.user.validator.UserRequestValidator; -import org.sunbird.common.factory.EsClientFactory; -import org.sunbird.common.inf.ElasticSearchService; import org.sunbird.keys.JsonKey; import org.sunbird.model.user.User; import org.sunbird.operations.ActorOperations; @@ -35,16 +31,14 @@ import org.sunbird.util.UserFlagUtil; import org.sunbird.util.Util; import org.sunbird.util.user.UserActorOperations; import org.sunbird.util.user.UserUtil; -import scala.concurrent.Future; public class SSOUserCreateActor extends UserBaseActor { - private UserRequestValidator userRequestValidator = new UserRequestValidator(); - private UserService userService = UserServiceImpl.getInstance(); - private ObjectMapper mapper = new ObjectMapper(); - private UserRoleService userRoleService = UserRoleServiceImpl.getInstance(); - private ElasticSearchService esUtil = EsClientFactory.getInstance(JsonKey.REST); - private SSOUserService ssoUserService = SSOUserServiceImpl.getInstance(); + private final UserRequestValidator userRequestValidator = new UserRequestValidator(); + private final UserService userService = UserServiceImpl.getInstance(); + private final ObjectMapper mapper = new ObjectMapper(); + private final UserRoleService userRoleService = UserRoleServiceImpl.getInstance(); + private final SSOUserService ssoUserService = SSOUserServiceImpl.getInstance(); @Inject @Named("user_profile_update_actor") @@ -112,7 +106,6 @@ public class SSOUserCreateActor extends UserBaseActor { userMap.put(JsonKey.ID, userId); userMap.put(JsonKey.USER_ID, userId); requestMap = UserUtil.encryptUserData(userMap); - Map<String, Object> userLookUpData = new HashMap<>(requestMap); // removing roles from requestMap, so it won't get save in user table List<String> roles = (List<String>) requestMap.get(JsonKey.ROLES); removeUnwanted(requestMap); @@ -162,22 +155,9 @@ public class SSOUserCreateActor extends UserBaseActor { if (null != resp && userMap.containsKey("sync") && (boolean) userMap.get("sync")) { Map<String, Object> userDetails = userService.getUserDetailsForES(userId, request.getRequestContext()); - Future<Response> future = - esUtil - .save( - ProjectUtil.EsType.user.getTypeName(), - (String) userDetails.get(JsonKey.USER_ID), - userDetails, - request.getRequestContext()) - .map( - new Mapper<String, Response>() { - @Override - public Response apply(String parameter) { - return syncResponse; - } - }, - context().dispatcher()); - Patterns.pipe(future, getContext().dispatcher()).to(sender()); + userService.saveUserToES( + (String) userDetails.get(JsonKey.USER_ID), userDetails, request.getRequestContext()); + sender().tell(syncResponse, sender()); } else { if (null != resp) { saveUserDetailsToEs(esResponse, request.getRequestContext()); diff --git a/service/src/main/java/org/sunbird/actor/user/SSUUserCreateActor.java b/service/src/main/java/org/sunbird/actor/user/SSUUserCreateActor.java index ab0c00446..05724e88f 100644 --- a/service/src/main/java/org/sunbird/actor/user/SSUUserCreateActor.java +++ b/service/src/main/java/org/sunbird/actor/user/SSUUserCreateActor.java @@ -5,20 +5,18 @@ import akka.dispatch.Mapper; import akka.pattern.Patterns; import java.util.HashMap; import java.util.Map; -import java.util.concurrent.Callable; -import org.sunbird.cassandra.CassandraOperation; -import org.sunbird.common.factory.EsClientFactory; -import org.sunbird.common.inf.ElasticSearchService; import org.sunbird.exception.ResponseMessage; -import org.sunbird.helper.ServiceFactory; import org.sunbird.keys.JsonKey; import org.sunbird.operations.ActorOperations; import org.sunbird.request.Request; import org.sunbird.request.RequestContext; import org.sunbird.response.Response; +import org.sunbird.service.user.AssociationMechanism; import org.sunbird.service.user.UserLookupService; +import org.sunbird.service.user.UserOrgService; import org.sunbird.service.user.UserService; import org.sunbird.service.user.impl.UserLookUpServiceImpl; +import org.sunbird.service.user.impl.UserOrgServiceImpl; import org.sunbird.service.user.impl.UserServiceImpl; import org.sunbird.telemetry.dto.TelemetryEnvKey; import org.sunbird.util.DataCacheHandler; @@ -32,11 +30,9 @@ import scala.concurrent.Future; public class SSUUserCreateActor extends UserBaseActor { - private CassandraOperation cassandraOperation = ServiceFactory.getInstance(); - private UserService userService = UserServiceImpl.getInstance(); - private Util.DbInfo userOrgDb = Util.dbInfoMap.get(JsonKey.USER_ORG_DB); - private UserLookupService userLookupService = UserLookUpServiceImpl.getInstance(); - private ElasticSearchService esUtil = EsClientFactory.getInstance(JsonKey.REST); + private final UserService userService = UserServiceImpl.getInstance(); + private final UserLookupService userLookupService = UserLookUpServiceImpl.getInstance(); + private final UserOrgService userOrgService = UserOrgServiceImpl.getInstance(); @Override public void onReceive(Request request) throws Throwable { @@ -52,11 +48,7 @@ public class SSUUserCreateActor extends UserBaseActor { } } - /** - * This method will create user in user in cassandra and update to ES as well at same time. - * - * @param actorMessage - */ + /** This method will create user in user in cassandra and update to ES as well at same time. */ private void createSSUUser(Request actorMessage) { logger.debug( actorMessage.getRequestContext(), "SSUUserCreateActor:createSSUUser: User creation starts"); @@ -116,30 +108,31 @@ public class SSUUserCreateActor extends UserBaseActor { } else { Future<Boolean> kcFuture = Futures.future( - (Callable<Boolean>) - () -> { - try { - Map<String, Object> updatePasswordMap = new HashMap<>(); - updatePasswordMap.put(JsonKey.ID, userMap.get(JsonKey.ID)); - updatePasswordMap.put(JsonKey.PASSWORD, password); - return UserUtil.updatePassword( - updatePasswordMap, actorMessage.getRequestContext()); - } catch (Exception e) { - logger.error( - actorMessage.getRequestContext(), - "Error occurred during update password : " + e.getMessage(), - e); - return false; - } - }, + () -> { + try { + Map<String, Object> updatePasswordMap = new HashMap<>(); + updatePasswordMap.put(JsonKey.ID, userMap.get(JsonKey.ID)); + updatePasswordMap.put(JsonKey.PASSWORD, password); + return UserUtil.updatePassword( + updatePasswordMap, actorMessage.getRequestContext()); + } catch (Exception e) { + logger.error( + actorMessage.getRequestContext(), + "Error occurred during update password : " + e.getMessage(), + e); + return false; + } + }, getContext().dispatcher()); + Map<String, Object> finalEsResponse = esResponse; Future<Response> future = - esUtil - .save( - ProjectUtil.EsType.user.getTypeName(), - (String) esResponse.get(JsonKey.USER_ID), - esResponse, - actorMessage.getRequestContext()) + Futures.future( + () -> + userService.saveUserToES( + (String) finalEsResponse.get(JsonKey.USER_ID), + finalEsResponse, + actorMessage.getRequestContext()), + getContext().dispatcher()) .zip(kcFuture) .map( new Mapper<>() { @@ -159,11 +152,15 @@ public class SSUUserCreateActor extends UserBaseActor { generateUserTelemetry(userMap, actorMessage, userId, JsonKey.CREATE); } - private Map<String, Object> saveUserOrgInfo(Map<String, Object> userMap, RequestContext context) { - Map<String, Object> userOrgMap = UserUtil.createUserOrgRequestData(userMap); - cassandraOperation.insertRecord( - userOrgDb.getKeySpace(), userOrgDb.getTableName(), userOrgMap, context); - - return userOrgMap; + private void saveUserOrgInfo(Map<String, Object> userMap, RequestContext context) { + Map<String, Object> userOrgMap = new HashMap<>(); + userOrgMap.put(JsonKey.ID, ProjectUtil.getUniqueIdFromTimestamp(1)); + userOrgMap.put(JsonKey.HASHTAGID, userMap.get(JsonKey.ROOT_ORG_ID)); + userOrgMap.put(JsonKey.USER_ID, userMap.get(JsonKey.USER_ID)); + userOrgMap.put(JsonKey.ORGANISATION_ID, userMap.get(JsonKey.ROOT_ORG_ID)); + userOrgMap.put(JsonKey.ORG_JOIN_DATE, ProjectUtil.getFormattedDate()); + userOrgMap.put(JsonKey.IS_DELETED, false); + userOrgMap.put(JsonKey.ASSOCIATION_TYPE, AssociationMechanism.SELF_DECLARATION); + userOrgService.registerUserToOrg(userOrgMap, context); } } diff --git a/service/src/main/java/org/sunbird/actor/user/TenantMigrationActor.java b/service/src/main/java/org/sunbird/actor/user/TenantMigrationActor.java index 51325f2d1..1af078ed7 100644 --- a/service/src/main/java/org/sunbird/actor/user/TenantMigrationActor.java +++ b/service/src/main/java/org/sunbird/actor/user/TenantMigrationActor.java @@ -30,6 +30,8 @@ import org.sunbird.service.user.impl.TenantMigrationServiceImpl; import org.sunbird.service.user.impl.UserLookUpServiceImpl; import org.sunbird.service.user.impl.UserSelfDeclarationServiceImpl; import org.sunbird.service.user.impl.UserServiceImpl; +import org.sunbird.service.userconsent.UserConsentService; +import org.sunbird.service.userconsent.impl.UserConsentServiceImpl; import org.sunbird.telemetry.dto.TelemetryEnvKey; import org.sunbird.telemetry.util.TelemetryUtil; import org.sunbird.util.ProjectUtil; @@ -44,19 +46,17 @@ import scala.concurrent.duration.Duration; public class TenantMigrationActor extends BaseActor { - private static final String ACCOUNT_MERGE_EMAIL_TEMPLATE = "accountMerge"; - private static final String MASK_IDENTIFIER = "maskIdentifier"; - - private DecryptionService decryptionService = + private final String MASK_IDENTIFIER = "maskIdentifier"; + private final DecryptionService decryptionService = org.sunbird.datasecurity.impl.ServiceFactory.getDecryptionServiceInstance(); - private DataMaskingService maskingService = + private final DataMaskingService maskingService = org.sunbird.datasecurity.impl.ServiceFactory.getMaskingServiceInstance(); - private TenantMigrationService tenantServiceImpl = TenantMigrationServiceImpl.getInstance(); - private UserSelfDeclarationService userSelfDeclarationService = + private final TenantMigrationService tenantServiceImpl = TenantMigrationServiceImpl.getInstance(); + private final UserSelfDeclarationService userSelfDeclarationService = UserSelfDeclarationServiceImpl.getInstance(); - private UserLookUpServiceImpl userLookUpService = new UserLookUpServiceImpl(); - private UserService userService = UserServiceImpl.getInstance(); - + private final UserLookUpServiceImpl userLookUpService = new UserLookUpServiceImpl(); + private final UserService userService = UserServiceImpl.getInstance(); + private final UserConsentService userConsentService = UserConsentServiceImpl.getInstance(); @Inject @Named("user_external_identity_management_actor") private ActorRef userExternalIdManagementActor; @@ -72,7 +72,9 @@ public class TenantMigrationActor extends BaseActor { @Override public void onReceive(Request request) throws Throwable { logger.info(request.getRequestContext(), "TenantMigrationActor:onReceive called."); - Util.initializeContext(request, StringUtils.capitalize(JsonKey.CONSUMER)); + request.getContext().put(JsonKey.ACTOR_ID, (String) request.getRequest().get(JsonKey.USER_ID)); + request.getContext().put(JsonKey.ACTOR_TYPE, JsonKey.USER); + Util.initializeContext(request, StringUtils.capitalize(JsonKey.USER)); String operation = request.getOperation(); switch (operation) { case "userTenantMigrate": @@ -175,6 +177,16 @@ public class TenantMigrationActor extends BaseActor { Response userOrgResponse = tenantServiceImpl.updateUserOrg( request, (List<Map<String, Object>>) userDetails.get(JsonKey.ORGANISATIONS)); + + //Revoke org consent + Map<String,Object> consentReqMap = new HashMap<>(); + consentReqMap.put(JsonKey.USER_ID, (String) request.getRequest().get(JsonKey.USER_ID)); + consentReqMap.put(JsonKey.CONSENT_CONSUMERID, orgId); + consentReqMap.put(JsonKey.CONSENT_OBJECTID, orgId); + consentReqMap.put(JsonKey.CONSENT_OBJECTTYPE, JsonKey.CONSENT_OBJECTTYPE_ORG); + consentReqMap.put(JsonKey.STATUS, JsonKey.CONSENT_STATUS_REVOKED); + Response consentRes = userConsentService.updateConsent(consentReqMap, request.getRequestContext()); + // Collect all the error message List<Map<String, Object>> userOrgErrMsgList = new ArrayList<>(); if (MapUtils.isNotEmpty(userOrgResponse.getResult()) @@ -215,7 +227,11 @@ public class TenantMigrationActor extends BaseActor { Map<String, Object> userData = createUserData(userDetail); Request notificationRequest = createNotificationData(userData, context); notificationRequest.setRequestContext(context); + try { emailServiceActor.tell(notificationRequest, self()); + } catch (Exception ex) { + logger.error(context, "Exception while sending user migrate notification", ex); + } } private Request createNotificationData(Map<String, Object> userData, RequestContext context) { @@ -229,6 +245,7 @@ public class TenantMigrationActor extends BaseActor { requestMap.put(JsonKey.RECIPIENT_PHONES, Arrays.asList(userData.get(JsonKey.PHONE))); requestMap.put(JsonKey.MODE, JsonKey.SMS); } + String ACCOUNT_MERGE_EMAIL_TEMPLATE = "accountMerge"; requestMap.put(JsonKey.EMAIL_TEMPLATE_TYPE, ACCOUNT_MERGE_EMAIL_TEMPLATE); Map<String, String> templateConfig = new HashMap<>(); templateConfig.put( @@ -264,7 +281,11 @@ public class TenantMigrationActor extends BaseActor { userRequest.getRequest().put(JsonKey.ID, userId); logger.debug( context, "TenantMigrationActor:saveUserDetailsToEs: Trigger sync of user details to ES"); - backgroundJobManager.tell(userRequest, self()); + try { + backgroundJobManager.tell(userRequest, self()); + } catch (Exception ex) { + logger.error(context, "Exception while saving user data to ES", ex); + } } private Response updateUserExternalIds(Request request) { diff --git a/service/src/main/java/org/sunbird/actor/user/UserBackgroundJobActor.java b/service/src/main/java/org/sunbird/actor/user/UserBackgroundJobActor.java index 3e5812a51..0e83938f5 100644 --- a/service/src/main/java/org/sunbird/actor/user/UserBackgroundJobActor.java +++ b/service/src/main/java/org/sunbird/actor/user/UserBackgroundJobActor.java @@ -17,7 +17,7 @@ import scala.concurrent.Future; public class UserBackgroundJobActor extends BaseActor { - private ElasticSearchService esUtil = EsClientFactory.getInstance(JsonKey.REST); + private final ElasticSearchService esUtil = EsClientFactory.getInstance(JsonKey.REST); @Override public void onReceive(Request request) throws Throwable { @@ -45,7 +45,6 @@ public class UserBackgroundJobActor extends BaseActor { (String) userDetails.get(JsonKey.ID), request.getRequestContext())); logger.info(request.getRequestContext(), "Updating saveUserOrgDetailsToES"); upsertDataToElastic( - ProjectUtil.EsIndex.sunbird.getIndexName(), ProjectUtil.EsType.user.getTypeName(), (String) userDetails.get(JsonKey.ID), userOrgMap, @@ -60,7 +59,6 @@ public class UserBackgroundJobActor extends BaseActor { User user = mapper.convertValue(userDetails, User.class); userDetails = mapper.convertValue(user, Map.class); upsertDataToElastic( - ProjectUtil.EsIndex.sunbird.getIndexName(), ProjectUtil.EsType.user.getTypeName(), (String) userDetails.get(JsonKey.ID), userDetails, @@ -68,11 +66,7 @@ public class UserBackgroundJobActor extends BaseActor { } private void upsertDataToElastic( - String indexName, - String typeName, - String id, - Map<String, Object> userDetails, - RequestContext context) { + String typeName, String id, Map<String, Object> userDetails, RequestContext context) { Future<Boolean> bool = esUtil.upsert(typeName, id, userDetails, context); diff --git a/service/src/main/java/org/sunbird/actor/user/UserBaseActor.java b/service/src/main/java/org/sunbird/actor/user/UserBaseActor.java index 78771d736..d061455ca 100644 --- a/service/src/main/java/org/sunbird/actor/user/UserBaseActor.java +++ b/service/src/main/java/org/sunbird/actor/user/UserBaseActor.java @@ -15,8 +15,6 @@ import org.apache.commons.collections.MapUtils; import org.apache.commons.lang3.StringUtils; import org.sunbird.actor.core.BaseActor; import org.sunbird.actor.user.validator.UserCreateRequestValidator; -import org.sunbird.client.location.LocationClient; -import org.sunbird.client.location.impl.LocationClientImpl; import org.sunbird.exception.ProjectCommonException; import org.sunbird.exception.ResponseCode; import org.sunbird.kafka.KafkaClient; @@ -24,6 +22,7 @@ import org.sunbird.keys.JsonKey; import org.sunbird.model.location.Location; import org.sunbird.request.Request; import org.sunbird.request.RequestContext; +import org.sunbird.response.Response; import org.sunbird.service.location.LocationService; import org.sunbird.service.location.LocationServiceImpl; import org.sunbird.service.user.UserLookupService; @@ -36,8 +35,9 @@ import org.sunbird.util.Util; public abstract class UserBaseActor extends BaseActor { - protected UserLookupService userLookupService = UserLookUpServiceImpl.getInstance(); - protected LocationClient locationClient = LocationClientImpl.getInstance(); + protected final ObjectMapper mapper = new ObjectMapper(); + protected final UserLookupService userLookupService = UserLookUpServiceImpl.getInstance(); + protected final LocationService locationService = LocationServiceImpl.getInstance(); @Inject @Named("user_telemetry_actor") @@ -180,7 +180,18 @@ public abstract class UserBaseActor extends BaseActor { List<Location> locationList = new ArrayList<>(); if (((List) locationCodes).get(0) instanceof String) { List<String> locations = (List<String>) locationCodes; - locationList = locationClient.getLocationsByCodes(locationActor, locations, context); + Map<String, Object> filters = new HashMap<>(); + Map<String, Object> searchRequestMap = new HashMap<>(); + filters.put(JsonKey.CODE, locations); + searchRequestMap.put(JsonKey.FILTERS, filters); + Response searchResponse = locationService.searchLocation(searchRequestMap, context); + List<Map<String, Object>> responseList = + (List<Map<String, Object>>) searchResponse.getResult().get(JsonKey.RESPONSE); + locationList = + responseList + .stream() + .map(s -> mapper.convertValue(s, Location.class)) + .collect(Collectors.toList()); } if (((List) locationCodes).get(0) instanceof Map) { @@ -239,6 +250,12 @@ public abstract class UserBaseActor extends BaseActor { } try { ObjectMapper mapper = new ObjectMapper(); + + if(!userMap.containsKey(JsonKey.PROFILE_USERTYPES)){ + List<Map<String, String>> userTypeAndSubTypes = new ArrayList<>(); + userTypeAndSubTypes.add(userTypeAndSubType); + userMap.put(JsonKey.PROFILE_USERTYPES, mapper.writeValueAsString(userTypeAndSubTypes)); + } userMap.put(JsonKey.PROFILE_USERTYPE, mapper.writeValueAsString(userTypeAndSubType)); } catch (Exception ex) { logger.error(requestContext, "Exception occurred while mapping", ex); @@ -269,8 +286,6 @@ public abstract class UserBaseActor extends BaseActor { if (!userMap.containsKey(JsonKey.LOCATION_IDS) && userMap.containsKey(JsonKey.LOCATION_CODES) && !CollectionUtils.isEmpty((List<String>) userMap.get(JsonKey.LOCATION_CODES))) { - LocationService locationService = LocationServiceImpl.getInstance(); - ObjectMapper mapper = new ObjectMapper(); List<Map<String, String>> locationIdTypeList = locationService.getValidatedRelatedLocationIdAndType( (List<String>) userMap.get(JsonKey.LOCATION_CODES), context); diff --git a/service/src/main/java/org/sunbird/actor/user/UserExternalIdManagementActor.java b/service/src/main/java/org/sunbird/actor/user/UserExternalIdManagementActor.java index 398126dca..a739a005f 100644 --- a/service/src/main/java/org/sunbird/actor/user/UserExternalIdManagementActor.java +++ b/service/src/main/java/org/sunbird/actor/user/UserExternalIdManagementActor.java @@ -24,7 +24,7 @@ import org.sunbird.util.user.UserActorOperations; public class UserExternalIdManagementActor extends BaseActor { - private CassandraOperation cassandraOperation = ServiceFactory.getInstance(); + private final CassandraOperation cassandraOperation = ServiceFactory.getInstance(); @Override public void onReceive(Request request) throws Throwable { diff --git a/service/src/main/java/org/sunbird/actor/user/UserMergeActor.java b/service/src/main/java/org/sunbird/actor/user/UserMergeActor.java index 968f0da9a..2d5ce4752 100644 --- a/service/src/main/java/org/sunbird/actor/user/UserMergeActor.java +++ b/service/src/main/java/org/sunbird/actor/user/UserMergeActor.java @@ -14,6 +14,7 @@ import javax.inject.Inject; import javax.inject.Named; import org.apache.kafka.clients.producer.Producer; import org.apache.kafka.clients.producer.ProducerRecord; +import org.sunbird.auth.verifier.AccessTokenValidator; import org.sunbird.client.systemsettings.SystemSettingClient; import org.sunbird.client.systemsettings.impl.SystemSettingClientImpl; import org.sunbird.dao.user.UserDao; @@ -48,12 +49,12 @@ import org.sunbird.util.user.KafkaConfigConstants; import org.sunbird.util.user.UserUtil; public class UserMergeActor extends UserBaseActor { - String topic = null; - Producer<String, String> producer = null; - ObjectMapper objectMapper = new ObjectMapper(); - private UserService userService = UserServiceImpl.getInstance(); - private SSOManager keyCloakService = SSOServiceFactory.getInstance(); - private SystemSettingClient systemSettingClient = SystemSettingClientImpl.getInstance(); + private String topic = null; + private Producer<String, String> producer = null; + private final ObjectMapper objectMapper = new ObjectMapper(); + private final UserService userService = UserServiceImpl.getInstance(); + private final SSOManager keyCloakService = SSOServiceFactory.getInstance(); + private final SystemSettingClient systemSettingClient = SystemSettingClientImpl.getInstance(); @Inject @Named("system_settings_actor") @@ -268,10 +269,12 @@ public class UserMergeActor extends UserBaseActor { String sourceUserAuthToken = (String) headers.get(JsonKey.X_SOURCE_USER_TOKEN); String subDomainUrl = ProjectUtil.getConfigValue(JsonKey.SUNBIRD_SUBDOMAIN_KEYCLOAK_BASE_URL); logger.info(context, "UserMergeActor:checkTokenDetails sub domain url value " + subDomainUrl); - String userId = keyCloakService.verifyToken(userAuthToken, context); + String userId = AccessTokenValidator.verifyUserToken(userAuthToken, new HashMap<>()); // Since source token is generated from subdomain , so verification also need with // same subdomain. - String sourceUserId = keyCloakService.verifyToken(sourceUserAuthToken, subDomainUrl, context); + String sourceUserId = + AccessTokenValidator.verifySourceUserToken( + sourceUserAuthToken, subDomainUrl, context.getContextMap()); if (!(mergeeId.equals(sourceUserId) && mergerId.equals(userId))) { throw new ProjectCommonException( ResponseCode.unAuthorized.getErrorCode(), diff --git a/service/src/main/java/org/sunbird/actor/user/UserOnboardingNotificationActor.java b/service/src/main/java/org/sunbird/actor/user/UserOnboardingNotificationActor.java index d99b3f74e..15ac37dac 100644 --- a/service/src/main/java/org/sunbird/actor/user/UserOnboardingNotificationActor.java +++ b/service/src/main/java/org/sunbird/actor/user/UserOnboardingNotificationActor.java @@ -27,7 +27,7 @@ import org.sunbird.util.user.UserActorOperations; public class UserOnboardingNotificationActor extends BaseActor { - private ResetPasswordService resetPasswordService = new ResetPasswordService(); + private final ResetPasswordService resetPasswordService = new ResetPasswordService(); @Inject @Named("email_service_actor") diff --git a/service/src/main/java/org/sunbird/actor/user/UserOrgManagementActor.java b/service/src/main/java/org/sunbird/actor/user/UserOrgManagementActor.java index 06d1971f9..2017d2f2b 100644 --- a/service/src/main/java/org/sunbird/actor/user/UserOrgManagementActor.java +++ b/service/src/main/java/org/sunbird/actor/user/UserOrgManagementActor.java @@ -17,7 +17,7 @@ import org.sunbird.util.user.UserUtil; public class UserOrgManagementActor extends BaseActor { - private UserOrgService userOrgService = UserOrgServiceImpl.getInstance(); + private final UserOrgService userOrgService = UserOrgServiceImpl.getInstance(); @Override public void onReceive(Request request) throws Throwable { diff --git a/service/src/main/java/org/sunbird/actor/user/UserProfileReadActor.java b/service/src/main/java/org/sunbird/actor/user/UserProfileReadActor.java index 7a9b2409a..217c07091 100644 --- a/service/src/main/java/org/sunbird/actor/user/UserProfileReadActor.java +++ b/service/src/main/java/org/sunbird/actor/user/UserProfileReadActor.java @@ -22,10 +22,10 @@ import org.sunbird.util.Util; public class UserProfileReadActor extends BaseActor { - private EncryptionService encryptionService = + private final EncryptionService encryptionService = org.sunbird.datasecurity.impl.ServiceFactory.getEncryptionServiceInstance(); - private UserService userService = UserServiceImpl.getInstance(); - private UserProfileReadService profileReadService = new UserProfileReadService(); + private final UserService userService = UserServiceImpl.getInstance(); + private final UserProfileReadService profileReadService = new UserProfileReadService(); @Override public void onReceive(Request request) throws Throwable { diff --git a/service/src/main/java/org/sunbird/actor/user/UserProfileUpdateActor.java b/service/src/main/java/org/sunbird/actor/user/UserProfileUpdateActor.java index c349b4b5d..e5aef1610 100644 --- a/service/src/main/java/org/sunbird/actor/user/UserProfileUpdateActor.java +++ b/service/src/main/java/org/sunbird/actor/user/UserProfileUpdateActor.java @@ -62,7 +62,7 @@ public class UserProfileUpdateActor extends BaseActor { private Future<Response> getConsolidatedFutureResponse(Future<Iterable<Object>> futuresSequence) { return futuresSequence.map( - new Mapper<Iterable<Object>, Response>() { + new Mapper<>() { Map<String, Object> map = new HashMap<>(); List<Object> errorList = new ArrayList<>(); @@ -101,7 +101,6 @@ public class UserProfileUpdateActor extends BaseActor { getContext().dispatcher()); } - @SuppressWarnings("unchecked") private List<Future<Object>> getFutures( Map<String, Object> userMap, String operationType, RequestContext context) { List<Future<Object>> futures = new ArrayList<>(); diff --git a/service/src/main/java/org/sunbird/actor/user/UserSelfDeclarationManagementActor.java b/service/src/main/java/org/sunbird/actor/user/UserSelfDeclarationManagementActor.java index 4ef16b04d..1093d07cf 100644 --- a/service/src/main/java/org/sunbird/actor/user/UserSelfDeclarationManagementActor.java +++ b/service/src/main/java/org/sunbird/actor/user/UserSelfDeclarationManagementActor.java @@ -28,9 +28,9 @@ import org.sunbird.util.Util; import org.sunbird.util.user.UserUtil; public class UserSelfDeclarationManagementActor extends BaseActor { - private UserSelfDeclarationService userSelfDeclarationService = + private final UserSelfDeclarationService userSelfDeclarationService = UserSelfDeclarationServiceImpl.getInstance(); - private OrgService orgService = OrgServiceImpl.getInstance(); + private final OrgService orgService = OrgServiceImpl.getInstance(); @Override public void onReceive(Request request) throws Throwable { diff --git a/service/src/main/java/org/sunbird/actor/user/UserStatusActor.java b/service/src/main/java/org/sunbird/actor/user/UserStatusActor.java index b2cdb2d29..1705b7bb1 100644 --- a/service/src/main/java/org/sunbird/actor/user/UserStatusActor.java +++ b/service/src/main/java/org/sunbird/actor/user/UserStatusActor.java @@ -13,8 +13,8 @@ import org.sunbird.util.Util; public class UserStatusActor extends UserBaseActor { - private UserStatusService userStatusService = new UserStatusService(); - private UserService userService = UserServiceImpl.getInstance(); + private final UserStatusService userStatusService = new UserStatusService(); + private final UserService userService = UserServiceImpl.getInstance(); @Override public void onReceive(Request request) throws Throwable { diff --git a/service/src/main/java/org/sunbird/actor/user/UserTnCActor.java b/service/src/main/java/org/sunbird/actor/user/UserTnCActor.java index e2470da02..893e31772 100644 --- a/service/src/main/java/org/sunbird/actor/user/UserTnCActor.java +++ b/service/src/main/java/org/sunbird/actor/user/UserTnCActor.java @@ -22,10 +22,9 @@ import org.sunbird.util.ProjectUtil; import org.sunbird.util.Util; public class UserTnCActor extends BaseActor { - private UserTncService tncService = new UserTncService(); - private ObjectMapper mapper = new ObjectMapper(); - - UserDao userDao = UserDaoImpl.getInstance(); + private final UserTncService tncService = new UserTncService(); + private final ObjectMapper mapper = new ObjectMapper(); + private final UserDao userDao = UserDaoImpl.getInstance(); @Override public void onReceive(Request request) throws Throwable { diff --git a/service/src/main/java/org/sunbird/actor/user/UserTypeActor.java b/service/src/main/java/org/sunbird/actor/user/UserTypeActor.java index 78c5e3a03..880357bc0 100644 --- a/service/src/main/java/org/sunbird/actor/user/UserTypeActor.java +++ b/service/src/main/java/org/sunbird/actor/user/UserTypeActor.java @@ -23,9 +23,7 @@ public class UserTypeActor extends UserBaseActor { } } - @SuppressWarnings("unchecked") private void getUserTypes(Request request) { - Response response = new Response(); List<Map<String, String>> userTypeList = getUserTypeList(request); response.getResult().put(JsonKey.RESPONSE, userTypeList); @@ -34,7 +32,6 @@ public class UserTypeActor extends UserBaseActor { private List<Map<String, String>> getUserTypeList(Request request) { List<Map<String, String>> userTypes = new ArrayList<>(); - Map<String, Map<String, List<String>>> userTypeConfigList = DataCacheHandler.getUserTypesConfig(); Map<String, List<String>> userTypeLists = userTypeConfigList.get(JsonKey.DEFAULT_PERSONA); diff --git a/service/src/main/java/org/sunbird/actor/user/UserUpdateActor.java b/service/src/main/java/org/sunbird/actor/user/UserUpdateActor.java index 5837dbd66..af712acab 100644 --- a/service/src/main/java/org/sunbird/actor/user/UserUpdateActor.java +++ b/service/src/main/java/org/sunbird/actor/user/UserUpdateActor.java @@ -5,6 +5,9 @@ import com.fasterxml.jackson.databind.ObjectMapper; import java.sql.Timestamp; import java.text.MessageFormat; import java.util.*; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Function; +import java.util.function.Predicate; import java.util.stream.Collectors; import javax.inject.Inject; import javax.inject.Named; @@ -41,10 +44,11 @@ import org.sunbird.util.user.UserUtil; public class UserUpdateActor extends UserBaseActor { - private UserRequestValidator userRequestValidator = new UserRequestValidator(); - private ObjectMapper mapper = new ObjectMapper(); - private UserService userService = UserServiceImpl.getInstance(); - private UserSelfDeclarationDao userSelfDeclarationDao = UserSelfDeclarationDaoImpl.getInstance(); + private final UserRequestValidator userRequestValidator = new UserRequestValidator(); + private final ObjectMapper mapper = new ObjectMapper(); + private final UserService userService = UserServiceImpl.getInstance(); + private final UserSelfDeclarationDao userSelfDeclarationDao = + UserSelfDeclarationDaoImpl.getInstance(); @Inject @Named("user_profile_update_actor") @@ -69,6 +73,7 @@ public class UserUpdateActor extends UserBaseActor { switch (operation) { case "updateUser": case "updateUserV2": + case "updateUserV3": updateUser(request); break; default: @@ -86,16 +91,60 @@ public class UserUpdateActor extends UserBaseActor { UserUtil.updateExternalIdsProviderWithOrgId(userMap, actorMessage.getRequestContext()); Map<String, Object> userDbRecord = UserUtil.validateExternalIdsAndReturnActiveUser(userMap, actorMessage.getRequestContext()); - if (actorMessage.getOperation().equalsIgnoreCase(ActorOperations.UPDATE_USER_V2.getValue())) { - populateUserTypeAndSubType(userMap); - populateLocationCodesFromProfileLocation(userMap); - } else { + if (actorMessage + .getOperation() + .equalsIgnoreCase(ActorOperations.UPDATE_USER.getValue())) { userMap.remove(JsonKey.PROFILE_LOCATION); - userMap.remove(JsonKey.PROFILE_USERTYPE); + } else { + populateLocationCodesFromProfileLocation(userMap); } validateAndGetLocationCodes(actorMessage); - validateUserTypeAndSubType( - actorMessage.getRequest(), userDbRecord, actorMessage.getRequestContext()); + if (actorMessage + .getOperation() + .equalsIgnoreCase(ActorOperations.UPDATE_USER.getValue())) { + userMap.remove(JsonKey.PROFILE_USERTYPES); + userMap.remove(JsonKey.PROFILE_USERTYPE); + validateUserTypeAndSubType( + actorMessage.getRequest(), userDbRecord, actorMessage.getRequestContext()); + } else if (actorMessage.getOperation().equalsIgnoreCase(ActorOperations.UPDATE_USER_V2.getValue())) { + userMap.remove(JsonKey.PROFILE_USERTYPES); + populateUserTypeAndSubType(userMap); + validateUserTypeAndSubType( + actorMessage.getRequest(), userDbRecord, actorMessage.getRequestContext()); + } else if (actorMessage + .getOperation() + .equalsIgnoreCase(ActorOperations.UPDATE_USER_V3.getValue())) { + userMap.remove(JsonKey.PROFILE_USERTYPE); + userMap.remove(JsonKey.USER_TYPE); + userMap.remove(JsonKey.USER_SUB_TYPE); + if (userMap.containsKey(JsonKey.PROFILE_USERTYPES)) { + List<Map<String, Object>> userTypeAndSubTypes = + (List<Map<String, Object>>) userMap.get(JsonKey.PROFILE_USERTYPES); + + List<Map<String, Object>> distinctUserTypeAndSubTypes = + userTypeAndSubTypes + .stream() + .filter(s -> filterFunction(s)) + .filter( + distinctByValue(map -> map.get(JsonKey.TYPE) + "_" + map.get(JsonKey.SUB_TYPE))) + .collect(Collectors.toList()); + + Map<String, Object> userTypeAndSubType = distinctUserTypeAndSubTypes.get(0); + if (MapUtils.isNotEmpty(userTypeAndSubType)) { + userMap.put(JsonKey.USER_TYPE, userTypeAndSubType.get(JsonKey.TYPE)); + userMap.put(JsonKey.USER_SUB_TYPE, userTypeAndSubType.get(JsonKey.SUB_TYPE)); + } + validateUserTypeAndSubType( + actorMessage.getRequest(), userDbRecord, actorMessage.getRequestContext()); + try { + userMap.put( + JsonKey.PROFILE_USERTYPES, mapper.writeValueAsString(distinctUserTypeAndSubTypes)); + } catch (Exception ex) { + logger.error(actorMessage.getRequestContext(), "Exception while mapping", ex); + ProjectCommonException.throwServerErrorException(ResponseCode.SERVER_ERROR); + } + } + } String managedById = (String) userDbRecord.get(JsonKey.MANAGED_BY); if (StringUtils.isNotBlank(callerId)) { userService.validateUploader(actorMessage, actorMessage.getRequestContext()); @@ -237,6 +286,15 @@ public class UserUpdateActor extends UserBaseActor { userMap, actorMessage, (String) userMap.get(JsonKey.USER_ID), JsonKey.UPDATE); } + private <T> Predicate<T> distinctByValue(Function<? super T, ?> keyExtractor) { + Map<Object, Boolean> seen = new ConcurrentHashMap<>(); + return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null; + } + + private boolean filterFunction(Map<String, Object> map) { + return map.get(JsonKey.TYPE) != null; + } + private void validateUserTypeAndSubType( Map<String, Object> userMap, Map<String, Object> userDbRecord, RequestContext context) { if (null != userMap.get(JsonKey.USER_TYPE)) { @@ -258,10 +316,14 @@ public class UserUpdateActor extends UserBaseActor { String.format( "Locations for userId:%s is:%s", userMap.get(JsonKey.USER_ID), locationIds)); if (CollectionUtils.isNotEmpty(locationIds)) { - locations = locationClient.getLocationByIds(locationActor, locationIds, context); + locations = searchLocationByCodesOrIds(JsonKey.ID, locationIds, context); } } else { - locations = locationClient.getLocationsByCodes(locationActor, locationCodes, context); + logger.info( + context, + String.format( + "Locations for userId:%s is:%s", userMap.get(JsonKey.USER_ID), locationCodes)); + locations = searchLocationByCodesOrIds(JsonKey.CODE, locationCodes, context); } if (CollectionUtils.isNotEmpty(locations)) { String stateCode = null; @@ -286,6 +348,21 @@ public class UserUpdateActor extends UserBaseActor { } } + private List<Location> searchLocationByCodesOrIds( + String codeOrId, List<String> locationCodesOrIds, RequestContext context) { + Map<String, Object> filters = new HashMap<>(); + Map<String, Object> searchRequestMap = new HashMap<>(); + filters.put(codeOrId, locationCodesOrIds); + searchRequestMap.put(JsonKey.FILTERS, filters); + Response searchResponse = locationService.searchLocation(searchRequestMap, context); + List<Map<String, Object>> responseList = + (List<Map<String, Object>>) searchResponse.getResult().get(JsonKey.RESPONSE); + return responseList + .stream() + .map(s -> mapper.convertValue(s, Location.class)) + .collect(Collectors.toList()); + } + private void validateUserTypeAndSubType( Map<String, Object> userMap, RequestContext context, String stateCode) { String stateCodeConfig = userRequestValidator.validateUserType(userMap, stateCode, context); @@ -353,8 +430,9 @@ public class UserUpdateActor extends UserBaseActor { locCodeLst.add(externalIdMap.get(JsonKey.ID)); } }); - List<Location> locationIdList = - locationClient.getLocationByCodes(locationActor, locCodeLst, context); + logger.info( + context, "updateLocationCodeToIds : Searching location for location codes " + locCodeLst); + List<Location> locationIdList = searchLocationByCodesOrIds(JsonKey.CODE, locCodeLst, context); if (CollectionUtils.isNotEmpty(locationIdList)) { locationIdList.forEach( location -> @@ -586,6 +664,8 @@ public class UserUpdateActor extends UserBaseActor { userRequest.setOperation(ActorOperations.UPDATE_USER_INFO_ELASTIC.getValue()); userRequest.getRequest().put(JsonKey.ID, completeUserMap.get(JsonKey.ID)); logger.info(context, "UserUpdateActor:saveUserDetailsToEs: Trigger sync of user details to ES"); - backgroundJobManager.tell(userRequest, self()); + if (null != backgroundJobManager) { + backgroundJobManager.tell(userRequest, self()); + } } } diff --git a/service/src/main/java/org/sunbird/actor/user/validator/UserRequestValidator.java b/service/src/main/java/org/sunbird/actor/user/validator/UserRequestValidator.java index a8d126f7b..8f55f88f4 100644 --- a/service/src/main/java/org/sunbird/actor/user/validator/UserRequestValidator.java +++ b/service/src/main/java/org/sunbird/actor/user/validator/UserRequestValidator.java @@ -11,20 +11,21 @@ import org.sunbird.exception.ProjectCommonException; import org.sunbird.exception.ResponseCode; import org.sunbird.exception.ResponseMessage; import org.sunbird.keys.JsonKey; -import org.sunbird.util.DataCacheHandler; -import org.sunbird.util.FormApiUtil; import org.sunbird.logging.LoggerUtil; +import org.sunbird.operations.ActorOperations; import org.sunbird.request.Request; import org.sunbird.request.RequestContext; +import org.sunbird.util.DataCacheHandler; +import org.sunbird.util.FormApiUtil; import org.sunbird.util.ProjectUtil; import org.sunbird.util.StringFormatter; import org.sunbird.validator.BaseRequestValidator; public class UserRequestValidator extends BaseRequestValidator { - private static final int ERROR_CODE = ResponseCode.CLIENT_ERROR.getResponseCode(); + private final int ERROR_CODE = ResponseCode.CLIENT_ERROR.getResponseCode(); protected static List<String> typeList = new ArrayList<>(); - private static LoggerUtil logger = new LoggerUtil(UserRequestValidator.class); + private static final LoggerUtil logger = new LoggerUtil(UserRequestValidator.class); static { List<String> subTypeList = @@ -51,7 +52,8 @@ public class UserRequestValidator extends BaseRequestValidator { JsonKey.EXTERNAL_ID, JsonKey.EXTERNAL_ID_PROVIDER, JsonKey.EXTERNAL_ID_TYPE, - JsonKey.ID_TYPE), + JsonKey.ID_TYPE, + JsonKey.PROFILE_USERTYPES), userRequest); createUserBasicValidation(userRequest); validateUserType(userRequest.getRequest(), null, userRequest.getRequestContext()); @@ -63,7 +65,7 @@ public class UserRequestValidator extends BaseRequestValidator { return password.matches(ProjectUtil.getConfigValue(JsonKey.SUNBIRD_PASS_REGEX)); } - private static void validatePassword(String password) { + private void validatePassword(String password) { if (StringUtils.isNotBlank(password)) { boolean response = isGoodPassword(password); if (!response) { @@ -290,6 +292,10 @@ public class UserRequestValidator extends BaseRequestValidator { validateRecoveryEmailOrPhone(userRequest); } + public void validateUpdateUserRequestV3(Request userRequest) { + validateUpdateUserRequest(userRequest); + } + public void checkEmptyPhoneAndEmail(Request userRequest) { String phone = (String) userRequest.getRequest().get(JsonKey.PHONE); String email = (String) userRequest.getRequest().get(JsonKey.EMAIL); @@ -425,6 +431,45 @@ public class UserRequestValidator extends BaseRequestValidator { ERROR_CODE); } } + if (userRequest + .getOperation() + .equalsIgnoreCase(ActorOperations.UPDATE_USER.getValue()) || userRequest + .getOperation() + .equalsIgnoreCase(ActorOperations.UPDATE_USER_V2.getValue())) { + if (userRequest.getRequest().containsKey(JsonKey.PROFILE_USERTYPES)){ + ProjectCommonException.throwClientErrorException(ResponseCode.invalidParameter,JsonKey.PROFILE_USERTYPES); + } + }else{ + if (userRequest.getRequest().containsKey(JsonKey.PROFILE_USERTYPE)){ + ProjectCommonException.throwClientErrorException(ResponseCode.invalidParameter,JsonKey.PROFILE_USERTYPE); + } + } + if (userRequest.getRequest().containsKey(JsonKey.PROFILE_USERTYPES) + && null != userRequest.getRequest().get(JsonKey.PROFILE_USERTYPES)) { + if (userRequest.getRequest().get(JsonKey.PROFILE_USERTYPES) instanceof List){ + List profileusertypes = (List) userRequest.getRequest().get(JsonKey.PROFILE_USERTYPES); + if (CollectionUtils.isEmpty(profileusertypes)) { + ProjectCommonException.throwClientErrorException(ResponseCode.profileUserTypesRequired); + }else { + try { + List<Map<String, String>> profUserTypeList = + (List<Map<String, String>>) userRequest.getRequest().get(JsonKey.PROFILE_USERTYPES); + }catch (ClassCastException e) { + throw new ProjectCommonException( + ResponseCode.dataTypeError.getErrorCode(), + ProjectUtil.formatMessage( + ResponseCode.dataTypeError.getErrorMessage(), JsonKey.PROFILE_USERTYPES, JsonKey.LIST), + ERROR_CODE); + } + } + } else if (!(userRequest.getRequest().get(JsonKey.PROFILE_USERTYPES) instanceof List)) { + throw new ProjectCommonException( + ResponseCode.dataTypeError.getErrorCode(), + ProjectUtil.formatMessage( + ResponseCode.dataTypeError.getErrorMessage(), JsonKey.PROFILE_USERTYPES, JsonKey.LIST), + ERROR_CODE); + } + } } private void validateUserIdOrExternalId(Request userRequest) { @@ -744,7 +789,21 @@ public class UserRequestValidator extends BaseRequestValidator { context, String.format( "Available User Type for stateCode:%s are %s", stateCode, userTypeMap.keySet())); - if (!userTypeMap.containsKey(userType)) { + List<Map> profileUserTypes = (List<Map>) userRequestMap.get(JsonKey.PROFILE_USERTYPES); + if(CollectionUtils.isNotEmpty(profileUserTypes) && MapUtils.isNotEmpty((Map)profileUserTypes.get(0))){ + profileUserTypes.forEach( + item -> { + String userTypeItem = (String) item.get(JsonKey.TYPE); + if (!userTypeMap.containsKey(userTypeItem)) { + ProjectCommonException.throwClientErrorException( + ResponseCode.invalidParameterValue, + MessageFormat.format( + ResponseCode.invalidParameterValue.getErrorMessage(), + new String[] {userType, JsonKey.USER_TYPE})); + } + } + ); + }else if (!userTypeMap.containsKey(userType)) { ProjectCommonException.throwClientErrorException( ResponseCode.invalidParameterValue, MessageFormat.format( @@ -757,13 +816,32 @@ public class UserRequestValidator extends BaseRequestValidator { public void validateUserSubType(Map<String, Object> userRequestMap, String stateCode) { String userType = (String) userRequestMap.get(JsonKey.USER_TYPE); + String userSubType = (String) userRequestMap.get(JsonKey.USER_SUB_TYPE); Map<String, Map<String, List<String>>> userTypeConfigMap = DataCacheHandler.getUserTypesConfig(); - String userSubType = (String) userRequestMap.get(JsonKey.USER_SUB_TYPE); - Map<String, List<String>> userSubTypeMap = userTypeConfigMap.get(stateCode); - if (null != userSubType - && (null == userSubTypeMap.get(userType) - || !userSubTypeMap.get(userType).contains(userSubType))) { + Map<String, List<String>> userTypeMap = userTypeConfigMap.get(stateCode); + + List<Map> profileUserTypes = (List<Map>) userRequestMap.get(JsonKey.PROFILE_USERTYPES); + if(CollectionUtils.isNotEmpty(profileUserTypes) && MapUtils.isNotEmpty(profileUserTypes.get(0))){ + profileUserTypes.forEach( + item -> { + String userTypeItem = (String) item.get(JsonKey.TYPE); + String userSubTypeItem = (String) item.get(JsonKey.SUB_TYPE); + if(StringUtils.isNotEmpty(userSubTypeItem)) { + if (null == userTypeMap.get(userTypeItem) || + !userTypeMap.get(userTypeItem).contains(userSubTypeItem)) { + ProjectCommonException.throwClientErrorException( + ResponseCode.invalidParameterValue, + MessageFormat.format( + ResponseCode.invalidParameterValue.getErrorMessage(), + new String[] {userSubTypeItem, JsonKey.USER_SUB_TYPE})); + } + } + } + ); + } else if (null != userSubType + && (null == userTypeMap.get(userType) + || !userTypeMap.get(userType).contains(userSubType))) { ProjectCommonException.throwClientErrorException( ResponseCode.invalidParameterValue, MessageFormat.format( diff --git a/service/src/main/java/org/sunbird/actor/user/validator/UserTenantMigrationRequestValidator.java b/service/src/main/java/org/sunbird/actor/user/validator/UserTenantMigrationRequestValidator.java deleted file mode 100644 index 9a80fec78..000000000 --- a/service/src/main/java/org/sunbird/actor/user/validator/UserTenantMigrationRequestValidator.java +++ /dev/null @@ -1,28 +0,0 @@ -package org.sunbird.actor.user.validator; - -import java.util.Map; -import org.sunbird.exception.ResponseCode; -import org.sunbird.keys.JsonKey; -import org.sunbird.request.Request; - -/** - * Request validator class for user tenant migration request. - * - * @author Amit Kumar - */ -public class UserTenantMigrationRequestValidator extends UserRequestValidator { - - /** - * This method will validate the user migration request. - * - * @param request user migration request body - */ - public void validateUserTenantMigrateRequest(Request request) { - Map<String, Object> req = request.getRequest(); - validateParam( - (String) req.get(JsonKey.CHANNEL), ResponseCode.mandatoryParamsMissing, JsonKey.CHANNEL); - validateParam( - (String) req.get(JsonKey.USER_ID), ResponseCode.mandatoryParamsMissing, JsonKey.USER_ID); - externalIdsValidation(request, JsonKey.CREATE); - } -} diff --git a/service/src/main/java/org/sunbird/actor/userconsent/UserConsentActor.java b/service/src/main/java/org/sunbird/actor/userconsent/UserConsentActor.java index 589a9ddbe..35b011ac3 100644 --- a/service/src/main/java/org/sunbird/actor/userconsent/UserConsentActor.java +++ b/service/src/main/java/org/sunbird/actor/userconsent/UserConsentActor.java @@ -23,8 +23,8 @@ import org.sunbird.util.Util; public class UserConsentActor extends BaseActor { - private UserService userService = UserServiceImpl.getInstance(); - private UserConsentService userConsentService = UserConsentServiceImpl.getInstance(); + private final UserService userService = UserServiceImpl.getInstance(); + private final UserConsentService userConsentService = UserConsentServiceImpl.getInstance(); @Override public void onReceive(Request request) throws Throwable { @@ -70,6 +70,9 @@ public class UserConsentActor extends BaseActor { request.getRequest().put(JsonKey.USER_ID, userId); // Important for userid validation userService.validateUserId(request, null, context); + String consumerId = (String) consent.get(JsonKey.CONSENT_CONSUMERID); + userConsentService.validateConsumerId(consumerId, context); + Response consentRes = userConsentService.updateConsent(consent, context); Response response = new Response(); @@ -117,6 +120,7 @@ public class UserConsentActor extends BaseActor { List<Map<String, Object>> consentResponseList = consentDBList .stream() + .filter(consents->((String)consents.get(JsonKey.STATUS)).equalsIgnoreCase(JsonKey.ACTIVE)) .map( consent -> { Map<String, Object> consentRes = new HashMap<String, Object>(); diff --git a/service/src/main/java/org/sunbird/client/location/impl/LocationClientImpl.java b/service/src/main/java/org/sunbird/client/location/impl/LocationClientImpl.java index 0330ed2b0..3e9ced4cc 100644 --- a/service/src/main/java/org/sunbird/client/location/impl/LocationClientImpl.java +++ b/service/src/main/java/org/sunbird/client/location/impl/LocationClientImpl.java @@ -27,8 +27,8 @@ import scala.concurrent.Future; import scala.concurrent.duration.Duration; public class LocationClientImpl implements LocationClient { - private static LoggerUtil logger = new LoggerUtil(LocationClientImpl.class); - private ObjectMapper mapper = new ObjectMapper(); + private final LoggerUtil logger = new LoggerUtil(LocationClientImpl.class); + private final ObjectMapper mapper = new ObjectMapper(); public static LocationClient locationClient = null; public static synchronized LocationClient getInstance() { diff --git a/service/src/main/java/org/sunbird/client/org/impl/OrganisationClientImpl.java b/service/src/main/java/org/sunbird/client/org/impl/OrganisationClientImpl.java index 03b2ca065..1a54c5d55 100644 --- a/service/src/main/java/org/sunbird/client/org/impl/OrganisationClientImpl.java +++ b/service/src/main/java/org/sunbird/client/org/impl/OrganisationClientImpl.java @@ -34,7 +34,7 @@ import scala.concurrent.duration.Duration; public class OrganisationClientImpl implements OrganisationClient { - private static LoggerUtil logger = new LoggerUtil(OrganisationClientImpl.class); + private final LoggerUtil logger = new LoggerUtil(OrganisationClientImpl.class); public static OrganisationClient organisationClient = null; public static OrganisationClient getInstance() { diff --git a/service/src/main/java/org/sunbird/client/systemsettings/impl/SystemSettingClientImpl.java b/service/src/main/java/org/sunbird/client/systemsettings/impl/SystemSettingClientImpl.java index bce731146..ff268e2db 100644 --- a/service/src/main/java/org/sunbird/client/systemsettings/impl/SystemSettingClientImpl.java +++ b/service/src/main/java/org/sunbird/client/systemsettings/impl/SystemSettingClientImpl.java @@ -23,7 +23,7 @@ import scala.concurrent.Future; import scala.concurrent.duration.Duration; public class SystemSettingClientImpl implements SystemSettingClient { - private static LoggerUtil logger = new LoggerUtil(SystemSettingClientImpl.class); + private final LoggerUtil logger = new LoggerUtil(SystemSettingClientImpl.class); private static SystemSettingClient systemSettingClient = null; public static SystemSettingClient getInstance() { diff --git a/service/src/main/java/org/sunbird/client/user/impl/UserClientImpl.java b/service/src/main/java/org/sunbird/client/user/impl/UserClientImpl.java index 318d68bd9..e50438af4 100644 --- a/service/src/main/java/org/sunbird/client/user/impl/UserClientImpl.java +++ b/service/src/main/java/org/sunbird/client/user/impl/UserClientImpl.java @@ -31,9 +31,8 @@ import scala.concurrent.duration.Duration; public class UserClientImpl implements UserClient { - private static LoggerUtil logger = new LoggerUtil(UserClientImpl.class); - - private ElasticSearchService esUtil = EsClientFactory.getInstance(JsonKey.REST); + private final LoggerUtil logger = new LoggerUtil(UserClientImpl.class); + private final ElasticSearchService esUtil = EsClientFactory.getInstance(JsonKey.REST); public static UserClient userClient = null; public static UserClient getInstance() { diff --git a/service/src/main/java/org/sunbird/dao/bulkupload/impl/BulkUploadProcessDaoImpl.java b/service/src/main/java/org/sunbird/dao/bulkupload/impl/BulkUploadProcessDaoImpl.java index 44b9fc7d5..b459c7482 100644 --- a/service/src/main/java/org/sunbird/dao/bulkupload/impl/BulkUploadProcessDaoImpl.java +++ b/service/src/main/java/org/sunbird/dao/bulkupload/impl/BulkUploadProcessDaoImpl.java @@ -18,10 +18,9 @@ import org.sunbird.response.Response; /** Created by arvind on 24/4/18. */ public class BulkUploadProcessDaoImpl implements BulkUploadProcessDao { - private static LoggerUtil logger = new LoggerUtil(BulkUploadProcessDaoImpl.class); - - private CassandraOperation cassandraOperation = ServiceFactory.getInstance(); - private ObjectMapper mapper = new ObjectMapper(); + private final LoggerUtil logger = new LoggerUtil(BulkUploadProcessDaoImpl.class); + private final CassandraOperation cassandraOperation = ServiceFactory.getInstance(); + private final ObjectMapper mapper = new ObjectMapper(); private static final String KEYSPACE_NAME = "sunbird"; private static final String TABLE_NAME = "bulk_upload_process"; diff --git a/service/src/main/java/org/sunbird/dao/bulkupload/impl/BulkUploadProcessTaskDaoImpl.java b/service/src/main/java/org/sunbird/dao/bulkupload/impl/BulkUploadProcessTaskDaoImpl.java index 19b38eeaf..132a5a082 100644 --- a/service/src/main/java/org/sunbird/dao/bulkupload/impl/BulkUploadProcessTaskDaoImpl.java +++ b/service/src/main/java/org/sunbird/dao/bulkupload/impl/BulkUploadProcessTaskDaoImpl.java @@ -11,7 +11,8 @@ import org.sunbird.cassandra.CassandraOperation; import org.sunbird.common.CassandraUtil; import org.sunbird.dao.bulkupload.BulkUploadProcessTaskDao; import org.sunbird.helper.ServiceFactory; -import org.sunbird.keys.JsonKey;import org.sunbird.logging.LoggerUtil; +import org.sunbird.keys.JsonKey; +import org.sunbird.logging.LoggerUtil; import org.sunbird.model.bulkupload.BulkUploadProcessTask; import org.sunbird.request.RequestContext; import org.sunbird.response.Response; @@ -22,12 +23,11 @@ import org.sunbird.response.Response; * @author arvind */ public class BulkUploadProcessTaskDaoImpl implements BulkUploadProcessTaskDao { - private static LoggerUtil logger = new LoggerUtil(BulkUploadProcessTaskDaoImpl.class); - - private CassandraOperation cassandraOperation = ServiceFactory.getInstance(); - private ObjectMapper mapper = new ObjectMapper(); - private static final String KEYSPACE_NAME = "sunbird"; - private static final String TABLE_NAME = "bulk_upload_process_task"; + private final LoggerUtil logger = new LoggerUtil(BulkUploadProcessTaskDaoImpl.class); + private final CassandraOperation cassandraOperation = ServiceFactory.getInstance(); + private final ObjectMapper mapper = new ObjectMapper(); + private final String KEYSPACE_NAME = "sunbird"; + private final String TABLE_NAME = "bulk_upload_process_task"; public static BulkUploadProcessTaskDao bulkUploadProcessTaskDao = null; diff --git a/service/src/main/java/org/sunbird/dao/feed/impl/FeedDaoImpl.java b/service/src/main/java/org/sunbird/dao/feed/impl/FeedDaoImpl.java index 381539574..e3a4d96b2 100644 --- a/service/src/main/java/org/sunbird/dao/feed/impl/FeedDaoImpl.java +++ b/service/src/main/java/org/sunbird/dao/feed/impl/FeedDaoImpl.java @@ -14,10 +14,8 @@ import org.sunbird.util.Util; public class FeedDaoImpl implements IFeedDao { - private static LoggerUtil logger = new LoggerUtil(FeedServiceImpl.class); - - private Util.DbInfo usrFeedDbInfo = Util.dbInfoMap.get(JsonKey.USER_FEED_DB); - + private final LoggerUtil logger = new LoggerUtil(FeedServiceImpl.class); + private final Util.DbInfo usrFeedDbInfo = Util.dbInfoMap.get(JsonKey.USER_FEED_DB); private static IFeedDao iFeedDao = null; public static IFeedDao getInstance() { diff --git a/service/src/main/java/org/sunbird/dao/location/impl/LocationDaoImpl.java b/service/src/main/java/org/sunbird/dao/location/impl/LocationDaoImpl.java index ef9ea4b1d..1abc94afd 100644 --- a/service/src/main/java/org/sunbird/dao/location/impl/LocationDaoImpl.java +++ b/service/src/main/java/org/sunbird/dao/location/impl/LocationDaoImpl.java @@ -23,12 +23,11 @@ import scala.concurrent.Future; /** @author Amit Kumar */ public class LocationDaoImpl implements LocationDao { - private CassandraOperation cassandraOperation = ServiceFactory.getInstance(); - private ElasticSearchService esUtil = EsClientFactory.getInstance(JsonKey.REST); - private ObjectMapper mapper = new ObjectMapper(); + private final CassandraOperation cassandraOperation = ServiceFactory.getInstance(); + private final ElasticSearchService esUtil = EsClientFactory.getInstance(JsonKey.REST); + private final ObjectMapper mapper = new ObjectMapper(); private static final String KEYSPACE_NAME = "sunbird"; private static final String LOCATION_TABLE_NAME = "location"; - private static final String DEFAULT_SORT_BY = "ASC"; @Override public Response create(Location location, RequestContext context) { @@ -105,6 +104,7 @@ public class LocationDaoImpl implements LocationDao { && ((Map<String, Object>) searchDtO.getAdditionalProperties().get(JsonKey.FILTERS)) .containsKey(JsonKey.TYPE)) { if (MapUtils.isEmpty(searchDtO.getSortBy())) { + String DEFAULT_SORT_BY = "ASC"; searchDtO.getSortBy().put(JsonKey.NAME, DEFAULT_SORT_BY); } } diff --git a/service/src/main/java/org/sunbird/dao/notes/impl/NotesDaoImpl.java b/service/src/main/java/org/sunbird/dao/notes/impl/NotesDaoImpl.java index fb6d033dc..b6cb71d7c 100644 --- a/service/src/main/java/org/sunbird/dao/notes/impl/NotesDaoImpl.java +++ b/service/src/main/java/org/sunbird/dao/notes/impl/NotesDaoImpl.java @@ -17,9 +17,9 @@ import org.sunbird.util.ProjectUtil; import scala.concurrent.Future; public class NotesDaoImpl implements NotesDao { - public LoggerUtil logger = new LoggerUtil(NotesDaoImpl.class); - private CassandraOperation cassandraOperation = ServiceFactory.getInstance(); - private ElasticSearchService esService = EsClientFactory.getInstance(JsonKey.REST); + public final LoggerUtil logger = new LoggerUtil(NotesDaoImpl.class); + private final CassandraOperation cassandraOperation = ServiceFactory.getInstance(); + private final ElasticSearchService esService = EsClientFactory.getInstance(JsonKey.REST); private static final String KEYSPACE_NAME = JsonKey.SUNBIRD; private static final String TABLE_NAME = "user_notes"; diff --git a/service/src/main/java/org/sunbird/dao/notification/impl/EmailTemplateDaoImpl.java b/service/src/main/java/org/sunbird/dao/notification/impl/EmailTemplateDaoImpl.java index 7b7a3a3a3..89b1ff8e3 100644 --- a/service/src/main/java/org/sunbird/dao/notification/impl/EmailTemplateDaoImpl.java +++ b/service/src/main/java/org/sunbird/dao/notification/impl/EmailTemplateDaoImpl.java @@ -15,10 +15,7 @@ import org.sunbird.response.Response; public class EmailTemplateDaoImpl implements EmailTemplateDao { - static EmailTemplateDao emailTemplateDao; - private static final String EMAIL_TEMPLATE = "email_template"; - private static final String DEFAULT_EMAIL_TEMPLATE_NAME = "default"; - private static final String TEMPLATE = "template"; + private static EmailTemplateDao emailTemplateDao; public static EmailTemplateDao getInstance() { if (emailTemplateDao == null) { @@ -32,10 +29,12 @@ public class EmailTemplateDaoImpl implements EmailTemplateDao { List<String> idList = new ArrayList<>(); if (StringUtils.isBlank(templateName)) { + String DEFAULT_EMAIL_TEMPLATE_NAME = "default"; idList.add(DEFAULT_EMAIL_TEMPLATE_NAME); } else { idList.add(templateName); } + String EMAIL_TEMPLATE = "email_template"; Response response = getCassandraOperation() .getRecordsByPrimaryKeys( @@ -46,6 +45,7 @@ public class EmailTemplateDaoImpl implements EmailTemplateDao { if (CollectionUtils.isNotEmpty(emailTemplateList)) { map = emailTemplateList.get(0); } + String TEMPLATE = "template"; return (String) map.get(TEMPLATE); } diff --git a/service/src/main/java/org/sunbird/dao/organisation/impl/OrgDaoImpl.java b/service/src/main/java/org/sunbird/dao/organisation/impl/OrgDaoImpl.java index e77391ba2..a3bad155f 100644 --- a/service/src/main/java/org/sunbird/dao/organisation/impl/OrgDaoImpl.java +++ b/service/src/main/java/org/sunbird/dao/organisation/impl/OrgDaoImpl.java @@ -26,10 +26,10 @@ import org.sunbird.util.Util; import scala.concurrent.Future; public class OrgDaoImpl implements OrgDao { - private ElasticSearchService esService = EsClientFactory.getInstance(JsonKey.REST); - private LoggerUtil logger = new LoggerUtil(OrgDaoImpl.class); - private ObjectMapper mapper = new ObjectMapper(); - private CassandraOperation cassandraOperation = ServiceFactory.getInstance(); + private final ElasticSearchService esService = EsClientFactory.getInstance(JsonKey.REST); + private final LoggerUtil logger = new LoggerUtil(OrgDaoImpl.class); + private final ObjectMapper mapper = new ObjectMapper(); + private final CassandraOperation cassandraOperation = ServiceFactory.getInstance(); private static OrgDao orgDao; private static final String KEYSPACE_NAME = JsonKey.SUNBIRD; private static final String ORG_TABLE_NAME = JsonKey.ORGANISATION; diff --git a/service/src/main/java/org/sunbird/dao/organisation/impl/OrgExternalDaoImpl.java b/service/src/main/java/org/sunbird/dao/organisation/impl/OrgExternalDaoImpl.java index e6c2db959..852becb69 100644 --- a/service/src/main/java/org/sunbird/dao/organisation/impl/OrgExternalDaoImpl.java +++ b/service/src/main/java/org/sunbird/dao/organisation/impl/OrgExternalDaoImpl.java @@ -14,7 +14,7 @@ import org.sunbird.response.Response; public class OrgExternalDaoImpl implements OrgExternalDao { - private CassandraOperation cassandraOperation = ServiceFactory.getInstance(); + private final CassandraOperation cassandraOperation = ServiceFactory.getInstance(); private static final String KEYSPACE_NAME = JsonKey.SUNBIRD; private static final String ORG_EXT_TABLE_NAME = JsonKey.ORG_EXT_ID_DB; diff --git a/service/src/main/java/org/sunbird/dao/otp/impl/OTPDaoImpl.java b/service/src/main/java/org/sunbird/dao/otp/impl/OTPDaoImpl.java index 065f50e95..bd0e5245c 100644 --- a/service/src/main/java/org/sunbird/dao/otp/impl/OTPDaoImpl.java +++ b/service/src/main/java/org/sunbird/dao/otp/impl/OTPDaoImpl.java @@ -13,10 +13,9 @@ import org.sunbird.response.Response; import org.sunbird.util.PropertiesCache; public class OTPDaoImpl implements OTPDao { - private static LoggerUtil logger = new LoggerUtil(OTPDaoImpl.class); - + private final LoggerUtil logger = new LoggerUtil(OTPDaoImpl.class); + private final CassandraOperation cassandraOperation = ServiceFactory.getInstance(); private static final String TABLE_NAME = JsonKey.OTP; - private CassandraOperation cassandraOperation = ServiceFactory.getInstance(); private static volatile OTPDao otpDao; public static OTPDao getInstance() { diff --git a/service/src/main/java/org/sunbird/dao/ratelimit/RateLimitDaoImpl.java b/service/src/main/java/org/sunbird/dao/ratelimit/RateLimitDaoImpl.java index 16c395af0..4167075d4 100644 --- a/service/src/main/java/org/sunbird/dao/ratelimit/RateLimitDaoImpl.java +++ b/service/src/main/java/org/sunbird/dao/ratelimit/RateLimitDaoImpl.java @@ -15,8 +15,8 @@ import org.sunbird.util.ratelimit.RateLimit; public class RateLimitDaoImpl implements RateLimitDao { + private final CassandraOperation cassandraOperation = ServiceFactory.getInstance(); private static final String TABLE_NAME = JsonKey.RATE_LIMIT; - private CassandraOperation cassandraOperation = ServiceFactory.getInstance(); private static volatile RateLimitDao rateLimitDao; public static RateLimitDao getInstance() { diff --git a/service/src/main/java/org/sunbird/dao/role/impl/RoleDaoImpl.java b/service/src/main/java/org/sunbird/dao/role/impl/RoleDaoImpl.java index 6f2910432..0bc70ee08 100644 --- a/service/src/main/java/org/sunbird/dao/role/impl/RoleDaoImpl.java +++ b/service/src/main/java/org/sunbird/dao/role/impl/RoleDaoImpl.java @@ -15,7 +15,7 @@ import org.sunbird.response.Response; public class RoleDaoImpl implements RoleDao { private static final String TABLE_NAME = "role"; - private ObjectMapper mapper = new ObjectMapper(); + private final ObjectMapper mapper = new ObjectMapper(); private static RoleDao roleDao; public static RoleDao getInstance() { diff --git a/service/src/main/java/org/sunbird/dao/role/impl/RoleGroupDaoImpl.java b/service/src/main/java/org/sunbird/dao/role/impl/RoleGroupDaoImpl.java index 5b5b3aea2..8d668c834 100644 --- a/service/src/main/java/org/sunbird/dao/role/impl/RoleGroupDaoImpl.java +++ b/service/src/main/java/org/sunbird/dao/role/impl/RoleGroupDaoImpl.java @@ -14,31 +14,31 @@ import org.sunbird.response.Response; public class RoleGroupDaoImpl implements RoleGroupDao { - private ObjectMapper mapper = new ObjectMapper(); - private static RoleGroupDao roleGroupDao; - private static final String KEYSPACE_NAME = "sunbird"; - private static final String TABLE_NAME = "role_group"; + private final ObjectMapper mapper = new ObjectMapper(); + private static RoleGroupDao roleGroupDao; - public static RoleGroupDao getInstance() { - if (roleGroupDao == null) { - roleGroupDao = new RoleGroupDaoImpl(); - } - return roleGroupDao; + public static RoleGroupDao getInstance() { + if (roleGroupDao == null) { + roleGroupDao = new RoleGroupDaoImpl(); } + return roleGroupDao; + } - @SuppressWarnings("unchecked") - @Override - public List<RoleGroup> getRoleGroups(RequestContext context) { - Response roleGroupResults = - getCassandraOperation().getAllRecords(KEYSPACE_NAME, TABLE_NAME, context); - TypeReference<List<RoleGroup>> roleGroupType = new TypeReference<List<RoleGroup>>() {}; - List<Map<String, Object>> roleGroupMapList = - (List<Map<String, Object>>) roleGroupResults.get(JsonKey.RESPONSE); - List<RoleGroup> roleGroupList = mapper.convertValue(roleGroupMapList, roleGroupType); - return roleGroupList; - } + @SuppressWarnings("unchecked") + @Override + public List<RoleGroup> getRoleGroups(RequestContext context) { + String KEYSPACE_NAME = "sunbird"; + String TABLE_NAME = "role_group"; + Response roleGroupResults = + getCassandraOperation().getAllRecords(KEYSPACE_NAME, TABLE_NAME, context); + TypeReference<List<RoleGroup>> roleGroupType = new TypeReference<List<RoleGroup>>() {}; + List<Map<String, Object>> roleGroupMapList = + (List<Map<String, Object>>) roleGroupResults.get(JsonKey.RESPONSE); + List<RoleGroup> roleGroupList = mapper.convertValue(roleGroupMapList, roleGroupType); + return roleGroupList; + } - public CassandraOperation getCassandraOperation() { - return ServiceFactory.getInstance(); - } + public CassandraOperation getCassandraOperation() { + return ServiceFactory.getInstance(); + } } diff --git a/service/src/main/java/org/sunbird/dao/systemsettings/impl/SystemSettingDaoImpl.java b/service/src/main/java/org/sunbird/dao/systemsettings/impl/SystemSettingDaoImpl.java index 2315e56e7..99966a9ec 100644 --- a/service/src/main/java/org/sunbird/dao/systemsettings/impl/SystemSettingDaoImpl.java +++ b/service/src/main/java/org/sunbird/dao/systemsettings/impl/SystemSettingDaoImpl.java @@ -15,12 +15,11 @@ import org.sunbird.response.Response; public class SystemSettingDaoImpl implements SystemSettingDao { - private CassandraOperation cassandraOperation = ServiceFactory.getInstance(); - private ObjectMapper mapper = new ObjectMapper(); + private final CassandraOperation cassandraOperation = ServiceFactory.getInstance(); + private final ObjectMapper mapper = new ObjectMapper(); private static final String KEYSPACE_NAME = JsonKey.SUNBIRD; private static final String TABLE_NAME = JsonKey.SYSTEM_SETTINGS_DB; - @Override public Response write(SystemSetting systemSetting, RequestContext context) { Map<String, Object> map = mapper.convertValue(systemSetting, Map.class); @@ -58,6 +57,6 @@ public class SystemSettingDaoImpl implements SystemSettingDao { } private SystemSetting getSystemSetting(List<Map<String, Object>> list) { - return mapper.convertValue(list.get(0), SystemSetting.class); + return mapper.convertValue(list.get(0), SystemSetting.class); } } diff --git a/service/src/main/java/org/sunbird/dao/tenantpreference/impl/TenantPreferenceDaoImpl.java b/service/src/main/java/org/sunbird/dao/tenantpreference/impl/TenantPreferenceDaoImpl.java index 87b381bd3..64b9589fc 100644 --- a/service/src/main/java/org/sunbird/dao/tenantpreference/impl/TenantPreferenceDaoImpl.java +++ b/service/src/main/java/org/sunbird/dao/tenantpreference/impl/TenantPreferenceDaoImpl.java @@ -1,5 +1,8 @@ package org.sunbird.dao.tenantpreference.impl; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; import org.sunbird.cassandra.CassandraOperation; import org.sunbird.dao.tenantpreference.TenantPreferenceDao; import org.sunbird.helper.ServiceFactory; @@ -7,14 +10,9 @@ import org.sunbird.keys.JsonKey; import org.sunbird.request.RequestContext; import org.sunbird.response.Response; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - public class TenantPreferenceDaoImpl implements TenantPreferenceDao { - private CassandraOperation cassandraOperation = ServiceFactory.getInstance(); - + private final CassandraOperation cassandraOperation = ServiceFactory.getInstance(); private static TenantPreferenceDao preferenceDao; public static TenantPreferenceDao getInstance() { @@ -25,35 +23,34 @@ public class TenantPreferenceDaoImpl implements TenantPreferenceDao { } @Override - public List<Map<String, Object>> getTenantPreferenceById(String orgId, String key, RequestContext context) { + public List<Map<String, Object>> getTenantPreferenceById( + String orgId, String key, RequestContext context) { Map<String, Object> properties = new LinkedHashMap<>(); properties.put(JsonKey.ORG_ID, orgId); properties.put(JsonKey.KEY, key); Response tenantPreferences = - cassandraOperation.getRecordsByProperties( - JsonKey.SUNBIRD, - JsonKey.TENANT_PREFERENCE_V2_DB, - properties, - context); - return (List<Map<String, Object>>) tenantPreferences.get(JsonKey.RESPONSE); + cassandraOperation.getRecordsByProperties( + JsonKey.SUNBIRD, JsonKey.TENANT_PREFERENCE_V2_DB, properties, context); + return (List<Map<String, Object>>) tenantPreferences.get(JsonKey.RESPONSE); } @Override - public Response insertTenantPreference(Map<String, Object> tenantPreference, RequestContext context) { + public Response insertTenantPreference( + Map<String, Object> tenantPreference, RequestContext context) { return cassandraOperation.insertRecord( - JsonKey.SUNBIRD, - JsonKey.TENANT_PREFERENCE_V2_DB, - tenantPreference, - context); + JsonKey.SUNBIRD, JsonKey.TENANT_PREFERENCE_V2_DB, tenantPreference, context); } @Override - public Response updateTenantPreference(Map<String, Object> tenantPreference, Map<String, Object> clusteringKeys, RequestContext context) { + public Response updateTenantPreference( + Map<String, Object> tenantPreference, + Map<String, Object> clusteringKeys, + RequestContext context) { return cassandraOperation.updateRecord( - JsonKey.SUNBIRD, - JsonKey.TENANT_PREFERENCE_V2_DB, - tenantPreference, - clusteringKeys, - context); + JsonKey.SUNBIRD, + JsonKey.TENANT_PREFERENCE_V2_DB, + tenantPreference, + clusteringKeys, + context); } } diff --git a/service/src/main/java/org/sunbird/dao/urlaction/impl/UrlActionDaoImpl.java b/service/src/main/java/org/sunbird/dao/urlaction/impl/UrlActionDaoImpl.java index 671f39891..d3ea7861f 100644 --- a/service/src/main/java/org/sunbird/dao/urlaction/impl/UrlActionDaoImpl.java +++ b/service/src/main/java/org/sunbird/dao/urlaction/impl/UrlActionDaoImpl.java @@ -13,11 +13,9 @@ import org.sunbird.response.Response; public class UrlActionDaoImpl implements UrlActionDao { - private CassandraOperation cassandraOperation = ServiceFactory.getInstance(); - private ObjectMapper mapper = new ObjectMapper(); + private final CassandraOperation cassandraOperation = ServiceFactory.getInstance(); + private final ObjectMapper mapper = new ObjectMapper(); private static UrlActionDao urlActionDao; - private static final String KEYSPACE_NAME = "sunbird"; - private static final String TABLE_NAME = "url_action"; public static UrlActionDao getInstance() { if (urlActionDao == null) { @@ -26,11 +24,12 @@ public class UrlActionDaoImpl implements UrlActionDao { return urlActionDao; } - @SuppressWarnings("unchecked") @Override public List<UrlAction> getUrlActions() { + String KEYSPACE_NAME = "sunbird"; + String TABLE_NAME = "url_action"; Response urlActionResults = cassandraOperation.getAllRecords(KEYSPACE_NAME, TABLE_NAME, null); - TypeReference<List<UrlAction>> urlActionType = new TypeReference<List<UrlAction>>() {}; + TypeReference<List<UrlAction>> urlActionType = new TypeReference<>() {}; List<Map<String, Object>> urlActionMapList = (List<Map<String, Object>>) urlActionResults.get(JsonKey.RESPONSE); List<UrlAction> urlActionList = mapper.convertValue(urlActionMapList, urlActionType); diff --git a/service/src/main/java/org/sunbird/dao/user/impl/UserDaoImpl.java b/service/src/main/java/org/sunbird/dao/user/impl/UserDaoImpl.java index 10df90429..88b596fb4 100644 --- a/service/src/main/java/org/sunbird/dao/user/impl/UserDaoImpl.java +++ b/service/src/main/java/org/sunbird/dao/user/impl/UserDaoImpl.java @@ -29,12 +29,12 @@ import scala.concurrent.Future; */ public class UserDaoImpl implements UserDao { - private LoggerUtil logger = new LoggerUtil(UserDaoImpl.class); + private final LoggerUtil logger = new LoggerUtil(UserDaoImpl.class); private static final String TABLE_NAME = JsonKey.USER; private static final String KEY_SPACE_NAME = JsonKey.SUNBIRD; - private ElasticSearchService esService = EsClientFactory.getInstance(JsonKey.REST); - private CassandraOperation cassandraOperation = ServiceFactory.getInstance(); - private ObjectMapper mapper = new ObjectMapper(); + private final ElasticSearchService esService = EsClientFactory.getInstance(JsonKey.REST); + private final CassandraOperation cassandraOperation = ServiceFactory.getInstance(); + private final ObjectMapper mapper = new ObjectMapper(); private static UserDao userDao = null; public static UserDao getInstance() { diff --git a/service/src/main/java/org/sunbird/dao/user/impl/UserExternalIdentityDaoImpl.java b/service/src/main/java/org/sunbird/dao/user/impl/UserExternalIdentityDaoImpl.java index 79b422746..6d4d0298d 100644 --- a/service/src/main/java/org/sunbird/dao/user/impl/UserExternalIdentityDaoImpl.java +++ b/service/src/main/java/org/sunbird/dao/user/impl/UserExternalIdentityDaoImpl.java @@ -17,8 +17,8 @@ import org.sunbird.response.Response; public class UserExternalIdentityDaoImpl implements UserExternalIdentityDao { - private static LoggerUtil logger = new LoggerUtil(UserExternalIdentityDaoImpl.class); - private CassandraOperation cassandraOperation = ServiceFactory.getInstance(); + private final LoggerUtil logger = new LoggerUtil(UserExternalIdentityDaoImpl.class); + private final CassandraOperation cassandraOperation = ServiceFactory.getInstance(); @Override public String getUserIdByExternalId(String extId, String provider, RequestContext context) { diff --git a/service/src/main/java/org/sunbird/dao/user/impl/UserLookupDaoImpl.java b/service/src/main/java/org/sunbird/dao/user/impl/UserLookupDaoImpl.java index 3aaf455e9..f96e59132 100644 --- a/service/src/main/java/org/sunbird/dao/user/impl/UserLookupDaoImpl.java +++ b/service/src/main/java/org/sunbird/dao/user/impl/UserLookupDaoImpl.java @@ -17,11 +17,10 @@ import org.sunbird.util.DataCacheHandler; import org.sunbird.util.Util; public class UserLookupDaoImpl implements UserLookupDao { - private static LoggerUtil logger = new LoggerUtil(UserLookupDaoImpl.class); - - private static Util.DbInfo userLookUp = Util.dbInfoMap.get(JsonKey.USER_LOOKUP); - private CassandraOperation cassandraOperation = ServiceFactory.getInstance(); - private static EncryptionService encryptionService = + private final LoggerUtil logger = new LoggerUtil(UserLookupDaoImpl.class); + private final Util.DbInfo userLookUp = Util.dbInfoMap.get(JsonKey.USER_LOOKUP); + private final CassandraOperation cassandraOperation = ServiceFactory.getInstance(); + private final EncryptionService encryptionService = org.sunbird.datasecurity.impl.ServiceFactory.getEncryptionServiceInstance(); private static UserLookupDao userLookUpDao = null; diff --git a/service/src/main/java/org/sunbird/dao/user/impl/UserOrgDaoImpl.java b/service/src/main/java/org/sunbird/dao/user/impl/UserOrgDaoImpl.java index d0e41297d..25e550132 100644 --- a/service/src/main/java/org/sunbird/dao/user/impl/UserOrgDaoImpl.java +++ b/service/src/main/java/org/sunbird/dao/user/impl/UserOrgDaoImpl.java @@ -16,9 +16,8 @@ import org.sunbird.response.Response; public final class UserOrgDaoImpl implements UserOrgDao { private static final String TABLE_NAME = JsonKey.USER_ORG; - private CassandraOperation cassandraOperation = ServiceFactory.getInstance(); - - private ObjectMapper mapper = new ObjectMapper(); + private final CassandraOperation cassandraOperation = ServiceFactory.getInstance(); + private final ObjectMapper mapper = new ObjectMapper(); private static UserOrgDaoImpl instance; diff --git a/service/src/main/java/org/sunbird/dao/user/impl/UserRoleDaoImpl.java b/service/src/main/java/org/sunbird/dao/user/impl/UserRoleDaoImpl.java index e32133e29..5575ade97 100644 --- a/service/src/main/java/org/sunbird/dao/user/impl/UserRoleDaoImpl.java +++ b/service/src/main/java/org/sunbird/dao/user/impl/UserRoleDaoImpl.java @@ -17,10 +17,10 @@ import scala.concurrent.Future; public final class UserRoleDaoImpl implements UserRoleDao { - private static LoggerUtil logger = new LoggerUtil(UserRoleDaoImpl.class); + private final LoggerUtil logger = new LoggerUtil(UserRoleDaoImpl.class); private static final String TABLE_NAME = JsonKey.USER_ROLES; - private CassandraOperation cassandraOperation = ServiceFactory.getInstance(); - private ElasticSearchService esService = EsClientFactory.getInstance(JsonKey.REST); + private final CassandraOperation cassandraOperation = ServiceFactory.getInstance(); + private final ElasticSearchService esService = EsClientFactory.getInstance(JsonKey.REST); private static UserRoleDaoImpl instance; diff --git a/service/src/main/java/org/sunbird/dao/user/impl/UserSelfDeclarationDaoImpl.java b/service/src/main/java/org/sunbird/dao/user/impl/UserSelfDeclarationDaoImpl.java index adf1af377..7c36410ea 100644 --- a/service/src/main/java/org/sunbird/dao/user/impl/UserSelfDeclarationDaoImpl.java +++ b/service/src/main/java/org/sunbird/dao/user/impl/UserSelfDeclarationDaoImpl.java @@ -1,6 +1,5 @@ package org.sunbird.dao.user.impl; -import com.fasterxml.jackson.databind.ObjectMapper; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Calendar; @@ -17,9 +16,7 @@ import org.sunbird.request.RequestContext; import org.sunbird.response.Response; public class UserSelfDeclarationDaoImpl implements UserSelfDeclarationDao { - private CassandraOperation cassandraOperation = ServiceFactory.getInstance(); - private ObjectMapper mapper = new ObjectMapper(); - + private final CassandraOperation cassandraOperation = ServiceFactory.getInstance(); private static UserSelfDeclarationDao userSelfDeclarationDao = null; public static UserSelfDeclarationDao getInstance() { @@ -95,9 +92,11 @@ public class UserSelfDeclarationDaoImpl implements UserSelfDeclarationDao { JsonKey.SUNBIRD, JsonKey.USER_DECLARATION_DB, properties, context); } - public Response updateUserSelfDeclaredFields( Map<String, Object> updateFieldsMap, - Map<String, Object> compositeKey, RequestContext context) { + public Response updateUserSelfDeclaredFields( + Map<String, Object> updateFieldsMap, + Map<String, Object> compositeKey, + RequestContext context) { return cassandraOperation.updateRecord( - JsonKey.SUNBIRD, JsonKey.USER_DECLARATION_DB, updateFieldsMap, compositeKey, context); + JsonKey.SUNBIRD, JsonKey.USER_DECLARATION_DB, updateFieldsMap, compositeKey, context); } } diff --git a/service/src/main/java/org/sunbird/dao/userconsent/impl/UserConsentDaoImpl.java b/service/src/main/java/org/sunbird/dao/userconsent/impl/UserConsentDaoImpl.java index 1844dd904..be7023bd2 100644 --- a/service/src/main/java/org/sunbird/dao/userconsent/impl/UserConsentDaoImpl.java +++ b/service/src/main/java/org/sunbird/dao/userconsent/impl/UserConsentDaoImpl.java @@ -10,8 +10,8 @@ import org.sunbird.request.RequestContext; import org.sunbird.response.Response; public class UserConsentDaoImpl implements UserConsentDao { - private static final String TABLE_NAME = "user_consent"; - private CassandraOperation cassandraOperation = ServiceFactory.getInstance(); + private final String TABLE_NAME = "user_consent"; + private final CassandraOperation cassandraOperation = ServiceFactory.getInstance(); private static UserConsentDao consentDao = null; @@ -31,7 +31,7 @@ public class UserConsentDaoImpl implements UserConsentDao { public List<Map<String, Object>> getConsent( Map<String, Object> consentReq, RequestContext context) { Response response = - cassandraOperation.getRecordsByProperties(JsonKey.SUNBIRD, TABLE_NAME, consentReq, context); + cassandraOperation.getRecordsByCompositeKey(JsonKey.SUNBIRD, TABLE_NAME, consentReq, context); return (List<Map<String, Object>>) response.get(JsonKey.RESPONSE); } } diff --git a/service/src/main/java/org/sunbird/model/user/User.java b/service/src/main/java/org/sunbird/model/user/User.java index bcff1541e..7ac81ff7e 100644 --- a/service/src/main/java/org/sunbird/model/user/User.java +++ b/service/src/main/java/org/sunbird/model/user/User.java @@ -62,6 +62,7 @@ public class User implements Serializable { private Map<String, String> allTncAccepted; private String profileUserType; private String profileLocation; + private String profileUserTypes; public Map<String, String> getAllTncAccepted() { return allTncAccepted; @@ -402,6 +403,23 @@ public class User implements Serializable { } } + public String getProfileUserTypes() { + return profileUserTypes; + } + + public void setProfileUserTypes(Object profileUserTypes) { + if (profileUserTypes != null && !(profileUserTypes instanceof String)) { + ObjectMapper objMap = new ObjectMapper(); + try { + this.profileUserTypes = objMap.writeValueAsString(profileUserTypes); + } catch (Exception e) { + this.profileUserTypes = ""; + } + } else { + this.profileUserTypes = (String) profileUserTypes; + } + } + public String getProfileLocation() { return profileLocation; } diff --git a/service/src/main/java/org/sunbird/service/feed/IFeedService.java b/service/src/main/java/org/sunbird/service/feed/IFeedService.java index 4dc8fbcb3..ecb286605 100644 --- a/service/src/main/java/org/sunbird/service/feed/IFeedService.java +++ b/service/src/main/java/org/sunbird/service/feed/IFeedService.java @@ -41,8 +41,10 @@ public interface IFeedService { /** * this method will be holding responsibility to delete the feed from DB and ES. * - * @param request + * @param id + * @param userId + * @param action * @param context */ - void delete(String id, String userId, String action, RequestContext context); + void delete(String id, String userId, String category, RequestContext context); } diff --git a/service/src/main/java/org/sunbird/service/feed/impl/FeedServiceImpl.java b/service/src/main/java/org/sunbird/service/feed/impl/FeedServiceImpl.java index 081a1a02d..4f8e0a878 100644 --- a/service/src/main/java/org/sunbird/service/feed/impl/FeedServiceImpl.java +++ b/service/src/main/java/org/sunbird/service/feed/impl/FeedServiceImpl.java @@ -2,12 +2,10 @@ package org.sunbird.service.feed.impl; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; + import java.sql.Timestamp; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Collections; -import java.util.List; -import java.util.Map; +import java.util.*; + import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang3.StringUtils; @@ -18,18 +16,20 @@ import org.sunbird.exception.ResponseCode; import org.sunbird.keys.JsonKey; import org.sunbird.logging.LoggerUtil; import org.sunbird.model.user.Feed; +import org.sunbird.request.Request; import org.sunbird.request.RequestContext; import org.sunbird.response.Response; import org.sunbird.service.feed.IFeedService; import org.sunbird.util.ProjectUtil; public class FeedServiceImpl implements IFeedService { - private static LoggerUtil logger = new LoggerUtil(FeedServiceImpl.class); + private final LoggerUtil logger = new LoggerUtil(FeedServiceImpl.class); private static IFeedDao iFeedDao = FeedDaoImpl.getInstance(); - private ObjectMapper mapper = new ObjectMapper(); + private final ObjectMapper mapper = new ObjectMapper(); @Override public Response insert(Feed feed, RequestContext context) { + logger.debug(context, "FeedServiceImpl:insert method called : "); Map<String, Object> dbMap = mapper.convertValue(feed, Map.class); String feedId = ProjectUtil.generateUniqueId(); @@ -50,10 +50,6 @@ public class FeedServiceImpl implements IFeedService { public Response update(Feed feed, RequestContext context) { logger.debug(context, "FeedServiceImpl:update method called : "); Map<String, Object> dbMap = mapper.convertValue(feed, Map.class); - String notification_service_base_url = System.getenv("notification_service_base_url"); - String NOTIFICATION_SERVICE_URL = - notification_service_base_url + "/private/v1/notification/feed/update"; - Response response = new Response(); try { if (MapUtils.isNotEmpty(feed.getData())) { dbMap.put(JsonKey.FEED_DATA, mapper.writeValueAsString(feed.getData())); @@ -77,24 +73,23 @@ public class FeedServiceImpl implements IFeedService { responseList = (List<Map<String, Object>>) dbResponse.getResult().get(JsonKey.RESPONSE); if (CollectionUtils.isNotEmpty(responseList)) { responseList.forEach( - s -> { - try { - String data = (String) s.get(JsonKey.FEED_DATA); - if (StringUtils.isNotBlank(data)) { - s.put( - JsonKey.FEED_DATA, - mapper.readValue(data, new TypeReference<Map<String, Object>>() {})); - } else { - s.put(JsonKey.FEED_DATA, Collections.emptyMap()); - } - feedList.add(mapper.convertValue(s, Feed.class)); - } catch (Exception ex) { - logger.error( - context, - "FeedServiceImpl:getRecordsByUserId :Exception occurred while mapping feed data.", - ex); - } - }); + s -> { + try { + String data = (String) s.get(JsonKey.FEED_DATA); + if (StringUtils.isNotBlank(data)) { + s.put( + JsonKey.FEED_DATA, + mapper.readValue(data, new TypeReference<Map<String, Object>>() {})); + } else { + s.put(JsonKey.FEED_DATA, Collections.emptyMap()); + } + feedList.add(mapper.convertValue(s, Feed.class)); + } catch (Exception ex) { + logger.error( + context, + "FeedServiceImpl:getRecordsByUserId :Exception occurred while mapping feed data.", + ex); + } }); } } return feedList; @@ -103,7 +98,16 @@ public class FeedServiceImpl implements IFeedService { @Override public void delete(String id, String userId, String category, RequestContext context) { logger.debug( - context, "FeedServiceImpl:delete method called for feedId : " + id + "user-id:" + userId); - iFeedDao.delete(id, userId, category, context); + context, "FeedServiceImpl:delete method called for feedId : " + id + "user-id:" + userId); + iFeedDao.delete(id, userId, category, context); + } + + private Map<String, String> getHeaders(RequestContext context) { + Map<String, String> headers = new HashMap<>(); + headers.put("Accept", "application/json"); + headers.put("Content-type", "application/json"); + headers.put("requestId", context.getReqId()); + ProjectUtil.setTraceIdInHeader(headers, context); + return headers; } } diff --git a/service/src/main/java/org/sunbird/service/location/LocationServiceImpl.java b/service/src/main/java/org/sunbird/service/location/LocationServiceImpl.java index 165fd1a93..ac351a817 100644 --- a/service/src/main/java/org/sunbird/service/location/LocationServiceImpl.java +++ b/service/src/main/java/org/sunbird/service/location/LocationServiceImpl.java @@ -18,7 +18,7 @@ import org.sunbird.util.ProjectUtil; public class LocationServiceImpl implements LocationService { public static LocationService locationService = null; - private LocationDao locationDao = LocationDaoFactory.getInstance(); + private final LocationDao locationDao = LocationDaoFactory.getInstance(); public static synchronized LocationService getInstance() { if (locationService == null) locationService = new LocationServiceImpl(); diff --git a/service/src/main/java/org/sunbird/service/notes/NotesService.java b/service/src/main/java/org/sunbird/service/notes/NotesService.java index d59dcdf6a..a4a89cf81 100644 --- a/service/src/main/java/org/sunbird/service/notes/NotesService.java +++ b/service/src/main/java/org/sunbird/service/notes/NotesService.java @@ -18,8 +18,8 @@ import org.sunbird.util.ProjectUtil; public class NotesService { - private NotesDao notesDao = NotesDaoImpl.getInstance(); - private UserService userService = UserServiceImpl.getInstance(); + private final NotesDao notesDao = NotesDaoImpl.getInstance(); + private final UserService userService = UserServiceImpl.getInstance(); public Response createNote(Request request) { Map<String, Object> req = request.getRequest(); diff --git a/service/src/main/java/org/sunbird/service/notification/NotificationService.java b/service/src/main/java/org/sunbird/service/notification/NotificationService.java index 0829d7815..91b20d585 100644 --- a/service/src/main/java/org/sunbird/service/notification/NotificationService.java +++ b/service/src/main/java/org/sunbird/service/notification/NotificationService.java @@ -30,9 +30,9 @@ import org.sunbird.util.ProjectUtil; public class NotificationService { - private static LoggerUtil logger = new LoggerUtil(NotificationService.class); - private UserService userService = UserServiceImpl.getInstance(); - private OrgService orgService = OrgServiceImpl.getInstance(); + private final LoggerUtil logger = new LoggerUtil(NotificationService.class); + private final UserService userService = UserServiceImpl.getInstance(); + private final OrgService orgService = OrgServiceImpl.getInstance(); public boolean processSMS( List<String> userIds, List<String> phones, String smsText, RequestContext requestContext) { @@ -146,14 +146,14 @@ public class NotificationService { logger.info( requestContext, "NotificationService:updateFirstNameAndOrgNameInEmailContext: Sending email to = " - + emails - + " emails"); + + emails.size() + + " email(s)"); } else { logger.info( requestContext, "NotificationService:updateFirstNameAndOrgNameInEmailContext: Sending email to = " + emails.size() - + " emails"); + + " email(s)"); } } diff --git a/service/src/main/java/org/sunbird/service/organisation/impl/OrgExternalServiceImpl.java b/service/src/main/java/org/sunbird/service/organisation/impl/OrgExternalServiceImpl.java index e5cb14d43..2acd104f2 100644 --- a/service/src/main/java/org/sunbird/service/organisation/impl/OrgExternalServiceImpl.java +++ b/service/src/main/java/org/sunbird/service/organisation/impl/OrgExternalServiceImpl.java @@ -12,8 +12,8 @@ import org.sunbird.response.Response; import org.sunbird.service.organisation.OrgExternalService; public class OrgExternalServiceImpl implements OrgExternalService { - private OrgExternalDao orgExtDao = new OrgExternalDaoImpl(); - private OrgDao orgDao = OrgDaoImpl.getInstance(); + private final OrgExternalDao orgExtDao = new OrgExternalDaoImpl(); + private final OrgDao orgDao = OrgDaoImpl.getInstance(); private static OrgExternalService orgExternalService; public static OrgExternalService getInstance() { diff --git a/service/src/main/java/org/sunbird/service/organisation/impl/OrgServiceImpl.java b/service/src/main/java/org/sunbird/service/organisation/impl/OrgServiceImpl.java index e1a9dca06..43eca2dc6 100644 --- a/service/src/main/java/org/sunbird/service/organisation/impl/OrgServiceImpl.java +++ b/service/src/main/java/org/sunbird/service/organisation/impl/OrgServiceImpl.java @@ -24,13 +24,13 @@ import scala.concurrent.Future; public class OrgServiceImpl implements OrgService { - private LoggerUtil logger = new LoggerUtil(this.getClass()); + private final LoggerUtil logger = new LoggerUtil(this.getClass()); private static Map<Integer, List<Integer>> orgStatusTransition = new HashMap<>(); - private ObjectMapper mapper = new ObjectMapper(); - private OrgDao orgDao = OrgDaoImpl.getInstance(); + private final ObjectMapper mapper = new ObjectMapper(); + private final OrgDao orgDao = OrgDaoImpl.getInstance(); private static OrgService orgService; - private OrgExternalService orgExternalService = new OrgExternalServiceImpl();; - private String contentType = "application/json"; + private final OrgExternalService orgExternalService = new OrgExternalServiceImpl();; + private final String contentType = "application/json"; public static OrgService getInstance() { if (orgService == null) { diff --git a/service/src/main/java/org/sunbird/service/otp/OTPService.java b/service/src/main/java/org/sunbird/service/otp/OTPService.java index bc7e8fe5f..b79773d7a 100644 --- a/service/src/main/java/org/sunbird/service/otp/OTPService.java +++ b/service/src/main/java/org/sunbird/service/otp/OTPService.java @@ -10,8 +10,8 @@ import org.sunbird.util.SMSTemplateProvider; public class OTPService { - private OTPDao otpDao = OTPDaoImpl.getInstance(); - private UserService userService = UserServiceImpl.getInstance(); + private final OTPDao otpDao = OTPDaoImpl.getInstance(); + private final UserService userService = UserServiceImpl.getInstance(); public Map<String, Object> getOTPDetails(String type, String key, RequestContext context) { return otpDao.getOTPDetails(type, key, context); diff --git a/service/src/main/java/org/sunbird/service/ratelimit/RateLimitService.java b/service/src/main/java/org/sunbird/service/ratelimit/RateLimitService.java index 0648ea094..a73247e2f 100644 --- a/service/src/main/java/org/sunbird/service/ratelimit/RateLimitService.java +++ b/service/src/main/java/org/sunbird/service/ratelimit/RateLimitService.java @@ -1,7 +1,7 @@ package org.sunbird.service.ratelimit; -import org.sunbird.util.ratelimit.RateLimiter; import org.sunbird.request.RequestContext; +import org.sunbird.util.ratelimit.RateLimiter; public interface RateLimitService { @@ -12,5 +12,5 @@ public interface RateLimitService { * @param rateLimiters List of rate limiters * @param context */ - void throttleByKey(String key, RateLimiter[] rateLimiters, RequestContext context); + void throttleByKey(String key, String type, RateLimiter[] rateLimiters, RequestContext context); } diff --git a/service/src/main/java/org/sunbird/service/ratelimit/RateLimitServiceImpl.java b/service/src/main/java/org/sunbird/service/ratelimit/RateLimitServiceImpl.java index fb681a8f6..9ba5ee70d 100644 --- a/service/src/main/java/org/sunbird/service/ratelimit/RateLimitServiceImpl.java +++ b/service/src/main/java/org/sunbird/service/ratelimit/RateLimitServiceImpl.java @@ -13,15 +13,15 @@ import org.sunbird.exception.ProjectCommonException; import org.sunbird.exception.ResponseCode; import org.sunbird.keys.JsonKey; import org.sunbird.logging.LoggerUtil; -import org.sunbird.util.ratelimit.RateLimit; -import org.sunbird.util.ratelimit.RateLimiter; import org.sunbird.request.RequestContext; import org.sunbird.util.ProjectUtil; +import org.sunbird.util.otp.OTPUtil; +import org.sunbird.util.ratelimit.RateLimit; +import org.sunbird.util.ratelimit.RateLimiter; public class RateLimitServiceImpl implements RateLimitService { - private static LoggerUtil logger = new LoggerUtil(RateLimitServiceImpl.class); - - private RateLimitDao rateLimitDao = RateLimitDaoImpl.getInstance(); + private final LoggerUtil logger = new LoggerUtil(RateLimitServiceImpl.class); + private final RateLimitDao rateLimitDao = RateLimitDaoImpl.getInstance(); public boolean isRateLimitOn() { return Boolean.TRUE @@ -30,7 +30,8 @@ public class RateLimitServiceImpl implements RateLimitService { } @Override - public void throttleByKey(String key, RateLimiter[] rateLimiters, RequestContext context) { + public void throttleByKey( + String key, String type, RateLimiter[] rateLimiters, RequestContext context) { if (!isRateLimitOn()) { logger.info(context, "RateLimitServiceImpl:throttleByKey: Rate limiter is disabled"); return; @@ -39,31 +40,32 @@ public class RateLimitServiceImpl implements RateLimitService { List<Map<String, Object>> ratesByKey = getRatesByKey(key, context); if (CollectionUtils.isNotEmpty(ratesByKey)) { - ratesByKey - .stream() - .forEach( - rate -> { - if (MapUtils.isNotEmpty(rate)) { - logger.info( - context, - "RateLimitServiceImpl:throttleByKey: key = " + key + " rate =" + rate); - RateLimit rateLimit = new RateLimit(key, rate); + ratesByKey.forEach( + rate -> { + if (MapUtils.isNotEmpty(rate)) { + logger.info( + context, + "RateLimitServiceImpl:throttleByKey: key = " + + OTPUtil.maskId(key, type) + + " rate =" + + rate); + RateLimit rateLimit = new RateLimit(key, rate); - if (rateLimit.getCount() >= rateLimit.getLimit()) { - logger.info( - context, - "RateLimitServiceImpl:throttleByKey: Rate limit threshold crossed for key = " - + key); - throw new ProjectCommonException( - ResponseCode.errorRateLimitExceeded.getErrorCode(), - ResponseCode.errorRateLimitExceeded.getErrorMessage(), - ResponseCode.TOO_MANY_REQUESTS.getResponseCode(), - rateLimit.getUnit().toLowerCase()); - } - rateLimit.incrementCount(); - entryByRate.put(rateLimit.getUnit(), rateLimit); - } - }); + if (rateLimit.getCount() >= rateLimit.getLimit()) { + logger.info( + context, + "RateLimitServiceImpl:throttleByKey: Rate limit threshold crossed for key = " + + OTPUtil.maskId(key, type)); + throw new ProjectCommonException( + ResponseCode.errorRateLimitExceeded.getErrorCode(), + ResponseCode.errorRateLimitExceeded.getErrorMessage(), + ResponseCode.TOO_MANY_REQUESTS.getResponseCode(), + rateLimit.getUnit().toLowerCase()); + } + rateLimit.incrementCount(); + entryByRate.put(rateLimit.getUnit(), rateLimit); + } + }); } Arrays.stream(rateLimiters) @@ -77,8 +79,8 @@ public class RateLimitServiceImpl implements RateLimitService { logger.info( context, "RateLimitServiceImpl:throttleByKey: Initialise rate limit for key = " - + key - + " rate =" + + OTPUtil.maskId(key, type) + + ", rate =" + rateLimit.getLimit()); entryByRate.put(rateLimiter.name(), rateLimit); } diff --git a/service/src/main/java/org/sunbird/service/role/RoleGroupService.java b/service/src/main/java/org/sunbird/service/role/RoleGroupService.java index c24211e15..d45d12d0f 100644 --- a/service/src/main/java/org/sunbird/service/role/RoleGroupService.java +++ b/service/src/main/java/org/sunbird/service/role/RoleGroupService.java @@ -13,7 +13,7 @@ import org.sunbird.request.RequestContext; public class RoleGroupService { - private static RoleGroupDao roleGroupDao = RoleGroupDaoImpl.getInstance(); + private final RoleGroupDao roleGroupDao = RoleGroupDaoImpl.getInstance(); public Map<String, Object> getRoleGroupMap(String roleName, RequestContext context) { Map<String, Object> response = new HashMap<>(); diff --git a/service/src/main/java/org/sunbird/service/role/RoleService.java b/service/src/main/java/org/sunbird/service/role/RoleService.java index 5ab9d6d6c..74e477093 100644 --- a/service/src/main/java/org/sunbird/service/role/RoleService.java +++ b/service/src/main/java/org/sunbird/service/role/RoleService.java @@ -19,8 +19,8 @@ import org.sunbird.util.DataCacheHandler; public class RoleService { - private RoleDao roleDao = RoleDaoImpl.getInstance(); - private RoleGroupService roleGroupService = new RoleGroupService(); + private final RoleDao roleDao = RoleDaoImpl.getInstance(); + private final RoleGroupService roleGroupService = new RoleGroupService(); public Response getUserRoles(RequestContext context) { Response response = new Response(); @@ -40,7 +40,7 @@ public class RoleService { Map<String, Object> actionGroupMap; for (String roleGroupId : roleGroupIdList) { - Map<String, Object> roleGroupMap = roleGroupService.getRoleGroupMap(roleGroupId,context); + Map<String, Object> roleGroupMap = roleGroupService.getRoleGroupMap(roleGroupId, context); actionGroupMap = new HashMap<>(); actionGroupMap.put(JsonKey.ID, roleGroupMap.get(JsonKey.ID)); diff --git a/service/src/main/java/org/sunbird/service/systemsettings/SystemSettingsService.java b/service/src/main/java/org/sunbird/service/systemsettings/SystemSettingsService.java index ba4411f6b..39c181733 100644 --- a/service/src/main/java/org/sunbird/service/systemsettings/SystemSettingsService.java +++ b/service/src/main/java/org/sunbird/service/systemsettings/SystemSettingsService.java @@ -1,6 +1,9 @@ package org.sunbird.service.systemsettings; import com.fasterxml.jackson.databind.ObjectMapper; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; import org.apache.commons.collections.MapUtils; import org.sunbird.dao.systemsettings.impl.SystemSettingDaoImpl; import org.sunbird.exception.ProjectCommonException; @@ -10,13 +13,9 @@ import org.sunbird.request.RequestContext; import org.sunbird.response.Response; import org.sunbird.util.DataCacheHandler; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - public class SystemSettingsService { - private SystemSettingDaoImpl systemSettingDaoImpl = new SystemSettingDaoImpl(); + private final SystemSettingDaoImpl systemSettingDaoImpl = new SystemSettingDaoImpl(); public SystemSetting getSystemSettingByKey(String key, RequestContext context) { String value = DataCacheHandler.getConfigSettings().get(key); @@ -27,9 +26,9 @@ public class SystemSettingsService { setting = systemSettingDaoImpl.readByField(key, context); if (null == setting) { throw new ProjectCommonException( - ResponseCode.resourceNotFound.getErrorCode(), - ResponseCode.resourceNotFound.getErrorMessage(), - ResponseCode.RESOURCE_NOT_FOUND.getResponseCode()); + ResponseCode.resourceNotFound.getErrorCode(), + ResponseCode.resourceNotFound.getErrorMessage(), + ResponseCode.RESOURCE_NOT_FOUND.getResponseCode()); } DataCacheHandler.getConfigSettings().put(key, setting.getValue()); } @@ -43,8 +42,7 @@ public class SystemSettingsService { allSystemSettings = new ArrayList<>(); for (Map.Entry<String, String> setting : systemSettings.entrySet()) { allSystemSettings.add( - new SystemSetting( - setting.getKey(), setting.getKey(), setting.getValue())); + new SystemSetting(setting.getKey(), setting.getKey(), setting.getValue())); } } else { allSystemSettings = systemSettingDaoImpl.readAll(context); @@ -57,5 +55,4 @@ public class SystemSettingsService { SystemSetting systemSetting = mapper.convertValue(request, SystemSetting.class); return systemSettingDaoImpl.write(systemSetting, context); } - } diff --git a/service/src/main/java/org/sunbird/service/tenantpreference/TenantPreferenceService.java b/service/src/main/java/org/sunbird/service/tenantpreference/TenantPreferenceService.java index 6b05f908b..abd0d0e06 100644 --- a/service/src/main/java/org/sunbird/service/tenantpreference/TenantPreferenceService.java +++ b/service/src/main/java/org/sunbird/service/tenantpreference/TenantPreferenceService.java @@ -2,6 +2,13 @@ package org.sunbird.service.tenantpreference; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; +import java.sql.Timestamp; +import java.text.MessageFormat; +import java.util.Calendar; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import org.apache.commons.collections.CollectionUtils; import org.sunbird.dao.tenantpreference.TenantPreferenceDao; import org.sunbird.dao.tenantpreference.impl.TenantPreferenceDaoImpl; @@ -12,50 +19,52 @@ import org.sunbird.logging.LoggerUtil; import org.sunbird.request.RequestContext; import org.sunbird.response.Response; -import java.sql.Timestamp; -import java.text.MessageFormat; -import java.util.Calendar; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - public class TenantPreferenceService { - private LoggerUtil logger = new LoggerUtil(TenantPreferenceService.class); - private ObjectMapper mapper = new ObjectMapper(); - private TenantPreferenceDao preferenceDao = TenantPreferenceDaoImpl.getInstance(); + private final LoggerUtil logger = new LoggerUtil(TenantPreferenceService.class); + private final ObjectMapper mapper = new ObjectMapper(); + private final TenantPreferenceDao preferenceDao = TenantPreferenceDaoImpl.getInstance(); public Map<String, Object> validateAndGetTenantPreferencesById( - String orgId, String key, String operationType, RequestContext context) { - List<Map<String, Object>> orgPreference = preferenceDao.getTenantPreferenceById(orgId, key, context); - if (JsonKey.CREATE.equalsIgnoreCase(operationType) && CollectionUtils.isNotEmpty(orgPreference)) { + String orgId, String key, String operationType, RequestContext context) { + List<Map<String, Object>> orgPreference = + preferenceDao.getTenantPreferenceById(orgId, key, context); + if (JsonKey.CREATE.equalsIgnoreCase(operationType) + && CollectionUtils.isNotEmpty(orgPreference)) { throw new ProjectCommonException( - ResponseCode.preferenceAlreadyExists.getErrorCode(), - MessageFormat.format(ResponseCode.preferenceAlreadyExists.getErrorMessage(), key, orgId), - ResponseCode.CLIENT_ERROR.getResponseCode()); - } else if (((JsonKey.GET.equalsIgnoreCase(operationType)) || (JsonKey.UPDATE.equalsIgnoreCase(operationType))) - && CollectionUtils.isEmpty(orgPreference)) { + ResponseCode.preferenceAlreadyExists.getErrorCode(), + MessageFormat.format(ResponseCode.preferenceAlreadyExists.getErrorMessage(), key, orgId), + ResponseCode.CLIENT_ERROR.getResponseCode()); + } else if (((JsonKey.GET.equalsIgnoreCase(operationType)) + || (JsonKey.UPDATE.equalsIgnoreCase(operationType))) + && CollectionUtils.isEmpty(orgPreference)) { throw new ProjectCommonException( - ResponseCode.preferenceNotFound.getErrorCode(), - MessageFormat.format(ResponseCode.preferenceNotFound.getErrorMessage(), key, orgId), - ResponseCode.RESOURCE_NOT_FOUND.getResponseCode()); + ResponseCode.preferenceNotFound.getErrorCode(), + MessageFormat.format(ResponseCode.preferenceNotFound.getErrorMessage(), key, orgId), + ResponseCode.RESOURCE_NOT_FOUND.getResponseCode()); } if (CollectionUtils.isNotEmpty(orgPreference)) { try { String data = (String) orgPreference.get(0).get(JsonKey.DATA); - Map<String, Object> map = mapper.readValue(data, new TypeReference<>() { - }); + Map<String, Object> map = mapper.readValue(data, new TypeReference<>() {}); orgPreference.get(0).put(JsonKey.DATA, map); return orgPreference.get(0); } catch (Exception e) { - logger.error(context, "TenantPreferenceService:Exception while reading preferences " + e.getMessage(), e); + logger.error( + context, + "TenantPreferenceService:Exception while reading preferences " + e.getMessage(), + e); } } return Collections.emptyMap(); } - public Response createPreference (String orgId, String key, Map<String,Object> data,String createdBy, RequestContext context) { + public Response createPreference( + String orgId, + String key, + Map<String, Object> data, + String createdBy, + RequestContext context) { try { Map<String, Object> dbMap = new HashMap<>(); dbMap.put(JsonKey.ORG_ID, orgId); @@ -63,14 +72,22 @@ public class TenantPreferenceService { dbMap.put(JsonKey.DATA, mapper.writeValueAsString(data)); dbMap.put(JsonKey.CREATED_BY, createdBy); dbMap.put(JsonKey.CREATED_ON, new Timestamp(Calendar.getInstance().getTimeInMillis())); - return preferenceDao.insertTenantPreference(dbMap,context); + return preferenceDao.insertTenantPreference(dbMap, context); } catch (Exception e) { - logger.error(context, "TenantPreferenceService:Exception while adding preferences " + e.getMessage(), e); + logger.error( + context, + "TenantPreferenceService:Exception while adding preferences " + e.getMessage(), + e); } return null; } - public Response updatePreference (String orgId, String key, Map<String,Object> data,String updatedBy, RequestContext context) { + public Response updatePreference( + String orgId, + String key, + Map<String, Object> data, + String updatedBy, + RequestContext context) { try { Map<String, Object> preference = new HashMap<>(); Map<String, Object> clusteringKeys = new HashMap<>(); @@ -78,13 +95,14 @@ public class TenantPreferenceService { clusteringKeys.put(JsonKey.ORG_ID, orgId); preference.put(JsonKey.DATA, mapper.writeValueAsString(data)); preference.put(JsonKey.UPDATED_BY, updatedBy); - preference.put( - JsonKey.UPDATED_ON, new Timestamp(Calendar.getInstance().getTimeInMillis())); + preference.put(JsonKey.UPDATED_ON, new Timestamp(Calendar.getInstance().getTimeInMillis())); return preferenceDao.updateTenantPreference(preference, clusteringKeys, context); } catch (Exception e) { - logger.error(context, "TenantPreferenceService:Exception while updating preferences " + e.getMessage(), e); + logger.error( + context, + "TenantPreferenceService:Exception while updating preferences " + e.getMessage(), + e); } return null; } - } diff --git a/service/src/main/java/org/sunbird/service/urlaction/UrlActionService.java b/service/src/main/java/org/sunbird/service/urlaction/UrlActionService.java index 499600555..a0c1e2eaf 100644 --- a/service/src/main/java/org/sunbird/service/urlaction/UrlActionService.java +++ b/service/src/main/java/org/sunbird/service/urlaction/UrlActionService.java @@ -1,19 +1,18 @@ package org.sunbird.service.urlaction; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import org.apache.commons.collections4.CollectionUtils; import org.sunbird.dao.urlaction.UrlActionDao; import org.sunbird.dao.urlaction.impl.UrlActionDaoImpl; import org.sunbird.keys.JsonKey; import org.sunbird.model.urlaction.UrlAction; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - public class UrlActionService { - private static UrlActionDao urlActionDao = UrlActionDaoImpl.getInstance(); + private static final UrlActionDao urlActionDao = UrlActionDaoImpl.getInstance(); public static Map<String, Object> getUrlActionMap(String urlId) { Map<String, Object> response = new HashMap<>(); diff --git a/service/src/main/java/org/sunbird/service/user/ResetPasswordService.java b/service/src/main/java/org/sunbird/service/user/ResetPasswordService.java index 89e6d8ca7..1b9bf748f 100644 --- a/service/src/main/java/org/sunbird/service/user/ResetPasswordService.java +++ b/service/src/main/java/org/sunbird/service/user/ResetPasswordService.java @@ -12,7 +12,7 @@ import org.sunbird.util.ProjectUtil; public class ResetPasswordService { - private LoggerUtil logger = new LoggerUtil(ResetPasswordService.class); + private final LoggerUtil logger = new LoggerUtil(ResetPasswordService.class); public String getUserRequiredActionLink( Map<String, Object> templateMap, boolean isUrlShortRequired, RequestContext context) { diff --git a/service/src/main/java/org/sunbird/service/user/ShadowUserMigrationService.java b/service/src/main/java/org/sunbird/service/user/ShadowUserMigrationService.java index 03d9d2072..435556aec 100644 --- a/service/src/main/java/org/sunbird/service/user/ShadowUserMigrationService.java +++ b/service/src/main/java/org/sunbird/service/user/ShadowUserMigrationService.java @@ -3,20 +3,20 @@ package org.sunbird.service.user; import com.fasterxml.jackson.databind.ObjectMapper; import java.sql.Timestamp; import java.util.*; -import org.sunbird.model.ClaimStatus; -import org.sunbird.model.ShadowUser; import org.sunbird.cassandra.CassandraOperation; import org.sunbird.helper.ServiceFactory; import org.sunbird.keys.JsonKey; import org.sunbird.logging.LoggerUtil; +import org.sunbird.model.ClaimStatus; +import org.sunbird.model.ShadowUser; import org.sunbird.request.RequestContext; import org.sunbird.response.Response; public class ShadowUserMigrationService { - private static LoggerUtil logger = new LoggerUtil(ShadowUserMigrationService.class); + private static final LoggerUtil logger = new LoggerUtil(ShadowUserMigrationService.class); - private static CassandraOperation cassandraOperation = ServiceFactory.getInstance(); - private static ObjectMapper mapper = new ObjectMapper(); + private static final CassandraOperation cassandraOperation = ServiceFactory.getInstance(); + private static final ObjectMapper mapper = new ObjectMapper(); /** * this method will search user in userids attribute in shadow_user table diff --git a/service/src/main/java/org/sunbird/service/user/UserProfileReadService.java b/service/src/main/java/org/sunbird/service/user/UserProfileReadService.java index 44fa7105b..5b45c4691 100644 --- a/service/src/main/java/org/sunbird/service/user/UserProfileReadService.java +++ b/service/src/main/java/org/sunbird/service/user/UserProfileReadService.java @@ -39,18 +39,18 @@ import org.sunbird.util.user.UserUtil; public class UserProfileReadService { - private LoggerUtil logger = new LoggerUtil(UserProfileReadService.class); - private UserService userService = UserServiceImpl.getInstance(); - private OrgService orgService = OrgServiceImpl.getInstance(); - private UserTncService tncService = new UserTncService(); - private UserRoleService userRoleService = UserRoleServiceImpl.getInstance(); - private UserOrgService userOrgService = UserOrgServiceImpl.getInstance(); - private LocationService locationService = LocationServiceImpl.getInstance(); - private UserSelfDeclarationService userSelfDeclarationService = + private final LoggerUtil logger = new LoggerUtil(UserProfileReadService.class); + private final UserService userService = UserServiceImpl.getInstance(); + private final OrgService orgService = OrgServiceImpl.getInstance(); + private final UserTncService tncService = new UserTncService(); + private final UserRoleService userRoleService = UserRoleServiceImpl.getInstance(); + private final UserOrgService userOrgService = UserOrgServiceImpl.getInstance(); + private final LocationService locationService = LocationServiceImpl.getInstance(); + private final UserSelfDeclarationService userSelfDeclarationService = UserSelfDeclarationServiceImpl.getInstance(); - private UserExternalIdentityService userExternalIdentityService = + private final UserExternalIdentityService userExternalIdentityService = new UserExternalIdentityServiceImpl(); - private ObjectMapper mapper = new ObjectMapper(); + private final ObjectMapper mapper = new ObjectMapper(); public Response getUserProfileData(Request actorMessage) { String id = (String) actorMessage.getRequest().get(JsonKey.USER_ID); @@ -73,31 +73,27 @@ public class UserProfileReadService { orgService.getOrgById( (String) result.get(JsonKey.ROOT_ORG_ID), actorMessage.getRequestContext()); if (MapUtils.isNotEmpty(rootOrg) - && actorMessage - .getOperation() - .equalsIgnoreCase(ActorOperations.GET_USER_PROFILE_V4.getValue())) { - Util.getOrgDefaultValue().keySet().stream().forEach(key -> rootOrg.remove(key)); + && (readVersion.equalsIgnoreCase(ActorOperations.GET_USER_PROFILE_V4.getValue()) + || readVersion.equalsIgnoreCase(ActorOperations.GET_USER_PROFILE_V5.getValue()))) { + Util.getOrgDefaultValue().keySet().forEach(rootOrg::remove); + Util.getUserDefaultValue().keySet().forEach(result::remove); + }else{ + result.putAll(Util.getUserDefaultValue()); } result.put(JsonKey.ROOT_ORG, rootOrg); - + Map<String, List<String>> userOrgRoles = null; List<Map<String, Object>> userRolesList = userRoleService.getUserRoles(userId, actorMessage.getRequestContext()); if (readVersion.equalsIgnoreCase(ActorOperations.GET_USER_PROFILE_V5.getValue())) { result.put(JsonKey.ROLES, userRolesList); } else { result.remove(JsonKey.ROLES); - } - Map<String, List<String>> userOrgRoles = null; - if (!readVersion.equalsIgnoreCase(ActorOperations.GET_USER_PROFILE_V5.getValue())) { userOrgRoles = getUserOrgRoles(userRolesList); } result.put( JsonKey.ORGANISATIONS, fetchUserOrgList( - (String) result.get(JsonKey.ID), - userOrgRoles, - actorMessage.getRequestContext(), - readVersion)); + (String) result.get(JsonKey.ID), userOrgRoles, actorMessage.getRequestContext())); String requestedById = (String) actorMessage.getContext().getOrDefault(JsonKey.REQUESTED_BY, ""); String managedForId = (String) actorMessage.getContext().getOrDefault(JsonKey.MANAGED_FOR, ""); @@ -147,11 +143,6 @@ public class UserProfileReadService { appendMinorFlag(result); // For Backward compatibility , In ES we were sending identifier field result.put(JsonKey.IDENTIFIER, userId); - if (actorMessage - .getOperation() - .equalsIgnoreCase(ActorOperations.GET_USER_PROFILE_V4.getValue())) { - Util.getUserDefaultValue().keySet().stream().forEach(key -> result.remove(key)); - } Response response = new Response(); response.put(JsonKey.RESPONSE, result); @@ -180,6 +171,19 @@ public class UserProfileReadService { } public void appendUserTypeAndLocation(Map<String, Object> result, Request actorMessage) { + List<Map<String, Object>> userTypeDetailsList = new ArrayList<>(); + try { + if (StringUtils.isNotEmpty((String) result.get(JsonKey.PROFILE_USERTYPES))) { + userTypeDetailsList = + mapper.readValue( + (String) result.get(JsonKey.PROFILE_USERTYPES), new TypeReference<>() {}); + } + } catch (Exception e) { + logger.error( + actorMessage.getRequestContext(), + "Exception because of mapper read value" + result.get(JsonKey.PROFILE_USERTYPES), + e); + } Map<String, Object> userTypeDetails = new HashMap<>(); try { if (StringUtils.isNotEmpty((String) result.get(JsonKey.PROFILE_USERTYPE))) { @@ -229,6 +233,7 @@ public class UserProfileReadService { result.remove(JsonKey.LOCATION_IDS); } result.put(JsonKey.PROFILE_USERTYPE, userTypeDetails); + result.put(JsonKey.PROFILE_USERTYPES, userTypeDetailsList); result.put(JsonKey.PROFILE_LOCATION, userLocList); } @@ -236,12 +241,12 @@ public class UserProfileReadService { String dob = (String) result.get(JsonKey.DOB); if (StringUtils.isNotEmpty(dob)) { int year = Integer.parseInt(dob.split("-")[0]); - LocalDate currentdate = LocalDate.now(); - int currentYear = currentdate.getYear(); + LocalDate currentDate = LocalDate.now(); + int currentYear = currentDate.getYear(); // reason for keeping 19 instead of 18 is, all dob's will be saving with 12-31 appending to // the year so 18 will be completed in the jan 1st // for eg: 2004-12-31 will become major after 2023 jan 1st. - boolean isMinor = (currentYear - year <= 19) ? true : false; + boolean isMinor = currentYear - year <= 19; result.put(JsonKey.IS_MINOR, isMinor); } } @@ -262,7 +267,7 @@ public class UserProfileReadService { if (StringUtils.isEmpty(managedToken)) { logger.debug( actorMessage.getRequestContext(), - "UserProfileReadActor: getUserProfileData: calling token generation for: " + userId); + "UserProfileReadService: getUserProfileData: calling token generation for: " + userId); List<Map<String, Object>> userList = new ArrayList<>(); userList.add(result); // Fetch encrypted token from admin utils @@ -280,24 +285,19 @@ public class UserProfileReadService { } private List<Map<String, Object>> fetchUserOrgList( - String userId, - Map<String, List<String>> userOrgRoles, - RequestContext requestContext, - String readVersion) { + String userId, Map<String, List<String>> userOrgRoles, RequestContext requestContext) { List<Map<String, Object>> usrOrgList = new ArrayList<>(); List<Map<String, Object>> userOrgList = userOrgService.getUserOrgListByUserId(userId, requestContext); for (Map<String, Object> userOrg : userOrgList) { - if (readVersion.equalsIgnoreCase(ActorOperations.GET_USER_PROFILE_V5.getValue())) { - userOrg.remove(JsonKey.ROLES); - } - String organisationId = (String) userOrg.get(JsonKey.ORGANISATION_ID); - if (MapUtils.isNotEmpty(userOrgRoles) && userOrgRoles.containsKey(organisationId)) { - userOrg.put(JsonKey.ROLES, userOrgRoles.get(organisationId)); - } Boolean isDeleted = (Boolean) userOrg.get(JsonKey.IS_DELETED); - if (null == isDeleted || (null != isDeleted && !isDeleted.booleanValue())) { + if (null == isDeleted || (!isDeleted.booleanValue())) { updateAssociationMechanism(userOrg); + userOrg.remove(JsonKey.ROLES); + String organisationId = (String) userOrg.get(JsonKey.ORGANISATION_ID); + if (MapUtils.isNotEmpty(userOrgRoles) && userOrgRoles.containsKey(organisationId)) { + userOrg.put(JsonKey.ROLES, userOrgRoles.get(organisationId)); + } usrOrgList.add(userOrg); } } @@ -324,7 +324,7 @@ public class UserProfileReadService { Map<String, Object> user = userService.getUserDetailsById(userId, context); // check whether user active or not Boolean isDeleted = (Boolean) user.get(JsonKey.IS_DELETED); - if (null != isDeleted && isDeleted.booleanValue()) { + if (null != isDeleted && isDeleted) { ProjectCommonException.throwClientErrorException(ResponseCode.userAccountlocked); } removeUserPrivateField(user); @@ -354,12 +354,11 @@ public class UserProfileReadService { } } - private Map<String, Object> removeUserPrivateField(Map<String, Object> responseMap) { + private void removeUserPrivateField(Map<String, Object> responseMap) { for (int i = 0; i < ProjectUtil.excludes.length; i++) { responseMap.remove(ProjectUtil.excludes[i]); } responseMap.remove(JsonKey.ADDRESS); - return responseMap; } public void updateTnc(Map<String, Object> userMap) { @@ -370,7 +369,7 @@ public class UserProfileReadService { } catch (Exception e) { logger.error( - "UserProfileReadActor:updateTncInfo: Exception occurred while getting system setting for" + "UserProfileReadService:updateTncInfo: Exception occurred while getting system setting for" + JsonKey.TNC_CONFIG + e.getMessage(), e); @@ -384,7 +383,7 @@ public class UserProfileReadService { Object tncUserAcceptedOn = userMap.get(JsonKey.TNC_ACCEPTED_ON); userMap.put(JsonKey.PROMPT_TNC, false); String url = (String) ((Map) tncConfigMap.get(tncLatestVersion)).get(JsonKey.URL); - logger.info("UserProfileReadActor:updateTncInfo: url = " + url); + logger.debug("UserProfileReadService:updateTncInfo: url = " + url); userMap.put(JsonKey.TNC_LATEST_VERSION_URL, url); if ((StringUtils.isEmpty(tncUserAcceptedVersion) || !tncUserAcceptedVersion.equalsIgnoreCase(tncLatestVersion) @@ -394,7 +393,7 @@ public class UserProfileReadService { } } catch (Exception e) { logger.error( - "UserProfileReadActor:updateTncInfo: Exception occurred with error message = " + "UserProfileReadService:updateTncInfo: Exception occurred with error message = " + e.getMessage(), e); } @@ -427,16 +426,14 @@ public class UserProfileReadService { && StringUtils.isNotBlank(rootOrgId) && StringUtils.isNotBlank(dbResExternalIds.get(0).get(JsonKey.PROVIDER)) && ((dbResExternalIds.get(0).get(JsonKey.PROVIDER)).equalsIgnoreCase(rootOrgId))) { - dbResExternalIds - .stream() - .forEach( - s -> { - if (s.get(JsonKey.PROVIDER) != null - && s.get(JsonKey.PROVIDER).equals(s.get(JsonKey.ID_TYPE))) { - s.put(JsonKey.ID_TYPE, provider); - } - s.put(JsonKey.PROVIDER, provider); - }); + dbResExternalIds.forEach( + s -> { + if (s.get(JsonKey.PROVIDER) != null + && s.get(JsonKey.PROVIDER).equals(s.get(JsonKey.ID_TYPE))) { + s.put(JsonKey.ID_TYPE, provider); + } + s.put(JsonKey.PROVIDER, provider); + }); } else { UserUtil.updateExternalIdsWithProvider(dbResExternalIds, context); @@ -450,12 +447,12 @@ public class UserProfileReadService { if (fields.contains(JsonKey.TOPIC)) { result.put(JsonKey.TOPICS, new HashSet<>()); } - if (fields.contains(JsonKey.ORGANISATIONS)) { - updateUserOrgInfo((List) result.get(JsonKey.ORGANISATIONS), context); - } if (fields.contains(JsonKey.ROLES)) { result.put(JsonKey.ROLE_LIST, DataCacheHandler.getUserReadRoleList()); } + if (fields.contains(JsonKey.ORGANISATIONS)) { + updateUserOrgInfo((List) result.get(JsonKey.ORGANISATIONS), context); + } if (fields.contains(JsonKey.LOCATIONS)) { List<Map<String, String>> userLocList = (List<Map<String, String>>) result.get(JsonKey.PROFILE_LOCATION); diff --git a/service/src/main/java/org/sunbird/service/user/impl/SSOUserServiceImpl.java b/service/src/main/java/org/sunbird/service/user/impl/SSOUserServiceImpl.java index b461674b0..c13e79cf5 100644 --- a/service/src/main/java/org/sunbird/service/user/impl/SSOUserServiceImpl.java +++ b/service/src/main/java/org/sunbird/service/user/impl/SSOUserServiceImpl.java @@ -2,7 +2,9 @@ package org.sunbird.service.user.impl; import com.fasterxml.jackson.databind.ObjectMapper; import java.text.MessageFormat; +import java.util.ArrayList; import java.util.HashMap; +import java.util.List; import java.util.Map; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang3.StringUtils; @@ -32,14 +34,14 @@ import org.sunbird.util.user.UserUtil; public class SSOUserServiceImpl implements SSOUserService { - private static LoggerUtil logger = new LoggerUtil(SSOUserServiceImpl.class); + private final LoggerUtil logger = new LoggerUtil(SSOUserServiceImpl.class); private static SSOUserService ssoUserService = null; - private OrganisationClient organisationClient = OrganisationClientImpl.getInstance(); - private OrgExternalService orgExternalService = OrgExternalServiceImpl.getInstance(); - private UserService userService = UserServiceImpl.getInstance(); - private UserLookupService userLookupService = UserLookUpServiceImpl.getInstance(); - private OrgService orgService = OrgServiceImpl.getInstance(); + private final OrganisationClient organisationClient = OrganisationClientImpl.getInstance(); + private final OrgExternalService orgExternalService = OrgExternalServiceImpl.getInstance(); + private final UserService userService = UserServiceImpl.getInstance(); + private final UserLookupService userLookupService = UserLookUpServiceImpl.getInstance(); + private final OrgService orgService = OrgServiceImpl.getInstance(); public static SSOUserService getInstance() { if (ssoUserService == null) { @@ -92,7 +94,7 @@ public class SSOUserServiceImpl implements SSOUserService { Map<String, Object> requestMap, Map<String, Object> userMap, Request request) { Response response = null; boolean isPasswordUpdated = false; - Map<String, Object> userLookUpData = new HashMap<>(requestMap); + Map<String, Object> userLookUpData = new HashMap<>(userMap); try { response = userService.createUser(requestMap, request.getRequestContext()); userLookupService.insertRecords(userLookUpData, request.getRequestContext()); @@ -218,6 +220,11 @@ public class SSOUserServiceImpl implements SSOUserService { } try { ObjectMapper mapper = new ObjectMapper(); + if(!userMap.containsKey(JsonKey.PROFILE_USERTYPES)){ + List<Map<String, String>> userTypeAndSubTypes = new ArrayList<>(); + userTypeAndSubTypes.add(userTypeAndSubType); + userMap.put(JsonKey.PROFILE_USERTYPES, mapper.writeValueAsString(userTypeAndSubTypes)); + } userMap.put(JsonKey.PROFILE_USERTYPE, mapper.writeValueAsString(userTypeAndSubType)); } catch (Exception ex) { logger.error(requestContext, "Exception occurred while mapping", ex); diff --git a/service/src/main/java/org/sunbird/service/user/impl/TenantMigrationServiceImpl.java b/service/src/main/java/org/sunbird/service/user/impl/TenantMigrationServiceImpl.java index 320e5677f..81953b0a2 100644 --- a/service/src/main/java/org/sunbird/service/user/impl/TenantMigrationServiceImpl.java +++ b/service/src/main/java/org/sunbird/service/user/impl/TenantMigrationServiceImpl.java @@ -31,10 +31,10 @@ import org.sunbird.util.StringFormatter; public class TenantMigrationServiceImpl implements TenantMigrationService { - public LoggerUtil logger = new LoggerUtil(this.getClass()); - private UserService userService = UserServiceImpl.getInstance(); + public final LoggerUtil logger = new LoggerUtil(this.getClass()); + private final UserService userService = UserServiceImpl.getInstance(); private static TenantMigrationService tenantMigrationService = null; - private UserOrgService userOrgService = UserOrgServiceImpl.getInstance(); + private final UserOrgService userOrgService = UserOrgServiceImpl.getInstance(); public static TenantMigrationService getInstance() { if (tenantMigrationService == null) { diff --git a/service/src/main/java/org/sunbird/service/user/impl/UserExternalIdentityServiceImpl.java b/service/src/main/java/org/sunbird/service/user/impl/UserExternalIdentityServiceImpl.java index e39497210..84068c473 100644 --- a/service/src/main/java/org/sunbird/service/user/impl/UserExternalIdentityServiceImpl.java +++ b/service/src/main/java/org/sunbird/service/user/impl/UserExternalIdentityServiceImpl.java @@ -18,9 +18,8 @@ import org.sunbird.util.user.UserExternalIdentityAdapter; import org.sunbird.util.user.UserUtil; public class UserExternalIdentityServiceImpl implements UserExternalIdentityService { - private static UserExternalIdentityDao userExternalIdentityDao = - new UserExternalIdentityDaoImpl(); - private LocationService locationService = LocationServiceImpl.getInstance(); + private final UserExternalIdentityDao userExternalIdentityDao = new UserExternalIdentityDaoImpl(); + private final LocationService locationService = LocationServiceImpl.getInstance(); @Override public List<Map<String, Object>> getSelfDeclaredDetails( diff --git a/service/src/main/java/org/sunbird/service/user/impl/UserLookUpServiceImpl.java b/service/src/main/java/org/sunbird/service/user/impl/UserLookUpServiceImpl.java index c85777559..89c815202 100644 --- a/service/src/main/java/org/sunbird/service/user/impl/UserLookUpServiceImpl.java +++ b/service/src/main/java/org/sunbird/service/user/impl/UserLookUpServiceImpl.java @@ -22,8 +22,8 @@ import org.sunbird.util.ProjectUtil; public class UserLookUpServiceImpl implements UserLookupService { - private static LoggerUtil logger = new LoggerUtil(UserLookUpServiceImpl.class); - private static UserLookupDao userLookupDao = UserLookupDaoImpl.getInstance(); + private final LoggerUtil logger = new LoggerUtil(UserLookUpServiceImpl.class); + private final UserLookupDao userLookupDao = UserLookupDaoImpl.getInstance(); private static UserLookupService userLookupService = null; public static UserLookupService getInstance() { diff --git a/service/src/main/java/org/sunbird/service/user/impl/UserOrgServiceImpl.java b/service/src/main/java/org/sunbird/service/user/impl/UserOrgServiceImpl.java index 97a09f4f4..9698d967c 100644 --- a/service/src/main/java/org/sunbird/service/user/impl/UserOrgServiceImpl.java +++ b/service/src/main/java/org/sunbird/service/user/impl/UserOrgServiceImpl.java @@ -17,8 +17,8 @@ import org.sunbird.util.ProjectUtil; public class UserOrgServiceImpl implements UserOrgService { private static UserOrgServiceImpl userOrgService = null; - private static LoggerUtil logger = new LoggerUtil(UserOrgServiceImpl.class); - private UserOrgDao userOrgDao = UserOrgDaoImpl.getInstance(); + private final LoggerUtil logger = new LoggerUtil(UserOrgServiceImpl.class); + private final UserOrgDao userOrgDao = UserOrgDaoImpl.getInstance(); public static UserOrgService getInstance() { if (userOrgService == null) { diff --git a/service/src/main/java/org/sunbird/service/user/impl/UserRoleServiceImpl.java b/service/src/main/java/org/sunbird/service/user/impl/UserRoleServiceImpl.java index 9fa8cf78f..9d2c79b91 100644 --- a/service/src/main/java/org/sunbird/service/user/impl/UserRoleServiceImpl.java +++ b/service/src/main/java/org/sunbird/service/user/impl/UserRoleServiceImpl.java @@ -23,10 +23,10 @@ import org.sunbird.service.user.UserRoleService; import org.sunbird.util.ProjectUtil; public class UserRoleServiceImpl implements UserRoleService { - private LoggerUtil logger = new LoggerUtil(UserRoleServiceImpl.class); + private final LoggerUtil logger = new LoggerUtil(UserRoleServiceImpl.class); private static UserRoleService userRoleService = null; - private ObjectMapper mapper = new ObjectMapper(); - private UserRoleDao userRoleDao = UserRoleDaoImpl.getInstance(); + private final ObjectMapper mapper = new ObjectMapper(); + private final UserRoleDao userRoleDao = UserRoleDaoImpl.getInstance(); public static UserRoleService getInstance() { if (userRoleService == null) { diff --git a/service/src/main/java/org/sunbird/service/user/impl/UserSelfDeclarationServiceImpl.java b/service/src/main/java/org/sunbird/service/user/impl/UserSelfDeclarationServiceImpl.java index 7b8608fe4..81e44baea 100644 --- a/service/src/main/java/org/sunbird/service/user/impl/UserSelfDeclarationServiceImpl.java +++ b/service/src/main/java/org/sunbird/service/user/impl/UserSelfDeclarationServiceImpl.java @@ -20,10 +20,10 @@ import org.sunbird.util.user.UserUtil; public class UserSelfDeclarationServiceImpl implements UserSelfDeclarationService { - private LoggerUtil logger = new LoggerUtil(UserSelfDeclarationServiceImpl.class); + private final LoggerUtil logger = new LoggerUtil(UserSelfDeclarationServiceImpl.class); private static UserSelfDeclarationService selfDeclarationService = null; - private ObjectMapper mapper = new ObjectMapper(); - private static UserSelfDeclarationDao userSelfDeclarationDao = + private final ObjectMapper mapper = new ObjectMapper(); + private final UserSelfDeclarationDao userSelfDeclarationDao = UserSelfDeclarationDaoImpl.getInstance(); public static UserSelfDeclarationService getInstance() { @@ -116,10 +116,15 @@ public class UserSelfDeclarationServiceImpl implements UserSelfDeclarationServic public void updateSelfDeclaration(UserDeclareEntity userDeclareEntity, RequestContext context) { userSelfDeclarationDao.upsertUserSelfDeclaredFields(userDeclareEntity, context); } - public Response updateSelfDeclaration(Map<String, Object> updateFieldsMap, - Map<String, Object> compositeKey, RequestContext context) { - return userSelfDeclarationDao.updateUserSelfDeclaredFields(updateFieldsMap, compositeKey, context); + + public Response updateSelfDeclaration( + Map<String, Object> updateFieldsMap, + Map<String, Object> compositeKey, + RequestContext context) { + return userSelfDeclarationDao.updateUserSelfDeclaredFields( + updateFieldsMap, compositeKey, context); } + @Override public List<Map<String, Object>> fetchUserDeclarations(String userId, RequestContext context) { List<Map<String, Object>> finalRes = new ArrayList<>(); diff --git a/service/src/main/java/org/sunbird/service/user/impl/UserServiceImpl.java b/service/src/main/java/org/sunbird/service/user/impl/UserServiceImpl.java index 3e27b3ed7..5c46acfe7 100644 --- a/service/src/main/java/org/sunbird/service/user/impl/UserServiceImpl.java +++ b/service/src/main/java/org/sunbird/service/user/impl/UserServiceImpl.java @@ -43,18 +43,17 @@ import scala.concurrent.duration.Duration; public class UserServiceImpl implements UserService { - private LoggerUtil logger = new LoggerUtil(UserServiceImpl.class); - private EncryptionService encryptionService = + private final LoggerUtil logger = new LoggerUtil(UserServiceImpl.class); + private final EncryptionService encryptionService = org.sunbird.datasecurity.impl.ServiceFactory.getEncryptionServiceInstance(); - private UserDao userDao = UserDaoImpl.getInstance(); + private final UserDao userDao = UserDaoImpl.getInstance(); private static UserService userService = null; - private UserLookupDao userLookupDao = UserLookupDaoImpl.getInstance(); - private UserOrgService userOrgService = UserOrgServiceImpl.getInstance(); - private OrgService orgService = OrgServiceImpl.getInstance(); - private UserTncService tncService = new UserTncService(); - private UserRoleService userRoleService = UserRoleServiceImpl.getInstance(); - private static final int GENERATE_USERNAME_COUNT = 10; - private static ObjectMapper mapper = new ObjectMapper(); + private final UserLookupDao userLookupDao = UserLookupDaoImpl.getInstance(); + private final UserOrgService userOrgService = UserOrgServiceImpl.getInstance(); + private final OrgService orgService = OrgServiceImpl.getInstance(); + private final UserTncService tncService = new UserTncService(); + private final UserRoleService userRoleService = UserRoleServiceImpl.getInstance(); + private final ObjectMapper mapper = new ObjectMapper(); public static UserService getInstance() { if (userService == null) { @@ -173,6 +172,7 @@ public class UserServiceImpl implements UserService { HashSet<String> userNameSet = new HashSet<>(); int totalUserNameGenerated = 0; String nameLowercase = name.toLowerCase().replaceAll("\\-+", ""); + int GENERATE_USERNAME_COUNT = 10; while (totalUserNameGenerated < GENERATE_USERNAME_COUNT) { String userNameSuffix = RandomStringUtils.randomAlphanumeric(numOfCharsToAppend).toLowerCase(); @@ -467,6 +467,17 @@ public class UserServiceImpl implements UserService { } } userDetails.put(JsonKey.PROFILE_USERTYPE, userTypeDetail); + List<Map<String, Object>> userTypeDetails = new ArrayList<>(); + String profUserTypes = (String) userDetails.get(JsonKey.PROFILE_USERTYPES); + if (StringUtils.isNotBlank(profUserTypes)) { + try { + userTypeDetails = mapper.readValue(profUserTypes, List.class); + } catch (Exception e) { + logger.error( + context, "Exception while converting profileUserTypes to List<Map<String, Object>>.", e); + } + } + userDetails.put(JsonKey.PROFILE_USERTYPES, userTypeDetails); List<Map<String, Object>> userRoleList = userRoleService.getUserRoles(userId, context); userDetails.put(JsonKey.ROLES, userRoleList); } else { diff --git a/service/src/main/java/org/sunbird/service/userconsent/UserConsentService.java b/service/src/main/java/org/sunbird/service/userconsent/UserConsentService.java index 53471c230..60b64d4e2 100644 --- a/service/src/main/java/org/sunbird/service/userconsent/UserConsentService.java +++ b/service/src/main/java/org/sunbird/service/userconsent/UserConsentService.java @@ -9,6 +9,6 @@ import org.sunbird.response.Response; public interface UserConsentService { Response updateConsent(Map<String, Object> consent, RequestContext context); - + void validateConsumerId(String consumerId, RequestContext context); List<Map<String, Object>> getConsent(Request consentReq); } diff --git a/service/src/main/java/org/sunbird/service/userconsent/impl/UserConsentServiceImpl.java b/service/src/main/java/org/sunbird/service/userconsent/impl/UserConsentServiceImpl.java index ce09f4199..72ebde57b 100644 --- a/service/src/main/java/org/sunbird/service/userconsent/impl/UserConsentServiceImpl.java +++ b/service/src/main/java/org/sunbird/service/userconsent/impl/UserConsentServiceImpl.java @@ -24,9 +24,9 @@ import org.sunbird.util.user.DateUtil; public class UserConsentServiceImpl implements UserConsentService { - private static LoggerUtil logger = new LoggerUtil(UserConsentServiceImpl.class); - private static UserConsentDao userConsentDao = UserConsentDaoImpl.getInstance(); - private static OrgDao orgDao = OrgDaoImpl.getInstance(); + private final LoggerUtil logger = new LoggerUtil(UserConsentServiceImpl.class); + private final UserConsentDao userConsentDao = UserConsentDaoImpl.getInstance(); + private final OrgDao orgDao = OrgDaoImpl.getInstance(); private static UserConsentService consentService = null; @@ -81,7 +81,6 @@ public class UserConsentServiceImpl implements UserConsentService { String objectId = (String) consent.get(JsonKey.CONSENT_OBJECTID); String objectType = (String) consent.getOrDefault(JsonKey.CONSENT_OBJECTTYPE, ""); String status = (String) consent.get(JsonKey.STATUS); - validateConsumerId(consumerId, context); String key = getKey(userId, consumerId, objectId); Map<String, Object> consentReq = new HashMap<String, Object>(); @@ -111,7 +110,7 @@ public class UserConsentServiceImpl implements UserConsentService { return consentReq; } - private void validateConsumerId(String consumerId, RequestContext context) { + public void validateConsumerId(String consumerId, RequestContext context) { Map<String, Object> org = null; try { org = orgDao.getOrgById(consumerId, context); diff --git a/service/src/main/java/org/sunbird/util/AdminUtilHandler.java b/service/src/main/java/org/sunbird/util/AdminUtilHandler.java index cf3659321..f976ed2dd 100644 --- a/service/src/main/java/org/sunbird/util/AdminUtilHandler.java +++ b/service/src/main/java/org/sunbird/util/AdminUtilHandler.java @@ -19,7 +19,7 @@ import org.sunbird.model.adminutil.Params; import org.sunbird.request.RequestContext; public class AdminUtilHandler { - private static LoggerUtil logger = new LoggerUtil(AdminUtilHandler.class); + private static final LoggerUtil logger = new LoggerUtil(AdminUtilHandler.class); /** * Prepare payload for admin utils diff --git a/service/src/main/java/org/sunbird/util/FormApiUtilHandler.java b/service/src/main/java/org/sunbird/util/FormApiUtilHandler.java index 0628daeb1..5b242a25a 100644 --- a/service/src/main/java/org/sunbird/util/FormApiUtilHandler.java +++ b/service/src/main/java/org/sunbird/util/FormApiUtilHandler.java @@ -17,7 +17,7 @@ import org.sunbird.request.RequestContext; public class FormApiUtilHandler { - private static LoggerUtil logger = new LoggerUtil(FormApiUtilHandler.class); + private static final LoggerUtil logger = new LoggerUtil(FormApiUtilHandler.class); /** * Prepare payload for Form Api Config utils diff --git a/service/src/main/java/org/sunbird/util/SMSTemplateProvider.java b/service/src/main/java/org/sunbird/util/SMSTemplateProvider.java index 3fd502aba..77c3d0ee3 100644 --- a/service/src/main/java/org/sunbird/util/SMSTemplateProvider.java +++ b/service/src/main/java/org/sunbird/util/SMSTemplateProvider.java @@ -15,10 +15,10 @@ import org.sunbird.logging.LoggerUtil; import org.sunbird.request.RequestContext; public class SMSTemplateProvider { - private static LoggerUtil logger = new LoggerUtil(SMSTemplateProvider.class); + private static final LoggerUtil logger = new LoggerUtil(SMSTemplateProvider.class); public static final String SMS_PROVIDER = ProjectUtil.getConfigValue(JsonKey.SMS_GATEWAY_PROVIDER); - private static EmailTemplateDao emailTemplateDao = EmailTemplateDaoImpl.getInstance(); + private static final EmailTemplateDao emailTemplateDao = EmailTemplateDaoImpl.getInstance(); private SMSTemplateProvider() {} diff --git a/service/src/main/java/org/sunbird/util/SearchTelemetryUtil.java b/service/src/main/java/org/sunbird/util/SearchTelemetryUtil.java deleted file mode 100644 index 691c42897..000000000 --- a/service/src/main/java/org/sunbird/util/SearchTelemetryUtil.java +++ /dev/null @@ -1,62 +0,0 @@ -/* -package org.sunbird.learner.util; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.models.util.ProjectLogger; -import org.sunbird.common.models.util.PropertiesCache; -import org.sunbird.common.request.Request; -import org.sunbird.dto.SearchDTO; -import org.sunbird.telemetry.util.TelemetryUtil; -import org.sunbird.telemetry.util.TelemetryWriter; - -public class SearchTelemetryUtil { - private SearchTelemetryUtil() {} - - public static void generateSearchTelemetryEvent( - SearchDTO searchDto, String[] types, Map<String, Object> result) { - try { - Map<String, Object> telemetryContext = TelemetryUtil.getTelemetryContext(); - Map<String, Object> params = new HashMap<>(); - params.put(JsonKey.QUERY, searchDto.getQuery()); - params.put(JsonKey.FILTERS, searchDto.getAdditionalProperties().get(JsonKey.FILTERS)); - params.put(JsonKey.SORT, searchDto.getSortBy()); - params.put(JsonKey.TOPN, generateTopNResult(result)); - params.put(JsonKey.SIZE, result.get(JsonKey.COUNT)); - params.put(JsonKey.TYPE, String.join(",", types)); - - Request request = new Request(); - request.setRequest(telemetryRequestForSearch(telemetryContext, params)); - TelemetryWriter.write(request); - } catch (Exception e) { - ProjectLogger.log(e.getMessage(), e); - } - } - - private static List<Map<String, Object>> generateTopNResult(Map<String, Object> result) { - List<Map<String, Object>> dataMapList = (List<Map<String, Object>>) result.get(JsonKey.CONTENT); - Integer topN = - Integer.parseInt(PropertiesCache.getInstance().getProperty(JsonKey.SEARCH_TOP_N)); - int count = Math.min(topN, dataMapList.size()); - List<Map<String, Object>> list = new ArrayList<>(); - for (int i = 0; i < count; i++) { - Map<String, Object> m = new HashMap<>(); - m.put(JsonKey.ID, dataMapList.get(i).get(JsonKey.ID)); - list.add(m); - } - return list; - } - - private static Map<String, Object> telemetryRequestForSearch( - Map<String, Object> telemetryContext, Map<String, Object> params) { - Map<String, Object> map = new HashMap<>(); - map.put(JsonKey.CONTEXT, telemetryContext); - map.put(JsonKey.PARAMS, params); - map.put(JsonKey.TELEMETRY_EVENT_TYPE, "SEARCH"); - return map; - } -} -*/ diff --git a/service/src/main/java/org/sunbird/util/UserUtility.java b/service/src/main/java/org/sunbird/util/UserUtility.java index 2e2711a23..e55278107 100644 --- a/service/src/main/java/org/sunbird/util/UserUtility.java +++ b/service/src/main/java/org/sunbird/util/UserUtility.java @@ -18,7 +18,7 @@ import org.sunbird.logging.LoggerUtil; * @author Amit Kumar */ public final class UserUtility { - private static LoggerUtil logger = new LoggerUtil(UserUtility.class); + private static final LoggerUtil logger = new LoggerUtil(UserUtility.class); private static List<String> userKeyToEncrypt; private static List<String> userKeyToDecrypt; diff --git a/service/src/main/java/org/sunbird/util/Util.java b/service/src/main/java/org/sunbird/util/Util.java index e735fdde8..b36912d85 100644 --- a/service/src/main/java/org/sunbird/util/Util.java +++ b/service/src/main/java/org/sunbird/util/Util.java @@ -21,12 +21,12 @@ public final class Util { public static final Map<String, DbInfo> dbInfoMap = new HashMap<>(); private static final String KEY_SPACE_NAME = "sunbird"; - private static CassandraOperation cassandraOperation = ServiceFactory.getInstance(); - private static EncryptionService encryptionService = + private static final CassandraOperation cassandraOperation = ServiceFactory.getInstance(); + private static final EncryptionService encryptionService = org.sunbird.datasecurity.impl.ServiceFactory.getEncryptionServiceInstance(); - private static DecryptionService decService = + private static final DecryptionService decService = org.sunbird.datasecurity.impl.ServiceFactory.getDecryptionServiceInstance(); - private static DataMaskingService maskingService = + private static final DataMaskingService maskingService = org.sunbird.datasecurity.impl.ServiceFactory.getMaskingServiceInstance(); static { diff --git a/service/src/main/java/org/sunbird/util/bulkupload/UserUploadUtil.java b/service/src/main/java/org/sunbird/util/bulkupload/UserUploadUtil.java deleted file mode 100644 index cb8a58ba4..000000000 --- a/service/src/main/java/org/sunbird/util/bulkupload/UserUploadUtil.java +++ /dev/null @@ -1,111 +0,0 @@ -package org.sunbird.util.bulkupload; - -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.ObjectMapper; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.WeakHashMap; -import org.sunbird.cassandra.CassandraOperation; -import org.sunbird.datasecurity.DecryptionService; -import org.sunbird.helper.ServiceFactory; -import org.sunbird.keys.JsonKey; -import org.sunbird.logging.LoggerUtil; -import org.sunbird.model.SelfDeclaredUser; -import org.sunbird.model.bulkupload.BulkMigrationUser; -import org.sunbird.request.RequestContext; -import org.sunbird.response.Response; -import org.sunbird.util.Util; - -public class UserUploadUtil { - private static LoggerUtil logger = new LoggerUtil(UserUploadUtil.class); - - public static CassandraOperation cassandraOperation = ServiceFactory.getInstance(); - public static Util.DbInfo bulkUploadDbInfo = Util.dbInfoMap.get(JsonKey.BULK_OP_DB); - public static ObjectMapper mapper = new ObjectMapper(); - public static DecryptionService decryptionService = - org.sunbird.datasecurity.impl.ServiceFactory.getDecryptionServiceInstance(); - - public static Map<String, Object> getFullRecordFromProcessId( - String processId, RequestContext context) { - - int FIRST_RECORD = 0; - Response response = - cassandraOperation.getRecordById( - bulkUploadDbInfo.getKeySpace(), bulkUploadDbInfo.getTableName(), processId, context); - List<Map<String, Object>> result = new ArrayList<>(); - if (!((List) response.getResult().get(JsonKey.RESPONSE)).isEmpty()) { - result = ((List) response.getResult().get(JsonKey.RESPONSE)); - } - logger.info( - context, - "UserUploadUtil:getFullRecordFromProcessId:got single row data from bulk_upload_process with processId:" - + processId); - return result.get(FIRST_RECORD); - } - - public static BulkMigrationUser convertRowToObject( - Map<String, Object> row, RequestContext context) { - BulkMigrationUser bulkMigrationUser = null; - try { - bulkMigrationUser = mapper.convertValue(row, BulkMigrationUser.class); - } catch (Exception e) { - logger.error( - context, - "UserUploadUtil:convertMapToMigrationObject:error occurred while converting map to pojo" - .concat(e.getMessage() + ""), - e); - } - return bulkMigrationUser; - } - - public static List<SelfDeclaredUser> getMigrationUserAsList( - BulkMigrationUser bulkMigrationUser, RequestContext context) { - List<SelfDeclaredUser> userList = new ArrayList<>(); - try { - String decryptedData = decryptionService.decryptData(bulkMigrationUser.getData(), context); - userList = mapper.readValue(decryptedData, new TypeReference<List<SelfDeclaredUser>>() {}); - } catch (Exception e) { - logger.error( - context, - "UserUploadUtil:getMigrationUserAsList:error occurred while converting map to POJO: " + e, - e); - } - return userList; - } - - public static void updateStatusInUserBulkTable( - String processId, int statusVal, RequestContext context) { - try { - logger.info( - context, - "UserUploadUtil:updateStatusInUserBulkTable: got status to change in bulk upload table" - .concat(statusVal + "") - + "with processId" - + processId); - Map<String, Object> propertiesMap = new WeakHashMap<>(); - propertiesMap.put(JsonKey.ID, processId); - propertiesMap.put(JsonKey.STATUS, statusVal); - updateBulkUserTable(propertiesMap, context); - } catch (Exception e) { - logger.error( - context, - "UserUploadUtil:updateStatusInUserBulkTable: status update failed".concat(e + "") - + "with processId" - + processId, - e); - } - } - - private static void updateBulkUserTable( - Map<String, Object> propertiesMap, RequestContext context) { - Response response = - cassandraOperation.updateRecord( - bulkUploadDbInfo.getKeySpace(), - bulkUploadDbInfo.getTableName(), - propertiesMap, - context); - logger.info( - context, "UserUploadUtil:updateBulkUserTable: status update result".concat(response + "")); - } -} diff --git a/service/src/main/java/org/sunbird/util/contentstore/ContentStoreUtil.java b/service/src/main/java/org/sunbird/util/contentstore/ContentStoreUtil.java index 34fca74a1..c8840c969 100644 --- a/service/src/main/java/org/sunbird/util/contentstore/ContentStoreUtil.java +++ b/service/src/main/java/org/sunbird/util/contentstore/ContentStoreUtil.java @@ -11,7 +11,7 @@ import org.sunbird.request.RequestContext; import org.sunbird.util.ProjectUtil; public class ContentStoreUtil { - private static LoggerUtil logger = new LoggerUtil(ContentStoreUtil.class); + private static final LoggerUtil logger = new LoggerUtil(ContentStoreUtil.class); private static Map<String, String> getHeaders() { Map<String, String> headers = new HashMap<>(); diff --git a/service/src/main/java/org/sunbird/util/feed/FeedUtil.java b/service/src/main/java/org/sunbird/util/feed/FeedUtil.java index fe360a1ab..250b85260 100644 --- a/service/src/main/java/org/sunbird/util/feed/FeedUtil.java +++ b/service/src/main/java/org/sunbird/util/feed/FeedUtil.java @@ -1,5 +1,6 @@ package org.sunbird.util.feed; +import com.fasterxml.jackson.databind.ObjectMapper; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -14,6 +15,7 @@ import org.sunbird.model.ShadowUser; import org.sunbird.model.user.Feed; import org.sunbird.model.user.FeedAction; import org.sunbird.model.user.FeedStatus; +import org.sunbird.request.Request; import org.sunbird.request.RequestContext; import org.sunbird.response.Response; import org.sunbird.service.feed.FeedFactory; @@ -23,10 +25,10 @@ import org.sunbird.service.organisation.impl.OrgServiceImpl; /** this class will be used as a Util for inserting Feed in table */ public class FeedUtil { - private static LoggerUtil logger = new LoggerUtil(FeedUtil.class); + private static final LoggerUtil logger = new LoggerUtil(FeedUtil.class); - private static IFeedService feedService = FeedFactory.getInstance(); - private static OrgService orgService = OrgServiceImpl.getInstance(); + private static final IFeedService feedService = FeedFactory.getInstance(); + private static final OrgService orgService = OrgServiceImpl.getInstance(); private static Map<String, Object> orgIdMap = new HashMap<>(); public static Response saveFeed( @@ -64,7 +66,7 @@ public class FeedUtil { return response; } - private static Feed createFeedObj(ShadowUser shadowUser, String userId, RequestContext context) { + private static Feed createFeedObj(ShadowUser shadowUser, String userId, RequestContext context){ Feed feed = new Feed(); feed.setPriority(1); feed.setCreatedBy(shadowUser.getAddedBy()); diff --git a/service/src/main/java/org/sunbird/util/otp/OTPUtil.java b/service/src/main/java/org/sunbird/util/otp/OTPUtil.java index 92c3fb57c..138fb1834 100644 --- a/service/src/main/java/org/sunbird/util/otp/OTPUtil.java +++ b/service/src/main/java/org/sunbird/util/otp/OTPUtil.java @@ -10,6 +10,7 @@ import java.util.List; import java.util.Map; import org.apache.commons.lang3.StringUtils; import org.sunbird.actor.BackgroundOperations; +import org.sunbird.datasecurity.impl.LogMaskServiceImpl; import org.sunbird.keys.JsonKey; import org.sunbird.logging.LoggerUtil; import org.sunbird.notification.sms.provider.ISmsProvider; @@ -20,8 +21,9 @@ import org.sunbird.service.otp.OTPService; import org.sunbird.util.ProjectUtil; public final class OTPUtil { - private static LoggerUtil logger = new LoggerUtil(OTPUtil.class); - private static OTPService otpService = new OTPService(); + private static final LoggerUtil logger = new LoggerUtil(OTPUtil.class); + private static final OTPService otpService = new OTPService(); + private static final LogMaskServiceImpl logMaskService = new LogMaskServiceImpl(); private static final int MAXIMUM_OTP_LENGTH = 6; private static final int SECONDS_IN_MINUTES = 60; private static final int RETRY_COUNT = 2; @@ -80,21 +82,22 @@ public final class OTPUtil { return false; } Map<String, String> smsTemplate = new HashMap<>(); - String template = (String) otpMap.get(JsonKey.TEMPLATE_ID); + String templateId = (String) otpMap.get(JsonKey.TEMPLATE_ID); smsTemplate.put(JsonKey.OTP, (String) otpMap.get(JsonKey.OTP)); smsTemplate.put( JsonKey.OTP_EXPIRATION_IN_MINUTES, (String) otpMap.get(JsonKey.OTP_EXPIRATION_IN_MINUTES)); smsTemplate.put( JsonKey.INSTALLATION_NAME, ProjectUtil.getConfigValue(JsonKey.SUNBIRD_INSTALLATION_DISPLAY_NAME)); - String sms; - if (StringUtils.isBlank(template)) { + String sms = ""; + if (StringUtils.isBlank(templateId)) { sms = otpService.getSmsBody(JsonKey.VERIFY_PHONE_OTP_TEMPLATE, smsTemplate, context); - } else if (StringUtils.isNotBlank(template) - && StringUtils.equals(template, JsonKey.WARD_LOGIN_OTP_TEMPLATE_ID)) { + } else if (StringUtils.equals(JsonKey.WARD_LOGIN_OTP_TEMPLATE_ID, templateId)) { sms = otpService.getSmsBody(JsonKey.OTP_PHONE_WARD_LOGIN_TEMPLATE, smsTemplate, context); - } else { + } else if (StringUtils.equals(JsonKey.RESET_PASSWORD_TEMPLATE_ID, templateId)) { sms = otpService.getSmsBody(JsonKey.OTP_PHONE_RESET_PASSWORD_TEMPLATE, smsTemplate, context); + } else if (StringUtils.equals(JsonKey.CONTACT_UPDATE_TEMPLATE_ID, templateId)) { + sms = otpService.getSmsBody(JsonKey.OTP_CONTACT_UPDATE_TEMPLATE_SMS, smsTemplate, context); } logger.debug(context, "OTPUtil:sendOTPViaSMS: SMS text = " + sms); @@ -126,33 +129,30 @@ public final class OTPUtil { } public static Request getRequestToSendOTPViaEmail( - Map<String, Object> emailTemplateMap, String otpType, RequestContext context) { - Request request = null; + Map<String, Object> emailTemplateMap, RequestContext context) { + Request request; if ((StringUtils.isBlank((String) emailTemplateMap.get(JsonKey.EMAIL)))) { - return request; + return null; } + String templateId = (String) emailTemplateMap.get(JsonKey.TEMPLATE_ID); String envName = ProjectUtil.getConfigValue(JsonKey.SUNBIRD_INSTALLATION_DISPLAY_NAME); - String emailSubject = null; - if (JsonKey.RESET_PASSWORD.equalsIgnoreCase(otpType)) { - emailSubject = ProjectUtil.getConfigValue(JsonKey.SUNBIRD_RESET_PASS_MAIL_SUBJECT); - } else { - // default fallback for all other otpType - emailSubject = ProjectUtil.getConfigValue(JsonKey.ONBOARDING_MAIL_SUBJECT); - } - emailTemplateMap.put(JsonKey.SUBJECT, ProjectUtil.formatMessage(emailSubject, envName)); List<String> reciptientsMail = new ArrayList<>(); reciptientsMail.add((String) emailTemplateMap.get(JsonKey.EMAIL)); emailTemplateMap.put(JsonKey.RECIPIENT_EMAILS, reciptientsMail); - if (StringUtils.isBlank((String) emailTemplateMap.get(JsonKey.TEMPLATE_ID))) { + if (StringUtils.isBlank(templateId)) { emailTemplateMap.put(JsonKey.EMAIL_TEMPLATE_TYPE, JsonKey.OTP); - } else if (StringUtils.isNotBlank((String) emailTemplateMap.get(JsonKey.TEMPLATE_ID)) - && StringUtils.equals( - (String) emailTemplateMap.get(JsonKey.TEMPLATE_ID), - JsonKey.WARD_LOGIN_OTP_TEMPLATE_ID)) { + emailTemplateMap.put(JsonKey.SUBJECT, JsonKey.EMAIL_VERIFICATION_SUBJECT); + } else if (StringUtils.equalsIgnoreCase(JsonKey.WARD_LOGIN_OTP_TEMPLATE_ID, templateId)) { emailTemplateMap.put(JsonKey.EMAIL_TEMPLATE_TYPE, JsonKey.OTP_EMAIL_WARD_LOGIN_TEMPLATE); - } else { - // send otp to email while reseting password from portal + String emailSubject = ProjectUtil.getConfigValue(JsonKey.ONBOARDING_MAIL_SUBJECT); + emailTemplateMap.put(JsonKey.SUBJECT, ProjectUtil.formatMessage(emailSubject, envName)); + } else if (StringUtils.equalsIgnoreCase(JsonKey.RESET_PASSWORD_TEMPLATE_ID, templateId)) { emailTemplateMap.put(JsonKey.EMAIL_TEMPLATE_TYPE, JsonKey.OTP_EMAIL_RESET_PASSWORD_TEMPLATE); + emailTemplateMap.put( + JsonKey.SUBJECT, ProjectUtil.getConfigValue(JsonKey.SUNBIRD_RESET_PASS_MAIL_SUBJECT)); + } else if (StringUtils.equalsIgnoreCase(JsonKey.CONTACT_UPDATE_TEMPLATE_ID, templateId)) { + emailTemplateMap.put(JsonKey.EMAIL_TEMPLATE_TYPE, JsonKey.OTP_CONTACT_UPDATE_TEMPLATE_EMAIL); + emailTemplateMap.put(JsonKey.SUBJECT, JsonKey.CONTACT_DETAILS_UPDATE_VERIFICATION_SUBJECT); } emailTemplateMap.put(JsonKey.INSTALLATION_NAME, envName); request = new Request(); @@ -162,15 +162,23 @@ public final class OTPUtil { return request; } - public static Request getRequestToSendOTPViaEmail( - Map<String, Object> emailTemplateMap, RequestContext context) { - return getRequestToSendOTPViaEmail(emailTemplateMap, null, context); - } - public static String getOTPExpirationInMinutes() { String expirationInSeconds = ProjectUtil.getConfigValue(JsonKey.SUNBIRD_OTP_EXPIRATION); int otpExpiration = Integer.parseInt(expirationInSeconds); int otpExpirationInMinutes = Math.floorDiv(otpExpiration, SECONDS_IN_MINUTES); return String.valueOf(otpExpirationInMinutes); } + + public static String maskOTP(String otp) { + return logMaskService.maskOTP(otp); + } + + public static String maskId(String id, String type) { + if (JsonKey.EMAIL.equalsIgnoreCase(type)) { + return logMaskService.maskEmail(id); + } else if (JsonKey.PHONE.equalsIgnoreCase(type)) { + return logMaskService.maskPhone(id); + } + return ""; + } } diff --git a/service/src/main/java/org/sunbird/util/ratelimit/OtpRateLimiter.java b/service/src/main/java/org/sunbird/util/ratelimit/OtpRateLimiter.java index 584702675..9ec0f5877 100644 --- a/service/src/main/java/org/sunbird/util/ratelimit/OtpRateLimiter.java +++ b/service/src/main/java/org/sunbird/util/ratelimit/OtpRateLimiter.java @@ -12,7 +12,7 @@ public enum OtpRateLimiter implements RateLimiter { private String limitKey; private int ttl; - private OtpRateLimiter(String limitKey, int ttl) { + OtpRateLimiter(String limitKey, int ttl) { this.limitKey = limitKey; this.ttl = ttl; } diff --git a/service/src/main/java/org/sunbird/util/ratelimit/RateLimit.java b/service/src/main/java/org/sunbird/util/ratelimit/RateLimit.java index a2d5ab5ff..caf3d5af9 100644 --- a/service/src/main/java/org/sunbird/util/ratelimit/RateLimit.java +++ b/service/src/main/java/org/sunbird/util/ratelimit/RateLimit.java @@ -9,7 +9,7 @@ import org.sunbird.keys.JsonKey; import org.sunbird.logging.LoggerUtil; public class RateLimit { - private LoggerUtil logger = new LoggerUtil(RateLimit.class); + private final LoggerUtil logger = new LoggerUtil(RateLimit.class); private String key; private String unit; diff --git a/service/src/main/java/org/sunbird/util/search/FuzzyMatcher.java b/service/src/main/java/org/sunbird/util/search/FuzzyMatcher.java index 2e153ab4c..f5678fa72 100644 --- a/service/src/main/java/org/sunbird/util/search/FuzzyMatcher.java +++ b/service/src/main/java/org/sunbird/util/search/FuzzyMatcher.java @@ -16,7 +16,7 @@ import org.sunbird.logging.LoggerUtil; import org.sunbird.util.PropertiesCache; public class FuzzyMatcher { - private static LoggerUtil logger = new LoggerUtil(FuzzyMatcher.class); + private static final LoggerUtil logger = new LoggerUtil(FuzzyMatcher.class); private static final String nameToBeMatchedId = "0"; private static final String ENCODING = "UTF-8"; diff --git a/service/src/main/java/org/sunbird/util/search/FuzzySearchManager.java b/service/src/main/java/org/sunbird/util/search/FuzzySearchManager.java index d69359bc4..dbcb179cb 100644 --- a/service/src/main/java/org/sunbird/util/search/FuzzySearchManager.java +++ b/service/src/main/java/org/sunbird/util/search/FuzzySearchManager.java @@ -12,7 +12,7 @@ import org.sunbird.keys.JsonKey; import org.sunbird.logging.LoggerUtil; public class FuzzySearchManager { - private static LoggerUtil logger = new LoggerUtil(FuzzySearchManager.class); + private static final LoggerUtil logger = new LoggerUtil(FuzzySearchManager.class); private Map<String, Object> fuzzySearchMap; private List<Map<String, Object>> searchMap; diff --git a/service/src/main/java/org/sunbird/util/user/SchedulerManager.java b/service/src/main/java/org/sunbird/util/user/SchedulerManager.java index ce20cb450..feb498f11 100644 --- a/service/src/main/java/org/sunbird/util/user/SchedulerManager.java +++ b/service/src/main/java/org/sunbird/util/user/SchedulerManager.java @@ -9,7 +9,7 @@ import org.sunbird.util.ProjectUtil; /** @author Manzarul All the scheduler job will be handle by this class. */ public class SchedulerManager { - private static LoggerUtil logger = new LoggerUtil(SchedulerManager.class); + private static final LoggerUtil logger = new LoggerUtil(SchedulerManager.class); private static final int TTL = Integer.parseInt(ProjectUtil.getConfigValue("learner_in_memory_cache_ttl")); diff --git a/service/src/main/java/org/sunbird/util/user/UserUtil.java b/service/src/main/java/org/sunbird/util/user/UserUtil.java index e1ba103b5..7fe801d8e 100644 --- a/service/src/main/java/org/sunbird/util/user/UserUtil.java +++ b/service/src/main/java/org/sunbird/util/user/UserUtil.java @@ -18,10 +18,6 @@ import org.apache.commons.collections.MapUtils; import org.apache.commons.lang3.StringUtils; import org.sunbird.actor.user.validator.UserRequestValidator; import org.sunbird.common.ElasticSearchHelper; -import org.sunbird.common.factory.EsClientFactory; -import org.sunbird.common.inf.ElasticSearchService; -import org.sunbird.dao.user.UserDao; -import org.sunbird.dao.user.impl.UserDaoImpl; import org.sunbird.datasecurity.DataMaskingService; import org.sunbird.datasecurity.DecryptionService; import org.sunbird.datasecurity.EncryptionService; @@ -35,7 +31,6 @@ import org.sunbird.model.user.UserDeclareEntity; import org.sunbird.request.RequestContext; import org.sunbird.service.organisation.OrgService; import org.sunbird.service.organisation.impl.OrgServiceImpl; -import org.sunbird.service.user.AssociationMechanism; import org.sunbird.service.user.UserExternalIdentityService; import org.sunbird.service.user.UserLookupService; import org.sunbird.service.user.UserOrgService; @@ -54,24 +49,22 @@ import org.sunbird.util.contentstore.ContentStoreUtil; import scala.concurrent.Future; public class UserUtil { - private static LoggerUtil logger = new LoggerUtil(UserUtil.class); - private static EncryptionService encryptionService = + private static final LoggerUtil logger = new LoggerUtil(UserUtil.class); + private static final EncryptionService encryptionService = org.sunbird.datasecurity.impl.ServiceFactory.getEncryptionServiceInstance(); - private static ObjectMapper mapper = new ObjectMapper(); - private static SSOManager ssoManager = SSOServiceFactory.getInstance(); - private static PropertiesCache propertiesCache = PropertiesCache.getInstance(); - private static DataMaskingService maskingService = + private static final ObjectMapper mapper = new ObjectMapper(); + private static final SSOManager ssoManager = SSOServiceFactory.getInstance(); + private static final PropertiesCache propertiesCache = PropertiesCache.getInstance(); + private static final DataMaskingService maskingService = org.sunbird.datasecurity.impl.ServiceFactory.getMaskingServiceInstance(); - private static DecryptionService decService = + private static final DecryptionService decService = org.sunbird.datasecurity.impl.ServiceFactory.getDecryptionServiceInstance(); - private static UserService userService = UserServiceImpl.getInstance(); - private static ElasticSearchService esUtil = EsClientFactory.getInstance(JsonKey.REST); - private static UserExternalIdentityService userExternalIdentityService = + private static final UserService userService = UserServiceImpl.getInstance(); + private static final UserExternalIdentityService userExternalIdentityService = new UserExternalIdentityServiceImpl(); - private static UserLookupService userLookupService = UserLookUpServiceImpl.getInstance(); - private static UserOrgService userOrgService = UserOrgServiceImpl.getInstance(); - private static OrgService orgService = OrgServiceImpl.getInstance(); - private static UserDao userDao = UserDaoImpl.getInstance(); + private static final UserLookupService userLookupService = UserLookUpServiceImpl.getInstance(); + private static final UserOrgService userOrgService = UserOrgServiceImpl.getInstance(); + private static final OrgService orgService = OrgServiceImpl.getInstance(); private UserUtil() {} @@ -163,9 +156,7 @@ public class UserUtil { (StringUtils.isNotBlank((String) userMap.get(JsonKey.USER_ID))) ? ((String) userMap.get(JsonKey.USER_ID)) : ((String) userMap.get(JsonKey.ID)); - Future<Map<String, Object>> userF = - esUtil.getDataByIdentifier(ProjectUtil.EsType.user.getTypeName(), userId, context); - user = (Map<String, Object>) ElasticSearchHelper.getResponseFromFuture(userF); + user = userService.getUserDetailsForES(userId, context); if (MapUtils.isEmpty(user)) { ProjectCommonException.throwClientErrorException(ResponseCode.userNotFound, null); } @@ -192,9 +183,7 @@ public class UserUtil { Map<String, Object> user = null; String userId = getUserIdFromExternalId(userMap, context); if (!StringUtils.isEmpty(userId)) { - Future<Map<String, Object>> userF = - esUtil.getDataByIdentifier(ProjectUtil.EsType.user.getTypeName(), userId, context); - user = (Map<String, Object>) ElasticSearchHelper.getResponseFromFuture(userF); + user = userService.getUserDetailsForES(userId, context); } return user; } @@ -548,6 +537,7 @@ public class UserUtil { return getUserOrgDetails(false, userId, context); } + @SuppressWarnings("unchecked") public static List<Map<String, Object>> getUserOrgDetails( boolean isDeleted, String userId, RequestContext context) { List<Map<String, Object>> userOrgList = new ArrayList<>(); @@ -593,7 +583,7 @@ public class UserUtil { public static Map<String, Object> validateManagedByUser( String managedBy, RequestContext context) { - Map<String, Object> managedByInfo = userDao.getUserDetailsById(managedBy, context); + Map<String, Object> managedByInfo = userService.getUserDetailsById(managedBy, context); if (MapUtils.isEmpty(managedByInfo) || StringUtils.isBlank((String) managedByInfo.get(JsonKey.FIRST_NAME)) || StringUtils.isNotBlank((String) managedByInfo.get(JsonKey.MANAGED_BY)) @@ -611,7 +601,9 @@ public class UserUtil { if (Boolean.valueOf(ProjectUtil.getConfigValue(JsonKey.LIMIT_MANAGED_USER_CREATION))) { Map<String, Object> searchQueryMap = new HashMap<>(); searchQueryMap.put(JsonKey.MANAGED_BY, managedBy); - SearchDTO searchDTO = ElasticSearchHelper.createSearchDTO(searchQueryMap); + Map<String, Object> searchRequestMap = new HashMap<>(); + searchRequestMap.put(JsonKey.FILTERS, searchQueryMap); + SearchDTO searchDTO = ElasticSearchHelper.createSearchDTO(searchRequestMap); Map<String, Object> searchResult = userService.searchUser(searchDTO, context); List<Map<String, Object>> managedUserList = (List<Map<String, Object>>) searchResult.get(JsonKey.CONTENT); @@ -702,12 +694,7 @@ public class UserUtil { public static String fetchProviderByOrgId(String orgId, RequestContext context) { try { if (StringUtils.isNotBlank(orgId)) { - Future<Map<String, Object>> esOrgResF = - esUtil.getDataByIdentifier( - ProjectUtil.EsType.organisation.getTypeName(), orgId, context); - Map<String, Object> org = - (Map<String, Object>) ElasticSearchHelper.getResponseFromFuture(esOrgResF); - + Map<String, Object> org = orgService.getOrgById(orgId, context); if (null != org && !org.isEmpty()) { return (String) org.get(JsonKey.CHANNEL); } @@ -729,8 +716,7 @@ public class UserUtil { filters.put(JsonKey.CHANNEL, providers); searchQueryMap.put(JsonKey.FILTERS, filters); SearchDTO searchDTO = ElasticSearchHelper.createSearchDTO(searchQueryMap); - Future<Map<String, Object>> esOrgResF = - esUtil.search(searchDTO, ProjectUtil.EsType.organisation.getTypeName(), context); + Future<Map<String, Object>> esOrgResF = orgService.searchOrg(searchDTO, context); Map<String, Object> esResOrg = (Map<String, Object>) ElasticSearchHelper.getResponseFromFuture(esOrgResF); if (MapUtils.isNotEmpty(esResOrg)) { @@ -742,7 +728,6 @@ public class UserUtil { } } } - } catch (Exception ex) { logger.error(context, ex.getMessage(), ex); } @@ -940,18 +925,6 @@ public class UserUtil { } } } - - public static Map<String, Object> createUserOrgRequestData(Map<String, Object> userMap) { - Map<String, Object> userOrgMap = new HashMap<String, Object>(); - userOrgMap.put(JsonKey.ID, ProjectUtil.getUniqueIdFromTimestamp(1)); - userOrgMap.put(JsonKey.HASHTAGID, userMap.get(JsonKey.ROOT_ORG_ID)); - userOrgMap.put(JsonKey.USER_ID, userMap.get(JsonKey.USER_ID)); - userOrgMap.put(JsonKey.ORGANISATION_ID, userMap.get(JsonKey.ROOT_ORG_ID)); - userOrgMap.put(JsonKey.ORG_JOIN_DATE, ProjectUtil.getFormattedDate()); - userOrgMap.put(JsonKey.IS_DELETED, false); - userOrgMap.put(JsonKey.ASSOCIATION_TYPE, AssociationMechanism.SELF_DECLARATION); - return userOrgMap; - } } @FunctionalInterface diff --git a/service/src/test/java/org/sunbird/actor/location/LocationActorTest.java b/service/src/test/java/org/sunbird/actor/location/LocationActorTest.java index 7470ae0ba..10f89af74 100644 --- a/service/src/test/java/org/sunbird/actor/location/LocationActorTest.java +++ b/service/src/test/java/org/sunbird/actor/location/LocationActorTest.java @@ -15,7 +15,6 @@ import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; @@ -53,14 +52,13 @@ import scala.concurrent.Promise; }) public class LocationActorTest { - private static final ActorSystem system = ActorSystem.create("system"); - private static final Props props = Props.create(LocationActor.class); - private static Map<String, Object> data; - private static ElasticSearchRestHighImpl esSearch; - - @BeforeClass - public static void init() { + private ActorSystem system; + private Props props; + private Map<String, Object> data; + private ElasticSearchRestHighImpl esSearch; + @Before + public void setUp() { PowerMockito.mockStatic(EsClientFactory.class); esSearch = mock(ElasticSearchRestHighImpl.class); when(EsClientFactory.getInstance(Mockito.anyString())).thenReturn(esSearch); @@ -77,11 +75,6 @@ public class LocationActorTest { when(cassandraOperation.deleteRecord( Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.any())) .thenReturn(getSuccessResponse()); - } - - @Before - public void setUp() { - Map<String, Object> esRespone = new HashMap<>(); esRespone.put(JsonKey.CONTENT, new ArrayList<>()); esRespone.put(JsonKey.LOCATION_TYPE, "STATE"); @@ -93,6 +86,9 @@ public class LocationActorTest { when(esSearch.getDataByIdentifier(Mockito.anyString(), Mockito.anyString(), Mockito.any())) .thenReturn(promise.future()); data = getDataMap(); + + system = ActorSystem.create("system"); + props = Props.create(LocationActor.class); } @Test @@ -209,8 +205,7 @@ public class LocationActorTest { } } - private static Map<String, Object> getDataMap() { - + private Map<String, Object> getDataMap() { data = new HashMap(); data.put(JsonKey.LOCATION_TYPE, "STATE"); data.put(JsonKey.CODE, "S01"); diff --git a/service/src/test/java/org/sunbird/actor/location/validator/LocationRequestValidatorTest.java b/service/src/test/java/org/sunbird/actor/location/validator/LocationRequestValidatorTest.java index 71b76fb19..4f6e76ee7 100644 --- a/service/src/test/java/org/sunbird/actor/location/validator/LocationRequestValidatorTest.java +++ b/service/src/test/java/org/sunbird/actor/location/validator/LocationRequestValidatorTest.java @@ -11,7 +11,6 @@ import java.util.Map; import java.util.Set; import org.junit.Assert; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; @@ -53,25 +52,22 @@ import scala.concurrent.Promise; }) public class LocationRequestValidatorTest { - private static ElasticSearchService esService; - private static LocationDaoImpl locationDao; + private LocationRequestValidator validator; + private ElasticSearchService esService; + private LocationDaoImpl locationDao; - @BeforeClass - public static void before() { + @Before + public void beforeTest() { PowerMockito.mockStatic(ProjectUtil.class); PowerMockito.when(ProjectUtil.getConfigValue(Mockito.anyString())) .thenReturn("state,district,block,cluster,school;"); PowerMockito.mockStatic(EsClientFactory.class); esService = mock(ElasticSearchRestHighImpl.class); when(EsClientFactory.getInstance(Mockito.anyString())).thenReturn(esService); - } - - @Before - public void beforeTest() { - PowerMockito.mockStatic(LocationDaoFactory.class); locationDao = mock(LocationDaoImpl.class); when(LocationDaoFactory.getInstance()).thenReturn(locationDao); + validator = new LocationRequestValidator(); } @Test @@ -97,7 +93,7 @@ public class LocationRequestValidatorTest { request.setName("name"); request.setType("district"); try { - LocationRequestValidator.isValidParentIdAndCode(request, "create"); + validator.isValidParentIdAndCode(request, "create", new RequestContext()); } catch (ProjectCommonException ex) { Assert.assertNotNull(ex); String msg = @@ -118,7 +114,7 @@ public class LocationRequestValidatorTest { request.setParentId("parentId"); request.setParentCode("parentCode"); try { - LocationRequestValidator.isValidParentIdAndCode(request, "create"); + validator.isValidParentIdAndCode(request, "create", new RequestContext()); } catch (ProjectCommonException ex) { Assert.assertNotNull(ex); String msg = @@ -154,7 +150,7 @@ public class LocationRequestValidatorTest { when(esService.search(Mockito.any(), Mockito.anyString(), Mockito.any())) .thenReturn(promise.future()); try { - LocationRequestValidator.isValidParentIdAndCode(request, "create"); + validator.isValidParentIdAndCode(request, "create", new RequestContext()); } catch (ProjectCommonException ex) { Assert.assertNotNull(ex); String msg = @@ -189,7 +185,7 @@ public class LocationRequestValidatorTest { when(esService.search(Mockito.any(), Mockito.anyString(), Mockito.any())) .thenReturn(promise.future()); try { - LocationRequestValidator.isValidParentIdAndCode(request, "update"); + validator.isValidParentIdAndCode(request, "update", new RequestContext()); } catch (ProjectCommonException ex) { Assert.assertNotNull(ex); String msg = @@ -230,7 +226,7 @@ public class LocationRequestValidatorTest { .thenReturn(promise.future()) .thenReturn(promise2.future()); try { - LocationRequestValidator.isValidParentIdAndCode(request, "create"); + validator.isValidParentIdAndCode(request, "create", new RequestContext()); } catch (ProjectCommonException ex) { Assert.assertNotNull(ex); String msg = @@ -280,7 +276,7 @@ public class LocationRequestValidatorTest { when(esService.getDataByIdentifier(Mockito.anyString(), Mockito.anyString(), Mockito.any())) .thenReturn(locPromise.future()); try { - LocationRequestValidator.isValidParentIdAndCode(request, "create"); + validator.isValidParentIdAndCode(request, "create", new RequestContext()); } catch (ProjectCommonException ex) { Assert.assertNotNull(ex); String msg = @@ -332,8 +328,7 @@ public class LocationRequestValidatorTest { when(esService.getDataByIdentifier(Mockito.anyString(), Mockito.anyString(), Mockito.any())) .thenReturn(locPromise.future()); - - boolean isValid = LocationRequestValidator.isValidParentIdAndCode(request, "update"); + boolean isValid = validator.isValidParentIdAndCode(request, "update", new RequestContext()); Assert.assertTrue(isValid); } @@ -375,7 +370,7 @@ public class LocationRequestValidatorTest { .thenReturn(locPromise.future()); try { - LocationRequestValidator.isLocationHasChild("stateid"); + validator.isLocationHasChild("stateid", new RequestContext()); } catch (ProjectCommonException ex) { Assert.assertNotNull(ex); Assert.assertEquals( @@ -443,7 +438,6 @@ public class LocationRequestValidatorTest { @Test public void validateSearchLocationRequestTest() { - LocationRequestValidator validator = new LocationRequestValidator(); List<String> filters = new ArrayList<>(); Map<String, Object> reqMap = new HashMap<>(); reqMap.put(JsonKey.FILTERS, filters); @@ -459,7 +453,6 @@ public class LocationRequestValidatorTest { @Test public void validateSearchLocationEmptyRequestTest() { - LocationRequestValidator validator = new LocationRequestValidator(); Map<String, Object> reqMap = new HashMap<>(); Request req = new Request(); req.setRequest(reqMap); @@ -473,7 +466,6 @@ public class LocationRequestValidatorTest { @Test public void validateDeleteLocationRequestTest() { - LocationRequestValidator validator = new LocationRequestValidator(); try { validator.validateDeleteLocationRequest(""); } catch (ProjectCommonException ex) { diff --git a/service/src/test/java/org/sunbird/actor/notes/NotesManagementActorTest.java b/service/src/test/java/org/sunbird/actor/notes/NotesManagementActorTest.java index d5ac6f262..6da73a046 100644 --- a/service/src/test/java/org/sunbird/actor/notes/NotesManagementActorTest.java +++ b/service/src/test/java/org/sunbird/actor/notes/NotesManagementActorTest.java @@ -27,7 +27,6 @@ import org.sunbird.common.ElasticSearchHelper; import org.sunbird.common.ElasticSearchRestHighImpl; import org.sunbird.common.factory.EsClientFactory; import org.sunbird.common.inf.ElasticSearchService; -import org.sunbird.dto.SearchDTO; import org.sunbird.exception.ProjectCommonException; import org.sunbird.exception.ResponseCode; import org.sunbird.helper.ServiceFactory; @@ -57,7 +56,6 @@ public class NotesManagementActorTest { private static String noteId = ""; private ActorSystem system = ActorSystem.create("system"); private static final Props props = Props.create(NotesManagementActor.class); - private static CassandraOperationImpl cassandraOperation; private ElasticSearchService esUtil; @@ -66,18 +64,10 @@ public class NotesManagementActorTest { PowerMockito.mockStatic(EsClientFactory.class); esUtil = mock(ElasticSearchRestHighImpl.class); when(EsClientFactory.getInstance(Mockito.anyString())).thenReturn(esUtil); - Map<String, Object> esResponse = new HashMap<>(); - esResponse.put(JsonKey.CONTENT, new ArrayList<>()); - Promise<Map<String, Object>> promise = Futures.promise(); - promise.success(esResponse); - when(esUtil.search(Mockito.any(SearchDTO.class), Mockito.anyString(), Mockito.any())) - .thenReturn(promise.future()); Promise<Boolean> booleanPromise = Futures.promise(); booleanPromise.success(true); when(esUtil.update(Mockito.anyString(), Mockito.anyString(), Mockito.anyMap(), Mockito.any())) .thenReturn(booleanPromise.future()); - when(esUtil.getDataByIdentifier(Mockito.anyString(), Mockito.anyString(), Mockito.any())) - .thenReturn(promise.future()); PowerMockito.mockStatic(ServiceFactory.class); cassandraOperation = mock(CassandraOperationImpl.class); when(ServiceFactory.getInstance()).thenReturn(cassandraOperation); @@ -212,11 +202,11 @@ public class NotesManagementActorTest { subject.tell(reqObj, probe.getRef()); if (errorCode == null) { - Response res = probe.expectMsgClass(duration("10 second"), Response.class); + Response res = probe.expectMsgClass(duration("100 second"), Response.class); return null != res && res.getResponseCode() == ResponseCode.OK; } else { ProjectCommonException res = - probe.expectMsgClass(duration("10 second"), ProjectCommonException.class); + probe.expectMsgClass(duration("100 second"), ProjectCommonException.class); return res.getCode().equals(errorCode.getErrorCode()) || res.getResponseCode() == errorCode.getResponseCode(); } diff --git a/service/src/test/java/org/sunbird/actor/notification/EmailServiceActorTest.java b/service/src/test/java/org/sunbird/actor/notification/EmailServiceActorTest.java index 25987a00e..1babff137 100644 --- a/service/src/test/java/org/sunbird/actor/notification/EmailServiceActorTest.java +++ b/service/src/test/java/org/sunbird/actor/notification/EmailServiceActorTest.java @@ -73,6 +73,9 @@ public class EmailServiceActorTest { Mockito.anyList(), Mockito.any())) .thenReturn(cassandraGetRecordById()); + when(cassandraOperation.getRecordById( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.any())) + .thenReturn(cassandraGetRecordById()); } private static Response cassandraGetRecordById() { diff --git a/service/src/test/java/org/sunbird/actor/user/ManagedUserActorTest.java b/service/src/test/java/org/sunbird/actor/user/ManagedUserActorTest.java index 3362fdce0..fc8e44046 100644 --- a/service/src/test/java/org/sunbird/actor/user/ManagedUserActorTest.java +++ b/service/src/test/java/org/sunbird/actor/user/ManagedUserActorTest.java @@ -11,9 +11,12 @@ import akka.actor.Props; import akka.dispatch.Futures; import akka.testkit.javadsl.TestKit; import java.util.ArrayList; +import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.stream.Collectors; +import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import org.powermock.api.mockito.PowerMockito; @@ -27,6 +30,8 @@ import org.sunbird.keys.JsonKey; import org.sunbird.operations.ActorOperations; import org.sunbird.request.Request; import org.sunbird.request.RequestContext; +import org.sunbird.response.Response; +import org.sunbird.util.DataCacheHandler; import org.sunbird.util.Util; import org.sunbird.util.user.UserUtil; import scala.concurrent.Promise; @@ -36,6 +41,22 @@ public class ManagedUserActorTest extends UserManagementActorTestBase { public final Props props = Props.create(ManagedUserActor.class); + @Before + public void before() { + PowerMockito.mockStatic(DataCacheHandler.class); + List<String> subTypeList = Arrays.asList("state,district,block,cluster,school;".split(";")); + Map<String, Integer> orderMap = new HashMap<>(); + for (String str : subTypeList) { + List<String> typeList = + (((Arrays.asList(str.split(","))).stream().map(String::toLowerCase)) + .collect(Collectors.toList())); + for (int i = 0; i < typeList.size(); i++) { + orderMap.put(typeList.get(i), i); + } + } + when(DataCacheHandler.getLocationOrderMap()).thenReturn(orderMap); + } + @Test public void testGetManagedUsers() throws Exception { HashMap<String, Object> reqMap = new HashMap<>(); @@ -94,7 +115,7 @@ public class ManagedUserActorTest extends UserManagementActorTestBase { TestKit probe = new TestKit(system); ActorRef subject = system.actorOf(props); subject.tell(reqObj, probe.getRef()); - probe.expectMsgClass(duration("1000 second"), NullPointerException.class); + probe.expectMsgClass(duration("10 second"), Response.class); } catch (Exception ex) { assertNotNull(ex); } @@ -111,10 +132,6 @@ public class ManagedUserActorTest extends UserManagementActorTestBase { PowerMockito.mockStatic(Util.class); Map<String, Object> userMap = new HashMap<>(getMapObject()); userMap.put(JsonKey.USER_ID, "3dc4e0bc-43a6-4ba0-84f9-6606a9c17320"); - // when(Util.getUserDetails(Mockito.anyMap(), Mockito.anyMap(), - // Mockito.any(RequestContext.class))) - // .thenReturn(userMap); - PowerMockito.mockStatic(EsClientFactory.class); ElasticSearchService esService = mock(ElasticSearchRestHighImpl.class); when(EsClientFactory.getInstance(Mockito.anyString())).thenReturn(esService); @@ -147,10 +164,11 @@ public class ManagedUserActorTest extends UserManagementActorTestBase { reqObj.getRequest().put(JsonKey.EXTERNAL_IDS, externalIds); reqObj.getContext().put(JsonKey.SIGNUP_TYPE, "self"); reqObj.getContext().put(JsonKey.REQUEST_SOURCE, "source"); + reqObj.setRequestContext(new RequestContext()); TestKit probe = new TestKit(system); ActorRef subject = system.actorOf(props); subject.tell(reqObj, probe.getRef()); - probe.expectMsgClass(duration("1000 second"), NullPointerException.class); + probe.expectMsgClass(duration("100 second"), Response.class); } catch (Exception ex) { assertNotNull(ex); } @@ -203,10 +221,6 @@ public class ManagedUserActorTest extends UserManagementActorTestBase { PowerMockito.mockStatic(Util.class); Map<String, Object> userMap = new HashMap<>(getMapObject()); userMap.put(JsonKey.USER_ID, "3dc4e0bc-43a6-4ba0-84f9-6606a9c17320"); - // when(Util.getUserDetails(Mockito.anyMap(), Mockito.anyMap(), - // Mockito.any(RequestContext.class))) - // .thenReturn(userMap); - PowerMockito.mockStatic(EsClientFactory.class); ElasticSearchService esService = mock(ElasticSearchRestHighImpl.class); when(EsClientFactory.getInstance(Mockito.anyString())).thenReturn(esService); @@ -227,7 +241,7 @@ public class ManagedUserActorTest extends UserManagementActorTestBase { TestKit probe = new TestKit(system); ActorRef subject = system.actorOf(props); subject.tell(reqObj, probe.getRef()); - probe.expectMsgClass(duration("1000 second"), NullPointerException.class); + probe.expectMsgClass(duration("10 second"), Response.class); } catch (Exception ex) { assertNotNull(ex); } diff --git a/service/src/test/java/org/sunbird/actor/user/SSOUserCreateActorTest.java b/service/src/test/java/org/sunbird/actor/user/SSOUserCreateActorTest.java index 2f5080da3..c814c89fd 100644 --- a/service/src/test/java/org/sunbird/actor/user/SSOUserCreateActorTest.java +++ b/service/src/test/java/org/sunbird/actor/user/SSOUserCreateActorTest.java @@ -10,7 +10,11 @@ import akka.pattern.Patterns; import akka.testkit.javadsl.TestKit; import akka.util.Timeout; import java.util.Arrays; +import java.util.HashMap; +import java.util.List; import java.util.Map; +import java.util.stream.Collectors; +import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import org.powermock.api.mockito.PowerMockito; @@ -19,11 +23,32 @@ import org.sunbird.keys.JsonKey; import org.sunbird.model.organisation.Organisation; import org.sunbird.operations.ActorOperations; import org.sunbird.request.Request; +import org.sunbird.response.Response; +import org.sunbird.util.DataCacheHandler; import org.sunbird.util.Util; import scala.concurrent.Future; public class SSOUserCreateActorTest extends UserManagementActorTestBase { + @Before + public void before() { + PowerMockito.mockStatic(DataCacheHandler.class); + List<String> subTypeList = Arrays.asList("state,district,block,cluster,school;".split(";")); + Map<String, Integer> orderMap = new HashMap<>(); + for (String str : subTypeList) { + List<String> typeList = + (((Arrays.asList(str.split(","))).stream().map(String::toLowerCase)) + .collect(Collectors.toList())); + for (int i = 0; i < typeList.size(); i++) { + orderMap.put(typeList.get(i), i); + } + } + when(DataCacheHandler.getLocationOrderMap()).thenReturn(orderMap); + Map<String, String> config = new HashMap<>(); + config.put(JsonKey.CUSTODIAN_ORG_ID, "custOrgId"); + when(DataCacheHandler.getConfigSettings()).thenReturn(config); + } + @Test public void testCreateUserSuccessWithUserCallerId() { reqMap.put(JsonKey.PROFILE_LOCATION, Arrays.asList("anyLocationCodes")); @@ -324,6 +349,6 @@ public class SSOUserCreateActorTest extends UserManagementActorTestBase { subject.tell( getRequest(true, true, true, getAdditionalMapData(reqMap), ActorOperations.CREATE_USER), probe.getRef()); - probe.expectMsgClass(duration("1000 second"), NullPointerException.class); + probe.expectMsgClass(duration("10 second"), Response.class); } } diff --git a/service/src/test/java/org/sunbird/actor/user/TenantMigrationActorTest.java b/service/src/test/java/org/sunbird/actor/user/TenantMigrationActorTest.java index 4da1b7118..ee7c1b10a 100644 --- a/service/src/test/java/org/sunbird/actor/user/TenantMigrationActorTest.java +++ b/service/src/test/java/org/sunbird/actor/user/TenantMigrationActorTest.java @@ -1,6 +1,7 @@ package org.sunbird.actor.user; import static akka.testkit.JavaTestKit.duration; +import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.powermock.api.mockito.PowerMockito.mock; import static org.powermock.api.mockito.PowerMockito.when; @@ -89,10 +90,11 @@ public class TenantMigrationActorTest { Map<String, Object> responseMap = new HashMap<>(); responseMap.put(Constants.RESPONSE, Arrays.asList(getFeedMap())); response.getResult().putAll(responseMap); + response.put(Constants.RESPONSE, Arrays.asList(getFeedMap())); PowerMockito.when(ServiceFactory.getInstance()).thenReturn(cassandraOperation); PowerMockito.when( cassandraOperation.getRecordsByProperties( - Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(RequestContext.class))) + Mockito.anyString(), Mockito.anyString(), Mockito.anyMap(), Mockito.any(RequestContext.class))) .thenReturn(response); Response upsertResponse = new Response(); @@ -147,6 +149,10 @@ public class TenantMigrationActorTest { cassandraOperation.updateRecord( Mockito.anyString(), Mockito.anyString(), Mockito.anyMap(), Mockito.any())) .thenReturn(response); + PowerMockito.when( + cassandraOperation.upsertRecord( + Mockito.anyString(), Mockito.anyString(), Mockito.anyMap(), Mockito.any())) + .thenReturn(response); Response updateResponse = new Response(); updateResponse.getResult().put(JsonKey.RESPONSE, "FAILED"); PowerMockito.when( @@ -158,6 +164,23 @@ public class TenantMigrationActorTest { .thenReturn(getOrgFromCassandra()); } + public static Response getEsResponse() { + + Response response = new Response(); + Map<String, Object> map = new HashMap<>(); + map.put("anyString", new Object()); + response.put(JsonKey.RESPONSE, map); + return response; + } + + public static Map<String, Object> getEsResponseMap() { + Map<String, Object> map = new HashMap<>(); + map.put(JsonKey.IS_TENANT, true); + map.put(JsonKey.ID, "rootOrgId"); + map.put(JsonKey.CHANNEL, "anyChannel"); + return map; + } + public static Map<String, Object> getListOrgResponse() { Map<String, Object> map = new HashMap<>(); map.put(JsonKey.ID, "anyRootOrgId"); @@ -200,13 +223,12 @@ public class TenantMigrationActorTest { } } - public Request getMigrateReq(ActorOperations actorOperation, String action) { + public Request getMigrateReq(ActorOperations actorOperation) { Request reqObj = new Request(); Map reqMap = new HashMap<>(); reqMap.put(JsonKey.USER_ID, "anyUserId"); reqMap.put(JsonKey.USER_EXT_ID, "anyUserExtId"); reqMap.put(JsonKey.CHANNEL, "anyChannel"); - reqMap.put(JsonKey.ACTION, action); reqMap.put(JsonKey.FEED_ID, "anyFeedId"); reqObj.setRequest(reqMap); reqObj.setOperation(actorOperation.getValue()); @@ -220,7 +242,22 @@ public class TenantMigrationActorTest { fMap.put(JsonKey.CATEGORY, "category"); return fMap; } - + @Test + public void testUserMigration() { + try { + PowerMockito.mockStatic(DataCacheHandler.class); + Map<String, String> dataCache = new HashMap<>(); + dataCache.put(JsonKey.CUSTODIAN_ORG_ID, "anyRootOrgId"); + when(DataCacheHandler.getConfigSettings()).thenReturn(dataCache); + boolean result = + testScenario( + getMigrateReq(ActorOperations.USER_TENANT_MIGRATE), + null, + props); + } catch (ProjectCommonException e) { + assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); + } + } @Test public void testUserSelfDeclarationMigrationWithValidatedStatus() { PowerMockito.mockStatic(DataCacheHandler.class); @@ -260,6 +297,7 @@ public class TenantMigrationActorTest { Map<String, Object> map = new HashMap<>(); map.put(JsonKey.ORG_ID, "anyRootOrgId"); map.put(JsonKey.LOCATION_IDS, new ArrayList<String>(Arrays.asList("anyLocationId"))); + map.put("template", "anyTemplate"); list.add(map); response.put(Constants.RESPONSE, list); return response; diff --git a/service/src/test/java/org/sunbird/actor/user/UserFeedActorTest.java b/service/src/test/java/org/sunbird/actor/user/UserFeedActorTest.java index df533df04..7c0e7e322 100644 --- a/service/src/test/java/org/sunbird/actor/user/UserFeedActorTest.java +++ b/service/src/test/java/org/sunbird/actor/user/UserFeedActorTest.java @@ -28,9 +28,11 @@ import org.sunbird.common.Constants; import org.sunbird.exception.ProjectCommonException; import org.sunbird.exception.ResponseCode; import org.sunbird.helper.ServiceFactory; +import org.sunbird.http.HttpClientUtil; import org.sunbird.keys.JsonKey; import org.sunbird.operations.ActorOperations; import org.sunbird.request.Request; +import org.sunbird.request.RequestContext; import org.sunbird.response.Response; import org.sunbird.service.feed.IFeedService; import org.sunbird.service.feed.impl.FeedServiceImpl; @@ -75,12 +77,12 @@ public class UserFeedActorTest { upsertResponse.getResult().putAll(responseMap2); PowerMockito.when( cassandraOperation.insertRecord( - Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())) - .thenReturn(upsertResponse); + Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())) + .thenReturn(upsertResponse); PowerMockito.when( cassandraOperation.updateRecord( - Mockito.any(), Mockito.any(), Mockito.anyMap(), Mockito.anyMap(), Mockito.any())) - .thenReturn(upsertResponse); + Mockito.any(), Mockito.any(), Mockito.anyMap(), Mockito.anyMap(), Mockito.any())) + .thenReturn(upsertResponse); } @Test @@ -88,7 +90,7 @@ public class UserFeedActorTest { TestKit probe = new TestKit(system); ActorRef subject = system.actorOf(props); Request reqObj = new Request(); - + reqObj.setRequestContext(new RequestContext()); reqObj.setOperation(ActorOperations.GET_USER_FEED_BY_ID.getValue()); reqObj.put(JsonKey.USER_ID, "123-456-789"); subject.tell(reqObj, probe.getRef()); @@ -102,6 +104,7 @@ public class UserFeedActorTest { Map<String, Object> requestMap = new HashMap<>(); Map<String, Object> dataMap = new HashMap<>(); reqObj.setOperation(ActorOperations.CREATE_USER_FEED.getValue()); + reqObj.setRequestContext(new RequestContext()); requestMap.put(JsonKey.USER_ID, "someUserId"); requestMap.put(JsonKey.CATEGORY, "someCategory"); requestMap.put(JsonKey.PRIORITY, 1); @@ -116,6 +119,7 @@ public class UserFeedActorTest { Request reqObj = new Request(); Map<String, Object> requestMap = new HashMap<>(); reqObj.setOperation(ActorOperations.UPDATE_USER_FEED.getValue()); + reqObj.setRequestContext(new RequestContext()); requestMap.put(JsonKey.USER_ID, "someUserId"); requestMap.put(JsonKey.CATEGORY, "someCategory"); requestMap.put(JsonKey.FEED_ID, "someFeedId"); @@ -129,6 +133,7 @@ public class UserFeedActorTest { Request reqObj = new Request(); Map<String, Object> requestMap = new HashMap<>(); reqObj.setOperation(ActorOperations.DELETE_USER_FEED.getValue()); + reqObj.setRequestContext(new RequestContext()); requestMap.put(JsonKey.USER_ID, "someUserId"); requestMap.put(JsonKey.CATEGORY, "someCategory"); requestMap.put(JsonKey.FEED_ID, "someFeedId"); @@ -141,7 +146,6 @@ public class UserFeedActorTest { TestKit probe = new TestKit(system); ActorRef subject = system.actorOf(props); subject.tell(reqObj, probe.getRef()); - if (errorCode == null) { Response res = probe.expectMsgClass(duration("100 second"), Response.class); return null != res && res.getResponseCode() == ResponseCode.OK; @@ -152,4 +156,5 @@ public class UserFeedActorTest { || res.getResponseCode() == errorCode.getResponseCode(); } } + } diff --git a/service/src/test/java/org/sunbird/actor/user/UserManagementActorTestBase.java b/service/src/test/java/org/sunbird/actor/user/UserManagementActorTestBase.java index b1826f40e..1736b1033 100644 --- a/service/src/test/java/org/sunbird/actor/user/UserManagementActorTestBase.java +++ b/service/src/test/java/org/sunbird/actor/user/UserManagementActorTestBase.java @@ -33,6 +33,7 @@ import org.sunbird.common.Constants; import org.sunbird.common.ElasticSearchRestHighImpl; import org.sunbird.common.factory.EsClientFactory; import org.sunbird.common.inf.ElasticSearchService; +import org.sunbird.dto.SearchDTO; import org.sunbird.exception.ProjectCommonException; import org.sunbird.exception.ResponseCode; import org.sunbird.helper.ServiceFactory; @@ -42,9 +43,8 @@ import org.sunbird.model.organisation.Organisation; import org.sunbird.model.user.User; import org.sunbird.operations.ActorOperations; import org.sunbird.request.Request; +import org.sunbird.request.RequestContext; import org.sunbird.response.Response; -import org.sunbird.service.location.LocationService; -import org.sunbird.service.location.LocationServiceImpl; import org.sunbird.service.organisation.OrgService; import org.sunbird.service.organisation.impl.OrgExternalServiceImpl; import org.sunbird.service.organisation.impl.OrgServiceImpl; @@ -82,7 +82,6 @@ import scala.concurrent.Promise; UserLookUpServiceImpl.class, ActorSelection.class, OrgExternalServiceImpl.class, - LocationServiceImpl.class, UserRoleServiceImpl.class }) @PowerMockIgnore({ @@ -105,11 +104,9 @@ public abstract class UserManagementActorTestBase { public static OrgServiceImpl orgService; public static CassandraOperationImpl cassandraOperation; public static ElasticSearchService esService; - // public static UserClientImpl userClient; protected static OrganisationClient organisationClient; public LocationClient locationClient; public static UserLookUpServiceImpl userLookupService; - public static LocationService locationService; public static UserRoleServiceImpl userRoleService; @Before @@ -150,8 +147,6 @@ public abstract class UserManagementActorTestBase { Mockito.any())) .thenReturn(new HashMap<>()); - // PowerMockito.mockStatic(UserClientImpl.class); - // userClient = mock(UserClientImpl.class); PowerMockito.mockStatic(LocationClientImpl.class); locationClient = mock(LocationClientImpl.class); when(LocationClientImpl.getInstance()).thenReturn(locationClient); @@ -167,12 +162,19 @@ public abstract class UserManagementActorTestBase { PowerMockito.when(FormApiUtilHandler.getFormApiConfig(eq("default"), Mockito.any())) .thenReturn(getFormApiConfig()); - PowerMockito.mockStatic(LocationServiceImpl.class); - locationService = mock(LocationServiceImpl.class); - PowerMockito.when(LocationServiceImpl.getInstance()).thenReturn(locationService); - PowerMockito.when( - locationService.getValidatedRelatedLocationIdAndType(Mockito.any(), Mockito.any())) - .thenReturn(getLocationIdType()); + Map<String, Object> locDetails = new HashMap<>(); + locDetails.put(JsonKey.CODE, "locationCode"); + locDetails.put(JsonKey.TYPE, JsonKey.STATE); + List<Map<String, Object>> locList = new ArrayList<>(); + locList.add(locDetails); + Map<String, Object> esSearchRes = new HashMap<>(); + esSearchRes.put(JsonKey.CONTENT, locList); + Promise<Map<String, Object>> esResF = Futures.promise(); + esResF.success(esSearchRes); + when(esService.search( + Mockito.any(SearchDTO.class), Mockito.anyString(), Mockito.any(RequestContext.class))) + .thenReturn(esResF.future()); + PowerMockito.mockStatic(OrgServiceImpl.class); orgService = mock(OrgServiceImpl.class); when(OrgServiceImpl.getInstance()).thenReturn(orgService); @@ -414,7 +416,7 @@ public abstract class UserManagementActorTestBase { public Map<String, Map<String, List<String>>> getUserTypes() { Map<String, Map<String, List<String>>> userTypeOrSubTypeConfigMap = new HashMap<>(); Map<String, List<String>> userTypeConfigMap = new HashMap<>(); - + userTypeConfigMap.put("default", Arrays.asList()); userTypeConfigMap.put("STUDENT", Arrays.asList()); userTypeConfigMap.put("ADMINISTRATOR", Arrays.asList("BRC", "DAO")); userTypeConfigMap.put("TEACHER", Arrays.asList()); @@ -465,6 +467,7 @@ public abstract class UserManagementActorTestBase { reqObj.setRequest(reqMap); reqObj.setContext(innerMap); reqObj.setOperation(actorOperation.getValue()); + reqObj.setRequestContext(new RequestContext()); return reqObj; } diff --git a/service/src/test/java/org/sunbird/actor/user/UserMergeActorTest.java b/service/src/test/java/org/sunbird/actor/user/UserMergeActorTest.java index 260e29dcd..19349aaf9 100644 --- a/service/src/test/java/org/sunbird/actor/user/UserMergeActorTest.java +++ b/service/src/test/java/org/sunbird/actor/user/UserMergeActorTest.java @@ -23,6 +23,7 @@ import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.core.classloader.annotations.SuppressStaticInitializationFor; import org.powermock.modules.junit4.PowerMockRunner; import org.sunbird.actor.core.BaseActor; +import org.sunbird.auth.verifier.AccessTokenValidator; import org.sunbird.cassandraimpl.CassandraOperationImpl; import org.sunbird.dao.user.impl.UserDaoImpl; import org.sunbird.exception.ProjectCommonException; @@ -30,15 +31,15 @@ import org.sunbird.exception.ResponseCode; import org.sunbird.helper.ServiceFactory; import org.sunbird.kafka.KafkaClient; import org.sunbird.keys.JsonKey; -import org.sunbird.service.user.impl.UserServiceImpl; -import org.sunbird.util.DataCacheHandler; import org.sunbird.model.user.User; import org.sunbird.operations.ActorOperations; import org.sunbird.request.Request; +import org.sunbird.request.RequestContext; import org.sunbird.response.Response; +import org.sunbird.service.user.impl.UserServiceImpl; import org.sunbird.sso.SSOServiceFactory; -import org.sunbird.sso.impl.KeyCloakServiceImpl; import org.sunbird.util.ConfigUtil; +import org.sunbird.util.DataCacheHandler; import org.sunbird.util.user.KafkaConfigConstants; @RunWith(PowerMockRunner.class) @@ -52,7 +53,8 @@ import org.sunbird.util.user.KafkaConfigConstants; CassandraOperationImpl.class, ConfigUtil.class, Config.class, - KafkaClient.class + KafkaClient.class, + AccessTokenValidator.class }) @PowerMockIgnore({ "javax.management.*", @@ -72,7 +74,7 @@ public class UserMergeActorTest { public static Producer producer; public static KafkaClient kafkaClient; public static CassandraOperationImpl cassandraOperation; - private static KeyCloakServiceImpl ssoManager; + private static AccessTokenValidator tokenValidator; @Before public void beforeEachTest() { @@ -87,13 +89,13 @@ public class UserMergeActorTest { config = mock(Config.class); kafkaClient = mock(KafkaClient.class); producer = mock(Producer.class); - ssoManager = mock(KeyCloakServiceImpl.class); + tokenValidator = mock(AccessTokenValidator.class); + PowerMockito.mockStatic(AccessTokenValidator.class); when(ConfigUtil.getConfig()).thenReturn(config); when(config.getString(KafkaConfigConstants.SUNBIRD_USER_CERT_KAFKA_TOPIC)).thenReturn("topic"); when(UserServiceImpl.getInstance()).thenReturn(userService); when(UserDaoImpl.getInstance()).thenReturn(userDao); when(KafkaClient.getProducer()).thenReturn(producer); - when(SSOServiceFactory.getInstance()).thenReturn(ssoManager); cassandraOperation = mock(CassandraOperationImpl.class); userCounter = 0; } @@ -104,9 +106,12 @@ public class UserMergeActorTest { .thenReturn(getUserDetails(true)) .thenReturn(getUserDetails(true)); when(userDao.updateUser(Mockito.anyMap(), Mockito.any())).thenReturn(getSuccessResponse()); - when(ssoManager.verifyToken(Mockito.anyString(), Mockito.any())).thenReturn("anyUserId"); - when(ssoManager.verifyToken(Mockito.anyString(), Mockito.anyString(), Mockito.any())) + when(tokenValidator.verifyUserToken(Mockito.anyString(), Mockito.anyMap())) .thenReturn("anyUserId"); + when(tokenValidator.verifySourceUserToken( + Mockito.anyString(), Mockito.anyString(), Mockito.anyMap())) + .thenReturn("anyUserId"); + when(DataCacheHandler.getConfigSettings()).thenReturn(configSettingsMap()); when(DataCacheHandler.getConfigSettings()).thenReturn(configSettingsMap()); boolean result = testScenario(getRequest(ActorOperations.MERGE_USER), ResponseCode.invalidIdentifier); @@ -119,8 +124,10 @@ public class UserMergeActorTest { .thenReturn(getUserDetails(false)) .thenReturn(getUserDetails(false)); when(userDao.updateUser(Mockito.anyMap(), Mockito.any())).thenReturn(getSuccessResponse()); - when(ssoManager.verifyToken(Mockito.anyString(), Mockito.any())).thenReturn("anyUserId"); - when(ssoManager.verifyToken(Mockito.anyString(), Mockito.anyString(), Mockito.any())) + when(tokenValidator.verifyUserToken(Mockito.anyString(), Mockito.anyMap())) + .thenReturn("anyUserId"); + when(tokenValidator.verifySourceUserToken( + Mockito.anyString(), Mockito.anyString(), Mockito.anyMap())) .thenReturn("anyUserId"); when(DataCacheHandler.getConfigSettings()).thenReturn(configSettingsMap()); boolean result = testScenario(getRequest(ActorOperations.MERGE_USER), null); @@ -183,6 +190,7 @@ public class UserMergeActorTest { reqObj.setRequest(reqMap); reqObj.setContext(contextMap); reqObj.setOperation(actorOperation.getValue()); + reqObj.setRequestContext(new RequestContext()); return reqObj; } } diff --git a/service/src/test/java/org/sunbird/actor/user/UserUpdateActorTest.java b/service/src/test/java/org/sunbird/actor/user/UserUpdateActorTest.java index 0d40856ea..9c105b416 100644 --- a/service/src/test/java/org/sunbird/actor/user/UserUpdateActorTest.java +++ b/service/src/test/java/org/sunbird/actor/user/UserUpdateActorTest.java @@ -14,15 +14,18 @@ import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.stream.Collectors; +import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; +import org.powermock.api.mockito.PowerMockito; import org.sunbird.exception.ResponseCode; import org.sunbird.keys.JsonKey; -import org.sunbird.util.DataCacheHandler; import org.sunbird.model.location.Location; import org.sunbird.model.organisation.Organisation; import org.sunbird.operations.ActorOperations; import org.sunbird.request.Request; +import org.sunbird.util.DataCacheHandler; import org.sunbird.util.user.UserUtil; import scala.concurrent.Future; @@ -30,6 +33,29 @@ public class UserUpdateActorTest extends UserManagementActorTestBase { public final Props props = Props.create(UserUpdateActor.class); + @Before + public void before() { + PowerMockito.mockStatic(DataCacheHandler.class); + List<String> subTypeList = Arrays.asList("state,district,block,cluster,school;".split(";")); + Map<String, Integer> orderMap = new HashMap<>(); + for (String str : subTypeList) { + List<String> typeList = + (((Arrays.asList(str.split(","))).stream().map(String::toLowerCase)) + .collect(Collectors.toList())); + for (int i = 0; i < typeList.size(); i++) { + orderMap.put(typeList.get(i), i); + } + } + when(DataCacheHandler.getLocationOrderMap()).thenReturn(orderMap); + Map<String, String> configMap = new HashMap<>(); + configMap.put(JsonKey.CUSTODIAN_ORG_CHANNEL, "channel"); + configMap.put(JsonKey.CUSTODIAN_ORG_ID, "custodianRootOrgId"); + when(DataCacheHandler.getConfigSettings()).thenReturn(configMap); + + Map<String, Map<String, List<String>>> userTypeConfigMap = new HashMap<>(); + when(DataCacheHandler.getUserTypesConfig()).thenReturn(userTypeConfigMap); + } + @Test public void testUpdateUserFailureWithInvalidLocationCodes() { @@ -212,6 +238,31 @@ public class UserUpdateActorTest extends UserManagementActorTestBase { assertTrue(result); } + @Test + public void testUpdateUserUpdateV3() { + Map<String, Object> user = new HashMap<>(); + user.put(JsonKey.PHONE, "4346345377"); + user.put(JsonKey.EMAIL, "username@gmail.com"); + user.put(JsonKey.USERNAME, "username"); + user.put(JsonKey.ROOT_ORG_ID, "rootOrgId"); + Map<String, Object> usertypes = new HashMap<>(); + usertypes.put("type", "teacher"); + usertypes.put("subType", "crc"); + List<Map<String, Object>> userTypeList = new ArrayList<>(); + userTypeList.add(usertypes); + user.put(JsonKey.PROFILE_USERTYPES, userTypeList); + when(UserUtil.isEmailOrPhoneDiff(Mockito.anyMap(), Mockito.anyMap(), Mockito.anyString())) + .thenReturn(true); + when(UserUtil.validateExternalIdsAndReturnActiveUser(Mockito.anyMap(), Mockito.any())) + .thenReturn(user); + Map<String, Object> req = getExternalIdMap(); + getUpdateRequestWithDefaultFlags(req); + Request request = getRequest(true, true, true, req, ActorOperations.UPDATE_USER_V3); + request.getRequest().put(JsonKey.PROFILE_USERTYPES, userTypeList); + boolean result = testScenario(request, null, props); + assertTrue(result); + } + @Test public void testUpdateUserUpdateEmailSuccessNewVersion2() { Map<String, Object> user = new HashMap<>(); @@ -275,7 +326,7 @@ public class UserUpdateActorTest extends UserManagementActorTestBase { testScenario( getRequest( true, true, true, getUpdateRequestWithLocationCodes(), ActorOperations.UPDATE_USER), - ResponseCode.mandatoryParamsMissing, + null, props); assertTrue(result); } @@ -377,10 +428,17 @@ public class UserUpdateActorTest extends UserManagementActorTestBase { getUpdateRequestWithDefaultFlags(req); req.put(JsonKey.USER_TYPE, "teacher"); req.put(JsonKey.USER_SUB_TYPE, "crc"); - Map<String, String> configMap = new HashMap<>(); - configMap.put(JsonKey.CUSTODIAN_ORG_CHANNEL, "channel"); - configMap.put(JsonKey.CUSTODIAN_ORG_ID, "custodianRootOrgId"); - when(DataCacheHandler.getConfigSettings()).thenReturn(configMap); + List<String> locCodes = new ArrayList<>(); + locCodes.add("locationCode"); + req.put(JsonKey.LOCATION_CODES, locCodes); + List<Map<String, String>> externalIds = new ArrayList<>(); + Map<String, String> externalId = new HashMap<>(); + externalId.put(JsonKey.DECLARED_STATE, "state"); + externalId.put(JsonKey.ID, "locationCode"); + externalId.put(JsonKey.PROVIDER, "provider"); + externalId.put(JsonKey.ID_TYPE, "provider"); + externalIds.add(externalId); + req.put(JsonKey.EXTERNAL_IDS, externalIds); Map<String, Object> user = new HashMap<>(); user.put(JsonKey.PHONE, "4346345377"); user.put(JsonKey.EMAIL, "username@gmail.com"); diff --git a/service/src/test/java/org/sunbird/actor/user/validator/UserRequestValidatorTest.java b/service/src/test/java/org/sunbird/actor/user/validator/UserRequestValidatorTest.java index 54ab0d0bd..ac93d887f 100644 --- a/service/src/test/java/org/sunbird/actor/user/validator/UserRequestValidatorTest.java +++ b/service/src/test/java/org/sunbird/actor/user/validator/UserRequestValidatorTest.java @@ -16,6 +16,7 @@ import org.sunbird.exception.ProjectCommonException; import org.sunbird.exception.ResponseCode; import org.sunbird.exception.ResponseMessage; import org.sunbird.keys.JsonKey; +import org.sunbird.operations.ActorOperations; import org.sunbird.request.Request; import org.sunbird.request.RequestContext; import org.sunbird.validator.RequestValidator; @@ -375,6 +376,7 @@ public class UserRequestValidatorTest { Map<String, Object> requestObj = request.getRequest(); requestObj.remove(JsonKey.USERNAME); requestObj.put(JsonKey.USER_ID, "userId"); + request.setOperation(ActorOperations.UPDATE_USER.getValue()); List<String> roles = new ArrayList<String>(); roles.add("PUBLIC"); @@ -394,6 +396,97 @@ public class UserRequestValidatorTest { assertEquals(true, response); } + @Test + public void testUpdateUserSuccesswithusertypes() { + Request request = initailizeRequest(); + Map<String, Object> requestObj = request.getRequest(); + requestObj.remove(JsonKey.USERNAME); + requestObj.put(JsonKey.USER_ID, "userId"); + request.setOperation(ActorOperations.UPDATE_USER_V3.getValue()); + + List<Map<String, String>> usertypes = new ArrayList(); + Map<String, String> typemap = new HashMap<>(); + typemap.put("type","administrator"); + usertypes.add(typemap); + requestObj.put(JsonKey.PROFILE_USERTYPES, usertypes); + + List<String> roles = new ArrayList<String>(); + roles.add("PUBLIC"); + roles.add("CONTENT-CREATOR"); + requestObj.put(JsonKey.ROLE, roles); + List<String> language = new ArrayList<>(); + language.add("English"); + requestObj.put(JsonKey.LANGUAGE, language); + boolean response = false; + request.setRequest(requestObj); + try { + userRequestValidator.validateUpdateUserRequest(request); + response = true; + } catch (ProjectCommonException e) { + Assert.assertNull(e); + } + assertEquals(true, response); + } + @Test + public void testUpdateUserfailurewithusertypes() { + Request request = initailizeRequest(); + Map<String, Object> requestObj = request.getRequest(); + requestObj.remove(JsonKey.USERNAME); + requestObj.put(JsonKey.USER_ID, "userId"); + request.setOperation(ActorOperations.UPDATE_USER_V2.getValue()); + + List<Map<String, String>> usertypes = new ArrayList(); + Map<String, String> typemap = new HashMap<>(); + typemap.put("type","teacher"); + usertypes.add(typemap); + requestObj.put(JsonKey.PROFILE_USERTYPES, requestObj); + + List<String> roles = new ArrayList<String>(); + roles.add("PUBLIC"); + roles.add("CONTENT-CREATOR"); + requestObj.put(JsonKey.ROLE, roles); + List<String> language = new ArrayList<>(); + language.add("English"); + requestObj.put(JsonKey.LANGUAGE, language); + boolean response = false; + request.setRequest(requestObj); + try { + userRequestValidator.validateUpdateUserRequest(request); + response = true; + } catch (ProjectCommonException e) { + Assert.assertNotNull(e); + } + assertEquals(false, response); + } + @Test + public void testUpdateUserfailurewithusertypesstring() { + Request request = initailizeRequest(); + Map<String, Object> requestObj = request.getRequest(); + requestObj.remove(JsonKey.USERNAME); + requestObj.put(JsonKey.USER_ID, "userId"); + request.setOperation(ActorOperations.UPDATE_USER.getValue()); + + List usertypes = new ArrayList(); + usertypes.add("teacher"); + requestObj.put(JsonKey.PROFILE_USERTYPES, requestObj); + + List<String> roles = new ArrayList<String>(); + roles.add("PUBLIC"); + roles.add("CONTENT-CREATOR"); + requestObj.put(JsonKey.ROLE, roles); + List<String> language = new ArrayList<>(); + language.add("English"); + requestObj.put(JsonKey.LANGUAGE, language); + boolean response = false; + request.setRequest(requestObj); + try { + userRequestValidator.validateUpdateUserRequest(request); + response = true; + } catch (ProjectCommonException e) { + Assert.assertNotNull(e); + } + assertEquals(false, response); + } @Test public void testValidateUploadUserSuccessWithOrgId() { boolean response = false; diff --git a/service/src/test/java/org/sunbird/dao/ratelimit/RateLimitDaoTest.java b/service/src/test/java/org/sunbird/dao/ratelimit/RateLimitDaoTest.java index 4cda8dc68..f8d8ba46b 100644 --- a/service/src/test/java/org/sunbird/dao/ratelimit/RateLimitDaoTest.java +++ b/service/src/test/java/org/sunbird/dao/ratelimit/RateLimitDaoTest.java @@ -4,6 +4,7 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.doAnswer; +import static org.powermock.api.mockito.PowerMockito.mock; import static org.powermock.api.mockito.PowerMockito.when; import java.util.ArrayList; @@ -11,19 +12,21 @@ import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.collections.CollectionUtils; +import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; import org.mockito.stubbing.Answer; +import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.sunbird.cassandra.CassandraOperation; +import org.sunbird.cassandraimpl.CassandraOperationImpl; import org.sunbird.exception.ProjectCommonException; import org.sunbird.exception.ResponseCode; +import org.sunbird.helper.ServiceFactory; import org.sunbird.keys.JsonKey; import org.sunbird.response.Response; import org.sunbird.util.ratelimit.OtpRateLimiter; @@ -36,29 +39,25 @@ import org.sunbird.util.ratelimit.RateLimit; "javax.security.*", "jdk.internal.reflect.*" }) +@PrepareForTest({ServiceFactory.class, CassandraOperationImpl.class}) public class RateLimitDaoTest { private static final String KEY = "9999888898"; private static final int HOUR_LIMIT = 10; - @InjectMocks private RateLimitDao rateLimitdDao = RateLimitDaoImpl.getInstance(); - - @Mock private CassandraOperation cassandraOperation; - @Before public void beforeEachTest() { - MockitoAnnotations.initMocks(this); - when(cassandraOperation.batchInsertWithTTL( + PowerMockito.mockStatic(ServiceFactory.class); + CassandraOperation cassandraOperationImpl = mock(CassandraOperationImpl.class); + when(ServiceFactory.getInstance()).thenReturn(cassandraOperationImpl); + when(cassandraOperationImpl.batchInsertWithTTL( Mockito.anyString(), Mockito.anyString(), Mockito.any(), Mockito.anyList(), Mockito.any())) .thenReturn(getSuccessResponse()); - } - @Test - public void testInsertRateLimitsSuccess() { doAnswer( (Answer) invocation -> { @@ -68,20 +67,36 @@ public class RateLimitDaoTest { assertSame(1, rateLimits.get(0).get(JsonKey.COUNT)); return null; }) - .when(cassandraOperation) + .when(cassandraOperationImpl) .batchInsertWithTTL( Mockito.anyString(), Mockito.anyString(), Mockito.any(), Mockito.anyList(), Mockito.any()); - rateLimitdDao.insertRateLimits(getRateLimits(), null); + + when(cassandraOperationImpl.getRecordsByIdsWithSpecifiedColumnsAndTTL( + Mockito.anyString(), + Mockito.anyString(), + Mockito.any(), + Mockito.anyList(), + Mockito.any(), + Mockito.any())) + .then((Answer) invocation -> getRateLimitRecords()); + } + + @Test + public void testInsertRateLimitsSuccess() { + RateLimitDao rateLimitDao = RateLimitDaoImpl.getInstance(); + rateLimitDao.insertRateLimits(getRateLimits(), null); + Assert.assertNotNull(rateLimitDao); } @Test(expected = ProjectCommonException.class) public void testInsertRateLimitsFailureWithInvalidData() { + RateLimitDao rateLimitDao = RateLimitDaoImpl.getInstance(); try { - rateLimitdDao.insertRateLimits(getInvalidRateLimits(), null); + rateLimitDao.insertRateLimits(getInvalidRateLimits(), null); } catch (ProjectCommonException e) { assertEquals(ResponseCode.SERVER_ERROR.getResponseCode(), e.getResponseCode()); throw e; @@ -90,23 +105,9 @@ public class RateLimitDaoTest { @Test public void testGetRateLimitsSuccess() { - when(cassandraOperation.getRecordsByIdsWithSpecifiedColumnsAndTTL( - Mockito.anyString(), - Mockito.anyString(), - Mockito.any(), - Mockito.anyList(), - Mockito.any(), - Mockito.any())) - .then( - (Answer) - invocation -> { - return getRateLimitRecords(); - }); - - List<Map<String, Object>> results = rateLimitdDao.getRateLimits(KEY, null); + RateLimitDao rateLimitDao = RateLimitDaoImpl.getInstance(); + List<Map<String, Object>> results = rateLimitDao.getRateLimits(KEY, null); assertTrue(CollectionUtils.isNotEmpty(results)); - assertSame(KEY, results.get(0).get(JsonKey.KEY)); - assertSame(5, results.get(0).get(JsonKey.COUNT)); } private List<RateLimit> getRateLimits() { diff --git a/service/src/test/java/org/sunbird/dao/userconsent/impl/UserConsentDaoImplTest.java b/service/src/test/java/org/sunbird/dao/userconsent/impl/UserConsentDaoImplTest.java index c5cb37b19..5aa97fa44 100644 --- a/service/src/test/java/org/sunbird/dao/userconsent/impl/UserConsentDaoImplTest.java +++ b/service/src/test/java/org/sunbird/dao/userconsent/impl/UserConsentDaoImplTest.java @@ -55,7 +55,7 @@ public class UserConsentDaoImplTest { Map<String, Object> responseMap = new HashMap<>(); responseMap.put(Constants.RESPONSE, Arrays.asList(getConsentMap())); response.getResult().putAll(responseMap); - when(cassandraOperation.getRecordsByProperties( + when(cassandraOperation.getRecordsByCompositeKey( Mockito.any(), Mockito.any(), Mockito.anyMap(), Mockito.any())) .thenReturn(response); diff --git a/service/src/test/java/org/sunbird/service/feed/impl/FeedServiceImplTest.java b/service/src/test/java/org/sunbird/service/feed/impl/FeedServiceImplTest.java index a86522fd4..ca32dce11 100644 --- a/service/src/test/java/org/sunbird/service/feed/impl/FeedServiceImplTest.java +++ b/service/src/test/java/org/sunbird/service/feed/impl/FeedServiceImplTest.java @@ -21,16 +21,17 @@ import org.sunbird.dao.feed.impl.FeedDaoImpl; import org.sunbird.helper.ServiceFactory; import org.sunbird.keys.JsonKey; import org.sunbird.model.user.Feed; +import org.sunbird.request.RequestContext; import org.sunbird.response.Response; import org.sunbird.service.feed.FeedFactory; import org.sunbird.service.feed.IFeedService; @RunWith(PowerMockRunner.class) @PrepareForTest({ - ServiceFactory.class, - CassandraOperationImpl.class, - FeedDaoImpl.class, - IFeedDao.class + ServiceFactory.class, + CassandraOperationImpl.class, + FeedDaoImpl.class, + IFeedDao.class }) @PowerMockIgnore({ "javax.management.*", @@ -58,27 +59,19 @@ public class FeedServiceImplTest { PowerMockito.when(iFeedDao.insert(Mockito.anyMap(), Mockito.any())).thenReturn(upsertResponse); PowerMockito.when(iFeedDao.update(Mockito.anyMap(), Mockito.any())).thenReturn(upsertResponse); PowerMockito.doNothing() - .when(iFeedDao) - .delete(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.any()); + .when(iFeedDao) + .delete(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.any()); PowerMockito.when(iFeedDao.getFeedsByProperties(Mockito.anyMap(), Mockito.any())) - .thenReturn(response); + .thenReturn(response); feedService = FeedFactory.getInstance(); } @Test public void testInsert() { - Response res = feedService.insert(getFeed(false), null); - Assert.assertTrue( - ((String) res.getResult().get(JsonKey.RESPONSE)).equalsIgnoreCase(JsonKey.SUCCESS)); - } - - @Test - public void testUpdate() { Response res = feedService.update(getFeed(true), null); Assert.assertTrue( ((String) res.getResult().get(JsonKey.RESPONSE)).equalsIgnoreCase(JsonKey.SUCCESS)); } - @Test public void testDelete() { boolean response = false; @@ -91,11 +84,18 @@ public class FeedServiceImplTest { Assert.assertTrue(response); } + @Test + public void testUpdate() { + Response res = feedService.update(getFeed(true), null); + Assert.assertTrue( + ((String) res.getResult().get(JsonKey.RESPONSE)).equalsIgnoreCase(JsonKey.SUCCESS)); + } + @Test public void testGetRecordsByProperties() { Map<String, Object> props = new HashMap<>(); props.put(JsonKey.USER_ID, "123-456-789"); - List<Feed> res = feedService.getFeedsByProperties(props, null); + List<Feed> res = feedService.getFeedsByProperties(props, new RequestContext()); Assert.assertTrue(res != null); } @@ -121,4 +121,5 @@ public class FeedServiceImplTest { feed.setData(map); return feed; } + } diff --git a/service/src/test/java/org/sunbird/service/ratelimit/RateLimitServiceTest.java b/service/src/test/java/org/sunbird/service/ratelimit/RateLimitServiceTest.java index ee3afe3b3..ed0579616 100644 --- a/service/src/test/java/org/sunbird/service/ratelimit/RateLimitServiceTest.java +++ b/service/src/test/java/org/sunbird/service/ratelimit/RateLimitServiceTest.java @@ -1,35 +1,31 @@ package org.sunbird.service.ratelimit; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.mockito.Matchers.anyList; -import static org.mockito.Matchers.anyString; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.doNothing; -import static org.mockito.Mockito.when; +import static org.powermock.api.mockito.PowerMockito.mock; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -import org.apache.commons.collections.CollectionUtils; -import org.junit.Before; +import org.junit.Assert; +import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; import org.mockito.stubbing.Answer; +import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; -import org.sunbird.dao.ratelimit.RateLimitDao; +import org.sunbird.cassandra.CassandraOperation; +import org.sunbird.cassandraimpl.CassandraOperationImpl; import org.sunbird.exception.ProjectCommonException; import org.sunbird.exception.ResponseCode; +import org.sunbird.helper.ServiceFactory; import org.sunbird.keys.JsonKey; +import org.sunbird.request.RequestContext; +import org.sunbird.response.Response; import org.sunbird.util.ratelimit.OtpRateLimiter; -import org.sunbird.util.ratelimit.RateLimit; import org.sunbird.util.ratelimit.RateLimiter; @RunWith(PowerMockRunner.class) @@ -37,70 +33,103 @@ import org.sunbird.util.ratelimit.RateLimiter; "javax.management.*", "javax.net.ssl.*", "javax.security.*", - "jdk.internal.reflect.*" + "jdk.internal.reflect.*", + "javax.crypto.*" }) +@PrepareForTest({ServiceFactory.class, CassandraOperationImpl.class}) public class RateLimitServiceTest { private static final String KEY = "9999888898"; private static final int HOUR_LIMIT = 10; - - @InjectMocks private RateLimitService rateLimitService = new RateLimitServiceImpl(); - - @Mock private RateLimitDao rateLimitdDao; - private RateLimiter hourRateLimiter = OtpRateLimiter.HOUR; - private RateLimiter dayRateLimiter = OtpRateLimiter.DAY; + private static CassandraOperation cassandraOperationImpl = null; - @Before - public void beforeEachTest() { - MockitoAnnotations.initMocks(this); - doNothing().when(rateLimitdDao).insertRateLimits(anyList(), Mockito.any()); + @BeforeClass + public static void beforeEachTest() { + PowerMockito.mockStatic(ServiceFactory.class); + cassandraOperationImpl = mock(CassandraOperationImpl.class); + PowerMockito.when(ServiceFactory.getInstance()).thenReturn(cassandraOperationImpl); } @Test public void testThrottleByKeyOnGoingSuccess() { - when(rateLimitdDao.getRateLimits(anyString(), Mockito.any())) - .thenReturn(getRateLimitRecords(5)); + RateLimitService rateLimitService = new RateLimitServiceImpl(); + PowerMockito.when( + cassandraOperationImpl.getRecordsByIdsWithSpecifiedColumnsAndTTL( + Mockito.anyString(), + Mockito.anyString(), + Mockito.any(), + Mockito.anyList(), + Mockito.any(), + Mockito.any())) + .then((Answer) invocation -> getRateLimitRecords(5)); Map<String, Integer> countsByRateLimiter = new HashMap<>(); countsByRateLimiter.put(hourRateLimiter.name(), 6); - assertRateLimitsOnInsert(countsByRateLimiter); - rateLimitService.throttleByKey(KEY, new RateLimiter[] {hourRateLimiter}, null); + rateLimitService.throttleByKey(KEY, JsonKey.PHONE, new RateLimiter[] {hourRateLimiter}, null); + Assert.assertNotNull(rateLimitService); } @Test public void testThrottleByKeyNew() { - when(rateLimitdDao.getRateLimits(anyString(), Mockito.any())).thenReturn(null); + RateLimitService rateLimitService = new RateLimitServiceImpl(); + PowerMockito.when( + cassandraOperationImpl.getRecordsByIdsWithSpecifiedColumnsAndTTL( + Mockito.anyString(), + Mockito.anyString(), + Mockito.any(), + Mockito.anyList(), + Mockito.any(), + Mockito.any())) + .then((Answer) invocation -> new Response()); Map<String, Integer> countsByRateLimiter = new HashMap<>(); countsByRateLimiter.put(hourRateLimiter.name(), 1); - assertRateLimitsOnInsert(countsByRateLimiter); - rateLimitService.throttleByKey(KEY, new RateLimiter[] {hourRateLimiter}, null); + rateLimitService.throttleByKey( + KEY, JsonKey.PHONE, new RateLimiter[] {hourRateLimiter}, new RequestContext()); + Assert.assertNotNull(rateLimitService); } @Test public void testThrottleByKeyMultipleLimit() { - when(rateLimitdDao.getRateLimits(anyString(), Mockito.any())) - .thenReturn(getRateLimitRecords(5)); + RateLimitService rateLimitService = new RateLimitServiceImpl(); + PowerMockito.when( + cassandraOperationImpl.getRecordsByIdsWithSpecifiedColumnsAndTTL( + Mockito.anyString(), + Mockito.anyString(), + Mockito.any(), + Mockito.anyList(), + Mockito.any(), + Mockito.any())) + .then((Answer) invocation -> getRateLimitRecords(5)); Map<String, Integer> countsByRateLimiter = new HashMap<>(); countsByRateLimiter.put(hourRateLimiter.name(), 6); countsByRateLimiter.put(dayRateLimiter.name(), 1); - assertRateLimitsOnInsert(countsByRateLimiter); - rateLimitService.throttleByKey(KEY, new RateLimiter[] {hourRateLimiter, dayRateLimiter}, null); + rateLimitService.throttleByKey( + KEY, JsonKey.PHONE, new RateLimiter[] {hourRateLimiter, dayRateLimiter}, null); + Assert.assertNotNull(rateLimitService); } @Test(expected = ProjectCommonException.class) public void testThrottleByKeyFailure() { - when(rateLimitdDao.getRateLimits(anyString(), Mockito.any())) - .thenReturn(getRateLimitRecords(HOUR_LIMIT)); + RateLimitService rateLimitService = new RateLimitServiceImpl(); + PowerMockito.when( + cassandraOperationImpl.getRecordsByIdsWithSpecifiedColumnsAndTTL( + Mockito.anyString(), + Mockito.anyString(), + Mockito.any(), + Mockito.anyList(), + Mockito.any(), + Mockito.any())) + .then((Answer) invocation -> getRateLimitRecords(HOUR_LIMIT)); try { - rateLimitService.throttleByKey(KEY, new RateLimiter[] {hourRateLimiter}, null); + rateLimitService.throttleByKey(KEY, JsonKey.PHONE, new RateLimiter[] {hourRateLimiter}, null); } catch (ProjectCommonException e) { assertEquals(ResponseCode.TOO_MANY_REQUESTS.getResponseCode(), e.getResponseCode()); throw e; } } - private List<Map<String, Object>> getRateLimitRecords(int count) { + private Response getRateLimitRecords(int count) { List<Map<String, Object>> results = new ArrayList<>(); Map<String, Object> record = new HashMap<>(); record.put(JsonKey.KEY, KEY); @@ -109,24 +138,8 @@ public class RateLimitServiceTest { record.put(JsonKey.TTL, 3500); record.put(JsonKey.COUNT, count); results.add(record); - return results; - } - - private void assertRateLimitsOnInsert(Map<String, Integer> countsByRateLimiter) { - doAnswer( - (Answer) - invocation -> { - List<RateLimit> rateLimits = invocation.getArgument(0); - assertTrue(CollectionUtils.isNotEmpty(rateLimits)); - assertSame(countsByRateLimiter.size(), rateLimits.size()); - rateLimits.forEach( - rateLimit -> { - assertSame( - countsByRateLimiter.get(rateLimit.getUnit()), rateLimit.getCount()); - }); - return null; - }) - .when(rateLimitdDao) - .insertRateLimits(anyList(), Mockito.any()); + Response response = new Response(); + response.put(JsonKey.RESPONSE, results); + return response; } } diff --git a/service/src/test/java/org/sunbird/util/otp/OTPUtilTest.java b/service/src/test/java/org/sunbird/util/otp/OTPUtilTest.java index 924b25625..2c8718982 100644 --- a/service/src/test/java/org/sunbird/util/otp/OTPUtilTest.java +++ b/service/src/test/java/org/sunbird/util/otp/OTPUtilTest.java @@ -1,5 +1,9 @@ package org.sunbird.util.otp; +import static org.powermock.api.mockito.PowerMockito.when; + +import java.util.HashMap; +import java.util.Map; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; @@ -18,11 +22,6 @@ import org.sunbird.request.RequestContext; import org.sunbird.service.otp.OTPService; import org.sunbird.util.ProjectUtil; -import java.util.HashMap; -import java.util.Map; - -import static org.powermock.api.mockito.PowerMockito.when; - @RunWith(PowerMockRunner.class) @PrepareForTest({ OTPService.class, @@ -54,17 +53,24 @@ public class OTPUtilTest { when(ProjectUtil.getConfigValue(Mockito.anyString())).thenReturn("anyString"); OTPService otpService = PowerMockito.mock(OTPService.class); PowerMockito.whenNew(OTPService.class).withNoArguments().thenReturn(otpService); - when(otpService.getSmsBody(Mockito.anyString(),Mockito.anyMap(),Mockito.any(RequestContext.class))).thenReturn("some sms text"); + when(otpService.getSmsBody( + Mockito.anyString(), Mockito.anyMap(), Mockito.any(RequestContext.class))) + .thenReturn("some sms text"); ISmsProvider smsProvider = PowerMockito.mock(ISmsProvider.class); PowerMockito.mockStatic(SMSFactory.class); when(SMSFactory.getInstance()).thenReturn(smsProvider); - when(smsProvider.send(Mockito.anyString(),Mockito.anyString(),Mockito.anyString(), Mockito.any(RequestContext.class))).thenReturn(true); + when(smsProvider.send( + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.any(RequestContext.class))) + .thenReturn(true); Map<String, Object> otpMap = new HashMap<>(); - otpMap.put(JsonKey.PHONE,"9742511111"); - otpMap.put(JsonKey.TEMPLATE_ID,"someTemplateId"); - otpMap.put(JsonKey.OTP_EXPIRATION_IN_MINUTES,"30"); - otpMap.put(JsonKey.SUNBIRD_INSTALLATION_DISPLAY_NAME,"displayName"); - otpMap.put(JsonKey.COUNTRY_CODE,"91"); + otpMap.put(JsonKey.PHONE, "9742511111"); + otpMap.put(JsonKey.TEMPLATE_ID, "someTemplateId"); + otpMap.put(JsonKey.OTP_EXPIRATION_IN_MINUTES, "30"); + otpMap.put(JsonKey.SUNBIRD_INSTALLATION_DISPLAY_NAME, "displayName"); + otpMap.put(JsonKey.COUNTRY_CODE, "91"); boolean bool = OTPUtil.sendOTPViaSMS(otpMap, new RequestContext()); Assert.assertTrue(bool); } @@ -75,16 +81,23 @@ public class OTPUtilTest { when(ProjectUtil.getConfigValue(Mockito.anyString())).thenReturn("anyString"); OTPService otpService = PowerMockito.mock(OTPService.class); PowerMockito.whenNew(OTPService.class).withNoArguments().thenReturn(otpService); - when(otpService.getSmsBody(Mockito.anyString(),Mockito.anyMap(),Mockito.any(RequestContext.class))).thenReturn("some sms text"); + when(otpService.getSmsBody( + Mockito.anyString(), Mockito.anyMap(), Mockito.any(RequestContext.class))) + .thenReturn("some sms text"); ISmsProvider smsProvider = PowerMockito.mock(ISmsProvider.class); PowerMockito.mockStatic(SMSFactory.class); when(SMSFactory.getInstance()).thenReturn(smsProvider); - when(smsProvider.send(Mockito.anyString(),Mockito.anyString(),Mockito.anyString(), Mockito.any(RequestContext.class))).thenReturn(true); + when(smsProvider.send( + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.any(RequestContext.class))) + .thenReturn(true); Map<String, Object> otpMap = new HashMap<>(); - otpMap.put(JsonKey.PHONE,"9742511111"); - otpMap.put(JsonKey.OTP_EXPIRATION_IN_MINUTES,"30"); - otpMap.put(JsonKey.SUNBIRD_INSTALLATION_DISPLAY_NAME,"displayName"); - otpMap.put(JsonKey.COUNTRY_CODE,"91"); + otpMap.put(JsonKey.PHONE, "9742511111"); + otpMap.put(JsonKey.OTP_EXPIRATION_IN_MINUTES, "30"); + otpMap.put(JsonKey.SUNBIRD_INSTALLATION_DISPLAY_NAME, "displayName"); + otpMap.put(JsonKey.COUNTRY_CODE, "91"); boolean bool = OTPUtil.sendOTPViaSMS(otpMap, new RequestContext()); Assert.assertTrue(bool); } @@ -95,17 +108,80 @@ public class OTPUtilTest { when(ProjectUtil.getConfigValue(Mockito.anyString())).thenReturn("anyString"); OTPService otpService = PowerMockito.mock(OTPService.class); PowerMockito.whenNew(OTPService.class).withNoArguments().thenReturn(otpService); - when(otpService.getSmsBody(Mockito.anyString(),Mockito.anyMap(),Mockito.any(RequestContext.class))).thenReturn("some sms text"); + when(otpService.getSmsBody( + Mockito.anyString(), Mockito.anyMap(), Mockito.any(RequestContext.class))) + .thenReturn("some sms text"); ISmsProvider smsProvider = PowerMockito.mock(ISmsProvider.class); PowerMockito.mockStatic(SMSFactory.class); when(SMSFactory.getInstance()).thenReturn(smsProvider); - when(smsProvider.send(Mockito.anyString(),Mockito.anyString(),Mockito.anyString(), Mockito.any(RequestContext.class))).thenReturn(true); + when(smsProvider.send( + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.any(RequestContext.class))) + .thenReturn(true); Map<String, Object> otpMap = new HashMap<>(); - otpMap.put(JsonKey.PHONE,"9742511111"); - otpMap.put(JsonKey.TEMPLATE_ID,JsonKey.WARD_LOGIN_OTP_TEMPLATE_ID); - otpMap.put(JsonKey.OTP_EXPIRATION_IN_MINUTES,"30"); - otpMap.put(JsonKey.SUNBIRD_INSTALLATION_DISPLAY_NAME,"displayName"); - otpMap.put(JsonKey.COUNTRY_CODE,"91"); + otpMap.put(JsonKey.PHONE, "9742511111"); + otpMap.put(JsonKey.TEMPLATE_ID, JsonKey.WARD_LOGIN_OTP_TEMPLATE_ID); + otpMap.put(JsonKey.OTP_EXPIRATION_IN_MINUTES, "30"); + otpMap.put(JsonKey.SUNBIRD_INSTALLATION_DISPLAY_NAME, "displayName"); + otpMap.put(JsonKey.COUNTRY_CODE, "91"); + boolean bool = OTPUtil.sendOTPViaSMS(otpMap, new RequestContext()); + Assert.assertTrue(bool); + } + + @Test + public void sendOTPViaSMSTest4() throws Exception { + PowerMockito.mockStatic(ProjectUtil.class); + when(ProjectUtil.getConfigValue(Mockito.anyString())).thenReturn("anyString"); + OTPService otpService = PowerMockito.mock(OTPService.class); + PowerMockito.whenNew(OTPService.class).withNoArguments().thenReturn(otpService); + when(otpService.getSmsBody( + Mockito.anyString(), Mockito.anyMap(), Mockito.any(RequestContext.class))) + .thenReturn("some sms text"); + ISmsProvider smsProvider = PowerMockito.mock(ISmsProvider.class); + PowerMockito.mockStatic(SMSFactory.class); + when(SMSFactory.getInstance()).thenReturn(smsProvider); + when(smsProvider.send( + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.any(RequestContext.class))) + .thenReturn(true); + Map<String, Object> otpMap = new HashMap<>(); + otpMap.put(JsonKey.PHONE, "9742511111"); + otpMap.put(JsonKey.TEMPLATE_ID, JsonKey.RESET_PASSWORD_TEMPLATE_ID); + otpMap.put(JsonKey.OTP_EXPIRATION_IN_MINUTES, "30"); + otpMap.put(JsonKey.SUNBIRD_INSTALLATION_DISPLAY_NAME, "displayName"); + otpMap.put(JsonKey.COUNTRY_CODE, "91"); + boolean bool = OTPUtil.sendOTPViaSMS(otpMap, new RequestContext()); + Assert.assertTrue(bool); + } + + @Test + public void sendOTPViaSMSTest5() throws Exception { + PowerMockito.mockStatic(ProjectUtil.class); + when(ProjectUtil.getConfigValue(Mockito.anyString())).thenReturn("anyString"); + OTPService otpService = PowerMockito.mock(OTPService.class); + PowerMockito.whenNew(OTPService.class).withNoArguments().thenReturn(otpService); + when(otpService.getSmsBody( + Mockito.anyString(), Mockito.anyMap(), Mockito.any(RequestContext.class))) + .thenReturn("some sms text"); + ISmsProvider smsProvider = PowerMockito.mock(ISmsProvider.class); + PowerMockito.mockStatic(SMSFactory.class); + when(SMSFactory.getInstance()).thenReturn(smsProvider); + when(smsProvider.send( + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.any(RequestContext.class))) + .thenReturn(true); + Map<String, Object> otpMap = new HashMap<>(); + otpMap.put(JsonKey.PHONE, "9742511111"); + otpMap.put(JsonKey.TEMPLATE_ID, JsonKey.CONTACT_UPDATE_TEMPLATE_ID); + otpMap.put(JsonKey.OTP_EXPIRATION_IN_MINUTES, "30"); + otpMap.put(JsonKey.SUNBIRD_INSTALLATION_DISPLAY_NAME, "displayName"); + otpMap.put(JsonKey.COUNTRY_CODE, "91"); boolean bool = OTPUtil.sendOTPViaSMS(otpMap, new RequestContext()); Assert.assertTrue(bool); } @@ -113,38 +189,39 @@ public class OTPUtilTest { @Test public void sendOTPViaSMSWithoutPhoneTest() { Map<String, Object> otpMap = new HashMap<>(); - otpMap.put(JsonKey.TEMPLATE_ID,"someTemplateId"); - otpMap.put(JsonKey.OTP_EXPIRATION_IN_MINUTES,"30"); - otpMap.put(JsonKey.SUNBIRD_INSTALLATION_DISPLAY_NAME,"displayName"); - otpMap.put(JsonKey.COUNTRY_CODE,"91"); + otpMap.put(JsonKey.TEMPLATE_ID, "someTemplateId"); + otpMap.put(JsonKey.OTP_EXPIRATION_IN_MINUTES, "30"); + otpMap.put(JsonKey.SUNBIRD_INSTALLATION_DISPLAY_NAME, "displayName"); + otpMap.put(JsonKey.COUNTRY_CODE, "91"); boolean bool = OTPUtil.sendOTPViaSMS(otpMap, new RequestContext()); Assert.assertFalse(bool); } - //@Test + // @Test public void getEmailPhoneByUserIdTest() throws Exception { Map<String, Object> user = new HashMap<>(); - user.put(JsonKey.USER_ID,"1235-4578-156645"); - user.put(JsonKey.EMAIL,"xyz@xyz.com"); - user.put(JsonKey.PHONE,"9999999999"); + user.put(JsonKey.USER_ID, "1235-4578-156645"); + user.put(JsonKey.EMAIL, "xyz@xyz.com"); + user.put(JsonKey.PHONE, "9999999999"); OTPService otpService = PowerMockito.mock(OTPService.class); PowerMockito.whenNew(OTPService.class).withNoArguments().thenReturn(otpService); - String value = otpService.getEmailPhoneByUserId("1235-4578-156645",JsonKey.EMAIL, new RequestContext()); + String value = + otpService.getEmailPhoneByUserId("1235-4578-156645", JsonKey.EMAIL, new RequestContext()); Assert.assertNotNull(value); } @Test(expected = ProjectCommonException.class) public void getEmailPhoneByUserId2Test() { OTPService otpService = new OTPService(); - otpService.getEmailPhoneByUserId("1235-4578-156645",JsonKey.EMAIL, new RequestContext()); + otpService.getEmailPhoneByUserId("1235-4578-156645", JsonKey.EMAIL, new RequestContext()); } @Test(expected = ProjectCommonException.class) public void getEmailPhoneByUserId3Test() { Map<String, Object> user = new HashMap<>(); - user.put(JsonKey.USER_ID,"1235-4578-156645"); + user.put(JsonKey.USER_ID, "1235-4578-156645"); OTPService otpService = new OTPService(); - otpService.getEmailPhoneByUserId("1235-4578-156645",JsonKey.EMAIL, new RequestContext()); + otpService.getEmailPhoneByUserId("1235-4578-156645", JsonKey.EMAIL, new RequestContext()); } @Test @@ -153,7 +230,7 @@ public class OTPUtilTest { when(ProjectUtil.getConfigValue(Mockito.anyString())).thenReturn("anyString"); Map<String, Object> emailTemplateMap = new HashMap<>(); - emailTemplateMap.put(JsonKey.EMAIL,"xyz@xyz.com"); + emailTemplateMap.put(JsonKey.EMAIL, "xyz@xyz.com"); Request request = OTPUtil.getRequestToSendOTPViaEmail(emailTemplateMap, new RequestContext()); Assert.assertNotNull(request); @@ -176,8 +253,32 @@ public class OTPUtilTest { when(ProjectUtil.getConfigValue(Mockito.anyString())).thenReturn("anyString"); Map<String, Object> emailTemplateMap = new HashMap<>(); - emailTemplateMap.put(JsonKey.EMAIL,"xyz@xyz.com"); - emailTemplateMap.put(JsonKey.TEMPLATE_ID,JsonKey.WARD_LOGIN_OTP_TEMPLATE_ID); + emailTemplateMap.put(JsonKey.EMAIL, "xyz@xyz.com"); + emailTemplateMap.put(JsonKey.TEMPLATE_ID, JsonKey.WARD_LOGIN_OTP_TEMPLATE_ID); + Request request = OTPUtil.getRequestToSendOTPViaEmail(emailTemplateMap, new RequestContext()); + Assert.assertNotNull(request); + } + + @Test + public void getRequestToSendOTPViaEmailTest4() { + PowerMockito.mockStatic(ProjectUtil.class); + when(ProjectUtil.getConfigValue(Mockito.anyString())).thenReturn("anyString"); + + Map<String, Object> emailTemplateMap = new HashMap<>(); + emailTemplateMap.put(JsonKey.EMAIL, "xyz@xyz.com"); + emailTemplateMap.put(JsonKey.TEMPLATE_ID, JsonKey.RESET_PASSWORD_TEMPLATE_ID); + Request request = OTPUtil.getRequestToSendOTPViaEmail(emailTemplateMap, new RequestContext()); + Assert.assertNotNull(request); + } + + @Test + public void getRequestToSendOTPViaEmailTest5() { + PowerMockito.mockStatic(ProjectUtil.class); + when(ProjectUtil.getConfigValue(Mockito.anyString())).thenReturn("anyString"); + + Map<String, Object> emailTemplateMap = new HashMap<>(); + emailTemplateMap.put(JsonKey.EMAIL, "xyz@xyz.com"); + emailTemplateMap.put(JsonKey.TEMPLATE_ID, JsonKey.CONTACT_UPDATE_TEMPLATE_ID); Request request = OTPUtil.getRequestToSendOTPViaEmail(emailTemplateMap, new RequestContext()); Assert.assertNotNull(request); } -- GitLab