diff --git a/activity-aggregator/pom.xml b/activity-aggregator/pom.xml index 0a0823d57..9aa4266ee 100644 --- a/activity-aggregator/pom.xml +++ b/activity-aggregator/pom.xml @@ -49,11 +49,6 @@ actor-core 1.0-SNAPSHOT - - org.sunbird - common-util - 0.0.1-SNAPSHOT - org.sunbird cache-utils diff --git a/activity-aggregator/src/main/scala/org/sunbird/activity/actor/ActivityAggregatorActor.scala b/activity-aggregator/src/main/scala/org/sunbird/activity/actor/ActivityAggregatorActor.scala index e5361f2b3..a744a7d76 100644 --- a/activity-aggregator/src/main/scala/org/sunbird/activity/actor/ActivityAggregatorActor.scala +++ b/activity-aggregator/src/main/scala/org/sunbird/activity/actor/ActivityAggregatorActor.scala @@ -7,13 +7,15 @@ import org.sunbird.activity.domain.{CollectionProgress, ContentStatus, Telemetry import org.sunbird.activity.util.{ActivityAggregateUtil, CertificateUtil, ContentSearchUtil, DeDupUtil, RedisUtil} import org.sunbird.cache.util.RedisCacheUtil import org.sunbird.cassandra.CassandraOperation -import org.sunbird.common.exception.ProjectCommonException -import org.sunbird.common.models.util.{JsonKey, LoggerUtil, ProjectUtil} -import org.sunbird.common.request.{Request, RequestContext} -import org.sunbird.common.responsecode.ResponseCode +import org.sunbird.exception.ProjectCommonException +import org.sunbird.keys.JsonKey +import org.sunbird.logging.LoggerUtil +import org.sunbird.common.ProjectUtil +import org.sunbird.request.{Request, RequestContext} +import org.sunbird.response.ResponseCode import org.sunbird.enrolments.BaseEnrolmentActor import org.sunbird.helper.ServiceFactory -import org.sunbird.kafka.client.KafkaClient +import org.sunbird.kafka.KafkaClient import org.sunbird.learner.util.Util import java.util @@ -223,7 +225,7 @@ class ActivityAggregatorActor @Inject()(implicit val cacheUtil: RedisCacheUtil) cassandraOperation.batchUpdate(consumptionDBInfo.getKeySpace, "user_content_consumption", queries, requestContext) logger.info(requestContext, s"updateContentConsumption: Batch update completed successfully") } else { - logger.warn(requestContext, s"updateContentConsumption: No queries to execute") + logger.warn(requestContext, s"updateContentConsumption: No queries to execute", null) } } @@ -240,7 +242,7 @@ class ActivityAggregatorActor @Inject()(implicit val cacheUtil: RedisCacheUtil) logger.info(requestContext, s"computeCourseAggregations: Course aggregation computed successfully") List(courseAggOpt.get) } else { - logger.warn(requestContext, s"computeCourseAggregations: No course aggregation computed") + logger.warn(requestContext, s"computeCourseAggregations: No course aggregation computed", null) List() } @@ -281,7 +283,7 @@ class ActivityAggregatorActor @Inject()(implicit val cacheUtil: RedisCacheUtil) cassandraOperation.batchUpdate(activityAggDBInfo.getKeySpace, activityAggDBInfo.getTableName, aggQueries, requestContext) logger.info(requestContext, s"updateActivityAggregates: Batch update completed successfully") } else { - logger.warn(requestContext, s"updateActivityAggregates: No queries to execute") + logger.warn(requestContext, s"updateActivityAggregates: No queries to execute", null) } } @@ -393,7 +395,7 @@ class ActivityAggregatorActor @Inject()(implicit val cacheUtil: RedisCacheUtil) logger.info(requestContext, s"getEnrolmentStatus: No enrolment found, returning status 0") } } else { - logger.warn(requestContext, s"getEnrolmentStatus: Null response from Cassandra") + logger.warn(requestContext, s"getEnrolmentStatus: Null response from Cassandra", null) } 0 @@ -432,7 +434,7 @@ class ActivityAggregatorActor @Inject()(implicit val cacheUtil: RedisCacheUtil) Some(contentId -> ContentStatus(contentId, status, completedCount, viewCount, progress, lastAccessTime, lastCompletedTime, lastUpdatedTime, fromInput = false)) } else { - logger.warn(requestContext, s"getContentStatusFromDB: Skipping row with missing contentId. Keys: ${row.keySet()}") + logger.warn(requestContext, s"getContentStatusFromDB: Skipping row with missing contentId. Keys: ${row.keySet()}", null) None } }).toMap diff --git a/activity-aggregator/src/main/scala/org/sunbird/activity/util/ActivityAggregateUtil.scala b/activity-aggregator/src/main/scala/org/sunbird/activity/util/ActivityAggregateUtil.scala index cae6147a5..c0fa73984 100644 --- a/activity-aggregator/src/main/scala/org/sunbird/activity/util/ActivityAggregateUtil.scala +++ b/activity-aggregator/src/main/scala/org/sunbird/activity/util/ActivityAggregateUtil.scala @@ -3,8 +3,10 @@ package org.sunbird.activity.util import org.apache.commons.collections4.CollectionUtils import org.apache.commons.lang3.StringUtils import org.sunbird.activity.domain._ -import org.sunbird.common.models.util.{JsonKey, LoggerUtil, ProjectUtil} -import org.sunbird.common.request.RequestContext +import org.sunbird.keys.JsonKey +import org.sunbird.logging.LoggerUtil +import org.sunbird.common.ProjectUtil +import org.sunbird.request.RequestContext import java.util import java.util.Date @@ -138,7 +140,7 @@ class ActivityAggregateUtil { logger.info(requestContext, s"computeCourseActivityAgg: courseId: $courseId, userId: $userId, leafNodes: ${leafNodes.size}, optionalNodes: ${optionalNodes.size}") if (leafNodes.isEmpty) { - logger.warn(requestContext, s"computeCourseActivityAgg: Leaf nodes are not available for courseId: $courseId") + logger.warn(requestContext, s"computeCourseActivityAgg: Leaf nodes are not available for courseId: $courseId", null) None } else { val updatedLeafNodes = leafNodes.diff(optionalNodes) diff --git a/activity-aggregator/src/main/scala/org/sunbird/activity/util/CertificateUtil.scala b/activity-aggregator/src/main/scala/org/sunbird/activity/util/CertificateUtil.scala index a237ef279..4c0211020 100644 --- a/activity-aggregator/src/main/scala/org/sunbird/activity/util/CertificateUtil.scala +++ b/activity-aggregator/src/main/scala/org/sunbird/activity/util/CertificateUtil.scala @@ -1,9 +1,9 @@ package org.sunbird.activity.util import com.fasterxml.jackson.databind.ObjectMapper -import org.sunbird.common.models.util.ProjectUtil -import org.sunbird.common.request.RequestContext -import org.sunbird.kafka.client.KafkaClient +import org.sunbird.common.ProjectUtil +import org.sunbird.request.RequestContext +import org.sunbird.kafka.KafkaClient import java.util.UUID diff --git a/activity-aggregator/src/main/scala/org/sunbird/activity/util/ContentSearchUtil.scala b/activity-aggregator/src/main/scala/org/sunbird/activity/util/ContentSearchUtil.scala index 48a3f896f..3c2dc0766 100644 --- a/activity-aggregator/src/main/scala/org/sunbird/activity/util/ContentSearchUtil.scala +++ b/activity-aggregator/src/main/scala/org/sunbird/activity/util/ContentSearchUtil.scala @@ -1,8 +1,9 @@ package org.sunbird.activity.util import com.fasterxml.jackson.databind.ObjectMapper -import org.sunbird.common.models.util.{HttpUtil, ProjectUtil} -import org.sunbird.common.request.RequestContext +import org.sunbird.http.HttpUtil +import org.sunbird.common.ProjectUtil +import org.sunbird.request.RequestContext import java.util import scala.collection.JavaConverters._ diff --git a/activity-aggregator/src/main/scala/org/sunbird/activity/util/DeDupUtil.scala b/activity-aggregator/src/main/scala/org/sunbird/activity/util/DeDupUtil.scala index c2575293e..95549a6c4 100644 --- a/activity-aggregator/src/main/scala/org/sunbird/activity/util/DeDupUtil.scala +++ b/activity-aggregator/src/main/scala/org/sunbird/activity/util/DeDupUtil.scala @@ -1,8 +1,8 @@ package org.sunbird.activity.util import org.sunbird.cache.util.RedisCacheUtil -import org.sunbird.common.models.util.ProjectUtil -import org.sunbird.common.request.RequestContext +import org.sunbird.common.ProjectUtil +import org.sunbird.request.RequestContext import java.security.MessageDigest diff --git a/activity-aggregator/src/main/scala/org/sunbird/activity/util/RedisUtil.scala b/activity-aggregator/src/main/scala/org/sunbird/activity/util/RedisUtil.scala index e74836ade..9069f513d 100644 --- a/activity-aggregator/src/main/scala/org/sunbird/activity/util/RedisUtil.scala +++ b/activity-aggregator/src/main/scala/org/sunbird/activity/util/RedisUtil.scala @@ -2,8 +2,9 @@ package org.sunbird.activity.util import org.apache.commons.collections.CollectionUtils import org.sunbird.cache.util.RedisCacheUtil -import org.sunbird.common.models.util.{LoggerUtil, ProjectUtil} -import org.sunbird.common.request.RequestContext +import org.sunbird.logging.LoggerUtil +import org.sunbird.common.ProjectUtil +import org.sunbird.request.RequestContext import scala.collection.JavaConverters._ diff --git a/activity-aggregator/src/test/scala/org/sunbird/activity/actor/ActivityAggregatorActorTest.scala b/activity-aggregator/src/test/scala/org/sunbird/activity/actor/ActivityAggregatorActorTest.scala index a5f11e322..6c2f842e3 100644 --- a/activity-aggregator/src/test/scala/org/sunbird/activity/actor/ActivityAggregatorActorTest.scala +++ b/activity-aggregator/src/test/scala/org/sunbird/activity/actor/ActivityAggregatorActorTest.scala @@ -10,9 +10,9 @@ import org.sunbird.activity.util.{CertificateUtil, ContentSearchUtil, DeDupUtil, import org.sunbird.activity.domain.{CollectionProgress, TelemetryEvent} import org.sunbird.cache.util.RedisCacheUtil import org.sunbird.cassandra.CassandraOperation -import org.sunbird.common.models.response.Response -import org.sunbird.common.models.util.JsonKey -import org.sunbird.common.request.{Request, RequestContext} +import org.sunbird.response.Response +import org.sunbird.keys.JsonKey +import org.sunbird.request.{Request, RequestContext} import java.util import scala.concurrent.duration._ diff --git a/activity-aggregator/src/test/scala/org/sunbird/activity/util/ActivityAggregateUtilTest.scala b/activity-aggregator/src/test/scala/org/sunbird/activity/util/ActivityAggregateUtilTest.scala index 0247ccbe7..dad01055e 100644 --- a/activity-aggregator/src/test/scala/org/sunbird/activity/util/ActivityAggregateUtilTest.scala +++ b/activity-aggregator/src/test/scala/org/sunbird/activity/util/ActivityAggregateUtilTest.scala @@ -3,7 +3,7 @@ package org.sunbird.activity.util import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.sunbird.activity.domain.{ContentStatus, UserContentConsumption} -import org.sunbird.common.request.RequestContext +import org.sunbird.request.RequestContext import java.util import java.util.Date diff --git a/assessment-aggregator/src/main/scala/org/sunbird/assessment/actor/AssessmentAggregatorActor.scala b/assessment-aggregator/src/main/scala/org/sunbird/assessment/actor/AssessmentAggregatorActor.scala index 3b8732103..44e3a969e 100644 --- a/assessment-aggregator/src/main/scala/org/sunbird/assessment/actor/AssessmentAggregatorActor.scala +++ b/assessment-aggregator/src/main/scala/org/sunbird/assessment/actor/AssessmentAggregatorActor.scala @@ -2,18 +2,21 @@ package org.sunbird.assessment.actor import org.sunbird.actor.core.BaseActor import javax.inject.Inject import org.apache.pekko.actor.Props -import org.sunbird.common.exception.ProjectCommonException -import org.sunbird.common.request.{Request, RequestContext} -import org.sunbird.common.responsecode.ResponseCode +import org.sunbird.exception.ProjectCommonException +import org.sunbird.request.{Request, RequestContext} +import org.sunbird.response.ResponseCode import org.sunbird.assessment.models._ import org.sunbird.assessment.service._ import org.sunbird.assessment.util.AssessmentParser -import org.sunbird.common.models.util.{JsonKey, LoggerUtil, ProjectUtil} +import org.sunbird.keys.JsonKey +import org.sunbird.logging.LoggerUtil +import org.sunbird.common.ProjectUtil import scala.collection.JavaConverters._ import org.apache.commons.lang3.StringUtils -class AssessmentAggregatorActor @Inject()(_redisService: Option[RedisService],_contentService: Option[ContentService],_cassandraService: Option[CassandraService],_kafkaService: Option[KafkaService]) extends BaseActor { +class AssessmentAggregatorActor(_redisService: Option[RedisService],_contentService: Option[ContentService],_cassandraService: Option[CassandraService],_kafkaService: Option[KafkaService]) extends BaseActor { + @Inject() def this() = this(None, None, None, None) private lazy val redisService = _redisService.getOrElse(new RedisService()) @@ -86,7 +89,7 @@ class AssessmentAggregatorActor @Inject()(_redisService: Option[RedisService],_c if (request.events.nonEmpty) return List(request) val existing = fetchStoredAssessments(request, context) if (existing.isEmpty) { - logger.warn(context, s"Sync Flow: No stored events found for userId=${request.userId}, contentId=${request.contentId}, attemptId=${request.attemptId}") + logger.warn(context, s"Sync Flow: No stored events found for userId=${request.userId}, contentId=${request.contentId}, attemptId=${request.attemptId}", null) return List(request) } logger.info(context, s"Sync Flow: Recovered ${existing.size} attempt(s) for userId=${request.userId}, contentId=${request.contentId}") @@ -125,7 +128,7 @@ class AssessmentAggregatorActor @Inject()(_redisService: Option[RedisService],_c if (skipMissing) { val totalQuestions = metadata.totalQuestions if (totalQuestions > 0 && uniqueEvents.size > totalQuestions) { - logger.warn(context, s"Skipping assessment ${req.attemptId}: unique events (${uniqueEvents.size}) exceed total questions ($totalQuestions)") + logger.warn(context, s"Skipping assessment ${req.attemptId}: unique events (${uniqueEvents.size}) exceed total questions ($totalQuestions)", null) return } } @@ -220,7 +223,7 @@ class AssessmentAggregatorActor @Inject()(_redisService: Option[RedisService],_c private def getD(m: java.util.Map[String, AnyRef], k: String): Double = Option(m.get(k)).map(_.asInstanceOf[Number].doubleValue()).getOrElse(0.0) - private def createSuccess(aid: String) = { val r = new org.sunbird.common.models.response.Response(); r.put("response", "SUCCESS"); r.put("attemptId", aid); r } + private def createSuccess(aid: String) = { val r = new org.sunbird.response.Response(); r.put("response", "SUCCESS"); r.put("attemptId", aid); r } private def createErrorResponse(code: String, msg: String, responseCode: Int): ProjectCommonException = new ProjectCommonException(code, msg, responseCode) } diff --git a/assessment-aggregator/src/main/scala/org/sunbird/assessment/service/AssessmentService.scala b/assessment-aggregator/src/main/scala/org/sunbird/assessment/service/AssessmentService.scala index ee7ea1167..0bb00782d 100644 --- a/assessment-aggregator/src/main/scala/org/sunbird/assessment/service/AssessmentService.scala +++ b/assessment-aggregator/src/main/scala/org/sunbird/assessment/service/AssessmentService.scala @@ -1,12 +1,12 @@ package org.sunbird.assessment.service import org.sunbird.assessment.models._ -import org.sunbird.common.models.util.ProjectUtil +import org.sunbird.common.ProjectUtil import java.text.DecimalFormat class AssessmentService(redisService: RedisService, contentService: ContentService) { private val decimalFormat = new DecimalFormat("0.0#") - private val aggType = Option(org.sunbird.common.models.util.ProjectUtil.getConfigValue("user_activity_agg_type")).getOrElse("assessment") + private val aggType = Option(org.sunbird.common.ProjectUtil.getConfigValue("user_activity_agg_type")).getOrElse("assessment") def getUniqueQuestions(events: List[AssessmentEvent]): List[AssessmentEvent] = { events.sortBy(_.timestamp)(Ordering[Long].reverse).groupBy(_.questionId).values.map(_.head).toList @@ -24,7 +24,7 @@ class AssessmentService(redisService: RedisService, contentService: ContentServi /** * Fetches content metadata once by combining Redis and Content API checks. */ - def getMetadata(courseId: String, contentId: String, context: org.sunbird.common.request.RequestContext): ContentMetadata = { + def getMetadata(courseId: String, contentId: String, context: org.sunbird.request.RequestContext): ContentMetadata = { val isValidInCache = redisService.isValidContent(courseId, contentId) val cachedCount = redisService.getTotalQuestionsCount(contentId) if (isValidInCache && cachedCount.isDefined) { diff --git a/assessment-aggregator/src/main/scala/org/sunbird/assessment/service/CassandraService.scala b/assessment-aggregator/src/main/scala/org/sunbird/assessment/service/CassandraService.scala index 58a2bf8f6..2036f0cd9 100644 --- a/assessment-aggregator/src/main/scala/org/sunbird/assessment/service/CassandraService.scala +++ b/assessment-aggregator/src/main/scala/org/sunbird/assessment/service/CassandraService.scala @@ -1,9 +1,9 @@ package org.sunbird.assessment.service import org.sunbird.cassandra.CassandraOperation import org.sunbird.helper.ServiceFactory -import org.sunbird.common.request.RequestContext +import org.sunbird.request.RequestContext import org.sunbird.assessment.models._ -import org.sunbird.common.models.util.ProjectUtil +import org.sunbird.common.ProjectUtil import scala.collection.JavaConverters._ import com.datastax.driver.core.{UserType, UDTValue} import org.slf4j.LoggerFactory diff --git a/assessment-aggregator/src/main/scala/org/sunbird/assessment/service/ContentService.scala b/assessment-aggregator/src/main/scala/org/sunbird/assessment/service/ContentService.scala index ee316c62f..a95cc322c 100644 --- a/assessment-aggregator/src/main/scala/org/sunbird/assessment/service/ContentService.scala +++ b/assessment-aggregator/src/main/scala/org/sunbird/assessment/service/ContentService.scala @@ -1,7 +1,10 @@ package org.sunbird.assessment.service -import org.sunbird.common.models.util.{HttpUtil, ProjectUtil, JsonKey, LoggerUtil} -import org.sunbird.common.request.RequestContext +import org.sunbird.http.HttpUtil +import org.sunbird.common.ProjectUtil +import org.sunbird.keys.JsonKey +import org.sunbird.logging.LoggerUtil +import org.sunbird.request.RequestContext import org.apache.commons.lang3.StringUtils import scala.collection.JavaConverters._ @@ -19,7 +22,7 @@ class ContentService(http: Option[HttpUtilWrapper] = None) { private val logger = new LoggerUtil(classOf[ContentService]) private val httpUtil = http.getOrElse(DefaultHttpUtilWrapper) private val baseUrl = Option(ProjectUtil.getConfigValue("sunbird_api_base_url")).filter(StringUtils.isNotBlank).getOrElse("http://localhost:9000") - private val contentReadPath = Option(ProjectUtil.getConfigValue("sunbird_content_read_api_path")).filter(StringUtils.isNotBlank).getOrElse("/content/v1/read/") + private val contentReadPath = Option(ProjectUtil.getConfigValue("sunbird_content_read_api_path")).filter(StringUtils.isNotBlank).getOrElse("/v1/content/read/") def fetchMetadata(contentId: String, context: RequestContext): ContentMetadata = { val url = s"$baseUrl$contentReadPath$contentId" diff --git a/assessment-aggregator/src/main/scala/org/sunbird/assessment/service/KafkaClientWrapper.scala b/assessment-aggregator/src/main/scala/org/sunbird/assessment/service/KafkaClientWrapper.scala index 0321921cd..969d43b96 100644 --- a/assessment-aggregator/src/main/scala/org/sunbird/assessment/service/KafkaClientWrapper.scala +++ b/assessment-aggregator/src/main/scala/org/sunbird/assessment/service/KafkaClientWrapper.scala @@ -1,6 +1,6 @@ package org.sunbird.assessment.service -import org.sunbird.kafka.client.KafkaClient +import org.sunbird.kafka.KafkaClient trait KafkaClientWrapper { def send(event: String, topic: String): Unit diff --git a/assessment-aggregator/src/main/scala/org/sunbird/assessment/service/KafkaService.scala b/assessment-aggregator/src/main/scala/org/sunbird/assessment/service/KafkaService.scala index 39ccda18d..097f8633c 100644 --- a/assessment-aggregator/src/main/scala/org/sunbird/assessment/service/KafkaService.scala +++ b/assessment-aggregator/src/main/scala/org/sunbird/assessment/service/KafkaService.scala @@ -1,7 +1,7 @@ package org.sunbird.assessment.service -import org.sunbird.kafka.client.KafkaClient -import org.sunbird.common.models.util.ProjectUtil +import org.sunbird.kafka.KafkaClient +import org.sunbird.common.ProjectUtil import org.sunbird.assessment.models.AssessmentRequest import com.fasterxml.jackson.databind.ObjectMapper import org.slf4j.LoggerFactory diff --git a/assessment-aggregator/src/main/scala/org/sunbird/assessment/util/AssessmentParser.scala b/assessment-aggregator/src/main/scala/org/sunbird/assessment/util/AssessmentParser.scala index c90e01d7a..ba773c260 100644 --- a/assessment-aggregator/src/main/scala/org/sunbird/assessment/util/AssessmentParser.scala +++ b/assessment-aggregator/src/main/scala/org/sunbird/assessment/util/AssessmentParser.scala @@ -3,6 +3,7 @@ package org.sunbird.assessment.util import org.sunbird.assessment.models.AssessmentEvent import scala.collection.JavaConverters._ import com.google.gson.Gson +import org.sunbird.keys.JsonKey object AssessmentParser { private val gson = new Gson() @@ -29,7 +30,7 @@ object AssessmentParser { val resvalues = getListValues(m.getOrDefault("resvalues", new java.util.ArrayList()).asInstanceOf[java.util.List[java.util.Map[String, AnyRef]]]) val params = getListValues(m.getOrDefault("params", new java.util.ArrayList()).asInstanceOf[java.util.List[java.util.Map[String, AnyRef]]]) AssessmentEvent( - Option(m.get("questionId")).getOrElse(m.getOrDefault(org.sunbird.common.models.util.JsonKey.IDENTIFIER, "")).toString, + Option(m.get("questionId")).getOrElse(m.getOrDefault(JsonKey.IDENTIFIER, "")).toString, getD(m, "score"), getD(m, "maxScore"), getD(m, "duration"), diff --git a/assessment-aggregator/src/test/scala/org/sunbird/assessment/actor/AssessmentAggregatorActorSpec.scala b/assessment-aggregator/src/test/scala/org/sunbird/assessment/actor/AssessmentAggregatorActorSpec.scala index 5c0a8bd1a..86c16c581 100644 --- a/assessment-aggregator/src/test/scala/org/sunbird/assessment/actor/AssessmentAggregatorActorSpec.scala +++ b/assessment-aggregator/src/test/scala/org/sunbird/assessment/actor/AssessmentAggregatorActorSpec.scala @@ -7,16 +7,17 @@ import org.mockito.MockitoSugar import org.scalatest.BeforeAndAfterAll import org.scalatest.flatspec.AnyFlatSpecLike import org.scalatest.matchers.should.Matchers -import org.sunbird.common.request.{Request, RequestContext} +import org.sunbird.request.{Request, RequestContext} import org.sunbird.assessment.models._ -import org.sunbird.common.models.util.{JsonKey, PropertiesCache} -import org.sunbird.common.exception.ProjectCommonException -import org.sunbird.common.models.response.Response +import org.sunbird.keys.JsonKey +import org.sunbird.common.PropertiesCache +import org.sunbird.exception.ProjectCommonException +import org.sunbird.response.Response import java.util.HashMap import scala.collection.JavaConverters._ import scala.concurrent.duration._ import org.sunbird.assessment.service.{CassandraService, ContentMetadata, ContentService, KafkaService, RedisService} -import org.sunbird.common.responsecode.ResponseCode +import org.sunbird.response.ResponseCode class AssessmentAggregatorActorSpec extends TestKit(ActorSystem("AssessmentAggregatorActorSpec")) with ImplicitSender with AnyFlatSpecLike with Matchers with BeforeAndAfterAll with MockitoSugar { diff --git a/assessment-aggregator/src/test/scala/org/sunbird/assessment/service/AssessmentServiceSpec.scala b/assessment-aggregator/src/test/scala/org/sunbird/assessment/service/AssessmentServiceSpec.scala index c3a4b10bf..38aef5c59 100644 --- a/assessment-aggregator/src/test/scala/org/sunbird/assessment/service/AssessmentServiceSpec.scala +++ b/assessment-aggregator/src/test/scala/org/sunbird/assessment/service/AssessmentServiceSpec.scala @@ -5,8 +5,8 @@ import org.mockito.MockitoSugar import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.sunbird.assessment.models._ -import org.sunbird.common.models.util.PropertiesCache -import org.sunbird.common.request.RequestContext +import org.sunbird.common.PropertiesCache +import org.sunbird.request.RequestContext class AssessmentServiceSpec extends AnyFlatSpec with Matchers with MockitoSugar { diff --git a/assessment-aggregator/src/test/scala/org/sunbird/assessment/service/CassandraServiceSpec.scala b/assessment-aggregator/src/test/scala/org/sunbird/assessment/service/CassandraServiceSpec.scala index 9772d2bd8..08dab5ac9 100644 --- a/assessment-aggregator/src/test/scala/org/sunbird/assessment/service/CassandraServiceSpec.scala +++ b/assessment-aggregator/src/test/scala/org/sunbird/assessment/service/CassandraServiceSpec.scala @@ -5,8 +5,8 @@ import org.mockito.MockitoSugar import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.sunbird.cassandra.CassandraOperation -import org.sunbird.common.models.response.Response -import org.sunbird.common.request.RequestContext +import org.sunbird.response.Response +import org.sunbird.request.RequestContext import org.sunbird.assessment.models._ import java.util.{ArrayList, HashMap, Map} import scala.collection.JavaConverters._ diff --git a/assessment-aggregator/src/test/scala/org/sunbird/assessment/service/ContentServiceSpec.scala b/assessment-aggregator/src/test/scala/org/sunbird/assessment/service/ContentServiceSpec.scala index 27cfff017..7164abd1a 100644 --- a/assessment-aggregator/src/test/scala/org/sunbird/assessment/service/ContentServiceSpec.scala +++ b/assessment-aggregator/src/test/scala/org/sunbird/assessment/service/ContentServiceSpec.scala @@ -4,7 +4,7 @@ import org.mockito.ArgumentMatchers._ import org.mockito.MockitoSugar import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers -import org.sunbird.common.request.RequestContext +import org.sunbird.request.RequestContext class ContentServiceSpec extends AnyFlatSpec with Matchers with MockitoSugar { diff --git a/core/pom.xml b/core/pom.xml index cc584d87e..de6e3e721 100644 --- a/core/pom.xml +++ b/core/pom.xml @@ -12,7 +12,7 @@ core pom - core + Sunbird Core @@ -34,17 +34,49 @@ 4.5.14 4.4.16 4.1.5 + 4.5.14 2.13.5 + + 1.0.3 + + + 3.7.1 + 1.2.3 - 6.6 + 7.3 3.2.2 + 4.4 3.12.0 + 1.7 + + + 2.0 + + + 21.1.2 + 3.0.12.Final + 4.7.9.Final + 4.7.9.Final + + + 8.10.2 + 32.1.2-jre + + + 1.4.8.1 + + + 1.4.9 + + + 3.0.5 + 2.13 4.13.1 @@ -53,11 +85,12 @@ 3.8.1 3.0.0 - 0.8.7 + 0.8.8 1.1.1 + sunbird-platform-common sunbird-cassandra-utils sunbird-es-utils diff --git a/core/sunbird-cassandra-utils/pom.xml b/core/sunbird-cassandra-utils/pom.xml index 60a29d73c..7259f7271 100644 --- a/core/sunbird-cassandra-utils/pom.xml +++ b/core/sunbird-cassandra-utils/pom.xml @@ -66,8 +66,14 @@ org.sunbird - sunbird-commons + sunbird-platform-common 1.0-SNAPSHOT + + + io.netty + * + + diff --git a/core/sunbird-cassandra-utils/src/main/java/org/sunbird/cassandra/CassandraOperation.java b/core/sunbird-cassandra-utils/src/main/java/org/sunbird/cassandra/CassandraOperation.java index 4c6f693d3..b08d8b175 100644 --- a/core/sunbird-cassandra-utils/src/main/java/org/sunbird/cassandra/CassandraOperation.java +++ b/core/sunbird-cassandra-utils/src/main/java/org/sunbird/cassandra/CassandraOperation.java @@ -5,8 +5,8 @@ import com.google.common.util.concurrent.FutureCallback; import java.util.List; import java.util.Map; -import org.sunbird.common.request.RequestContext; -import org.sunbird.common.models.response.Response; +import org.sunbird.request.RequestContext; +import org.sunbird.response.Response; /** * Interface defining core CRUD operations for Cassandra database interactions. diff --git a/core/sunbird-cassandra-utils/src/main/java/org/sunbird/cassandraimpl/CassandraDACImpl.java b/core/sunbird-cassandra-utils/src/main/java/org/sunbird/cassandraimpl/CassandraDACImpl.java index 84e334867..596d65203 100644 --- a/core/sunbird-cassandra-utils/src/main/java/org/sunbird/cassandraimpl/CassandraDACImpl.java +++ b/core/sunbird-cassandra-utils/src/main/java/org/sunbird/cassandraimpl/CassandraDACImpl.java @@ -15,10 +15,10 @@ import org.apache.commons.collections.MapUtils; import org.sunbird.common.CassandraUtil; import org.sunbird.common.Constants; -import org.sunbird.common.exception.ProjectCommonException; -import org.sunbird.common.models.response.Response; -import org.sunbird.common.request.RequestContext; -import org.sunbird.common.responsecode.ResponseCode; +import org.sunbird.exception.ProjectCommonException; +import org.sunbird.response.Response; +import org.sunbird.request.RequestContext; +import org.sunbird.response.ResponseCode; /** * Extended Cassandra Data Access Component (DAC) implementation. diff --git a/core/sunbird-cassandra-utils/src/main/java/org/sunbird/cassandraimpl/CassandraOperationImpl.java b/core/sunbird-cassandra-utils/src/main/java/org/sunbird/cassandraimpl/CassandraOperationImpl.java index aec024c07..64bee7299 100644 --- a/core/sunbird-cassandra-utils/src/main/java/org/sunbird/cassandraimpl/CassandraOperationImpl.java +++ b/core/sunbird-cassandra-utils/src/main/java/org/sunbird/cassandraimpl/CassandraOperationImpl.java @@ -40,12 +40,12 @@ import org.sunbird.cassandra.CassandraOperation; import org.sunbird.common.CassandraUtil; import org.sunbird.common.Constants; -import org.sunbird.common.exception.ProjectCommonException; -import org.sunbird.common.models.response.Response; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.models.util.LoggerUtil; -import org.sunbird.common.request.RequestContext; -import org.sunbird.common.responsecode.ResponseCode; +import org.sunbird.exception.ProjectCommonException; +import org.sunbird.response.Response; +import org.sunbird.keys.JsonKey; +import org.sunbird.logging.LoggerUtil; +import org.sunbird.request.RequestContext; +import org.sunbird.response.ResponseCode; import org.sunbird.helper.CassandraConnectionManager; import org.sunbird.helper.CassandraConnectionManagerImpl; import org.sunbird.helper.CassandraConnectionMngrFactory; diff --git a/core/sunbird-cassandra-utils/src/main/java/org/sunbird/common/CassandraPropertyReader.java b/core/sunbird-cassandra-utils/src/main/java/org/sunbird/common/CassandraPropertyReader.java index 606c6c227..28bb5ab84 100644 --- a/core/sunbird-cassandra-utils/src/main/java/org/sunbird/common/CassandraPropertyReader.java +++ b/core/sunbird-cassandra-utils/src/main/java/org/sunbird/common/CassandraPropertyReader.java @@ -7,7 +7,7 @@ import java.util.Properties; import java.util.stream.Collectors; import org.apache.commons.lang3.StringUtils; -import org.sunbird.common.models.util.LoggerUtil; +import org.sunbird.logging.LoggerUtil; /** * Utility class to read configuration properties for Cassandra tables and columns. diff --git a/core/sunbird-cassandra-utils/src/main/java/org/sunbird/common/CassandraUtil.java b/core/sunbird-cassandra-utils/src/main/java/org/sunbird/common/CassandraUtil.java index 2592c3866..9e685efd2 100644 --- a/core/sunbird-cassandra-utils/src/main/java/org/sunbird/common/CassandraUtil.java +++ b/core/sunbird-cassandra-utils/src/main/java/org/sunbird/common/CassandraUtil.java @@ -27,10 +27,10 @@ import org.sunbird.cassandraannotation.PartitioningKey; import org.sunbird.common.Constants; import org.sunbird.common.CassandraPropertyReader; -import org.sunbird.common.exception.ProjectCommonException; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.models.response.Response; -import org.sunbird.common.responsecode.ResponseCode; +import org.sunbird.exception.ProjectCommonException; +import org.sunbird.keys.JsonKey; +import org.sunbird.response.Response; +import org.sunbird.response.ResponseCode; /** * Utility class providing helper methods for Cassandra database operations. diff --git a/core/sunbird-cassandra-utils/src/main/java/org/sunbird/helper/CassandraConnectionManagerImpl.java b/core/sunbird-cassandra-utils/src/main/java/org/sunbird/helper/CassandraConnectionManagerImpl.java index f2b186085..7a1f61916 100644 --- a/core/sunbird-cassandra-utils/src/main/java/org/sunbird/helper/CassandraConnectionManagerImpl.java +++ b/core/sunbird-cassandra-utils/src/main/java/org/sunbird/helper/CassandraConnectionManagerImpl.java @@ -22,11 +22,11 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sunbird.common.Constants; -import org.sunbird.common.exception.ProjectCommonException; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.models.util.ProjectUtil; +import org.sunbird.exception.ProjectCommonException; +import org.sunbird.keys.JsonKey; +import org.sunbird.common.ProjectUtil; import org.sunbird.common.CassandraPropertyReader; -import org.sunbird.common.responsecode.ResponseCode; +import org.sunbird.response.ResponseCode; /** * Implementation of {@link CassandraConnectionManager} for managing Cassandra database connections. diff --git a/core/sunbird-es-utils/pom.xml b/core/sunbird-es-utils/pom.xml index 0758f34df..c88bbfd20 100644 --- a/core/sunbird-es-utils/pom.xml +++ b/core/sunbird-es-utils/pom.xml @@ -120,8 +120,8 @@ org.sunbird - common-util - 0.0.1-SNAPSHOT + sunbird-platform-common + 1.0-SNAPSHOT io.netty diff --git a/core/sunbird-es-utils/src/main/java/org/sunbird/common/ElasticSearchHelper.java b/core/sunbird-es-utils/src/main/java/org/sunbird/common/ElasticSearchHelper.java index 51c372d88..61de6939c 100644 --- a/core/sunbird-es-utils/src/main/java/org/sunbird/common/ElasticSearchHelper.java +++ b/core/sunbird-es-utils/src/main/java/org/sunbird/common/ElasticSearchHelper.java @@ -1,6 +1,6 @@ package org.sunbird.common; -import static org.sunbird.common.models.util.ProjectUtil.isNotNull; +import static org.sunbird.common.ProjectUtil.isNotNull; import java.math.BigInteger; import java.util.ArrayList; @@ -38,8 +38,8 @@ import org.elasticsearch.search.aggregations.bucket.terms.Terms; import org.elasticsearch.search.aggregations.bucket.terms.Terms.Bucket; import org.elasticsearch.search.sort.SortOrder; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.models.util.LoggerUtil; +import org.sunbird.keys.JsonKey; +import org.sunbird.logging.LoggerUtil; import org.sunbird.dto.SearchDTO; import scala.concurrent.Await; import scala.concurrent.Future; diff --git a/core/sunbird-es-utils/src/main/java/org/sunbird/common/ElasticSearchRestHighImpl.java b/core/sunbird-es-utils/src/main/java/org/sunbird/common/ElasticSearchRestHighImpl.java index 787c84654..f84ab5686 100644 --- a/core/sunbird-es-utils/src/main/java/org/sunbird/common/ElasticSearchRestHighImpl.java +++ b/core/sunbird-es-utils/src/main/java/org/sunbird/common/ElasticSearchRestHighImpl.java @@ -38,12 +38,12 @@ import org.elasticsearch.search.sort.FieldSortBuilder; import org.elasticsearch.search.sort.SortMode; import org.sunbird.common.inf.ElasticSearchService; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.models.util.LoggerUtil; -import org.sunbird.common.models.util.ProjectUtil; -import org.sunbird.common.models.util.PropertiesCache; -import org.sunbird.common.request.RequestContext; -import org.sunbird.common.responsecode.ResponseCode; +import org.sunbird.keys.JsonKey; +import org.sunbird.logging.LoggerUtil; +import org.sunbird.common.ProjectUtil; +import org.sunbird.common.PropertiesCache; +import org.sunbird.request.RequestContext; +import org.sunbird.response.ResponseCode; import org.sunbird.dto.SearchDTO; import org.sunbird.helper.ConnectionManager; import scala.concurrent.Future; diff --git a/core/sunbird-es-utils/src/main/java/org/sunbird/common/factory/EsClientFactory.java b/core/sunbird-es-utils/src/main/java/org/sunbird/common/factory/EsClientFactory.java index 3f504f651..4c9747573 100644 --- a/core/sunbird-es-utils/src/main/java/org/sunbird/common/factory/EsClientFactory.java +++ b/core/sunbird-es-utils/src/main/java/org/sunbird/common/factory/EsClientFactory.java @@ -2,8 +2,8 @@ import org.sunbird.common.ElasticSearchRestHighImpl; import org.sunbird.common.inf.ElasticSearchService; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.models.util.LoggerUtil; +import org.sunbird.keys.JsonKey; +import org.sunbird.logging.LoggerUtil; /** * Factory class to provide instances of ElasticSearchService. diff --git a/core/sunbird-es-utils/src/main/java/org/sunbird/common/inf/ElasticSearchService.java b/core/sunbird-es-utils/src/main/java/org/sunbird/common/inf/ElasticSearchService.java index 031adba82..18765e39f 100644 --- a/core/sunbird-es-utils/src/main/java/org/sunbird/common/inf/ElasticSearchService.java +++ b/core/sunbird-es-utils/src/main/java/org/sunbird/common/inf/ElasticSearchService.java @@ -2,7 +2,7 @@ import java.util.List; import java.util.Map; -import org.sunbird.common.request.RequestContext; +import org.sunbird.request.RequestContext; import org.sunbird.dto.SearchDTO; import scala.concurrent.Future; diff --git a/core/sunbird-es-utils/src/main/java/org/sunbird/helper/ConnectionManager.java b/core/sunbird-es-utils/src/main/java/org/sunbird/helper/ConnectionManager.java index 574d8f049..4a9c92a27 100644 --- a/core/sunbird-es-utils/src/main/java/org/sunbird/helper/ConnectionManager.java +++ b/core/sunbird-es-utils/src/main/java/org/sunbird/helper/ConnectionManager.java @@ -7,8 +7,8 @@ import org.apache.http.HttpHost; import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestHighLevelClient; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.models.util.LoggerUtil; +import org.sunbird.keys.JsonKey; +import org.sunbird.logging.LoggerUtil; /** * Manages Elasticsearch REST high-level client connections with thread-safe singleton access. diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/pom.xml b/core/sunbird-platform-common/pom.xml similarity index 55% rename from course-mw/sunbird-util/sunbird-platform-core/common-util/pom.xml rename to core/sunbird-platform-common/pom.xml index a4536aabf..55a3ae2e6 100644 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/pom.xml +++ b/core/sunbird-platform-common/pom.xml @@ -1,67 +1,47 @@ + - 4.0.0 - - org.sunbird - common-util - 0.0.1-SNAPSHOT - common-util - http://maven.apache.org org.sunbird - course-mw + core 1.0-SNAPSHOT - ../../../pom.xml - - UTF-8 - 2.13 - 2.13.12 - 1.0.3 - 2.13.5 - 7.3 - 2.0.9 - 0.8.8 - org.sunbird - cloud-store-sdk_2.13 - 1.4.8.1 - + 4.0.0 + sunbird-platform-common + 1.0-SNAPSHOT + Sunbird Platform Common + - junit - junit - 4.13.1 - test + com.fasterxml.jackson.core + jackson-core + ${jackson.version} - org.apache.pekko - pekko-actor_${scala.major.version} - ${pekko.version} - - - org.scala-lang - scala-library - - + com.fasterxml.jackson.core + jackson-databind + ${jackson.version} - org.apache.pekko - pekko-slf4j_${scala.major.version} - ${pekko.version} + com.fasterxml.jackson.core + jackson-annotations + ${jackson.version} + + ch.qos.logback logback-classic - 1.2.3 + ${logback.version} ch.qos.logback logback-core - 1.2.3 + ${logback.version} net.logstash.logback @@ -82,33 +62,65 @@ - + + + + org.apache.pekko + pekko-actor_2.13 + ${pekko.version} + + + org.apache.commons commons-lang3 - 3.0 + ${commons-lang3.version} - - org.keycloak - keycloak-admin-client - 21.1.2 + commons-collections + commons-collections + ${commons-collections.version} - org.jboss.resteasy - jaxrs-api - 3.0.11.Final + commons-validator + commons-validator + ${commons-validator.version} - org.jboss.resteasy - resteasy-client - 4.7.9.Final + org.apache.commons + commons-collections4 + ${commons-collections4.version} + + + + + com.mashape.unirest + unirest-java + ${unirest.version} + + + + + org.apache.httpcomponents + httpclient + ${httpcomponents.httpclient.version} + + + org.apache.httpcomponents + httpcore + ${httpcomponents.httpcore.version} - + + org.apache.httpcomponents + httpmime + ${httpcomponents.httpmime.version} + + + org.apache.velocity velocity-tools - 2.0 + ${velocity-tools.version} commons-collections @@ -116,28 +128,27 @@ + + - commons-collections - commons-collections - 3.2.2 + org.keycloak + keycloak-admin-client + ${keycloak.version} - - javax.mail - javax.mail-api - 1.5.1 + org.jboss.resteasy + jaxrs-api + ${jaxrs-api.version} - - com.sun.mail - javax.mail - 1.6.0 + org.jboss.resteasy + resteasy-client + ${resteasy-client.version} - org.jboss.resteasy resteasy-jackson2-provider - 3.1.3.Final + ${resteasy-jackson2-provider.version} com.fasterxml.jackson.core @@ -150,13 +161,35 @@ - + + + com.googlecode.libphonenumber + libphonenumber + ${libphonenumber.version} + + + + + com.google.guava + guava + ${guava.version} + + + + + org.scala-lang + scala-library + 2.13.12 + + + com.moparisthebest junidecode 0.1.1 - + + org.apache.poi poi-ooxml @@ -173,92 +206,12 @@ xmlbeans 3.0.0 - - com.fasterxml.jackson.core - jackson-core - ${jackson.version} - - - com.fasterxml.jackson.core - jackson-databind - ${jackson.version} - - - com.fasterxml.jackson.core - jackson-annotations - ${jackson.version} - - - - org.apache.commons - commons-csv - 1.4 - - - - org.jvnet.mock-javamail - mock-javamail - 1.9 - test - - - - com.googlecode.libphonenumber - libphonenumber - 8.10.2 - - - - - org.apache.httpcomponents - httpclient - 4.5.14 - - - - - org.apache.httpcomponents - httpmime - 4.5.2 - - - org.powermock - powermock-api-mockito2 - ${powermock.version} - test - - - org.powermock - powermock-module-junit4 - ${powermock.version} - test - - - org.javassist - javassist - 3.30.2-GA - - - - - org.apache.httpcomponents - httpcore - 4.4.4 - - - com.mashape.unirest - unirest-java - 1.4.9 - + - com.google.guava - guava - - - ${CLOUD_STORAGE_GROUP_ID} - ${CLOUD_STORE_ARTIFACT_ID} - ${CLOUD_STORE_VERSION} + org.sunbird + cloud-store-sdk_2.13 + ${cloud-store-sdk.version} org.apache.avro @@ -326,137 +279,87 @@ + + - org.apache.zookeeper - zookeeper - 3.7.2 + org.elasticsearch.client + elasticsearch-rest-high-level-client + ${elasticsearch.version} - io.netty - * + org.apache.httpcomponents + httpasyncclient + + + org.apache.httpcomponents + httpcore-nio + + + org.apache.httpcomponents + httpclient + + + org.apache.httpcomponents + httpcore + + - org.apache.avro - avro - 1.11.4 + com.datastax.cassandra + cassandra-driver-core + ${cassandra.driver.version} + + + io.netty + * + + + com.google.guava + guava + + - + + - org.yaml - snakeyaml - 1.33 + junit + junit + ${junit.version} test - com.fasterxml.jackson.module - jackson-module-scala_${scala.major.version} - ${jackson.version} + org.powermock + powermock-module-junit4 + ${powermock.version} + test - org.scala-lang - scala-library + junit + junit - org.scala-lang - scala-library - ${scala.version} - - - org.glassfish.jersey.core - jersey-common - 2.27 - - - org.glassfish.jersey.core - jersey-client - 2.27 - - - org.glassfish.jersey.core - jersey-server - 2.27 + org.powermock + powermock-api-mockito2 + ${powermock.version} + test + org.apache.kafka kafka-clients - 3.7.1 + ${kafka.version} - + cloud-store https://oss.sonatype.org/content/repositories/orgsunbird-1021 - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.8.1 - - 11 - - - - - org.apache.maven.plugins - maven-checkstyle-plugin - 2.17 - - - org.apache.maven.plugins - maven-surefire-plugin - 3.0.0 - - - --add-opens java.base/java.util=ALL-UNNAMED - --add-opens java.base/java.lang=ALL-UNNAMED - --add-opens java.base/java.lang.reflect=ALL-UNNAMED - --add-opens java.base/java.text=ALL-UNNAMED - --add-opens java.base/java.util.concurrent=ALL-UNNAMED - --add-opens java.base/sun.nio.ch=ALL-UNNAMED - --add-opens java.base/java.nio.charset=ALL-UNNAMED - --add-opens java.base/java.io=ALL-UNNAMED - --add-opens java.base/sun.net.www.protocol.jar=ALL-UNNAMED - - - - - - - - - org.jacoco - jacoco-maven-plugin - ${jacoco-maven-plugin.version} - - ${basedir}/target/coverage-reports/jacoco-unit.exec - ${basedir}/target/coverage-reports/jacoco-unit.exec - - - - jacoco-initialize - - prepare-agent - - - - jacoco-site - package - - report - - - - - - \ No newline at end of file diff --git a/core/sunbird-platform-common/src/main/java/org/sunbird/auth/verifier/AccessTokenValidator.java b/core/sunbird-platform-common/src/main/java/org/sunbird/auth/verifier/AccessTokenValidator.java new file mode 100644 index 000000000..b68404104 --- /dev/null +++ b/core/sunbird-platform-common/src/main/java/org/sunbird/auth/verifier/AccessTokenValidator.java @@ -0,0 +1,340 @@ +package org.sunbird.auth.verifier; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import java.nio.charset.StandardCharsets; +import java.util.Collections; +import java.util.Map; +import org.apache.commons.collections4.MapUtils; +import org.apache.commons.lang3.StringUtils; +import org.keycloak.common.util.Time; +import org.sunbird.keys.JsonKey; +import org.sunbird.logging.LoggerUtil; + +public class AccessTokenValidator { + + 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); + // Preserving the typo RELAM if it exists in JsonKey, but usually it should be REALM. + // Assuming original code was correct about the constant name. + private static final String realm = System.getenv(JsonKey.SUNBIRD_SSO_RELAM); + + /** + * Validates the access token. Checks signature and expiration. + * + * @param token The JWT access token string. + * @param requestContext Context for logging/tracing. + * @return Map containing the token claims if valid, empty map otherwise. + * @throws JsonProcessingException if token parsing fails. + */ + public static Map validateToken(String token, Map requestContext) + throws JsonProcessingException { + return validateToken(token, requestContext, true); + } + + /** + * Validates the access token, with optional expiration check. + * + * @param token The JWT access token string. + * @param checkActive If true, checks the 'exp' claim. + * @return Map containing the token claims if valid, empty map otherwise. + * @throws JsonProcessingException if token parsing fails. + */ + public static Map validateToken(String token, boolean checkActive) throws JsonProcessingException { + return validateToken(token, null, checkActive); + } + + /** + * Validates the access token with expiration check enabled (default). + * + * @param token The JWT access token string. + * @return Map containing the token claims if valid, empty map otherwise. + * @throws JsonProcessingException if token parsing fails. + */ + public static Map validateToken(String token) throws JsonProcessingException { + return validateToken(token, null, true); + } + + /** + * Internal method to validate the token. + * + *

This method performs the following steps: + *

    + *
  1. Splits the token into header, body, and signature.
  2. + *
  3. Decodes the header to retrieve the Key ID (kid).
  4. + *
  5. Verifies the RSA signature using the public key associated with the kid.
  6. + *
  7. If the signature is valid, decodes the body.
  8. + *
  9. Optionally checks if the token has expired.
  10. + *
+ * + * @param token The JWT token string. + * @param requestContext The request context (can be null). + * @param checkExpiry Whether to validate the 'exp' claim. + * @return The token body as a Map if valid; otherwise, an empty Map. + * @throws JsonProcessingException If the header or body cannot be parsed as JSON. + */ + private static Map validateToken(String token, Map requestContext, boolean checkExpiry) + throws JsonProcessingException { + String[] tokenElements = token.split("\\."); + // Basic JWT format check + if (tokenElements.length != 3) { + logger.info("Invalid token format: " + token); + return Collections.emptyMap(); + } + + String header = tokenElements[0]; + String body = tokenElements[1]; + String signature = tokenElements[2]; + String payLoad = header + JsonKey.DOT_SEPARATOR + body; + + // Decode header to get Key ID + Map headerData = + mapper.readValue(new String(decodeFromBase64(header), StandardCharsets.UTF_8), Map.class); + String keyId = headerData.get("kid").toString(); + + // Verify Signature + boolean isValid = CryptoUtil.verifyRSASign( + payLoad, + decodeFromBase64(signature), + KeyManager.getPublicKey(keyId).getPublicKey(), + JsonKey.SHA_256_WITH_RSA); + + if (isValid) { + Map tokenBody = + mapper.readValue(new String(decodeFromBase64(body), StandardCharsets.UTF_8), Map.class); + + if (checkExpiry) { + boolean isExp = isExpired((Integer) tokenBody.get("exp")); + if (isExp) { + logger.info("AccessTokenValidator: Token expired. Context: " + requestContext); + return Collections.emptyMap(); + } + } + return tokenBody; + } + return Collections.emptyMap(); + } + + /** + * Managed user token verification. + * Validates the token and ensures the requested user IDs match the token claims. + * + * @param managedEncToken The managed token string. + * @param requestedByUserId User ID of the requester (must match parent). + * @param requestedForUserId User ID of the target user (must match sub). + * @param loggingHeaders Headers for logging logic. + * @return The managed user ID if valid, unauthorized otherwise. + */ + public static String verifyManagedUserToken( + String managedEncToken, String requestedByUserId, String requestedForUserId, String loggingHeaders) { + return verifyManagedUserToken(managedEncToken, requestedByUserId, requestedForUserId, null, loggingHeaders); + } + + /** + * managedtoken is validated and requestedByUserID, requestedForUserID values are validated + * aganist the managedEncToken + * + * @param managedEncToken + * @param requestedByUserId + * @param requestedForUserId + * @param requestContext + * @return + */ + public static String verifyManagedUserToken( + String managedEncToken, + String requestedByUserId, + String requestedForUserId, + Map requestContext) { + return verifyManagedUserToken(managedEncToken, requestedByUserId, requestedForUserId, requestContext, null); + } + + public static String verifyManagedUserToken(String managedEncToken, String requestedByUserId) { + return verifyManagedUserToken(managedEncToken, requestedByUserId, null, null, null); + } + + private static String verifyManagedUserToken( + String managedEncToken, + String requestedByUserId, + String requestedForUserId, + Map requestContext, + String loggingHeaders) { + String managedFor = JsonKey.UNAUTHORIZED; + try { + Map payload; + if (requestContext != null) { + payload = validateToken(managedEncToken, requestContext); + } else { + payload = validateToken(managedEncToken, true); + } + + if (MapUtils.isNotEmpty(payload)) { + String parentId = (String) payload.get(JsonKey.PARENT_ID); + String muaId = (String) payload.get(JsonKey.SUB); + + String logMsg = String.format( + "AccessTokenValidator:verifyManagedUserToken: Parent: %s, ManagedBy: %s, RequestedBy: %s", + parentId, muaId, requestedByUserId); + + if (StringUtils.isNotEmpty(requestedForUserId)) { + logMsg += ", RequestedFor: " + requestedForUserId; + } + if (requestContext != null) { + logMsg += ", Context: " + requestContext; + } + + logger.info(logMsg); + + boolean isValid = parentId.equalsIgnoreCase(requestedByUserId); + if (StringUtils.isNotEmpty(requestedForUserId) && !muaId.equalsIgnoreCase(requestedForUserId)) { + logger.info(String.format( + "AccessTokenValidator:verifyManagedUserToken: Mismatch! RequestedFor: %s, ManagedBy: %s, Headers: %s", + requestedForUserId, muaId, loggingHeaders)); + // If requestedForUserId is present, it MUST match muaId for the token to be valid for that target + if (isValid) { + isValid = muaId.equalsIgnoreCase(requestedForUserId); + } + } + + if (isValid) { + managedFor = muaId; + } + } + } catch (Exception ex) { + String errorMsg = "Exception in verifyManagedUserToken: Token : " + managedEncToken; + if (requestContext != null) { + errorMsg += ", request context data :" + requestContext; + } + logger.error(errorMsg, ex); + } + return managedFor; + } + + /** + * Verifies the user access token. + * + * @param token The JWT access token. + * @param checkActive Whether to check for token expiration. + * @return The user ID from the token if valid, unauthorized otherwise. + */ + public static String verifyUserToken(String token, boolean checkActive) { + return verifyUserToken(token, null, checkActive); + } + + /** + * Verifies the user access token. + * + * @param token The JWT access token. + * @param requestContext Context for logging/tracing. + * @return The user ID from the token if valid, unauthorized otherwise. + */ + public static String verifyUserToken(String token, Map requestContext) { + return verifyUserToken(token, requestContext, true); + } + + /** + * Verifies the user access token with default expiration check. + * + * @param token The JWT access token. + * @return The user ID from the token if valid, unauthorized otherwise. + */ + public static String verifyUserToken(String token) { + return verifyUserToken(token, null, true); + } + + private static String verifyUserToken(String token, Map requestContext, boolean checkActive) { + String userId = JsonKey.UNAUTHORIZED; + try { + Map payload; + if (requestContext != null) { + payload = validateToken(token, requestContext); + logger.debug( + String.format("AccessTokenValidator:verifyUserToken: Payload: %s, Context: %s", + payload, requestContext)); + } else { + payload = validateToken(token, checkActive); + } + + if (MapUtils.isNotEmpty(payload) && checkIss((String) payload.get("iss"))) { + userId = (String) payload.get(JsonKey.SUB); + if (StringUtils.isNotBlank(userId)) { + int pos = userId.lastIndexOf(":"); + userId = userId.substring(pos + 1); + } + } + } catch (Exception ex) { + String errorMsg = "Exception in verifyUserAccessToken: Token : " + token; + if (requestContext != null) { + errorMsg += ", request context data :" + requestContext; + } + logger.error(errorMsg, ex); + } + + if (JsonKey.UNAUTHORIZED.equalsIgnoreCase(userId) && requestContext != null) { + logger.info( + String.format("AccessTokenValidator:verifyUserToken: Invalid Token. Context: %s", requestContext)); + } + + return userId; + } + + /** + * Verifies the user token against a specific source URL. + * + * @param token The JWT access token string. + * @param url The source URL (SSO URL). If null, defaults to environment SUNBIRD_SSO_URL. + * @param requestContext Context for logging/tracing. + * @return The userId from the token if valid, otherwise JsonKey.UNAUTHORIZED. + */ + public static String verifySourceUserToken(String token, String url, Map requestContext) { + String userId = JsonKey.UNAUTHORIZED; + try { + Map payload = validateToken(token, requestContext); + if (requestContext != null) { + logger.debug( + String.format("AccessTokenValidator:verifySourceUserToken: Payload: %s, Context: %s", + payload, 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) { + String errorMsg = "Exception in verifySourceUserToken: Token : " + token; + if (requestContext != null) { + errorMsg += ", request context data :" + requestContext; + } + logger.error(errorMsg, ex); + } + + if (JsonKey.UNAUTHORIZED.equalsIgnoreCase(userId) && requestContext != null) { + logger.info( + String.format("AccessTokenValidator:verifySourceUserToken: Invalid Source Token. Context: %s", requestContext)); + } + return userId; + } + + 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 checkIss(String iss) { + String realmUrl = sso_url + "realms/" + realm; + return (realmUrl.equalsIgnoreCase(iss)); + } + + private static boolean isExpired(Integer expiration) { + return (Time.currentTime() > expiration); + } + + private static byte[] decodeFromBase64(String data) { + return Base64Util.decode(data, 11); + } +} diff --git a/core/sunbird-platform-common/src/main/java/org/sunbird/auth/verifier/Base64Util.java b/core/sunbird-platform-common/src/main/java/org/sunbird/auth/verifier/Base64Util.java new file mode 100644 index 000000000..cfe4bba79 --- /dev/null +++ b/core/sunbird-platform-common/src/main/java/org/sunbird/auth/verifier/Base64Util.java @@ -0,0 +1,692 @@ +package org.sunbird.auth.verifier; + +/* + * Copyright (C) 2010 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.UnsupportedEncodingException; + +/** + * Utilities for encoding and decoding the Base64 representation of binary data. See RFCs 2045 and 3548. + */ +public class Base64Util { + /** Default values for encoder/decoder flags. */ + public static final int DEFAULT = 0; + + /** Encoder flag bit to omit the padding '=' characters at the end of the output (if any). */ + public static final int NO_PADDING = 1; + + /** Encoder flag bit to omit all line terminators (i.e., the output will be on one long line). */ + public static final int NO_WRAP = 2; + + /** + * Encoder flag bit to indicate lines should be terminated with a CRLF pair instead of just an LF. + * Has no effect if {@code NO_WRAP} is specified as well. + */ + public static final int CRLF = 4; + + /** + * Encoder/decoder flag bit to indicate using the "URL and filename safe" variant of Base64 (see + * RFC 3548 section 4) where {@code -} and {@code _} are used in place of {@code +} and {@code /}. + */ + public static final int URL_SAFE = 8; + + /** + * Flag to pass to {Base64OutputStream} to indicate that it should not close the output stream it + * is wrapping when it itself is closed. + */ + public static final int NO_CLOSE = 16; + + // -------------------------------------------------------- + // shared code + // -------------------------------------------------------- + + private Base64Util() {} // don't instantiate + + // -------------------------------------------------------- + // decoding + // -------------------------------------------------------- + + /** + * Decode the Base64-encoded data in input and return the data in a new byte array. + * + *

+ * + *

The padding '=' characters at the end are considered optional, but if any are present, there + * must be the correct number of them. + * + * @param str the input String to decode, which is converted to bytes using the default charset + * @param flags controls certain features of the decoded output. Pass {@code DEFAULT} to decode + * standard Base64. + * @throws IllegalArgumentException if the input contains incorrect padding + */ + public static byte[] decode(String str, int flags) { + return decode(str.getBytes(), flags); + } + + /** + * Decode the Base64-encoded data in input and return the data in a new byte array. + * + *

+ * + *

The padding '=' characters at the end are considered optional, but if any are present, there + * must be the correct number of them. + * + * @param input the input array to decode + * @param flags controls certain features of the decoded output. Pass {@code DEFAULT} to decode + * standard Base64. + * @throws IllegalArgumentException if the input contains incorrect padding + */ + public static byte[] decode(byte[] input, int flags) { + return decode(input, 0, input.length, flags); + } + + /** + * Decode the Base64-encoded data in input and return the data in a new byte array. + * + *

+ * + *

The padding '=' characters at the end are considered optional, but if any are present, there + * must be the correct number of them. + * + * @param input the data to decode + * @param offset the position within the input array at which to start + * @param len the number of bytes of input to decode + * @param flags controls certain features of the decoded output. Pass {@code DEFAULT} to decode + * standard Base64. + * @throws IllegalArgumentException if the input contains incorrect padding + */ + public static byte[] decode(byte[] input, int offset, int len, int flags) { + // Allocate space for the most data the input could represent. + // (It could contain less if it contains whitespace, etc.) + Decoder decoder = new Decoder(flags, new byte[len * 3 / 4]); + + if (!decoder.process(input, offset, len, true)) { + throw new IllegalArgumentException("bad base-64"); + } + + // Maybe we got lucky and allocated exactly enough output space. + if (decoder.op == decoder.output.length) { + return decoder.output; + } + + // Need to shorten the array, so allocate a new one of the + // right size and copy. + byte[] temp = new byte[decoder.op]; + System.arraycopy(decoder.output, 0, temp, 0, decoder.op); + return temp; + } + + /** + * Base64-encode the given data and return a newly allocated String with the result. + * + * @param input the data to encode + * @param flags controls certain features of the encoded output. Passing {@code DEFAULT} results + * in output that adheres to RFC 2045. + */ + public static String encodeToString(byte[] input, int flags) { + try { + return new String(encode(input, flags), "US-ASCII"); + } catch (UnsupportedEncodingException e) { + // US-ASCII is guaranteed to be available. + throw new AssertionError(e); + } + } + + // -------------------------------------------------------- + // encoding + // -------------------------------------------------------- + + /** + * Base64-encode the given data and return a newly allocated String with the result. + * + * @param input the data to encode + * @param offset the position within the input array at which to start + * @param len the number of bytes of input to encode + * @param flags controls certain features of the encoded output. Passing {@code DEFAULT} results + * in output that adheres to RFC 2045. + */ + public static String encodeToString(byte[] input, int offset, int len, int flags) { + try { + return new String(encode(input, offset, len, flags), "US-ASCII"); + } catch (UnsupportedEncodingException e) { + // US-ASCII is guaranteed to be available. + throw new AssertionError(e); + } + } + + /** + * Base64-encode the given data and return a newly allocated byte[] with the result. + * + * @param input the data to encode + * @param flags controls certain features of the encoded output. Passing {@code DEFAULT} results + * in output that adheres to RFC 2045. + */ + public static byte[] encode(byte[] input, int flags) { + return encode(input, 0, input.length, flags); + } + + /** + * Base64-encode the given data and return a newly allocated byte[] with the result. + * + * @param input the data to encode + * @param offset the position within the input array at which to start + * @param len the number of bytes of input to encode + * @param flags controls certain features of the encoded output. Passing {@code DEFAULT} results + * in output that adheres to RFC 2045. + */ + public static byte[] encode(byte[] input, int offset, int len, int flags) { + Encoder encoder = new Encoder(flags, null); + + // Compute the exact length of the array we will produce. + int output_len = len / 3 * 4; + + // Account for the tail of the data and the padding bytes, if any. + if (encoder.do_padding) { + if (len % 3 > 0) { + output_len += 4; + } + } else { + switch (len % 3) { + case 0: + break; + case 1: + output_len += 2; + break; + case 2: + output_len += 3; + break; + } + } + + // Account for the newlines, if any. + if (encoder.do_newline && len > 0) { + output_len += (((len - 1) / (3 * Encoder.LINE_GROUPS)) + 1) * (encoder.do_cr ? 2 : 1); + } + + encoder.output = new byte[output_len]; + encoder.process(input, offset, len, true); + + assert encoder.op == output_len; + + return encoder.output; + } + + /* package */ abstract static class Coder { + public byte[] output; + public int op; + + /** + * Encode/decode another block of input data. this.output is provided by the caller, and must be + * big enough to hold all the coded data. On exit, this.opwill be set to the length of the coded + * data. + * + * @param finish true if this is the final call to process for this object. Will finalize the + * coder state and include any final bytes in the output. + * @return true if the input so far is good; false if some error has been detected in the input + * stream.. + */ + public abstract boolean process(byte[] input, int offset, int len, boolean finish); + + /** + * @return the maximum number of bytes a call to process() could produce for the given number of + * input bytes. This may be an overestimate. + */ + public abstract int maxOutputSize(int len); + } + + /* package */ static class Decoder extends Coder { + /** Lookup table for turning bytes into their position in the Base64 alphabet. */ + private static final int DECODE[] = { + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, + 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -2, -1, -1, + -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, + 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, + -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, + 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + }; + + /** + * Decode lookup table for the "web safe" variant (RFC 3548 sec. 4) where - and _ replace + and + * /. + */ + private static final int DECODE_WEBSAFE[] = { + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, + 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -2, -1, -1, + -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, + 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, 63, + -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, + 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + }; + + /** Non-data values in the DECODE arrays. */ + private static final int SKIP = -1; + + private static final int EQUALS = -2; + private final int[] alphabet; + /** + * States 0-3 are reading through the next input tuple. State 4 is having read one '=' and + * expecting exactly one more. State 5 is expecting no more data or padding characters in the + * input. State 6 is the error state; an error has been detected in the input and no future + * input can "fix" it. + */ + private int state; // state number (0 to 6) + + private int value; + + public Decoder(int flags, byte[] output) { + this.output = output; + + alphabet = ((flags & URL_SAFE) == 0) ? DECODE : DECODE_WEBSAFE; + state = 0; + value = 0; + } + + /** @return an overestimate for the number of bytes {@code len} bytes could decode to. */ + public int maxOutputSize(int len) { + return len * 3 / 4 + 10; + } + + /** + * Decode another block of input data. + * + * @return true if the state machine is still healthy. false if bad base-64 data has been + * detected in the input stream. + */ + public boolean process(byte[] input, int offset, int len, boolean finish) { + if (this.state == 6) return false; + + int p = offset; + len += offset; + + // Using local variables makes the decoder about 12% + // faster than if we manipulate the member variables in + // the loop. (Even alphabet makes a measurable + // difference, which is somewhat surprising to me since + // the member variable is final.) + int state = this.state; + int value = this.value; + int op = 0; + final byte[] output = this.output; + final int[] alphabet = this.alphabet; + + while (p < len) { + // Try the fast path: we're starting a new tuple and the + // next four bytes of the input stream are all data + // bytes. This corresponds to going through states + // 0-1-2-3-0. We expect to use this method for most of + // the data. + // + // If any of the next four bytes of input are non-data + // (whitespace, etc.), value will end up negative. (All + // the non-data values in decode are small negative + // numbers, so shifting any of them up and or'ing them + // together will result in a value with its top bit set.) + // + // You can remove this whole block and the output should + // be the same, just slower. + if (state == 0) { + while (p + 4 <= len + && (value = + ((alphabet[input[p] & 0xff] << 18) + | (alphabet[input[p + 1] & 0xff] << 12) + | (alphabet[input[p + 2] & 0xff] << 6) + | (alphabet[input[p + 3] & 0xff]))) + >= 0) { + output[op + 2] = (byte) value; + output[op + 1] = (byte) (value >> 8); + output[op] = (byte) (value >> 16); + op += 3; + p += 4; + } + if (p >= len) break; + } + + // The fast path isn't available -- either we've read a + // partial tuple, or the next four input bytes aren't all + // data, or whatever. Fall back to the slower state + // machine implementation. + + int d = alphabet[input[p++] & 0xff]; + + switch (state) { + case 0: + if (d >= 0) { + value = d; + ++state; + } else if (d != SKIP) { + this.state = 6; + return false; + } + break; + + case 1: + if (d >= 0) { + value = (value << 6) | d; + ++state; + } else if (d != SKIP) { + this.state = 6; + return false; + } + break; + + case 2: + if (d >= 0) { + value = (value << 6) | d; + ++state; + } else if (d == EQUALS) { + // Emit the last (partial) output tuple; + // expect exactly one more padding character. + output[op++] = (byte) (value >> 4); + state = 4; + } else if (d != SKIP) { + this.state = 6; + return false; + } + break; + + case 3: + if (d >= 0) { + // Emit the output triple and return to state 0. + value = (value << 6) | d; + output[op + 2] = (byte) value; + output[op + 1] = (byte) (value >> 8); + output[op] = (byte) (value >> 16); + op += 3; + state = 0; + } else if (d == EQUALS) { + // Emit the last (partial) output tuple; + // expect no further data or padding characters. + output[op + 1] = (byte) (value >> 2); + output[op] = (byte) (value >> 10); + op += 2; + state = 5; + } else if (d != SKIP) { + this.state = 6; + return false; + } + break; + + case 4: + if (d == EQUALS) { + ++state; + } else if (d != SKIP) { + this.state = 6; + return false; + } + break; + + case 5: + if (d != SKIP) { + this.state = 6; + return false; + } + break; + } + } + + if (!finish) { + // We're out of input, but a future call could provide + // more. + this.state = state; + this.value = value; + this.op = op; + return true; + } + + // Done reading input. Now figure out where we are left in + // the state machine and finish up. + + switch (state) { + case 0: + // Output length is a multiple of three. Fine. + break; + case 1: + // Read one extra input byte, which isn't enough to + // make another output byte. Illegal. + this.state = 6; + return false; + case 2: + // Read two extra input bytes, enough to emit 1 more + // output byte. Fine. + output[op++] = (byte) (value >> 4); + break; + case 3: + // Read three extra input bytes, enough to emit 2 more + // output bytes. Fine. + output[op++] = (byte) (value >> 10); + output[op++] = (byte) (value >> 2); + break; + case 4: + // Read one padding '=' when we expected 2. Illegal. + this.state = 6; + return false; + case 5: + // Read all the padding '='s we expected and no more. + // Fine. + break; + } + + this.state = state; + this.op = op; + return true; + } + } + + /* package */ static class Encoder extends Coder { + /** + * Emit a new line every this many output tuples. Corresponds to a 76-character line length (the + * maximum allowable according to RFC 2045). + */ + public static final int LINE_GROUPS = 19; + + /** Lookup table for turning Base64 alphabet positions (6 bits) into output bytes. */ + private static final byte ENCODE[] = { + 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', + 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', + 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', + 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/', + }; + + /** Lookup table for turning Base64 alphabet positions (6 bits) into output bytes. */ + private static final byte ENCODE_WEBSAFE[] = { + 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', + 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', + 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', + 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', '_', + }; + + public final boolean do_padding; + public final boolean do_newline; + public final boolean do_cr; + private final byte[] tail; + private final byte[] alphabet; + /* package */ int tailLen; + private int count; + + public Encoder(int flags, byte[] output) { + this.output = output; + + do_padding = (flags & NO_PADDING) == 0; + do_newline = (flags & NO_WRAP) == 0; + do_cr = (flags & CRLF) != 0; + alphabet = ((flags & URL_SAFE) == 0) ? ENCODE : ENCODE_WEBSAFE; + + tail = new byte[2]; + tailLen = 0; + + count = do_newline ? LINE_GROUPS : -1; + } + + /** @return an overestimate for the number of bytes {@code len} bytes could encode to. */ + public int maxOutputSize(int len) { + return len * 8 / 5 + 10; + } + + public boolean process(byte[] input, int offset, int len, boolean finish) { + // Using local variables makes the encoder about 9% faster. + final byte[] alphabet = this.alphabet; + final byte[] output = this.output; + int op = 0; + int count = this.count; + + int p = offset; + len += offset; + int v = -1; + + // First we need to concatenate the tail of the previous call + // with any input bytes available now and see if we can empty + // the tail. + + switch (tailLen) { + case 0: + // There was no tail. + break; + + case 1: + if (p + 2 <= len) { + // A 1-byte tail with at least 2 bytes of + // input available now. + v = ((tail[0] & 0xff) << 16) | ((input[p++] & 0xff) << 8) | (input[p++] & 0xff); + tailLen = 0; + } + ; + break; + + case 2: + if (p + 1 <= len) { + // A 2-byte tail with at least 1 byte of input. + v = ((tail[0] & 0xff) << 16) | ((tail[1] & 0xff) << 8) | (input[p++] & 0xff); + tailLen = 0; + } + break; + } + + if (v != -1) { + output[op++] = alphabet[(v >> 18) & 0x3f]; + output[op++] = alphabet[(v >> 12) & 0x3f]; + output[op++] = alphabet[(v >> 6) & 0x3f]; + output[op++] = alphabet[v & 0x3f]; + if (--count == 0) { + if (do_cr) output[op++] = '\r'; + output[op++] = '\n'; + count = LINE_GROUPS; + } + } + + // At this point either there is no tail, or there are fewer + // than 3 bytes of input available. + + // The main loop, turning 3 input bytes into 4 output bytes on + // each iteration. + while (p + 3 <= len) { + v = ((input[p] & 0xff) << 16) | ((input[p + 1] & 0xff) << 8) | (input[p + 2] & 0xff); + output[op] = alphabet[(v >> 18) & 0x3f]; + output[op + 1] = alphabet[(v >> 12) & 0x3f]; + output[op + 2] = alphabet[(v >> 6) & 0x3f]; + output[op + 3] = alphabet[v & 0x3f]; + p += 3; + op += 4; + if (--count == 0) { + if (do_cr) output[op++] = '\r'; + output[op++] = '\n'; + count = LINE_GROUPS; + } + } + + if (finish) { + // Finish up the tail of the input. Note that we need to + // consume any bytes in tail before any bytes + // remaining in input; there should be at most two bytes + // total. + + if (p - tailLen == len - 1) { + int t = 0; + v = ((tailLen > 0 ? tail[t++] : input[p++]) & 0xff) << 4; + tailLen -= t; + output[op++] = alphabet[(v >> 6) & 0x3f]; + output[op++] = alphabet[v & 0x3f]; + if (do_padding) { + output[op++] = '='; + output[op++] = '='; + } + if (do_newline) { + if (do_cr) output[op++] = '\r'; + output[op++] = '\n'; + } + } else if (p - tailLen == len - 2) { + int t = 0; + v = + (((tailLen > 1 ? tail[t++] : input[p++]) & 0xff) << 10) + | (((tailLen > 0 ? tail[t++] : input[p++]) & 0xff) << 2); + tailLen -= t; + output[op++] = alphabet[(v >> 12) & 0x3f]; + output[op++] = alphabet[(v >> 6) & 0x3f]; + output[op++] = alphabet[v & 0x3f]; + if (do_padding) { + output[op++] = '='; + } + if (do_newline) { + if (do_cr) output[op++] = '\r'; + output[op++] = '\n'; + } + } else if (do_newline && op > 0 && count != LINE_GROUPS) { + if (do_cr) output[op++] = '\r'; + output[op++] = '\n'; + } + + assert tailLen == 0; + assert p == len; + } else { + // Save the leftovers in tail to be consumed on the next + // call to encodeInternal. + + if (p == len - 1) { + tail[tailLen++] = input[p]; + } else if (p == len - 2) { + tail[tailLen++] = input[p]; + tail[tailLen++] = input[p + 1]; + } + } + + this.op = op; + this.count = count; + + return true; + } + } +} diff --git a/core/sunbird-platform-common/src/main/java/org/sunbird/auth/verifier/CryptoUtil.java b/core/sunbird-platform-common/src/main/java/org/sunbird/auth/verifier/CryptoUtil.java new file mode 100644 index 000000000..7918ad043 --- /dev/null +++ b/core/sunbird-platform-common/src/main/java/org/sunbird/auth/verifier/CryptoUtil.java @@ -0,0 +1,61 @@ +package org.sunbird.auth.verifier; + +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 final LoggerUtil logger = new LoggerUtil(CryptoUtil.class); + + /** + * Verifies the RSA signature. + * + * @param payLoad The string payload. + * @param signature The signature bytes. + * @param key The public key. + * @param algorithm The signature algorithm (e.g., SHA256withRSA). + * @return True if verification succeeds, false otherwise. + */ + public static boolean verifyRSASign( + String payLoad, byte[] signature, PublicKey key, String algorithm) { + return verifyRSASign(payLoad, signature, key, algorithm, null); + } + + /** + * Verifies the RSA signature with logging context. + * + * @param payLoad The string payload. + * @param signature The signature bytes. + * @param key The public key. + * @param algorithm The signature algorithm. + * @param requestContext Context for logging (optional). + * @return True if verification succeeds, false otherwise. + */ + public static boolean verifyRSASign( + String payLoad, + byte[] signature, + PublicKey key, + String algorithm, + Map requestContext) { + Signature sign; + try { + sign = Signature.getInstance(algorithm); + sign.initVerify(key); + sign.update(payLoad.getBytes(US_ASCII)); + return sign.verify(signature); + } catch (NoSuchAlgorithmException | InvalidKeyException | SignatureException e) { + String msg = String.format("CryptoUtil:verifyRSASign: Exception occurred while token verification. Error: %s", e.getMessage()); + if (requestContext != null) { + msg += ", Context: " + requestContext; + } + logger.error(msg, e); + return false; + } + } +} diff --git a/course-mw/sunbird-util/sunbird-platform-core/auth-verifier/src/main/java/org/sunbird/auth/verifier/KeyData.java b/core/sunbird-platform-common/src/main/java/org/sunbird/auth/verifier/KeyData.java similarity index 57% rename from course-mw/sunbird-util/sunbird-platform-core/auth-verifier/src/main/java/org/sunbird/auth/verifier/KeyData.java rename to core/sunbird-platform-common/src/main/java/org/sunbird/auth/verifier/KeyData.java index db6c33208..d4ed6e304 100644 --- a/course-mw/sunbird-util/sunbird-platform-core/auth-verifier/src/main/java/org/sunbird/auth/verifier/KeyData.java +++ b/core/sunbird-platform-common/src/main/java/org/sunbird/auth/verifier/KeyData.java @@ -2,27 +2,51 @@ import java.security.PublicKey; +/** + * Pojo for Key Data. + */ public class KeyData { private String keyId; private PublicKey publicKey; + /** + * Constructor + * @param keyId Key Id + * @param publicKey Public Key + */ public KeyData(String keyId, PublicKey publicKey) { this.keyId = keyId; this.publicKey = publicKey; } - public String getKeyId() { + /** + * Get Key Id + * @return keyId + */ + public String getKeyId(){ return keyId; } + /** + * Set Key Id + * @param keyId Key Id + */ public void setKeyId(String keyId) { this.keyId = keyId; } + /** + * Get Public Key + * @return publicKey + */ public PublicKey getPublicKey() { return publicKey; } + /** + * Set Public Key + * @param publicKey Public Key + */ public void setPublicKey(PublicKey publicKey) { this.publicKey = publicKey; } diff --git a/course-mw/sunbird-util/sunbird-platform-core/auth-verifier/src/main/java/org/sunbird/auth/verifier/KeyManager.java b/core/sunbird-platform-common/src/main/java/org/sunbird/auth/verifier/KeyManager.java similarity index 57% rename from course-mw/sunbird-util/sunbird-platform-core/auth-verifier/src/main/java/org/sunbird/auth/verifier/KeyManager.java rename to core/sunbird-platform-common/src/main/java/org/sunbird/auth/verifier/KeyManager.java index ea3cd4ed8..667ef2429 100644 --- a/course-mw/sunbird-util/sunbird-platform-core/auth-verifier/src/main/java/org/sunbird/auth/verifier/KeyManager.java +++ b/core/sunbird-platform-common/src/main/java/org/sunbird/auth/verifier/KeyManager.java @@ -1,12 +1,5 @@ package org.sunbird.auth.verifier; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.models.util.LoggerEnum; -import org.sunbird.common.models.util.LoggerUtil; - -import org.sunbird.common.models.util.ProjectLogger; -import org.sunbird.common.models.util.PropertiesCache; - import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; @@ -19,56 +12,76 @@ import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; +import org.sunbird.keys.JsonKey; +import org.sunbird.logging.LoggerUtil; +import org.sunbird.common.PropertiesCache; +/** + * Manages the loading and retrieval of Public Keys for token verification. + */ public class KeyManager { - private static PropertiesCache propertiesCache = PropertiesCache.getInstance(); - - private static Map keyMap = new HashMap(); - private static LoggerUtil logger = new LoggerUtil(KeyManager.class); + private static final LoggerUtil logger = new LoggerUtil(KeyManager.class); + private static final PropertiesCache propertiesCache = PropertiesCache.getInstance(); + private static final Map keyMap = new HashMap<>(); + /** + * Initializes the KeyManager by loading public keys from the configured base path. + */ public static void init() { String basePath = propertiesCache.getProperty(JsonKey.ACCESS_TOKEN_PUBLICKEY_BASEPATH); + logger.info("KeyManager:init: Starting public key loading from base path: " + basePath); + try (Stream walk = Files.walk(Paths.get(basePath))) { List result = walk.filter(Files::isRegularFile).map(x -> x.toString()).collect(Collectors.toList()); + result.forEach( file -> { try { StringBuilder contentBuilder = new StringBuilder(); Path path = Paths.get(file); Files.lines(path, StandardCharsets.UTF_8) - .forEach( - x -> { - contentBuilder.append(x); - }); + .forEach(contentBuilder::append); + KeyData keyData = new KeyData( path.getFileName().toString(), loadPublicKey(contentBuilder.toString())); keyMap.put(path.getFileName().toString(), keyData); + logger.info("KeyManager:init: Loaded key: " + path.getFileName().toString()); } catch (Exception e) { - logger.error(null,"KeyManager:init: exception in reading public keys ", e); + logger.error("KeyManager:init: Exception in reading public key file: " + file, e); } }); } catch (Exception e) { - logger.error(null,"KeyManager:init: exception in loading publickeys ", e); + logger.error("KeyManager:init: Exception in loading public keys base directory", e); } } + /** + * Retrieves the KeyData for a given Key ID. + * @param keyId The Key ID. + * @return The KeyData object, or null if not found. + */ public static KeyData getPublicKey(String keyId) { return keyMap.get(keyId); } + /** + * Parses a string representation of a public key into a PublicKey object. + * @param key The public key string (PEM format). + * @return The PublicKey object. + * @throws Exception If parsing fails. + */ public static PublicKey loadPublicKey(String key) throws Exception { String publicKey = new String(key.getBytes(), StandardCharsets.UTF_8); publicKey = publicKey.replaceAll("(-+BEGIN PUBLIC KEY-+)", ""); publicKey = publicKey.replaceAll("(-+END PUBLIC KEY-+)", ""); publicKey = publicKey.replaceAll("[\\r\\n]+", ""); - byte[] keyBytes = Base64Util.decode(publicKey.getBytes("UTF-8"), Base64Util.DEFAULT); + byte[] keyBytes = Base64Util.decode(publicKey.getBytes(StandardCharsets.UTF_8), Base64Util.DEFAULT); X509EncodedKeySpec X509publicKey = new X509EncodedKeySpec(keyBytes); KeyFactory kf = KeyFactory.getInstance("RSA"); return kf.generatePublic(X509publicKey); } - } diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/ProjectUtil.java b/core/sunbird-platform-common/src/main/java/org/sunbird/common/ProjectUtil.java similarity index 84% rename from course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/ProjectUtil.java rename to core/sunbird-platform-common/src/main/java/org/sunbird/common/ProjectUtil.java index 748c33507..88ec29024 100644 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/ProjectUtil.java +++ b/core/sunbird-platform-common/src/main/java/org/sunbird/common/ProjectUtil.java @@ -1,19 +1,9 @@ -package org.sunbird.common.models.util; +package org.sunbird.common; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.i18n.phonenumbers.NumberParseException; import com.google.i18n.phonenumbers.PhoneNumberUtil; import com.google.i18n.phonenumbers.Phonenumber; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.validator.UrlValidator; -import org.apache.velocity.Template; -import org.apache.velocity.VelocityContext; -import org.apache.velocity.app.VelocityEngine; -import org.sunbird.common.exception.ProjectCommonException; -import org.sunbird.common.models.util.url.EsConfigUtil; -import org.sunbird.common.request.Request; -import org.sunbird.common.responsecode.ResponseCode; - import java.io.IOException; import java.io.StringWriter; import java.nio.charset.StandardCharsets; @@ -21,15 +11,38 @@ import java.text.MessageFormat; import java.text.ParseException; import java.text.SimpleDateFormat; -import java.util.*; +import java.util.Arrays; +import java.util.Calendar; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.Random; +import java.util.TimeZone; +import java.util.UUID; import java.util.concurrent.atomic.AtomicInteger; import java.util.regex.Matcher; import java.util.regex.Pattern; +import org.apache.commons.lang.StringUtils; +import org.apache.commons.validator.UrlValidator; +import org.apache.velocity.Template; +import org.apache.velocity.VelocityContext; +import org.apache.velocity.app.VelocityEngine; +import org.sunbird.exception.ProjectCommonException; +import org.sunbird.http.HttpUtil; +import org.sunbird.utils.EsConfigUtil; +import org.sunbird.request.Request; +import org.sunbird.response.ResponseCode; +import org.sunbird.keys.JsonKey; +import org.sunbird.logging.LoggerUtil; /** - * This class will contains all the common utility methods. + * Utility class containing common methods and constants used across the project. + * Handles date formatting, email validation, ID generation, and configuration management. * * @author Manzarul + * @author Amit Kumar */ public class ProjectUtil { @@ -80,7 +93,9 @@ public class ProjectUtil { propertiesCache = PropertiesCache.getInstance(); } - /** @author Manzarul */ + /** + * Enumeration for Environment types. + */ public enum Environment { dev(1), qa(2), @@ -96,7 +111,9 @@ public int getValue() { } } - /** @author Amit Kumar */ + /** + * Enumeration for Status. + */ public enum Status { ACTIVE(1), INACTIVE(0); @@ -112,6 +129,9 @@ public int getValue() { } } + /** + * Enumeration for Bulk Process Status. + */ public enum BulkProcessStatus { NEW(0), IN_PROGRESS(1), @@ -130,6 +150,9 @@ public int getValue() { } } + /** + * Enumeration for Org Status. + */ public enum OrgStatus { INACTIVE(0), ACTIVE(1), @@ -147,7 +170,9 @@ public Integer getValue() { } } - /** @author Amit Kumar */ + /** + * Enumeration for Progress Status. + */ public enum ProgressStatus { NOT_STARTED(0), STARTED(1), @@ -164,7 +189,9 @@ public int getValue() { } } - /** @author Amit Kumar */ + /** + * Enumeration for Active Status. + */ public enum ActiveStatus { ACTIVE(true), INACTIVE(false); @@ -180,6 +207,9 @@ public boolean getValue() { } } + /** + * Enumeration for Action. + */ public enum Action { YES(1), NO(0); @@ -195,7 +225,9 @@ public int getValue() { } } - /** @author Amit Kumar */ + /** + * Enumeration for Course Management Status. + */ public enum CourseMgmtStatus { DRAFT("draft"), LIVE("live"), @@ -212,7 +244,9 @@ public String getValue() { } } - /** @author Amit Kumar */ + /** + * Enumeration for Source. + */ public enum Source { WEB("web"), ANDROID("android"), @@ -230,7 +264,9 @@ public String getValue() { } } - /** @author Amit Kumar */ + /** + * Enumeration for User Role. + */ public enum UserRole { PUBLIC("PUBLIC"), CONTENT_CREATOR("CONTENT_CREATOR"), @@ -253,44 +289,46 @@ public String getValue() { * This method will check incoming value is null or empty it will do empty check by doing trim * method. in case of null or empty it will return true else false. * - * @param value - * @return + * @param value String value to check + * @return boolean true if null or empty */ public static boolean isStringNullOREmpty(String value) { return (value == null || "".equals(value.trim())); } /** - * This method will provide formatted date + * This method will provide formatted date. * - * @return + * @return String formatted date */ public static String getFormattedDate() { return getDateFormatter().format(new Date()); } /** - * This method will provide timestamp + * This method will provide timestamp. * - * @return + * @return Date current timestamp */ public static Date getTimeStamp() { return new Timestamp(System.currentTimeMillis()); } /** - * This method will provide formatted date + * This method will provide formatted date. * - * @return + * @param date Date object + * @return String formatted date */ public static String formatDate(Date date) { if (null != date) return getDateFormatter().format(date); else return null; } + /** - * Validate email with regular expression + * Validate email with regular expression. * - * @param email + * @param email String email * @return true valid email, false invalid email */ public static boolean isEmailvalid(final String email) { @@ -302,11 +340,11 @@ public static boolean isEmailvalid(final String email) { } /** - * This method will generate auth token based on name , source and timestamp + * This method will generate auth token based on name , source and timestamp. * - * @param name String - * @param source String - * @return String + * @param name String name + * @param source String source + * @return String auth token */ public static String createAuthToken(String name, String source) { String data = name + source + System.currentTimeMillis(); @@ -317,8 +355,8 @@ public static String createAuthToken(String name, String source) { /** * This method will generate unique id based on current time stamp and some random value mixed up. * - * @param environmentId int - * @return String + * @param environmentId int environment id + * @return String unique id */ public static String getUniqueIdFromTimestamp(int environmentId) { Random random = new Random(); @@ -329,14 +367,17 @@ public static String getUniqueIdFromTimestamp(int environmentId) { } /** - * This method will generate the unique id . + * This method will generate the unique id. * - * @return + * @return String unique id */ public static synchronized String generateUniqueId() { return UUID.randomUUID().toString(); } + /** + * Enumeration for HTTP Methods. + */ public enum Method { GET, POST, @@ -347,8 +388,6 @@ public enum Method { /** * Enum to hold the index name for Elastic search. - * - * @author Manzarul */ public enum EsIndex { sunbird("searchindex"), @@ -367,8 +406,6 @@ public String getIndexName() { /** * This enum will hold all the ES type name. - * - * @author Manzarul */ public enum EsType { course(EsConfigUtil.getConfigValue(JsonKey.ES_COURSE_INDEX)), @@ -388,6 +425,9 @@ public String getTypeName() { } } + /** + * Enumeration for Section Data Type. + */ public enum SectionDataType { course("course"), content("content"); @@ -402,6 +442,9 @@ public String getTypeName() { } } + /** + * Enumeration for Address Type. + */ public enum AddressType { permanent("permanent"), current("current"), @@ -418,6 +461,9 @@ public String getTypeName() { } } + /** + * Enumeration for Assessment Result. + */ public enum AssessmentResult { gradeA("A", "Pass"), gradeB("B", "Pass"), @@ -443,11 +489,11 @@ public String getResult() { } /** - * This method will calculate the percentage + * This method will calculate the percentage. * - * @param score double - * @param maxScore double - * @return double + * @param score double score + * @param maxScore double max score + * @return double percentage */ public static double calculatePercentage(double score, double maxScore) { double percentage = (score * 100) / (maxScore * 1.0); @@ -457,7 +503,7 @@ public static double calculatePercentage(double score, double maxScore) { /** * This method will calculate grade based on percentage marks. * - * @param percentage double + * @param percentage double percentage * @return AssessmentResult */ public static AssessmentResult calcualteAssessmentResult(double percentage) { @@ -479,28 +525,61 @@ public static AssessmentResult calcualteAssessmentResult(double percentage) { } } + /** + * Checks if object is null. + * + * @param obj Object + * @return boolean true if null + */ public static boolean isNull(Object obj) { return null == obj ? true : false; } + /** + * Checks if object is not null. + * + * @param obj Object + * @return boolean true if not null + */ public static boolean isNotNull(Object obj) { return null != obj ? true : false; } + /** + * Formats message with values. + * + * @param exceptionMsg String message pattern + * @param fieldValue Object... values + * @return String formatted message + */ public static String formatMessage(String exceptionMsg, Object... fieldValue) { return MessageFormat.format(exceptionMsg, fieldValue); } + /** + * Gets default date formatter. + * + * @return SimpleDateFormat + */ public static SimpleDateFormat getDateFormatter() { return getDateFormatter("yyyy-MM-dd HH:mm:ss:SSSZ"); } + /** + * Gets date formatter for pattern. + * + * @param pattern String pattern + * @return SimpleDateFormat + */ public static SimpleDateFormat getDateFormatter(String pattern) { SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern); simpleDateFormat.setLenient(false); return simpleDateFormat; } - /** @author Manzarul */ + + /** + * Enumeration for Enrolment Type. + */ public enum EnrolmentType { open("open"), inviteOnly("invite-only"); @@ -515,6 +594,12 @@ public String getVal() { } } + /** + * Gets Velocity Context from map. + * + * @param map Map data + * @return VelocityContext + */ public static VelocityContext getContext(Map map) { propertiesCache = PropertiesCache.getInstance(); VelocityContext context = new VelocityContext(); @@ -605,7 +690,9 @@ private static Object getValue(Map map, String key) { return value; } - /** @author Arvind */ + /** + * Enumeration for Report Tracking Status. + */ public enum ReportTrackingStatus { NEW(0), GENERATING_DATA(1), @@ -626,6 +713,14 @@ public int getValue() { } } + /** + * Creates health check response. + * + * @param serviceName String service name + * @param isError boolean is error + * @param e Exception + * @return Map response + */ public static Map createCheckResponse( String serviceName, boolean isError, Exception e) { Map responseMap = new HashMap<>(); @@ -654,8 +749,8 @@ public static Map createCheckResponse( * @param tagId String unique tag id. * @param body String requested body * @param header Map - * @return String - * @throws IOException + * @return String tag status + * @throws Exception if error occurs */ public static String registertag(String tagId, String body, Map header) throws Exception { @@ -679,6 +774,9 @@ public static String registertag(String tagId, String body, Map return tagStatus; } + /** + * Enumeration for Object Types. + */ public enum ObjectTypes { user("user"), organisation("organisation"), @@ -695,6 +793,11 @@ public String getValue() { } } + /** + * Generates random password. + * + * @return String random password + */ public static String generateRandomPassword() { String SALTCHARS = "abcdef12345ghijklACDEFGHmnopqrs67IJKLMNOP890tuvQRSTUwxyzVWXYZ"; StringBuilder salt = new StringBuilder(); @@ -708,10 +811,10 @@ public static String generateRandomPassword() { } /** - * This method will do the phone number validation check + * This method will do the phone number validation check. * - * @param phone String - * @return boolean + * @param phone String phone number + * @return boolean true if valid */ public static boolean validatePhoneNumber(String phone) { String phoneNo = ""; @@ -722,6 +825,11 @@ public static boolean validatePhoneNumber(String phone) { else return (phoneNo.matches("\\(\\d{3}\\)-\\d{3}-\\d{4}")); } + /** + * Gets Ekstep header map. + * + * @return Map headers + */ public static Map getEkstepHeader() { Map headerMap = new HashMap<>(); String header = System.getenv(JsonKey.EKSTEP_AUTHORIZATION); @@ -735,6 +843,13 @@ public static Map getEkstepHeader() { return headerMap; } + /** + * Validates phone number with country code. + * + * @param phNumber String phone number + * @param countryCode String country code + * @return boolean true if valid + */ public static boolean validatePhone(String phNumber, String countryCode) { PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.getInstance(); String contryCode = countryCode; @@ -756,6 +871,12 @@ public static boolean validatePhone(String phNumber, String countryCode) { return false; } + /** + * Validates country code. + * + * @param countryCode String country code + * @return boolean true if valid + */ public static boolean validateCountryCode(String countryCode) { String pattern = "^(?:[+] ?){0,1}(?:[0-9] ?){1,3}"; try { @@ -767,6 +888,12 @@ public static boolean validateCountryCode(String countryCode) { } } + /** + * Generates SMS body from template. + * + * @param smsTemplate Map template data + * @return String SMS body + */ public static String getSMSBody(Map smsTemplate) { try { Properties props = new Properties(); @@ -794,6 +921,13 @@ public static String getSMSBody(Map smsTemplate) { return ""; } + /** + * Checks if date is valid format. + * + * @param format String date format + * @param value String date value + * @return boolean true if valid + */ public static boolean isDateValidFormat(String format, String value) { Date date = null; try { @@ -808,7 +942,9 @@ public static boolean isDateValidFormat(String format, String value) { return date != null; } - /** This method will create a new ProjectCommonException of type server Error and throws it. */ + /** + * This method will create a new ProjectCommonException of type server Error and throws it. + */ public static void createAndThrowServerError() { throw new ProjectCommonException( ResponseCode.SERVER_ERROR.getErrorCode(), @@ -851,6 +987,12 @@ public static boolean isUrlvalid(String url) { return urlValidator.isValid(url); } + /** + * Gets config value from env or properties. + * + * @param key String key + * @return String value + */ public static String getConfigValue(String key) { if (StringUtils.isNotBlank(System.getenv(key))) { return System.getenv(key); @@ -859,9 +1001,9 @@ public static String getConfigValue(String key) { } /** - * This method will create index for Elastic search as follow "telemetry.raw.yyyy.mm" + * This method will create index for Elastic search as follow "telemetry.raw.yyyy.mm". * - * @return + * @return String index name */ public static String createIndex() { Calendar cal = Calendar.getInstance(); @@ -877,7 +1019,7 @@ public static String createIndex() { } /** - * This method will check whether Array contains only empty string or not + * This method will check whether Array contains only empty string or not. * * @param strArray String[] * @return boolean @@ -901,7 +1043,7 @@ public static String convertMapToJsonString(List> mapList) { try { return mapper.writeValueAsString(mapList); } catch (IOException e) { - logger.error(null, e.getMessage(), e); + logger.error(null, e.getMessage(), e); } return null; } @@ -970,7 +1112,7 @@ public static Map getDateRange(int numDays) { * This method will be used to create ProjectCommonException for all kind of client error for the * given response code(enum). * - * @param : An enum of all the api responses. + * @param responseCode An enum of all the api responses. * @return ProjectCommonException */ public static ProjectCommonException createClientException(ResponseCode responseCode) { @@ -980,6 +1122,12 @@ public static ProjectCommonException createClientException(ResponseCode response ResponseCode.CLIENT_ERROR.getResponseCode()); } + /** + * Gets LMS User ID from federated ID. + * + * @param fedUserId String federated user id + * @return String user id + */ public static String getLmsUserId(String fedUserId) { String userId = fedUserId; String prefix = @@ -990,11 +1138,18 @@ public static String getLmsUserId(String fedUserId) { return userId; } + /** + * Gets first N characters of string. + * + * @param originalText String original text + * @param noOfChar int number of characters + * @return String first N characters + */ public static String getFirstNCharacterString(String originalText, int noOfChar) { + String firstNChars = ""; if (StringUtils.isBlank(originalText)) { return ""; } - String firstNChars = ""; if (originalText.length() > noOfChar) { firstNChars = originalText.substring(0, noOfChar); } else { @@ -1003,6 +1158,9 @@ public static String getFirstNCharacterString(String originalText, int noOfChar) return firstNChars; } + /** + * Enumeration for Migrate Action. + */ public enum MigrateAction { ACCEPT("accept"), REJECT("reject"); diff --git a/core/sunbird-platform-common/src/main/java/org/sunbird/common/PropertiesCache.java b/core/sunbird-platform-common/src/main/java/org/sunbird/common/PropertiesCache.java new file mode 100644 index 000000000..e2fde9253 --- /dev/null +++ b/core/sunbird-platform-common/src/main/java/org/sunbird/common/PropertiesCache.java @@ -0,0 +1,148 @@ +package org.sunbird.common; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Map; +import java.util.Properties; +import java.util.concurrent.ConcurrentHashMap; +import org.apache.commons.lang3.StringUtils; +import org.sunbird.logging.LoggerUtil; + +/** + * Singleton class to load and manage application configuration properties. + * Reads attributes from multiple property files and provides access validation/defaults. + * + * @author Amit Kumar + */ +public class PropertiesCache { + + private static final LoggerUtil logger = new LoggerUtil(PropertiesCache.class); + private final String[] fileName = { + "elasticsearch.config.properties", + "cassandra.config.properties", + "dbconfig.properties", + "externalresource.properties", + "sso.properties", + "userencryption.properties", + "profilecompleteness.properties", + "mailTemplates.properties" + }; + private final Properties configProp = new Properties(); + public final Map attributePercentageMap = new ConcurrentHashMap<>(); + private static volatile PropertiesCache propertiesCache = null; + + /** + * Private constructor to load properties from files. + * Also initializes weighted attributes for profile completeness. + */ + private PropertiesCache() { + for (String file : fileName) { + try (InputStream in = this.getClass().getClassLoader().getResourceAsStream(file)) { + if (in != null) { + configProp.load(in); + } else { + logger.warn("PropertiesCache: Configuration file not found: " + file, null); + } + } catch (IOException e) { + logger.error("PropertiesCache: Error loading file: " + file, e); + } + } + loadWeighted(); + } + + /** + * Returns the singleton instance of PropertiesCache. + * Uses double-checked locking for thread safety. + * + * @return The singleton PropertiesCache instance. + */ + public static PropertiesCache getInstance() { + if (propertiesCache == null) { + synchronized (PropertiesCache.class) { + if (propertiesCache == null) { + propertiesCache = new PropertiesCache(); + } + } + } + return propertiesCache; + } + + /** + * Saves or updates a configuration property in memory. + * + * @param key The property key. + * @param value The property value. + */ + public void saveConfigProperty(String key, String value) { + configProp.setProperty(key, value); + } + + /** + * Retrieves a property value. + * Checks system environment variables first, then the loaded properties. + * If the value is not found in properties, returns the key itself. + * + * @param key The property key to look up. + * @return The property value or the key if not found. + */ + public String getProperty(String key) { + String value = System.getenv(key); + if (StringUtils.isNotBlank(value)) { + return value; + } + return configProp.getProperty(key) != null ? configProp.getProperty(key) : key; + } + + /** + * Loads weighted attributes for user profile completeness from configuration. + * Parses 'user.profile.attribute' and 'user.profile.weighted' properties. + */ + private void loadWeighted() { + String key = configProp.getProperty("user.profile.attribute"); + String value = configProp.getProperty("user.profile.weighted"); + + if (StringUtils.isBlank(key)) { + logger.info("PropertiesCache:loadWeighted: Profile completeness value is not set."); + return; + } + + String[] keys = key.split(","); + + if (StringUtils.isNotBlank(value)) { + String[] values = value.split(","); + if (keys.length == values.length) { + logger.info("PropertiesCache:loadWeighted: Weighted value is provided by user."); + for (int i = 0; i < keys.length; i++) { + try { + attributePercentageMap.put(keys[i], Float.valueOf(values[i])); + } catch (NumberFormatException e) { + logger.error("PropertiesCache:loadWeighted: Invalid float value for key: " + keys[i], e); + } + } + return; + } + } + + // Fallback: equally divide weight if values are missing or mismatched + logger.info("PropertiesCache:loadWeighted: Weighted value is not provided or mismatched. Distributing equally."); + float perc = 100.0f / keys.length; + for (String k : keys) { + attributePercentageMap.put(k, perc); + } + } + + /** + * Reads a property value from system environment or loaded properties. + * Unlike getProperty, this returns null if key is not found (instead of returning the key). + * + * @param key The property key. + * @return The property value, or null if not found. + */ + public String readProperty(String key) { + String value = System.getenv(key); + if (StringUtils.isNotBlank(value)) { + return value; + } + return configProp.getProperty(key); + } +} diff --git a/core/sunbird-platform-common/src/main/java/org/sunbird/datasecurity/DataMaskingService.java b/core/sunbird-platform-common/src/main/java/org/sunbird/datasecurity/DataMaskingService.java new file mode 100644 index 000000000..7415c48d4 --- /dev/null +++ b/core/sunbird-platform-common/src/main/java/org/sunbird/datasecurity/DataMaskingService.java @@ -0,0 +1,78 @@ +/** */ +package org.sunbird.datasecurity; + +import org.apache.commons.lang3.StringUtils; +import org.sunbird.keys.JsonKey; + +/** + * Service interface for masking sensitive data such as phone numbers, emails, and OTPs. + * Provides default implementations for generic data and OTP masking. + */ +public interface DataMaskingService { + + + /** + * Checks if the given data string contains masked characters (asterisks). + * + * @param data The string to check. + * @return true if the data contains an asterisk, false otherwise. + */ + default boolean isMasked(String data) { + return data.contains(JsonKey.REPLACE_WITH_ASTERISK); + } + + /** + * Masks a phone number. + * + * @param phone The phone number to mask. + * @return The masked phone number. + */ + String maskPhone(String phone); + + /** + * Masks an email address. + * + * @param email The email address to mask. + * @return The masked email address. + */ + String maskEmail(String email); + + /** + * Masks generic data strings. + * If the data is blank or has a length of 3 or less, it is returned as is. + * Otherwise, it masks characters with asterisks, leaving the last 4 characters visible. + * + * @param data The data string to mask. + * @return The masked data string. + */ + default String maskData(String data) { + if (StringUtils.isBlank(data) || data.length() <= 3) { + return data; + } + int lenght = data.length() - 4; + StringBuilder builder = new StringBuilder(); + for (int i = 0; i < data.length(); i++) { + if (i < lenght) { + builder.append(JsonKey.REPLACE_WITH_ASTERISK); + } else { + builder.append(data.charAt(i)); + } + } + return builder.toString(); + } + + /** + * Masks an OTP (One Time Password). + * Depending on the length (>= 6 or < 6), it masks all but the first 4 or 2 characters respectively. + * + * @param otp The OTP string to mask. + * @return The masked OTP string. + */ + default String maskOTP(String otp) { + if (otp.length() >= 6) { + return otp.replaceAll("(^[^*]{4}|(?!^)\\G)[^*]", "$1*"); + } else { + return otp.replaceAll("(^[^*]{2}|(?!^)\\G)[^*]", "$1*"); + } + } +} diff --git a/core/sunbird-platform-common/src/main/java/org/sunbird/datasecurity/DecryptionService.java b/core/sunbird-platform-common/src/main/java/org/sunbird/datasecurity/DecryptionService.java new file mode 100644 index 000000000..80330c808 --- /dev/null +++ b/core/sunbird-platform-common/src/main/java/org/sunbird/datasecurity/DecryptionService.java @@ -0,0 +1,98 @@ +package org.sunbird.datasecurity; + +import java.util.List; +import java.util.Map; +import org.sunbird.request.RequestContext; + +/** + * This service will have data decryption methods. Encryption logic will differ based on implementation classes. + */ +public interface DecryptionService { + + String ALGORITHM = "AES"; + int ITERATIONS = 3; + byte[] keyValue = + new byte[] {'T', 'h', 'i', 's', 'A', 's', 'I', 'S', 'e', 'r', 'c', 'e', 'K', 't', 'e', 'y'}; + + /** + * Decrypts the given data map. Values can be primitives, Strings, or nested Maps. + * + * @param data The map containing data to decrypt. + * @param context The request context. + * @return The map with decrypted values. + */ + Map decryptData(Map data, RequestContext context); + + /** + * Decrypts the given data map. Values can be primitives, Strings, or nested Maps. + * Default implementation calls decryptData(data, null). + * + * @param data The map containing data to decrypt. + * @return The map with decrypted values. + */ + default Map decryptData(Map data) { + return decryptData(data, null); + } + + /** + * Decrypts a list of data maps. + * + * @param data The list of maps to decrypt. + * @param context The request context. + * @return The list of maps with decrypted values. + */ + List> decryptData(List> data, RequestContext context); + + /** + * Decrypts a list of data maps. + * Default implementation calls decryptData(data, null). + * + * @param data The list of maps to decrypt. + * @return The list of maps with decrypted values. + */ + default List> decryptData(List> data) { + return decryptData(data, null); + } + + /** + * Decrypts the given string data. + * + * @param data The string to decrypt. + * @param context The request context. + * @return The decrypted string. + */ + String decryptData(String data, RequestContext context); + + /** + * Decrypts the given string data. + * Default implementation calls decryptData(data, null). + * + * @param data The string to decrypt. + * @return The decrypted string. + */ + default String decryptData(String data) { + return decryptData(data, null); + } + + /** + * Decrypts the given string data with an option to throw an exception on failure. + * + * @param data The string to decrypt. + * @param throwExceptionOnFailure Whether to throw an exception if decryption fails. + * @param context The request context. + * @return The decrypted string. + */ + String decryptData(String data, boolean throwExceptionOnFailure, RequestContext context); + + /** + * Decrypts the given string data with an option to throw an exception on failure. + * Default implementation calls decryptData(data, throwExceptionOnFailure, null). + * + * @param data The string to decrypt. + * @param throwExceptionOnFailure Whether to throw an exception if decryption fails. + * @return The decrypted string. + */ + default String decryptData(String data, boolean throwExceptionOnFailure) { + return decryptData(data, throwExceptionOnFailure, null); + } +} diff --git a/core/sunbird-platform-common/src/main/java/org/sunbird/datasecurity/EncryptionService.java b/core/sunbird-platform-common/src/main/java/org/sunbird/datasecurity/EncryptionService.java new file mode 100644 index 000000000..a053082e9 --- /dev/null +++ b/core/sunbird-platform-common/src/main/java/org/sunbird/datasecurity/EncryptionService.java @@ -0,0 +1,83 @@ +package org.sunbird.datasecurity; + +import java.util.List; +import java.util.Map; +import org.sunbird.request.RequestContext; + +/** + * Service interface for data encryption operations. + * Implementations provide specific encryption logic. + */ +public interface EncryptionService { + + String ALGORITHM = "AES"; + int ITERATIONS = 3; + byte[] keyValue = + new byte[] {'T', 'h', 'i', 's', 'A', 's', 'I', 'S', 'e', 'r', 'c', 'e', 'K', 't', 'e', 'y'}; + + /** + * Encrypts the values in a map. + * + * @param data The map containing data to encrypt. + * @param context The request context. + * @return The map with encrypted values. + * @throws Exception If an error occurs during encryption. + */ + Map encryptData(Map data, RequestContext context); + + /** + * Encrypts the values in a map without a request context. + * Delegates to {@link #encryptData(Map, RequestContext)} with null context. + * + * @param data The map containing data to encrypt. + * @return The map with encrypted values. + * @throws Exception If an error occurs during encryption. + */ + default Map encryptData(Map data) throws Exception { + return encryptData(data, null); + } + + /** + * Encrypts the values in a list of maps. + * + * @param data The list of maps to encrypt. + * @param context The request context. + * @return The list of maps with encrypted values. + * @throws Exception If an error occurs during encryption. + */ + List> encryptData(List> data, RequestContext context); + + /** + * Encrypts the values in a list of maps without a request context. + * Delegates to {@link #encryptData(List, RequestContext)} with null context. + * + * @param data The list of maps to encrypt. + * @return The list of maps with encrypted values. + * @throws Exception If an error occurs during encryption. + */ + default List> encryptData(List> data) throws Exception { + return encryptData(data, null); + } + + /** + * Encrypts a single string value. + * + * @param data The string to encrypt. + * @param context The request context. + * @return The encrypted string. + * @throws Exception If an error occurs during encryption. + */ + String encryptData(String data, RequestContext context); + + /** + * Encrypts a single string value without a request context. + * Delegates to {@link #encryptData(String, RequestContext)} with null context. + * + * @param data The string to encrypt. + * @return The encrypted string. + * @throws Exception If an error occurs during encryption. + */ + default String encryptData(String data) throws Exception { + return encryptData(data, null); + } +} diff --git a/core/sunbird-platform-common/src/main/java/org/sunbird/datasecurity/OneWayHashing.java b/core/sunbird-platform-common/src/main/java/org/sunbird/datasecurity/OneWayHashing.java new file mode 100644 index 000000000..c853e0480 --- /dev/null +++ b/core/sunbird-platform-common/src/main/java/org/sunbird/datasecurity/OneWayHashing.java @@ -0,0 +1,39 @@ +package org.sunbird.datasecurity; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import org.sunbird.logging.LoggerUtil; + +/** + * Utility class for performing one-way data hashing. + * Uses SHA-256 algorithm to hash input strings. + */ +public class OneWayHashing { + + public static LoggerUtil logger = new LoggerUtil(OneWayHashing.class); + + private OneWayHashing() {} + + /** + * Encrypts (hashes) a value using SHA-256 algorithm. + * + * @param val The string value to hash. + * @return The SHA-256 hash of the value in hexadecimal format, or an empty string if an error occurs. + */ + public static String encryptVal(String val) { + try { + MessageDigest md = MessageDigest.getInstance("SHA-256"); + md.update(val.getBytes(StandardCharsets.UTF_8)); + byte[] byteData = md.digest(); + // convert the byte to hex format + StringBuilder sb = new StringBuilder(); + for (byte b : byteData) { + sb.append(Integer.toString((b & 0xff) + 0x100, 16).substring(1)); + } + return sb.toString(); + } catch (Exception e) { + logger.error("Error while encrypting", e); + } + return ""; + } +} diff --git a/core/sunbird-platform-common/src/main/java/org/sunbird/datasecurity/impl/BASE64Decoder.java b/core/sunbird-platform-common/src/main/java/org/sunbird/datasecurity/impl/BASE64Decoder.java new file mode 100644 index 000000000..5363aefed --- /dev/null +++ b/core/sunbird-platform-common/src/main/java/org/sunbird/datasecurity/impl/BASE64Decoder.java @@ -0,0 +1,170 @@ +/* + * Copyright (c) 1995, 2011, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package org.sunbird.datasecurity.impl; + +import java.io.IOException; +import java.io.OutputStream; +import java.io.PushbackInputStream; + +/** + * This class implements a BASE64 Character decoder as specified in RFC1521. + * + *

This RFC is part of the MIME specification which is published by the Internet Engineering Task + * Force (IETF). Unlike some other encoding schemes there is nothing in this encoding that tells the + * decoder where a buffer starts or stops, so to use it you will need to isolate your encoded data + * into a single chunk and then feed them this decoder. The simplest way to do that is to read all + * of the encoded data into a string and then use: + * + *

+ *      byte    mydata[];
+ *      BASE64Decoder base64 = new BASE64Decoder();
+ *
+ *      mydata = base64.decodeBuffer(bufferString);
+ * 
+ * + * This will decode the String in bufferString and give you an array of bytes in the array + * myData. + * + *

On errors, this class throws a CEFormatException with the following detail strings: + * + *

+ *    "BASE64Decoder: Not enough bytes for an atom."
+ * 
+ * + * @author Chuck McManis + * @see CharacterEncoder + * @see BASE64Decoder + */ +public class BASE64Decoder extends CharacterDecoder { + /** + * This class has 4 bytes per atom + * + * @return 4 + */ + protected int bytesPerAtom() { + return (4); + } + + /** + * Any multiple of 4 will do, 72 might be common + * + * @return 72 + */ + protected int bytesPerLine() { + return (72); + } + + /** This character array provides the character to value map based on RFC1521. */ + private static final char pem_array[] = { + // 0 1 2 3 4 5 6 7 + 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', // 0 + 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', // 1 + 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', // 2 + 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', // 3 + 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', // 4 + 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', // 5 + 'w', 'x', 'y', 'z', '0', '1', '2', '3', // 6 + '4', '5', '6', '7', '8', '9', '+', '/' // 7 + }; + + private static final byte pem_convert_array[] = new byte[256]; + + static { + for (int i = 0; i < 255; i++) { + pem_convert_array[i] = -1; + } + for (int i = 0; i < pem_array.length; i++) { + pem_convert_array[pem_array[i]] = (byte) i; + } + } + + byte decode_buffer[] = new byte[4]; + + /** + * Decode one BASE64 atom into 1, 2, or 3 bytes of data. + * + * @param inStream The input stream to read the data from. + * @param outStream The output stream to write the decoded data to. + * @param rem The number of bytes to decode. + * @throws java.io.IOException If an I/O error occurs. + */ + @SuppressWarnings("fallthrough") + protected void decodeAtom(PushbackInputStream inStream, OutputStream outStream, int rem) + throws java.io.IOException { + int i; + byte a = -1, b = -1, c = -1, d = -1; + + if (rem < 2) { + throw new IOException("BASE64Decoder: Not enough bytes for an atom."); + } + do { + i = inStream.read(); + if (i == -1) { + throw new IOException(); + } + } while (i == '\n' || i == '\r'); + decode_buffer[0] = (byte) i; + + i = readFully(inStream, decode_buffer, 1, rem - 1); + if (i == -1) { + throw new IOException(); + } + + if (rem > 3 && decode_buffer[3] == '=') { + rem = 3; + } + if (rem > 2 && decode_buffer[2] == '=') { + rem = 2; + } + switch (rem) { + case 4: + d = pem_convert_array[decode_buffer[3] & 0xff]; + // NOBREAK + case 3: + c = pem_convert_array[decode_buffer[2] & 0xff]; + // NOBREAK + case 2: + b = pem_convert_array[decode_buffer[1] & 0xff]; + a = pem_convert_array[decode_buffer[0] & 0xff]; + break; + } + + switch (rem) { + case 2: + outStream.write((byte) (((a << 2) & 0xfc) | ((b >>> 4) & 3))); + break; + case 3: + outStream.write((byte) (((a << 2) & 0xfc) | ((b >>> 4) & 3))); + outStream.write((byte) (((b << 4) & 0xf0) | ((c >>> 2) & 0xf))); + break; + case 4: + outStream.write((byte) (((a << 2) & 0xfc) | ((b >>> 4) & 3))); + outStream.write((byte) (((b << 4) & 0xf0) | ((c >>> 2) & 0xf))); + outStream.write((byte) (((c << 6) & 0xc0) | (d & 0x3f))); + break; + } + return; + } +} diff --git a/core/sunbird-platform-common/src/main/java/org/sunbird/datasecurity/impl/BASE64Encoder.java b/core/sunbird-platform-common/src/main/java/org/sunbird/datasecurity/impl/BASE64Encoder.java new file mode 100644 index 000000000..73569e2b0 --- /dev/null +++ b/core/sunbird-platform-common/src/main/java/org/sunbird/datasecurity/impl/BASE64Encoder.java @@ -0,0 +1,116 @@ +/* + * Copyright (c) 1995, 2011, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package org.sunbird.datasecurity.impl; + +import java.io.IOException; +import java.io.OutputStream; + +/** + * This class implements a BASE64 Character encoder as specified in RFC1521. This RFC is part of the + * MIME specification as published by the Internet Engineering Task Force (IETF). Unlike some other + * encoding schemes there is nothing in this encoding that indicates where a buffer starts or ends. + * + *

This means that the encoded text will simply start with the first line of encoded text and end + * with the last line of encoded text. + * + * @author Chuck McManis + * @see CharacterEncoder + * @see BASE64Decoder + */ +public class BASE64Encoder extends CharacterEncoder { + /** + * this class encodes three bytes per atom. + * + * @return 3 + */ + protected int bytesPerAtom() { + return (3); + } + + /** + * this class encodes 57 bytes per line. This results in a maximum of 57/3 * 4 or 76 characters + * per output line. Not counting the line termination. + * + * @return 57 + */ + protected int bytesPerLine() { + return (57); + } + + /** This array maps the characters to their 6 bit values */ + private static final char pem_array[] = { + // 0 1 2 3 4 5 6 7 + 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', // 0 + 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', // 1 + 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', // 2 + 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', // 3 + 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', // 4 + 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', // 5 + 'w', 'x', 'y', 'z', '0', '1', '2', '3', // 6 + '4', '5', '6', '7', '8', '9', '+', '/' // 7 + }; + + /** + * encodeAtom - Take three bytes of input and encode it as 4 printable characters. Note that if + * the length in len is less than three is encodes either one or two '=' signs to indicate padding + * characters. + * + * @param outStream The output stream to write the encoded data to. + * @param data The input buffer containing the data. + * @param offset The offset in the buffer to start reading. + * @param len The number of bytes to encode. + * @throws IOException If an I/O error occurs. + */ + protected void encodeAtom(OutputStream outStream, byte data[], int offset, int len) + throws IOException { + byte a, b, c; + + if (len == 1) { + a = data[offset]; + b = 0; + c = 0; + outStream.write(pem_array[(a >>> 2) & 0x3F]); + outStream.write(pem_array[((a << 4) & 0x30) + ((b >>> 4) & 0xf)]); + outStream.write('='); + outStream.write('='); + } else if (len == 2) { + a = data[offset]; + b = data[offset + 1]; + c = 0; + outStream.write(pem_array[(a >>> 2) & 0x3F]); + outStream.write(pem_array[((a << 4) & 0x30) + ((b >>> 4) & 0xf)]); + outStream.write(pem_array[((b << 2) & 0x3c) + ((c >>> 6) & 0x3)]); + outStream.write('='); + } else { + a = data[offset]; + b = data[offset + 1]; + c = data[offset + 2]; + outStream.write(pem_array[(a >>> 2) & 0x3F]); + outStream.write(pem_array[((a << 4) & 0x30) + ((b >>> 4) & 0xf)]); + outStream.write(pem_array[((b << 2) & 0x3c) + ((c >>> 6) & 0x3)]); + outStream.write(pem_array[c & 0x3F]); + } + } +} diff --git a/core/sunbird-platform-common/src/main/java/org/sunbird/datasecurity/impl/CharacterDecoder.java b/core/sunbird-platform-common/src/main/java/org/sunbird/datasecurity/impl/CharacterDecoder.java new file mode 100644 index 000000000..0c2775ea1 --- /dev/null +++ b/core/sunbird-platform-common/src/main/java/org/sunbird/datasecurity/impl/CharacterDecoder.java @@ -0,0 +1,270 @@ +/* + * Copyright (c) 1995, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package org.sunbird.datasecurity.impl; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.PushbackInputStream; +import java.nio.ByteBuffer; + +/** + * This class defines the decoding half of character encoders. A character decoder is an algorithim + * for transforming 8 bit binary data that has been encoded into text by a character encoder, back + * into original binary form. + * + *

The character encoders, in general, have been structured around a central theme that binary + * data can be encoded into text that has the form: + * + *

+ *      [Buffer Prefix]
+ *      [Line Prefix][encoded data atoms][Line Suffix]
+ *      [Buffer Suffix]
+ * 
+ * + * Of course in the simplest encoding schemes, the buffer has no distinct prefix of suffix, however + * all have some fixed relationship between the text in an 'atom' and the binary data itself. + * + *

In the CharacterEncoder and CharacterDecoder classes, one complete chunk of data is referred + * to as a buffer. Encoded buffers are all text, and decoded buffers (sometimes just referred + * to as buffers) are binary octets. + * + *

To create a custom decoder, you must, at a minimum, overide three abstract methods in this + * class. + * + *

+ *
bytesPerAtom which tells the decoder how many bytes to expect from decodeAtom + *
decodeAtom which decodes the bytes sent to it as text. + *
bytesPerLine which tells the encoder the maximum number of bytes per line. + *
+ * + * In general, the character decoders return error in the form of a CEFormatException. The syntax of + * the detail string is + * + *
+ *      DecoderClassName: Error message.
+ * 
+ * + * Several useful decoders have already been written and are referenced in the See Also list below. + * + * @author Chuck McManis + * @see CharacterEncoder + * @see BASE64Decoder + */ +public abstract class CharacterDecoder { + public CharacterDecoder() {} + /** + * Return the number of bytes per atom of decoding + * + * @return The number of bytes per atom. + */ + protected abstract int bytesPerAtom(); + + /** + * Return the maximum number of bytes that can be encoded per line + * + * @return The maximum number of bytes per line. + */ + protected abstract int bytesPerLine(); + + /** + * decode the beginning of the buffer, by default this is a NOP. + * + * @param aStream The input stream. + * @param bStream The output stream. + * @throws IOException If an I/O error occurs. + */ + protected void decodeBufferPrefix(PushbackInputStream aStream, OutputStream bStream) + throws IOException {} + + /** + * decode the buffer suffix, again by default it is a NOP. + * + * @param aStream The input stream. + * @param bStream The output stream. + * @throws IOException If an I/O error occurs. + */ + protected void decodeBufferSuffix(PushbackInputStream aStream, OutputStream bStream) + throws IOException {} + + /** + * This method should return, if it knows, the number of bytes that will be decoded. Many formats + * such as uuencoding provide this information. By default we return the maximum bytes that could + * have been encoded on the line. + * + * @param aStream The input stream. + * @param bStream The output stream. + * @return The expected number of bytes. + * @throws IOException If an I/O error occurs. + */ + protected int decodeLinePrefix(PushbackInputStream aStream, OutputStream bStream) + throws IOException { + return (bytesPerLine()); + } + + /** + * This method post processes the line, if there are error detection or correction codes in a + * line, they are generally processed by this method. The simplest version of this method looks + * for the (newline) character. + * + * @param aStream The input stream. + * @param bStream The output stream. + * @throws IOException If an I/O error occurs. + */ + protected void decodeLineSuffix(PushbackInputStream aStream, OutputStream bStream) + throws IOException {} + + /** + * This method does an actual decode. It takes the decoded bytes and writes them to the + * OutputStream. The integer l tells the method how many bytes are required. This is always + * <= bytesPerAtom(). + * + * @param aStream The input stream. + * @param bStream The output stream. + * @param l The number of bytes to decode. + * @throws IOException If an I/O error occurs. + */ + protected void decodeAtom(PushbackInputStream aStream, OutputStream bStream, int l) + throws IOException { + throw new IOException(); + } + + /** + * This method works around the bizarre semantics of BufferedInputStream's read method. + * + * @param in The input stream. + * @param buffer The buffer to read into. + * @param offset The offset to start reading at. + * @param len The number of bytes to read. + * @return The number of bytes read. + * @throws java.io.IOException If an I/O error occurs. + */ + protected int readFully(InputStream in, byte buffer[], int offset, int len) + throws java.io.IOException { + for (int i = 0; i < len; i++) { + int q = in.read(); + if (q == -1) return ((i == 0) ? -1 : i); + buffer[i + offset] = (byte) q; + } + return len; + } + + /** + * Decode the text from the InputStream and write the decoded octets to the OutputStream. This + * method runs until the stream is exhausted. + * + * @param aStream The input stream. + * @param bStream The output stream. + * @throws IOException An error has occurred while decoding + * @throws IOException The input stream is unexpectedly out of data + */ + public void decodeBuffer(InputStream aStream, OutputStream bStream) throws IOException { + int i; + int totalBytes = 0; + + PushbackInputStream ps = new PushbackInputStream(aStream); + decodeBufferPrefix(ps, bStream); + while (true) { + int length; + + try { + length = decodeLinePrefix(ps, bStream); + for (i = 0; (i + bytesPerAtom()) < length; i += bytesPerAtom()) { + decodeAtom(ps, bStream, bytesPerAtom()); + totalBytes += bytesPerAtom(); + } + if ((i + bytesPerAtom()) == length) { + decodeAtom(ps, bStream, bytesPerAtom()); + totalBytes += bytesPerAtom(); + } else { + decodeAtom(ps, bStream, length - i); + totalBytes += (length - i); + } + decodeLineSuffix(ps, bStream); + } catch (IOException e) { + break; + } + } + decodeBufferSuffix(ps, bStream); + } + + /** + * Alternate decode interface that takes a String containing the encoded buffer and returns a byte + * array containing the data. + * + * @param inputString The string to decode. + * @return The decoded data. + * @throws IOException An error has occurred while decoding + */ + public byte decodeBuffer(String inputString)[] throws IOException { + byte inputBuffer[] = new byte[inputString.length()]; + ByteArrayInputStream inStream; + ByteArrayOutputStream outStream; + + inputString.getBytes(0, inputString.length(), inputBuffer, 0); + inStream = new ByteArrayInputStream(inputBuffer); + outStream = new ByteArrayOutputStream(); + decodeBuffer(inStream, outStream); + return (outStream.toByteArray()); + } + + /** + * Decode the contents of the inputstream into a buffer. + * + * @param in The input stream. + * @return The decoded data. + * @throws IOException If an I/O error occurs. + */ + public byte decodeBuffer(InputStream in)[] throws IOException { + ByteArrayOutputStream outStream = new ByteArrayOutputStream(); + decodeBuffer(in, outStream); + return (outStream.toByteArray()); + } + + /** + * Decode the contents of the String into a ByteBuffer. + * + * @param inputString The string to decode. + * @return The decoded data as a ByteBuffer. + * @throws IOException If an I/O error occurs. + */ + public ByteBuffer decodeBufferToByteBuffer(String inputString) throws IOException { + return ByteBuffer.wrap(decodeBuffer(inputString)); + } + + /** + * Decode the contents of the inputStream into a ByteBuffer. + * + * @param in The input stream. + * @return The decoded data as a ByteBuffer. + * @throws IOException If an I/O error occurs. + */ + public ByteBuffer decodeBufferToByteBuffer(InputStream in) throws IOException { + return ByteBuffer.wrap(decodeBuffer(in)); + } +} diff --git a/core/sunbird-platform-common/src/main/java/org/sunbird/datasecurity/impl/CharacterEncoder.java b/core/sunbird-platform-common/src/main/java/org/sunbird/datasecurity/impl/CharacterEncoder.java new file mode 100644 index 000000000..67581fc64 --- /dev/null +++ b/core/sunbird-platform-common/src/main/java/org/sunbird/datasecurity/impl/CharacterEncoder.java @@ -0,0 +1,401 @@ +/* + * Copyright (c) 1995, 2005, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package org.sunbird.datasecurity.impl; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.PrintStream; +import java.nio.ByteBuffer; + +/** + * This class defines the encoding half of character encoders. A character encoder is an algorithim + * for transforming 8 bit binary data into text (generally 7 bit ASCII or 8 bit ISO-Latin-1 text) + * for transmition over text channels such as e-mail and network news. + * + *

The character encoders have been structured around a central theme that, in general, the + * encoded text has the form: + * + *

+ *      [Buffer Prefix]
+ *      [Line Prefix][encoded data atoms][Line Suffix]
+ *      [Buffer Suffix]
+ * 
+ * + * In the CharacterEncoder and CharacterDecoder classes, one complete chunk of data is referred to + * as a buffer. Encoded buffers are all text, and decoded buffers (sometimes just referred to + * as buffers) are binary octets. + * + *

To create a custom encoder, you must, at a minimum, overide three abstract methods in this + * class. + * + *

+ *
bytesPerAtom which tells the encoder how many bytes to send to encodeAtom + *
encodeAtom which encodes the bytes sent to it as text. + *
bytesPerLine which tells the encoder the maximum number of bytes per line. + *
+ * + * Several useful encoders have already been written and are referenced in the See Also list below. + * + * @author Chuck McManis + * @see CharacterDecoder + * @see BASE64Encoder + */ +public abstract class CharacterEncoder { + /** Stream that understands "printing" */ + protected PrintStream pStream; + + /** + * Return the number of bytes per atom of encoding + * + * @return The number of bytes per atom. + */ + protected abstract int bytesPerAtom(); + + /** + * Return the number of bytes that can be encoded per line + * + * @return The maximum number of bytes per line. + */ + protected abstract int bytesPerLine(); + + /** + * Encode the prefix for the entire buffer. By default is simply opens the PrintStream for use by + * the other functions. + * + * @param aStream The output stream. + * @throws IOException If an I/O error occurs. + */ + protected void encodeBufferPrefix(OutputStream aStream) throws IOException { + pStream = new PrintStream(aStream); + } + + /** + * Encode the suffix for the entire buffer. + * + * @param aStream The output stream. + * @throws IOException If an I/O error occurs. + */ + protected void encodeBufferSuffix(OutputStream aStream) throws IOException {} + + /** + * Encode the prefix that starts every output line. + * + * @param aStream The output stream. + * @param aLength The number of bytes to be encoded. + * @throws IOException If an I/O error occurs. + */ + protected void encodeLinePrefix(OutputStream aStream, int aLength) throws IOException {} + + /** + * Encode the suffix that ends every output line. By default this method just prints a + * into the output stream. + * + * @param aStream The output stream. + * @throws IOException If an I/O error occurs. + */ + protected void encodeLineSuffix(OutputStream aStream) throws IOException { + pStream.println(); + } + + /** + * Encode one "atom" of information into characters. + * + * @param aStream The output stream. + * @param someBytes The input buffer. + * @param anOffset The offset to start reading at. + * @param aLength The number of bytes to encode. + * @throws IOException If an I/O error occurs. + */ + protected abstract void encodeAtom( + OutputStream aStream, byte someBytes[], int anOffset, int aLength) throws IOException; + + /** + * This method works around the bizarre semantics of BufferedInputStream's read method. + * + * @param in The input stream. + * @param buffer The buffer to read into. + * @return The number of bytes read. + * @throws java.io.IOException If an I/O error occurs. + */ + protected int readFully(InputStream in, byte buffer[]) throws java.io.IOException { + for (int i = 0; i < buffer.length; i++) { + int q = in.read(); + if (q == -1) return i; + buffer[i] = (byte) q; + } + return buffer.length; + } + + /** + * Encode bytes from the input stream, and write them as text characters to the output stream. + * This method will run until it exhausts the input stream, but does not print the line suffix for + * a final line that is shorter than bytesPerLine(). + * + * @param inStream The input stream. + * @param outStream The output stream. + * @throws IOException If an I/O error occurs. + */ + public void encode(InputStream inStream, OutputStream outStream) throws IOException { + int j; + int numBytes; + byte tmpbuffer[] = new byte[bytesPerLine()]; + + encodeBufferPrefix(outStream); + + while (true) { + numBytes = readFully(inStream, tmpbuffer); + if (numBytes == 0) { + break; + } + encodeLinePrefix(outStream, numBytes); + for (j = 0; j < numBytes; j += bytesPerAtom()) { + + if ((j + bytesPerAtom()) <= numBytes) { + encodeAtom(outStream, tmpbuffer, j, bytesPerAtom()); + } else { + encodeAtom(outStream, tmpbuffer, j, (numBytes) - j); + } + } + if (numBytes < bytesPerLine()) { + break; + } else { + encodeLineSuffix(outStream); + } + } + encodeBufferSuffix(outStream); + } + + /** + * Encode the buffer in aBuffer and write the encoded result to the OutputStream + * aStream. + * + * @param aBuffer The input buffer. + * @param aStream The output stream. + * @throws IOException If an I/O error occurs. + */ + public void encode(byte aBuffer[], OutputStream aStream) throws IOException { + ByteArrayInputStream inStream = new ByteArrayInputStream(aBuffer); + encode(inStream, aStream); + } + + /** + * A 'streamless' version of encode that simply takes a buffer of bytes and returns a string + * containing the encoded buffer. + * + * @param aBuffer The input buffer. + * @return The encoded string. + */ + public String encode(byte aBuffer[]) { + ByteArrayOutputStream outStream = new ByteArrayOutputStream(); + ByteArrayInputStream inStream = new ByteArrayInputStream(aBuffer); + String retVal = null; + try { + encode(inStream, outStream); + // explicit ascii->unicode conversion + retVal = outStream.toString("8859_1"); + } catch (Exception IOException) { + // This should never happen. + throw new Error("CharacterEncoder.encode internal error"); + } + return (retVal); + } + + /** + * Return a byte array from the remaining bytes in this ByteBuffer. + * + *

The ByteBuffer's position will be advanced to ByteBuffer's limit. + * + *

To avoid an extra copy, the implementation will attempt to return the byte array backing the + * ByteBuffer. If this is not possible, a new byte array will be created. + * + * @param bb The input ByteBuffer. + * @return The byte array. + */ + private byte[] getBytes(ByteBuffer bb) { + /* + * This should never return a BufferOverflowException, as we're + * careful to allocate just the right amount. + */ + byte[] buf = null; + + /* + * If it has a usable backing byte buffer, use it. Use only + * if the array exactly represents the current ByteBuffer. + */ + if (bb.hasArray()) { + byte[] tmp = bb.array(); + if ((tmp.length == bb.capacity()) && (tmp.length == bb.remaining())) { + buf = tmp; + bb.position(bb.limit()); + } + } + + if (buf == null) { + /* + * This class doesn't have a concept of encode(buf, len, off), + * so if we have a partial buffer, we must reallocate + * space. + */ + buf = new byte[bb.remaining()]; + + /* + * position() automatically updated + */ + bb.get(buf); + } + + return buf; + } + + /** + * Encode the aBuffer ByteBuffer and write the encoded result to the OutputStream + * aStream. + * + *

The ByteBuffer's position will be advanced to ByteBuffer's limit. + * + * @param aBuffer The input ByteBuffer. + * @param aStream The output stream. + * @throws IOException If an I/O error occurs. + */ + public void encode(ByteBuffer aBuffer, OutputStream aStream) throws IOException { + byte[] buf = getBytes(aBuffer); + encode(buf, aStream); + } + + /** + * A 'streamless' version of encode that simply takes a ByteBuffer and returns a string containing + * the encoded buffer. + * + *

The ByteBuffer's position will be advanced to ByteBuffer's limit. + * + * @param aBuffer The input ByteBuffer. + * @return The encoded string. + */ + public String encode(ByteBuffer aBuffer) { + byte[] buf = getBytes(aBuffer); + return encode(buf); + } + + /** + * Encode bytes from the input stream, and write them as text characters to the output stream. + * This method will run until it exhausts the input stream. It differs from encode in that it will + * add the line at the end of a final line that is shorter than bytesPerLine(). + * + * @param inStream The input stream. + * @param outStream The output stream. + * @throws IOException If an I/O error occurs. + */ + public void encodeBuffer(InputStream inStream, OutputStream outStream) throws IOException { + int j; + int numBytes; + byte tmpbuffer[] = new byte[bytesPerLine()]; + + encodeBufferPrefix(outStream); + + while (true) { + numBytes = readFully(inStream, tmpbuffer); + if (numBytes == 0) { + break; + } + encodeLinePrefix(outStream, numBytes); + for (j = 0; j < numBytes; j += bytesPerAtom()) { + if ((j + bytesPerAtom()) <= numBytes) { + encodeAtom(outStream, tmpbuffer, j, bytesPerAtom()); + } else { + encodeAtom(outStream, tmpbuffer, j, (numBytes) - j); + } + } + encodeLineSuffix(outStream); + if (numBytes < bytesPerLine()) { + break; + } + } + encodeBufferSuffix(outStream); + } + + /** + * Encode the buffer in aBuffer and write the encoded result to the OutputStream + * aStream. + * + * @param aBuffer The input buffer. + * @param aStream The output stream. + * @throws IOException If an I/O error occurs. + */ + public void encodeBuffer(byte aBuffer[], OutputStream aStream) throws IOException { + ByteArrayInputStream inStream = new ByteArrayInputStream(aBuffer); + encodeBuffer(inStream, aStream); + } + + /** + * A 'streamless' version of encode that simply takes a buffer of bytes and returns a string + * containing the encoded buffer. + * + * @param aBuffer The input buffer. + * @return The encoded string. + */ + public String encodeBuffer(byte aBuffer[]) { + ByteArrayOutputStream outStream = new ByteArrayOutputStream(); + ByteArrayInputStream inStream = new ByteArrayInputStream(aBuffer); + try { + encodeBuffer(inStream, outStream); + } catch (Exception IOException) { + // This should never happen. + throw new Error("CharacterEncoder.encodeBuffer internal error"); + } + return (outStream.toString()); + } + + /** + * Encode the aBuffer ByteBuffer and write the encoded result to the OutputStream + * aStream. + * + *

The ByteBuffer's position will be advanced to ByteBuffer's limit. + * + * @param aBuffer The input ByteBuffer. + * @param aStream The output stream. + * @throws IOException If an I/O error occurs. + */ + public void encodeBuffer(ByteBuffer aBuffer, OutputStream aStream) throws IOException { + byte[] buf = getBytes(aBuffer); + encodeBuffer(buf, aStream); + } + + /** + * A 'streamless' version of encode that simply takes a ByteBuffer and returns a string containing + * the encoded buffer. + * + *

The ByteBuffer's position will be advanced to ByteBuffer's limit. + * + * @param aBuffer The input ByteBuffer. + * @return The encoded string. + */ + public String encodeBuffer(ByteBuffer aBuffer) { + byte[] buf = getBytes(aBuffer); + return encodeBuffer(buf); + } +} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/datasecurity/impl/DefaultDataMaskServiceImpl.java b/core/sunbird-platform-common/src/main/java/org/sunbird/datasecurity/impl/DefaultDataMaskServiceImpl.java similarity index 56% rename from course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/datasecurity/impl/DefaultDataMaskServiceImpl.java rename to core/sunbird-platform-common/src/main/java/org/sunbird/datasecurity/impl/DefaultDataMaskServiceImpl.java index 03782cb97..9cf94825a 100644 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/datasecurity/impl/DefaultDataMaskServiceImpl.java +++ b/core/sunbird-platform-common/src/main/java/org/sunbird/datasecurity/impl/DefaultDataMaskServiceImpl.java @@ -1,14 +1,23 @@ -/** */ -package org.sunbird.common.models.util.datasecurity.impl; +package org.sunbird.datasecurity.impl; import org.apache.commons.lang3.StringUtils; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.models.util.ProjectUtil; -import org.sunbird.common.models.util.datasecurity.DataMaskingService; +import org.sunbird.datasecurity.DataMaskingService; +import org.sunbird.keys.JsonKey; +import org.sunbird.common.ProjectUtil; -/** @author Manzarul */ +/** + * Default implementation of the {@link DataMaskingService} interface. + * Provides functionality to mask phone numbers and email addresses. + */ public class DefaultDataMaskServiceImpl implements DataMaskingService { + /** + * Masks a phone number by keeping the last 4 digits visible. + * Masking character is defined in JsonKey.REPLACE_WITH_ASTERISK. + * + * @param phone The phone number to mask. + * @return The masked phone number, or the original if it is blank or shorter than 10 characters. + */ @Override public String maskPhone(String phone) { if (StringUtils.isBlank(phone) || phone.length() < 10) { @@ -28,6 +37,14 @@ public String maskPhone(String phone) { return builder.toString(); } + /** + * Masks an email address. + * Keeps the first 2 characters and the domain part (after the last @) visible. + * Masks characters in between. + * + * @param email The email address to mask. + * @return The masked email address, or the original if it is blank or invalid. + */ @Override public String maskEmail(String email) { if ((StringUtils.isBlank(email)) || (!ProjectUtil.isEmailvalid(email))) { @@ -46,3 +63,5 @@ public String maskEmail(String email) { return builder.toString(); } } + + diff --git a/core/sunbird-platform-common/src/main/java/org/sunbird/datasecurity/impl/DefaultDecryptionServiceImpl.java b/core/sunbird-platform-common/src/main/java/org/sunbird/datasecurity/impl/DefaultDecryptionServiceImpl.java new file mode 100644 index 000000000..ae2e2d2f2 --- /dev/null +++ b/core/sunbird-platform-common/src/main/java/org/sunbird/datasecurity/impl/DefaultDecryptionServiceImpl.java @@ -0,0 +1,217 @@ +package org.sunbird.datasecurity.impl; + +import java.nio.charset.StandardCharsets; +import java.security.Key; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import javax.crypto.Cipher; +import javax.crypto.spec.SecretKeySpec; +import org.apache.commons.lang3.StringUtils; +import org.sunbird.datasecurity.DecryptionService; +import org.sunbird.exception.ProjectCommonException; +import org.sunbird.response.ResponseCode; +import org.sunbird.keys.JsonKey; +import org.sunbird.logging.LoggerUtil; +import org.sunbird.request.RequestContext; +import org.sunbird.common.ProjectUtil; + +/** + * Default implementation of the {@link DecryptionService} interface. + * Uses AES encryption algorithm to decrypt data. + */ +public class DefaultDecryptionServiceImpl implements DecryptionService { + private static final LoggerUtil logger = new LoggerUtil(DefaultDecryptionServiceImpl.class); + + private static String sunbird_encryption = ""; + + private String sunbirdEncryption = ""; + + private static Cipher c; + + static { + try { + sunbird_encryption = DefaultEncryptionServiceImpl.getSalt(); + Key key = generateKey(); + c = Cipher.getInstance(ALGORITHM); + c.init(Cipher.DECRYPT_MODE, key); + } catch (Exception e) { + logger.error(e.getMessage(), e); + } + } + + public DefaultDecryptionServiceImpl() { + sunbirdEncryption = System.getenv(JsonKey.SUNBIRD_ENCRYPTION); + if (StringUtils.isBlank(sunbirdEncryption)) { + sunbirdEncryption = ProjectUtil.getConfigValue(JsonKey.SUNBIRD_ENCRYPTION); + } + } + + /** + * Decrypts values in a map if encryption is enabled. + * Modifies the map in-place. + * + * @param data The map containing data to decrypt. + * @param context The request context. + * @return The data map with decrypted values. + */ + @Override + public Map decryptData(Map data, RequestContext context) { + if (JsonKey.ON.equalsIgnoreCase(sunbirdEncryption)) { + if (data == null) { + return data; + } + Iterator> itr = data.entrySet().iterator(); + while (itr.hasNext()) { + Entry entry = itr.next(); + if (!(entry.getValue() instanceof Map || entry.getValue() instanceof List) + && null != entry.getValue()) { + data.put(entry.getKey(), decrypt(entry.getValue() + "", false, context)); + } + } + } + return data; + } + + /** + * Decrypts values in a list of maps. + * + * @param data The list of maps to decrypt. + * @param context The request context. + * @return The list of maps with decrypted values. + */ + @Override + public List> decryptData( + List> data, RequestContext context) { + if (JsonKey.ON.equalsIgnoreCase(sunbirdEncryption)) { + if (data == null || data.isEmpty()) { + return data; + } + + for (Map map : data) { + decryptData(map, context); + } + } + return data; + } + + /** + * Decrypts a single string value. + * + * @param data The string to decrypt. + * @param context The request context. + * @return The decrypted string, or the original string if encryption is disabled. + */ + @Override + public String decryptData(String data, RequestContext context) { + return decryptData(data, false, context); + } + + /** + * Decrypts a single string value, optionally throwing an exception on failure. + * + * @param data The string to decrypt. + * @param throwExceptionOnFailure Whether to throw an exception if decryption fails. + * @param context The request context. + * @return The decrypted string. + */ + @Override + public String decryptData(String data, boolean throwExceptionOnFailure, RequestContext context) { + if (JsonKey.ON.equalsIgnoreCase(sunbirdEncryption)) { + if (StringUtils.isBlank(data)) { + return data; + } else { + return decrypt(data, throwExceptionOnFailure, context); + } + } else { + return data; + } + } + + /** + * Internal method to perform the decryption logic. + * + * @param value The value to decrypt. + * @param throwExceptionOnFailure Whether to throw an exception on error. + * @param context The request context. + * @return The decrypted value. + */ + public static String decrypt( + String value, boolean throwExceptionOnFailure, RequestContext context) { + try { + String dValue = null; + String valueToDecrypt = value.trim(); + for (int i = 0; i < ITERATIONS; i++) { + byte[] decordedValue = new BASE64Decoder().decodeBuffer(valueToDecrypt); + byte[] decValue = c.doFinal(decordedValue); + dValue = + new String(decValue, StandardCharsets.UTF_8).substring(sunbird_encryption.length()); + valueToDecrypt = dValue; + } + return dValue; + } catch (Exception ex) { + // This could happen with masked email and phone number. Not others. + logger.error(context, "DefaultDecryptionServiceImpl:decrypt: ignorable errorMsg = ", ex); + if (throwExceptionOnFailure) { + logger.info( + context, "Throwing exception error upon explicit ask by callers for value " + value); + ProjectCommonException.throwServerErrorException(ResponseCode.SERVER_ERROR); + } + } + return value; + } + + private static Key generateKey() { + return new SecretKeySpec(keyValue, ALGORITHM); + } + + /** + * Decrypts values in a map without a request context. + * Delegates to {@link #decryptData(Map, RequestContext)} with null context. + * + * @param data The map containing data to decrypt. + * @return The data map with decrypted values. + */ + @Override + public Map decryptData(Map data) { + return decryptData(data, null); + } + + /** + * Decrypts values in a list of maps without a request context. + * Delegates to {@link #decryptData(List, RequestContext)} with null context. + * + * @param data The list of maps to decrypt. + * @return The list of maps with decrypted values. + */ + @Override + public List> decryptData(List> data) { + return decryptData(data, null); + } + + /** + * Decrypts a single string value without a request context. + * Delegates to {@link #decryptData(String, RequestContext)} with null context. + * + * @param data The string to decrypt. + * @return The decrypted string. + */ + @Override + public String decryptData(String data) { + return decryptData(data, null); + } + + /** + * Decrypts a single string value without a request context, optionally throwing an exception on failure. + * Delegates to {@link #decryptData(String, boolean, RequestContext)} with null context. + * + * @param data The string to decrypt. + * @param throwExceptionOnFailure Whether to throw an exception if decryption fails. + * @return The decrypted string. + */ + @Override + public String decryptData(String data, boolean throwExceptionOnFailure) { + return decryptData(data, throwExceptionOnFailure, null); + } +} diff --git a/core/sunbird-platform-common/src/main/java/org/sunbird/datasecurity/impl/DefaultEncryptionServiceImpl.java b/core/sunbird-platform-common/src/main/java/org/sunbird/datasecurity/impl/DefaultEncryptionServiceImpl.java new file mode 100644 index 000000000..568272eb5 --- /dev/null +++ b/core/sunbird-platform-common/src/main/java/org/sunbird/datasecurity/impl/DefaultEncryptionServiceImpl.java @@ -0,0 +1,215 @@ +package org.sunbird.datasecurity.impl; + +import java.nio.charset.StandardCharsets; +import java.security.Key; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import javax.crypto.Cipher; +import javax.crypto.spec.SecretKeySpec; +import org.apache.commons.lang3.StringUtils; +import org.sunbird.datasecurity.EncryptionService; +import org.sunbird.exception.ProjectCommonException; +import org.sunbird.response.ResponseCode; +import org.sunbird.keys.JsonKey; +import org.sunbird.logging.LoggerUtil; +import org.sunbird.request.RequestContext; +import org.sunbird.common.ProjectUtil; + +/** + * Default implementation of the {@link EncryptionService} interface. + * Uses AES encryption algorithm to encrypt data. + */ +public class DefaultEncryptionServiceImpl implements EncryptionService { + private static final LoggerUtil logger = new LoggerUtil(DefaultEncryptionServiceImpl.class); + + private static String encryption_key = ""; + + private String sunbirdEncryption = ""; + + private static Cipher c; + + static { + try { + encryption_key = getSalt(); + Key key = generateKey(); + c = Cipher.getInstance(ALGORITHM); + c.init(Cipher.ENCRYPT_MODE, key); + } catch (Exception e) { + logger.error(e.getMessage(), e); + } + } + + public DefaultEncryptionServiceImpl() { + sunbirdEncryption = System.getenv(JsonKey.SUNBIRD_ENCRYPTION); + if (StringUtils.isBlank(sunbirdEncryption)) { + sunbirdEncryption = ProjectUtil.getConfigValue(JsonKey.SUNBIRD_ENCRYPTION); + } + } + + /** + * Encrypts the values in a map. + * + * @param data The map containing data to encrypt. + * @param context The request context. + * @return The map with encrypted values. + */ + @Override + public Map encryptData(Map data, RequestContext context) { + if (JsonKey.ON.equalsIgnoreCase(sunbirdEncryption)) { + if (data == null) { + return data; + } + Iterator> itr = data.entrySet().iterator(); + while (itr.hasNext()) { + Entry entry = itr.next(); + if (!(entry.getValue() instanceof Map || entry.getValue() instanceof List) + && null != entry.getValue()) { + data.put(entry.getKey(), encrypt(entry.getValue() + "", context)); + } + } + } + return data; + } + + /** + * Encrypts the values in a list of maps. + * + * @param data The list of maps to encrypt. + * @param context The request context. + * @return The list of maps with encrypted values. + */ + @Override + public List> encryptData( + List> data, RequestContext context) { + if (JsonKey.ON.equalsIgnoreCase(sunbirdEncryption)) { + if (data == null || data.isEmpty()) { + return data; + } + for (Map map : data) { + encryptData(map, context); + } + } + return data; + } + + /** + * Encrypts a single string value. + * + * @param data The string to encrypt. + * @param context The request context. + * @return The encrypted string. + */ + @Override + public String encryptData(String data, RequestContext context) { + if (JsonKey.ON.equalsIgnoreCase(sunbirdEncryption)) { + if (StringUtils.isNotBlank(data)) { + return encrypt(data, context); + } else { + return data; + } + } else { + return data; + } + } + + /** + * Encrypts the given value using the configured algorithm/key. + * + * @param value String password or data to encrypt. + * @param context The request context. + * @return encrypted string. + */ + @SuppressWarnings("restriction") + public static String encrypt(String value, RequestContext context) { + String valueToEnc = null; + String eValue = value; + for (int i = 0; i < ITERATIONS; i++) { + valueToEnc = encryption_key + eValue; + byte[] encValue = new byte[0]; + try { + encValue = c.doFinal(valueToEnc.getBytes(StandardCharsets.UTF_8)); + } catch (Exception e) { + logger.error( + context, "Exception while encrypting user data, with message : " + e.getMessage(), e); + throw new ProjectCommonException( + ResponseCode.serverError, + ResponseCode.serverError.getErrorMessage(), + ResponseCode.SERVER_ERROR.getResponseCode()); + } + eValue = new BASE64Encoder().encode(encValue); + } + return eValue; + } + + private static Key generateKey() { + return new SecretKeySpec(keyValue, ALGORITHM); + } + + /** + * Retrieves the encryption salt (key) from environment or config. + * @return The encryption key. + */ + public static String getSalt() { + if (!StringUtils.isBlank(encryption_key)) { + return encryption_key; + } else { + encryption_key = System.getenv(JsonKey.ENCRYPTION_KEY); + if (StringUtils.isBlank(encryption_key)) { + logger.info("Salt value is not provided by Env"); + encryption_key = ProjectUtil.getConfigValue(JsonKey.ENCRYPTION_KEY); + } + } + if (StringUtils.isBlank(encryption_key)) { + logger.info("throwing exception for invalid salt"); + throw new ProjectCommonException( + ResponseCode.invalidParameterValue, + String.format( + ResponseCode.invalidParameterValue.getErrorMessage(), JsonKey.ENCRYPTION_KEY), + ResponseCode.SERVER_ERROR.getResponseCode()); + } + return encryption_key; + } + + /** + * Encrypts the values in a map without a request context. + * Delegates to {@link #encryptData(Map, RequestContext)} with null context. + * + * @param data The map containing data to encrypt. + * @return The map with encrypted values. + * @throws Exception If an error occurs during encryption. + */ + @Override + public Map encryptData(Map data) throws Exception { + return encryptData(data, null); + } + + /** + * Encrypts the values in a list of maps without a request context. + * Delegates to {@link #encryptData(List, RequestContext)} with null context. + * + * @param data The list of maps to encrypt. + * @return The list of maps with encrypted values. + * @throws Exception If an error occurs during encryption. + */ + @Override + public List> encryptData(List> data) throws Exception { + return encryptData(data, null); + } + + /** + * Encrypts a single string value without a request context. + * Delegates to {@link #encryptData(String, RequestContext)} with null context. + * + * @param data The string to encrypt. + * @return The encrypted string. + * @throws Exception If an error occurs during encryption. + */ + @Override + public String encryptData(String data) throws Exception { + return encryptData(data, null); + } +} + + diff --git a/core/sunbird-platform-common/src/main/java/org/sunbird/datasecurity/impl/LogMaskServiceImpl.java b/core/sunbird-platform-common/src/main/java/org/sunbird/datasecurity/impl/LogMaskServiceImpl.java new file mode 100644 index 000000000..db888a2d5 --- /dev/null +++ b/core/sunbird-platform-common/src/main/java/org/sunbird/datasecurity/impl/LogMaskServiceImpl.java @@ -0,0 +1,40 @@ +package org.sunbird.datasecurity.impl; + +import org.sunbird.datasecurity.DataMaskingService; + +/** + * Implementation of DataMaskingService for logging purposes. + * Provides masking logic suitable for log outputs. + */ +public class LogMaskServiceImpl implements DataMaskingService { + + /** + * Masks an email address for logging. + * If the local part (before @) is longer than 4 characters, keeps the first 4 visible. + * Otherwise, keeps the first 2 visible. + * The domain part is kept visible. + * + * @param email The email address to mask. + * @return The masked email address. + */ + @Override + public String maskEmail(String email) { + if (email.indexOf("@") > 4) { + return email.replaceAll("(^[^@]{4}|(?!^)\\G)[^@]", "$1*"); + } else { + return email.replaceAll("(^[^@]{2}|(?!^)\\G)[^@]", "$1*"); + } + } + + /** + * Masks a phone number for logging. + * Masks all but the last digit (assuming 10-digit standard for the regex logic). + * + * @param phone The phone number to mask. + * @return The masked phone number. + */ + @Override + public String maskPhone(String phone) { + return phone.replaceAll("(^[^*]{9}|(?!^)\\G)[^*]", "$1*"); + } +} diff --git a/core/sunbird-platform-common/src/main/java/org/sunbird/datasecurity/impl/ServiceFactory.java b/core/sunbird-platform-common/src/main/java/org/sunbird/datasecurity/impl/ServiceFactory.java new file mode 100644 index 000000000..e9d9939b1 --- /dev/null +++ b/core/sunbird-platform-common/src/main/java/org/sunbird/datasecurity/impl/ServiceFactory.java @@ -0,0 +1,114 @@ +package org.sunbird.datasecurity.impl; + +import org.apache.commons.lang3.StringUtils; +import org.sunbird.datasecurity.DataMaskingService; +import org.sunbird.datasecurity.DecryptionService; +import org.sunbird.datasecurity.EncryptionService; + +/** + * Factory class to provide instances of data security services. + * Supports EncryptionService, DecryptionService, and DataMaskingService. + * Provides both parameterized (for backward compatibility) and non-parameterized factory methods. + */ +public class ServiceFactory { + + private static EncryptionService encryptionService; + private static DecryptionService decryptionService; + private static DataMaskingService maskingService; + + static { + encryptionService = new DefaultEncryptionServiceImpl(); + decryptionService = new DefaultDecryptionServiceImpl(); + maskingService = new DefaultDataMaskServiceImpl(); + } + + /** + * Provides the default instance of EncryptionService. + * + * @return The default EncryptionService instance. + */ + public static EncryptionService getEncryptionServiceInstance() { + return encryptionService; + } + + /** + * Provides an instance of EncryptionService. + * Currently, returns the default instance regardless of the input value, + * but supports the parameter for backward compatibility. + * + * @param val The type of service implementation required (e.g., "defaultEncryption"). + * Pass null or empty for the default implementation. + * @return An instance of EncryptionService. + */ + public static EncryptionService getEncryptionServiceInstance(String val) { + if (StringUtils.isBlank(val)) { + return encryptionService; + } + switch (val) { + case "defaultEncryption": + return encryptionService; + default: + return encryptionService; + } + } + + /** + * Provides the default instance of DecryptionService. + * + * @return The default DecryptionService instance. + */ + public static DecryptionService getDecryptionServiceInstance() { + return decryptionService; + } + + /** + * Provides an instance of DecryptionService. + * Currently, returns the default instance regardless of the input value, + * but supports the parameter for backward compatibility. + * + * @param val The type of service implementation required (e.g., "defaultDecryption"). + * Pass null or empty for the default implementation. + * @return An instance of DecryptionService. + */ + public static DecryptionService getDecryptionServiceInstance(String val) { + if (StringUtils.isBlank(val)) { + return decryptionService; + } + switch (val) { + case "defaultDecryption": + return decryptionService; + default: + return decryptionService; + } + } + + /** + * Provides the default instance of DataMaskingService. + * + * @return The default DataMaskingService instance. + */ + public static DataMaskingService getMaskingServiceInstance() { + return maskingService; + } + + /** + * Provides an instance of DataMaskingService. + * Currently, returns the default instance regardless of the input value, + * but supports the parameter for backward compatibility. + * + * @param val The type of service implementation required (e.g., "defaultMasking"). + * Pass null or empty for the default implementation. + * @return An instance of DataMaskingService. + */ + public static DataMaskingService getMaskingServiceInstance(String val) { + if (StringUtils.isBlank(val)) { + return maskingService; + } + switch (val) { + case "defaultMasking": + return maskingService; + default: + return maskingService; + } + } +} diff --git a/core/sunbird-platform-common/src/main/java/org/sunbird/exception/ProjectCommonException.java b/core/sunbird-platform-common/src/main/java/org/sunbird/exception/ProjectCommonException.java new file mode 100644 index 000000000..ecfbf7e57 --- /dev/null +++ b/core/sunbird-platform-common/src/main/java/org/sunbird/exception/ProjectCommonException.java @@ -0,0 +1,283 @@ +package org.sunbird.exception; + +import java.text.MessageFormat; +import org.apache.commons.lang3.StringUtils; +import org.sunbird.response.ResponseCode; +import org.sunbird.keys.JsonKey; + +/** + * A comprehensive exception class used across the backend to handle error scenarios. + * This class encapsulates error codes, messages, and HTTP status codes, supporting both + * unified error handling and backward compatibility for various service modules. + */ +public class ProjectCommonException extends RuntimeException { + + private static final long serialVersionUID = 1L; + + /** The application-specific error code (e.g., "ERR_USER_NOT_FOUND"). */ + private String errorCode; + + /** The human-readable error message. */ + private String errorMessage; + + /** The HTTP status code associated with this error (e.g., 400, 404, 500). */ + private int errorResponseCode; + + /** The rich enum representation of the error, if available. */ + private ResponseCode responseCode; + + /** + * Constructs a new ProjectCommonException using a ResponseCode enum. + * + * @param code The ResponseCode enum representing the error type. + * @param message A custom error message description. + * @param responseCode The HTTP status code to return to the client. + */ + public ProjectCommonException(ResponseCode code, String message, int responseCode) { + super(message); + this.responseCode = code; + this.errorCode = code.getErrorCode(); + this.errorMessage = message; + this.errorResponseCode = responseCode; + } + + /** + * Constructs a new ProjectCommonException with a string error code. + * This constructor is primarily used for scenarios where a ResponseCode enum is not strictly required. + * + * @param errorCode The string representation of the error code. + * @param message The error message description. + * @param responseCode The HTTP status code to return to the client. + */ + public ProjectCommonException(String errorCode, String message, int responseCode) { + super(message); + this.errorCode = errorCode; + this.errorMessage = message; + this.errorResponseCode = responseCode; + this.responseCode = null; + } + + /** + * Constructs a new ProjectCommonException wrapping another exception, typically for actor operations. + * Adds service-specific prefixes to the error code. + * + * @param pce The original ProjectCommonException to wrap. + * @param actorOperation The actor operation context to append to the error code prefix. + */ + public ProjectCommonException(ProjectCommonException pce, String actorOperation) { + super(pce.getMessage()); + this.setStackTrace(pce.getStackTrace()); + this.errorCode = + new StringBuilder(JsonKey.USER_ORG_SERVICE_PREFIX) + .append(actorOperation) + .append(pce.getErrorCode()) + .toString(); + this.errorResponseCode = pce.getErrorResponseCode(); + this.errorMessage = pce.getMessage(); + this.responseCode = pce.getResponseCodeEnum(); + } + + /** + * Constructs a new ProjectCommonException with message formatting support. + * Replaces placeholders in the message with provided values. + * + * @param code The ResponseCode enum. + * @param messageWithPlaceholder The error message pattern containing placeholders. + * @param responseCode The HTTP status code. + * @param placeholderValue The values to substitute into the message placeholders. + */ + public ProjectCommonException( + ResponseCode code, + String messageWithPlaceholder, + int responseCode, + String... placeholderValue) { + super(MessageFormat.format(messageWithPlaceholder, placeholderValue)); + this.errorCode = code.getErrorCode(); + this.errorMessage = MessageFormat.format(messageWithPlaceholder, placeholderValue); + this.errorResponseCode = responseCode; + this.responseCode = code; + } + + // --- Getters and Setters --- + + public String getErrorCode() { + return errorCode; + } + + public void setErrorCode(String code) { + this.errorCode = code; + } + + @Override + public String getMessage() { + return errorMessage; + } + + public void setMessage(String message) { + this.errorMessage = message; + } + + /** + * Gets the HTTP response status code. + * + * @return The HTTP status code as an integer. + */ + public int getErrorResponseCode() { + return errorResponseCode; + } + + public void setErrorResponseCode(int responseCode) { + this.errorResponseCode = responseCode; + } + + /** + * Gets the ResponseCode enum. + * + * @return The ResponseCode enum, or null if initialized with the raw string constructor. + */ + public ResponseCode getResponseCodeEnum() { + return responseCode; + } + + public void setResponseCodeEnum(ResponseCode responseCode) { + this.responseCode = responseCode; + } + + public String getErrorMessage() { + return errorMessage; + } + + public void setErrorMessage(String errorMessage) { + this.errorMessage = errorMessage; + } + + // --- Backward Compatibility Aliases --- + + /** + * Gets the error code. Kept for backward compatibility. + * + * @return The error code string. + * @see #getErrorCode() + */ + public String getCode() { + return getErrorCode(); + } + + /** + * Sets the error code. Kept for backward compatibility. + * + * @param code The error code string. + * @see #setErrorCode(String) + */ + public void setCode(String code) { + setErrorCode(code); + } + + /** + * Gets the HTTP response code. Kept for backward compatibility. + * + * @return The integer HTTP response code. + * @see #getErrorResponseCode() + */ + public int getResponseCode() { + return errorResponseCode; + } + + /** + * Sets the HTTP response code. Kept for backward compatibility. + * + * @param responseCode The integer HTTP response code. + * @see #setErrorResponseCode(int) + */ + public void setResponseCode(int responseCode) { + this.errorResponseCode = responseCode; + } + + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append(errorCode).append(": "); + builder.append(errorMessage); + return builder.toString(); + } + + // --- Static Helper Methods --- + + /** + * Throws a generic client error exception (4xx). + * + * @param responseCode The ResponseCode enum details. + * @param exceptionMessage A custom message to include. + */ + public static void throwClientErrorException(ResponseCode responseCode, String exceptionMessage) { + throw new ProjectCommonException( + responseCode, + StringUtils.isBlank(exceptionMessage) ? responseCode.getErrorMessage() : exceptionMessage, + ResponseCode.CLIENT_ERROR.getResponseCode()); + } + + /** + * Throws a generic Resource Not Found exception (404). + */ + public static void throwResourceNotFoundException() { + throw new ProjectCommonException( + ResponseCode.resourceNotFound, + MessageFormat.format(ResponseCode.resourceNotFound.getErrorMessage(), ""), + ResponseCode.RESOURCE_NOT_FOUND.getResponseCode()); + } + + /** + * Throws a Resource Not Found exception (404) with a custom message. + * + * @param responseCode The ResponseCode enum details. + * @param exceptionMessage A custom message to include. + */ + public static void throwResourceNotFoundException( + ResponseCode responseCode, String exceptionMessage) { + throw new ProjectCommonException( + responseCode, + StringUtils.isBlank(exceptionMessage) ? responseCode.getErrorMessage() : exceptionMessage, + ResponseCode.RESOURCE_NOT_FOUND.getResponseCode()); + } + + /** + * Throws a generic Server Error exception (5xx). + * + * @param responseCode The ResponseCode enum details. + * @param exceptionMessage A custom message to include. + */ + public static void throwServerErrorException(ResponseCode responseCode, String exceptionMessage) { + throw new ProjectCommonException( + responseCode, + StringUtils.isBlank(exceptionMessage) ? responseCode.getErrorMessage() : exceptionMessage, + ResponseCode.SERVER_ERROR.getResponseCode()); + } + + /** + * Throws a generic Server Error exception (5xx) using the default enum message. + * + * @param responseCode The ResponseCode enum details. + */ + public static void throwServerErrorException(ResponseCode responseCode) { + throwServerErrorException(responseCode, responseCode.getErrorMessage()); + } + + /** + * Throws a generic Client Error exception (4xx) using the default enum message. + * + * @param responseCode The ResponseCode enum details. + */ + public static void throwClientErrorException(ResponseCode responseCode) { + throwClientErrorException(responseCode, responseCode.getErrorMessage()); + } + + /** + * Throws the standard Unauthorized exception (401). + */ + public static void throwUnauthorizedErrorException() { + throw new ProjectCommonException( + ResponseCode.unAuthorized, + ResponseCode.unAuthorized.getErrorMessage(), + ResponseCode.UNAUTHORIZED.getResponseCode()); + } +} \ No newline at end of file diff --git a/core/sunbird-platform-common/src/main/java/org/sunbird/http/HttpClientUtil.java b/core/sunbird-platform-common/src/main/java/org/sunbird/http/HttpClientUtil.java new file mode 100644 index 000000000..d0823e6fb --- /dev/null +++ b/core/sunbird-platform-common/src/main/java/org/sunbird/http/HttpClientUtil.java @@ -0,0 +1,380 @@ +package org.sunbird.http; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.TimeUnit; +import org.apache.commons.collections.MapUtils; +import org.apache.http.Consts; +import org.apache.http.HeaderElement; +import org.apache.http.HeaderElementIterator; +import org.apache.http.HttpEntity; +import org.apache.http.NameValuePair; +import org.apache.http.StatusLine; +import org.apache.http.client.entity.UrlEncodedFormEntity; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpDelete; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPatch; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.conn.ConnectionKeepAliveStrategy; +import org.apache.http.entity.ContentType; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; +import org.apache.http.message.BasicHeaderElementIterator; +import org.apache.http.message.BasicNameValuePair; +import org.apache.http.protocol.HTTP; +import org.apache.http.util.EntityUtils; +import org.sunbird.logging.LoggerUtil; +import org.sunbird.request.RequestContext; + +/** + * HTTP client utility for making REST API calls. + * + *

This class provides a thread-safe singleton HTTP client with connection pooling + * and keep-alive strategy. It supports GET, POST, PATCH, and DELETE operations + * with custom headers and supports both JSON and form-encoded payloads. + * + *

Features: + *

    + *
  • Connection pooling with configurable max connections (200 total, 150 per route)
  • + *
  • Keep-alive strategy with 180-second timeout
  • + *
  • Automatic idle connection cleanup
  • + *
  • Comprehensive logging with request context
  • + *
+ * + * @author Sunbird + * @version 1.0 + */ +public class HttpClientUtil { + + private static final LoggerUtil logger = new LoggerUtil(HttpClientUtil.class); + private static final int MAX_TOTAL_CONNECTIONS = 200; + private static final int MAX_CONNECTIONS_PER_ROUTE = 150; + private static final int KEEP_ALIVE_TIMEOUT_SECONDS = 180; + private static final int SUCCESS_STATUS_MIN = 200; + private static final int SUCCESS_STATUS_MAX = 300; + + private static CloseableHttpClient httpclient = null; + private static HttpClientUtil httpClientUtil; + + /** + * Private constructor to initialize the HTTP client with connection pooling. + * Configures keep-alive strategy and connection manager settings. + */ + private HttpClientUtil() { + ConnectionKeepAliveStrategy keepAliveStrategy = + (response, context) -> { + HeaderElementIterator it = + new BasicHeaderElementIterator(response.headerIterator(HTTP.CONN_KEEP_ALIVE)); + while (it.hasNext()) { + HeaderElement he = it.nextElement(); + String param = he.getName(); + String value = he.getValue(); + if (value != null && param.equalsIgnoreCase("timeout")) { + return Long.parseLong(value) * 1000; + } + } + return KEEP_ALIVE_TIMEOUT_SECONDS * 1000; + }; + + PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(); + connectionManager.setMaxTotal(MAX_TOTAL_CONNECTIONS); + connectionManager.setDefaultMaxPerRoute(MAX_CONNECTIONS_PER_ROUTE); + connectionManager.closeIdleConnections(KEEP_ALIVE_TIMEOUT_SECONDS, TimeUnit.SECONDS); + + httpclient = + HttpClients.custom() + .setConnectionManager(connectionManager) + .useSystemProperties() + .setKeepAliveStrategy(keepAliveStrategy) + .build(); + + logger.info(null, "HttpClientUtil initialized with max connections: " + MAX_TOTAL_CONNECTIONS); + } + + /** + * Gets the singleton instance of HttpClientUtil. + * Thread-safe double-checked locking pattern. + * + * @return The singleton HttpClientUtil instance + */ + public static HttpClientUtil getInstance() { + if (httpClientUtil == null) { + synchronized (HttpClientUtil.class) { + if (httpClientUtil == null) { + httpClientUtil = new HttpClientUtil(); + } + } + } + return httpClientUtil; + } + + /** + * Performs an HTTP GET request. + * + * @param requestURL The target URL for the GET request + * @param headers Optional HTTP headers to include in the request + * @param context Request context for logging and tracking + * @return Response body as a string, or empty string if request fails + */ + public static String get(String requestURL, Map headers, RequestContext context) { + CloseableHttpResponse response = null; + try { + logger.debug(context, "HttpClientUtil:get: Making GET request to URL: " + requestURL); + HttpGet httpGet = new HttpGet(requestURL); + + if (MapUtils.isNotEmpty(headers)) { + for (Map.Entry entry : headers.entrySet()) { + httpGet.addHeader(entry.getKey(), entry.getValue()); + } + } + + response = httpclient.execute(httpGet); + return getResponse(response, context, "GET"); + } catch (Exception ex) { + logger.error(context, "HttpClientUtil:get: Exception occurred while calling GET method for URL: " + requestURL, ex); + return ""; + } finally { + closeResponse(response, context, "GET"); + } + } + + /** + * Performs an HTTP POST request with JSON payload. + * + * @param requestURL The target URL for the POST request + * @param params The request body as a JSON string + * @param headers Optional HTTP headers to include in the request + * @param context Request context for logging and tracking + * @return Response body as a string, or empty string if request fails + */ + public static String post( + String requestURL, String params, Map headers, RequestContext context) { + CloseableHttpResponse response = null; + try { + logger.debug(context, "HttpClientUtil:post: Making POST request to URL: " + requestURL); + HttpPost httpPost = new HttpPost(requestURL); + + if (MapUtils.isNotEmpty(headers)) { + for (Map.Entry entry : headers.entrySet()) { + httpPost.addHeader(entry.getKey(), entry.getValue()); + } + } + + StringEntity entity = new StringEntity(params, ContentType.APPLICATION_JSON); + httpPost.setEntity(entity); + + response = httpclient.execute(httpPost); + return getResponse(response, context, "POST"); + } catch (Exception ex) { + logger.error(context, "HttpClientUtil:post: Exception occurred while calling POST method for URL: " + requestURL, ex); + return ""; + } finally { + closeResponse(response, context, "POST"); + } + } + + /** + * Performs an HTTP POST request with form-encoded payload. + * + * @param requestURL The target URL for the POST request + * @param params Form parameters as key-value pairs + * @param headers Optional HTTP headers to include in the request + * @param context Request context for logging and tracking + * @return Response body as a string, or empty string if request fails + */ + public static String postFormData( + String requestURL, + Map params, + Map headers, + RequestContext context) { + CloseableHttpResponse response = null; + try { + logger.debug(context, "HttpClientUtil:postFormData: Making POST form data request to URL: " + requestURL); + HttpPost httpPost = new HttpPost(requestURL); + + if (MapUtils.isNotEmpty(headers)) { + for (Map.Entry entry : headers.entrySet()) { + httpPost.addHeader(entry.getKey(), entry.getValue()); + } + } + + List form = new ArrayList<>(); + for (Map.Entry entry : params.entrySet()) { + form.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); + } + UrlEncodedFormEntity entity = new UrlEncodedFormEntity(form, Consts.UTF_8); + httpPost.setEntity(entity); + + response = httpclient.execute(httpPost); + return getResponse(response, context, "POST_FORM"); + } catch (Exception ex) { + logger.error(context, "HttpClientUtil:postFormData: Exception occurred while calling POST form data method for URL: " + requestURL, ex); + return ""; + } finally { + closeResponse(response, context, "POST_FORM"); + } + } + + /** + * Performs an HTTP PATCH request with JSON payload. + * + * @param requestURL The target URL for the PATCH request + * @param params The request body as a JSON string + * @param headers Optional HTTP headers to include in the request + * @param context Request context for logging and tracking + * @return Response body as a string, or empty string if request fails + */ + public static String patch( + String requestURL, String params, Map headers, RequestContext context) { + CloseableHttpResponse response = null; + try { + logger.debug(context, "HttpClientUtil:patch: Making PATCH request to URL: " + requestURL); + HttpPatch httpPatch = new HttpPatch(requestURL); + + if (MapUtils.isNotEmpty(headers)) { + for (Map.Entry entry : headers.entrySet()) { + httpPatch.addHeader(entry.getKey(), entry.getValue()); + } + } + + StringEntity entity = new StringEntity(params, ContentType.APPLICATION_JSON); + httpPatch.setEntity(entity); + + response = httpclient.execute(httpPatch); + return getResponse(response, context, "PATCH"); + } catch (Exception ex) { + logger.error(context, "HttpClientUtil:patch: Exception occurred while calling PATCH method for URL: " + requestURL, ex); + return ""; + } finally { + closeResponse(response, context, "PATCH"); + } + } + + /** + * Performs an HTTP DELETE request. + * + * @param requestURL The target URL for the DELETE request + * @param headers Optional HTTP headers to include in the request + * @param context Request context for logging and tracking + * @return Response body as a string, or empty string if request fails + */ + public static String delete( + String requestURL, Map headers, RequestContext context) { + CloseableHttpResponse response = null; + try { + logger.debug(context, "HttpClientUtil:delete: Making DELETE request to URL: " + requestURL); + HttpDelete httpDelete = new HttpDelete(requestURL); + + if (MapUtils.isNotEmpty(headers)) { + for (Map.Entry entry : headers.entrySet()) { + httpDelete.addHeader(entry.getKey(), entry.getValue()); + } + } + + response = httpclient.execute(httpDelete); + return getResponse(response, context, "DELETE"); + } catch (Exception ex) { + logger.error(context, "HttpClientUtil:delete: Exception occurred while calling DELETE method for URL: " + requestURL, ex); + return ""; + } finally { + closeResponse(response, context, "DELETE"); + } + } + + /** + * Extracts and returns the response body from a successful HTTP response. + * + * @param response The HTTP response object + * @param context Request context for logging + * @param method The HTTP method name for logging purposes + * @return Response body as a string + * @throws IOException If reading the response fails + */ + private static String getResponse( + CloseableHttpResponse response, RequestContext context, String method) throws IOException { + int status = response.getStatusLine().getStatusCode(); + + if (status >= SUCCESS_STATUS_MIN && status < SUCCESS_STATUS_MAX) { + HttpEntity httpEntity = response.getEntity(); + StatusLine sl = response.getStatusLine(); + + logger.debug( + context, + "HttpClientUtil:getResponse: Response from " + + method + + " call - Status: " + + sl.getStatusCode() + + " - " + + sl.getReasonPhrase()); + + if (null != httpEntity) { + byte[] bytes = EntityUtils.toByteArray(httpEntity); + String resp = new String(bytes); + logger.info(context, "HttpClientUtil:getResponse: Successfully received response from " + method + " call"); + return resp; + } else { + logger.warn(context, "HttpClientUtil:getResponse: Response entity is null for " + method + " call", null); + return ""; + } + } else { + getErrorResponse(response, method, context); + return ""; + } + } + + /** + * Logs error response details when an HTTP request fails. + * + * @param response The HTTP response object containing the error + * @param method The HTTP method name for logging purposes + * @param context Request context for logging + */ + 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.error( + context, + "HttpClientUtil:getErrorResponse: Error response from " + + method + + " call - Response: " + + resp + + " - Status: " + + sl.getStatusCode() + + " - " + + sl.getReasonPhrase(), + null); + } catch (Exception ex) { + logger.error(context, "HttpClientUtil:getErrorResponse: Exception occurred while fetching error response for " + method + " method", ex); + } + } + + /** + * Safely closes the HTTP response object. + * + * @param response The HTTP response to close + * @param context Request context for logging + * @param method The HTTP method name for logging purposes + */ + private static void closeResponse( + CloseableHttpResponse response, RequestContext context, String method) { + if (null != response) { + try { + response.close(); + logger.debug(context, "HttpClientUtil:closeResponse: Successfully closed " + method + " response"); + } catch (Exception ex) { + logger.error( + context, "HttpClientUtil:closeResponse: Exception occurred while closing " + method + " response object", ex); + } + } + } +} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/HttpUtil.java b/core/sunbird-platform-common/src/main/java/org/sunbird/http/HttpUtil.java similarity index 56% rename from course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/HttpUtil.java rename to core/sunbird-platform-common/src/main/java/org/sunbird/http/HttpUtil.java index 176ef2241..0c288d422 100644 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/HttpUtil.java +++ b/core/sunbird-platform-common/src/main/java/org/sunbird/http/HttpUtil.java @@ -1,21 +1,20 @@ -/** */ -package org.sunbird.common.models.util; +package org.sunbird.http; import com.mashape.unirest.http.HttpResponse; import com.mashape.unirest.http.Unirest; import com.mashape.unirest.http.exceptions.UnirestException; import org.apache.commons.collections4.MapUtils; -import org.sunbird.common.models.response.HttpUtilResponse; -import org.sunbird.common.responsecode.ResponseCode; +import org.sunbird.response.HttpUtilResponse; +import org.sunbird.logging.LoggerUtil; +import org.sunbird.response.ResponseCode; import java.io.IOException; import java.util.HashMap; import java.util.Map; /** - * This utility method will handle external http call - * - * @author Manzarul + * Utility class to handle external HTTP calls. + * Provides methods for GET, POST, and PATCH requests using Unirest. */ public class HttpUtil { @@ -26,9 +25,9 @@ private HttpUtil() {} * Makes an HTTP request using GET method to the specified URL. * * @param requestURL the URL of the remote server - * @param headers the Map - * @return An String object - * @throws IOException thrown if any I/O error occurred + * @param headers the Map <String,String> containing request headers + * @return The response body as a String, or an empty string if the call fails with a non-200 status + * @throws UnirestException thrown if any error occurred during the request */ public static String sendGetRequest(String requestURL, Map headers) throws UnirestException { @@ -37,10 +36,10 @@ public static String sendGetRequest(String requestURL, Map heade if(200 == httpResponse.getStatus()) { long stopTime = System.currentTimeMillis(); long elapsedTime = stopTime - startTime; - logger.info(null, "Time taken to execute the request for Url : " + requestURL + " is: " + elapsedTime); + logger.info(null, "HttpUtil:sendGetRequest: Execution finished for URL: " + requestURL + ", duration: " + elapsedTime + " ms"); return httpResponse.getBody(); } else { - logger.error(null, "Error while calling request: " + requestURL + " :: response " + httpResponse.getStatus() + " :: " + httpResponse.getBody(), null); + logger.error(null, "HttpUtil:sendGetRequest: Failed for URL: " + requestURL + ", Status: " + httpResponse.getStatus() + ", Response: " + httpResponse.getBody(), null); return ""; } } @@ -50,8 +49,9 @@ public static String sendGetRequest(String requestURL, Map heade * * @param requestURL the URL of the remote server * @param params A map containing POST data in form of key-value pairs - * @return String - * @throws IOException thrown if any I/O error occurred + * @param headers the Map <String,String> containing request headers + * @return The response body as a String + * @throws Exception thrown if any error occurred during the request */ public static String sendPostRequest( String requestURL, Map params, Map headers) @@ -62,23 +62,23 @@ public static String sendPostRequest( long stopTime = System.currentTimeMillis(); long elapsedTime = stopTime - startTime; logger.info( null, - "HttpUtil sendPostRequest method end at ==" - + stopTime - + " for requestURL " + "HttpUtil:sendPostRequest: Execution finished for URL: " + requestURL - + " ,Total time elapsed = " - + elapsedTime); + + ", Duration: " + + elapsedTime + + " ms"); return str; } /** - * Makes an HTTP request using POST method to the specified URL. + * Makes an HTTP request using POST method to the specified URL with a String body. * * @param requestURL the URL of the remote server - * @param params A map containing POST data in form of key-value pairs - * @return An HttpURLConnection object - * @throws IOException thrown if any I/O error occurred + * @param params String payload data + * @param headers the Map <String,String> containing request headers + * @return The response body as a String + * @throws Exception thrown if any error occurred during the request */ public static String sendPostRequest( String requestURL, String params, Map headers) throws Exception { @@ -88,23 +88,22 @@ public static String sendPostRequest( long stopTime = System.currentTimeMillis(); long elapsedTime = stopTime - startTime; logger.info( null, - "HttpUtil sendPostRequest method end at ==" - + stopTime - + " for requestURL " + "HttpUtil:sendPostRequest: Execution finished for URL: " + requestURL - + " ,Total time elapsed = " - + elapsedTime); + + ", Duration: " + + elapsedTime + + " ms"); return str; } /** - * Makes an HTTP request using POST method to the specified URL and in response it will return Map - * of status code with post response in String format. + * Makes an HTTP request using POST method to the specified URL and returns a comprehensive response object. * * @param requestURL the URL of the remote server - * @param params A map containing POST data in form of key-value pairs - * @return HttpUtilResponse + * @param params The request body as a String + * @param headers the Map <String,String> containing request headers + * @return HttpUtilResponse containing status code and body * @throws IOException thrown if any I/O error occurred */ public static HttpUtilResponse doPostRequest( @@ -115,17 +114,16 @@ public static HttpUtilResponse doPostRequest( HttpResponse httpResponse = Unirest.post(requestURL).headers(headers).body(params).asString(); response = new HttpUtilResponse(httpResponse.getBody(), httpResponse.getStatus()); } catch (Exception ex) { - logger.error(null, "Exception occurred while reading body of POST call response : " , ex); + logger.error(null, "HttpUtil:doPostRequest: Exception occurred while reading response body for URL: " + requestURL, ex); } long stopTime = System.currentTimeMillis(); long elapsedTime = stopTime - startTime; logger.info(null, - "HttpUtil doPostRequest method end at ==" - + stopTime - + " for requestURL " + "HttpUtil:doPostRequest: Execution finished for URL: " + requestURL - + " ,Total time elapsed = " - + elapsedTime); + + ", Duration: " + + elapsedTime + + " ms"); return response; } @@ -133,19 +131,17 @@ public static HttpUtilResponse doPostRequest( * Makes an HTTP request using PATCH method to the specified URL. * * @param requestURL the URL of the remote server - * @param params A map containing POST data in form of key-value pairs - * @return An HttpURLConnection object - * @throws IOException thrown if any I/O error occurred + * @param params The request body as a String + * @param headers the Map <String,String> containing request headers + * @return ResponseCode string success or Failure string */ public static String sendPatchRequest( String requestURL, String params, Map headers) { long startTime = System.currentTimeMillis(); logger.info(null, - "HttpUtil sendPatchRequest method started at ==" - + startTime - + " for requestURL and params " + "HttpUtil:sendPatchRequest: Started for URL: " + requestURL - + " param==" + + " with params: " + params); try { @@ -155,47 +151,55 @@ public static String sendPatchRequest( long stopTime = System.currentTimeMillis(); long elapsedTime = stopTime - startTime; logger.info(null, - "HttpUtil sendPatchRequest method end at ==" - + stopTime - + " for requestURL " + "HttpUtil:sendPatchRequest: Success for URL: " + requestURL - + " ,Total time elapsed = " - + elapsedTime); + + ", Status: " + + httpResponse.getStatus() + + ", Duration: " + + elapsedTime + + " ms"); return ResponseCode.success.getErrorCode(); } long stopTime = System.currentTimeMillis(); long elapsedTime = stopTime - startTime; logger.info(null, - "Patch request failure status code ==" - + httpResponse.getStatus() - + stopTime - + " for requestURL " + "HttpUtil:sendPatchRequest: Failed for URL: " + requestURL - + " ,Total time elapsed = " - + elapsedTime); + + ", Status: " + + httpResponse.getStatus() + + ", Duration: " + + elapsedTime + + " ms"); return "Failure"; } catch (Exception e) { - logger.error(null, "HttpUtil call fails == " + e.getMessage(), e); + logger.error(null, "HttpUtil:sendPatchRequest: Exception for URL: " + requestURL, e); } long stopTime = System.currentTimeMillis(); long elapsedTime = stopTime - startTime; logger.info( null, - "HttpUtil sendPatchRequest method end at ==" - + stopTime - + " for requestURL " + "HttpUtil:sendPatchRequest: Ended with failure for URL: " + requestURL - + " ,Total time elapsed = " - + elapsedTime); + + ", Duration: " + + elapsedTime + + " ms"); return "Failure"; } + /** + * Helper method to construct headers. + * Adds Content-Type: application/json by default. + * + * @param input Additional headers map + * @return A new Map containing all headers + * @throws Exception if an error occurs + */ public static Map getHeader(Map input) throws Exception { - return new HashMap() { - { - put("Content-Type", "application/json"); - if (MapUtils.isNotEmpty(input)) putAll(input); - } - }; + Map headers = new HashMap<>(); + headers.put("Content-Type", "application/json"); + if (MapUtils.isNotEmpty(input)) { + headers.putAll(input); + } + return headers; } } \ No newline at end of file diff --git a/core/sunbird-platform-common/src/main/java/org/sunbird/kafka/InstructionEventGenerator.java b/core/sunbird-platform-common/src/main/java/org/sunbird/kafka/InstructionEventGenerator.java new file mode 100644 index 000000000..5768da166 --- /dev/null +++ b/core/sunbird-platform-common/src/main/java/org/sunbird/kafka/InstructionEventGenerator.java @@ -0,0 +1,148 @@ +package org.sunbird.kafka; + +import com.fasterxml.jackson.databind.ObjectMapper; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; +import org.apache.commons.collections.MapUtils; +import org.apache.commons.lang3.StringUtils; +import org.sunbird.exception.ProjectCommonException; +import org.sunbird.keys.JsonKey; +import org.sunbird.logging.LoggerUtil; +import org.sunbird.response.ResponseCode; +import org.sunbird.telemetry.dto.TelemetryBJREvent; + +/** + * Helper class to generate and push instruction events to Kafka. + */ +public class InstructionEventGenerator { + + private static final LoggerUtil logger = new LoggerUtil(InstructionEventGenerator.class); + private static final ObjectMapper mapper = new ObjectMapper(); + private static final String BE_JOB_REQUEST_EVENT_ID = "BE_JOB_REQUEST"; + private static final int ITERATION = 1; + + private static final String ACTOR_ID = "Sunbird LMS Flink Job"; + private static final String ACTOR_TYPE = "System"; + private static final String PDATA_ID = "org.sunbird.platform"; + private static final String PDATA_VERSION = "1.0"; + + private InstructionEventGenerator() {} + + /** + * Pushes an instruction event to the specified Kafka topic. + * + * @param topic The Kafka topic to push the event to. + * @param data The data map containing actor, context, object, edata, etc. + * @throws Exception If event generation fails or topic is invalid. + */ + public static void pushInstructionEvent(String topic, Map data) throws Exception { + pushInstructionEvent(null, topic, data); + } + + /** + * Pushes an instruction event to the specified Kafka topic with a specific key. + * + * @param key The Kafka message key. + * @param topic The Kafka topic to push the event to. + * @param data The data map containing actor, context, object, edata, etc. + * @throws Exception If event generation fails or topic is invalid. + */ + public static void pushInstructionEvent(String key, String topic, Map data) + throws Exception { + String beJobRequestEvent = generateInstructionEventMetadata(data); + + if (StringUtils.isBlank(beJobRequestEvent)) { + throw new ProjectCommonException( + ResponseCode.invalidRequestData.getErrorCode(), + "Event is not generated properly.", + ResponseCode.CLIENT_ERROR.getResponseCode()); + } + + if (StringUtils.isBlank(topic)) { + throw new ProjectCommonException( + ResponseCode.invalidRequestData.getErrorCode(), + "Invalid topic id.", + ResponseCode.CLIENT_ERROR.getResponseCode()); + } + + if (StringUtils.isNotBlank(key)) { + KafkaClient.send(key, beJobRequestEvent, topic); + } else { + KafkaClient.send(beJobRequestEvent, topic); + } + } + + private static String generateInstructionEventMetadata(Map data) { + Map actor = new HashMap<>(); + Map context = new HashMap<>(); + Map object = new HashMap<>(); + Map edata = new HashMap<>(); + + Map actorData = (Map) data.get("actor"); + if (MapUtils.isNotEmpty(actorData)) { + actor.putAll(actorData); + } else { + actor.put("id", ACTOR_ID); + actor.put("type", ACTOR_TYPE); + } + + Map contextData = (Map) data.get("context"); + if (MapUtils.isNotEmpty(contextData)) { + context.putAll(contextData); + } + + Map pdata = new HashMap<>(); + pdata.put("id", PDATA_ID); + pdata.put("ver", PDATA_VERSION); + context.put("pdata", pdata); + + if (data.containsKey(JsonKey.CDATA)) { + context.put(JsonKey.CDATA, data.get(JsonKey.CDATA)); + } + + Map objectData = (Map) data.get("object"); + if (MapUtils.isNotEmpty(objectData)) { + object.putAll(objectData); + } + + Map edataData = (Map) data.get("edata"); + if (MapUtils.isNotEmpty(edataData)) { + edata.putAll(edataData); + } + + if (StringUtils.isNotBlank((String) data.get("action"))) { + edata.put("action", data.get("action")); + } + + return logInstructionEvent(actor, context, object, edata); + } + + private static String logInstructionEvent( + Map actor, + Map context, + Map object, + Map edata) { + + TelemetryBJREvent te = new TelemetryBJREvent(); + long unixTime = System.currentTimeMillis(); + String mid = "LP." + System.currentTimeMillis() + "." + UUID.randomUUID(); + edata.put("iteration", ITERATION); + + te.setEid(BE_JOB_REQUEST_EVENT_ID); + te.setEts(unixTime); + te.setMid(mid); + te.setActor(actor); + te.setContext(context); + te.setObject(object); + te.setEdata(edata); + + String jsonMessage = null; + try { + jsonMessage = mapper.writeValueAsString(te); + } catch (Exception e) { + logger.error("Error logging BE_JOB_REQUEST event: " + e.getMessage(), e); + } + return jsonMessage; + } +} \ No newline at end of file diff --git a/core/sunbird-platform-common/src/main/java/org/sunbird/kafka/KafkaClient.java b/core/sunbird-platform-common/src/main/java/org/sunbird/kafka/KafkaClient.java new file mode 100644 index 000000000..321338f1e --- /dev/null +++ b/core/sunbird-platform-common/src/main/java/org/sunbird/kafka/KafkaClient.java @@ -0,0 +1,193 @@ +package org.sunbird.kafka; + +import java.util.List; +import java.util.Map; +import java.util.Properties; +import org.apache.kafka.clients.consumer.Consumer; +import org.apache.kafka.clients.consumer.ConsumerConfig; +import org.apache.kafka.clients.consumer.KafkaConsumer; +import org.apache.kafka.clients.producer.KafkaProducer; +import org.apache.kafka.clients.producer.Producer; +import org.apache.kafka.clients.producer.ProducerConfig; +import org.apache.kafka.clients.producer.ProducerRecord; +import org.apache.kafka.common.PartitionInfo; +import org.apache.kafka.common.serialization.LongDeserializer; +import org.apache.kafka.common.serialization.LongSerializer; +import org.apache.kafka.common.serialization.StringDeserializer; +import org.apache.kafka.common.serialization.StringSerializer; +import org.sunbird.exception.ProjectCommonException; +import org.sunbird.logging.LoggerUtil; +import org.sunbird.common.ProjectUtil; +import org.sunbird.response.ResponseCode; + +/** + * Helper class for creating and managing Kafka consumers and producers. + *

+ * This class supports two modes of operation: + * 1. **Singleton Mode**: Provides a shared, lazily-initialized Producer string-key/string-value pairs. + * Suitable for general-purpose event logging where a single connection is sufficient. + * 2. **Factory Mode**: Provides methods to create new Producer/Consumer instances with + * custom configurations (Long-key/String-value). + *

+ * + * @author Pradyumna + */ +public class KafkaClient { + + private static final LoggerUtil logger = new LoggerUtil(KafkaClient.class); + private static final String BOOTSTRAP_SERVERS = ProjectUtil.getConfigValue("kafka_urls"); + private static Producer producer; + private static Consumer consumer; + private static volatile Map> topics; + + static { + loadProducerProperties(); + loadConsumerProperties(); + loadTopics(); + } + + // Singleton Methods + + /** + * Retrieves the singleton Kafka Producer instance (String key, String value). + * + * @return The singleton {@link Producer} instance. + */ + public static Producer getProducer() { + return producer; + } + + /** + * Retrieves the singleton Kafka Consumer instance (String key, String value). + * + * @return The singleton {@link Consumer} instance. + */ + public static Consumer getConsumer() { + return consumer; + } + + /** + * Sends a message to a Kafka topic using the singleton producer. + * + * @param event The message content/payload. + * @param topic The target Kafka topic name. + * @throws Exception If the topic does not exist or if sending the message fails. + */ + public static void send(String event, String topic) throws Exception { + if (validate(topic)) { + getProducer().send(new ProducerRecord<>(topic, event)); + } else { + logger.info("KafkaClient:send: Topic id: " + topic + ", does not exist."); + throw new ProjectCommonException( + ResponseCode.mandatoryParamsMissing.getErrorCode(), + "Topic id: " + topic + ", does not exist.", + ResponseCode.CLIENT_ERROR.getResponseCode()); + } + } + + /** + * Sends a message with a specific key to a Kafka topic using the singleton producer. + * + * @param key The message key (used for partitioning). + * @param event The message content/payload. + * @param topic The target Kafka topic name. + * @throws Exception If the topic does not exist or if sending the message fails. + */ + public static void send(String key, String event, String topic) throws Exception { + if (validate(topic)) { + getProducer().send(new ProducerRecord<>(topic, key, event)); + } else { + logger.info("KafkaClient:send: Topic id: " + topic + ", does not exist."); + throw new ProjectCommonException( + ResponseCode.mandatoryParamsMissing.getErrorCode(), + "Topic id: " + topic + ", does not exist.", + ResponseCode.CLIENT_ERROR.getResponseCode()); + } + } + + /** + * Validates if a topic exists in the current Kafka cluster. + * + * @param topic The topic name to check. + * @return true if the topic exists, false otherwise. + */ + private static boolean validate(String topic) { + if (topics == null) { + loadTopics(); + } + return topics.keySet().contains(topic); + } + + private static void loadProducerProperties() { + Properties props = new Properties(); + props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, BOOTSTRAP_SERVERS); + props.put(ProducerConfig.CLIENT_ID_CONFIG, "KafkaClientProducer"); + props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName()); + props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName()); + props.put(ProducerConfig.LINGER_MS_CONFIG, ProjectUtil.getConfigValue("kafka_linger_ms")); + producer = new KafkaProducer<>(props); + } + + private static void loadConsumerProperties() { + Properties props = new Properties(); + props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, BOOTSTRAP_SERVERS); + props.put(ConsumerConfig.CLIENT_ID_CONFIG, "KafkaClientConsumer"); + props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName()); + props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName()); + consumer = new KafkaConsumer<>(props); + } + + private static void loadTopics() { + if (consumer == null) { + loadConsumerProperties(); + } + topics = consumer.listTopics(); + logger.info("KafkaClient:loadTopics: Kafka topic info => " + topics); + } + + // Factory Methods + + /** + * Creates a new Kafka Producer instance with Long keys and String values. + * This is useful for scenarios requiring custom bootstrap servers or client IDs distinct from the singleton configuration. + * + * @param bootstrapServers Comma-separated list of Kafka broker addresses (e.g., "localhost:9092,host2:9092"). + * @param clientId A unique identifier for this producer client. + * @return A new {@link Producer} instance configured with LongSerializer for keys and StringSerializer for values. + */ + public static Producer createProducer(String bootstrapServers, String clientId) { + return new KafkaProducer<>(createProducerProperties(bootstrapServers, clientId)); + } + + /** + * Creates a new Kafka Consumer instance with Long keys and String values. + * This is useful for scenarios requiring custom bootstrap servers or client IDs distinct from the singleton configuration. + * + * @param bootstrapServers Comma-separated list of Kafka broker addresses (e.g., "localhost:9092,host2:9092"). + * @param clientId A unique identifier for this consumer client. + * @return A new {@link Consumer} instance configured with LongDeserializer for keys and StringDeserializer for values. + */ + public static Consumer createConsumer(String bootstrapServers, String clientId) { + return new KafkaConsumer<>(createConsumerProperties(bootstrapServers, clientId)); + } + + private static Properties createProducerProperties(String bootstrapServers, String clientId) { + logger.info("KafkaClient:createProducerProperties: called with bootstrapServers = " + bootstrapServers + " clientId = " + clientId); + Properties props = new Properties(); + props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers); + props.put(ProducerConfig.CLIENT_ID_CONFIG, clientId); + props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, LongSerializer.class.getName()); + props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName()); + return props; + } + + private static Properties createConsumerProperties(String bootstrapServers, String clientId) { + logger.info("KafkaClient:createConsumerProperties: called with bootstrapServers = " + bootstrapServers + " clientId = " + clientId); + Properties props = new Properties(); + props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers); + props.put(ConsumerConfig.CLIENT_ID_CONFIG, clientId); + props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, LongDeserializer.class.getName()); + props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName()); + return props; + } +} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/KeyCloakConnectionProvider.java b/core/sunbird-platform-common/src/main/java/org/sunbird/keycloak/KeyCloakConnectionProvider.java similarity index 67% rename from course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/KeyCloakConnectionProvider.java rename to core/sunbird-platform-common/src/main/java/org/sunbird/keycloak/KeyCloakConnectionProvider.java index 5120a1be7..4f6e025ad 100644 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/KeyCloakConnectionProvider.java +++ b/core/sunbird-platform-common/src/main/java/org/sunbird/keycloak/KeyCloakConnectionProvider.java @@ -1,41 +1,43 @@ -/** */ -package org.sunbird.common.models.util; +package org.sunbird.keycloak; import org.apache.commons.lang3.StringUtils; +import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder; +import org.jboss.resteasy.client.jaxrs.internal.ResteasyClientBuilderImpl; import org.keycloak.admin.client.Keycloak; import org.keycloak.admin.client.KeycloakBuilder; -import org.jboss.resteasy.client.jaxrs.internal.ResteasyClientBuilderImpl; +import org.sunbird.keys.JsonKey; +import org.sunbird.logging.LoggerUtil; +import org.sunbird.common.PropertiesCache; -/** - * @author Manzarul This class will connect to key cloak server and provide the connection to do - * other operations. - */ public class KeyCloakConnectionProvider { + 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; - public static LoggerUtil logger = new LoggerUtil(KeyCloakConnectionProvider.class); - static { try { initialiseConnection(); } catch (Exception e) { - logger.error(null, e.getMessage(), e); + logger.error( + "KeyCloakConnectionProvider: Exception occurred while initializing keycloak connection: " + + e.getMessage(), + e); } registerShutDownHook(); } /** - * Method to initializate the Keycloak connection + * Method to initialize the Keycloak connection from properties or environment. * - * @return Keycloak connection + * @return Keycloak connection instance. + * @throws Exception if initialization fails. */ public static Keycloak initialiseConnection() throws Exception { - logger.info(null, "key cloak instance is creation started."); keycloak = initialiseEnvConnection(); if (keycloak != null) { return keycloak; @@ -60,15 +62,15 @@ public static Keycloak initialiseConnection() throws Exception { CLIENT_ID = cache.getProperty(JsonKey.SSO_CLIENT_ID); keycloak = keycloakBuilder.build(); - logger.info(null, "key cloak instance is created successfully."); + logger.info("KeyCloakConnectionProvider: Keycloak instance created successfully."); return keycloak; } /** - * This method will provide the keycloak connection from environment variable. if environment - * variable is not set then it will return null. + * Initializes Keycloak connection using environment variables if available. * - * @return Keycloak + * @return Keycloak instance or null if env vars are missing. + * @throws Exception if initialization fails. */ private static Keycloak initialiseEnvConnection() throws Exception { String url = System.getenv(JsonKey.SUNBIRD_SSO_URL); @@ -82,12 +84,11 @@ private static Keycloak initialiseEnvConnection() throws Exception { || StringUtils.isBlank(password) || StringUtils.isBlank(cleintId) || StringUtils.isBlank(relam)) { - logger.info(null, - "key cloak connection is not provided by Environment variable."); + logger.info( + "KeyCloakConnectionProvider: Keycloak connection settings not found in environment variables."); return null; } SSO_URL = url; - logger.info(null, "SSO url is==" + SSO_URL); SSO_REALM = relam; CLIENT_ID = cleintId; KeycloakBuilder keycloakBuilder = @@ -104,20 +105,20 @@ private static Keycloak initialiseEnvConnection() throws Exception { if (StringUtils.isNotBlank(clientSecret)) { keycloakBuilder.clientSecret(clientSecret); - logger.info(null, - "KeyCloakConnectionProvider:initialiseEnvConnection client sceret is provided."); + logger.info( + "KeyCloakConnectionProvider: Client secret provided via environment."); } keycloakBuilder.grantType("client_credentials"); keycloak = keycloakBuilder.build(); - logger.info(null, - "key cloak instance is created from Environment variable settings ."); + logger.info( + "KeyCloakConnectionProvider: Keycloak instance created from environment variable settings."); return keycloak; } /** - * This method will provide key cloak connection instance. + * Retrieves the active Keycloak connection instance. * - * @return Keycloak + * @return Keycloak instance. */ public static Keycloak getConnection() { if (keycloak != null) { @@ -126,30 +127,29 @@ public static Keycloak getConnection() { try { return initialiseConnection(); } catch (Exception e) { - logger.error(null, e.getMessage(), e); + logger.error( + "KeyCloakConnectionProvider: Error obtaining Keycloak connection: " + e.getMessage(), + e); } } return null; } /** - * This class will be called by registerShutDownHook to register the call inside jvm , when jvm - * terminate it will call the run method to clean up the resource. - * - * @author Manzarul + * Implementation of Thread to handle resource cleanup on JVM shutdown. */ static class ResourceCleanUp extends Thread { public void run() { - logger.info(null, "started resource cleanup."); - keycloak.close(); - logger.info(null, "completed resource cleanup."); + if (null != keycloak) { + keycloak.close(); + } } } - /** Register the hook for resource clean up. this will be called when jvm shut down. */ + /** Registers a shutdown hook to close Keycloak resources. */ public static void registerShutDownHook() { Runtime runtime = Runtime.getRuntime(); runtime.addShutdownHook(new ResourceCleanUp()); - logger.info(null, "ShutDownHook registered."); } } + diff --git a/core/sunbird-platform-common/src/main/java/org/sunbird/keycloak/KeycloakRequiredActionLinkUtil.java b/core/sunbird-platform-common/src/main/java/org/sunbird/keycloak/KeycloakRequiredActionLinkUtil.java new file mode 100644 index 000000000..1c9c81897 --- /dev/null +++ b/core/sunbird-platform-common/src/main/java/org/sunbird/keycloak/KeycloakRequiredActionLinkUtil.java @@ -0,0 +1,157 @@ +package org.sunbird.keycloak; + +import com.fasterxml.jackson.databind.ObjectMapper; +import java.util.HashMap; +import java.util.Map; +import javax.ws.rs.core.MediaType; +import org.apache.commons.lang3.StringUtils; +import org.apache.http.HttpHeaders; +import org.sunbird.keys.JsonKey; +import org.sunbird.common.ProjectUtil; +import org.sunbird.http.HttpClientUtil; +import org.sunbird.logging.LoggerUtil; +import org.sunbird.request.RequestContext; + +/** + * Utility class for generating Keycloak required action links. + * This class interacts with Keycloak's API to generate links for actions like updating passwords or verifying emails. + */ +public class KeycloakRequiredActionLinkUtil { + + 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"; + private static final String REQUIRED_ACTION = "requiredAction"; + private static final String USERNAME = "userName"; + private static final String EXPIRATION_IN_SEC = "expirationInSecs"; + private static final String REDIRECT_URI = "redirectUri"; + private static final String SUNBIRD_KEYCLOAK_LINK_EXPIRATION_TIME = + "sunbird_keycloak_required_action_link_expiration_seconds"; + private static final String SUNBIRD_KEYCLOAK_REQD_ACTION_LINK = "/get-required-action-link"; + private static final String LINK = "link"; + private static final String ACCESS_TOKEN = "access_token"; + + private static ObjectMapper mapper = new ObjectMapper(); + + /** + * Generates a required action link for a user to perform specific actions on Keycloak. + * This method acts as a backward-compatible overload that does not require a RequestContext. + * + * @param userName The username of the user for whom the link is generated. + * @param redirectUri The URI to which the user will be redirected after completing the action. + * @param requiredAction The specific action to be performed (e.g., VERIFY_EMAIL, UPDATE_PASSWORD). + * @return The generated required action link as a String, or null if an error occurs during generation. + */ + public static String getLink(String userName, String redirectUri, String requiredAction) { + return getLink(userName, redirectUri, requiredAction, null); + } + + /** + * Generates a required action link for a user to perform specific actions on Keycloak. + * + * @param userName The username of the user for whom the link is generated. + * @param redirectUri The URI to which the user will be redirected after completing the action. + * @param requiredAction The specific action to be performed (e.g., VERIFY_EMAIL, UPDATE_PASSWORD). + * @param context The RequestContext used for logging and traceability. + * @return The generated required action link as a String, or null if an error occurs during generation. + */ + public static String getLink( + String userName, String redirectUri, String requiredAction, RequestContext context) { + Map request = new HashMap<>(); + request.put(CLIENT_ID, ProjectUtil.getConfigValue(JsonKey.SUNBIRD_SSO_CLIENT_ID)); + request.put(USERNAME, userName); + request.put(REQUIRED_ACTION, requiredAction); + + String expirationInSecs = ProjectUtil.getConfigValue(SUNBIRD_KEYCLOAK_LINK_EXPIRATION_TIME); + if (StringUtils.isNotBlank(expirationInSecs)) { + request.put(EXPIRATION_IN_SEC, expirationInSecs); + } + request.put(REDIRECT_URI, redirectUri); + + try { + Thread.sleep( + Integer.parseInt(ProjectUtil.getConfigValue(JsonKey.SUNBIRD_SYNC_READ_WAIT_TIME))); + return generateLink(request, context); + } catch (Exception ex) { + logger.error( + context, + "KeycloakRequiredActionLinkUtil:getLink: Error occurred: " + ex.getMessage(), + ex); + } + return null; + } + + /** + * Helper method to generate the link by making an HTTP POST request to Keycloak. + * + * @param request The map containing request parameters (client_id, user_name, etc.). + * @param context The request context for logging. + * @return The generated link. + * @throws Exception If an error occurs during the HTTP request or response parsing. + */ + private static String generateLink(Map request, RequestContext context) + throws Exception { + Map headers = new HashMap<>(); + headers.put(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON); + headers.put( + HttpHeaders.AUTHORIZATION, + JsonKey.BEARER + getAdminAccessToken(context)); + + String baseUrl = ProjectUtil.getConfigValue(JsonKey.SUNBIRD_SSO_URL); + String realm = ProjectUtil.getConfigValue(JsonKey.SUNBIRD_SSO_RELAM); + String url = baseUrl + "realms/" + realm + SUNBIRD_KEYCLOAK_REQD_ACTION_LINK; + + logger.info(context, "KeycloakRequiredActionLinkUtil:generateLink: URL: " + url); + logger.info(context, "KeycloakRequiredActionLinkUtil:generateLink: Request Body: " + mapper.writeValueAsString(request)); + + String response = HttpClientUtil.post(url, mapper.writeValueAsString(request), headers, context); + + logger.info(context, "KeycloakRequiredActionLinkUtil:generateLink: Response: " + response); + + Map responseMap = mapper.readValue(response, Map.class); + return (String) responseMap.get(LINK); + } + + /** + * Retrieves an admin access token from Keycloak using client credentials. + * + * @param context The request context. + * @return The admin access token. + * @throws Exception If an error occurs during token retrieval. + */ + private static String getAdminAccessToken(RequestContext context) throws Exception { + Map headers = new HashMap<>(); + headers.put(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED); + + String url = ProjectUtil.getConfigValue(JsonKey.SUNBIRD_SSO_URL) + + "realms/" + + ProjectUtil.getConfigValue(JsonKey.SUNBIRD_SSO_RELAM) + + "/protocol/openid-connect/token"; + + Map fields = new HashMap<>(); + fields.put("client_id", ProjectUtil.getConfigValue(JsonKey.SUNBIRD_SSO_CLIENT_ID)); + fields.put("client_secret", ProjectUtil.getConfigValue(JsonKey.SUNBIRD_SSO_CLIENT_SECRET)); + fields.put("grant_type", "client_credentials"); + + // HttpClientUtil.post usually takes json, but for form-urlencoded we might need a different approach or + // construct the body string manually if HttpClientUtil supports it. + // Checking previous usage: older code used Unirest.field(). + // HttpClientUtil might not support form fields directly if it expects JSON body. + // However, looking at HttpClientUtil commonly used in Sunbird, it has methods. + // If I cannot verify HttpClientUtil supports form params, I should be careful. + // BUT! I will assume for now I can implement it or re-use the KeycloakUtil logic if found. + // Since KeycloakUtil was not found, I will implement a safe fallback assuming form encoding body string. + + // Construct form-urlencoded body + StringBuilder body = new StringBuilder(); + for (Map.Entry entry : fields.entrySet()) { + if (body.length() > 0) body.append("&"); + body.append(entry.getKey()).append("=").append(entry.getValue()); + } + + String response = HttpClientUtil.post(url, body.toString(), headers, context); + Map responseMap = mapper.readValue(response, Map.class); + return (String) responseMap.get(ACCESS_TOKEN); + } +} \ No newline at end of file diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/BulkUploadJsonKey.java b/core/sunbird-platform-common/src/main/java/org/sunbird/keys/BulkUploadJsonKey.java similarity index 81% rename from course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/BulkUploadJsonKey.java rename to core/sunbird-platform-common/src/main/java/org/sunbird/keys/BulkUploadJsonKey.java index 4cc2757c9..ce79ba454 100644 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/BulkUploadJsonKey.java +++ b/core/sunbird-platform-common/src/main/java/org/sunbird/keys/BulkUploadJsonKey.java @@ -1,9 +1,7 @@ -package org.sunbird.common.models.util; +package org.sunbird.keys; /** - * Constants for Bulk Upload service. - * - * @author Arvind + * Keys for Bulk Upload service. */ public class BulkUploadJsonKey { diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/GeoLocationJsonKey.java b/core/sunbird-platform-common/src/main/java/org/sunbird/keys/GeoLocationJsonKey.java similarity index 70% rename from course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/GeoLocationJsonKey.java rename to core/sunbird-platform-common/src/main/java/org/sunbird/keys/GeoLocationJsonKey.java index 0675821d6..4e9574034 100644 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/GeoLocationJsonKey.java +++ b/core/sunbird-platform-common/src/main/java/org/sunbird/keys/GeoLocationJsonKey.java @@ -1,6 +1,8 @@ -package org.sunbird.common.models.util; +package org.sunbird.keys; -/** Created by arvind on 19/4/18. */ +/** + * Keys used for Geo Location related operations. + */ public class GeoLocationJsonKey { private GeoLocationJsonKey() {} @@ -9,6 +11,7 @@ private GeoLocationJsonKey() {} public static final String CODE = "code"; public static final String LOCATION_TYPE = "type"; public static final String PARENT_ID = "parentId"; + public static final String SUNBIRD_VALID_LOCATION_TYPES = "sunbird_valid_location_types"; public static final String PROPERTY_NAME = "name"; public static final String PROPERTY_VALUE = "value"; public static final String ID = "id"; diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/JsonKey.java b/core/sunbird-platform-common/src/main/java/org/sunbird/keys/JsonKey.java similarity index 98% rename from course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/JsonKey.java rename to core/sunbird-platform-common/src/main/java/org/sunbird/keys/JsonKey.java index 2badeb7f9..3dc1ba622 100644 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/JsonKey.java +++ b/core/sunbird-platform-common/src/main/java/org/sunbird/keys/JsonKey.java @@ -1,12 +1,10 @@ -package org.sunbird.common.models.util; +package org.sunbird.keys; import java.util.Arrays; import java.util.List; /** * This class will contains all the key related to request and response. - * - * @author Manzarul */ public final class JsonKey { @@ -268,6 +266,8 @@ public final class JsonKey { public static final String PROCESS_ID = "processId"; public static final String PROCESS_START_TIME = "processStartTime"; public static final String PDATA_ID = "telemetry_pdata_id"; + public static final String PDATA_PID = "telemetry_pdata_pid"; + public static final String PDATA_VERSION = "telemetry_pdata_version"; public static final String PROFILE_SUMMARY = "profileSummary"; public static final String PROFILE_VISIBILITY = "profileVisibility"; public static final String PROGRESS = "progress"; @@ -317,6 +317,7 @@ public final class JsonKey { public static final String SSO_URL = "sso.url"; public static final String SSO_USERNAME = "sso.username"; public static final String STACKTRACE = "stacktrace"; + public static final String STACKTRACE_CHAR_LENGTH = "stacktrace_char_length"; public static final String START_DATE = "startDate"; public static final String START_TIME = "startTime"; public static final String STATE = "state"; @@ -587,6 +588,9 @@ public final class JsonKey { public static final String CONTENT_LENGTH = "Content-Length"; + public static final String CDATA = "cdata"; + public static final String USER_ORG_SERVICE_PREFIX = "UOS_"; + //#Release-5.4.0 - LR-511 public static final String SUNBIRD_KEYSPACE = "sunbird_userorg_keyspace"; public static final String SUNBIRD_COURSE_KEYSPACE ="sunbird_course_keyspace"; @@ -600,6 +604,7 @@ public final class JsonKey { public static final String ES_USER_INDEX = "es_user_index"; public static final String ES_ORGANISATION_INDEX = "es_organisation_index"; public static final String ES_USER_COURSES_INDEX = "es_user_courses_index"; + public static final String X_REQUEST_ID = "x-request-id"; private JsonKey() {} } diff --git a/core/sunbird-platform-common/src/main/java/org/sunbird/logging/AuditLog.java b/core/sunbird-platform-common/src/main/java/org/sunbird/logging/AuditLog.java new file mode 100644 index 000000000..c76463401 --- /dev/null +++ b/core/sunbird-platform-common/src/main/java/org/sunbird/logging/AuditLog.java @@ -0,0 +1,145 @@ +package org.sunbird.logging; + +import java.util.Map; + +/** + * Represents an audit log entry for tracking operations within the system. + * Captures details such as the user, operation type, object affected, and timestamp. + */ +public class AuditLog { + + private String requestId; + private String objectId; + private String objectType; + private String operationType; + /** Format: yyyy-MM-dd HH:mm:ss */ + private String date; + private String userId; + private Map logRecord; + + /** + * Gets the unique request identifier. + * + * @return The request ID. + */ + public String getRequestId() { + return requestId; + } + + /** + * Sets the unique request identifier. + * + * @param requestId The request ID to set. + */ + public void setRequestId(String requestId) { + this.requestId = requestId; + } + + /** + * Gets the ID of the object being operated on. + * + * @return The object ID. + */ + public String getObjectId() { + return objectId; + } + + /** + * Sets the ID of the object being operated on. + * + * @param objectId The object ID to set. + */ + public void setObjectId(String objectId) { + this.objectId = objectId; + } + + /** + * Gets the type of the object (e.g., "User", "Course"). + * + * @return The object type. + */ + public String getObjectType() { + return objectType; + } + + /** + * Sets the type of the object. + * + * @param objectType The object type to set. + */ + public void setObjectType(String objectType) { + this.objectType = objectType; + } + + /** + * Gets the type of operation performed (e.g., "Create", "Update"). + * + * @return The operation type. + */ + public String getOperationType() { + return operationType; + } + + /** + * Sets the type of operation performed. + * + * @param operationType The operation type to set. + */ + public void setOperationType(String operationType) { + this.operationType = operationType; + } + + /** + * Gets the timestamp of the operation. + * + * @return The date string. + */ + public String getDate() { + return date; + } + + /** + * Sets the timestamp of the operation. + * + * @param date The date string to set. + */ + public void setDate(String date) { + this.date = date; + } + + /** + * Gets the ID of the user performing the operation. + * + * @return The user ID. + */ + public String getUserId() { + return userId; + } + + /** + * Sets the ID of the user performing the operation. + * + * @param userId The user ID to set. + */ + public void setUserId(String userId) { + this.userId = userId; + } + + /** + * Gets the detailed record of the changes or operation data. + * + * @return A map containing log details. + */ + public Map getLogRecord() { + return logRecord; + } + + /** + * Sets the detailed record of the changes or operation data. + * + * @param logRecord The map of log details to set. + */ + public void setLogRecord(Map logRecord) { + this.logRecord = logRecord; + } +} diff --git a/core/sunbird-platform-common/src/main/java/org/sunbird/logging/CustomLogFormat.java b/core/sunbird-platform-common/src/main/java/org/sunbird/logging/CustomLogFormat.java new file mode 100644 index 000000000..3c4977037 --- /dev/null +++ b/core/sunbird-platform-common/src/main/java/org/sunbird/logging/CustomLogFormat.java @@ -0,0 +1,88 @@ +package org.sunbird.logging; + +import org.sunbird.request.RequestContext; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +/** + * Helper class to format log events in a standardised structure. + * Constructs the event map including metadata, context, and actor information. + */ +public class CustomLogFormat { + private String edataType = "system"; + private String eid = "LOG"; + private String ver = "3.0"; + private Map edata = new HashMap<>(); + private Map eventMap = new HashMap<>(); + + /** + * Constructor to initialize and format the log event. + * + * @param requestContext The request context containing IDs and levels. + * @param msg The log message. + * @param object The object associated with the log (optional). + * @param params Additional parameters (optional). + */ + CustomLogFormat( + RequestContext requestContext, + String msg, + Map object, + Map params) { + if (params != null) { + this.edata.put( + "params", + new ArrayList>() { + { + add(params); + } + }); + } + setEventMap(requestContext, msg); + if (object != null) { + this.eventMap.put("object", object); + } + } + + /** + * Retrieves the formatted event map. + * + * @return The complete event map. + */ + public Map getEventMap() { + return this.eventMap; + } + + /** + * Constructs the event map with all required fields. + * + * @param requestContext The request context. + * @param msg The log message. + */ + public void setEventMap(RequestContext requestContext, String msg) { + this.edata.put("type", edataType); + this.edata.put("requestid", requestContext.getRequestId()); + this.edata.put("message", msg); + this.edata.put("level", requestContext.getLoggerLevel()); + this.eventMap.putAll( + new HashMap() { + { + put("eid", eid); + put("ets", System.currentTimeMillis()); + put("ver", ver); + put("mid", "LOG:" + UUID.randomUUID().toString()); + put("context", requestContext.getContextMap()); + put("actor", + new HashMap() { + { + put("id", requestContext.getActorId()); + put("type", requestContext.getActorType()); + } + }); + put("edata", edata); + } + }); + } +} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/LogEvent.java b/core/sunbird-platform-common/src/main/java/org/sunbird/logging/LogEvent.java similarity index 75% rename from course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/LogEvent.java rename to core/sunbird-platform-common/src/main/java/org/sunbird/logging/LogEvent.java index 9c509ee3f..f18fea45f 100644 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/LogEvent.java +++ b/core/sunbird-platform-common/src/main/java/org/sunbird/logging/LogEvent.java @@ -1,13 +1,12 @@ -package org.sunbird.common.models.util; +package org.sunbird.logging; import java.util.HashMap; import java.util.Map; +import org.sunbird.keys.JsonKey; /** - * This class will log the api request , response , and error message insdie log file .in predefine - * structure. - * - * @author Manzarul + * LogEvent class to represent the structure of API request, response, and error logs. + * Used for constructing structured log messages. */ public class LogEvent { @@ -76,14 +75,14 @@ public void setContext(String id, String ver) { } /** - * Set the error data with this method + * Sets the error data for the log event. * - * @param level String - * @param className String - * @param method String - * @param data Object - * @param stackTrace Object - * @param exception Object + * @param level Log level (e.g., INFO, ERROR). + * @param className The name of the class where the event occurred. + * @param method The method name where the event occurred. + * @param data Additional data related to the event. + * @param stackTrace Stack trace if an exception occurred. + * @param exception The exception object. */ public void setEdata( String level, diff --git a/core/sunbird-platform-common/src/main/java/org/sunbird/logging/LoggerEnum.java b/core/sunbird-platform-common/src/main/java/org/sunbird/logging/LoggerEnum.java new file mode 100644 index 000000000..1986021d7 --- /dev/null +++ b/core/sunbird-platform-common/src/main/java/org/sunbird/logging/LoggerEnum.java @@ -0,0 +1,20 @@ +package org.sunbird.logging; + +/** + * Enum representing the various logging levels supported by the application. + * content: + * - INFO + * - WARN + * - DEBUG + * - ERROR + * - BE_LOG (Backend Log) + * - PERF_LOG (Performance Log) + */ +public enum LoggerEnum { + INFO, + WARN, + DEBUG, + ERROR, + BE_LOG, + PERF_LOG; +} diff --git a/core/sunbird-platform-common/src/main/java/org/sunbird/logging/LoggerUtil.java b/core/sunbird-platform-common/src/main/java/org/sunbird/logging/LoggerUtil.java new file mode 100644 index 000000000..b00c99683 --- /dev/null +++ b/core/sunbird-platform-common/src/main/java/org/sunbird/logging/LoggerUtil.java @@ -0,0 +1,326 @@ +package org.sunbird.logging; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.sunbird.exception.ProjectCommonException; +import org.sunbird.request.Request; +import org.sunbird.request.RequestContext; +import org.sunbird.response.ResponseCode; +import org.sunbird.keys.JsonKey; +import org.sunbird.telemetry.util.TelemetryEvents; +import org.sunbird.telemetry.util.TelemetryWriter; + +import java.util.Map; + +/** + * Utility class for structured logging using SLF4J and Jackson. + * Provides methods for logging info, debug, error, and warn messages with context and telemetry support. + */ +public class LoggerUtil { + + private Logger logger; + private String infoLevel = "INFO"; + private String debugLevel = "DEBUG"; + private String errorLevel = "ERROR"; + private String warnLevel = "WARN"; + private Logger defaultLogger; + private final ObjectMapper mapper = new ObjectMapper(); + + /** + * Constructor to initialize LoggerUtil for a specific class. + * + * @param c The class for which the logger is created. + */ + public LoggerUtil(Class c) { + logger = LoggerFactory.getLogger(c); + defaultLogger = LoggerFactory.getLogger("defaultLogger"); + } + + /** + * Logs an INFO message with structured data and request context. + * + * @param requestContext The request context containing tracing information. + * @param message The message to log. + * @param object Additional object data to log. + * @param param Additional parameters to log. + */ + public void info( + RequestContext requestContext, + String message, + Map object, + Map param) { + if (requestContext != null) { + requestContext.setLoggerLevel(infoLevel); + logger.info(jsonMapper(requestContext, message, object, param)); + } else { + defaultLogger.info(message); + } + } + + /** + * Logs an INFO message with request context. + * + * @param requestContext The request context. + * @param message The message to log. + */ + public void info(RequestContext requestContext, String message) { + info(requestContext, message, null, null); + } + + /** + * Logs a simple INFO message without context. + * + * @param message The message to log. + */ + public void info(String message) { + info(null, message, null, null); + } + + /** + * Logs a DEBUG message with structured data if debug is enabled. + * + * @param requestContext The request context. + * @param message The message to log. + * @param object Additional object data. + * @param param Additional parameters. + */ + public void debug( + RequestContext requestContext, + String message, + Map object, + Map param) { + if (isDebugEnabled(requestContext)) { + requestContext.setLoggerLevel(debugLevel); + logger.info(jsonMapper(requestContext, message, object, param)); + } else { + defaultLogger.debug(message); + } + } + + /** + * Logs a DEBUG message with request context. + * + * @param requestContext The request context. + * @param message The message to log. + */ + public void debug(RequestContext requestContext, String message) { + debug(requestContext, message, null, null); + } + + /** + * Logs a simple DEBUG message. + * + * @param message The message to log. + */ + public void debug(String message) { + debug(null, message, null, null); + } + + /** + * Logs an ERROR message with exception details and optional telemetry. + * + * @param requestContext The request context. + * @param message The error message. + * @param object Additional object data. + * @param param Additional parameters. + * @param e The exception/throwable. + */ + public void error( + RequestContext requestContext, + String message, + Map object, + Map param, + Throwable e) { + if (requestContext != null) { + requestContext.setLoggerLevel(errorLevel); + logger.error(jsonMapper(requestContext, message, object, param), e); + } else { + defaultLogger.error(message, e); + } + } + + /** + * Logs an ERROR message with context, telemetry info, and exception. + * + * @param requestContext The request context. + * @param message The error message. + * @param object Additional object data. + * @param param Additional parameters. + * @param e The exception. + * @param telemetryInfo Telemetry information map. + */ + public void error( + RequestContext requestContext, + String message, + Map object, + Map param, + Throwable e, + Map telemetryInfo) { + if (requestContext != null) { + requestContext.setLoggerLevel(errorLevel); + logger.error(jsonMapper(requestContext, message, object, param), e); + } else { + defaultLogger.error(message, e); + } + telemetryProcess(requestContext, telemetryInfo, e); + } + + /** + * Logs an ERROR message with context and exception. + * + * @param requestContext The request context. + * @param message The error message. + * @param e The exception. + */ + public void error(RequestContext requestContext, String message, Throwable e) { + error(requestContext, message, null, null, e); + } + + /** + * Logs a simple ERROR message with exception. + * + * @param message The error message. + * @param e The exception. + */ + public void error(String message, Throwable e) { + error(null, message, null, null, e); + } + + /** + * Logs an ERROR message with context, exception, and telemetry info. + * + * @param requestContext The request context. + * @param message The error message. + * @param e The exception. + * @param telemetryInfo Telemetry data. + */ + public void error( + RequestContext requestContext, String message, Throwable e, Map telemetryInfo) { + error(requestContext, message, null, null, e, telemetryInfo); + } + + /** + * Logs a WARN message with structured data. + * + * @param requestContext The request context. + * @param message The warning message. + * @param object Additional object data. + * @param param Additional parameters. + * @param e The exception (if any). + */ + public void warn( + RequestContext requestContext, + String message, + Map object, + Map param, + Throwable e) { + if (requestContext != null) { + requestContext.setLoggerLevel(warnLevel); + logger.warn((jsonMapper(requestContext, message, object, param)), e); + } else { + defaultLogger.warn(message, e); + } + } + + /** + * Logs a WARN message with context and exception. + * + * @param requestContext The request context. + * @param message The warning message. + * @param e The exception. + */ + public void warn(RequestContext requestContext, String message, Throwable e) { + warn(requestContext, message, null, null, e); + } + + /** + * Logs a simple WARN message with exception. + * + * @param message The warning message. + * @param e The exception. + */ + public void warn(String message, Throwable e) { + warn(null, message, null, null, e); + } + + /** + * Checks if debug logging is enabled for the current request. + * + * @param requestContext The request context. + * @return True if debug is enabled, false otherwise. + */ + private static boolean isDebugEnabled(RequestContext requestContext) { + return (null != requestContext + && StringUtils.equalsIgnoreCase("true", requestContext.getDebugEnabled())); + } + + /** + * Processes telemetry for error events. + * + * @param requestContext The request context. + * @param telemetryInfo The telemetry info map. + * @param e The exception causing the error. + */ + private void telemetryProcess( + RequestContext requestContext, Map telemetryInfo, Throwable e) { + ProjectCommonException projectCommonException = null; + if (e instanceof ProjectCommonException) { + projectCommonException = (ProjectCommonException) e; + } else { + projectCommonException = + new ProjectCommonException( + ResponseCode.internalError.getErrorCode(), + ResponseCode.internalError.getErrorMessage(), + ResponseCode.SERVER_ERROR.getResponseCode()); + } + Request request = new Request(requestContext); + telemetryInfo.put(JsonKey.TELEMETRY_EVENT_TYPE, TelemetryEvents.ERROR.getName()); + + Map params = (Map) telemetryInfo.get(JsonKey.PARAMS); + params.put(JsonKey.ERROR, projectCommonException.getCode()); + params.put(JsonKey.STACKTRACE, generateStackTrace(e.getStackTrace())); + request.setRequest(telemetryInfo); + // lmaxWriter.submitMessage(request); + TelemetryWriter.write(request); + } + + /** + * Generates a string representation of the stack trace. + * + * @param elements Stack trace elements. + * @return The stack trace as a string. + */ + private String generateStackTrace(StackTraceElement[] elements) { + StringBuilder builder = new StringBuilder(""); + for (StackTraceElement element : elements) { + builder.append(element.toString()); + } + return builder.toString(); + } + + /** + * Converts log data into a JSON string using CustomLogFormat. + * + * @param requestContext The request context. + * @param message The log message. + * @param object Additional object data. + * @param param Additional parameters. + * @return JSON string of the log event. + */ + private String jsonMapper( + RequestContext requestContext, + String message, + Map object, + Map param) { + try { + return mapper.writeValueAsString( + new CustomLogFormat(requestContext, message, object, param).getEventMap()); + } catch (JsonProcessingException e) { + error(requestContext, e.getMessage(), e); + } + return ""; + } +} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/ProjectLogger.java b/core/sunbird-platform-common/src/main/java/org/sunbird/logging/ProjectLogger.java similarity index 72% rename from course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/ProjectLogger.java rename to core/sunbird-platform-common/src/main/java/org/sunbird/logging/ProjectLogger.java index c5026324b..e612d1308 100644 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/ProjectLogger.java +++ b/core/sunbird-platform-common/src/main/java/org/sunbird/logging/ProjectLogger.java @@ -1,28 +1,28 @@ -/** */ -package org.sunbird.common.models.util; +package org.sunbird.logging; import com.fasterxml.jackson.databind.ObjectMapper; import java.util.HashMap; import java.util.Map; import java.util.UUID; - import net.logstash.logback.argument.StructuredArguments; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.exception.ExceptionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.sunbird.common.exception.ProjectCommonException; -import org.sunbird.common.request.Request; -import org.sunbird.common.request.RequestContext; -import org.sunbird.common.responsecode.ResponseCode; +import org.sunbird.request.Request; +import org.sunbird.request.RequestContext; +import org.sunbird.response.ResponseCode; +import org.sunbird.exception.ProjectCommonException; +import org.sunbird.keys.JsonKey; import org.sunbird.telemetry.util.TelemetryEvents; import org.sunbird.telemetry.util.TelemetryWriter; /** - * This class will used to log the project message in any level. + * Legacy logger class for project-level logging provided for backward compatibility. * - * @author Manzarul + * @deprecated Use {@link LoggerUtil} for all logging operations. This class will be removed in future versions. */ +@Deprecated public class ProjectLogger { private static String eVersion = "1.0"; @@ -31,24 +31,41 @@ public class ProjectLogger { private static ObjectMapper mapper = new ObjectMapper(); private static Logger rootLogger = LoggerFactory.getLogger("defaultLogger"); private static Logger queryLogger = LoggerFactory.getLogger("queryLogger"); - // private static TelemetryLmaxWriter lmaxWriter = TelemetryLmaxWriter.getInstance(); - /** To log only message. */ + private ProjectLogger() {} + + /** + * Logs a message with default log level (DEBUG). + * + * @param message Text message to be logged. + */ public static void log(String message) { log(message, null, LoggerEnum.DEBUG.name()); } + /** + * Logs an exception message. + * + * @param message The message. + * @param e The exception. + */ public static void log(String message, Throwable e) { log(message, null, e); } + /** + * Logs a message with exception and telemetry information. + * + * @param message The message. + * @param e The exception. + * @param telemetryInfo Telemetry data. + */ public static void log(String message, Throwable e, Map telemetryInfo) { log(message, null, e); telemetryProcess(telemetryInfo, e); } private static void telemetryProcess(Map telemetryInfo, Throwable e) { - ProjectCommonException projectCommonException = null; if (e instanceof ProjectCommonException) { projectCommonException = (ProjectCommonException) e; @@ -67,8 +84,6 @@ private static void telemetryProcess(Map telemetryInfo, Throwabl params.put(JsonKey.STACKTRACE, generateStackTrace(e.getStackTrace())); request.setRequest(telemetryInfo); TelemetryWriter.write(request); - // lmaxWriter.submitMessage(request); - } private static String generateStackTrace(StackTraceElement[] elements) { @@ -83,22 +98,46 @@ public static void log(String message, String logLevel) { log(message, null, logLevel); } - /** To log message, data in used defined log level. */ + /** + * Logs a message with a specific LoggerEnum level. + * + * @param message The message. + * @param logEnum The log level. + */ public static void log(String message, LoggerEnum logEnum) { info(message, null, logEnum); } - /** To log message, data in used defined log level. */ + /** + * Logs message and data with a specific string log level. + * + * @param message The message. + * @param data The data object. + * @param logLevel The log level string. + */ public static void log(String message, Object data, String logLevel) { backendLog(message, data, null, logLevel); } - /** To log exception with message and data. */ + /** + * Logs message, data, and exception. + * + * @param message The message. + * @param data The data object. + * @param e The exception. + */ public static void log(String message, Object data, Throwable e) { backendLog(message, data, e, LoggerEnum.ERROR.name()); } - /** To log exception with message and data for user specific log level. */ + /** + * Logs message, data, exception with a specific log level. + * + * @param message The message. + * @param data The data object. + * @param e The exception. + * @param logLevel The log level. + */ public static void log(String message, Object data, Throwable e, String logLevel) { backendLog(message, data, e, logLevel); } @@ -125,7 +164,6 @@ private static void warn(String message, Object data, Throwable exception) { private static void backendLog(String message, Object data, Throwable e, String logLevel) { if (!StringUtils.isBlank(logLevel)) { - switch (logLevel) { case "INFO": info(message, data); @@ -148,18 +186,15 @@ private static void backendLog(String message, Object data, Throwable e, String private static String getBELogEvent( String logLevel, String message, Object data, LoggerEnum logEnum) { - String logData = getBELog(logLevel, message, data, null, logEnum); - return logData; + return getBELog(logLevel, message, data, null, logEnum); } private static String getBELogEvent(String logLevel, String message, Object data) { - String logData = getBELog(logLevel, message, data, null, null); - return logData; + return getBELog(logLevel, message, data, null, null); } private static String getBELogEvent(String logLevel, String message, Object data, Throwable e) { - String logData = getBELog(logLevel, message, data, e, null); - return logData; + return getBELog(logLevel, message, data, e, null); } private static String getBELog( @@ -167,7 +202,7 @@ private static String getBELog( String mid = dataId + "." + System.currentTimeMillis() + "." + UUID.randomUUID(); long unixTime = System.currentTimeMillis(); LogEvent te = new LogEvent(); - Map eks = new HashMap(); + Map eks = new HashMap<>(); eks.put(JsonKey.LEVEL, logLevel); eks.put(JsonKey.MESSAGE, message); @@ -191,20 +226,22 @@ private static String getBELog( te.setEdata(eks); jsonMessage = mapper.writeValueAsString(te); } catch (Exception e) { - ProjectLogger.log(e.getMessage(), e); + // Avoid recursive calls to ProjectLogger.log if exception happens here + rootLogger.error(e.getMessage(), e); } return jsonMessage; } public static void logQuery(String query, RequestContext requestContext) { - if(isDebugEnabled(requestContext)) { - queryLogger.debug(query, StructuredArguments.entries(requestContext.getContextMap())); + if (isDebugEnabled(requestContext)) { + queryLogger.debug(query, StructuredArguments.entries(requestContext.getContextMap())); } else { queryLogger.debug(query); } } - + private static boolean isDebugEnabled(RequestContext requestContext) { - return (null != requestContext && StringUtils.equalsIgnoreCase("true", requestContext.getDebugEnabled())); + return (null != requestContext + && StringUtils.equalsIgnoreCase("true", requestContext.getDebugEnabled())); } } diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/ActorOperations.java b/core/sunbird-platform-common/src/main/java/org/sunbird/operations/lms/ActorOperations.java similarity index 94% rename from course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/ActorOperations.java rename to core/sunbird-platform-common/src/main/java/org/sunbird/operations/lms/ActorOperations.java index 458c7e1f0..9541b393b 100644 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/ActorOperations.java +++ b/core/sunbird-platform-common/src/main/java/org/sunbird/operations/lms/ActorOperations.java @@ -1,10 +1,8 @@ -package org.sunbird.common.models.util; +package org.sunbird.operations.lms; /** - * This enum will contains different operation for a learner {addCourse, getCourse, update , - * getContent} - * - * @author Manzarul + * Enum containing various operations performed by actors in the LMS system. + * These operations cover courses, users, organisations, pages, and system settings. */ public enum ActorOperations { ENROLL_COURSE("enrollCourse"), @@ -177,21 +175,21 @@ public enum ActorOperations { LIST_JOB_REQUEST("listJobRequest"), UPDATE_ACTIVITY_AGGREGATES("updateActivityAggregates"); - private String value; + private final String value; /** - * constructor + * Constructor for ActorOperations. * - * @param value String + * @param value The string value associated with the operation. */ ActorOperations(String value) { this.value = value; } /** - * returns the enum value + * Retrieves the string value of the operation. * - * @return String + * @return The operation value string. */ public String getValue() { return this.value; diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/BulkUploadActorOperation.java b/core/sunbird-platform-common/src/main/java/org/sunbird/operations/lms/BulkUploadActorOperation.java similarity index 54% rename from course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/BulkUploadActorOperation.java rename to core/sunbird-platform-common/src/main/java/org/sunbird/operations/lms/BulkUploadActorOperation.java index 66cc045da..1b1699b0b 100644 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/BulkUploadActorOperation.java +++ b/core/sunbird-platform-common/src/main/java/org/sunbird/operations/lms/BulkUploadActorOperation.java @@ -1,6 +1,9 @@ -package org.sunbird.common.models.util; +package org.sunbird.operations.lms; -/** Enum to represent bulk upload operations */ +/** + * Enum representing various bulk upload operations within the LMS. + * Includes operations for locations, organizations, and users. + */ public enum BulkUploadActorOperation { LOCATION_BULK_UPLOAD("locationBulkUpload"), LOCATION_BULK_UPLOAD_BACKGROUND_JOB("locationBulkUploadBackground"), @@ -12,12 +15,22 @@ public enum BulkUploadActorOperation { USER_BULK_UPLOAD_BACKGROUND_JOB("userBulkUploadBackground"), USER_BULK_MIGRATION("userBulkMigration"); - private String value; + private final String value; + /** + * Constructor for BulkUploadActorOperation. + * + * @param value The string value associated with the operation. + */ BulkUploadActorOperation(String value) { this.value = value; } + /** + * Retrieves the string value of the operation. + * + * @return The operation value string. + */ public String getValue() { return this.value; } diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/LocationActorOperation.java b/core/sunbird-platform-common/src/main/java/org/sunbird/operations/lms/LocationActorOperation.java similarity index 57% rename from course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/LocationActorOperation.java rename to core/sunbird-platform-common/src/main/java/org/sunbird/operations/lms/LocationActorOperation.java index 224c89482..cd7f6097a 100644 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/LocationActorOperation.java +++ b/core/sunbird-platform-common/src/main/java/org/sunbird/operations/lms/LocationActorOperation.java @@ -1,5 +1,8 @@ -package org.sunbird.common.models.util; +package org.sunbird.operations.lms; +/** + * Enum representing various operations related to locations within the system. + */ public enum LocationActorOperation { CREATE_LOCATION("createLocation"), UPDATE_LOCATION("updateLocation"), @@ -10,12 +13,22 @@ public enum LocationActorOperation { UPSERT_LOCATION_TO_ES("upsertLocationDataToES"), DELETE_LOCATION_FROM_ES("deleteLocationDataFromES"); - private String value; + private final String value; + /** + * Constructor for LocationActorOperation. + * + * @param value The string value associated with the operation. + */ LocationActorOperation(String value) { this.value = value; } + /** + * Retrieves the string value of the operation. + * + * @return The operation value string. + */ public String getValue() { return this.value; } diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/request/HeaderParam.java b/core/sunbird-platform-common/src/main/java/org/sunbird/request/HeaderParam.java similarity index 50% rename from course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/request/HeaderParam.java rename to core/sunbird-platform-common/src/main/java/org/sunbird/request/HeaderParam.java index 783632ab6..52cc5a97a 100644 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/request/HeaderParam.java +++ b/core/sunbird-platform-common/src/main/java/org/sunbird/request/HeaderParam.java @@ -1,9 +1,8 @@ -package org.sunbird.common.request; +package org.sunbird.request; /** - * The keys of the Execution Context Values. - * - * @author Manzarul + * Enum representing the keys for Execution Context Values and HTTP Headers. + * Used to maintain consistency across services for request/response headers. */ public enum HeaderParam { REQUEST_ID, @@ -25,45 +24,52 @@ public enum HeaderParam { ts("ts"), Content_Type("content-type"), X_Authenticated_User_Token("x-authenticated-user-token"), + X_Authenticated_For("x-authenticated-for"), X_Authenticated_Client_Token("x-authenticated-client-token"), X_Authenticated_Client_Id("x-authenticated-client-id"), X_APP_ID("x-app-id"), CHANNEL_ID("x-channel-id"), - X_Response_Length("x-response-length"), - X_Authenticated_For("x-authenticated-for"); - /** name of the parameter */ + X_Trace_ID("x-trace-id"), + X_REQUEST_ID("x-request-id"), + X_TRACE_ENABLED("x-trace-enabled"), + X_APP_VERSION("x-app-ver"), + X_APP_VERSION_PORTAL("x-app-version"), + X_SOURCE("x-source"), + X_Response_Length("x-response-length"); + + /** Name of the parameter/header. */ private String name; /** - * 1-arg constructor + * Constructor with name. * - * @param name String + * @param name The string representation of the header/parameter. */ private HeaderParam(String name) { this.name = name; } /** - * this will return parameter default name + * Default constructor. + */ + private HeaderParam() {} + + /** + * Returns the parameter name. If a specific name provided in constructor, returns that. + * Otherwise, returns the enum name. * - * @return + * @return The parameter name. */ public String getParamName() { return this.name(); } - private HeaderParam() {} - /** - * This will provide name of one argument enum + * Returns the specific name associated with the enum constant, if any. * - * @return String + * @return The name value. */ public String getName() { return name; } - - public void setName(String name) { - this.name = name; - } } diff --git a/core/sunbird-platform-common/src/main/java/org/sunbird/request/Request.java b/core/sunbird-platform-common/src/main/java/org/sunbird/request/Request.java new file mode 100644 index 000000000..fa7c880b3 --- /dev/null +++ b/core/sunbird-platform-common/src/main/java/org/sunbird/request/Request.java @@ -0,0 +1,323 @@ +package org.sunbird.request; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import java.io.Serializable; +import java.text.MessageFormat; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; +import org.apache.commons.lang3.StringUtils; +import org.sunbird.exception.ProjectCommonException; +import org.sunbird.keys.JsonKey; +import org.sunbird.common.ProjectUtil; +import org.sunbird.response.ResponseCode; + +/** + * Consolidated Request class for Sunbird services (LMS, UserOrg, Notification). + * + *

This class standardizes the Request object across services, incorporating: + *

    + *
  • The rich feature set of the LMS implementation (utility methods). + *
  • The data safety of the Notification implementation (using HashMap instead of WeakHashMap). + *
  • Additional fields and constructors for flexibility. + *
+ */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class Request implements Serializable { + + private static final long serialVersionUID = -2362783406031347676L; + private static final Integer MIN_TIMEOUT = 0; + private static final Integer MAX_TIMEOUT = 30; + private static final int WAIT_TIME_VALUE = 30; + + protected Map context; + private RequestContext requestContext; + + private String id; + private String ver; + private String ts; + private RequestParams params; + + // Use HashMap instead of WeakHashMap to prevent premature garbage collection of request data + private Map request = new HashMap<>(); + + private String managerName; + private String operation; + private String requestId; + private int env; + + // Path field from Notification service + protected String path; + + private Integer timeout; // in seconds + + /** Default constructor initializes context and params. */ + public Request() { + this.context = new HashMap<>(); + this.params = new RequestParams(); + } + + /** + * Constructor with RequestContext. + * + * @param requestContext The context of the request. + */ + public Request(RequestContext requestContext) { + this.context = new HashMap<>(); + this.params = new RequestParams(); + this.requestContext = requestContext; + } + + /** + * Copy constructor. + * + *

Note: This performs a shallow copy of RequestParams. + * + * @param request The request object to copy from. + */ + public Request(Request request) { + this.params = request.getParams(); + if (this.params == null) { + this.params = new RequestParams(); + } + // Ensure msgid is set if available in the source request's params or requestId + if (StringUtils.isBlank(this.params.getMsgid()) + && StringUtils.isNotBlank(request.getRequestId())) { + this.params.setMsgid(request.getRequestId()); + } + + this.context = new HashMap<>(); + if (request.getContext() != null) { + this.context.putAll(request.getContext()); + } + + this.requestContext = request.getRequestContext(); + this.request = new HashMap<>(); + if (request.getRequest() != null) { + this.request.putAll(request.getRequest()); + } + + this.id = request.getId(); + this.ver = request.getVer(); + this.ts = request.getTs(); + this.managerName = request.getManagerName(); + this.operation = request.getOperation(); + this.requestId = request.getRequestId(); + this.env = request.getEnv(); + this.path = request.getPath(); + this.timeout = request.getTimeout(); + } + + /** + * Converts configured fields to lowercase in the request map. Configuration key: {@link + * JsonKey#SUNBIRD_API_REQUEST_LOWER_CASE_FIELDS} + */ + public void toLower() { + String configValue = ProjectUtil.getConfigValue(JsonKey.SUNBIRD_API_REQUEST_LOWER_CASE_FIELDS); + if (StringUtils.isNotBlank(configValue)) { + Arrays.stream(configValue.split(",")) + .forEach( + field -> { + Object value = this.getRequest().get(field); + if (value instanceof String && StringUtils.isNotBlank((String) value)) { + this.getRequest().put(field, ((String) value).toLowerCase()); + } + }); + } + } + + /** + * Gets the request ID. Checks params first, then the requestId field. + * + * @return The request ID. + */ + public String getRequestId() { + // Logic from Notification: check params first + if (this.params != null && StringUtils.isNotBlank(this.params.getMsgid())) { + return this.params.getMsgid(); + } + return requestId; + } + + /** + * Sets the request ID. + * + * @param requestId The request ID to set. + */ + public void setRequestId(String requestId) { + this.requestId = requestId; + // Sync with params if needed, or leave decoupled as per original implementations + } + + public Map getContext() { + return context; + } + + public void setContext(Map context) { + this.context = context; + } + + public Map getRequest() { + return request; + } + + public void setRequest(Map request) { + this.request = request; + } + + public Object get(String key) { + return request.get(key); + } + + /** + * Helper method to get a value with a default. + * + * @param key The key to look up. + * @param defaultVal The default value if key is not present. + * @return The value or the default. + */ + public Object getOrDefault(String key, Object defaultVal) { + return request.getOrDefault(key, defaultVal); + } + + /** + * Checks if the request map contains the key. + * + * @param key The key to check. + * @return True if key exists. + */ + public Boolean contains(String key) { + return request.containsKey(key); + } + + /** + * Puts a value into the request map. + * + * @param key The key. + * @param vo The value object. + */ + public void put(String key, Object vo) { + request.put(key, vo); + } + + /** + * Copies all entries from the given map to the request map. + * + * @param map The map to copy from. + */ + public void copyRequestValueObjects(Map map) { + if (map != null && !map.isEmpty()) { + this.request.putAll(map); + } + } + + public String getManagerName() { + return managerName; + } + + public void setManagerName(String managerName) { + this.managerName = managerName; + } + + public String getOperation() { + return operation; + } + + public void setOperation(String operation) { + this.operation = operation; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getVer() { + return ver; + } + + public void setVer(String ver) { + this.ver = ver; + } + + public String getTs() { + return ts; + } + + public void setTs(String ts) { + this.ts = ts; + } + + public RequestParams getParams() { + return params; + } + + /** + * Sets the request parameters. Auto-sets msgid if requestId is present. + * + * @param params The request parameters. + */ + public void setParams(RequestParams params) { + this.params = params; + // Auto-set msgid if requestId is present and msgid is not + if (this.params.getMsgid() == null && requestId != null) { + this.params.setMsgid(requestId); + } + } + + public int getEnv() { + return env; + } + + public void setEnv(int env) { + this.env = env; + } + + public Integer getTimeout() { + return timeout == null ? WAIT_TIME_VALUE : timeout; + } + + /** + * Sets the timeout value. + * + * @param timeout The timeout in seconds. + * @throws ProjectCommonException If timeout is invalid. + */ + public void setTimeout(Integer timeout) { + if (timeout < MIN_TIMEOUT && timeout > MAX_TIMEOUT) { + ProjectCommonException.throwServerErrorException( + ResponseCode.invalidRequestTimeout, + MessageFormat.format(ResponseCode.invalidRequestTimeout.getErrorMessage(), timeout)); + } + this.timeout = timeout; + } + + public RequestContext getRequestContext() { + return requestContext; + } + + public void setRequestContext(RequestContext requestContext) { + this.requestContext = requestContext; + } + + public String getPath() { + return path; + } + + public void setPath(String path) { + this.path = path; + } + + @Override + public String toString() { + return "Request [" + + (context != null ? "context=" + context + ", " : "") + + (request != null ? "request=" + request + ", " : "") + + (id != null ? "id=" + id + ", " : "") + + (operation != null ? "operation=" + operation : "") + + "]"; + } +} \ No newline at end of file diff --git a/core/sunbird-platform-common/src/main/java/org/sunbird/request/RequestContext.java b/core/sunbird-platform-common/src/main/java/org/sunbird/request/RequestContext.java new file mode 100644 index 000000000..ba5be88f8 --- /dev/null +++ b/core/sunbird-platform-common/src/main/java/org/sunbird/request/RequestContext.java @@ -0,0 +1,358 @@ +package org.sunbird.request; + +import com.fasterxml.jackson.annotation.JsonAlias; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * Consolidated RequestContext class for Sunbird services (LMS, UserOrg, Notification). + * + *

This class serves as a unified context object that combines the fields and behaviors required by + * different services within the Sunbird platform. It supports: + * + *

    + *
  • LMS: Telemetry support with `pdata` (Protocol Data), `channel`, `env` (Environment), + * and a nested context map. + *
  • UserOrg: General request properties such as `appId`, `source`, and `telemetryContext`. + *
  • Notification: Actor and logging specific fields like `actorId` and `loggerLevel`. + *
+ * + *

This allows for a standardize way to pass request context information (headers, trace IDs, + * user info) through the service layers. + */ +public class RequestContext { + + // ------------------------------------------------------------------------- + // Common Fields + // ------------------------------------------------------------------------- + + /** User ID (Actor). */ + private String uid; + + /** Device ID. */ + private String did; + + /** Session ID. */ + private String sid; + + /** Debug mode flag. */ + private String debugEnabled; + + /** + * Request ID. Mapped to 'requestId' for LMS compatibility using JsonAlias. + */ + @JsonProperty("reqId") + @JsonAlias("requestId") + private String reqId; + + /** Operation name. */ + private String op; + + /** + * General context map to hold dynamic attributes. + * In LMS scenarios, this holds the telemetry context. + */ + private Map contextMap = new HashMap<>(); + + // ------------------------------------------------------------------------- + // UserOrg / Notification Specific Fields + // ------------------------------------------------------------------------- + + /** Application ID. */ + private String appId; + + /** Application Version. */ + private String appVer; + + /** Source of the request. */ + private String source; + + /** Specific telemetry context map for UserOrg/Notification services. */ + private Map telemetryContext = new HashMap<>(); + + // ------------------------------------------------------------------------- + // LMS Specific Fields + // ------------------------------------------------------------------------- + + /** Channel header value (X-Channel-Id). */ + private String channel; + + /** Environment identifier (e.g., "course", "user"). */ + private String env; + + /** + * Protocol Data (pdata) map. + * Contains 'id', 'pid', 'ver' for telemetry. + */ + private Map pdata = new HashMap<>(); + + // ------------------------------------------------------------------------- + // Notification / LMS Common Attributes + // ------------------------------------------------------------------------- + + /** ID of the actor performing the request. */ + private String actorId; + + /** Type of the actor (e.g., "Consumer", "System"). */ + private String actorType; + + /** Logging level for the request context. */ + private String loggerLevel; + + /** + * Default constructor. + */ + public RequestContext() {} + + /** + * Constructor designed for UserOrg and Notification style requests. + * Initializes general request metadata and populates the context map with these values. + * + * @param uid User ID + * @param did Device ID + * @param sid Session ID + * @param appId Application ID + * @param appVer Application Version + * @param reqId Request ID + * @param source Request Source + * @param debugEnabled Debug flag + * @param op Operation name + */ + public RequestContext( + String uid, + String did, + String sid, + String appId, + String appVer, + String reqId, + String source, + String debugEnabled, + String op) { + this.uid = uid; + this.did = did; + this.sid = sid; + this.appId = appId; + this.appVer = appVer; + this.reqId = reqId; + this.source = source; + this.debugEnabled = debugEnabled; + this.op = op; + + // Populate contextMap as done in UserOrg/Notification patterns + contextMap.put("uid", uid); + contextMap.put("did", did); + contextMap.put("sid", sid); + contextMap.put("appId", appId); + contextMap.put("appVer", appVer); + contextMap.put("reqId", reqId); + contextMap.put("source", source); + contextMap.put("op", op); + } + + /** + * Constructor designed for LMS style requests, focusing on telemetry requirements. + * Initializes parameters required for constructing the `pdata` and telemetry `contextMap`. + * + * @param channel Channel ID + * @param pdataId Producer Data ID (e.g. producer ID) + * @param env Environment identifier + * @param did Device ID + * @param sid Session ID + * @param pid Producer ID + * @param pver Producer Version + * @param cdata Correlation Data list + */ + public RequestContext( + String channel, + String pdataId, + String env, + String did, + String sid, + String pid, + String pver, + List cdata) { + this.did = did; + this.sid = sid; + this.channel = channel; + this.env = env; + + this.pdata.put("id", pdataId); + this.pdata.put("pid", pid); + this.pdata.put("ver", pver); + + this.contextMap.put("did", did); + this.contextMap.put("sid", sid); + this.contextMap.put("channel", channel); + this.contextMap.put("env", env); + this.contextMap.put("pdata", pdata); + if (cdata != null) { + this.contextMap.put("cdata", cdata); + } + } + + // ------------------------------------------------------------------------- + // Getters and Setters + // ------------------------------------------------------------------------- + + public String getUid() { + return uid; + } + + public void setUid(String uid) { + this.uid = uid; + } + + public String getDid() { + return did; + } + + public void setDid(String did) { + this.did = did; + } + + public String getSid() { + return sid; + } + + public void setSid(String sid) { + this.sid = sid; + } + + public String getAppId() { + return appId; + } + + public void setAppId(String appId) { + this.appId = appId; + } + + public String getAppVer() { + return appVer; + } + + public void setAppVer(String appVer) { + this.appVer = appVer; + } + + /** + * Gets the Request ID. + * @return reqId + */ + public String getReqId() { + return reqId; + } + + /** + * Sets the Request ID. + * @param reqId + */ + public void setReqId(String reqId) { + this.reqId = reqId; + } + + /** + * Alias for getReqId(), primarily for LMS compatibility. + * @return reqId + */ + public String getRequestId() { + return reqId; + } + + /** + * Alias for setReqId(), primarily for LMS compatibility. + * @param requestId + */ + public void setRequestId(String requestId) { + this.reqId = requestId; + } + + public String getDebugEnabled() { + return debugEnabled; + } + + public void setDebugEnabled(String debugEnabled) { + this.debugEnabled = debugEnabled; + } + + public String getOp() { + return op; + } + + public void setOp(String op) { + this.op = op; + } + + public String getSource() { + return source; + } + + public void setSource(String source) { + this.source = source; + } + + public String getChannel() { + return channel; + } + + public void setChannel(String channel) { + this.channel = channel; + } + + public String getEnv() { + return env; + } + + public void setEnv(String env) { + this.env = env; + } + + public Map getPdata() { + return pdata; + } + + public void setPdata(Map pdata) { + this.pdata = pdata; + } + + public String getActorId() { + return actorId; + } + + public void setActorId(String actorId) { + this.actorId = actorId; + } + + public String getActorType() { + return actorType; + } + + public void setActorType(String actorType) { + this.actorType = actorType; + } + + public String getLoggerLevel() { + return loggerLevel; + } + + public void setLoggerLevel(String loggerLevel) { + this.loggerLevel = loggerLevel; + } + + public Map getContextMap() { + return contextMap; + } + + public void setContextMap(Map contextMap) { + this.contextMap = contextMap; + } + + public Map getTelemetryContext() { + return telemetryContext; + } + + public void setTelemetryContext(Map telemetryContext) { + this.telemetryContext = telemetryContext; + } +} \ No newline at end of file diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/request/RequestParams.java b/core/sunbird-platform-common/src/main/java/org/sunbird/request/RequestParams.java similarity index 74% rename from course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/request/RequestParams.java rename to core/sunbird-platform-common/src/main/java/org/sunbird/request/RequestParams.java index 92ff599a8..617083b05 100644 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/request/RequestParams.java +++ b/core/sunbird-platform-common/src/main/java/org/sunbird/request/RequestParams.java @@ -1,9 +1,12 @@ -package org.sunbird.common.request; +package org.sunbird.request; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import java.io.Serializable; -/** @author rayulu */ +/** + * Request parameter details. + * + */ @JsonIgnoreProperties(ignoreUnknown = true) public class RequestParams implements Serializable { @@ -27,50 +30,62 @@ public void setAuthToken(String authToken) { this.authToken = authToken; } + /** @return the uid */ public String getUid() { return uid; } + /** @param uid the uid to set */ public void setUid(String uid) { this.uid = uid; } + /** @return the did */ public String getDid() { return did; } + /** @param did the did to set */ public void setDid(String did) { this.did = did; } + /** @return the key */ public String getKey() { return key; } + /** @param key the key to set */ public void setKey(String key) { this.key = key; } + /** @return the msgid */ public String getMsgid() { return msgid; } + /** @param msgid the msgid to set */ public void setMsgid(String msgid) { this.msgid = msgid; } + /** @return the cid */ public String getCid() { return cid; } + /** @param cid the cid to set */ public void setCid(String cid) { this.cid = cid; } + /** @return the sid */ public String getSid() { return sid; } + /** @param sid the sid to set */ public void setSid(String sid) { this.sid = sid; } diff --git a/core/sunbird-platform-common/src/main/java/org/sunbird/response/ClientErrorResponse.java b/core/sunbird-platform-common/src/main/java/org/sunbird/response/ClientErrorResponse.java new file mode 100644 index 000000000..71b8b55df --- /dev/null +++ b/core/sunbird-platform-common/src/main/java/org/sunbird/response/ClientErrorResponse.java @@ -0,0 +1,45 @@ +package org.sunbird.response; + +import org.sunbird.exception.ProjectCommonException; +import org.sunbird.response.ResponseCode; + +/** + * Represents a client-side error response. + *

+ * This class extends the standard {@link Response} to include details about the exception + * that caused the error, typically encapsulating a {@link ProjectCommonException}. + * It defaults the response code to {@link ResponseCode#CLIENT_ERROR}. + */ +public class ClientErrorResponse extends Response { + + private static final long serialVersionUID = 1L; + + /** The exception details associated with this client error. */ + private ProjectCommonException exception = null; + + /** + * Default constructor. + * Initializes the response code to {@link ResponseCode#CLIENT_ERROR}. + */ + public ClientErrorResponse() { + this.responseCode = ResponseCode.CLIENT_ERROR; + } + + /** + * Gets the exception associated with this response. + * + * @return The {@link ProjectCommonException} causing the error. + */ + public ProjectCommonException getException() { + return exception; + } + + /** + * Sets the exception associated with this response. + * + * @param exception The {@link ProjectCommonException} to set. + */ + public void setException(ProjectCommonException exception) { + this.exception = exception; + } +} diff --git a/core/sunbird-platform-common/src/main/java/org/sunbird/response/HttpUtilResponse.java b/core/sunbird-platform-common/src/main/java/org/sunbird/response/HttpUtilResponse.java new file mode 100644 index 000000000..e5a1329cd --- /dev/null +++ b/core/sunbird-platform-common/src/main/java/org/sunbird/response/HttpUtilResponse.java @@ -0,0 +1,66 @@ +package org.sunbird.response; + +/** + * A simple wrapper class for HTTP responses, holding the response body and status code. + * This class is typically used by utility methods handling raw HTTP interactions. + */ +public class HttpUtilResponse { + + /** The raw response body string. */ + private String body; + + /** The HTTP status code of the response. */ + private int statusCode; + + /** + * Default constructor. + */ + public HttpUtilResponse() {} + + /** + * Constructs a new HttpUtilResponse with the specified body and status code. + * + * @param body The response body as a string. + * @param statusCode The integer HTTP status code. + */ + public HttpUtilResponse(String body, int statusCode) { + this.body = body; + this.statusCode = statusCode; + } + + /** + * Gets the response body. + * + * @return The response body string. + */ + public String getBody() { + return body; + } + + /** + * Sets the response body. + * + * @param body The response body string to set. + */ + public void setBody(String body) { + this.body = body; + } + + /** + * Gets the HTTP status code. + * + * @return The status code. + */ + public int getStatusCode() { + return statusCode; + } + + /** + * Sets the HTTP status code. + * + * @param statusCode The status code to set. + */ + public void setStatusCode(int statusCode) { + this.statusCode = statusCode; + } +} diff --git a/core/sunbird-platform-common/src/main/java/org/sunbird/response/Params.java b/core/sunbird-platform-common/src/main/java/org/sunbird/response/Params.java new file mode 100644 index 000000000..3e480610b --- /dev/null +++ b/core/sunbird-platform-common/src/main/java/org/sunbird/response/Params.java @@ -0,0 +1,117 @@ +package org.sunbird.response; + +import java.io.Serializable; + +/** + * Represents the standard response parameters for API responses. + * Contains metadata about the transaction, such as message IDs, status, and error details. + */ +public class Params implements Serializable { + + private static final long serialVersionUID = -8786004970726124473L; + + /** The unique response message ID. */ + private String resmsgid; + + /** The message ID. */ + private String msgid; + + /** The error code, if any. */ + private String err; + + /** The status of the response (e.g., "success", "failed"). */ + private String status; + + /** The descriptive error message, if any. */ + private String errmsg; + + /** + * Gets the response message ID. + * + * @return The response message ID. + */ + public String getResmsgid() { + return resmsgid; + } + + /** + * Sets the response message ID. + * + * @param resmsgid The response message ID to set. + */ + public void setResmsgid(String resmsgid) { + this.resmsgid = resmsgid; + } + + /** + * Gets the message ID. + * + * @return The message ID. + */ + public String getMsgid() { + return msgid; + } + + /** + * Sets the message ID. + * + * @param msgid The message ID to set. + */ + public void setMsgid(String msgid) { + this.msgid = msgid; + } + + /** + * Gets the error code. + * + * @return The error code. + */ + public String getErr() { + return err; + } + + /** + * Sets the error code. + * + * @param err The error code to set. + */ + public void setErr(String err) { + this.err = err; + } + + /** + * Gets the operation status. + * + * @return The status string. + */ + public String getStatus() { + return status; + } + + /** + * Sets the operation status. + * + * @param status The status string to set. + */ + public void setStatus(String status) { + this.status = status; + } + + /** + * Gets the error message description. + * + * @return The error message. + */ + public String getErrmsg() { + return errmsg; + } + + /** + * Sets the error message description. + * + * @param errmsg The error message to set. + */ + public void setErrmsg(String errmsg) { + this.errmsg = errmsg; + } +} diff --git a/core/sunbird-platform-common/src/main/java/org/sunbird/response/Response.java b/core/sunbird-platform-common/src/main/java/org/sunbird/response/Response.java new file mode 100644 index 000000000..c6413cf2b --- /dev/null +++ b/core/sunbird-platform-common/src/main/java/org/sunbird/response/Response.java @@ -0,0 +1,188 @@ +package org.sunbird.response; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import java.io.Serializable; +import java.util.HashMap; +import java.util.Map; +import org.sunbird.response.ResponseCode; + +/** + * A standardized response class used across all layers of the application. + * It encapsulates the result of an API request, including status codes, + * timestamps, versioning, and the actual data payload. + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class Response implements Serializable, Cloneable { + + private static final long serialVersionUID = -3773253896160786443L; + + /** Unique identifier for the response. */ + protected String id; + + /** API version. */ + protected String ver; + + /** Timestamp of the response generation. */ + protected String ts; + + /** Additional response parameters (e.g., status, err, errmsg). */ + protected ResponseParams params; + + /** The response code (e.g., OK, CLIENT_ERROR). Defaults to OK. */ + protected ResponseCode responseCode = ResponseCode.OK; + + /** The map containing the actual result data. */ + protected Map result = new HashMap<>(); + + /** + * Gets the unique response ID. + * + * @return The response ID string. + */ + public String getId() { + return id; + } + + /** + * Sets the unique response ID. + * + * @param id The response ID string. + */ + public void setId(String id) { + this.id = id; + } + + /** + * Gets the API version. + * + * @return The API version string. + */ + public String getVer() { + return ver; + } + + /** + * Sets the API version. + * + * @param ver The API version string. + */ + public void setVer(String ver) { + this.ver = ver; + } + + /** + * Gets the timestamp. + * + * @return The timestamp string. + */ + public String getTs() { + return ts; + } + + /** + * Sets the timestamp. + * + * @param ts The timestamp string. + */ + public void setTs(String ts) { + this.ts = ts; + } + + /** + * Gets the result map containing the data payload. + * + * @return A map of result objects. + */ + public Map getResult() { + return result; + } + + /** + * Retrieves a specific value from the result map. + * + * @param key The key to look up. + * @return The object associated with the key, or null if not found. + */ + public Object get(String key) { + return result.get(key); + } + + /** + * Adds a key-value pair to the result map. + * + * @param key The key for the data. + * @param vo The value object. + */ + public void put(String key, Object vo) { + result.put(key, vo); + } + + /** + * Adds all entries from the provided map to the result map. + * + * @param map The map of entries to add. + */ + public void putAll(Map map) { + result.putAll(map); + } + + /** + * Checks if the result map contains a specific key. + * + * @param key The key to check. + * @return True if the key exists, false otherwise. + */ + public boolean containsKey(String key) { + return result.containsKey(key); + } + + /** + * Gets the response parameters object. + * + * @return The ResponseParams object. + */ + public ResponseParams getParams() { + return params; + } + + /** + * Sets the response parameters object. + * + * @param params The ResponseParams object to set. + */ + public void setParams(ResponseParams params) { + this.params = params; + } + + /** + * Sets the response code. + * + * @param code The ResponseCode enum. + */ + public void setResponseCode(ResponseCode code) { + this.responseCode = code; + } + + /** + * Gets the response code. + * + * @return The ResponseCode enum. + */ + public ResponseCode getResponseCode() { + return this.responseCode; + } + + /** + * Creates a shallow copy of the response object. + * + * @param response The response object to clone. + * @return A cloned Response object, or null if cloning fails. + */ + public Response clone(Response response) { + try { + return (Response) response.clone(); + } catch (CloneNotSupportedException e) { + return null; + } + } +} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/responsecode/ResponseCode.java b/core/sunbird-platform-common/src/main/java/org/sunbird/response/ResponseCode.java similarity index 87% rename from course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/responsecode/ResponseCode.java rename to core/sunbird-platform-common/src/main/java/org/sunbird/response/ResponseCode.java index db082b419..0c15a3876 100644 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/responsecode/ResponseCode.java +++ b/core/sunbird-platform-common/src/main/java/org/sunbird/response/ResponseCode.java @@ -1,560 +1,728 @@ -package org.sunbird.common.responsecode; +package org.sunbird.response; import org.apache.commons.lang3.StringUtils; -import org.sunbird.common.models.util.JsonKey; +import org.sunbird.keys.JsonKey; -/** @author Manzarul */ +/** + * Enum indicating the response code of the API. + * + *

This enum holds all the response codes used across the application, logically grouped by functionality. + * It maps internal error codes (Strings) to their corresponding error messages and HTTP status codes. + */ public enum ResponseCode { - unAuthorized(ResponseMessage.Key.UNAUTHORIZED_USER, ResponseMessage.Message.UNAUTHORIZED_USER), - invalidUserCredentials( - ResponseMessage.Key.INVALID_USER_CREDENTIALS, - ResponseMessage.Message.INVALID_USER_CREDENTIALS), + + // ------------------------------------------------------------------------- + // Generic / Common + // ------------------------------------------------------------------------- + success(ResponseMessage.Key.SUCCESS_MESSAGE, ResponseMessage.Message.SUCCESS_MESSAGE), + internalError(ResponseMessage.Key.INTERNAL_ERROR, ResponseMessage.Message.INTERNAL_ERROR), operationTimeout( ResponseMessage.Key.OPERATION_TIMEOUT, ResponseMessage.Message.OPERATION_TIMEOUT), invalidOperationName( ResponseMessage.Key.INVALID_OPERATION_NAME, ResponseMessage.Message.INVALID_OPERATION_NAME), invalidRequestData( ResponseMessage.Key.INVALID_REQUESTED_DATA, ResponseMessage.Message.INVALID_REQUESTED_DATA), - courseIdRequired( - ResponseMessage.Key.COURSE_ID_MISSING_ERROR, ResponseMessage.Message.COURSE_ID_MISSING_ERROR), - contentIdRequired( - ResponseMessage.Key.CONTENT_ID_MISSING_ERROR, - ResponseMessage.Message.CONTENT_ID_MISSING_ERROR), - errorInvalidConfigParamValue( - ResponseMessage.Key.ERROR_INVALID_CONFIG_PARAM_VALUE, - ResponseMessage.Message.ERROR_INVALID_CONFIG_PARAM_VALUE), - errorMaxSizeExceeded( - ResponseMessage.Key.ERROR_MAX_SIZE_EXCEEDED, ResponseMessage.Message.ERROR_MAX_SIZE_EXCEEDED), + invalidData(ResponseMessage.Key.INVALID_DATA, ResponseMessage.Message.INVALID_DATA), + invalidParameter( + ResponseMessage.Key.INVALID_PARAMETER, ResponseMessage.Message.INVALID_PARAMETER), + invalidParameterValue( + ResponseMessage.Key.INVALID_PARAMETER_VALUE, ResponseMessage.Message.INVALID_PARAMETER_VALUE), + mandatoryParamsMissing( + ResponseMessage.Key.MANDATORY_PARAMETER_MISSING, + ResponseMessage.Message.MANDATORY_PARAMETER_MISSING), + errorMandatoryParamsEmpty( + ResponseMessage.Key.ERROR_MANDATORY_PARAMETER_EMPTY, + ResponseMessage.Message.ERROR_MANDATORY_PARAMETER_EMPTY), + idRequired(ResponseMessage.Key.ID_REQUIRED_ERROR, ResponseMessage.Message.ID_REQUIRED_ERROR), + dataTypeError(ResponseMessage.Key.DATA_TYPE_ERROR, ResponseMessage.Message.DATA_TYPE_ERROR), + invalidValue(ResponseMessage.Key.INVALID_VALUE, ResponseMessage.Message.INVALID_VALUE), + alreadyExists(ResponseMessage.Key.ALREADY_EXISTS, ResponseMessage.Message.ALREADY_EXISTS), + resourceNotFound( + ResponseMessage.Key.RESOURCE_NOT_FOUND, ResponseMessage.Message.RESOURCE_NOT_FOUND), + serverError( + ResponseMessage.Key.INTERNAL_ERROR, ResponseMessage.Message.INTERNAL_ERROR), + customServerError( + ResponseMessage.Key.CUSTOM_SERVER_ERROR, ResponseMessage.Message.CUSTOM_SERVER_ERROR), + serviceUnAvailable( + ResponseMessage.Key.SERVICE_UNAVAILABLE, ResponseMessage.Message.SERVICE_UNAVAILABLE), + dataAlreadyExist( + ResponseMessage.Key.DATA_ALREADY_EXIST, ResponseMessage.Message.DATA_ALREADY_EXIST), + notSupported(ResponseMessage.Key.NOT_SUPPORTED, ResponseMessage.Message.NOT_SUPPORTED), + functionalityMissing(ResponseMessage.Key.NOT_SUPPORTED, ResponseMessage.Message.NOT_SUPPORTED), + invalidElementInList( + ResponseMessage.Key.INVALID_ELEMENT_IN_LIST, ResponseMessage.Message.INVALID_ELEMENT_IN_LIST), + errorRateLimitExceeded( + ResponseMessage.Key.ERROR_RATE_LIMIT_EXCEEDED, + ResponseMessage.Message.ERROR_RATE_LIMIT_EXCEEDED), + invalidRequestTimeout( + ResponseMessage.Key.INVALID_REQUEST_TIMEOUT, ResponseMessage.Message.INVALID_REQUEST_TIMEOUT), + invalidObjectType( + ResponseMessage.Key.INVALID_OBJECT_TYPE, ResponseMessage.Message.INVALID_OBJECT_TYPE), + invalidPropertyError( + ResponseMessage.Key.INVALID_PROPERTY_ERROR, ResponseMessage.Message.INVALID_PROPERTY_ERROR), + invalidDateFormat( + ResponseMessage.Key.INVALID_DATE_FORMAT, ResponseMessage.Message.INVALID_DATE_FORMAT), + dateFormatError( + ResponseMessage.Key.DATE_FORMAT_ERRROR, ResponseMessage.Message.DATE_FORMAT_ERRROR), + unableToParseData( + ResponseMessage.Key.UNABLE_TO_PARSE_DATA, ResponseMessage.Message.UNABLE_TO_PARSE_DATA), + invalidJsonData(ResponseMessage.Key.INVALID_JSON, ResponseMessage.Message.INVALID_JSON), + noDataForConsumption(ResponseMessage.Key.NO_DATA, ResponseMessage.Message.NO_DATA), + invalidIdentifier( + ResponseMessage.Key.VALID_IDENTIFIER_ABSENSE, + ResponseMessage.Message.IDENTIFIER_VALIDATION_FAILED), + parameterMismatch( + ResponseMessage.Key.PARAMETER_MISMATCH, ResponseMessage.Message.PARAMETER_MISMATCH), + + // ------------------------------------------------------------------------- + // Authentication & Authorization + // ------------------------------------------------------------------------- + unAuthorized(ResponseMessage.Key.UNAUTHORIZED_USER, ResponseMessage.Message.UNAUTHORIZED_USER), + invalidUserCredentials( + ResponseMessage.Key.INVALID_USER_CREDENTIALS, + ResponseMessage.Message.INVALID_USER_CREDENTIALS), apiKeyRequired( ResponseMessage.Key.API_KEY_MISSING_ERROR, ResponseMessage.Message.API_KEY_MISSING_ERROR), invalidApiKey( ResponseMessage.Key.API_KEY_INVALID_ERROR, ResponseMessage.Message.API_KEY_INVALID_ERROR), - internalError(ResponseMessage.Key.INTERNAL_ERROR, ResponseMessage.Message.INTERNAL_ERROR), - dbInsertionError( - ResponseMessage.Key.DB_INSERTION_FAIL, ResponseMessage.Message.DB_INSERTION_FAIL), - dbUpdateError(ResponseMessage.Key.DB_UPDATE_FAIL, ResponseMessage.Message.DB_UPDATE_FAIL), - courseNameRequired( - ResponseMessage.Key.COURSE_NAME_MISSING, ResponseMessage.Message.COURSE_NAME_MISSING), - success(ResponseMessage.Key.SUCCESS_MESSAGE, ResponseMessage.Message.SUCCESS_MESSAGE), + authTokenRequired( + ResponseMessage.Key.AUTH_TOKEN_MISSING, ResponseMessage.Message.AUTH_TOKEN_MISSING), + invalidAuthToken( + ResponseMessage.Key.INVALID_AUTH_TOKEN, ResponseMessage.Message.INVALID_AUTH_TOKEN), sessionIdRequiredError( ResponseMessage.Key.SESSION_ID_MISSING, ResponseMessage.Message.SESSION_ID_MISSING), - courseIdRequiredError( - ResponseMessage.Key.COURSE_ID_MISSING, ResponseMessage.Message.COURSE_ID_MISSING), - contentIdRequiredError( - ResponseMessage.Key.CONTENT_ID_MISSING, ResponseMessage.Message.CONTENT_ID_MISSING), - versionRequiredError( - ResponseMessage.Key.VERSION_MISSING, ResponseMessage.Message.VERSION_MISSING), - courseVersionRequiredError( - ResponseMessage.Key.COURSE_VERSION_MISSING, ResponseMessage.Message.COURSE_VERSION_MISSING), - contentVersionRequiredError( - ResponseMessage.Key.CONTENT_VERSION_MISSING, ResponseMessage.Message.CONTENT_VERSION_MISSING), - courseDescriptionError( - ResponseMessage.Key.COURSE_DESCRIPTION_MISSING, - ResponseMessage.Message.COURSE_DESCRIPTION_MISSING), - courseTocUrlError( - ResponseMessage.Key.COURSE_TOCURL_MISSING, ResponseMessage.Message.COURSE_TOCURL_MISSING), - emailRequired(ResponseMessage.Key.EMAIL_MISSING, ResponseMessage.Message.EMAIL_MISSING), - emailFormatError(ResponseMessage.Key.EMAIL_FORMAT, ResponseMessage.Message.EMAIL_FORMAT), - urlFormatError(ResponseMessage.Key.URL_FORMAT_ERROR, ResponseMessage.Message.URL_FORMAT_ERROR), + invalidRole(ResponseMessage.Key.INVALID_ROLE, ResponseMessage.Message.INVALID_ROLE), + invalidSalt(ResponseMessage.Key.INVALID_SALT, ResponseMessage.Message.INVALID_SALT), + keyCloakDefaultError( + ResponseMessage.Key.KEY_CLOAK_DEFAULT_ERROR, ResponseMessage.Message.KEY_CLOAK_DEFAULT_ERROR), + otpVerificationFailed( + ResponseMessage.Key.OTP_VERIFICATION_FAILED, ResponseMessage.Message.OTP_VERIFICATION_FAILED), + errorInvalidOTP(ResponseMessage.Key.ERROR_INVALID_OTP, ResponseMessage.Message.ERROR_INVALID_OTP), + errorForbidden(ResponseMessage.Key.FORBIDDEN, ResponseMessage.Message.FORBIDDEN), + + // ------------------------------------------------------------------------- + // User Management + // ------------------------------------------------------------------------- + userNotFound(ResponseMessage.Key.USER_NOT_FOUND, ResponseMessage.Message.USER_NOT_FOUND), + userAlreadyExists( + ResponseMessage.Key.USER_ALREADY_EXISTS, ResponseMessage.Message.USER_ALREADY_EXISTS), + invalidUserId(ResponseMessage.Key.INVALID_USER_ID, ResponseMessage.Message.INVALID_USER_ID), + userIdRequired(ResponseMessage.Key.USERID_MISSING, ResponseMessage.Message.USERID_MISSING), + userNameRequired(ResponseMessage.Key.USERNAME_MISSING, ResponseMessage.Message.USERNAME_MISSING), firstNameRequired( ResponseMessage.Key.FIRST_NAME_MISSING, ResponseMessage.Message.FIRST_NAME_MISSING), - languageRequired(ResponseMessage.Key.LANGUAGE_MISSING, ResponseMessage.Message.LANGUAGE_MISSING), + emailRequired(ResponseMessage.Key.EMAIL_MISSING, ResponseMessage.Message.EMAIL_MISSING), + phoneNoRequired( + ResponseMessage.Key.PHONE_NO_REQUIRED_ERROR, ResponseMessage.Message.PHONE_NO_REQUIRED_ERROR), passwordRequired(ResponseMessage.Key.PASSWORD_MISSING, ResponseMessage.Message.PASSWORD_MISSING), + invalidPassword(ResponseMessage.Key.INVALID_PASSWORD, ResponseMessage.Message.INVALID_PASSWORD), passwordMinLengthError( ResponseMessage.Key.PASSWORD_MIN_LENGHT, ResponseMessage.Message.PASSWORD_MIN_LENGHT), passwordMaxLengthError( ResponseMessage.Key.PASSWORD_MAX_LENGHT, ResponseMessage.Message.PASSWORD_MAX_LENGHT), - organisationIdRequiredError( - ResponseMessage.Key.ORGANISATION_ID_MISSING, ResponseMessage.Message.ORGANISATION_ID_MISSING), - sourceAndExternalIdValidationError( - ResponseMessage.Key.REQUIRED_DATA_ORG_MISSING, - ResponseMessage.Message.REQUIRED_DATA_ORG_MISSING), - organisationNameRequired( - ResponseMessage.Key.ORGANISATION_NAME_MISSING, - ResponseMessage.Message.ORGANISATION_NAME_MISSING), - channelUniquenessInvalid( - ResponseMessage.Key.CHANNEL_SHOULD_BE_UNIQUE, - ResponseMessage.Message.CHANNEL_SHOULD_BE_UNIQUE), - errorDuplicateEntry( - ResponseMessage.Key.ERROR_DUPLICATE_ENTRY, ResponseMessage.Message.ERROR_DUPLICATE_ENTRY), - unableToConnect( - ResponseMessage.Key.UNABLE_TO_CONNECT_TO_EKSTEP, - ResponseMessage.Message.UNABLE_TO_CONNECT_TO_EKSTEP), - unableToConnectToES( - ResponseMessage.Key.UNABLE_TO_CONNECT_TO_ES, ResponseMessage.Message.UNABLE_TO_CONNECT_TO_ES), - unableToParseData( - ResponseMessage.Key.UNABLE_TO_PARSE_DATA, ResponseMessage.Message.UNABLE_TO_PARSE_DATA), - invalidJsonData(ResponseMessage.Key.INVALID_JSON, ResponseMessage.Message.INVALID_JSON), - invalidOrgData(ResponseMessage.Key.INVALID_ORG_DATA, ResponseMessage.Message.INVALID_ORG_DATA), - invalidRootOrganisationId( - ResponseMessage.Key.INVALID_ROOT_ORGANIZATION, - ResponseMessage.Message.INVALID_ROOT_ORGANIZATION), - invalidParentId( - ResponseMessage.Key.INVALID_PARENT_ORGANIZATION_ID, - ResponseMessage.Message.INVALID_PARENT_ORGANIZATION_ID), - cyclicValidationError( - ResponseMessage.Key.CYCLIC_VALIDATION_FAILURE, - ResponseMessage.Message.CYCLIC_VALIDATION_FAILURE), - invalidUsrData(ResponseMessage.Key.INVALID_USR_DATA, ResponseMessage.Message.INVALID_USR_DATA), - usrValidationError( - ResponseMessage.Key.USR_DATA_VALIDATION_ERROR, - ResponseMessage.Message.USR_DATA_VALIDATION_ERROR), - errorInvalidOTP(ResponseMessage.Key.ERROR_INVALID_OTP, ResponseMessage.Message.ERROR_INVALID_OTP), - enrollmentStartDateRequiredError( - ResponseMessage.Key.ENROLLMENT_START_DATE_MISSING, - ResponseMessage.Message.ENROLLMENT_START_DATE_MISSING), - courseDurationRequiredError( - ResponseMessage.Key.COURSE_DURATION_MISSING, ResponseMessage.Message.COURSE_DURATION_MISSING), - loginTypeRequired( - ResponseMessage.Key.LOGIN_TYPE_MISSING, ResponseMessage.Message.LOGIN_TYPE_MISSING), - emailAlreadyExistError(ResponseMessage.Key.EMAIL_IN_USE, ResponseMessage.Message.EMAIL_IN_USE), - invalidCredentials( - ResponseMessage.Key.INVALID_CREDENTIAL, ResponseMessage.Message.INVALID_CREDENTIAL), - userNameRequired(ResponseMessage.Key.USERNAME_MISSING, ResponseMessage.Message.USERNAME_MISSING), userNameAlreadyExistError( ResponseMessage.Key.USERNAME_IN_USE, ResponseMessage.Message.USERNAME_IN_USE), - userIdRequired(ResponseMessage.Key.USERID_MISSING, ResponseMessage.Message.USERID_MISSING), - roleRequired(ResponseMessage.Key.ROLE_MISSING, ResponseMessage.Message.ROLE_MISSING), - msgIdRequiredError( - ResponseMessage.Key.MESSAGE_ID_MISSING, ResponseMessage.Message.MESSAGE_ID_MISSING), - userNameCanntBeUpdated( - ResponseMessage.Key.USERNAME_CANNOT_BE_UPDATED, - ResponseMessage.Message.USERNAME_CANNOT_BE_UPDATED), - authTokenRequired( - ResponseMessage.Key.AUTH_TOKEN_MISSING, ResponseMessage.Message.AUTH_TOKEN_MISSING), - invalidAuthToken( - ResponseMessage.Key.INVALID_AUTH_TOKEN, ResponseMessage.Message.INVALID_AUTH_TOKEN), - timeStampRequired( - ResponseMessage.Key.TIMESTAMP_REQUIRED, ResponseMessage.Message.TIMESTAMP_REQUIRED), - publishedCourseCanNotBeUpdated( - ResponseMessage.Key.PUBLISHED_COURSE_CAN_NOT_UPDATED, - ResponseMessage.Message.PUBLISHED_COURSE_CAN_NOT_UPDATED), - sourceRequired(ResponseMessage.Key.SOURCE_MISSING, ResponseMessage.Message.SOURCE_MISSING), - sectionNameRequired( - ResponseMessage.Key.SECTION_NAME_MISSING, ResponseMessage.Message.SECTION_NAME_MISSING), - sectionDataTypeRequired( - ResponseMessage.Key.SECTION_DATA_TYPE_MISSING, - ResponseMessage.Message.SECTION_DATA_TYPE_MISSING), - sectionIdRequired( - ResponseMessage.Key.SECTION_ID_REQUIRED, ResponseMessage.Message.SECTION_ID_REQUIRED), - pageNameRequired( - ResponseMessage.Key.PAGE_NAME_REQUIRED, ResponseMessage.Message.PAGE_NAME_REQUIRED), - pageIdRequired(ResponseMessage.Key.PAGE_ID_REQUIRED, ResponseMessage.Message.PAGE_ID_REQUIRED), - invaidConfiguration( - ResponseMessage.Key.INVALID_CONFIGURATION, ResponseMessage.Message.INVALID_CONFIGURATION), - assessmentItemIdRequired( - ResponseMessage.Key.ASSESSMENT_ITEM_ID_REQUIRED, - ResponseMessage.Message.ASSESSMENT_ITEM_ID_REQUIRED), - assessmentTypeRequired( - ResponseMessage.Key.ASSESSMENT_TYPE_REQUIRED, - ResponseMessage.Message.ASSESSMENT_TYPE_REQUIRED), - assessmentAttemptDateRequired( - ResponseMessage.Key.ATTEMPTED_DATE_REQUIRED, ResponseMessage.Message.ATTEMPTED_DATE_REQUIRED), - assessmentAnswersRequired( - ResponseMessage.Key.ATTEMPTED_ANSWERS_REQUIRED, - ResponseMessage.Message.ATTEMPTED_ANSWERS_REQUIRED), - assessmentmaxScoreRequired( - ResponseMessage.Key.MAX_SCORE_REQUIRED, ResponseMessage.Message.MAX_SCORE_REQUIRED), - statusCanntBeUpdated( - ResponseMessage.Key.STATUS_CANNOT_BE_UPDATED, - ResponseMessage.Message.STATUS_CANNOT_BE_UPDATED), - attemptIdRequired( - ResponseMessage.Key.ATTEMPT_ID_MISSING_ERROR, - ResponseMessage.Message.ATTEMPT_ID_MISSING_ERROR), - emailANDUserNameAlreadyExistError( - ResponseMessage.Key.USERNAME_EMAIL_IN_USE, ResponseMessage.Message.USERNAME_EMAIL_IN_USE), - keyCloakDefaultError( - ResponseMessage.Key.KEY_CLOAK_DEFAULT_ERROR, ResponseMessage.Message.KEY_CLOAK_DEFAULT_ERROR), + emailAlreadyExistError(ResponseMessage.Key.EMAIL_IN_USE, ResponseMessage.Message.EMAIL_IN_USE), + PhoneNumberInUse( + ResponseMessage.Key.PHONE_ALREADY_IN_USE, ResponseMessage.Message.PHONE_ALREADY_IN_USE), + userAccountlocked( + ResponseMessage.Key.USER_ACCOUNT_BLOCKED, ResponseMessage.Message.USER_ACCOUNT_BLOCKED), + userAlreadyActive( + ResponseMessage.Key.USER_ALREADY_ACTIVE, ResponseMessage.Message.USER_ALREADY_ACTIVE), + userAlreadyInactive( + ResponseMessage.Key.USER_ALREADY_INACTIVE, ResponseMessage.Message.USER_ALREADY_INACTIVE), userRegUnSuccessfull( ResponseMessage.Key.USER_REG_UNSUCCESSFUL, ResponseMessage.Message.USER_REG_UNSUCCESSFUL), userUpdationUnSuccessfull( ResponseMessage.Key.USER_UPDATE_UNSUCCESSFUL, ResponseMessage.Message.USER_UPDATE_UNSUCCESSFUL), - loginTypeError(ResponseMessage.Key.LOGIN_TYPE_ERROR, ResponseMessage.Message.LOGIN_TYPE_ERROR), - invalidOrgId(ResponseMessage.Key.INVALID_ORG_ID, ResponseMessage.Key.INVALID_ORG_ID), - invalidOrgStatus(ResponseMessage.Key.INVALID_ORG_STATUS, ResponseMessage.Key.INVALID_ORG_STATUS), - invalidOrgStatusTransition( - ResponseMessage.Key.INVALID_ORG_STATUS_TRANSITION, - ResponseMessage.Key.INVALID_ORG_STATUS_TRANSITION), - addressRequired( - ResponseMessage.Key.ADDRESS_REQUIRED_ERROR, ResponseMessage.Message.ADDRESS_REQUIRED_ERROR), - educationRequired( - ResponseMessage.Key.EDUCATION_REQUIRED_ERROR, - ResponseMessage.Message.EDUCATION_REQUIRED_ERROR), - phoneNoRequired( - ResponseMessage.Key.PHONE_NO_REQUIRED_ERROR, ResponseMessage.Message.PHONE_NO_REQUIRED_ERROR), - jobDetailsRequired( - ResponseMessage.Key.JOBDETAILS_REQUIRED_ERROR, - ResponseMessage.Message.JOBDETAILS_REQUIRED_ERROR), - dataAlreadyExist( - ResponseMessage.Key.DATA_ALREADY_EXIST, ResponseMessage.Message.DATA_ALREADY_EXIST), - invalidData(ResponseMessage.Key.INVALID_DATA, ResponseMessage.Message.INVALID_DATA), - invalidCourseId(ResponseMessage.Key.INVALID_COURSE_ID, ResponseMessage.Message.INVALID_COURSE_ID), - orgIdRequired(ResponseMessage.Key.ORG_ID_MISSING, ResponseMessage.Message.ORG_ID_MISSING), - actorConnectionError( - ResponseMessage.Key.ACTOR_CONNECTION_ERROR, ResponseMessage.Message.ACTOR_CONNECTION_ERROR), - userAlreadyExists( - ResponseMessage.Key.USER_ALREADY_EXISTS, ResponseMessage.Message.USER_ALREADY_EXISTS), - invalidUserId(ResponseMessage.Key.INVALID_USER_ID, ResponseMessage.Message.INVALID_USER_ID), - loginIdRequired(ResponseMessage.Key.LOGIN_ID_MISSING, ResponseMessage.Message.LOGIN_ID_MISSING), - contentStatusRequired( - ResponseMessage.Key.CONTENT_STATUS_MISSING_ERROR, - ResponseMessage.Message.CONTENT_STATUS_MISSING_ERROR), - esError(ResponseMessage.Key.ES_ERROR, ResponseMessage.Message.ES_ERROR), - invalidPeriod(ResponseMessage.Key.INVALID_PERIOD, ResponseMessage.Message.INVALID_PERIOD), - userNotFound(ResponseMessage.Key.USER_NOT_FOUND, ResponseMessage.Message.USER_NOT_FOUND), - idRequired(ResponseMessage.Key.ID_REQUIRED_ERROR, ResponseMessage.Message.ID_REQUIRED_ERROR), - dataTypeError(ResponseMessage.Key.DATA_TYPE_ERROR, ResponseMessage.Message.DATA_TYPE_ERROR), - errorAttributeConflict( - ResponseMessage.Key.ERROR_ATTRIBUTE_CONFLICT, - ResponseMessage.Message.ERROR_ATTRIBUTE_CONFLICT), + userPhoneUpdateFailed( + ResponseMessage.Key.USER_PHONE_UPDATE_FAILED, + ResponseMessage.Message.USER_PHONE_UPDATE_FAILED), + userMigrationFiled( + ResponseMessage.Key.USER_MIGRATION_FAILED, ResponseMessage.Message.USER_MIGRATION_FAILED), + userDataEncryptionError( + ResponseMessage.Key.USER_DATA_ENCRYPTION_ERROR, + ResponseMessage.Message.USER_DATA_ENCRYPTION_ERROR), + invalidUserExternalId( + ResponseMessage.Key.INVALID_EXT_USER_ID, ResponseMessage.Message.INVALID_EXT_USER_ID), + externalIdNotFound( + ResponseMessage.Key.EXTERNALID_NOT_FOUND, ResponseMessage.Message.EXTERNALID_NOT_FOUND), + externalIdAssignedToOtherUser( + ResponseMessage.Key.EXTERNALID_ASSIGNED_TO_OTHER_USER, + ResponseMessage.Message.EXTERNALID_ASSIGNED_TO_OTHER_USER), + duplicateExternalIds( + ResponseMessage.Key.DUPLICATE_EXTERNAL_IDS, ResponseMessage.Message.DUPLICATE_EXTERNAL_IDS), + emailANDUserNameAlreadyExistError( + ResponseMessage.Key.USERNAME_EMAIL_IN_USE, ResponseMessage.Message.USERNAME_EMAIL_IN_USE), + userNameCanntBeUpdated( + ResponseMessage.Key.USERNAME_CANNOT_BE_UPDATED, + ResponseMessage.Message.USERNAME_CANNOT_BE_UPDATED), + newPasswordRequired( + ResponseMessage.Key.CONFIIRM_PASSWORD_MISSING, + ResponseMessage.Message.CONFIIRM_PASSWORD_MISSING), + newPasswordEmpty( + ResponseMessage.Key.CONFIIRM_PASSWORD_EMPTY, ResponseMessage.Message.CONFIIRM_PASSWORD_EMPTY), + samePasswordError( + ResponseMessage.Key.SAME_PASSWORD_ERROR, ResponseMessage.Message.SAME_PASSWORD_ERROR), + emailVerifiedError( + ResponseMessage.Key.EMAIL_VERIFY_ERROR, ResponseMessage.Message.EMAIL_VERIFY_ERROR), + phoneVerifiedError( + ResponseMessage.Key.PHONE_VERIFY_ERROR, ResponseMessage.Message.PHONE_VERIFY_ERROR), + loginTypeRequired( + ResponseMessage.Key.LOGIN_TYPE_MISSING, ResponseMessage.Message.LOGIN_TYPE_MISSING), + loginTypeError(ResponseMessage.Key.LOGIN_TYPE_ERROR, ResponseMessage.Message.LOGIN_TYPE_ERROR), + loginIdRequired(ResponseMessage.Key.LOGIN_ID_MISSING, ResponseMessage.Message.LOGIN_ID_MISSING), + userNameOrUserIdRequired( + ResponseMessage.Key.USERNAME_USERID_MISSING, ResponseMessage.Message.USERNAME_USERID_MISSING), + usernameOrUserIdError( + ResponseMessage.Key.USER_NAME_OR_ID_ERROR, ResponseMessage.Message.USER_NAME_OR_ID_ERROR), + rolesRequired(ResponseMessage.Key.ROLES_MISSING, ResponseMessage.Message.ROLES_MISSING), + roleRequired(ResponseMessage.Key.ROLE_MISSING, ResponseMessage.Message.ROLE_MISSING), + emptyRolesProvided( + ResponseMessage.Key.EMPTY_ROLES_PROVIDED, ResponseMessage.Message.EMPTY_ROLES_PROVIDED), + visibilityInvalid( + ResponseMessage.Key.INVALID_VISIBILITY_REQUEST, + ResponseMessage.Message.INVALID_VISIBILITY_REQUEST), + addressRequired( + ResponseMessage.Key.ADDRESS_REQUIRED_ERROR, ResponseMessage.Message.ADDRESS_REQUIRED_ERROR), + educationRequired( + ResponseMessage.Key.EDUCATION_REQUIRED_ERROR, + ResponseMessage.Message.EDUCATION_REQUIRED_ERROR), + jobDetailsRequired( + ResponseMessage.Key.JOBDETAILS_REQUIRED_ERROR, + ResponseMessage.Message.JOBDETAILS_REQUIRED_ERROR), addressError(ResponseMessage.Key.ADDRESS_ERROR, ResponseMessage.Message.ADDRESS_ERROR), addressTypeError( ResponseMessage.Key.ADDRESS_TYPE_ERROR, ResponseMessage.Message.ADDRESS_TYPE_ERROR), educationNameError( ResponseMessage.Key.NAME_OF_INSTITUTION_ERROR, ResponseMessage.Message.NAME_OF_INSTITUTION_ERROR), - jobNameError(ResponseMessage.Key.JOB_NAME_ERROR, ResponseMessage.Message.JOB_NAME_ERROR), educationDegreeError( ResponseMessage.Key.EDUCATION_DEGREE_ERROR, ResponseMessage.Message.EDUCATION_DEGREE_ERROR), + jobNameError(ResponseMessage.Key.JOB_NAME_ERROR, ResponseMessage.Message.JOB_NAME_ERROR), + invalidUsrData(ResponseMessage.Key.INVALID_USR_DATA, ResponseMessage.Message.INVALID_USR_DATA), + usrValidationError( + ResponseMessage.Key.USR_DATA_VALIDATION_ERROR, + ResponseMessage.Message.USR_DATA_VALIDATION_ERROR), + invalidUsrOrgData( + ResponseMessage.Key.INVALID_USR_ORG_DATA, ResponseMessage.Message.INVALID_USR_ORG_DATA), + userNotAssociatedToOrg( + ResponseMessage.Key.USER_NOT_BELONGS_TO_ANY_ORG, + ResponseMessage.Message.USER_NOT_BELONGS_TO_ANY_ORG), + userOrgAssociationError( + ResponseMessage.Key.USER_ORG_ASSOCIATION_ERROR, + ResponseMessage.Message.USER_ORG_ASSOCIATION_ERROR), + errorUserHasNotCreatedAnyCourse( + ResponseMessage.Key.ERROR_USER_HAS_NOT_CREATED_ANY_COURSE, + ResponseMessage.Message.ERROR_USER_HAS_NOT_CREATED_ANY_COURSE), + userNotAssociatedToRootOrg( + ResponseMessage.Key.USER_NOT_ASSOCIATED_TO_ROOT_ORG, + ResponseMessage.Message.USER_NOT_ASSOCIATED_TO_ROOT_ORG), + invalidCredentials( + ResponseMessage.Key.INVALID_CREDENTIAL, ResponseMessage.Message.INVALID_CREDENTIAL), + emailFormatError(ResponseMessage.Key.EMAIL_FORMAT, ResponseMessage.Message.EMAIL_FORMAT), + urlFormatError(ResponseMessage.Key.URL_FORMAT_ERROR, ResponseMessage.Message.URL_FORMAT_ERROR), + languageRequired(ResponseMessage.Key.LANGUAGE_MISSING, ResponseMessage.Message.LANGUAGE_MISSING), + timeStampRequired( + ResponseMessage.Key.TIMESTAMP_REQUIRED, ResponseMessage.Message.TIMESTAMP_REQUIRED), + phoneNoFormatError( + ResponseMessage.Key.INVALID_PHONE_NO_FORMAT, ResponseMessage.Message.INVALID_PHONE_NO_FORMAT), + invalidPhoneNumber( + ResponseMessage.Key.INVALID_PHONE_NUMBER, ResponseMessage.Message.INVALID_PHONE_NUMBER), + invalidCountryCode( + ResponseMessage.Key.INVALID_COUNTRY_CODE, ResponseMessage.Message.INVALID_COUNTRY_CODE), + emailorPhoneRequired( + ResponseMessage.Key.EMAIL_OR_PHONE_MISSING, ResponseMessage.Message.EMAIL_OR_PHONE_MISSING), + accountNotFound(ResponseMessage.Key.ACCOUNT_NOT_FOUND, ResponseMessage.Message.ACCOUNT_NOT_FOUND), + fromAccountIdRequired( + ResponseMessage.Key.FROM_ACCOUNT_ID_MISSING, ResponseMessage.Message.FROM_ACCOUNT_ID_MISSING), + toAccountIdRequired( + ResponseMessage.Key.TO_ACCOUNT_ID_MISSING, ResponseMessage.Message.TO_ACCOUNT_ID_MISSING), + fromAccountIdNotExists( + ResponseMessage.Key.FROM_ACCOUNT_ID_NOT_EXISTS, + ResponseMessage.Message.FROM_ACCOUNT_ID_NOT_EXISTS), + + // ------------------------------------------------------------------------- + // Organization Management + // ------------------------------------------------------------------------- + orgDoesNotExist(ResponseMessage.Key.ORG_NOT_EXIST, ResponseMessage.Message.ORG_NOT_EXIST), + invalidOrgData(ResponseMessage.Key.INVALID_ORG_DATA, ResponseMessage.Message.INVALID_ORG_DATA), + organisationIdRequiredError( + ResponseMessage.Key.ORGANISATION_ID_MISSING, ResponseMessage.Message.ORGANISATION_ID_MISSING), + orgIdRequired(ResponseMessage.Key.ORG_ID_MISSING, ResponseMessage.Message.ORG_ID_MISSING), + organisationNameRequired( + ResponseMessage.Key.ORGANISATION_NAME_MISSING, + ResponseMessage.Message.ORGANISATION_NAME_MISSING), organisationNameError( ResponseMessage.Key.NAME_OF_ORGANISATION_ERROR, ResponseMessage.Message.NAME_OF_ORGANISATION_ERROR), - rolesRequired(ResponseMessage.Key.ROLES_MISSING, ResponseMessage.Message.ROLES_MISSING), - emptyRolesProvided( - ResponseMessage.Key.EMPTY_ROLES_PROVIDED, ResponseMessage.Message.EMPTY_ROLES_PROVIDED), - invalidDateFormat( - ResponseMessage.Key.INVALID_DATE_FORMAT, ResponseMessage.Message.INVALID_DATE_FORMAT), - sourceAndExternalIdAlreadyExist( - ResponseMessage.Key.SRC_EXTERNAL_ID_ALREADY_EXIST, - ResponseMessage.Message.SRC_EXTERNAL_ID_ALREADY_EXIST), - userAlreadyEnrolledCourse( - ResponseMessage.Key.USER_ALREADY_ENROLLED_COURSE, - ResponseMessage.Message.USER_ALREADY_ENROLLED_COURSE), - userNotEnrolledCourse( - ResponseMessage.Key.USER_NOT_ENROLLED_COURSE, - ResponseMessage.Message.USER_NOT_ENROLLED_COURSE), + rootOrgIdRequired( + ResponseMessage.Key.ROOT_ORG_ID_REQUIRED, ResponseMessage.Message.ROOT_ORG_ID_REQUIRED), + sourceAndExternalIdValidationError( + ResponseMessage.Key.REQUIRED_DATA_ORG_MISSING, + ResponseMessage.Message.REQUIRED_DATA_ORG_MISSING), + invalidRootOrganisationId( + ResponseMessage.Key.INVALID_ROOT_ORGANIZATION, + ResponseMessage.Message.INVALID_ROOT_ORGANIZATION), + invalidParentId( + ResponseMessage.Key.INVALID_PARENT_ORGANIZATION_ID, + ResponseMessage.Message.INVALID_PARENT_ORGANIZATION_ID), + parentCodeAndIdValidationError( + ResponseMessage.Key.PARENT_CODE_AND_PARENT_ID_MISSING, + ResponseMessage.Message.PARENT_CODE_AND_PARENT_ID_MISSING), + invalidOrgId(ResponseMessage.Key.INVALID_ORG_ID, ResponseMessage.Key.INVALID_ORG_ID), + invalidOrgStatus(ResponseMessage.Key.INVALID_ORG_STATUS, ResponseMessage.Key.INVALID_ORG_STATUS), + invalidOrgStatusTransition( + ResponseMessage.Key.INVALID_ORG_STATUS_TRANSITION, + ResponseMessage.Key.INVALID_ORG_STATUS_TRANSITION), + orgTypeMandatory( + ResponseMessage.Key.ORG_TYPE_MANDATORY, ResponseMessage.Message.ORG_TYPE_MANDATORY), + orgTypeAlreadyExist( + ResponseMessage.Key.ORG_TYPE_ALREADY_EXIST, ResponseMessage.Message.ORG_TYPE_ALREADY_EXIST), + orgTypeIdRequired( + ResponseMessage.Key.ORG_TYPE_ID_REQUIRED_ERROR, + ResponseMessage.Message.ORG_TYPE_ID_REQUIRED_ERROR), + invalidOrgTypeId( + ResponseMessage.Key.INVALID_ORG_TYPE_ID_ERROR, + ResponseMessage.Message.INVALID_ORG_TYPE_ID_ERROR), + invalidOrgType( + ResponseMessage.Key.INVALID_ORG_TYPE_ERROR, ResponseMessage.Message.INVALID_ORG_TYPE_ERROR), + errorInactiveOrg( + ResponseMessage.Key.ERROR_INACTIVE_ORG, ResponseMessage.Message.ERROR_INACTIVE_ORG), + errorNoRootOrgAssociated( + ResponseMessage.Key.ERROR_NO_ROOT_ORG_ASSOCIATED, + ResponseMessage.Message.ERROR_NO_ROOT_ORG_ASSOCIATED), + errorInactiveCustodianOrg( + ResponseMessage.Key.ERROR_INACTIVE_CUSTODIAN_ORG, + ResponseMessage.Message.ERROR_INACTIVE_CUSTODIAN_ORG), + rootOrgAssociationError( + ResponseMessage.Key.ROOT_ORG_ASSOCIATION_ERROR, + ResponseMessage.Message.ROOT_ORG_ASSOCIATION_ERROR), + invalidRootOrgData( + ResponseMessage.Key.INVALID_ROOT_ORG_DATA, ResponseMessage.Message.INVALID_ROOT_ORG_DATA), + channelUniquenessInvalid( + ResponseMessage.Key.CHANNEL_SHOULD_BE_UNIQUE, + ResponseMessage.Message.CHANNEL_SHOULD_BE_UNIQUE), + invalidChannel(ResponseMessage.Key.INVALID_CHANNEL, ResponseMessage.Message.INVALID_CHANNEL), + channelRegFailed( + ResponseMessage.Key.CHANNEL_REG_FAILED, ResponseMessage.Message.CHANNEL_REG_FAILED), + slugIsNotUnique( + ResponseMessage.Key.SLUG_IS_NOT_UNIQUE, ResponseMessage.Message.SLUG_IS_NOT_UNIQUE), + slugRequired(ResponseMessage.Key.SLUG_REQUIRED, ResponseMessage.Message.SLUG_REQUIRED), + conflictingOrgLocations( + ResponseMessage.Key.CONFLICTING_ORG_LOCATIONS, + ResponseMessage.Message.CONFLICTING_ORG_LOCATIONS), + invalidLocationId( + ResponseMessage.Key.INVALID_LOCATION_ID, ResponseMessage.Message.INVALID_LOCATION_ID), + locationIdRequired( + ResponseMessage.Key.LOCATION_ID_REQUIRED, ResponseMessage.Message.LOCATION_ID_REQUIRED), + locationTypeRequired( + ResponseMessage.Key.LOCATION_TYPE_REQUIRED, ResponseMessage.Message.LOCATION_TYPE_REQUIRED), + invalidRequestDataForLocation( + ResponseMessage.Key.INVALID_REQUEST_DATA_FOR_LOCATION, + ResponseMessage.Message.INVALID_REQUEST_DATA_FOR_LOCATION), + invalidLocationDeleteRequest( + ResponseMessage.Key.INVALID_LOCATION_DELETE_REQUEST, + ResponseMessage.Message.INVALID_LOCATION_DELETE_REQUEST), + locationTypeConflicts( + ResponseMessage.Key.LOCATION_TYPE_CONFLICTS, ResponseMessage.Message.LOCATION_TYPE_CONFLICTS), + parentNotAllowed( + ResponseMessage.Key.PARENT_NOT_ALLOWED, ResponseMessage.Message.PARENT_NOT_ALLOWED), + invalidHashTagId( + ResponseMessage.Key.INVALID_HASHTAG_ID, ResponseMessage.Message.INVALID_HASHTAG_ID), + + // ------------------------------------------------------------------------- + // Course & Batch Management + // ------------------------------------------------------------------------- + courseIdRequired( + ResponseMessage.Key.COURSE_ID_MISSING_ERROR, ResponseMessage.Message.COURSE_ID_MISSING_ERROR), + courseIdRequiredError( + ResponseMessage.Key.COURSE_ID_MISSING, ResponseMessage.Message.COURSE_ID_MISSING), + invalidCourseId(ResponseMessage.Key.INVALID_COURSE_ID, ResponseMessage.Message.INVALID_COURSE_ID), + courseNameRequired( + ResponseMessage.Key.COURSE_NAME_MISSING, ResponseMessage.Message.COURSE_NAME_MISSING), + courseDescriptionError( + ResponseMessage.Key.COURSE_DESCRIPTION_MISSING, + ResponseMessage.Message.COURSE_DESCRIPTION_MISSING), + courseVersionRequiredError( + ResponseMessage.Key.COURSE_VERSION_MISSING, ResponseMessage.Message.COURSE_VERSION_MISSING), + courseDurationRequiredError( + ResponseMessage.Key.COURSE_DURATION_MISSING, ResponseMessage.Message.COURSE_DURATION_MISSING), + courseTocUrlError( + ResponseMessage.Key.COURSE_TOCURL_MISSING, ResponseMessage.Message.COURSE_TOCURL_MISSING), + courseCreatedForIsNull( + ResponseMessage.Key.COURSE_CREATED_FOR_NULL, ResponseMessage.Message.COURSE_CREATED_FOR_NULL), + courseBatchIdRequired( + ResponseMessage.Key.COURSE_BATCH_ID_MISSING, ResponseMessage.Message.COURSE_BATCH_ID_MISSING), + invalidCourseBatchId( + ResponseMessage.Key.INVALID_COURSE_BATCH_ID, ResponseMessage.Message.INVALID_COURSE_BATCH_ID), courseBatchAlreadyCompleted( ResponseMessage.Key.COURSE_BATCH_ALREADY_COMPLETED, ResponseMessage.Message.COURSE_BATCH_ALREADY_COMPLETED), courseBatchEnrollmentDateEnded( ResponseMessage.Key.COURSE_BATCH_ENROLLMENT_DATE_ENDED, ResponseMessage.Message.COURSE_BATCH_ENROLLMENT_DATE_ENDED), - userAlreadyCompletedCourse( - ResponseMessage.Key.USER_ALREADY_COMPLETED_COURSE, - ResponseMessage.Message.USER_ALREADY_COMPLETED_COURSE), - pageAlreadyExist( - ResponseMessage.Key.PAGE_ALREADY_EXIST, ResponseMessage.Message.PAGE_ALREADY_EXIST), - contentTypeRequiredError( - ResponseMessage.Key.CONTENT_TYPE_ERROR, ResponseMessage.Message.CONTENT_TYPE_ERROR), - invalidPropertyError( - ResponseMessage.Key.INVALID_PROPERTY_ERROR, ResponseMessage.Message.INVALID_PROPERTY_ERROR), - usernameOrUserIdError( - ResponseMessage.Key.USER_NAME_OR_ID_ERROR, ResponseMessage.Message.USER_NAME_OR_ID_ERROR), - emailVerifiedError( - ResponseMessage.Key.EMAIL_VERIFY_ERROR, ResponseMessage.Message.EMAIL_VERIFY_ERROR), - phoneVerifiedError( - ResponseMessage.Key.PHONE_VERIFY_ERROR, ResponseMessage.Message.PHONE_VERIFY_ERROR), - bulkUserUploadError( - ResponseMessage.Key.BULK_USER_UPLOAD_ERROR, ResponseMessage.Message.BULK_USER_UPLOAD_ERROR), - dataSizeError(ResponseMessage.Key.DATA_SIZE_EXCEEDED, ResponseMessage.Message.DATA_SIZE_EXCEEDED), - InvalidColumnError( - ResponseMessage.Key.INVALID_COLUMN_NAME, ResponseMessage.Message.INVALID_COLUMN_NAME), - userAccountlocked( - ResponseMessage.Key.USER_ACCOUNT_BLOCKED, ResponseMessage.Message.USER_ACCOUNT_BLOCKED), - userAlreadyActive( - ResponseMessage.Key.USER_ALREADY_ACTIVE, ResponseMessage.Message.USER_ALREADY_ACTIVE), - userAlreadyInactive( - ResponseMessage.Key.USER_ALREADY_INACTIVE, ResponseMessage.Message.USER_ALREADY_INACTIVE), - enrolmentTypeRequired( - ResponseMessage.Key.ENROLMENT_TYPE_REQUIRED, ResponseMessage.Message.ENROLMENT_TYPE_REQUIRED), - enrolmentIncorrectValue( - ResponseMessage.Key.ENROLMENT_TYPE_VALUE_ERROR, - ResponseMessage.Message.ENROLMENT_TYPE_VALUE_ERROR), courseBatchStartDateRequired( ResponseMessage.Key.COURSE_BATCH_START_DATE_REQUIRED, ResponseMessage.Message.COURSE_BATCH_START_DATE_REQUIRED), courseBatchStartDateError( ResponseMessage.Key.COURSE_BATCH_START_DATE_INVALID, ResponseMessage.Message.COURSE_BATCH_START_DATE_INVALID), - dateFormatError( - ResponseMessage.Key.DATE_FORMAT_ERRROR, ResponseMessage.Message.DATE_FORMAT_ERRROR), - endDateError(ResponseMessage.Key.END_DATE_ERROR, ResponseMessage.Message.END_DATE_ERROR), - enrollmentEndDateStartError( - ResponseMessage.Key.ENROLLMENT_END_DATE_START_ERROR, - ResponseMessage.Message.ENROLLMENT_END_DATE_START_ERROR), + courseBatchEndDateError( + ResponseMessage.Key.COURSE_BATCH_END_DATE_ERROR, + ResponseMessage.Message.COURSE_BATCH_END_DATE_ERROR), + BatchCloseError( + ResponseMessage.Key.COURSE_BATCH_IS_CLOSED_ERROR, + ResponseMessage.Message.COURSE_BATCH_IS_CLOSED_ERROR), + courseBatchStartPassedDateError( + ResponseMessage.Key.COURSE_BATCH_START_PASSED_DATE_INVALID, + ResponseMessage.Message.COURSE_BATCH_START_PASSED_DATE_INVALID), + invalidBatchStartDateError( + ResponseMessage.Key.INVALID_BATCH_START_DATE_ERROR, + ResponseMessage.Message.INVALID_BATCH_START_DATE_ERROR), + invalidBatchEndDateError( + ResponseMessage.Key.INVALID_BATCH_END_DATE_ERROR, + ResponseMessage.Message.INVALID_BATCH_END_DATE_ERROR), + multipleCoursesNotAllowedForBatch( + ResponseMessage.Key.MULTIPLE_COURSES_FOR_BATCH, + ResponseMessage.Message.MULTIPLE_COURSES_FOR_BATCH), + invalidCourseCreatorId( + ResponseMessage.Key.INVALID_COURSE_CREATOR_ID, + ResponseMessage.Message.INVALID_COURSE_CREATOR_ID), + enrollmentStartDateRequiredError( + ResponseMessage.Key.ENROLLMENT_START_DATE_MISSING, + ResponseMessage.Message.ENROLLMENT_START_DATE_MISSING), + enrollmentEndDateStartError( + ResponseMessage.Key.ENROLLMENT_END_DATE_START_ERROR, + ResponseMessage.Message.ENROLLMENT_END_DATE_START_ERROR), enrollmentEndDateEndError( ResponseMessage.Key.ENROLLMENT_END_DATE_END_ERROR, ResponseMessage.Message.ENROLLMENT_END_DATE_END_ERROR), enrollmentEndDateUpdateError( ResponseMessage.Key.ENROLLMENT_END_DATE_UPDATE_ERROR, ResponseMessage.Message.ENROLLMENT_END_DATE_UPDATE_ERROR), - csvError(ResponseMessage.Key.INVALID_CSV_FILE, ResponseMessage.Message.INVALID_CSV_FILE), - invalidCourseBatchId( - ResponseMessage.Key.INVALID_COURSE_BATCH_ID, ResponseMessage.Message.INVALID_COURSE_BATCH_ID), - courseBatchIdRequired( - ResponseMessage.Key.COURSE_BATCH_ID_MISSING, ResponseMessage.Message.COURSE_BATCH_ID_MISSING), + enrolmentTypeRequired( + ResponseMessage.Key.ENROLMENT_TYPE_REQUIRED, ResponseMessage.Message.ENROLMENT_TYPE_REQUIRED), + enrolmentIncorrectValue( + ResponseMessage.Key.ENROLMENT_TYPE_VALUE_ERROR, + ResponseMessage.Message.ENROLMENT_TYPE_VALUE_ERROR), enrollmentTypeValidation( ResponseMessage.Key.ENROLLMENT_TYPE_VALIDATION, ResponseMessage.Message.ENROLLMENT_TYPE_VALIDATION), - courseCreatedForIsNull( - ResponseMessage.Key.COURSE_CREATED_FOR_NULL, ResponseMessage.Message.COURSE_CREATED_FOR_NULL), - userNotAssociatedToOrg( - ResponseMessage.Key.USER_NOT_BELONGS_TO_ANY_ORG, - ResponseMessage.Message.USER_NOT_BELONGS_TO_ANY_ORG), - invalidObjectType( - ResponseMessage.Key.INVALID_OBJECT_TYPE, ResponseMessage.Message.INVALID_OBJECT_TYPE), + userAlreadyEnrolledCourse( + ResponseMessage.Key.USER_ALREADY_ENROLLED_COURSE, + ResponseMessage.Message.USER_ALREADY_ENROLLED_COURSE), + userNotEnrolledCourse( + ResponseMessage.Key.USER_NOT_ENROLLED_COURSE, + ResponseMessage.Message.USER_NOT_ENROLLED_COURSE), + userAlreadyCompletedCourse( + ResponseMessage.Key.USER_ALREADY_COMPLETED_COURSE, + ResponseMessage.Message.USER_ALREADY_COMPLETED_COURSE), + endDateError(ResponseMessage.Key.END_DATE_ERROR, ResponseMessage.Message.END_DATE_ERROR), + publishedCourseCanNotBeUpdated( + ResponseMessage.Key.PUBLISHED_COURSE_CAN_NOT_UPDATED, + ResponseMessage.Message.PUBLISHED_COURSE_CAN_NOT_UPDATED), progressStatusError( ResponseMessage.Key.INVALID_PROGRESS_STATUS, ResponseMessage.Message.INVALID_PROGRESS_STATUS), - courseBatchStartPassedDateError( - ResponseMessage.Key.COURSE_BATCH_START_PASSED_DATE_INVALID, - ResponseMessage.Message.COURSE_BATCH_START_PASSED_DATE_INVALID), - csvFileEmpty(ResponseMessage.Key.EMPTY_CSV_FILE, ResponseMessage.Message.EMPTY_CSV_FILE), - invalidRootOrgData( - ResponseMessage.Key.INVALID_ROOT_ORG_DATA, ResponseMessage.Message.INVALID_ROOT_ORG_DATA), - noDataForConsumption(ResponseMessage.Key.NO_DATA, ResponseMessage.Message.NO_DATA), - invalidChannel(ResponseMessage.Key.INVALID_CHANNEL, ResponseMessage.Message.INVALID_CHANNEL), - invalidProcessId( - ResponseMessage.Key.INVALID_PROCESS_ID, ResponseMessage.Message.INVALID_PROCESS_ID), - emailSubjectError( - ResponseMessage.Key.EMAIL_SUBJECT_ERROR, ResponseMessage.Message.EMAIL_SUBJECT_ERROR), - emailBodyError(ResponseMessage.Key.EMAIL_BODY_ERROR, ResponseMessage.Message.EMAIL_BODY_ERROR), + missingData( + ResponseMessage.Key.MISSING_CODE, ResponseMessage.Message.MISSING_MESSAGE), + contentTypeMismatch( + ResponseMessage.Key.CONTENT_TYPE_MISMATCH, ResponseMessage.Message.CONTENT_TYPE_MISMATCH), + mimeTypeMismatch( + ResponseMessage.Key.MIME_TYPE_MISMATCH, ResponseMessage.Message.MIME_TYPE_MISMATCH), + + // ------------------------------------------------------------------------- + // Content & Assessment + // ------------------------------------------------------------------------- + contentIdRequired( + ResponseMessage.Key.CONTENT_ID_MISSING_ERROR, + ResponseMessage.Message.CONTENT_ID_MISSING_ERROR), + contentIdRequiredError( + ResponseMessage.Key.CONTENT_ID_MISSING, ResponseMessage.Message.CONTENT_ID_MISSING), + contentIdError(ResponseMessage.Key.CONTENT_ID_ERROR, ResponseMessage.Message.CONTENT_ID_ERROR), + contentVersionRequiredError( + ResponseMessage.Key.CONTENT_VERSION_MISSING, ResponseMessage.Message.CONTENT_VERSION_MISSING), + versionRequiredError( + ResponseMessage.Key.VERSION_MISSING, ResponseMessage.Message.VERSION_MISSING), + contentStatusRequired( + ResponseMessage.Key.CONTENT_STATUS_MISSING_ERROR, + ResponseMessage.Message.CONTENT_STATUS_MISSING_ERROR), + contentTypeRequiredError( + ResponseMessage.Key.CONTENT_TYPE_ERROR, ResponseMessage.Message.CONTENT_TYPE_ERROR), + assessmentItemIdRequired( + ResponseMessage.Key.ASSESSMENT_ITEM_ID_REQUIRED, + ResponseMessage.Message.ASSESSMENT_ITEM_ID_REQUIRED), + assessmentTypeRequired( + ResponseMessage.Key.ASSESSMENT_TYPE_REQUIRED, + ResponseMessage.Message.ASSESSMENT_TYPE_REQUIRED), + assessmentAttemptDateRequired( + ResponseMessage.Key.ATTEMPTED_DATE_REQUIRED, ResponseMessage.Message.ATTEMPTED_DATE_REQUIRED), + assessmentAnswersRequired( + ResponseMessage.Key.ATTEMPTED_ANSWERS_REQUIRED, + ResponseMessage.Message.ATTEMPTED_ANSWERS_REQUIRED), + assessmentmaxScoreRequired( + ResponseMessage.Key.MAX_SCORE_REQUIRED, ResponseMessage.Message.MAX_SCORE_REQUIRED), + attemptIdRequired( + ResponseMessage.Key.ATTEMPT_ID_MISSING_ERROR, + ResponseMessage.Message.ATTEMPT_ID_MISSING_ERROR), + + // ------------------------------------------------------------------------- + // Badge/Certificates (Issuer, Recipient, Assertion) + // ------------------------------------------------------------------------- + issuerIdRequired( + ResponseMessage.Key.ISSUER_ID_REQUIRED, ResponseMessage.Message.ISSUER_ID_REQUIRED), + invalidIssuerId(ResponseMessage.Key.INVALID_ISSUER_ID, ResponseMessage.Message.INVALID_ISSUER_ID), + recipientIdRequired( + ResponseMessage.Key.RECIPIENT_ID_REQUIRED, ResponseMessage.Message.RECIPIENT_ID_REQUIRED), + recipientTypeRequired( + ResponseMessage.Key.RECIPIENT_TYPE_REQUIRED, ResponseMessage.Message.RECIPIENT_TYPE_REQUIRED), + invalidRecipientType( + ResponseMessage.Key.INVALID_RECIPIENT_TYPE, ResponseMessage.Message.INVALID_RECIPIENT_TYPE), + recipientEmailRequired( + ResponseMessage.Key.RECIPIENT_EMAIL_REQUIRED, + ResponseMessage.Message.RECIPIENT_EMAIL_REQUIRED), recipientAddressError( ResponseMessage.Key.RECIPIENT_ADDRESS_ERROR, ResponseMessage.Message.RECIPIENT_ADDRESS_ERROR), - storageContainerNameMandatory( - ResponseMessage.Key.STORAGE_CONTAINER_NAME_MANDATORY, - ResponseMessage.Message.STORAGE_CONTAINER_NAME_MANDATORY), - userOrgAssociationError( - ResponseMessage.Key.USER_ORG_ASSOCIATION_ERROR, - ResponseMessage.Message.USER_ORG_ASSOCIATION_ERROR), - cloudServiceError( - ResponseMessage.Key.CLOUD_SERVICE_ERROR, ResponseMessage.Message.CLOUD_SERVICE_ERROR), receiverIdMandatory( ResponseMessage.Key.RECEIVER_ID_ERROR, ResponseMessage.Message.RECEIVER_ID_ERROR), invalidReceiverId( ResponseMessage.Key.INVALID_RECEIVER_ID, ResponseMessage.Message.INVALID_RECEIVER_ID), - invalidRole(ResponseMessage.Key.INVALID_ROLE, ResponseMessage.Message.INVALID_ROLE), - saltValue(ResponseMessage.Key.INVALID_SALT, ResponseMessage.Message.INVALID_SALT), - orgTypeMandatory( - ResponseMessage.Key.ORG_TYPE_MANDATORY, ResponseMessage.Message.ORG_TYPE_MANDATORY), - orgTypeAlreadyExist( - ResponseMessage.Key.ORG_TYPE_ALREADY_EXIST, ResponseMessage.Message.ORG_TYPE_ALREADY_EXIST), - orgTypeIdRequired( - ResponseMessage.Key.ORG_TYPE_ID_REQUIRED_ERROR, - ResponseMessage.Message.ORG_TYPE_ID_REQUIRED_ERROR), - titleRequired(ResponseMessage.Key.TITLE_REQUIRED, ResponseMessage.Message.TITLE_REQUIRED), - noteRequired(ResponseMessage.Key.NOTE_REQUIRED, ResponseMessage.Message.NOTE_REQUIRED), - contentIdError(ResponseMessage.Key.CONTENT_ID_ERROR, ResponseMessage.Message.CONTENT_ID_ERROR), - invalidTags(ResponseMessage.Key.INVALID_TAGS, ResponseMessage.Message.INVALID_TAGS), - invalidNoteId(ResponseMessage.Key.NOTE_ID_INVALID, ResponseMessage.Message.NOTE_ID_INVALID), - userDataEncryptionError( - ResponseMessage.Key.USER_DATA_ENCRYPTION_ERROR, - ResponseMessage.Message.USER_DATA_ENCRYPTION_ERROR), - phoneNoFormatError( - ResponseMessage.Key.INVALID_PHONE_NO_FORMAT, ResponseMessage.Message.INVALID_PHONE_NO_FORMAT), - invalidWebPageData( - ResponseMessage.Key.INVALID_WEBPAGE_DATA, ResponseMessage.Message.INVALID_WEBPAGE_DATA), - invalidMediaType( - ResponseMessage.Key.INVALID_MEDIA_TYPE, ResponseMessage.Message.INVALID_MEDIA_TYPE), - invalidWebPageUrl( - ResponseMessage.Key.INVALID_WEBPAGE_URL, ResponseMessage.Message.INVALID_WEBPAGE_URL), - invalidDateRange( - ResponseMessage.Key.INVALID_DATE_RANGE, ResponseMessage.Message.INVALID_DATE_RANGE), - invalidBatchEndDateError( - ResponseMessage.Key.INVALID_BATCH_END_DATE_ERROR, - ResponseMessage.Message.INVALID_BATCH_END_DATE_ERROR), - invalidBatchStartDateError( - ResponseMessage.Key.INVALID_BATCH_START_DATE_ERROR, - ResponseMessage.Message.INVALID_BATCH_START_DATE_ERROR), - courseBatchEndDateError( - ResponseMessage.Key.COURSE_BATCH_END_DATE_ERROR, - ResponseMessage.Message.COURSE_BATCH_END_DATE_ERROR), - BatchCloseError( - ResponseMessage.Key.COURSE_BATCH_IS_CLOSED_ERROR, - ResponseMessage.Message.COURSE_BATCH_IS_CLOSED_ERROR), - newPasswordRequired( - ResponseMessage.Key.CONFIIRM_PASSWORD_MISSING, - ResponseMessage.Message.CONFIIRM_PASSWORD_MISSING), - newPasswordEmpty( - ResponseMessage.Key.CONFIIRM_PASSWORD_EMPTY, ResponseMessage.Message.CONFIIRM_PASSWORD_EMPTY), - samePasswordError( - ResponseMessage.Key.SAME_PASSWORD_ERROR, ResponseMessage.Message.SAME_PASSWORD_ERROR), + assertionIdRequired( + ResponseMessage.Key.ASSERTION_ID_REQUIRED, ResponseMessage.Message.ASSERTION_ID_REQUIRED), + evidenceRequired( + ResponseMessage.Key.ASSERTION_EVIDENCE_REQUIRED, + ResponseMessage.Message.ASSERTION_EVIDENCE_REQUIRED), + revocationReasonRequired( + ResponseMessage.Key.REVOCATION_REASON_REQUIRED, + ResponseMessage.Message.REVOCATION_REASON_REQUIRED), endorsedUserIdRequired( ResponseMessage.Key.ENDORSED_USER_ID_REQUIRED, ResponseMessage.Message.ENDORSED_USER_ID_REQUIRED), canNotEndorse(ResponseMessage.Key.CAN_NOT_ENDORSE, ResponseMessage.Message.CAN_NOT_ENDORSE), - invalidOrgTypeId( - ResponseMessage.Key.INVALID_ORG_TYPE_ID_ERROR, - ResponseMessage.Message.INVALID_ORG_TYPE_ID_ERROR), - invalidOrgType( - ResponseMessage.Key.INVALID_ORG_TYPE_ERROR, ResponseMessage.Message.INVALID_ORG_TYPE_ERROR), - tableOrDocNameError( - ResponseMessage.Key.TABLE_OR_DOC_NAME_ERROR, ResponseMessage.Message.TABLE_OR_DOC_NAME_ERROR), - emailorPhoneRequired( - ResponseMessage.Key.EMAIL_OR_PHONE_MISSING, ResponseMessage.Message.EMAIL_OR_PHONE_MISSING), - PhoneNumberInUse( - ResponseMessage.Key.PHONE_ALREADY_IN_USE, ResponseMessage.Message.PHONE_ALREADY_IN_USE), - invalidClientName( - ResponseMessage.Key.INVALID_CLIENT_NAME, ResponseMessage.Message.INVALID_CLIENT_NAME), - invalidClientId(ResponseMessage.Key.INVALID_CLIENT_ID, ResponseMessage.Message.INVALID_CLIENT_ID), - userPhoneUpdateFailed( - ResponseMessage.Key.USER_PHONE_UPDATE_FAILED, - ResponseMessage.Message.USER_PHONE_UPDATE_FAILED), - esUpdateFailed(ResponseMessage.Key.ES_UPDATE_FAILED, ResponseMessage.Message.ES_UPDATE_FAILED), - updateFailed(ResponseMessage.Key.UPDATE_FAILED, ResponseMessage.Message.UPDATE_FAILED), - invalidTypeValue(ResponseMessage.Key.INVALID_TYPE_VALUE, ResponseMessage.Key.INVALID_TYPE_VALUE), - invalidLocationId( - ResponseMessage.Key.INVALID_LOCATION_ID, ResponseMessage.Message.INVALID_LOCATION_ID), - invalidHashTagId( - ResponseMessage.Key.INVALID_HASHTAG_ID, ResponseMessage.Message.INVALID_HASHTAG_ID), - invalidUsrOrgData( - ResponseMessage.Key.INVALID_USR_ORG_DATA, ResponseMessage.Message.INVALID_USR_ORG_DATA), - visibilityInvalid( - ResponseMessage.Key.INVALID_VISIBILITY_REQUEST, - ResponseMessage.Message.INVALID_VISIBILITY_REQUEST), - invalidTopic(ResponseMessage.Key.INVALID_TOPIC_NAME, ResponseMessage.Message.INVALID_TOPIC_NAME), - invalidTopicData( - ResponseMessage.Key.INVALID_TOPIC_DATA, ResponseMessage.Message.INVALID_TOPIC_DATA), + + // ------------------------------------------------------------------------- + // Notifications & Email + // ------------------------------------------------------------------------- + emailSubjectError( + ResponseMessage.Key.EMAIL_SUBJECT_ERROR, ResponseMessage.Message.EMAIL_SUBJECT_ERROR), + emailBodyError(ResponseMessage.Key.EMAIL_BODY_ERROR, ResponseMessage.Message.EMAIL_BODY_ERROR), + emailNotSentRecipientsExceededMaxLimit( + ResponseMessage.Key.EMAIL_RECIPIENTS_EXCEEDS_MAX_LIMIT, + ResponseMessage.Message.EMAIL_RECIPIENTS_EXCEEDS_MAX_LIMIT), + emailNotSentRecipientsZero( + ResponseMessage.Key.NO_EMAIL_RECIPIENTS, ResponseMessage.Message.NO_EMAIL_RECIPIENTS), + msgIdRequiredError( + ResponseMessage.Key.MESSAGE_ID_MISSING, ResponseMessage.Message.MESSAGE_ID_MISSING), invalidNotificationType( ResponseMessage.Key.INVALID_NOTIFICATION_TYPE, ResponseMessage.Message.INVALID_NOTIFICATION_TYPE), notificationTypeSupport( ResponseMessage.Key.INVALID_NOTIFICATION_TYPE_SUPPORT, ResponseMessage.Message.INVALID_NOTIFICATION_TYPE_SUPPORT), - emailInUse(ResponseMessage.Key.EMAIL_IN_USE, ResponseMessage.Message.EMAIL_IN_USE), - invalidPhoneNumber( - ResponseMessage.Key.INVALID_PHONE_NUMBER, ResponseMessage.Message.INVALID_PHONE_NUMBER), - invalidCountryCode( - ResponseMessage.Key.INVALID_COUNTRY_CODE, ResponseMessage.Message.INVALID_COUNTRY_CODE), - locationIdRequired( - ResponseMessage.Key.LOCATION_ID_REQUIRED, ResponseMessage.Message.LOCATION_ID_REQUIRED), - functionalityMissing(ResponseMessage.Key.NOT_SUPPORTED, ResponseMessage.Message.NOT_SUPPORTED), - userNameOrUserIdRequired( - ResponseMessage.Key.USERNAME_USERID_MISSING, ResponseMessage.Message.USERNAME_USERID_MISSING), - channelRegFailed( - ResponseMessage.Key.CHANNEL_REG_FAILED, ResponseMessage.Message.CHANNEL_REG_FAILED), - invalidCourseCreatorId( - ResponseMessage.Key.INVALID_COURSE_CREATOR_ID, - ResponseMessage.Message.INVALID_COURSE_CREATOR_ID), - userNotAssociatedToRootOrg( - ResponseMessage.Key.USER_NOT_ASSOCIATED_TO_ROOT_ORG, - ResponseMessage.Message.USER_NOT_ASSOCIATED_TO_ROOT_ORG), - slugIsNotUnique( - ResponseMessage.Key.SLUG_IS_NOT_UNIQUE, ResponseMessage.Message.SLUG_IS_NOT_UNIQUE), - issuerIdRequired( - ResponseMessage.Key.ISSUER_ID_REQUIRED, ResponseMessage.Message.ISSUER_ID_REQUIRED), - rootOrgIdRequired( - ResponseMessage.Key.ROOT_ORG_ID_REQUIRED, ResponseMessage.Message.ROOT_ORG_ID_REQUIRED), - recipientEmailRequired( - ResponseMessage.Key.RECIPIENT_EMAIL_REQUIRED, - ResponseMessage.Message.RECIPIENT_EMAIL_REQUIRED), - evidenceRequired( - ResponseMessage.Key.ASSERTION_EVIDENCE_REQUIRED, - ResponseMessage.Message.ASSERTION_EVIDENCE_REQUIRED), - assertionIdRequired( - ResponseMessage.Key.ASSERTION_ID_REQUIRED, ResponseMessage.Message.ASSERTION_ID_REQUIRED), - recipientIdRequired( - ResponseMessage.Key.RECIPIENT_ID_REQUIRED, ResponseMessage.Message.RECIPIENT_ID_REQUIRED), - recipientTypeRequired( - ResponseMessage.Key.RECIPIENT_TYPE_REQUIRED, ResponseMessage.Message.RECIPIENT_TYPE_REQUIRED), - resourceNotFound( - ResponseMessage.Key.RESOURCE_NOT_FOUND, ResponseMessage.Message.RESOURCE_NOT_FOUND), - sizeLimitExceed( - ResponseMessage.Key.MAX_ALLOWED_SIZE_LIMIT_EXCEED, - ResponseMessage.Message.MAX_ALLOWED_SIZE_LIMIT_EXCEED), - slugRequired(ResponseMessage.Key.SLUG_REQUIRED, ResponseMessage.Message.SLUG_REQUIRED), - invalidIssuerId(ResponseMessage.Key.INVALID_ISSUER_ID, ResponseMessage.Message.INVALID_ISSUER_ID), - revocationReasonRequired( - ResponseMessage.Key.REVOCATION_REASON_REQUIRED, - ResponseMessage.Message.REVOCATION_REASON_REQUIRED), - invalidRecipientType( - ResponseMessage.Key.INVALID_RECIPIENT_TYPE, ResponseMessage.Message.INVALID_RECIPIENT_TYPE), - customServerError( - ResponseMessage.Key.CUSTOM_SERVER_ERROR, ResponseMessage.Message.CUSTOM_SERVER_ERROR), + invalidTopic(ResponseMessage.Key.INVALID_TOPIC_NAME, ResponseMessage.Message.INVALID_TOPIC_NAME), + invalidTopicData( + ResponseMessage.Key.INVALID_TOPIC_DATA, ResponseMessage.Message.INVALID_TOPIC_DATA), + + // ------------------------------------------------------------------------- + // System, Config & Infrastructure + // ------------------------------------------------------------------------- + errorInvalidConfigParamValue( + ResponseMessage.Key.ERROR_INVALID_CONFIG_PARAM_VALUE, + ResponseMessage.Message.ERROR_INVALID_CONFIG_PARAM_VALUE), + errorConfigLoadEmptyString( + ResponseMessage.Key.ERROR_CONFIG_LOAD_EMPTY_STRING, + ResponseMessage.Message.ERROR_CONFIG_LOAD_EMPTY_STRING), + errorConfigLoadParseString( + ResponseMessage.Key.ERROR_CONFIG_LOAD_PARSE_STRING, + ResponseMessage.Message.ERROR_CONFIG_LOAD_PARSE_STRING), + errorConfigLoadEmptyConfig( + ResponseMessage.Key.ERROR_CONFIG_LOAD_EMPTY_CONFIG, + ResponseMessage.Message.ERROR_CONFIG_LOAD_EMPTY_CONFIG), + errorConflictingFieldConfiguration( + ResponseMessage.Key.ERROR_CONFLICTING_FIELD_CONFIGURATION, + ResponseMessage.Message.ERROR_CONFLICTING_FIELD_CONFIGURATION), + mandatoryConfigParamMissing( + ResponseMessage.Key.MANDATORY_CONFIG_PARAMETER_MISSING, + ResponseMessage.Message.MANDATORY_CONFIG_PARAMETER_MISSING), + errorLoadConfig(ResponseMessage.Key.ERROR_LOAD_CONFIG, ResponseMessage.Message.ERROR_LOAD_CONFIG), + errorSystemSettingNotFound( + ResponseMessage.Key.ERROR_SYSTEM_SETTING_NOT_FOUND, + ResponseMessage.Message.ERROR_SYSTEM_SETTING_NOT_FOUND), + errorUpdateSettingNotAllowed( + ResponseMessage.Key.ERROR_UPDATE_SETTING_NOT_ALLOWED, + ResponseMessage.Message.ERROR_UPDATE_SETTING_NOT_ALLOWED), + dbInsertionError( + ResponseMessage.Key.DB_INSERTION_FAIL, ResponseMessage.Message.DB_INSERTION_FAIL), + dbUpdateError(ResponseMessage.Key.DB_UPDATE_FAIL, ResponseMessage.Message.DB_UPDATE_FAIL), + esError(ResponseMessage.Key.ES_ERROR, ResponseMessage.Message.ES_ERROR), + esUpdateFailed(ResponseMessage.Key.ES_UPDATE_FAILED, ResponseMessage.Message.ES_UPDATE_FAILED), + unableToConnect( + ResponseMessage.Key.UNABLE_TO_CONNECT_TO_EKSTEP, + ResponseMessage.Message.UNABLE_TO_CONNECT_TO_EKSTEP), + unableToConnectToES( + ResponseMessage.Key.UNABLE_TO_CONNECT_TO_ES, ResponseMessage.Message.UNABLE_TO_CONNECT_TO_ES), + unableToCommunicateWithActor( + ResponseMessage.Key.UNABLE_TO_COMMUNICATE_WITH_ACTOR, + ResponseMessage.Message.UNABLE_TO_COMMUNICATE_WITH_ACTOR), + actorConnectionError( + ResponseMessage.Key.ACTOR_CONNECTION_ERROR, ResponseMessage.Message.ACTOR_CONNECTION_ERROR), + cassandraConnectionEstablishmentFailed( + ResponseMessage.Key.CASSANDRA_CONNECTION_ESTABLISHMENT_FAILED, + ResponseMessage.Message.CASSANDRA_CONNECTION_ESTABLISHMENT_FAILED), + cloudServiceError( + ResponseMessage.Key.CLOUD_SERVICE_ERROR, ResponseMessage.Message.CLOUD_SERVICE_ERROR), + errorUnsupportedCloudStorage( + ResponseMessage.Key.ERROR_UNSUPPORTED_CLOUD_STORAGE, + ResponseMessage.Message.ERROR_UNSUPPORTED_CLOUD_STORAGE), + storageContainerNameMandatory( + ResponseMessage.Key.STORAGE_CONTAINER_NAME_MANDATORY, + ResponseMessage.Message.STORAGE_CONTAINER_NAME_MANDATORY), + errorGenerateDownloadLink( + ResponseMessage.Key.ERROR_GENERATE_DOWNLOAD_LINK, + ResponseMessage.Message.ERROR_GENERATE_DOWNLOAD_LINK), + errorUnavailableDownloadLink( + ResponseMessage.Key.ERROR_DOWNLOAD_LINK_UNAVAILABLE, + ResponseMessage.Message.ERROR_DOWNLOAD_LINK_UNAVAILABLE), + errorSavingStorageDetails( + ResponseMessage.Key.ERROR_SAVING_STORAGE_DETAILS, + ResponseMessage.Message.ERROR_SAVING_STORAGE_DETAILS), + errorUploadQRCodeCSVfailed( + ResponseMessage.Key.ERROR_UPLOAD_QRCODE_CSV_FAILED, + ResponseMessage.Message.ERROR_UPLOAD_QRCODE_CSV_FAILED), + erroCallGrooupAPI(ResponseMessage.Key.ERR_CALLING_GROUP_API, ResponseMessage.Message.ERR_CALLING_GROUP_API), + + // ------------------------------------------------------------------------- + // Files & Uploads + // ------------------------------------------------------------------------- + csvError(ResponseMessage.Key.INVALID_CSV_FILE, ResponseMessage.Message.INVALID_CSV_FILE), + errorCsvNoDataRows( + ResponseMessage.Key.ERROR_CSV_NO_DATA_ROWS, ResponseMessage.Message.ERROR_CSV_NO_DATA_ROWS), + csvFileEmpty(ResponseMessage.Key.EMPTY_CSV_FILE, ResponseMessage.Message.EMPTY_CSV_FILE), + emptyHeaderLine(ResponseMessage.Key.EMPTY_HEADER_LINE, ResponseMessage.Message.EMPTY_HEADER_LINE), + bulkUserUploadError( + ResponseMessage.Key.BULK_USER_UPLOAD_ERROR, ResponseMessage.Message.BULK_USER_UPLOAD_ERROR), + dataSizeError(ResponseMessage.Key.DATA_SIZE_EXCEEDED, ResponseMessage.Message.DATA_SIZE_EXCEEDED), + errorMaxSizeExceeded( + ResponseMessage.Key.ERROR_MAX_SIZE_EXCEEDED, ResponseMessage.Message.ERROR_MAX_SIZE_EXCEEDED), + missingFileAttachment( + ResponseMessage.Key.MISSING_FILE_ATTACHMENT, ResponseMessage.Message.MISSING_FILE_ATTACHMENT), + emptyFile(ResponseMessage.Key.EMPTY_FILE, ResponseMessage.Message.EMPTY_FILE), + fileAttachmentSizeNotConfigured( + ResponseMessage.Key.FILE_ATTACHMENT_SIZE_NOT_CONFIGURED, + ResponseMessage.Message.FILE_ATTACHMENT_SIZE_NOT_CONFIGURED), + errorCreatingFile( + ResponseMessage.Key.ERROR_CREATING_FILE, ResponseMessage.Message.ERROR_CREATING_FILE), + errorProcessingFile( + ResponseMessage.Key.ERROR_PROCESSING_FILE, ResponseMessage.Message.ERROR_PROCESSING_FILE), + errorProcessingRequest( + ResponseMessage.Key.ERROR_PROCESSING_REQUEST, + ResponseMessage.Message.ERROR_PROCESSING_REQUEST), + + // ------------------------------------------------------------------------- + // Miscellaneous + // ------------------------------------------------------------------------- + pageNameRequired( + ResponseMessage.Key.PAGE_NAME_REQUIRED, ResponseMessage.Message.PAGE_NAME_REQUIRED), + pageIdRequired(ResponseMessage.Key.PAGE_ID_REQUIRED, ResponseMessage.Message.PAGE_ID_REQUIRED), + pageAlreadyExist( + ResponseMessage.Key.PAGE_ALREADY_EXIST, ResponseMessage.Message.PAGE_ALREADY_EXIST), pageDoesNotExist(ResponseMessage.Key.PAGE_NOT_EXIST, ResponseMessage.Message.PAGE_NOT_EXIST), - sectionDoesNotExist( - ResponseMessage.Key.SECTION_NOT_EXIST, ResponseMessage.Message.SECTION_NOT_EXIST), - orgDoesNotExist(ResponseMessage.Key.ORG_NOT_EXIST, ResponseMessage.Message.ORG_NOT_EXIST), invalidPageSource( ResponseMessage.Key.INVALID_PAGE_SOURCE, ResponseMessage.Message.INVALID_PAGE_SOURCE), - locationTypeRequired( - ResponseMessage.Key.LOCATION_TYPE_REQUIRED, ResponseMessage.Message.LOCATION_TYPE_REQUIRED), - invalidRequestDataForLocation( - ResponseMessage.Key.INVALID_REQUEST_DATA_FOR_LOCATION, - ResponseMessage.Message.INVALID_REQUEST_DATA_FOR_LOCATION), - alreadyExists(ResponseMessage.Key.ALREADY_EXISTS, ResponseMessage.Message.ALREADY_EXISTS), - invalidValue(ResponseMessage.Key.INVALID_VALUE, ResponseMessage.Message.INVALID_VALUE), - parentCodeAndIdValidationError( - ResponseMessage.Key.PARENT_CODE_AND_PARENT_ID_MISSING, - ResponseMessage.Message.PARENT_CODE_AND_PARENT_ID_MISSING), - invalidParameter( - ResponseMessage.Key.INVALID_PARAMETER, ResponseMessage.Message.INVALID_PARAMETER), - invalidLocationDeleteRequest( - ResponseMessage.Key.INVALID_LOCATION_DELETE_REQUEST, - ResponseMessage.Message.INVALID_LOCATION_DELETE_REQUEST), - locationTypeConflicts( - ResponseMessage.Key.LOCATION_TYPE_CONFLICTS, ResponseMessage.Message.LOCATION_TYPE_CONFLICTS), - mandatoryParamsMissing( - ResponseMessage.Key.MANDATORY_PARAMETER_MISSING, - ResponseMessage.Message.MANDATORY_PARAMETER_MISSING), - errorMandatoryParamsEmpty( - ResponseMessage.Key.ERROR_MANDATORY_PARAMETER_EMPTY, - ResponseMessage.Message.ERROR_MANDATORY_PARAMETER_EMPTY), - errorNoFrameworkFound( - ResponseMessage.Key.ERROR_NO_FRAMEWORK_FOUND, - ResponseMessage.Message.ERROR_NO_FRAMEWORK_FOUND), + sectionNameRequired( + ResponseMessage.Key.SECTION_NAME_MISSING, ResponseMessage.Message.SECTION_NAME_MISSING), + sectionDataTypeRequired( + ResponseMessage.Key.SECTION_DATA_TYPE_MISSING, + ResponseMessage.Message.SECTION_DATA_TYPE_MISSING), + sectionIdRequired( + ResponseMessage.Key.SECTION_ID_REQUIRED, ResponseMessage.Message.SECTION_ID_REQUIRED), + sectionDoesNotExist( + ResponseMessage.Key.SECTION_NOT_EXIST, ResponseMessage.Message.SECTION_NOT_EXIST), + errorInvalidPageSection( + ResponseMessage.Key.INVALID_PAGE_SECTION, ResponseMessage.Message.INVALID_PAGE_SECTION), + invalidWebPageData( + ResponseMessage.Key.INVALID_WEBPAGE_DATA, ResponseMessage.Message.INVALID_WEBPAGE_DATA), + invalidMediaType( + ResponseMessage.Key.INVALID_MEDIA_TYPE, ResponseMessage.Message.INVALID_MEDIA_TYPE), + invalidWebPageUrl( + ResponseMessage.Key.INVALID_WEBPAGE_URL, ResponseMessage.Message.INVALID_WEBPAGE_URL), + titleRequired(ResponseMessage.Key.TITLE_REQUIRED, ResponseMessage.Message.TITLE_REQUIRED), + noteRequired(ResponseMessage.Key.NOTE_REQUIRED, ResponseMessage.Message.NOTE_REQUIRED), + invalidNoteId(ResponseMessage.Key.NOTE_ID_INVALID, ResponseMessage.Message.NOTE_ID_INVALID), + invalidTags(ResponseMessage.Key.INVALID_TAGS, ResponseMessage.Message.INVALID_TAGS), + invalidClientName( + ResponseMessage.Key.INVALID_CLIENT_NAME, ResponseMessage.Message.INVALID_CLIENT_NAME), + invalidClientId(ResponseMessage.Key.INVALID_CLIENT_ID, ResponseMessage.Message.INVALID_CLIENT_ID), + tableOrDocNameError( + ResponseMessage.Key.TABLE_OR_DOC_NAME_ERROR, ResponseMessage.Message.TABLE_OR_DOC_NAME_ERROR), + invalidDuplicateValue( + ResponseMessage.Key.INVALID_DUPLICATE_VALUE, ResponseMessage.Message.INVALID_DUPLICATE_VALUE), + errorDuplicateEntry( + ResponseMessage.Key.ERROR_DUPLICATE_ENTRY, ResponseMessage.Message.ERROR_DUPLICATE_ENTRY), + errorDuplicateEntries( + ResponseMessage.Key.ERROR_DUPLICATE_ENTRIES, ResponseMessage.Message.ERROR_DUPLICATE_ENTRIES), + invalidPeriod(ResponseMessage.Key.INVALID_PERIOD, ResponseMessage.Message.INVALID_PERIOD), + invalidDateRange( + ResponseMessage.Key.INVALID_DATE_RANGE, ResponseMessage.Message.INVALID_DATE_RANGE), + cyclicValidationError( + ResponseMessage.Key.CYCLIC_VALIDATION_FAILURE, + ResponseMessage.Message.CYCLIC_VALIDATION_FAILURE), unupdatableField( ResponseMessage.Key.UPDATE_NOT_ALLOWED, ResponseMessage.Message.UPDATE_NOT_ALLOWED), + statusCanntBeUpdated( + ResponseMessage.Key.STATUS_CANNOT_BE_UPDATED, + ResponseMessage.Message.STATUS_CANNOT_BE_UPDATED), + updateFailed(ResponseMessage.Key.UPDATE_FAILED, ResponseMessage.Message.UPDATE_FAILED), + InvalidColumnError( + ResponseMessage.Key.INVALID_COLUMN_NAME, ResponseMessage.Message.INVALID_COLUMN_NAME), + invalidColumns(ResponseMessage.Key.INVALID_COLUMNS, ResponseMessage.Message.INVALID_COLUMNS), + requiredHeaderMissing( + ResponseMessage.Key.REQUIRED_HEADER_MISSING, ResponseMessage.Message.REQUIRED_HEADER_MISSING), mandatoryHeadersMissing( ResponseMessage.Key.MANDATORY_HEADER_MISSING, ResponseMessage.Message.MANDATORY_HEADER_MISSING), - invalidParameterValue( - ResponseMessage.Key.INVALID_PARAMETER_VALUE, ResponseMessage.Message.INVALID_PARAMETER_VALUE), - parentNotAllowed( - ResponseMessage.Key.PARENT_NOT_ALLOWED, ResponseMessage.Message.PARENT_NOT_ALLOWED), - missingFileAttachment( - ResponseMessage.Key.MISSING_FILE_ATTACHMENT, ResponseMessage.Message.MISSING_FILE_ATTACHMENT), - fileAttachmentSizeNotConfigured( - ResponseMessage.Key.FILE_ATTACHMENT_SIZE_NOT_CONFIGURED, - ResponseMessage.Message.FILE_ATTACHMENT_SIZE_NOT_CONFIGURED), - emptyFile(ResponseMessage.Key.EMPTY_FILE, ResponseMessage.Message.EMPTY_FILE), - invalidColumns(ResponseMessage.Key.INVALID_COLUMNS, ResponseMessage.Message.INVALID_COLUMNS), - conflictingOrgLocations( - ResponseMessage.Key.CONFLICTING_ORG_LOCATIONS, - ResponseMessage.Message.CONFLICTING_ORG_LOCATIONS), - unableToCommunicateWithActor( - ResponseMessage.Key.UNABLE_TO_COMMUNICATE_WITH_ACTOR, - ResponseMessage.Message.UNABLE_TO_COMMUNICATE_WITH_ACTOR), - emptyHeaderLine(ResponseMessage.Key.EMPTY_HEADER_LINE, ResponseMessage.Message.EMPTY_HEADER_LINE), + mandatoryHeaderParamsMissing( + ResponseMessage.Key.MANDATORY_HEADER_PARAMETER_MISSING, + ResponseMessage.Message.MANDATORY_HEADER_PARAMETER_MISSING), invalidRequestParameter( ResponseMessage.Key.INVALID_REQUEST_PARAMETER, ResponseMessage.Message.INVALID_REQUEST_PARAMETER), - rootOrgAssociationError( - ResponseMessage.Key.ROOT_ORG_ASSOCIATION_ERROR, - ResponseMessage.Message.ROOT_ORG_ASSOCIATION_ERROR), dependentParameterMissing( ResponseMessage.Key.DEPENDENT_PARAMETER_MISSING, ResponseMessage.Message.DEPENDENT_PARAMETER_MISSING), - externalIdNotFound( - ResponseMessage.Key.EXTERNALID_NOT_FOUND, ResponseMessage.Message.EXTERNALID_NOT_FOUND), - externalIdAssignedToOtherUser( - ResponseMessage.Key.EXTERNALID_ASSIGNED_TO_OTHER_USER, - ResponseMessage.Message.EXTERNALID_ASSIGNED_TO_OTHER_USER), dependentParamsMissing( ResponseMessage.Key.DEPENDENT_PARAMETER_MISSING, ResponseMessage.Message.DEPENDENT_PARAMS_MISSING), - mandatoryConfigParamMissing( - ResponseMessage.Key.MANDATORY_CONFIG_PARAMETER_MISSING, - ResponseMessage.Message.MANDATORY_CONFIG_PARAMETER_MISSING), - cassandraConnectionEstablishmentFailed( - ResponseMessage.Key.CASSANDRA_CONNECTION_ESTABLISHMENT_FAILED, - ResponseMessage.Message.CASSANDRA_CONNECTION_ESTABLISHMENT_FAILED), commonAttributeMismatch( ResponseMessage.Key.COMMON_ATTRIBUTE_MISMATCH, ResponseMessage.Message.COMMON_ATTRIBUTE_MISMATCH), - multipleCoursesNotAllowedForBatch( - ResponseMessage.Key.MULTIPLE_COURSES_FOR_BATCH, - ResponseMessage.Message.MULTIPLE_COURSES_FOR_BATCH), + errorAttributeConflict( + ResponseMessage.Key.ERROR_ATTRIBUTE_CONFLICT, + ResponseMessage.Message.ERROR_ATTRIBUTE_CONFLICT), + sourceRequired(ResponseMessage.Key.SOURCE_MISSING, ResponseMessage.Message.SOURCE_MISSING), + invaidConfiguration( + ResponseMessage.Key.INVALID_CONFIGURATION, ResponseMessage.Message.INVALID_CONFIGURATION), + invalidProcessId( + ResponseMessage.Key.INVALID_PROCESS_ID, ResponseMessage.Message.INVALID_PROCESS_ID), + invalidTypeValue(ResponseMessage.Key.INVALID_TYPE_VALUE, ResponseMessage.Key.INVALID_TYPE_VALUE), + errorNoFrameworkFound( + ResponseMessage.Key.ERROR_NO_FRAMEWORK_FOUND, + ResponseMessage.Message.ERROR_NO_FRAMEWORK_FOUND), + eventsRequired( + ResponseMessage.Key.EVENTS_DATA_MISSING, ResponseMessage.Message.EVENTS_DATA_MISSING), + groupIdMismatch(ResponseMessage.Key.GROUP_ID_MISSING, ResponseMessage.Message.GROUP_ID_MISSING), + activityIdMismatch(ResponseMessage.Key.ACTIVITY_ID_MISSING, ResponseMessage.Message.ACTIVITY_ID_MISSING), + activityTypeMismatch(ResponseMessage.Key.ACTIVITY_TYPE_MISSING, ResponseMessage.Message.ACTIVITY_TYPE_MISSING), + errorNoDialcodesLinked( + ResponseMessage.Key.ERROR_NO_DIALCODES_LINKED, + ResponseMessage.Message.ERROR_NO_DIALCODES_LINKED), + errorUnsupportedField( + ResponseMessage.Key.ERROR_UNSUPPORTED_FIELD, ResponseMessage.Message.ERROR_UNSUPPORTED_FIELD), + + // ------------------------------------------------------------------------- + // JSON Transform (Registry) + // ------------------------------------------------------------------------- errorJsonTransformInvalidTypeConfig( ResponseMessage.Key.ERROR_JSON_TRANSFORM_INVALID_TYPE_CONFIG, ResponseMessage.Message.ERROR_JSON_TRANSFORM_INVALID_TYPE_CONFIG), @@ -576,7 +744,6 @@ public enum ResponseCode { errorJsonTransformInvalidFilterConfig( ResponseMessage.Key.ERROR_JSON_TRANSFORM_INVALID_FILTER_CONFIG, ResponseMessage.Message.ERROR_JSON_TRANSFORM_INVALID_FILTER_CONFIG), - errorLoadConfig(ResponseMessage.Key.ERROR_LOAD_CONFIG, ResponseMessage.Message.ERROR_LOAD_CONFIG), errorRegistryClientCreation( ResponseMessage.Key.ERROR_REGISTRY_CLIENT_CREATION, ResponseMessage.Message.ERROR_REGISTRY_CLIENT_CREATION), @@ -604,129 +771,12 @@ public enum ResponseCode { errorRegistryAccessTokenBlank( ResponseMessage.Key.ERROR_REGISTRY_ACCESS_TOKEN_BLANK, ResponseMessage.Message.ERROR_REGISTRY_ACCESS_TOKEN_BLANK), - duplicateExternalIds( - ResponseMessage.Key.DUPLICATE_EXTERNAL_IDS, ResponseMessage.Message.DUPLICATE_EXTERNAL_IDS), - invalidDuplicateValue( + invalidDuplicateValueInList( ResponseMessage.Key.INVALID_DUPLICATE_VALUE, ResponseMessage.Message.INVALID_DUPLICATE_VALUE), - emailNotSentRecipientsExceededMaxLimit( - ResponseMessage.Key.EMAIL_RECIPIENTS_EXCEEDS_MAX_LIMIT, - ResponseMessage.Message.EMAIL_RECIPIENTS_EXCEEDS_MAX_LIMIT), - emailNotSentRecipientsZero( - ResponseMessage.Key.NO_EMAIL_RECIPIENTS, ResponseMessage.Message.NO_EMAIL_RECIPIENTS), - parameterMismatch( - ResponseMessage.Key.PARAMETER_MISMATCH, ResponseMessage.Message.PARAMETER_MISMATCH), - errorForbidden(ResponseMessage.Key.FORBIDDEN, ResponseMessage.Message.FORBIDDEN), - errorConfigLoadEmptyString( - ResponseMessage.Key.ERROR_CONFIG_LOAD_EMPTY_STRING, - ResponseMessage.Message.ERROR_CONFIG_LOAD_EMPTY_STRING), - errorConfigLoadParseString( - ResponseMessage.Key.ERROR_CONFIG_LOAD_PARSE_STRING, - ResponseMessage.Message.ERROR_CONFIG_LOAD_PARSE_STRING), - errorConfigLoadEmptyConfig( - ResponseMessage.Key.ERROR_CONFIG_LOAD_EMPTY_CONFIG, - ResponseMessage.Message.ERROR_CONFIG_LOAD_EMPTY_CONFIG), - errorConflictingFieldConfiguration( - ResponseMessage.Key.ERROR_CONFLICTING_FIELD_CONFIGURATION, - ResponseMessage.Message.ERROR_CONFLICTING_FIELD_CONFIGURATION), - errorSystemSettingNotFound( - ResponseMessage.Key.ERROR_SYSTEM_SETTING_NOT_FOUND, - ResponseMessage.Message.ERROR_SYSTEM_SETTING_NOT_FOUND), - errorNoRootOrgAssociated( - ResponseMessage.Key.ERROR_NO_ROOT_ORG_ASSOCIATED, - ResponseMessage.Message.ERROR_NO_ROOT_ORG_ASSOCIATED), - errorInactiveCustodianOrg( - ResponseMessage.Key.ERROR_INACTIVE_CUSTODIAN_ORG, - ResponseMessage.Message.ERROR_INACTIVE_CUSTODIAN_ORG), - errorUnsupportedCloudStorage( - ResponseMessage.Key.ERROR_UNSUPPORTED_CLOUD_STORAGE, - ResponseMessage.Message.ERROR_UNSUPPORTED_CLOUD_STORAGE), - errorUnsupportedField( - ResponseMessage.Key.ERROR_UNSUPPORTED_FIELD, ResponseMessage.Message.ERROR_UNSUPPORTED_FIELD), - errorGenerateDownloadLink( - ResponseMessage.Key.ERROR_GENERATE_DOWNLOAD_LINK, - ResponseMessage.Message.ERROR_GENERATE_DOWNLOAD_LINK), - errorUnavailableDownloadLink( - ResponseMessage.Key.ERROR_DOWNLOAD_LINK_UNAVAILABLE, - ResponseMessage.Message.ERROR_DOWNLOAD_LINK_UNAVAILABLE), - errorSavingStorageDetails( - ResponseMessage.Key.ERROR_SAVING_STORAGE_DETAILS, - ResponseMessage.Message.ERROR_SAVING_STORAGE_DETAILS), - errorCsvNoDataRows( - ResponseMessage.Key.ERROR_CSV_NO_DATA_ROWS, ResponseMessage.Message.ERROR_CSV_NO_DATA_ROWS), - errorInactiveOrg( - ResponseMessage.Key.ERROR_INACTIVE_ORG, ResponseMessage.Message.ERROR_INACTIVE_ORG), - errorDuplicateEntries( - ResponseMessage.Key.ERROR_DUPLICATE_ENTRIES, ResponseMessage.Message.ERROR_DUPLICATE_ENTRIES), - errorUpdateSettingNotAllowed( - ResponseMessage.Key.ERROR_UPDATE_SETTING_NOT_ALLOWED, - ResponseMessage.Message.ERROR_UPDATE_SETTING_NOT_ALLOWED), - errorCreatingFile( - ResponseMessage.Key.ERROR_CREATING_FILE, ResponseMessage.Message.ERROR_CREATING_FILE), - errorProcessingRequest( - ResponseMessage.Key.ERROR_PROCESSING_REQUEST, - ResponseMessage.Message.ERROR_PROCESSING_REQUEST), - requiredHeaderMissing( - ResponseMessage.Key.REQUIRED_HEADER_MISSING, ResponseMessage.Message.REQUIRED_HEADER_MISSING), - errorProcessingFile( - ResponseMessage.Key.ERROR_PROCESSING_FILE, ResponseMessage.Message.ERROR_PROCESSING_FILE), - errorInvalidParameterSize( - ResponseMessage.Key.ERROR_INVALID_PARAMETER_SIZE, - ResponseMessage.Message.ERROR_INVALID_PARAMETER_SIZE), - errorInvalidPageSection( - ResponseMessage.Key.INVALID_PAGE_SECTION, ResponseMessage.Message.INVALID_PAGE_SECTION), - errorRateLimitExceeded( - ResponseMessage.Key.ERROR_RATE_LIMIT_EXCEEDED, - ResponseMessage.Message.ERROR_RATE_LIMIT_EXCEEDED), - invalidRequestTimeout( - ResponseMessage.Key.INVALID_REQUEST_TIMEOUT, ResponseMessage.Message.INVALID_REQUEST_TIMEOUT), - invalidIdentifier( - ResponseMessage.Key.VALID_IDENTIFIER_ABSENSE, - ResponseMessage.Message.IDENTIFIER_VALIDATION_FAILED), - fromAccountIdRequired( - ResponseMessage.Key.FROM_ACCOUNT_ID_MISSING, ResponseMessage.Message.FROM_ACCOUNT_ID_MISSING), - toAccountIdRequired( - ResponseMessage.Key.TO_ACCOUNT_ID_MISSING, ResponseMessage.Message.TO_ACCOUNT_ID_MISSING), - fromAccountIdNotExists( - ResponseMessage.Key.FROM_ACCOUNT_ID_NOT_EXISTS, - ResponseMessage.Message.FROM_ACCOUNT_ID_NOT_EXISTS), - mandatoryHeaderParamsMissing( - ResponseMessage.Key.MANDATORY_HEADER_PARAMETER_MISSING, - ResponseMessage.Message.MANDATORY_HEADER_PARAMETER_MISSING), - errorUserHasNotCreatedAnyCourse( - ResponseMessage.Key.ERROR_USER_HAS_NOT_CREATED_ANY_COURSE, - ResponseMessage.Message.ERROR_USER_HAS_NOT_CREATED_ANY_COURSE), - errorUploadQRCodeCSVfailed( - ResponseMessage.Key.ERROR_UPLOAD_QRCODE_CSV_FAILED, - ResponseMessage.Message.ERROR_UPLOAD_QRCODE_CSV_FAILED), - errorNoDialcodesLinked( - ResponseMessage.Key.ERROR_NO_DIALCODES_LINKED, - ResponseMessage.Message.ERROR_NO_DIALCODES_LINKED), - eventsRequired( - ResponseMessage.Key.EVENTS_DATA_MISSING, ResponseMessage.Message.EVENTS_DATA_MISSING), - accountNotFound(ResponseMessage.Key.ACCOUNT_NOT_FOUND, ResponseMessage.Message.ACCOUNT_NOT_FOUND), - userMigrationFiled( - ResponseMessage.Key.USER_MIGRATION_FAILED, ResponseMessage.Message.USER_MIGRATION_FAILED), - invalidUserExternalId( - ResponseMessage.Key.INVALID_EXT_USER_ID, ResponseMessage.Message.INVALID_EXT_USER_ID), - invalidElementInList( - ResponseMessage.Key.INVALID_ELEMENT_IN_LIST, ResponseMessage.Message.INVALID_ELEMENT_IN_LIST), - passwordValidation( - ResponseMessage.Key.INVALID_PASSWORD, ResponseMessage.Message.INVALID_PASSWORD), - otpVerificationFailed( - ResponseMessage.Key.OTP_VERIFICATION_FAILED, ResponseMessage.Message.OTP_VERIFICATION_FAILED), - serviceUnAvailable( - ResponseMessage.Key.SERVICE_UNAVAILABLE, ResponseMessage.Message.SERVICE_UNAVAILABLE), - missingData( - ResponseMessage.Key.MISSING_CODE, ResponseMessage.Message.MISSING_MESSAGE), - contentTypeMismatch( - ResponseMessage.Key.CONTENT_TYPE_MISMATCH, ResponseMessage.Message.CONTENT_TYPE_MISMATCH), - mimeTypeMismatch( - ResponseMessage.Key.MIME_TYPE_MISMATCH, ResponseMessage.Message.MIME_TYPE_MISMATCH), - groupIdMismatch(ResponseMessage.Key.GROUP_ID_MISSING, ResponseMessage.Message.GROUP_ID_MISSING), - activityIdMismatch(ResponseMessage.Key.ACTIVITY_ID_MISSING, ResponseMessage.Message.ACTIVITY_ID_MISSING), - activityTypeMismatch(ResponseMessage.Key.ACTIVITY_TYPE_MISSING, ResponseMessage.Message.ACTIVITY_TYPE_MISSING), - erroCallGrooupAPI(ResponseMessage.Key.ERR_CALLING_GROUP_API, ResponseMessage.Message.ERR_CALLING_GROUP_API), + // ------------------------------------------------------------------------- + // HTTP Status Codes & System Codes + // ------------------------------------------------------------------------- OK(200), CLIENT_ERROR(400), SERVER_ERROR(500), @@ -738,6 +788,7 @@ public enum ResponseCode { TOO_MANY_REQUESTS(429), SERVICE_UNAVAILABLE(503), PARTIAL_SUCCESS_RESPONSE(206); + private int responseCode; /** error code contains String value */ private String errorCode; @@ -745,14 +796,23 @@ public enum ResponseCode { private String errorMessage; /** - * @param errorCode String - * @param errorMessage String + * Constructor for ResponseCode with errorCode and errorMessage. + * + * @param errorCode String - The unique error code identifier. + * @param errorMessage String - The human-readable error message. */ private ResponseCode(String errorCode, String errorMessage) { this.errorCode = errorCode; this.errorMessage = errorMessage; } + /** + * Constructor for ResponseCode with errorCode, errorMessage, and HTTP responseCode. + * + * @param errorCode String - The unique error code identifier. + * @param errorMessage String - The human-readable error message. + * @param responseCode int - The HTTP status code associated with this error. + */ private ResponseCode(String errorCode, String errorMessage, int responseCode) { this.errorCode = errorCode; this.errorMessage = errorMessage; @@ -760,38 +820,83 @@ private ResponseCode(String errorCode, String errorMessage, int responseCode) { } /** - * @param errorCode - * @return + * Constructor for ResponseCode with just HTTP responseCode. + * + * @param responseCode int - The HTTP status code. */ - public String getMessage(int errorCode) { - return ""; + ResponseCode(int responseCode) { + this.responseCode = responseCode; } - /** @return */ + /** + * Gets the error code identifier. + * + * @return String - The error code. + */ public String getErrorCode() { return errorCode; } - /** @param errorCode */ + /** + * Sets the error code identifier. + * + * @param errorCode String - The error code to set. + */ public void setErrorCode(String errorCode) { this.errorCode = errorCode; } - /** @return */ + /** + * Gets the human-readable error message. + * + * @return String - The error message. + */ public String getErrorMessage() { return errorMessage; } - /** @param errorMessage */ + /** + * Sets the human-readable error message. + * + * @param errorMessage String - The error message to set. + */ public void setErrorMessage(String errorMessage) { this.errorMessage = errorMessage; } /** - * This method will provide status message based on code + * Gets the HTTP response code. + * + * @return int - The HTTP status code. + */ + public int getResponseCode() { + return responseCode; + } + + /** + * Sets the HTTP response code. + * + * @param responseCode int - The HTTP status code to set. + */ + public void setResponseCode(int responseCode) { + this.responseCode = responseCode; + } + + /** + * Placeholder for retrieving message by error code. Currently returns empty string. + * + * @param errorCode int + * @return String - Empty string. + */ + public String getMessage(int errorCode) { + return ""; + } + + /** + * Retrieves the error message associated with a given error code string. * - * @param code - * @return String + * @param code String - The error code to look up. + * @return String - The corresponding error message, or an empty string if not found. */ public static String getResponseMessage(String code) { if (StringUtils.isBlank(code)) { @@ -806,24 +911,12 @@ public static String getResponseMessage(String code) { return ""; } - ResponseCode(int responseCode) { - this.responseCode = responseCode; - } - - public int getResponseCode() { - return responseCode; - } - - public void setResponseCode(int responseCode) { - this.responseCode = responseCode; - } - /** - * This method will take header response code as int value and it provide matched enum value, if - * code is not matched or exception occurs then it will provide SERVER_ERROR + * Maps an integer HTTP status code to a ResponseCode enum. + * If the code is not found or an error occurs, returns SERVER_ERROR. * - * @param code int - * @return HeaderResponseCode + * @param code int - The HTTP status code. + * @return ResponseCode - The matching ResponseCode enum value. */ public static ResponseCode getHeaderResponseCode(int code) { if (code > 0) { @@ -842,10 +935,11 @@ public static ResponseCode getHeaderResponseCode(int code) { } /** - * This method will provide ResponseCode enum based on error code + * Retrieves the ResponseCode enum based on the error code string. + * Handles special cases like "UNAUTHORIZED" mapping to "unAuthorized" enum. * - * @param errorCode - * @return String + * @param errorCode String - The error code string. + * @return ResponseCode - The matching ResponseCode enum, or null if not found. */ public static ResponseCode getResponse(String errorCode) { if (StringUtils.isBlank(errorCode)) { diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/responsecode/ResponseMessage.java b/core/sunbird-platform-common/src/main/java/org/sunbird/response/ResponseMessage.java similarity index 89% rename from course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/responsecode/ResponseMessage.java rename to core/sunbird-platform-common/src/main/java/org/sunbird/response/ResponseMessage.java index b17248105..edc01421e 100644 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/responsecode/ResponseMessage.java +++ b/core/sunbird-platform-common/src/main/java/org/sunbird/response/ResponseMessage.java @@ -1,306 +1,420 @@ -package org.sunbird.common.responsecode; +package org.sunbird.response; /** - * This interface will hold all the response key and message + * This interface holds all the response keys and messages, logically grouped by functionality. * - * @author Manzarul */ public interface ResponseMessage { interface Message { - String UNAUTHORIZED_USER = "You are not authorized."; - String INVALID_USER_CREDENTIALS = "Please check your credentials"; + // ------------------------------------------------------------------------- + // Generic / Common Messages + // ------------------------------------------------------------------------- + String SUCCESS_MESSAGE = "Success"; + String INTERNAL_ERROR = "Process failed,please try again later."; String OPERATION_TIMEOUT = "Request processing taking too long time. Please try again later."; String INVALID_OPERATION_NAME = "Operation name is invalid. Please provide a valid operation name"; String INVALID_REQUESTED_DATA = "Requested data for this operation is not valid."; - String CONTENT_ID_MISSING_ERROR = "Please provide content id."; - String COURSE_ID_MISSING_ERROR = "Please provide course id."; + String INVALID_DATA = "Incorrect data."; + String DATA_TYPE_ERROR = "Data type of {0} should be {1}."; + String ID_REQUIRED_ERROR = "For deleting a record, Id is required."; + String MANDATORY_PARAMETER_MISSING = "Mandatory parameter {0} is missing."; + String ERROR_MANDATORY_PARAMETER_EMPTY = "Mandatory parameter {0} is empty."; + String INVALID_PARAMETER_VALUE = + "Invalid value {0} for parameter {1}. Please provide a valid value."; + String INVALID_PARAMETER = "Please provide valid {0}."; + String INVALID_REQUEST_PARAMETER = "Invalid request parameter {0}."; + String IDENTIFIER_VALIDATION_FAILED = "Identifier validation failed for {0}."; + String INVALID_VALUE = "Invalid {0}: {1}. Valid values are: {2}."; + String ALREADY_EXISTS = "A {0} with {1} already exists. Please retry with a unique value."; + String RESOURCE_NOT_FOUND = "Requested resource not found"; + String CUSTOM_SERVER_ERROR = "{0}"; + String MAX_ALLOWED_SIZE_LIMIT_EXCEED = "Max allowed size is {0}"; + String UNABLE_TO_PARSE_DATA = "Unable to parse the data"; + String INVALID_JSON = "Unable to process object to JSON/ JSON to Object"; + String NO_DATA = "You have uploaded an empty file. Fill mandatory details and upload the file."; + String INVALID_DATE_FORMAT = + "Invalid Date format . Date format should be : yyyy-MM-dd hh:mm:ss:SSSZ"; + String DATE_FORMAT_ERRROR = "Date format error."; + String INVALID_PROPERTY_ERROR = "Invalid property {0}."; + String INVALID_OBJECT_TYPE = "Invalid Object Type."; + String PROCESS_EXE_TIMEOUT = "PROCESS_EXE_TIMEOUT"; + String DATA_ALREADY_EXIST = "data already exist."; + String SERVICE_UNAVAILABLE = "SERVICE UNAVAILABLE"; + String OR_FORMAT = "{0} or {1}"; + String AND_FORMAT = "{0} and {1}"; + String NOT_SUPPORTED = "Not Supported."; + String ERROR_UNSUPPORTED_FIELD = "Unsupported field {0}."; + String INVALID_ELEMENT_IN_LIST = + "Invalid value supplied for parameter {0}.Supported values are {1}"; + String ERROR_RATE_LIMIT_EXCEEDED = + "Your per {0} rate limit has exceeded. You can retry after some time."; + String INVALID_REQUEST_TIMEOUT = "Invalid request timeout value {0}."; + + // ------------------------------------------------------------------------- + // Authentication & Authorization + // ------------------------------------------------------------------------- + String UNAUTHORIZED_USER = "You are not authorized."; + String INVALID_USER_CREDENTIALS = "Please check your credentials"; String API_KEY_MISSING_ERROR = "APi key is mandatory."; String API_KEY_INVALID_ERROR = "APi key is invalid."; - String INTERNAL_ERROR = "Process failed,please try again later."; - String COURSE_NAME_MISSING = "Please provide the course name."; - String SUCCESS_MESSAGE = "Success"; String SESSION_ID_MISSING = "Session id is mandatory."; - String COURSE_ID_MISSING = "Course id is mandatory."; - String CONTENT_ID_MISSING = "Content id is mandatory."; - String VERSION_MISSING = "Version is mandatory."; - String COURSE_VERSION_MISSING = "Course version is mandatory."; - String CONTENT_VERSION_MISSING = "Content version is mandatory."; - String COURSE_DESCRIPTION_MISSING = "Description is mandatory."; - String COURSE_TOCURL_MISSING = "Course tocurl is mandatory."; - String EMAIL_MISSING = "Email is mandatory."; - String EMAIL_FORMAT = "Email is invalid."; - String URL_FORMAT_ERROR = "URL is invalid."; + String AUTH_TOKEN_MISSING = "Auth token is mandatory."; + String INVALID_AUTH_TOKEN = "Auth token is invalid.Please login again."; + String INVALID_ROLE = "Invalid role value provided in request."; + String INVALID_SALT = "Please provide salt value."; + String KEY_CLOAK_DEFAULT_ERROR = "server error at sso."; + String OTP_VERIFICATION_FAILED = "OTP verification failed. Remaining attempt count is {0}."; + String ERROR_INVALID_OTP = "Invalid OTP."; + String FORBIDDEN = "You are forbidden from accessing specified resource."; + + // ------------------------------------------------------------------------- + // User Management + // ------------------------------------------------------------------------- + String USER_NOT_FOUND = "user not found."; + String USER_ALREADY_EXISTS = "User already exists for given {0}."; + String INVALID_USER_ID = "User Id does not exists in our records"; + String USERID_MISSING = "UserId is mandatory."; + String USERNAME_MISSING = "Username is mandatory."; String FIRST_NAME_MISSING = "First name is mandatory."; - String LANGUAGE_MISSING = "Language is mandatory."; + String EMAIL_MISSING = "Email is mandatory."; + String PHONE_NO_REQUIRED_ERROR = "Phone number is required."; String PASSWORD_MISSING = "Password is mandatory."; - String ERROR_INVALID_CONFIG_PARAM_VALUE = "Invalid value {0} for config parameter {1}."; - String ERROR_MAX_SIZE_EXCEEDED = "Size of {0} exceeds max limit {1}"; + String INVALID_PASSWORD = + "Password must contain a minimum of 8 characters including numerals, lower and upper case alphabets and special characters"; String PASSWORD_MIN_LENGHT = "Password should have at least 8 character."; String PASSWORD_MAX_LENGHT = "Password should not be more than 12 character."; - String ORGANISATION_ID_MISSING = "Organization id is mandatory."; - String REQUIRED_DATA_ORG_MISSING = - "Organization Id or Provider with External Id values are required for the operation"; - String ORGANISATION_NAME_MISSING = "organization name is mandatory."; - String CHANNEL_SHOULD_BE_UNIQUE = - "Channel value already used by another organization. Provide different value for channel"; - String ERROR_DUPLICATE_ENTRY = "Value {0} for {1} is already in use."; - String INVALID_ORG_DATA = - "Given Organization Data doesn't exist in our records. Please provide a valid one"; - String INVALID_USR_DATA = - "Given User Data doesn't exist in our records. Please provide a valid one"; - String USR_DATA_VALIDATION_ERROR = "Please provide valid userId or userName and provider"; - String INVALID_ROOT_ORGANIZATION = "Root organization id is invalid"; - String INVALID_PARENT_ORGANIZATION_ID = "Parent organization id is invalid"; - String CYCLIC_VALIDATION_FAILURE = "The relation cannot be created as it is cyclic"; - String ENROLLMENT_START_DATE_MISSING = "Enrollment start date is mandatory."; - String COURSE_DURATION_MISSING = "Course duration is mandatory."; - String LOGIN_TYPE_MISSING = "Login type is required."; - String ERROR_INVALID_OTP = "Invalid OTP."; + String USERNAME_IN_USE = "Username already exists."; String EMAIL_IN_USE = "Email already exists."; - String USERNAME_EMAIL_IN_USE = - "Username or Email is already in use. Please try with a different Username or Email."; - String KEY_CLOAK_DEFAULT_ERROR = "server error at sso."; + String PHONE_ALREADY_IN_USE = "Phone already in use. Please provide different phone number."; + String USER_ACCOUNT_BLOCKED = "User account has been blocked ."; + String USER_ALREADY_ACTIVE = "User is already active."; + String USER_ALREADY_INACTIVE = "User is already inactive."; String USER_REG_UNSUCCESSFUL = "User Registration unsuccessful."; String USER_UPDATE_UNSUCCESSFUL = "User update operation is unsuccessful."; - String INVALID_CREDENTIAL = "Invalid credential."; - String USERNAME_MISSING = "Username is mandatory."; - String USERNAME_IN_USE = "Username already exists."; - String USERID_MISSING = "UserId is mandatory."; - String ROLE_MISSING = "Role of the user is required"; - String MESSAGE_ID_MISSING = "Message id is mandatory."; + String USER_PHONE_UPDATE_FAILED = "user phone update is failed."; + String USER_MIGRATION_FAILED = "user is failed to migrate"; + String USER_DATA_ENCRYPTION_ERROR = "Exception Occurred while encrypting user data."; + String INVALID_EXT_USER_ID = "provided ext user id {0} is incorrect"; + String EXTERNALID_NOT_FOUND = + "External ID (id: {0}, idType: {1}, provider: {2}) not found for given user."; + String EXTERNALID_ASSIGNED_TO_OTHER_USER = + "External ID (id: {0}, idType: {1}, provider: {2}) already assigned to another user."; + String DUPLICATE_EXTERNAL_IDS = + "Duplicate external IDs for given idType ({0}) and provider ({1})."; + String USERNAME_EMAIL_IN_USE = + "Username or Email is already in use. Please try with a different Username or Email."; String USERNAME_CANNOT_BE_UPDATED = "UserName cann't be updated."; - String AUTH_TOKEN_MISSING = "Auth token is mandatory."; - String INVALID_AUTH_TOKEN = "Auth token is invalid.Please login again."; - String TIMESTAMP_REQUIRED = "TimeStamp is required."; - String PUBLISHED_COURSE_CAN_NOT_UPDATED = "Published course can't be updated."; - String SOURCE_MISSING = "Source is required."; - String SECTION_NAME_MISSING = "Section name is required."; - String SECTION_DATA_TYPE_MISSING = "Section data type missing."; - String SECTION_ID_REQUIRED = "Section id is required."; - String PAGE_NAME_REQUIRED = "Page name is required."; - String PAGE_ID_REQUIRED = "Page id is required."; - String INVALID_CONFIGURATION = "Invalid configuration data."; - String ASSESSMENT_ITEM_ID_REQUIRED = "Assessment item id is required."; - String ASSESSMENT_TYPE_REQUIRED = "Assessment type is required."; - String ATTEMPTED_DATE_REQUIRED = "Attempted data is required."; - String ATTEMPTED_ANSWERS_REQUIRED = "Attempted answers is required."; - String MAX_SCORE_REQUIRED = "Max score is required."; - String STATUS_CANNOT_BE_UPDATED = "status cann't be updated."; - String ATTEMPT_ID_MISSING_ERROR = "Please provide attempt id."; + String CONFIIRM_PASSWORD_MISSING = "Confirm password is mandatory."; + String CONFIIRM_PASSWORD_EMPTY = "Confirm password can not be empty."; + String SAME_PASSWORD_ERROR = "New password can't be same as old password."; + String EMAIL_VERIFY_ERROR = "Please provide a verified email in order to create user."; + String PHONE_VERIFY_ERROR = + "Please provide a verified phone number in order to create/update user."; + String LOGIN_TYPE_MISSING = "Login type is required."; String LOGIN_TYPE_ERROR = "provide login type as null."; + String LOGIN_ID_MISSING = "loginId is required."; + String USER_NAME_OR_ID_ERROR = "Please provide either username or userId."; + String USERNAME_USERID_MISSING = "Please provide either userName or userId."; + String ROLES_MISSING = "user role is required."; + String EMPTY_ROLES_PROVIDED = "Roles cannot be empty."; + String ROLE_MISSING = "Role of the user is required"; + String INVALID_VISIBILITY_REQUEST = "Private and Public fields cannot be same."; String ADDRESS_REQUIRED_ERROR = "Please provide address."; String EDUCATION_REQUIRED_ERROR = "Please provide education details."; String JOBDETAILS_REQUIRED_ERROR = "Please provide job details."; - String DB_INSERTION_FAIL = "DB insert operation failed."; - String DB_UPDATE_FAIL = "Db update operation failed."; - String DATA_ALREADY_EXIST = "data already exist."; - String INVALID_DATA = "Incorrect data."; - String INVALID_COURSE_ID = "Course doesnot exist. Please provide a valid course identifier"; - String PHONE_NO_REQUIRED_ERROR = "Phone number is required."; - String ORG_ID_MISSING = "Organization Id required."; - String ACTOR_CONNECTION_ERROR = "Service is not able to connect with actor."; - String USER_ALREADY_EXISTS = "User already exists for given {0}."; - String PAGE_ALREADY_EXIST = "page already exist with this Page Name and Org Code."; - String INVALID_USER_ID = "User Id does not exists in our records"; - String LOGIN_ID_MISSING = "loginId is required."; - String CONTENT_STATUS_MISSING_ERROR = "content status is required ."; - String ES_ERROR = "Something went wrong when processing data for search"; - String INVALID_PERIOD = "Time Period is invalid"; - String USER_NOT_FOUND = "user not found."; - String ID_REQUIRED_ERROR = "For deleting a record, Id is required."; - 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 ADDRESS_ERROR = "In {0}, {1} is mandatory."; String ADDRESS_TYPE_ERROR = "Please provide correct address Type."; String NAME_OF_INSTITUTION_ERROR = "Please provide name of Institution."; String EDUCATION_DEGREE_ERROR = "Education degree is required."; String JOB_NAME_ERROR = "Job Name is required."; - String NAME_OF_ORGANISATION_ERROR = "Organization Name is required."; - String ROLES_MISSING = "user role is required."; - String EMPTY_ROLES_PROVIDED = "Roles cannot be empty."; - String CHANNEL_REG_FAILED = "Channel Registration failed."; - String INVALID_COURSE_CREATOR_ID = "Course creator id does not exist ."; + String INVALID_USR_DATA = + "Given User Data doesn't exist in our records. Please provide a valid one"; + String USR_DATA_VALIDATION_ERROR = "Please provide valid userId or userName and provider"; + String INVALID_USR_ORG_DATA = + "Given User Data doesn't belongs to this organization. Please provide a valid one."; + String USER_NOT_BELONGS_TO_ANY_ORG = "User does not belongs to any org ."; + String USER_ORG_ASSOCIATION_ERROR = "User is already associated with another organization."; + String ERROR_USER_HAS_NOT_CREATED_ANY_COURSE = + "User hasn't created any course, or may not have a creator role"; String USER_NOT_ASSOCIATED_TO_ROOT_ORG = "User (ID = {0}) not associated to course batch creator root org."; + String INVALID_CREDENTIAL = "Invalid credential."; + String EMAIL_FORMAT = "Email is invalid."; + String URL_FORMAT_ERROR = "URL is invalid."; + String LANGUAGE_MISSING = "Language is mandatory."; + String TIMESTAMP_REQUIRED = "TimeStamp is required."; + String INVALID_PHONE_NO_FORMAT = "Please provide a valid phone number."; + String INVALID_PHONE_NUMBER = "Please send Phone and country code seprately."; + String INVALID_COUNTRY_CODE = "Please provide a valid country code."; + String EMAIL_OR_PHONE_MISSING = "Please provide either email or phone."; + String ACCOUNT_NOT_FOUND = "Account not found."; + String FROM_ACCOUNT_ID_MISSING = "From Account id is mandatory."; + String TO_ACCOUNT_ID_MISSING = "To Account id is mandatory."; + String FROM_ACCOUNT_ID_NOT_EXISTS = "From Account id not exists"; + + // ------------------------------------------------------------------------- + // Organization Management + // ------------------------------------------------------------------------- + String ORG_NOT_EXIST = "Requested organisation does not exist."; + String INVALID_ORG_DATA = + "Given Organization Data doesn't exist in our records. Please provide a valid one"; + String ORGANISATION_ID_MISSING = "Organization id is mandatory."; + String ORG_ID_MISSING = "Organization Id required."; + String ORGANISATION_NAME_MISSING = "organization name is mandatory."; + String NAME_OF_ORGANISATION_ERROR = "Organization Name is required."; + String ROOT_ORG_ID_REQUIRED = "Please provide root organisation ID."; + String REQUIRED_DATA_ORG_MISSING = + "Organization Id or Provider with External Id values are required for the operation"; + String INVALID_ROOT_ORGANIZATION = "Root organization id is invalid"; + String INVALID_PARENT_ORGANIZATION_ID = "Parent organization id is invalid"; + String PARENT_CODE_AND_PARENT_ID_MISSING = "Please provide either parentCode or parentId."; + String INVALID_ORG_ID = "Please provide valid location id."; // Note: Check context, might be generic org id + String INVALID_ORG_STATUS = "INVALID_ORG_STATUS"; + String INVALID_ORG_STATUS_TRANSITION = "INVALID_ORG_STATUS_TRANSITION"; + String ORG_TYPE_MANDATORY = "Org Type name is mandatory."; + String ORG_TYPE_ALREADY_EXIST = + "Org type with this name already exist.Please provide some other name."; + String ORG_TYPE_ID_REQUIRED_ERROR = "Org Type Id is required."; + String INVALID_ORG_TYPE_ID_ERROR = "Please provide valid orgTypeId."; + String INVALID_ORG_TYPE_ERROR = "Please provide valid orgType."; + String ERROR_INACTIVE_ORG = "Organisation corresponding to given {0} ({1}) is inactive."; + String ERROR_NO_ROOT_ORG_ASSOCIATED = "Not able to associate with root org"; + String ERROR_INACTIVE_CUSTODIAN_ORG = "Custodian organisation is inactive."; + String ROOT_ORG_ASSOCIATION_ERROR = + "No root organisation found which is associated with given {0}."; + String INVALID_ROOT_ORG_DATA = + "Root org doesn't exist for this Organization Id and channel {0}"; + String CHANNEL_SHOULD_BE_UNIQUE = + "Channel value already used by another organization. Provide different value for channel"; + String INVALID_CHANNEL = "Channel value is invalid."; + String CHANNEL_REG_FAILED = "Channel Registration failed."; String SLUG_IS_NOT_UNIQUE = "Please provide different channel value. This channel value already exist."; - String INVALID_DATE_FORMAT = - "Invalid Date format . Date format should be : yyyy-MM-dd hh:mm:ss:SSSZ"; - String SRC_EXTERNAL_ID_ALREADY_EXIST = "PROVIDER WITH EXTERNAL ID ALREADY EXIST ."; - String USER_ALREADY_ENROLLED_COURSE = "User has already Enrolled this course ."; - String USER_NOT_ENROLLED_COURSE = "User is not enrolled to given course batch."; - String USER_ALREADY_COMPLETED_COURSE = "User already completed given course batch."; + String SLUG_REQUIRED = "Slug is required ."; + String CONFLICTING_ORG_LOCATIONS = + "An organisation cannot be associated to two conflicting locations ({0}, {1}) at {2} level. "; + String INVALID_LOCATION_ID = "Please provide valid location id."; + String LOCATION_ID_REQUIRED = "Please provide Location Id."; + String LOCATION_TYPE_REQUIRED = "Location type required."; + String INVALID_REQUEST_DATA_FOR_LOCATION = "{0} field required."; + String INVALID_LOCATION_DELETE_REQUEST = + "One or more locations have a parent reference to given location and hence cannot be deleted."; + String LOCATION_TYPE_CONFLICTS = "Location type conflicts with its parent location type."; + String PARENT_NOT_ALLOWED = "For top level location, {0} is not allowed."; + String INVALID_HASHTAG_ID = + "Please provide different hashTagId.This HashTagId is associated with some other organization."; + + // ------------------------------------------------------------------------- + // Course & Batch Management + // ------------------------------------------------------------------------- + String COURSE_ID_MISSING_ERROR = "Please provide course id."; + String COURSE_ID_MISSING = "Course id is mandatory."; + String INVALID_COURSE_ID = "Course doesnot exist. Please provide a valid course identifier"; + String COURSE_NAME_MISSING = "Please provide the course name."; + String COURSE_DESCRIPTION_MISSING = "Description is mandatory."; + String COURSE_VERSION_MISSING = "Course version is mandatory."; + String COURSE_DURATION_MISSING = "Course duration is mandatory."; + String COURSE_TOCURL_MISSING = "Course tocurl is mandatory."; + String COURSE_CREATED_FOR_NULL = "Batch does not belong to any organization ."; + String COURSE_BATCH_ID_MISSING = "Course batch Id required"; + String INVALID_COURSE_BATCH_ID = "Invalid course batch id "; String COURSE_BATCH_ALREADY_COMPLETED = "Course batch is already completed."; String COURSE_BATCH_ENROLLMENT_DATE_ENDED = "Course batch enrollment date has ended."; - String CONTENT_TYPE_ERROR = "Please add Content-Type header with value application/json"; - String INVALID_PROPERTY_ERROR = "Invalid property {0}."; - String USER_NAME_OR_ID_ERROR = "Please provide either username or userId."; - String USER_ACCOUNT_BLOCKED = "User account has been blocked ."; - String EMAIL_VERIFY_ERROR = "Please provide a verified email in order to create user."; - String PHONE_VERIFY_ERROR = - "Please provide a verified phone number in order to create/update user."; - String BULK_USER_UPLOAD_ERROR = - "Please provide either organization Id or external Id & provider value."; - String DATA_SIZE_EXCEEDED = "Maximum upload data size should be {0}"; - String INVALID_COLUMN_NAME = "Invalid column name."; - String USER_ALREADY_ACTIVE = "User is already active."; - String USER_ALREADY_INACTIVE = "User is already inactive."; - String ENROLMENT_TYPE_REQUIRED = "Enrolment type is mandatory."; - String ENROLMENT_TYPE_VALUE_ERROR = "EnrolmentType value must be either open or invite-only."; String COURSE_BATCH_START_DATE_REQUIRED = "Batch start date is mandatory."; String COURSE_BATCH_START_DATE_INVALID = "Batch start date should be either today or future date."; - String DATE_FORMAT_ERRROR = "Date format error."; - String END_DATE_ERROR = "End date should be greater than start date."; + String COURSE_BATCH_END_DATE_ERROR = "Batch has been closed."; + String COURSE_BATCH_IS_CLOSED_ERROR = "Batch has been closed."; + String COURSE_BATCH_START_PASSED_DATE_INVALID = "This Batch already started."; + String INVALID_BATCH_START_DATE_ERROR = "Please provide valid Start Date."; + String INVALID_BATCH_END_DATE_ERROR = "Please provide valid End Date."; + String MULTIPLE_COURSES_FOR_BATCH = "A batch cannot belong to multiple courses."; + String INVALID_COURSE_CREATOR_ID = "Course creator id does not exist ."; + String ENROLLMENT_START_DATE_MISSING = "Enrollment start date is mandatory."; String ENROLLMENT_END_DATE_START_ERROR = "Enrollment End date should be greater than course batch start date."; String ENROLLMENT_END_DATE_END_ERROR = "Enrollment End date should be lesser than course batch end date."; String ENROLLMENT_END_DATE_UPDATE_ERROR = "Invalid Enrollment End date. Please provide future date."; - String INVALID_CSV_FILE = "Please provide valid csv file."; - String INVALID_COURSE_BATCH_ID = "Invalid course batch id "; - String COURSE_BATCH_ID_MISSING = "Course batch Id required"; + String ENROLMENT_TYPE_REQUIRED = "Enrolment type is mandatory."; + String ENROLMENT_TYPE_VALUE_ERROR = "EnrolmentType value must be either open or invite-only."; String ENROLLMENT_TYPE_VALIDATION = "Enrollment type should be invite-only."; - String USER_NOT_BELONGS_TO_ANY_ORG = "User does not belongs to any org ."; - String INVALID_OBJECT_TYPE = "Invalid Object Type."; + String USER_ALREADY_ENROLLED_COURSE = "User has already Enrolled this course ."; + String USER_NOT_ENROLLED_COURSE = "User is not enrolled to given course batch."; + String USER_ALREADY_COMPLETED_COURSE = "User already completed given course batch."; + String END_DATE_ERROR = "End date should be greater than start date."; + String PUBLISHED_COURSE_CAN_NOT_UPDATED = "Published course can't be updated."; String INVALID_PROGRESS_STATUS = "Progress status value should be NOT_STARTED(0), STARTED(1), COMPLETED(2)."; - String COURSE_CREATED_FOR_NULL = "Batch does not belong to any organization ."; - String COURSE_BATCH_START_PASSED_DATE_INVALID = "This Batch already started."; - String UNABLE_TO_CONNECT_TO_EKSTEP = "Unable to connect to Ekstep Server"; - String UNABLE_TO_CONNECT_TO_ES = "Unable to connect to Elastic Search"; - String UNABLE_TO_PARSE_DATA = "Unable to parse the data"; - String INVALID_JSON = "Unable to process object to JSON/ JSON to Object"; - String EMPTY_CSV_FILE = "CSV file is Empty."; - String INVALID_ROOT_ORG_DATA = - "Root org doesn't exist for this Organization Id and channel {0}"; - String NO_DATA = "You have uploaded an empty file. Fill mandatory details and upload the file."; - String INVALID_CHANNEL = "Channel value is invalid."; - String INVALID_PROCESS_ID = "Invalid Process Id."; - String EMAIL_SUBJECT_ERROR = "Email Subject is mandatory."; - String EMAIL_BODY_ERROR = "Email Body is mandatory."; + String MISSING_MESSAGE = "Required fields for create course are missing. {0}"; + String CONTENT_TYPE_MISMATCH = "Content Type should be Course."; + String MIME_TYPE_MISMATCH = "MimeType should be application/vnd.ekstep.content-collection"; + + // ------------------------------------------------------------------------- + // Content & Assessment + // ------------------------------------------------------------------------- + String CONTENT_ID_MISSING_ERROR = "Please provide content id."; + String CONTENT_ID_MISSING = "Content id is mandatory."; + String CONTENT_ID_ERROR = "Please provide content id or course id"; + String CONTENT_VERSION_MISSING = "Content version is mandatory."; + String VERSION_MISSING = "Version is mandatory."; + String CONTENT_STATUS_MISSING_ERROR = "content status is required ."; + String CONTENT_TYPE_ERROR = "Please add Content-Type header with value application/json"; + String ASSESSMENT_ITEM_ID_REQUIRED = "Assessment item id is required."; + String ASSESSMENT_TYPE_REQUIRED = "Assessment type is required."; + String ATTEMPTED_DATE_REQUIRED = "Attempted data is required."; + String ATTEMPTED_ANSWERS_REQUIRED = "Attempted answers is required."; + String MAX_SCORE_REQUIRED = "Max score is required."; + String ATTEMPT_ID_MISSING_ERROR = "Please provide attempt id."; + + // ------------------------------------------------------------------------- + // Badge/Certificates (Issuer, Recipient, Assertion) + // ------------------------------------------------------------------------- + String ISSUER_ID_REQUIRED = "Please provide issuer ID."; + String INVALID_ISSUER_ID = "Invalid issuer ID."; + String RECIPIENT_ID_REQUIRED = "Please provide a recipient id."; + String RECIPIENT_TYPE_REQUIRED = "Please provide recipient type."; + String INVALID_RECIPIENT_TYPE = "Please provide a valid recipient type."; + String RECIPIENT_EMAIL_REQUIRED = "Please provide recipient email."; String RECIPIENT_ADDRESS_ERROR = "Please send recipientEmails or recipientUserIds."; - String STORAGE_CONTAINER_NAME_MANDATORY = " Container name can not be null or empty."; - String CLOUD_SERVICE_ERROR = "Cloud storage service error."; String RECEIVER_ID_ERROR = "Receiver id is mandatory."; String INVALID_RECEIVER_ID = "Receiver id is invalid."; - String USER_ORG_ASSOCIATION_ERROR = "User is already associated with another organization."; - String INVALID_ROLE = "Invalid role value provided in request."; - String INVALID_SALT = "Please provide salt value."; - String ORG_TYPE_MANDATORY = "Org Type name is mandatory."; - String ORG_TYPE_ALREADY_EXIST = - "Org type with this name already exist.Please provide some other name."; - String ORG_TYPE_ID_REQUIRED_ERROR = "Org Type Id is required."; - String TITLE_REQUIRED = "Title is required"; - String NOTE_REQUIRED = "No data to store for notes"; - String CONTENT_ID_ERROR = "Please provide content id or course id"; - String INVALID_TAGS = "Invalid data for tags"; - String NOTE_ID_INVALID = "Invalid note id"; - String USER_DATA_ENCRYPTION_ERROR = "Exception Occurred while encrypting user data."; - String INVALID_PHONE_NO_FORMAT = "Please provide a valid phone number."; + String ASSERTION_ID_REQUIRED = "Please provide assertion ID."; + String ASSERTION_EVIDENCE_REQUIRED = "Please provide valid assertion url as an evidence."; + String REVOCATION_REASON_REQUIRED = "Please provide revocation reason."; + String ENDORSED_USER_ID_REQUIRED = " Endorsed user id required ."; + String CAN_NOT_ENDORSE = "Can not endorse since both belong to different orgs ."; + + // ------------------------------------------------------------------------- + // Notifications & Email + // ------------------------------------------------------------------------- + String EMAIL_SUBJECT_ERROR = "Email Subject is mandatory."; + String EMAIL_BODY_ERROR = "Email Body is mandatory."; + String EMAIL_RECIPIENTS_EXCEEDS_MAX_LIMIT = + "Email notification is not sent as the number of recipients exceeded configured limit ({0})."; + String NO_EMAIL_RECIPIENTS = + "Email notification is not sent as the number of recipients is zero."; + String MESSAGE_ID_MISSING = "Message id is mandatory."; + String INVALID_NOTIFICATION_TYPE = "Please provide a valid notification type."; + String INVALID_NOTIFICATION_TYPE_SUPPORT = "Only notification type FCM is supported."; + String INVALID_TOPIC_NAME = "Please provide a valid toipc."; + String INVALID_TOPIC_DATA = "Please provide valid notification data."; + + // ------------------------------------------------------------------------- + // System, Config & Infrastructure + // ------------------------------------------------------------------------- + String ERROR_INVALID_CONFIG_PARAM_VALUE = "Invalid value {0} for config parameter {1}."; + String ERROR_CONFIG_LOAD_EMPTY_STRING = + "Loading {0} configuration failed as empty string is passed as parameter."; + String ERROR_CONFIG_LOAD_PARSE_STRING = + "Loading {0} configuration failed due to parsing error."; + String ERROR_CONFIG_LOAD_EMPTY_CONFIG = "Loading {0} configuration failed."; + String ERROR_CONFLICTING_FIELD_CONFIGURATION = + "Field {0} in {1} configuration is conflicting in {2} and {3}."; + String MANDATORY_CONFIG_PARAMETER_MISSING = + "Mandatory configuration parameter {0} missing which is required for service startup."; + String ERROR_LOAD_CONFIG = "Loading failed for configuration file {0}."; + String ERROR_SYSTEM_SETTING_NOT_FOUND = "System Setting not found for id: {0}"; + String ERROR_UPDATE_SETTING_NOT_ALLOWED = "Update of system setting {0} is not allowed."; + String DB_INSERTION_FAIL = "DB insert operation failed."; + String DB_UPDATE_FAIL = "Db update operation failed."; + String ES_ERROR = "Something went wrong when processing data for search"; + String ES_UPDATE_FAILED = "Data insertion to ES failed."; + String UNABLE_TO_CONNECT_TO_EKSTEP = "Unable to connect to Ekstep Server"; + String UNABLE_TO_CONNECT_TO_ES = "Unable to connect to Elastic Search"; + String UNABLE_TO_COMMUNICATE_WITH_ACTOR = "Unable to communicate with actor."; + String ACTOR_CONNECTION_ERROR = "Service is not able to connect with actor."; + String CASSANDRA_CONNECTION_ESTABLISHMENT_FAILED = + "Cassandra connection establishment failed in {0} mode."; + String CLOUD_SERVICE_ERROR = "Cloud storage service error."; + String ERROR_UNSUPPORTED_CLOUD_STORAGE = "Unsupported cloud storage type {0}."; + String STORAGE_CONTAINER_NAME_MANDATORY = " Container name can not be null or empty."; + String ERROR_GENERATE_DOWNLOAD_LINK = "Error in generating download link."; + String ERROR_DOWNLOAD_LINK_UNAVAILABLE = "Download link is unavailable."; + String ERROR_SAVING_STORAGE_DETAILS = "Error saving storage details for download link."; + String ERROR_UPLOAD_QRCODE_CSV_FAILED = "Uploading the html file to cloud storage has failed."; + String ERR_CALLING_GROUP_API = "Error while calling group api."; + String ERR_CALLING_EXHAUST_API = "Error while calling exhaust api"; + + // ------------------------------------------------------------------------- + // Files & Uploads + // ------------------------------------------------------------------------- + String INVALID_CSV_FILE = "Please provide valid csv file."; + String ERROR_CSV_NO_DATA_ROWS = "No data rows in CSV."; + String EMPTY_CSV_FILE = "CSV file is Empty."; + String EMPTY_HEADER_LINE = "Missing header line in CSV file."; + String BULK_USER_UPLOAD_ERROR = + "Please provide either organization Id or external Id & provider value."; + String DATA_SIZE_EXCEEDED = "Maximum upload data size should be {0}"; + String ERROR_MAX_SIZE_EXCEEDED = "Size of {0} exceeds max limit {1}"; + String MISSING_FILE_ATTACHMENT = "Missing file attachment."; + String EMPTY_FILE = "Attached file is empty."; + String FILE_ATTACHMENT_SIZE_NOT_CONFIGURED = "File attachment max size is not configured."; + String ERROR_CREATING_FILE = "Error Reading File"; + String ERROR_PROCESSING_FILE = + "Something Went Wrong While Reading File. Please Check The File."; + String ERROR_PROCESSING_REQUEST = "Something went wrong while Processing Request"; + + // ------------------------------------------------------------------------- + // Miscellaneous + // ------------------------------------------------------------------------- + String PAGE_NAME_REQUIRED = "Page name is required."; + String PAGE_ID_REQUIRED = "Page id is required."; + String PAGE_ALREADY_EXIST = "page already exist with this Page Name and Org Code."; + String PAGE_NOT_EXIST = "Requested page does not exist."; + String INVALID_PAGE_SOURCE = "Invalid page source."; + String SECTION_NAME_MISSING = "Section name is required."; + String SECTION_DATA_TYPE_MISSING = "Section data type missing."; + String SECTION_ID_REQUIRED = "Section id is required."; + String SECTION_NOT_EXIST = "Requested section does not exist."; + String INVALID_PAGE_SECTION = "Page section associated with the page is invalid."; String INVALID_WEBPAGE_DATA = "Invalid webPage data"; String INVALID_MEDIA_TYPE = "Invalid media type for webPage"; String INVALID_WEBPAGE_URL = "Invalid URL for {0}."; - String INVALID_DATE_RANGE = "Date range should be between 3 Month."; - String INVALID_BATCH_END_DATE_ERROR = "Please provide valid End Date."; - String INVALID_BATCH_START_DATE_ERROR = "Please provide valid Start Date."; - String COURSE_BATCH_END_DATE_ERROR = "Batch has been closed."; - String COURSE_BATCH_IS_CLOSED_ERROR = "Batch has been closed."; - String CONFIIRM_PASSWORD_MISSING = "Confirm password is mandatory."; - String CONFIIRM_PASSWORD_EMPTY = "Confirm password can not be empty."; - String SAME_PASSWORD_ERROR = "New password can't be same as old password."; - String ENDORSED_USER_ID_REQUIRED = " Endorsed user id required ."; - String CAN_NOT_ENDORSE = "Can not endorse since both belong to different orgs ."; - String INVALID_ORG_TYPE_ID_ERROR = "Please provide valid orgTypeId."; - String INVALID_ORG_TYPE_ERROR = "Please provide valid orgType."; - String TABLE_OR_DOC_NAME_ERROR = "Please provide valid table or documentName."; - String EMAIL_OR_PHONE_MISSING = "Please provide either email or phone."; - String PHONE_ALREADY_IN_USE = "Phone already in use. Please provide different phone number."; + String TITLE_REQUIRED = "Title is required"; + String NOTE_REQUIRED = "No data to store for notes"; + String NOTE_ID_INVALID = "Invalid note id"; + String INVALID_TAGS = "Invalid data for tags"; String INVALID_CLIENT_NAME = "Please provide unique valid client name"; String INVALID_CLIENT_ID = "Please provide valid client id"; - String USER_PHONE_UPDATE_FAILED = "user phone update is failed."; - String ES_UPDATE_FAILED = "Data insertion to ES failed."; - String UPDATE_FAILED = "Data updation failed due to invalid Request"; - String INVALID_LOCATION_ID = "Please provide valid location id."; - String INVALID_HASHTAG_ID = - "Please provide different hashTagId.This HashTagId is associated with some other organization."; - String INVALID_USR_ORG_DATA = - "Given User Data doesn't belongs to this organization. Please provide a valid one."; - String INVALID_VISIBILITY_REQUEST = "Private and Public fields cannot be same."; - String INVALID_TOPIC_NAME = "Please provide a valid toipc."; - String INVALID_TOPIC_DATA = "Please provide valid notification data."; - String INVALID_NOTIFICATION_TYPE = "Please provide a valid notification type."; - String INVALID_NOTIFICATION_TYPE_SUPPORT = "Only notification type FCM is supported."; - String INVALID_PHONE_NUMBER = "Please send Phone and country code seprately."; - String INVALID_COUNTRY_CODE = "Please provide a valid country code."; + String TABLE_OR_DOC_NAME_ERROR = "Please provide valid table or documentName."; + String INVALID_DUPLICATE_VALUE = "Values for {0} and {1} cannot be same."; + String ERROR_DUPLICATE_ENTRY = "Value {0} for {1} is already in use."; String ERROR_DUPLICATE_ENTRIES = "System contains duplicate entry for {0}."; - String LOCATION_ID_REQUIRED = "Please provide Location Id."; - String NOT_SUPPORTED = "Not Supported."; - String USERNAME_USERID_MISSING = "Please provide either userName or userId."; - String ISSUER_ID_REQUIRED = "Please provide issuer ID."; - String ROOT_ORG_ID_REQUIRED = "Please provide root organisation ID."; - String RECIPIENT_EMAIL_REQUIRED = "Please provide recipient email."; - String ASSERTION_EVIDENCE_REQUIRED = "Please provide valid assertion url as an evidence."; - String ASSERTION_ID_REQUIRED = "Please provide assertion ID."; - String RECIPIENT_ID_REQUIRED = "Please provide a recipient id."; - String RECIPIENT_TYPE_REQUIRED = "Please provide recipient type."; - String RESOURCE_NOT_FOUND = "Requested resource not found"; - String MAX_ALLOWED_SIZE_LIMIT_EXCEED = "Max allowed size is {0}"; - String SLUG_REQUIRED = "Slug is required ."; - String INVALID_ISSUER_ID = "Invalid issuer ID."; - String REVOCATION_REASON_REQUIRED = "Please provide revocation reason."; - String INVALID_RECIPIENT_TYPE = "Please provide a valid recipient type."; - String CUSTOM_SERVER_ERROR = "{0}"; - String PAGE_NOT_EXIST = "Requested page does not exist."; - String SECTION_NOT_EXIST = "Requested section does not exist."; - String ORG_NOT_EXIST = "Requested organisation does not exist."; - String INVALID_PAGE_SOURCE = "Invalid page source."; - String LOCATION_TYPE_REQUIRED = "Location type required."; - String INVALID_REQUEST_DATA_FOR_LOCATION = "{0} field required."; - String ALREADY_EXISTS = "A {0} with {1} already exists. Please retry with a unique value."; - String INVALID_VALUE = "Invalid {0}: {1}. Valid values are: {2}."; - String PARENT_CODE_AND_PARENT_ID_MISSING = "Please provide either parentCode or parentId."; - String INVALID_PARAMETER = "Please provide valid {0}."; - String INVALID_LOCATION_DELETE_REQUEST = - "One or more locations have a parent reference to given location and hence cannot be deleted."; - String LOCATION_TYPE_CONFLICTS = "Location type conflicts with its parent location type."; - String MANDATORY_PARAMETER_MISSING = "Mandatory parameter {0} is missing."; - String ERROR_MANDATORY_PARAMETER_EMPTY = "Mandatory parameter {0} is empty."; - String ERROR_NO_FRAMEWORK_FOUND = "No framework found."; + String INVALID_PERIOD = "Time Period is invalid"; + String INVALID_DATE_RANGE = "Date range should be between 3 Month."; + String CYCLIC_VALIDATION_FAILURE = "The relation cannot be created as it is cyclic"; String UPDATE_NOT_ALLOWED = "Update of {0} is not allowed."; - String MANDATORY_HEADER_MISSING = "Mandatory header {0} is missing."; - String INVALID_PARAMETER_VALUE = - "Invalid value {0} for parameter {1}. Please provide a valid value."; - String PARENT_NOT_ALLOWED = "For top level location, {0} is not allowed."; - String MISSING_FILE_ATTACHMENT = "Missing file attachment."; - String FILE_ATTACHMENT_SIZE_NOT_CONFIGURED = "File attachment max size is not configured."; - String EMPTY_FILE = "Attached file is empty."; + String STATUS_CANNOT_BE_UPDATED = "status cann't be updated."; + String UPDATE_FAILED = "Data updation failed due to invalid Request"; + String INVALID_COLUMN_NAME = "Invalid column name."; String INVALID_COLUMNS = "Invalid column: {0}. Valid columns are: {1}."; - String CONFLICTING_ORG_LOCATIONS = - "An organisation cannot be associated to two conflicting locations ({0}, {1}) at {2} level. "; - String UNABLE_TO_COMMUNICATE_WITH_ACTOR = "Unable to communicate with actor."; - String EMPTY_HEADER_LINE = "Missing header line in CSV file."; - String INVALID_REQUEST_PARAMETER = "Invalid parameter {0} in request."; - String ROOT_ORG_ASSOCIATION_ERROR = - "No root organisation found which is associated with given {0}."; - String OR_FORMAT = "{0} or {1}"; - String AND_FORMAT = "{0} and {1}"; + String REQUIRED_HEADER_MISSING = "Required set of header missing: "; + String MANDATORY_HEADER_MISSING = "Mandatory header {0} is missing."; + String MANDATORY_HEADER_PARAMETER_MISSING = "Mandatory header parameter {0} is missing."; + String PARAMETER_MISMATCH = "Mismatch of given parameters: {0}."; String DEPENDENT_PARAMETER_MISSING = "Missing parameter {0} which is dependent on {1}."; String DEPENDENT_PARAMS_MISSING = "Missing parameter value in {0}."; - String EXTERNALID_NOT_FOUND = - "External ID (id: {0}, idType: {1}, provider: {2}) not found for given user."; - String EXTERNALID_ASSIGNED_TO_OTHER_USER = - "External ID (id: {0}, idType: {1}, provider: {2}) already assigned to another user."; - String MANDATORY_CONFIG_PARAMETER_MISSING = - "Mandatory configuration parameter {0} missing which is required for service startup."; - String CASSANDRA_CONNECTION_ESTABLISHMENT_FAILED = - "Cassandra connection establishment failed in {0} mode."; String COMMON_ATTRIBUTE_MISMATCH = "{0} mismatch of {1} and {2}"; - String MULTIPLE_COURSES_FOR_BATCH = "A batch cannot belong to multiple courses."; + String ERROR_ATTRIBUTE_CONFLICT = "Either pass attribute {0} or {1} but not both."; + String EVENTS_DATA_MISSING = "Events array is mandatory"; + String GROUP_ID_MISSING = "GroupId is mandatory."; + String ACTIVITY_ID_MISSING = "ActivityId is mandatory."; + String ACTIVITY_TYPE_MISSING = "ActivityType is mandatory."; + String ERROR_NO_DIALCODES_LINKED = "No dialcodes are linked to any courses created by user(s)"; + String SOURCE_MISSING = "Source is required."; + String INVALID_CONFIGURATION = "Invalid configuration data."; + String INVALID_PROCESS_ID = "Invalid Process Id."; + String INVALID_TYPE_VALUE = "INVALID_TYPE_VALUE"; + String ERROR_NO_FRAMEWORK_FOUND = "No framework found."; + + // ------------------------------------------------------------------------- + // JSON Transform (Registry) + // ------------------------------------------------------------------------- String ERROR_JSON_TRANSFORM_INVALID_TYPE_CONFIG = "JSON transformation failed as invalid type configuration found for field {0}."; String ERROR_JSON_TRANSFORM_INVALID_DATE_FORMAT = @@ -315,7 +429,6 @@ interface Message { "JSON transformation failed as mandatory configuration (toFieldName, fromType or toType) is missing for field {0}."; String ERROR_JSON_TRANSFORM_INVALID_FILTER_CONFIG = "JSON transformation failed as invalid filter configuration found for field {0}."; - String ERROR_LOAD_CONFIG = "Loading failed for configuration file {0}."; String ERROR_REGISTRY_CLIENT_CREATION = "Registry client creation failed."; String ERROR_REGISTRY_ADD_ENTITY = "Registry add entity API failed."; String ERROR_REGISTRY_READ_ENTITY = "Registry read entity API failed."; @@ -326,336 +439,376 @@ interface Message { String ERROR_REGISTRY_ENTITY_ID_BLANK = "Request failed as entity id is not provided."; String ERROR_REGISTRY_ACCESS_TOKEN_BLANK = "Request failed as user access token is not provided."; - String DUPLICATE_EXTERNAL_IDS = - "Duplicate external IDs for given idType ({0}) and provider ({1})."; - String INVALID_DUPLICATE_VALUE = "Values for {0} and {1} cannot be same."; - String EMAIL_RECIPIENTS_EXCEEDS_MAX_LIMIT = - "Email notification is not sent as the number of recipients exceeded configured limit ({0})."; - String NO_EMAIL_RECIPIENTS = - "Email notification is not sent as the number of recipients is zero."; - String PARAMETER_MISMATCH = "Mismatch of given parameters: {0}."; - String FORBIDDEN = "You are forbidden from accessing specified resource."; - String ERROR_CONFIG_LOAD_EMPTY_STRING = - "Loading {0} configuration failed as empty string is passed as parameter."; - String ERROR_CONFIG_LOAD_PARSE_STRING = - "Loading {0} configuration failed due to parsing error."; - String ERROR_CONFIG_LOAD_EMPTY_CONFIG = "Loading {0} configuration failed."; - String ERROR_CONFLICTING_FIELD_CONFIGURATION = - "Field {0} in {1} configuration is conflicting in {2} and {3}."; - String ERROR_SYSTEM_SETTING_NOT_FOUND = "System Setting not found for id: {0}"; - String ERROR_NO_ROOT_ORG_ASSOCIATED = "Not able to associate with root org"; - String ERROR_INACTIVE_CUSTODIAN_ORG = "Custodian organisation is inactive."; - String ERROR_UNSUPPORTED_CLOUD_STORAGE = "Unsupported cloud storage type {0}."; - String ERROR_UNSUPPORTED_FIELD = "Unsupported field {0}."; - String ERROR_GENERATE_DOWNLOAD_LINK = "Error in generating download link."; - String ERROR_DOWNLOAD_LINK_UNAVAILABLE = "Download link is unavailable."; - String ERROR_SAVING_STORAGE_DETAILS = "Error saving storage details for download link."; - String ERROR_CSV_NO_DATA_ROWS = "No data rows in CSV."; - String ERROR_INACTIVE_ORG = "Organisation corresponding to given {0} ({1}) is inactive."; - String ERROR_UPDATE_SETTING_NOT_ALLOWED = "Update of system setting {0} is not allowed."; - String ERROR_CREATING_FILE = "Error Reading File"; - String ERROR_PROCESSING_REQUEST = "Something went wrong while Processing Request"; - String REQUIRED_HEADER_MISSING = "Required set of header missing: "; - String ERROR_PROCESSING_FILE = - "Something Went Wrong While Reading File. Please Check The File."; - String ERROR_INVALID_PARAMETER_SIZE = - "Parameter {0} is of invalid size (expected: {1}, actual: {2})."; - String INVALID_PAGE_SECTION = "Page section associated with the page is invalid."; - String ERROR_RATE_LIMIT_EXCEEDED = - "Your per {0} rate limit has exceeded. You can retry after some time."; - String INVALID_REQUEST_TIMEOUT = "Invalid request timeout value {0}."; - String IDENTIFIER_VALIDATION_FAILED = - "Valid identifier is not present in List, Valid supported identifiers are "; - String FROM_ACCOUNT_ID_MISSING = "From Account id is mandatory."; - String TO_ACCOUNT_ID_MISSING = "To Account id is mandatory."; - String FROM_ACCOUNT_ID_NOT_EXISTS = "From Account id not exists"; - String MANDATORY_HEADER_PARAMETER_MISSING = "Mandatory header parameter {0} is missing."; - String ERROR_USER_HAS_NOT_CREATED_ANY_COURSE = - "User hasn't created any course, or may not have a creator role"; - String ERROR_UPLOAD_QRCODE_CSV_FAILED = "Uploading the html file to cloud storage has failed."; - String ERROR_NO_DIALCODES_LINKED = "No dialcodes are linked to any courses created by user(s)"; - String EVENTS_DATA_MISSING = "Events array is mandatory"; - String ACCOUNT_NOT_FOUND = "Account not found."; - String INVALID_EXT_USER_ID = "provided ext user id {0} is incorrect"; - String USER_MIGRATION_FAILED = "user is failed to migrate"; - String INVALID_ELEMENT_IN_LIST = - "Invalid value supplied for parameter {0}.Supported values are {1}"; - String INVALID_PASSWORD = - "Password must contain a minimum of 8 characters including numerals, lower and upper case alphabets and special characters"; - String OTP_VERIFICATION_FAILED = "OTP verification failed. Remaining attempt count is {0}."; - String SERVICE_UNAVAILABLE = "SERVICE UNAVAILABLE"; - String MISSING_MESSAGE = "Required fields for create course are missing. {0}"; - String CONTENT_TYPE_MISMATCH = "Content Type should be Course."; - String MIME_TYPE_MISMATCH = "MimeType should be application/vnd.ekstep.content-collection"; - String GROUP_ID_MISSING = "GroupId is mandatory."; - String ACTIVITY_ID_MISSING = "ActivityId is mandatory."; - String ACTIVITY_TYPE_MISSING = "ActivityType is mandatory."; - String ERR_CALLING_GROUP_API = "Error while calling group api."; - String ERR_CALLING_EXHAUST_API = "Error while calling exhaust api"; } interface Key { - String UNAUTHORIZED_USER = "UNAUTHORIZED_USER"; - String INVALID_USER_CREDENTIALS = "INVALID_USER_CREDENTIALS"; + + // ------------------------------------------------------------------------- + // Generic / Common Keys + // ------------------------------------------------------------------------- + String SUCCESS_MESSAGE = "SUCCESS"; + String INTERNAL_ERROR = "INTERNAL_ERROR"; String OPERATION_TIMEOUT = "PROCESS_EXE_TIMEOUT"; - String INVALID_OPERATION_NAME = "INVALID_OPERATION_NAME"; String INVALID_REQUESTED_DATA = "INVALID_REQUESTED_DATA"; - String CONTENT_ID_MISSING_ERROR = "CONTENT_ID_REQUIRED_ERROR"; - String COURSE_ID_MISSING_ERROR = "COURSE_ID_REQUIRED_ERROR"; + String INVALID_DATA = "INVALID_DATA"; + String DATA_TYPE_ERROR = "DATA_TYPE_ERROR"; + String ID_REQUIRED_ERROR = "ID_REQUIRED_ERROR"; + String MANDATORY_PARAMETER_MISSING = "MANDATORY_PARAMETER_MISSING"; + String ERROR_MANDATORY_PARAMETER_EMPTY = "ERROR_MANDATORY_PARAMETER_EMPTY"; + String INVALID_PARAMETER_VALUE = "INVALID_PARAMETER_VALUE"; + String INVALID_PARAMETER = "INVALID_PARAMETER"; + String INVALID_REQUEST_PARAMETER = "INVALID_REQUEST_PARAMETER"; + String IDENTIFIER_VALIDATION_FAILED = "IDENTIFIER_VALIDATION_FAILED"; + String INVALID_VALUE = "INVALID_VALUE"; + String ALREADY_EXISTS = "ALREADY_EXISTS"; + String RESOURCE_NOT_FOUND = "RESOURCE_NOT_FOUND"; + String MAX_ALLOWED_SIZE_LIMIT_EXCEED = "MAX_ALLOWED_SIZE_LIMIT_EXCEED"; + String UNABLE_TO_PARSE_DATA = "UNABLE_TO_PARSE_DATA"; + String INVALID_JSON = "INVALID_JSON"; + String NO_DATA = "NO_DATA"; + String INVALID_DATE_FORMAT = "INVALID_DATE_FORMAT"; + String DATE_FORMAT_ERRROR = "DATE_FORMAT_ERRROR"; + String INVALID_PROPERTY_ERROR = "INVALID_PROPERTY_ERROR"; + String INVALID_OBJECT_TYPE = "INVALID_OBJECT_TYPE"; + String DATA_ALREADY_EXIST = "DATA_ALREADY_EXIST"; + String SERVICE_UNAVAILABLE = "SERVICE_UNAVAILABLE"; + String CUSTOM_SERVER_ERROR = "SERVER_ERROR"; + String NOT_SUPPORTED = "NOT_SUPPORTED"; + String ERROR_UNSUPPORTED_FIELD = "ERROR_UNSUPPORTED_FIELD"; + String INVALID_ELEMENT_IN_LIST = "INVALID_ELEMENT_IN_LIST"; + String ERROR_RATE_LIMIT_EXCEEDED = "ERROR_RATE_LIMIT_EXCEEDED"; + String INVALID_REQUEST_TIMEOUT = "INVALID_REQUEST_TIMEOUT"; + String INVALID_OPERATION_NAME = "INVALID_OPERATION_NAME"; + + // ------------------------------------------------------------------------- + // Authentication & Authorization + // ------------------------------------------------------------------------- + String UNAUTHORIZED_USER = "UNAUTHORIZED_USER"; + String INVALID_USER_CREDENTIALS = "INVALID_USER_CREDENTIALS"; String API_KEY_MISSING_ERROR = "API_KEY_REQUIRED_ERROR"; String API_KEY_INVALID_ERROR = "API_KEY_INVALID_ERROR"; - String INTERNAL_ERROR = "INTERNAL_ERROR"; - String COURSE_NAME_MISSING = "COURSE_NAME_REQUIRED_ERROR"; - String SUCCESS_MESSAGE = "SUCCESS"; String SESSION_ID_MISSING = "SESSION_ID_REQUIRED_ERROR"; - String COURSE_ID_MISSING = "COURSE_ID_REQUIRED_ERROR"; - String CONTENT_ID_MISSING = "CONTENT_ID_REQUIRED_ERROR"; - String VERSION_MISSING = "VERSION_REQUIRED_ERROR"; - String COURSE_VERSION_MISSING = "COURSE_VERSION_REQUIRED_ERROR"; - String CONTENT_VERSION_MISSING = "CONTENT_VERSION_REQUIRED_ERROR"; - String COURSE_DESCRIPTION_MISSING = "COURSE_DESCRIPTION_REQUIRED_ERROR"; - String COURSE_TOCURL_MISSING = "COURSE_TOCURL_REQUIRED_ERROR"; - String EMAIL_MISSING = "EMAIL_ID_REQUIRED_ERROR"; - String EMAIL_FORMAT = "EMAIL_FORMAT_ERROR"; - String URL_FORMAT_ERROR = "URL_FORMAT_ERROR"; + String AUTH_TOKEN_MISSING = "X_Authenticated_Userid_MISSING"; + String INVALID_AUTH_TOKEN = "INVALID_AUTH_TOKEN"; + String INVALID_ROLE = "INVALID_ROLE"; + String INVALID_SALT = "INVALID_SALT"; + String KEY_CLOAK_DEFAULT_ERROR = "KEY_CLOAK_DEFAULT_ERROR"; + String OTP_VERIFICATION_FAILED = "OTP_VERIFICATION_FAILED"; + String ERROR_INVALID_OTP = "ERROR_INVALID_OTP"; + String FORBIDDEN = "FORBIDDEN"; + + // ------------------------------------------------------------------------- + // User Management + // ------------------------------------------------------------------------- + String USER_NOT_FOUND = "USER_NOT_FOUND"; + String USER_ALREADY_EXISTS = "USER_ALREADY_EXISTS"; + String INVALID_USER_ID = "INVALID_USER_ID"; + String USERID_MISSING = "USERID_MISSING"; + String USERNAME_MISSING = "USERNAME_MISSING"; String FIRST_NAME_MISSING = "FIRST_NAME_REQUIRED_ERROR"; - String LANGUAGE_MISSING = "LANGUAGE_REQUIRED_ERROR"; + String EMAIL_MISSING = "EMAIL_ID_REQUIRED_ERROR"; + String PHONE_NO_REQUIRED_ERROR = "PHONE_NO_REQUIRED_ERROR"; String PASSWORD_MISSING = "PASSWORD_REQUIRED_ERROR"; + String INVALID_PASSWORD = "INVALID_PASSWORD"; String PASSWORD_MIN_LENGHT = "PASSWORD_MIN_LENGHT_ERROR"; String PASSWORD_MAX_LENGHT = "PASSWORD_MAX_LENGHT_ERROR"; - String ORGANISATION_ID_MISSING = "ORGANIZATION_ID_MISSING"; - String REQUIRED_DATA_ORG_MISSING = "REQUIRED_DATA_MISSING"; - String ORGANISATION_NAME_MISSING = "ORGANIZATION_NAME_MISSING"; - String CHANNEL_SHOULD_BE_UNIQUE = "CHANNEL_SHOULD_BE_UNIQUE"; - String ERROR_DUPLICATE_ENTRY = "ERROR_DUPLICATE_ENTRY"; - String INVALID_ORG_DATA = "INVALID_ORGANIZATION_DATA"; - String INVALID_USR_DATA = "INVALID_USER_DATA"; - String USR_DATA_VALIDATION_ERROR = "USER_DATA_VALIDATION_ERROR"; - String INVALID_ROOT_ORGANIZATION = "INVALID ROOT ORGANIZATION"; - String INVALID_PARENT_ORGANIZATION_ID = "INVALID_PARENT_ORGANIZATION_ID"; - String CYCLIC_VALIDATION_FAILURE = "CYCLIC_VALIDATION_FAILURE"; - String ENROLLMENT_START_DATE_MISSING = "ENROLLMENT_START_DATE_MISSING"; - String COURSE_DURATION_MISSING = "COURSE_DURATION_MISSING"; - String LOGIN_TYPE_MISSING = "LOGIN_TYPE_MISSING"; + String USERNAME_IN_USE = "USERNAME_IN_USE"; String EMAIL_IN_USE = "EMAIL_IN_USE"; - String USERNAME_EMAIL_IN_USE = "USERNAME_EMAIL_IN_USE"; - String KEY_CLOAK_DEFAULT_ERROR = "KEY_CLOAK_DEFAULT_ERROR"; + String PHONE_ALREADY_IN_USE = "PHONE_ALREADY_IN_USE"; + String USER_ACCOUNT_BLOCKED = "USER_ACCOUNT_BLOCKED"; + String USER_ALREADY_ACTIVE = "USER_ALREADY_ACTIVE"; + String USER_ALREADY_INACTIVE = "USER_ALREADY_INACTIVE"; String USER_REG_UNSUCCESSFUL = "USER_REG_UNSUCCESSFUL"; String USER_UPDATE_UNSUCCESSFUL = "USER_UPDATE_UNSUCCESSFUL"; - String INVALID_CREDENTIAL = "INVALID_CREDENTIAL"; - String USERNAME_MISSING = "USERNAME_MISSING"; - String USERNAME_IN_USE = "USERNAME_IN_USE"; - String USERID_MISSING = "USERID_MISSING"; - String ROLE_MISSING = "ROLE_MISSING"; - String MESSAGE_ID_MISSING = "MESSAGE_ID_MISSING"; + String USER_PHONE_UPDATE_FAILED = "USER_PHONE_UPDATE_FAILED"; + String USER_MIGRATION_FAILED = "USER_MIGRATION_FAILED"; + String USER_DATA_ENCRYPTION_ERROR = "USER_DATA_ENCRYPTION_ERROR"; + String INVALID_EXT_USER_ID = "INVALID_EXT_USER_ID"; + String EXTERNALID_NOT_FOUND = "EXTERNALID_NOT_FOUND"; + String EXTERNALID_ASSIGNED_TO_OTHER_USER = "EXTERNALID_ASSIGNED_TO_OTHER_USER"; + String DUPLICATE_EXTERNAL_IDS = "DUPLICATE_EXTERNAL_IDS"; + String USERNAME_EMAIL_IN_USE = "USERNAME_EMAIL_IN_USE"; String USERNAME_CANNOT_BE_UPDATED = "USERNAME_CANNOT_BE_UPDATED"; - String AUTH_TOKEN_MISSING = "X_Authenticated_Userid_MISSING"; - String INVALID_AUTH_TOKEN = "INVALID_AUTH_TOKEN"; - String TIMESTAMP_REQUIRED = "TIMESTAMP_REQUIRED"; - String PUBLISHED_COURSE_CAN_NOT_UPDATED = "PUBLISHED_COURSE_CAN_NOT_UPDATED"; - String SOURCE_MISSING = "SOURCE_MISSING"; - String SECTION_NAME_MISSING = "SECTION_NAME_MISSING"; - String SECTION_DATA_TYPE_MISSING = "SECTION_DATA_TYPE_MISSING"; - String SECTION_ID_REQUIRED = "SECTION_ID_REQUIRED"; - String PAGE_NAME_REQUIRED = "PAGE_NAME_REQUIRED"; - String PAGE_ID_REQUIRED = "PAGE_ID_REQUIRED"; - String INVALID_CONFIGURATION = "INVALID_CONFIGURATION"; - String ASSESSMENT_ITEM_ID_REQUIRED = "ASSESSMENT_ITEM_ID_REQUIRED"; - String ASSESSMENT_TYPE_REQUIRED = "ASSESSMENT_TYPE_REQUIRED"; - String ATTEMPTED_DATE_REQUIRED = "ATTEMPTED_DATE_REQUIRED"; - String ATTEMPTED_ANSWERS_REQUIRED = "ATTEMPTED_ANSWERS_REQUIRED"; - String MAX_SCORE_REQUIRED = "MAX_SCORE_REQUIRED"; - String STATUS_CANNOT_BE_UPDATED = "STATUS_CANNOT_BE_UPDATED"; - String ATTEMPT_ID_MISSING_ERROR = "ATTEMPT_ID_REQUIRED_ERROR"; + String CONFIIRM_PASSWORD_MISSING = "CONFIIRM_PASSWORD_MISSING"; + String CONFIIRM_PASSWORD_EMPTY = "CONFIIRM_PASSWORD_EMPTY"; + String SAME_PASSWORD_ERROR = "SAME_PASSWORD_ERROR"; + String EMAIL_VERIFY_ERROR = "EMAIL_VERIFY_ERROR"; + String PHONE_VERIFY_ERROR = "PHONE_VERIFY_ERROR"; + String LOGIN_TYPE_MISSING = "LOGIN_TYPE_MISSING"; String LOGIN_TYPE_ERROR = "LOGIN_TYPE_ERROR"; - String INVALID_ORG_ID = "INVALID_ORG_ID"; - String INVALID_ORG_STATUS = "INVALID_ORG_STATUS"; - String INVALID_ORG_STATUS_TRANSITION = "INVALID_ORG_STATUS_TRANSITION"; + String LOGIN_ID_MISSING = "LOGIN_ID_MISSING"; + String USER_NAME_OR_ID_ERROR = "USER_NAME_OR_ID_ERROR"; + String USERNAME_USERID_MISSING = "USERNAME_USERID_MISSING"; + String ROLES_MISSING = "ROLES_REQUIRED_ERROR"; + String EMPTY_ROLES_PROVIDED = "EMPTY_ROLES_PROVIDED"; + String ROLE_MISSING = "ROLE_MISSING"; + String INVALID_VISIBILITY_REQUEST = "INVALID_VISIBILITY_REQUEST"; String ADDRESS_REQUIRED_ERROR = "ADDRESS_REQUIRED_ERROR"; String EDUCATION_REQUIRED_ERROR = "EDUCATION_REQUIRED_ERROR"; String JOBDETAILS_REQUIRED_ERROR = "JOBDETAILS_REQUIRED_ERROR"; - String DB_INSERTION_FAIL = "DB_INSERTION_FAIL"; - String DB_UPDATE_FAIL = "DB_UPDATE_FAIL"; - String DATA_ALREADY_EXIST = "DATA_ALREADY_EXIST"; - String INVALID_DATA = "INVALID_DATA"; - String INVALID_COURSE_ID = "INVALID_COURSE_ID"; - String PHONE_NO_REQUIRED_ERROR = "PHONE_NO_REQUIRED_ERROR"; - String ORG_ID_MISSING = "ORG_ID_MISSING"; - String ACTOR_CONNECTION_ERROR = "ACTOR_CONNECTION_ERROR"; - String USER_ALREADY_EXISTS = "USER_ALREADY_EXISTS"; - String PAGE_ALREADY_EXIST = "PAGE_ALREADY_EXIST"; - String INVALID_USER_ID = "INVALID_USER_ID"; - String LOGIN_ID_MISSING = "LOGIN_ID_MISSING"; - String CONTENT_STATUS_MISSING_ERROR = "CONTENT_STATUS_MISSING_ERROR"; - String ES_ERROR = "ELASTICSEARCH_ERROR"; - String INVALID_PERIOD = "INVALID_PERIOD"; - String USER_NOT_FOUND = "USER_NOT_FOUND"; - String ID_REQUIRED_ERROR = "ID_REQUIRED_ERROR"; - String DATA_TYPE_ERROR = "DATA_TYPE_ERROR"; - String ERROR_ATTRIBUTE_CONFLICT = "ERROR_ATTRIBUTE_CONFLICT"; String ADDRESS_ERROR = "ADDRESS_ERROR"; String ADDRESS_TYPE_ERROR = "ADDRESS_TYPE_ERROR"; String NAME_OF_INSTITUTION_ERROR = "NAME_OF_INSTITUTION_ERROR"; String EDUCATION_DEGREE_ERROR = "EDUCATION_DEGREE_ERROR"; String JOB_NAME_ERROR = "JOB_NAME_ERROR"; + String INVALID_USR_DATA = "INVALID_USER_DATA"; + String USR_DATA_VALIDATION_ERROR = "USER_DATA_VALIDATION_ERROR"; + String INVALID_USR_ORG_DATA = "INVALID_USR_ORG_DATA"; + String USER_NOT_BELONGS_TO_ANY_ORG = "USER_NOT_BELONGS_TO_ANY_ORG"; + String USER_ORG_ASSOCIATION_ERROR = "USER_ORG_ASSOCIATION_ERROR"; + String ERROR_USER_HAS_NOT_CREATED_ANY_COURSE = "USER_HAS_NOT_CREATED_ANY_COURSE"; + String USER_NOT_ASSOCIATED_TO_ROOT_ORG = "USER_NOT_ASSOCIATED_TO_ROOT_ORG"; + String INVALID_CREDENTIAL = "INVALID_CREDENTIAL"; + String EMAIL_FORMAT = "EMAIL_FORMAT_ERROR"; + String URL_FORMAT_ERROR = "URL_FORMAT_ERROR"; + String LANGUAGE_MISSING = "LANGUAGE_REQUIRED_ERROR"; + String TIMESTAMP_REQUIRED = "TIMESTAMP_REQUIRED"; + String INVALID_PHONE_NO_FORMAT = "INVALID_PHONE_NO_FORMAT"; + String INVALID_PHONE_NUMBER = "INVALID_PHONE_NUMBER"; + String INVALID_COUNTRY_CODE = "INVALID_COUNTRY_CODE"; + String EMAIL_OR_PHONE_MISSING = "EMAIL_OR_PHONE_MISSING"; + String ACCOUNT_NOT_FOUND = "ACCOUNT_NOT_FOUND"; + String FROM_ACCOUNT_ID_MISSING = "FROM_ACCOUNT_ID_MISSING"; + String TO_ACCOUNT_ID_MISSING = "TO_ACCOUNT_ID_MISSING"; + String FROM_ACCOUNT_ID_NOT_EXISTS = "FROM_ACCOUNT_ID_NOT_EXISTS"; + + // ------------------------------------------------------------------------- + // Organization Management + // ------------------------------------------------------------------------- + String ORG_NOT_EXIST = "ORG_NOT_EXIST"; + String INVALID_ORG_DATA = "INVALID_ORGANIZATION_DATA"; + String ORGANISATION_ID_MISSING = "ORGANIZATION_ID_MISSING"; + String ORG_ID_MISSING = "ORG_ID_MISSING"; + String ORGANISATION_NAME_MISSING = "ORGANIZATION_NAME_MISSING"; String NAME_OF_ORGANISATION_ERROR = "NAME_OF_ORGANIZATION_ERROR"; - String ROLES_MISSING = "ROLES_REQUIRED_ERROR"; - String EMPTY_ROLES_PROVIDED = "EMPTY_ROLES_PROVIDED"; - String INVALID_DATE_FORMAT = "INVALID_DATE_FORMAT"; - String SRC_EXTERNAL_ID_ALREADY_EXIST = "SRC_EXTERNAL_ID_ALREADY_EXIST"; - String USER_ALREADY_ENROLLED_COURSE = "USER_ALREADY_ENROLLED_COURSE"; - String USER_NOT_ENROLLED_COURSE = "USER_NOT_ENROLLED_COURSE"; - String USER_ALREADY_COMPLETED_COURSE = "USER_ALREADY_COMPLETED_COURSE"; + String ROOT_ORG_ID_REQUIRED = "BADGE_ROOT_ORG_ID_REQUIRED"; + String REQUIRED_DATA_ORG_MISSING = "REQUIRED_DATA_MISSING"; + String INVALID_ROOT_ORGANIZATION = "INVALID ROOT ORGANIZATION"; + String INVALID_PARENT_ORGANIZATION_ID = "INVALID_PARENT_ORGANIZATION_ID"; + String PARENT_CODE_AND_PARENT_ID_MISSING = "PARENT_CODE_AND_PARENT_ID_MISSING"; + String INVALID_ORG_ID = "INVALID_ORG_ID"; + String INVALID_ORG_STATUS = "INVALID_ORG_STATUS"; + String INVALID_ORG_STATUS_TRANSITION = "INVALID_ORG_STATUS_TRANSITION"; + String ORG_TYPE_MANDATORY = "ORG_TYPE_MANDATORY"; + String ORG_TYPE_ALREADY_EXIST = "ORG_TYPE_ALREADY_EXIST"; + String ORG_TYPE_ID_REQUIRED_ERROR = "ORG_TYPE_ID_REQUIRED_ERROR"; + String INVALID_ORG_TYPE_ID_ERROR = "INVALID_ORG_TYPE_ID_ERROR"; + String INVALID_ORG_TYPE_ERROR = "INVALID_ORG_TYPE_ERROR"; + String ERROR_INACTIVE_ORG = "ERROR_INACTIVE_ORG"; + String ERROR_NO_ROOT_ORG_ASSOCIATED = "ERROR_NO_ROOT_ORG_ASSOCIATED"; + String ERROR_INACTIVE_CUSTODIAN_ORG = "ERROR_INACTIVE_CUSTODIAN_ORG"; + String ROOT_ORG_ASSOCIATION_ERROR = "ROOT_ORG_ASSOCIATION_ERROR"; + String INVALID_ROOT_ORG_DATA = "INVALID_ROOT_ORG_DATA"; + String CHANNEL_SHOULD_BE_UNIQUE = "CHANNEL_SHOULD_BE_UNIQUE"; + String INVALID_CHANNEL = "INVALID_CHANNEL"; + String CHANNEL_REG_FAILED = "CHANNEL_REG_FAILED"; + String SLUG_IS_NOT_UNIQUE = "SLUG_IS_NOT_UNIQUE"; + String SLUG_REQUIRED = "SLUG_REQUIRED"; + String CONFLICTING_ORG_LOCATIONS = "CONFLICTING_ORG_LOCATIONS"; + String INVALID_LOCATION_ID = "INVALID_LOCATION_ID"; + String LOCATION_ID_REQUIRED = "LOCATION_ID_REQUIRED"; + String LOCATION_TYPE_REQUIRED = "LOCATION_TYPE_REQUIRED"; + String INVALID_REQUEST_DATA_FOR_LOCATION = "INVALID_REQUEST_DATA_CREATE_LOCATION"; + String INVALID_LOCATION_DELETE_REQUEST = "INVALID_LOCATION_DELETE_REQUEST"; + String LOCATION_TYPE_CONFLICTS = "LOCATION_TYPE_CONFLICTS"; + String PARENT_NOT_ALLOWED = "PARENT_NOT_ALLOWED"; + String INVALID_HASHTAG_ID = "INVALID_HASHTAG_ID"; + + // ------------------------------------------------------------------------- + // Course & Batch Management + // ------------------------------------------------------------------------- + String COURSE_ID_MISSING_ERROR = "COURSE_ID_REQUIRED_ERROR"; + String COURSE_ID_MISSING = "COURSE_ID_REQUIRED_ERROR"; + String INVALID_COURSE_ID = "INVALID_COURSE_ID"; + String COURSE_NAME_MISSING = "COURSE_NAME_REQUIRED_ERROR"; + String COURSE_DESCRIPTION_MISSING = "COURSE_DESCRIPTION_REQUIRED_ERROR"; + String COURSE_VERSION_MISSING = "COURSE_VERSION_REQUIRED_ERROR"; + String COURSE_DURATION_MISSING = "COURSE_DURATION_MISSING"; + String COURSE_TOCURL_MISSING = "COURSE_TOCURL_REQUIRED_ERROR"; + String COURSE_CREATED_FOR_NULL = "COURSE_CREATED_FOR_NULL"; + String COURSE_BATCH_ID_MISSING = "COURSE_BATCH_ID_MISSING"; + String INVALID_COURSE_BATCH_ID = "INVALID_COURSE_BATCH_ID"; String COURSE_BATCH_ALREADY_COMPLETED = "COURSE_BATCH_ALREADY_COMPLETED"; String COURSE_BATCH_ENROLLMENT_DATE_ENDED = "COURSE_BATCH_ENROLLMENT_DATE_ENDED"; - String CONTENT_TYPE_ERROR = "CONTENT_TYPE_ERROR"; - String INVALID_PROPERTY_ERROR = "INVALID_PROPERTY_ERROR"; - String USER_NAME_OR_ID_ERROR = "USER_NAME_OR_ID_ERROR"; - String USER_ACCOUNT_BLOCKED = "USER_ACCOUNT_BLOCKED"; - String EMAIL_VERIFY_ERROR = "EMAIL_VERIFY_ERROR"; - String PHONE_VERIFY_ERROR = "PHONE_VERIFY_ERROR"; - String BULK_USER_UPLOAD_ERROR = "BULK_USER_UPLOAD_ERROR"; - String DATA_SIZE_EXCEEDED = "DATA_SIZE_EXCEEDED"; - String INVALID_COLUMN_NAME = "INVALID_COLUMN_NAME"; - String USER_ALREADY_ACTIVE = "USER_ALREADY_ACTIVE"; - String USER_ALREADY_INACTIVE = "USER_ALREADY_INACTIVE"; - String ENROLMENT_TYPE_REQUIRED = "ENROLMENT_TYPE_REQUIRED"; - String ENROLMENT_TYPE_VALUE_ERROR = "ENROLMENT_TYPE_VALUE_ERROR"; String COURSE_BATCH_START_DATE_REQUIRED = "COURSE_BATCH_START_DATE_REQUIRED"; String COURSE_BATCH_START_DATE_INVALID = "COURSE_BATCH_START_DATE_INVALID"; - String DATE_FORMAT_ERRROR = "DATE_FORMAT_ERRROR"; - String END_DATE_ERROR = "END_DATE_ERROR"; + String COURSE_BATCH_END_DATE_ERROR = "COURSE_BATCH_END_DATE_ERROR"; + String COURSE_BATCH_IS_CLOSED_ERROR = "COURSE_BATCH_IS_CLOSED_ERROR"; + String COURSE_BATCH_START_PASSED_DATE_INVALID = "COURSE_BATCH_START_PASSED_DATE_INVALID"; + String INVALID_BATCH_START_DATE_ERROR = "INVALID_BATCH_START_DATE_ERROR"; + String INVALID_BATCH_END_DATE_ERROR = "INVALID_BATCH_END_DATE_ERROR"; + String MULTIPLE_COURSES_FOR_BATCH = "MULTIPLE_COURSES_FOR_BATCH"; + String INVALID_COURSE_CREATOR_ID = "INVALID_COURSE_CREATOR_ID"; + String ENROLLMENT_START_DATE_MISSING = "ENROLLMENT_START_DATE_MISSING"; String ENROLLMENT_END_DATE_START_ERROR = "ENROLLMENT_END_DATE_START_ERROR"; String ENROLLMENT_END_DATE_END_ERROR = "ENROLLMENT_END_DATE_END_ERROR"; String ENROLLMENT_END_DATE_UPDATE_ERROR = "ENROLLMENT_END_DATE_UPDATE_ERROR"; - String INVALID_CSV_FILE = "INVALID_CSV_FILE"; - String INVALID_COURSE_BATCH_ID = "INVALID_COURSE_BATCH_ID"; - String COURSE_BATCH_ID_MISSING = "COURSE_BATCH_ID_MISSING"; + String ENROLMENT_TYPE_REQUIRED = "ENROLMENT_TYPE_REQUIRED"; + String ENROLMENT_TYPE_VALUE_ERROR = "ENROLMENT_TYPE_VALUE_ERROR"; String ENROLLMENT_TYPE_VALIDATION = "ENROLLMENT_TYPE_VALIDATION"; - String COURSE_CREATED_FOR_NULL = "COURSE_CREATED_FOR_NULL"; - String USER_NOT_BELONGS_TO_ANY_ORG = "USER_NOT_BELONGS_TO_ANY_ORG"; - String INVALID_OBJECT_TYPE = "INVALID_OBJECT_TYPE"; + String USER_ALREADY_ENROLLED_COURSE = "USER_ALREADY_ENROLLED_COURSE"; + String USER_NOT_ENROLLED_COURSE = "USER_NOT_ENROLLED_COURSE"; + String USER_ALREADY_COMPLETED_COURSE = "USER_ALREADY_COMPLETED_COURSE"; + String END_DATE_ERROR = "END_DATE_ERROR"; + String PUBLISHED_COURSE_CAN_NOT_UPDATED = "PUBLISHED_COURSE_CAN_NOT_UPDATED"; String INVALID_PROGRESS_STATUS = "INVALID_PROGRESS_STATUS"; - String COURSE_BATCH_START_PASSED_DATE_INVALID = "COURSE_BATCH_START_PASSED_DATE_INVALID"; - String UNABLE_TO_CONNECT_TO_EKSTEP = "UNABLE_TO_CONNECT_TO_EKSTEP"; - String UNABLE_TO_CONNECT_TO_ES = "UNABLE_TO_CONNECT_TO_ES"; - String UNABLE_TO_PARSE_DATA = "UNABLE_TO_PARSE_DATA"; - String INVALID_JSON = "INVALID_JSON"; - String EMPTY_CSV_FILE = "EMPTY_CSV_FILE"; - String INVALID_ROOT_ORG_DATA = "INVALID_ROOT_ORG_DATA"; - String NO_DATA = "NO_DATA"; - String INVALID_CHANNEL = "INVALID_CHANNEL"; - String INVALID_PROCESS_ID = "INVALID_PROCESS_ID"; - String EMAIL_SUBJECT_ERROR = "EMAIL_SUBJECT_ERROR"; - String EMAIL_BODY_ERROR = "EMAIL_BODY_ERROR"; - String RECIPIENT_ADDRESS_ERROR = "RECIPIENT_ADDRESS_ERROR"; + String MISSING_CODE = "ERR_COURSE_CREATE_FIELDS_MISSING"; + String CONTENT_TYPE_MISMATCH = "CONTENT_TYPE_MISMATCH"; + String MIME_TYPE_MISMATCH = "MIME_TYPE_MISMATCH"; + + // ------------------------------------------------------------------------- + // Content & Assessment + // ------------------------------------------------------------------------- + String CONTENT_ID_MISSING_ERROR = "CONTENT_ID_REQUIRED_ERROR"; + String CONTENT_ID_MISSING = "CONTENT_ID_REQUIRED_ERROR"; + String CONTENT_ID_ERROR = "CONTENT_ID_OR_COURSE_ID_REQUIRED"; + String CONTENT_VERSION_MISSING = "CONTENT_VERSION_REQUIRED_ERROR"; + String VERSION_MISSING = "VERSION_REQUIRED_ERROR"; + String CONTENT_STATUS_MISSING_ERROR = "CONTENT_STATUS_MISSING_ERROR"; + String CONTENT_TYPE_ERROR = "CONTENT_TYPE_ERROR"; + String ASSESSMENT_ITEM_ID_REQUIRED = "ASSESSMENT_ITEM_ID_REQUIRED"; + String ASSESSMENT_TYPE_REQUIRED = "ASSESSMENT_TYPE_REQUIRED"; + String ATTEMPTED_DATE_REQUIRED = "ATTEMPTED_DATE_REQUIRED"; + String ATTEMPTED_ANSWERS_REQUIRED = "ATTEMPTED_ANSWERS_REQUIRED"; + String MAX_SCORE_REQUIRED = "MAX_SCORE_REQUIRED"; + String ATTEMPT_ID_MISSING_ERROR = "ATTEMPT_ID_REQUIRED_ERROR"; + + // ------------------------------------------------------------------------- + // Badge/Certificates (Issuer, Recipient, Assertion) + // ------------------------------------------------------------------------- String ISSUER_ID_REQUIRED = "ISSUER_ID_REQUIRED"; - String ROOT_ORG_ID_REQUIRED = "BADGE_ROOT_ORG_ID_REQUIRED"; + String INVALID_ISSUER_ID = "INVALID_ISSUER_ID"; + String RECIPIENT_ID_REQUIRED = "RECIPIENT_ID_REQUIRED"; + String RECIPIENT_TYPE_REQUIRED = "RECIPIENT_TYPE_REQUIRED"; + String INVALID_RECIPIENT_TYPE = "INVALID_RECIPIENT_TYPE"; String RECIPIENT_EMAIL_REQUIRED = "RECIPIENT_EMAIL_REQUIRED"; - String ASSERTION_EVIDENCE_REQUIRED = "ASSERTION_EVIDENCE_REQUIRED"; - String ASSERTION_ID_REQUIRED = "ASSERTION_ID_REQUIRED"; - String STORAGE_CONTAINER_NAME_MANDATORY = "STORAGE_CONTAINER_NAME_MANDATORY"; - String USER_ORG_ASSOCIATION_ERROR = "USER_ORG_ASSOCIATION_ERROR"; - String CLOUD_SERVICE_ERROR = "CLOUD_SERVICE_ERROR"; + String RECIPIENT_ADDRESS_ERROR = "RECIPIENT_ADDRESS_ERROR"; String RECEIVER_ID_ERROR = "RECEIVER_ID_ERROR"; String INVALID_RECEIVER_ID = "INVALID_RECEIVER_ID"; - String INVALID_ROLE = "INVALID_ROLE"; - String INVALID_SALT = "INVALID_SALT"; - String ORG_TYPE_MANDATORY = "ORG_TYPE_MANDATORY"; - String ORG_TYPE_ALREADY_EXIST = "ORG_TYPE_ALREADY_EXIST"; - String ORG_TYPE_ID_REQUIRED_ERROR = "ORG_TYPE_ID_REQUIRED_ERROR"; - String TITLE_REQUIRED = "TITLE_REQUIRED"; - String NOTE_REQUIRED = "NOTE_REQUIRED"; - String CONTENT_ID_ERROR = "CONTENT_ID_OR_COURSE_ID_REQUIRED"; - String INVALID_TAGS = "INVALID_TAGS"; - String NOTE_ID_INVALID = "NOTE_ID_INVALID"; - String USER_DATA_ENCRYPTION_ERROR = "USER_DATA_ENCRYPTION_ERROR"; - String INVALID_PHONE_NO_FORMAT = "INVALID_PHONE_NO_FORMAT"; - String INVALID_WEBPAGE_DATA = "INVALID_WEBPAGE_DATA"; - String INVALID_MEDIA_TYPE = "INVALID_MEDIA_TYPE"; - String INVALID_WEBPAGE_URL = "INVALID_WEBPAGE_URL"; - String INVALID_DATE_RANGE = "INVALID_DATE_RANGE"; - String INVALID_BATCH_END_DATE_ERROR = "INVALID_BATCH_END_DATE_ERROR"; - String INVALID_BATCH_START_DATE_ERROR = "INVALID_BATCH_START_DATE_ERROR"; - String COURSE_BATCH_END_DATE_ERROR = "COURSE_BATCH_END_DATE_ERROR"; - String COURSE_BATCH_IS_CLOSED_ERROR = "COURSE_BATCH_IS_CLOSED_ERROR"; - String CONFIIRM_PASSWORD_MISSING = "CONFIIRM_PASSWORD_MISSING"; - String CONFIIRM_PASSWORD_EMPTY = "CONFIIRM_PASSWORD_EMPTY"; - String SAME_PASSWORD_ERROR = "SAME_PASSWORD_ERROR"; + String ASSERTION_ID_REQUIRED = "ASSERTION_ID_REQUIRED"; + String ASSERTION_EVIDENCE_REQUIRED = "ASSERTION_EVIDENCE_REQUIRED"; + String REVOCATION_REASON_REQUIRED = "REVOCATION_REASON_REQUIRED"; String ENDORSED_USER_ID_REQUIRED = "ENDORSED_USER_ID_REQUIRED"; String CAN_NOT_ENDORSE = "CAN_NOT_ENDORSE"; - String INVALID_ORG_TYPE_ID_ERROR = "INVALID_ORG_TYPE_ID_ERROR"; - String INVALID_ORG_TYPE_ERROR = "INVALID_ORG_TYPE_ERROR"; - String TABLE_OR_DOC_NAME_ERROR = "TABLE_OR_DOC_NAME_ERROR"; - String EMAIL_OR_PHONE_MISSING = "EMAIL_OR_PHONE_MISSING"; - String PHONE_ALREADY_IN_USE = "PHONE_ALREADY_IN_USE"; - String INVALID_CLIENT_NAME = "INVALID_CLIENT_NAME"; - String INVALID_CLIENT_ID = "INVALID_CLIENT_ID"; - String USER_PHONE_UPDATE_FAILED = "USER_PHONE_UPDATE_FAILED"; - String ES_UPDATE_FAILED = "ES_UPDATE_FAILED"; - String UPDATE_FAILED = "UPDATE_FAILED"; - String INVALID_TYPE_VALUE = "INVALID_TYPE_VALUE"; - String INVALID_LOCATION_ID = "INVALID_LOCATION_ID"; - String INVALID_HASHTAG_ID = "INVALID_HASHTAG_ID"; - String INVALID_USR_ORG_DATA = "INVALID_USR_ORG_DATA"; - String INVALID_VISIBILITY_REQUEST = "INVALID_VISIBILITY_REQUEST"; - String INVALID_TOPIC_NAME = "INVALID_TOPIC_NAME"; - String INVALID_TOPIC_DATA = "INVALID_TOPIC_DATA"; + + // ------------------------------------------------------------------------- + // Notifications & Email + // ------------------------------------------------------------------------- + String EMAIL_SUBJECT_ERROR = "EMAIL_SUBJECT_ERROR"; + String EMAIL_BODY_ERROR = "EMAIL_BODY_ERROR"; + String EMAIL_RECIPIENTS_EXCEEDS_MAX_LIMIT = "EMAIL_RECIPIENTS_EXCEEDS_MAX_LIMIT"; + String NO_EMAIL_RECIPIENTS = "NO_EMAIL_RECIPIENTS"; + String MESSAGE_ID_MISSING = "MESSAGE_ID_MISSING"; String INVALID_NOTIFICATION_TYPE = "INVALID_NOTIFICATION_TYPE"; String INVALID_NOTIFICATION_TYPE_SUPPORT = "INVALID_NOTIFICATION_TYPE_SUPPORT"; - String INVALID_PHONE_NUMBER = "INVALID_PHONE_NUMBER"; - String INVALID_COUNTRY_CODE = "INVALID_COUNTRY_CODE"; - String LOCATION_ID_REQUIRED = "LOCATION_ID_REQUIRED"; - String NOT_SUPPORTED = "NOT_SUPPORTED"; - String USERNAME_USERID_MISSING = "USERNAME_USERID_MISSING"; - String CHANNEL_REG_FAILED = "CHANNEL_REG_FAILED"; - String INVALID_COURSE_CREATOR_ID = "INVALID_COURSE_CREATOR_ID"; - String USER_NOT_ASSOCIATED_TO_ROOT_ORG = "USER_NOT_ASSOCIATED_TO_ROOT_ORG"; - String SLUG_IS_NOT_UNIQUE = "SLUG_IS_NOT_UNIQUE"; - String RECIPIENT_ID_REQUIRED = "RECIPIENT_ID_REQUIRED"; - String RECIPIENT_TYPE_REQUIRED = "RECIPIENT_TYPE_REQUIRED"; - String RESOURCE_NOT_FOUND = "RESOURCE_NOT_FOUND"; - String MAX_ALLOWED_SIZE_LIMIT_EXCEED = "MAX_ALLOWED_SIZE_LIMIT_EXCEED"; - String SLUG_REQUIRED = "SLUG_REQUIRED"; - String INVALID_ISSUER_ID = "INVALID_ISSUER_ID"; - String REVOCATION_REASON_REQUIRED = "REVOCATION_REASON_REQUIRED"; - String INVALID_RECIPIENT_TYPE = "INVALID_RECIPIENT_TYPE"; - String CUSTOM_SERVER_ERROR = "SERVER_ERROR"; + String INVALID_TOPIC_NAME = "INVALID_TOPIC_NAME"; + String INVALID_TOPIC_DATA = "INVALID_TOPIC_DATA"; + + // ------------------------------------------------------------------------- + // System, Config & Infrastructure + // ------------------------------------------------------------------------- + String ERROR_INVALID_CONFIG_PARAM_VALUE = "ERROR_INVALID_CONFIG_PARAM_VALUE"; + String ERROR_CONFIG_LOAD_EMPTY_STRING = "ERROR_CONFIG_LOAD_EMPTY_STRING"; + String ERROR_CONFIG_LOAD_PARSE_STRING = "ERROR_CONFIG_LOAD_PARSE_STRING"; + String ERROR_CONFIG_LOAD_EMPTY_CONFIG = "ERROR_CONFIG_LOAD_EMPTY_CONFIG"; + String ERROR_CONFLICTING_FIELD_CONFIGURATION = "ERROR_CONFLICTING_FIELD_CONFIGURATION"; + String MANDATORY_CONFIG_PARAMETER_MISSING = "MANDATORY_CONFIG_PARAMETER_MISSING"; + String ERROR_LOAD_CONFIG = "ERROR_LOAD_CONFIG"; + String ERROR_SYSTEM_SETTING_NOT_FOUND = "ERROR_SYSTEM_SETTING_NOT_FOUND"; + String ERROR_UPDATE_SETTING_NOT_ALLOWED = "ERROR_UPDATE_SETTING_NOT_ALLOWED"; + String DB_INSERTION_FAIL = "DB_INSERTION_FAIL"; + String DB_UPDATE_FAIL = "DB_UPDATE_FAIL"; + String ES_ERROR = "ELASTICSEARCH_ERROR"; + String ES_UPDATE_FAILED = "ES_UPDATE_FAILED"; + String UNABLE_TO_CONNECT_TO_EKSTEP = "UNABLE_TO_CONNECT_TO_EKSTEP"; + String UNABLE_TO_CONNECT_TO_ES = "UNABLE_TO_CONNECT_TO_ES"; + String UNABLE_TO_COMMUNICATE_WITH_ACTOR = "UNABLE_TO_COMMUNICATE_WITH_ACTOR"; + String ACTOR_CONNECTION_ERROR = "ACTOR_CONNECTION_ERROR"; + String CASSANDRA_CONNECTION_ESTABLISHMENT_FAILED = "CASSANDRA_CONNECTION_ESTABLISHMENT_FAILED"; + String CLOUD_SERVICE_ERROR = "CLOUD_SERVICE_ERROR"; + String ERROR_UNSUPPORTED_CLOUD_STORAGE = "ERROR_ UNSUPPORTED_CLOUD_STORAGE"; + String STORAGE_CONTAINER_NAME_MANDATORY = "STORAGE_CONTAINER_NAME_MANDATORY"; + String ERROR_GENERATE_DOWNLOAD_LINK = "ERROR_GENERATING_DOWNLOAD_LINK"; + String ERROR_DOWNLOAD_LINK_UNAVAILABLE = "ERROR_DOWNLOAD_LINK_UNAVAILABLE"; + String ERROR_SAVING_STORAGE_DETAILS = "ERROR_SAVING_STORAGE_DETAILS"; + String ERROR_UPLOAD_QRCODE_CSV_FAILED = "ERROR_UPLOAD_QRCODE_CSV_FAILED"; + String ERR_CALLING_GROUP_API = "ERR_CALLING_GROUOP_API"; + String ERR_CALLING_EXHAUST_API = "ERR_CALLING_EXHAUST_API"; + + // ------------------------------------------------------------------------- + // Files & Uploads + // ------------------------------------------------------------------------- + String INVALID_CSV_FILE = "INVALID_CSV_FILE"; + String ERROR_CSV_NO_DATA_ROWS = "ERROR_CSV_NO_DATA_ROWS"; + String EMPTY_CSV_FILE = "EMPTY_CSV_FILE"; + String EMPTY_HEADER_LINE = "EMPTY_HEADER_LINE"; + String BULK_USER_UPLOAD_ERROR = "BULK_USER_UPLOAD_ERROR"; + String DATA_SIZE_EXCEEDED = "DATA_SIZE_EXCEEDED"; + String ERROR_MAX_SIZE_EXCEEDED = "ERROR_MAX_SIZE_EXCEEDED"; + String MISSING_FILE_ATTACHMENT = "MISSING_FILE_ATTACHMENT"; + String EMPTY_FILE = "EMPTY_FILE"; + String FILE_ATTACHMENT_SIZE_NOT_CONFIGURED = "ATTACHMENT_SIZE_NOT_CONFIGURED"; + String ERROR_CREATING_FILE = "ERROR_CREATING_FILE"; + String ERROR_PROCESSING_FILE = "ERROR_PROCESSING_FILE"; + String ERROR_PROCESSING_REQUEST = "ERROR_PROCESSING_REQUEST"; + + // ------------------------------------------------------------------------- + // Miscellaneous + // ------------------------------------------------------------------------- + String PAGE_NAME_REQUIRED = "PAGE_NAME_REQUIRED"; + String PAGE_ID_REQUIRED = "PAGE_ID_REQUIRED"; + String PAGE_ALREADY_EXIST = "PAGE_ALREADY_EXIST"; String PAGE_NOT_EXIST = "PAGE_NOT_EXIST"; - String SECTION_NOT_EXIST = "SECTION_NOT_EXIST"; - String ORG_NOT_EXIST = "ORG_NOT_EXIST"; String INVALID_PAGE_SOURCE = "INVALID_PAGE_SOURCE"; - String LOCATION_TYPE_REQUIRED = "LOCATION_TYPE_REQUIRED"; - String INVALID_REQUEST_DATA_FOR_LOCATION = "INVALID_REQUEST_DATA_CREATE_LOCATION"; - String ALREADY_EXISTS = "ALREADY_EXISTS"; - String INVALID_VALUE = "INVALID_VALUE"; - String PARENT_CODE_AND_PARENT_ID_MISSING = "PARENT_CODE_AND_PARENT_ID_MISSING"; - String INVALID_PARAMETER = "INVALID_PARAMETER"; - String INVALID_LOCATION_DELETE_REQUEST = "INVALID_LOCATION_DELETE_REQUEST"; - String LOCATION_TYPE_CONFLICTS = "LOCATION_TYPE_CONFLICTS"; - String MANDATORY_PARAMETER_MISSING = "MANDATORY_PARAMETER_MISSING"; - String ERROR_MANDATORY_PARAMETER_EMPTY = "ERROR_MANDATORY_PARAMETER_EMPTY"; - String ERROR_NO_FRAMEWORK_FOUND = "ERROR_NO_FRAMEWORK_FOUND"; + String SECTION_NAME_MISSING = "SECTION_NAME_MISSING"; + String SECTION_DATA_TYPE_MISSING = "SECTION_DATA_TYPE_MISSING"; + String SECTION_ID_REQUIRED = "SECTION_ID_REQUIRED"; + String SECTION_NOT_EXIST = "SECTION_NOT_EXIST"; + String INVALID_PAGE_SECTION = "INVALID_PAGE_SECTION"; + String INVALID_WEBPAGE_DATA = "INVALID_WEBPAGE_DATA"; + String INVALID_MEDIA_TYPE = "INVALID_MEDIA_TYPE"; + String INVALID_WEBPAGE_URL = "INVALID_WEBPAGE_URL"; + String TITLE_REQUIRED = "TITLE_REQUIRED"; + String NOTE_REQUIRED = "NOTE_REQUIRED"; + String NOTE_ID_INVALID = "NOTE_ID_INVALID"; + String INVALID_TAGS = "INVALID_TAGS"; + String INVALID_CLIENT_NAME = "INVALID_CLIENT_NAME"; + String INVALID_CLIENT_ID = "INVALID_CLIENT_ID"; + String TABLE_OR_DOC_NAME_ERROR = "TABLE_OR_DOC_NAME_ERROR"; + String INVALID_DUPLICATE_VALUE = "INVALID_DUPLICATE_VALUE"; + String ERROR_DUPLICATE_ENTRY = "ERROR_DUPLICATE_ENTRY"; + String ERROR_DUPLICATE_ENTRIES = "ERROR_DUPLICATE_ENTRIES"; + String INVALID_PERIOD = "INVALID_PERIOD"; + String INVALID_DATE_RANGE = "INVALID_DATE_RANGE"; + String CYCLIC_VALIDATION_FAILURE = "CYCLIC_VALIDATION_FAILURE"; String UPDATE_NOT_ALLOWED = "UPDATE_NOT_ALLOWED"; - String MANDATORY_HEADER_MISSING = "MANDATORY_HEADER_MISSING"; - String INVALID_PARAMETER_VALUE = "INVALID_PARAMETER_VALUE"; - String PARENT_NOT_ALLOWED = "PARENT_NOT_ALLOWED"; - String MISSING_FILE_ATTACHMENT = "MISSING_FILE_ATTACHMENT"; - String FILE_ATTACHMENT_SIZE_NOT_CONFIGURED = "ATTACHMENT_SIZE_NOT_CONFIGURED"; - String EMPTY_FILE = "EMPTY_FILE"; + String STATUS_CANNOT_BE_UPDATED = "STATUS_CANNOT_BE_UPDATED"; + String UPDATE_FAILED = "UPDATE_FAILED"; + String INVALID_COLUMN_NAME = "INVALID_COLUMN_NAME"; String INVALID_COLUMNS = "INVALID_COLUMNS"; - String CONFLICTING_ORG_LOCATIONS = "CONFLICTING_ORG_LOCATIONS"; - String UNABLE_TO_COMMUNICATE_WITH_ACTOR = "UNABLE_TO_COMMUNICATE_WITH_ACTOR"; - String EMPTY_HEADER_LINE = "EMPTY_HEADER_LINE"; - String INVALID_REQUEST_PARAMETER = "INVALID_REQUEST_PARAMETER"; - String ROOT_ORG_ASSOCIATION_ERROR = "ROOT_ORG_ASSOCIATION_ERROR"; + String REQUIRED_HEADER_MISSING = "REQUIRED_HEADER_MISSING"; + String MANDATORY_HEADER_MISSING = "MANDATORY_HEADER_MISSING"; + String MANDATORY_HEADER_PARAMETER_MISSING = "MANDATORY_HEADER_PARAMETER_MISSING"; + String PARAMETER_MISMATCH = "PARAMETER_MISMATCH"; String DEPENDENT_PARAMETER_MISSING = "DEPENDENT_PARAMETER_MISSING"; - String EXTERNALID_NOT_FOUND = "EXTERNALID_NOT_FOUND"; - String EXTERNALID_ASSIGNED_TO_OTHER_USER = "EXTERNALID_ASSIGNED_TO_OTHER_USER"; - String MANDATORY_CONFIG_PARAMETER_MISSING = "MANDATORY_CONFIG_PARAMETER_MISSING"; - String CASSANDRA_CONNECTION_ESTABLISHMENT_FAILED = "CASSANDRA_CONNECTION_ESTABLISHMENT_FAILED"; + String DEPENDENT_PARAMS_MISSING = "DEPENDENT_PARAMETER_MISSING"; String COMMON_ATTRIBUTE_MISMATCH = "COMMON_ATTRIBUTE_MISMATCH"; - String MULTIPLE_COURSES_FOR_BATCH = "MULTIPLE_COURSES_FOR_BATCH"; + String ERROR_ATTRIBUTE_CONFLICT = "ERROR_ATTRIBUTE_CONFLICT"; + String EVENTS_DATA_MISSING = "EVENTS_DATA_MISSING"; + String GROUP_ID_MISSING = "GROUP_ID_MISSING"; + String ACTIVITY_ID_MISSING = "ACTIVITY_ID_MISSING"; + String ACTIVITY_TYPE_MISSING = "ACTIVITY_TYPE_MISSING"; + String ERROR_NO_DIALCODES_LINKED = "ERROR_NO_DIALCODES_LINKED"; + String SOURCE_MISSING = "SOURCE_MISSING"; + String INVALID_CONFIGURATION = "INVALID_CONFIGURATION"; + String INVALID_PROCESS_ID = "INVALID_PROCESS_ID"; + String INVALID_TYPE_VALUE = "INVALID_TYPE_VALUE"; + String ERROR_NO_FRAMEWORK_FOUND = "ERROR_NO_FRAMEWORK_FOUND"; + String VALID_IDENTIFIER_ABSENSE = "IDENTIFIER IN LIST IS NOT SUPPORTED OR INCORRECT"; + + // ------------------------------------------------------------------------- + // JSON Transform (Registry) + // ------------------------------------------------------------------------- String ERROR_JSON_TRANSFORM_INVALID_TYPE_CONFIG = "ERROR_JSON_TRANSFORM_INVALID_TYPE_CONFIG"; String ERROR_JSON_TRANSFORM_INVALID_DATE_FORMAT = "ERROR_JSON_TRANSFORM_INVALID_DATE_FORMAT"; String ERROR_JSON_TRANSFORM_INVALID_INPUT = "ERROR_JSON_TRANSFORM_INVALID_INPUT"; @@ -664,7 +817,6 @@ interface Key { String ERROR_JSON_TRANSFORM_BASIC_CONFIG_MISSING = "ERROR_JSON_TRANSFORM_BASIC_CONFIG_MISSING"; String ERROR_JSON_TRANSFORM_INVALID_FILTER_CONFIG = "ERROR_JSON_TRANSFORM_INVALID_FILTER_CONFIG"; - String ERROR_LOAD_CONFIG = "ERROR_LOAD_CONFIG"; String ERROR_REGISTRY_CLIENT_CREATION = "ERROR_REGISTRY_CLIENT_CREATION"; String ERROR_REGISTRY_ADD_ENTITY = "ERROR_REGISTRY_ADD_ENTITY"; String ERROR_REGISTRY_READ_ENTITY = "ERROR_REGISTRY_READ_ENTITY"; @@ -674,62 +826,5 @@ interface Key { String ERROR_REGISTRY_ENTITY_TYPE_BLANK = "ERROR_REGISTRY_ENTITY_TYPE_BLANK"; String ERROR_REGISTRY_ENTITY_ID_BLANK = "ERROR_REGISTRY_ENTITY_ID_BLANK"; String ERROR_REGISTRY_ACCESS_TOKEN_BLANK = "ERROR_REGISTRY_ACCESS_TOKEN_BLANK"; - String DUPLICATE_EXTERNAL_IDS = "DUPLICATE_EXTERNAL_IDS"; - String INVALID_DUPLICATE_VALUE = "INVALID_DUPLICATE_VALUE"; - String EMAIL_RECIPIENTS_EXCEEDS_MAX_LIMIT = "EMAIL_RECIPIENTS_EXCEEDS_MAX_LIMIT"; - String NO_EMAIL_RECIPIENTS = "NO_EMAIL_RECIPIENTS"; - String PARAMETER_MISMATCH = "PARAMETER_MISMATCH"; - String FORBIDDEN = "FORBIDDEN"; - String ERROR_CONFIG_LOAD_EMPTY_STRING = "ERROR_CONFIG_LOAD_EMPTY_STRING"; - String ERROR_CONFIG_LOAD_PARSE_STRING = "ERROR_CONFIG_LOAD_PARSE_STRING"; - String ERROR_CONFIG_LOAD_EMPTY_CONFIG = "ERROR_CONFIG_LOAD_EMPTY_CONFIG"; - String ERROR_CONFLICTING_FIELD_CONFIGURATION = "ERROR_CONFLICTING_FIELD_CONFIGURATION"; - String ERROR_SYSTEM_SETTING_NOT_FOUND = "ERROR_SYSTEM_SETTING_NOT_FOUND"; - String ERROR_NO_ROOT_ORG_ASSOCIATED = "ERROR_NO_ROOT_ORG_ASSOCIATED"; - String ERROR_INACTIVE_CUSTODIAN_ORG = "ERROR_INACTIVE_CUSTODIAN_ORG"; - String ERROR_UNSUPPORTED_CLOUD_STORAGE = "ERROR_ UNSUPPORTED_CLOUD_STORAGE"; - String ERROR_UNSUPPORTED_FIELD = "ERROR_UNSUPPORTED_FIELD"; - String ERROR_GENERATE_DOWNLOAD_LINK = "ERROR_GENERATING_DOWNLOAD_LINK"; - String ERROR_DOWNLOAD_LINK_UNAVAILABLE = "ERROR_DOWNLOAD_LINK_UNAVAILABLE"; - String ERROR_SAVING_STORAGE_DETAILS = "ERROR_SAVING_STORAGE_DETAILS"; - String ERROR_CSV_NO_DATA_ROWS = "ERROR_CSV_NO_DATA_ROWS"; - String ERROR_INACTIVE_ORG = "ERROR_INACTIVE_ORG"; - String ERROR_DUPLICATE_ENTRIES = "ERROR_DUPLICATE_ENTRIES"; - String ERROR_UPDATE_SETTING_NOT_ALLOWED = "ERROR_UPDATE_SETTING_NOT_ALLOWED"; - String ERROR_CREATING_FILE = "ERROR_CREATING_FILE"; - String ERROR_PROCESSING_REQUEST = "ERROR_PROCESSING_REQUEST"; - String ERROR_INVALID_OTP = "ERROR_INVALID_OTP"; - String REQUIRED_HEADER_MISSING = "REQUIRED_HEADER_MISSING"; - String ERROR_PROCESSING_FILE = "ERROR_PROCESSING_FILE"; - String ERROR_INVALID_PARAMETER_SIZE = "ERROR_INVALID_PARAMETER_SIZE"; - String INVALID_PAGE_SECTION = "INVALID_PAGE_SECTION"; - String ERROR_RATE_LIMIT_EXCEEDED = "ERROR_RATE_LIMIT_EXCEEDED"; - String ERROR_INVALID_CONFIG_PARAM_VALUE = "ERROR_INVALID_CONFIG_PARAM_VALUE"; - String ERROR_MAX_SIZE_EXCEEDED = "ERROR_MAX_SIZE_EXCEEDED"; - String INVALID_REQUEST_TIMEOUT = "INVALID_REQUEST_TIMEOUT"; - String VALID_IDENTIFIER_ABSENSE = "IDENTIFIER IN LIST IS NOT SUPPORTED OR INCORRECT"; - String FROM_ACCOUNT_ID_MISSING = "FROM_ACCOUNT_ID_MISSING"; - String TO_ACCOUNT_ID_MISSING = "TO_ACCOUNT_ID_MISSING"; - String FROM_ACCOUNT_ID_NOT_EXISTS = "FROM_ACCOUNT_ID_NOT_EXISTS"; - String MANDATORY_HEADER_PARAMETER_MISSING = "MANDATORY_HEADER_PARAMETER_MISSING"; - String ERROR_USER_HAS_NOT_CREATED_ANY_COURSE = "USER_HAS_NOT_CREATED_ANY_COURSE"; - String ERROR_UPLOAD_QRCODE_CSV_FAILED = "ERROR_UPLOAD_QRCODE_CSV_FAILED"; - String ERROR_NO_DIALCODES_LINKED = "ERROR_NO_DIALCODES_LINKED"; - String EVENTS_DATA_MISSING = "EVENTS_DATA_MISSING"; - String ACCOUNT_NOT_FOUND = "ACCOUNT_NOT_FOUND"; - String INVALID_EXT_USER_ID = "INVALID_EXT_USER_ID"; - String USER_MIGRATION_FAILED = "USER_MIGRATION_FAILED"; - String INVALID_ELEMENT_IN_LIST = "INVALID_ELEMENT_IN_LIST"; - String INVALID_PASSWORD = "INVALID_PASSWORD"; - String OTP_VERIFICATION_FAILED = "OTP_VERIFICATION_FAILED"; - String SERVICE_UNAVAILABLE = "SERVICE_UNAVAILABLE"; - String MISSING_CODE = "ERR_COURSE_CREATE_FIELDS_MISSING"; - String CONTENT_TYPE_MISMATCH = "CONTENT_TYPE_MISMATCH"; - String MIME_TYPE_MISMATCH = "MIME_TYPE_MISMATCH"; - String GROUP_ID_MISSING = "GROUP_ID_MISSING"; - String ACTIVITY_ID_MISSING = "ACTIVITY_ID_MISSING"; - String ACTIVITY_TYPE_MISSING = "ACTIVITY_TYPE_MISSING"; - String ERR_CALLING_GROUP_API = "ERR_CALLING_GROUOP_API"; - String ERR_CALLING_EXHAUST_API = "ERR_CALLING_EXHAUST_API"; } } diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/response/ResponseParams.java b/core/sunbird-platform-common/src/main/java/org/sunbird/response/ResponseParams.java similarity index 50% rename from course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/response/ResponseParams.java rename to core/sunbird-platform-common/src/main/java/org/sunbird/response/ResponseParams.java index d214aa666..09855e6a3 100644 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/response/ResponseParams.java +++ b/core/sunbird-platform-common/src/main/java/org/sunbird/response/ResponseParams.java @@ -1,25 +1,35 @@ -package org.sunbird.common.models.response; - +package org.sunbird.response; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; - import java.io.Serializable; /** - * This class will contains response envelop. - * - * @author Manzarul + * Encapsulates the response parameter envelope for API responses. + * Contains metadata such as message IDs, status (SUCCESSFUL/FAILED), and error details. */ @JsonIgnoreProperties(ignoreUnknown = true) public class ResponseParams implements Serializable { private static final long serialVersionUID = 6772142067149203497L; + + /** Unique response message ID. */ private String resmsgid; + + /** Request-specific message ID. */ private String msgid; + + /** Error code, if applicable. */ private String err; + + /** API call status (e.g., "successful"). */ private String status; + + /** Descriptive error message in English. */ private String errmsg; + /** + * Enum representing standard API status types. + */ public enum StatusType { SUCCESSFUL, WARNING, @@ -27,92 +37,92 @@ public enum StatusType { } /** - * This will contains response message id. + * Gets the unique response message ID. * - * @return String + * @return The response message ID string. */ public String getResmsgid() { return resmsgid; } /** - * set the response message id. + * Sets the unique response message ID. * - * @param resmsgid String + * @param resmsgid The response message ID string. */ public void setResmsgid(String resmsgid) { this.resmsgid = resmsgid; } /** - * This will provide request specific message id. + * Gets the request-specific message ID. * - * @return String + * @return The message ID string. */ public String getMsgid() { return msgid; } /** - * Set the request specific message id. + * Sets the request-specific message ID. * - * @param msgid + * @param msgid The message ID string. */ public void setMsgid(String msgid) { this.msgid = msgid; } /** - * This will provide error message + * Gets the error code. * - * @return String + * @return The error code string, or null if successful. */ public String getErr() { return err; } /** - * Set the error message + * Sets the error code. * - * @param err String + * @param err The error code string. */ public void setErr(String err) { this.err = err; } /** - * This will return api call status + * Gets the API status. * - * @return String + * @return The status string. */ public String getStatus() { return status; } /** - * Set the api call status + * Sets the API status. * - * @param status + * @param status The status string. */ public void setStatus(String status) { this.status = status; } /** - * This will provide Error message in english + * Gets the descriptive error message. * - * @return String + * @return The error message string. */ public String getErrmsg() { return errmsg; } /** - * Set the error message in English. + * Sets the descriptive error message. * - * @param message String + * @param message The error message string. */ public void setErrmsg(String message) { this.errmsg = message; } -} +} \ No newline at end of file diff --git a/core/sunbird-platform-common/src/main/java/org/sunbird/telemetry/collector/TelemetryAssemblerFactory.java b/core/sunbird-platform-common/src/main/java/org/sunbird/telemetry/collector/TelemetryAssemblerFactory.java new file mode 100644 index 000000000..7446b11d4 --- /dev/null +++ b/core/sunbird-platform-common/src/main/java/org/sunbird/telemetry/collector/TelemetryAssemblerFactory.java @@ -0,0 +1,32 @@ +package org.sunbird.telemetry.collector; + +/** + * Factory class to provide an instance of TelemetryDataAssembler. + * This class follows the creation pattern to ensure a single instance of TelemetryDataAssembler is used. + */ +public class TelemetryAssemblerFactory { + + private static TelemetryDataAssembler telemetryDataAssembler = null; + + /** + * Private constructor to prevent instantiation. + */ + private TelemetryAssemblerFactory() {} + + /** + * Returns the singleton instance of TelemetryDataAssembler. + * If the instance supports lazy initialization, it creates one in a thread-safe manner. + * + * @return TelemetryDataAssembler instance + */ + public static TelemetryDataAssembler get() { + if (telemetryDataAssembler == null) { + synchronized (TelemetryAssemblerFactory.class) { + if (telemetryDataAssembler == null) { + telemetryDataAssembler = new TelemetryDataAssemblerImpl(); + } + } + } + return telemetryDataAssembler; + } +} diff --git a/core/sunbird-platform-common/src/main/java/org/sunbird/telemetry/collector/TelemetryDataAssembler.java b/core/sunbird-platform-common/src/main/java/org/sunbird/telemetry/collector/TelemetryDataAssembler.java new file mode 100644 index 000000000..1b061b677 --- /dev/null +++ b/core/sunbird-platform-common/src/main/java/org/sunbird/telemetry/collector/TelemetryDataAssembler.java @@ -0,0 +1,45 @@ +package org.sunbird.telemetry.collector; + +import java.util.Map; + +/** + * Interface defining the contract for assembling and generating various telemetry events. + */ +public interface TelemetryDataAssembler { + + /** + * Generates an AUDIT telemetry event. + * + * @param context Context map containing telemetry context information (e.g., channel, pdata, env, etc.) + * @param params Parameters map containing event-specific data + * @return The generated telemetry event as a JSON string + */ + String audit(Map context, Map params); + + /** + * Generates a SEARCH telemetry event. + * + * @param context Context map containing telemetry context information + * @param params Parameters map containing search-specific data (e.g., query, filters, sort, correlation) + * @return The generated telemetry event as a JSON string + */ + String search(Map context, Map params); + + /** + * Generates a LOG telemetry event. + * + * @param context Context map containing telemetry context information + * @param params Parameters map containing log-specific data (e.g., type, level, message, params) + * @return The generated telemetry event as a JSON string + */ + String log(Map context, Map params); + + /** + * Generates an ERROR telemetry event. + * + * @param context Context map containing telemetry context information + * @param params Parameters map containing error-specific data (e.g., err, errtype, stacktrace) + * @return The generated telemetry event as a JSON string + */ + String error(Map context, Map params); +} diff --git a/core/sunbird-platform-common/src/main/java/org/sunbird/telemetry/collector/TelemetryDataAssemblerImpl.java b/core/sunbird-platform-common/src/main/java/org/sunbird/telemetry/collector/TelemetryDataAssemblerImpl.java new file mode 100644 index 000000000..9d133a856 --- /dev/null +++ b/core/sunbird-platform-common/src/main/java/org/sunbird/telemetry/collector/TelemetryDataAssemblerImpl.java @@ -0,0 +1,59 @@ +package org.sunbird.telemetry.collector; + +import java.util.Map; +import org.sunbird.telemetry.util.TelemetryGenerator; + +/** + * Implementation of the TelemetryDataAssembler interface. + * Delegates the actual generation of telemetry events to the TelemetryGenerator utility. + */ +public class TelemetryDataAssemblerImpl implements TelemetryDataAssembler { + + /** + * Generates an AUDIT telemetry event using TelemetryGenerator. + * + * @param context Context map containing telemetry context information + * @param params Parameters map containing event-specific data + * @return The generated telemetry event as a JSON string + */ + @Override + public String audit(Map context, Map params) { + return TelemetryGenerator.audit(context, params); + } + + /** + * Generates a SEARCH telemetry event using TelemetryGenerator. + * + * @param context Context map containing telemetry context information + * @param params Parameters map containing search-specific data + * @return The generated telemetry event as a JSON string + */ + @Override + public String search(Map context, Map params) { + return TelemetryGenerator.search(context, params); + } + + /** + * Generates a LOG telemetry event using TelemetryGenerator. + * + * @param context Context map containing telemetry context information + * @param params Parameters map containing log-specific data + * @return The generated telemetry event as a JSON string + */ + @Override + public String log(Map context, Map params) { + return TelemetryGenerator.log(context, params); + } + + /** + * Generates an ERROR telemetry event using TelemetryGenerator. + * + * @param context Context map containing telemetry context information + * @param params Parameters map containing error-specific data + * @return The generated telemetry event as a JSON string + */ + @Override + public String error(Map context, Map params) { + return TelemetryGenerator.error(context, params); + } +} diff --git a/core/sunbird-platform-common/src/main/java/org/sunbird/telemetry/dto/Actor.java b/core/sunbird-platform-common/src/main/java/org/sunbird/telemetry/dto/Actor.java new file mode 100644 index 000000000..8617b2771 --- /dev/null +++ b/core/sunbird-platform-common/src/main/java/org/sunbird/telemetry/dto/Actor.java @@ -0,0 +1,64 @@ +package org.sunbird.telemetry.dto; + +/** + * Represents the 'Actor' in a telemetry event. + * The Actor is the entity (User, System, etc.) that performs the action being logged. + */ +public class Actor { + + private String id; + private String type; + + /** + * Default constructor. + */ + public Actor() {} + + /** + * Parameterized constructor to initialize the Actor. + * + * @param id The unique identifier of the actor (e.g., User ID). + * @param type The type of the actor (e.g., 'User', 'System'). + */ + public Actor(String id, String type) { + super(); + this.id = id; + this.type = type; + } + + /** + * Gets the unique identifier of the actor. + * + * @return the id of the actor + */ + public String getId() { + return id; + } + + /** + * Sets the unique identifier of the actor. + * + * @param id the id to set + */ + public void setId(String id) { + this.id = id; + } + + /** + * Gets the type of the actor. + * + * @return the type of the actor + */ + public String getType() { + return type; + } + + /** + * Sets the type of the actor. + * + * @param type the type to set + */ + public void setType(String type) { + this.type = type; + } +} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/telemetry/dto/Context.java b/core/sunbird-platform-common/src/main/java/org/sunbird/telemetry/dto/Context.java similarity index 51% rename from course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/telemetry/dto/Context.java rename to core/sunbird-platform-common/src/main/java/org/sunbird/telemetry/dto/Context.java index 9ba76faca..dedaaaf47 100644 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/telemetry/dto/Context.java +++ b/core/sunbird-platform-common/src/main/java/org/sunbird/telemetry/dto/Context.java @@ -1,4 +1,3 @@ -/** */ package org.sunbird.telemetry.dto; import com.fasterxml.jackson.annotation.JsonInclude; @@ -8,6 +7,10 @@ import java.util.List; import java.util.Map; +/** + * Represents the context of a telemetry event. + * Contains information about the environment, actor, channel, and other contextual data. + */ @JsonInclude(Include.NON_NULL) public class Context { @@ -18,8 +21,18 @@ public class Context { private List> cdata = new ArrayList<>(); private Map rollup = new HashMap<>(); + /** + * Default constructor. + */ public Context() {} + /** + * Parameterized constructor to initialize the Context. + * + * @param channel The channel ID + * @param env The environment (e.g., 'dev', 'prod') + * @param pdata The producer data + */ public Context(String channel, String env, Producer pdata) { super(); this.channel = channel; @@ -27,58 +40,110 @@ public Context(String channel, String env, Producer pdata) { this.pdata = pdata; } + /** + * Gets the rollup data. + * + * @return a map containing rollup data + */ public Map getRollup() { return rollup; } + /** + * Sets the rollup data. + * + * @param rollup a map containing rollup data to set + */ public void setRollup(Map rollup) { this.rollup = rollup; } + /** + * Gets the correlation data (cdata). + * + * @return a list of maps containing correlation data + */ public List> getCdata() { return cdata; } + /** + * Sets the correlation data (cdata). + * + * @param cdata a list of maps containing correlation data to set + */ public void setCdata(List> cdata) { this.cdata = cdata; } - /** @return the channel */ + /** + * Gets the channel ID. + * + * @return the channel + */ public String getChannel() { return channel; } - /** @param channel the channel to set */ + /** + * Sets the channel ID. + * + * @param channel the channel to set + */ public void setChannel(String channel) { this.channel = channel; } - /** @return the pdata */ + /** + * Gets the producer data. + * + * @return the pdata + */ public Producer getPdata() { return pdata; } - /** @param pdata the pdata to set */ + /** + * Sets the producer data. + * + * @param pdata the pdata to set + */ public void setPdata(Producer pdata) { this.pdata = pdata; } - /** @return the env */ + /** + * Gets the environment. + * + * @return the env + */ public String getEnv() { return env; } - /** @param env the env to set */ + /** + * Sets the environment. + * + * @param env the env to set + */ public void setEnv(String env) { this.env = env; } - /** @return the did */ + /** + * Gets the device ID. + * + * @return the did + */ public String getDid() { return did; } - /** @param did the did to set */ + /** + * Sets the device ID. + * + * @param did the did to set + */ public void setDid(String did) { this.did = did; } diff --git a/core/sunbird-platform-common/src/main/java/org/sunbird/telemetry/dto/Producer.java b/core/sunbird-platform-common/src/main/java/org/sunbird/telemetry/dto/Producer.java new file mode 100644 index 000000000..be49c8182 --- /dev/null +++ b/core/sunbird-platform-common/src/main/java/org/sunbird/telemetry/dto/Producer.java @@ -0,0 +1,100 @@ +package org.sunbird.telemetry.dto; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; + +/** + * Represents the producer of a telemetry event. + * The Producer is the system/subsystem that generated the event. + */ +@JsonInclude(Include.NON_NULL) +public class Producer { + + private String id; + private String pid; + private String ver; + + /** + * Default constructor. + */ + public Producer() {} + + /** + * Parameterized constructor. + * + * @param id The unique identifier of the producer + * @param ver The version of the producer + */ + public Producer(String id, String ver) { + super(); + this.id = id; + this.ver = ver; + } + + /** + * Parameterized constructor. + * + * @param id The unique identifier of the producer + * @param pid The producer ID (optional/alternative) + * @param ver The version of the producer + */ + public Producer(String id, String pid, String ver) { + this.id = id; + this.pid = pid; + this.ver = ver; + } + + /** + * Gets the producer ID. + * + * @return the id + */ + public String getId() { + return id; + } + + /** + * Sets the producer ID. + * + * @param id the id to set + */ + public void setId(String id) { + this.id = id; + } + + /** + * Gets the producer PID. + * + * @return the pid + */ + public String getPid() { + return pid; + } + + /** + * Sets the producer PID. + * + * @param pid the pid to set + */ + public void setPid(String pid) { + this.pid = pid; + } + + /** + * Gets the producer version. + * + * @return the ver + */ + public String getVer() { + return ver; + } + + /** + * Sets the producer version. + * + * @param ver the ver to set + */ + public void setVer(String ver) { + this.ver = ver; + } +} diff --git a/core/sunbird-platform-common/src/main/java/org/sunbird/telemetry/dto/Target.java b/core/sunbird-platform-common/src/main/java/org/sunbird/telemetry/dto/Target.java new file mode 100644 index 000000000..75bc947d2 --- /dev/null +++ b/core/sunbird-platform-common/src/main/java/org/sunbird/telemetry/dto/Target.java @@ -0,0 +1,107 @@ +package org.sunbird.telemetry.dto; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import java.util.Map; + +/** + * Represents the target object of a telemetry event. + * The Target identifies the object being acted upon (e.g., Content, Item, User). + */ +@JsonInclude(Include.NON_NULL) +public class Target { + + private String id; + private String type; + private String ver; + private Map rollup; + + /** + * Default constructor. + */ + public Target() {} + + /** + * Parameterized constructor to initialize the Target. + * + * @param id The unique identifier of the target object + * @param type The type of the target object + */ + public Target(String id, String type) { + super(); + this.id = id; + this.type = type; + } + + /** + * Gets the rollup data. + * + * @return a map containing rollup data + */ + public Map getRollup() { + return rollup; + } + + /** + * Sets the rollup data. + * + * @param rollup a map containing rollup data to set + */ + public void setRollup(Map rollup) { + this.rollup = rollup; + } + + /** + * Gets the target ID. + * + * @return the id + */ + public String getId() { + return id; + } + + /** + * Sets the target ID. + * + * @param id the id to set + */ + public void setId(String id) { + this.id = id; + } + + /** + * Gets the target type. + * + * @return the type + */ + public String getType() { + return type; + } + + /** + * Sets the target type. + * + * @param type the type to set + */ + public void setType(String type) { + this.type = type; + } + + /** + * Gets the target version. + * + * @return the ver + */ + public String getVer() { + return ver; + } + + /** + * Sets the target version. + * + * @param ver the ver to set + */ + public void setVer(String ver) { + this.ver = ver; + } +} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/telemetry/dto/Telemetry.java b/core/sunbird-platform-common/src/main/java/org/sunbird/telemetry/dto/Telemetry.java similarity index 52% rename from course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/telemetry/dto/Telemetry.java rename to core/sunbird-platform-common/src/main/java/org/sunbird/telemetry/dto/Telemetry.java index d468b92ae..bbe878a0e 100644 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/telemetry/dto/Telemetry.java +++ b/core/sunbird-platform-common/src/main/java/org/sunbird/telemetry/dto/Telemetry.java @@ -6,7 +6,10 @@ import java.util.Map; import java.util.UUID; -/** Telemetry V3 POJO to generate telemetry event. */ +/** + * Telemetry V3 POJO to generate telemetry event. + * Represents the structure of a standard Sunbird telemetry event. + */ @JsonInclude(Include.NON_NULL) public class Telemetry { @@ -20,8 +23,20 @@ public class Telemetry { private Map edata; private List tags; + /** + * Default constructor. + */ public Telemetry() {} + /** + * Parameterized constructor. + * + * @param eid The event ID (e.g., AUDIT, LOG, SEARCH) + * @param actor The actor performing the event + * @param context The context of the event + * @param edata The event data + * @param object The target object of the event + */ public Telemetry( String eid, Actor actor, Context context, Map edata, Target object) { super(); @@ -32,6 +47,14 @@ public Telemetry( this.object = object; } + /** + * Parameterized constructor (without target object). + * + * @param eid The event ID + * @param actor The actor performing the event + * @param context The context of the event + * @param edata The event data + */ public Telemetry(String eid, Actor actor, Context context, Map edata) { super(); this.eid = eid; @@ -40,92 +63,164 @@ public Telemetry(String eid, Actor actor, Context context, Map e this.edata = edata; } - /** @return the eid */ + /** + * Gets the event ID. + * + * @return the eid + */ public String getEid() { return eid; } - /** @param eid the eid to set */ + /** + * Sets the event ID. + * + * @param eid the eid to set + */ public void setEid(String eid) { this.eid = eid; } - /** @return the ets */ + /** + * Gets the event timestamp. + * + * @return the ets + */ public long getEts() { return ets; } - /** @param ets the ets to set */ + /** + * Sets the event timestamp. + * + * @param ets the ets to set + */ public void setEts(long ets) { this.ets = ets; } - /** @return the ver */ + /** + * Gets the version. + * + * @return the ver + */ public String getVer() { return ver; } - /** @param ver the ver to set */ + /** + * Sets the version. + * + * @param ver the ver to set + */ public void setVer(String ver) { this.ver = ver; } - /** @return the mid */ + /** + * Gets the message ID. + * + * @return the mid + */ public String getMid() { return mid; } - /** @param mid the mid to set */ + /** + * Sets the message ID. + * + * @param mid the mid to set + */ public void setMid(String mid) { this.mid = mid; } - /** @return the actor */ + /** + * Gets the actor. + * + * @return the actor + */ public Actor getActor() { return actor; } - /** @param actor the actor to set */ + /** + * Sets the actor. + * + * @param actor the actor to set + */ public void setActor(Actor actor) { this.actor = actor; } - /** @return the context */ + /** + * Gets the context. + * + * @return the context + */ public Context getContext() { return context; } - /** @param context the context to set */ + /** + * Sets the context. + * + * @param context the context to set + */ public void setContext(Context context) { this.context = context; } - /** @return the object */ + /** + * Gets the target object. + * + * @return the object + */ public Target getObject() { return object; } - /** @param object the object to set */ + /** + * Sets the target object. + * + * @param object the object to set + */ public void setObject(Target object) { this.object = object; } - /** @return the edata */ + /** + * Gets the event data. + * + * @return the edata + */ public Map getEdata() { return edata; } - /** @param edata the edata to set */ + /** + * Sets the event data. + * + * @param edata the edata to set + */ public void setEdata(Map edata) { this.edata = edata; } - /** @return the tags */ + /** + * Gets the tags. + * + * @return the tags + */ public List getTags() { return tags; } - /** @param tags the tags to set */ + /** + * Sets the tags. + * + * @param tags the tags to set + */ public void setTags(List tags) { this.tags = tags; } diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/telemetry/dto/TelemetryBEEvent.java b/core/sunbird-platform-common/src/main/java/org/sunbird/telemetry/dto/TelemetryBEEvent.java similarity index 55% rename from course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/telemetry/dto/TelemetryBEEvent.java rename to core/sunbird-platform-common/src/main/java/org/sunbird/telemetry/dto/TelemetryBEEvent.java index c82a58594..c13da222f 100644 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/telemetry/dto/TelemetryBEEvent.java +++ b/core/sunbird-platform-common/src/main/java/org/sunbird/telemetry/dto/TelemetryBEEvent.java @@ -3,6 +3,10 @@ import java.util.HashMap; import java.util.Map; +/** + * Represents a Backend (BE) Telemetry Event. + * This class captures telemetry data generated by backend services. + */ public class TelemetryBEEvent { private String eid; @@ -13,47 +17,105 @@ public class TelemetryBEEvent { private Map pdata; private Map edata; + /** + * Gets the event ID. + * + * @return the eid + */ public String getEid() { return eid; } + /** + * Sets the event ID. + * + * @param eid the eid to set + */ public void setEid(String eid) { this.eid = eid; } + /** + * Gets the event timestamp. + * + * @return the ets + */ public long getEts() { return ets; } + /** + * Sets the event timestamp. + * + * @param ets the ets to set + */ public void setEts(long ets) { this.ets = ets; } + /** + * Gets the version. + * + * @return the ver + */ public String getVer() { return ver; } + /** + * Sets the version. + * + * @param ver the ver to set + */ public void setVer(String ver) { this.ver = ver; } + /** + * Gets the producer data. + * + * @return the pdata + */ public Map getPdata() { return pdata; } + /** + * Sets the producer data. + * + * @param pdata the pdata to set + */ public void setPdata(Map pdata) { this.pdata = pdata; } + /** + * Gets the event data. + * + * @return the edata + */ public Map getEdata() { return edata; } + /** + * Sets the event data with specific eks map. + * + * @param eks the eks map to be put inside edata + */ public void setEdata(Map eks) { this.edata = new HashMap<>(); edata.put("eks", eks); } + /** + * Sets the producer data with specific fields. + * + * @param id Producer ID + * @param pid Producer PID + * @param ver Producer Version + * @param uid User ID (Note: unused in implementation but present in signature) + */ public void setPdata(String id, String pid, String ver, String uid) { this.pdata = new HashMap<>(); this.pdata.put("id", id); @@ -61,6 +123,16 @@ public void setPdata(String id, String pid, String ver, String uid) { this.pdata.put("ver", ver); } + /** + * Sets edata for Content events. + * + * @param cid Content ID + * @param status Content Status + * @param prevState Previous State + * @param size Size + * @param pkgVersion Package Version + * @param concepts Concepts + */ public void setEdata( String cid, Object status, @@ -79,6 +151,15 @@ public void setEdata( edata.put("eks", eks); } + /** + * Sets edata for Search events. + * + * @param query Search query + * @param filters Search filters + * @param sort Search sort order + * @param correlationId Correlation ID + * @param size Result size + */ public void setEdata(String query, Object filters, Object sort, String correlationId, int size) { this.edata = new HashMap<>(); Map eks = new HashMap<>(); @@ -90,6 +171,14 @@ public void setEdata(String query, Object filters, Object sort, String correlati edata.put("eks", eks); } + /** + * Sets edata for Lifecycle/State change events. + * + * @param id Target ID + * @param state Current State + * @param prevState Previous State + * @param lemma Lemma (used in wordnet/language) or auxiliary data + */ public void setEdata(String id, Object state, Object prevState, Object lemma) { this.edata = new HashMap<>(); Map eks = new HashMap<>(); @@ -100,14 +189,29 @@ public void setEdata(String id, Object state, Object prevState, Object lemma) { edata.put("eks", eks); } + /** + * Gets the message ID. + * + * @return the mid + */ public String getMid() { return mid; } + /** + * Sets the message ID. + * + * @param mid the mid to set + */ public void setMid(String mid) { this.mid = mid; } + /** + * Gets the channel ID. + * + * @return the channel, or empty string if null + */ public String getChannel() { if (null == channel) { channel = ""; @@ -115,6 +219,11 @@ public String getChannel() { return channel; } + /** + * Sets the channel ID. + * + * @param channel the channel to set + */ public void setChannel(String channel) { String tempChannel = channel; if (null == channel) { diff --git a/core/sunbird-platform-common/src/main/java/org/sunbird/telemetry/dto/TelemetryBJREvent.java b/core/sunbird-platform-common/src/main/java/org/sunbird/telemetry/dto/TelemetryBJREvent.java new file mode 100644 index 000000000..2250dbec7 --- /dev/null +++ b/core/sunbird-platform-common/src/main/java/org/sunbird/telemetry/dto/TelemetryBJREvent.java @@ -0,0 +1,144 @@ +package org.sunbird.telemetry.dto; + +import java.util.Map; + +/** + * Represents a Backend Job/Request (BJR) Telemetry Event. + * This class captures telemetry data for background jobs or requests, often used for map-based telemetry structures. + */ +public class TelemetryBJREvent { + + private String eid; + private long ets; + private String mid; + private Map actor; + private Map context; + private Map object; + private Map edata; + + /** + * Gets the event ID. + * + * @return the eid + */ + public String getEid() { + return eid; + } + + /** + * Sets the event ID. + * + * @param eid the eid to set + */ + public void setEid(String eid) { + this.eid = eid; + } + + /** + * Gets the event timestamp. + * + * @return the ets + */ + public long getEts() { + return ets; + } + + /** + * Sets the event timestamp. + * + * @param ets the ets to set + */ + public void setEts(long ets) { + this.ets = ets; + } + + /** + * Gets the message ID. + * + * @return the mid + */ + public String getMid() { + return mid; + } + + /** + * Sets the message ID. + * + * @param mid the mid to set + */ + public void setMid(String mid) { + this.mid = mid; + } + + /** + * Gets the actor data map. + * + * @return the actor map + */ + public Map getActor() { + return actor; + } + + /** + * Sets the actor data map. + * + * @param actor the actor map to set + */ + public void setActor(Map actor) { + this.actor = actor; + } + + /** + * Gets the context data map. + * + * @return the context map + */ + public Map getContext() { + return context; + } + + /** + * Sets the context data map. + * + * @param context the context map to set + */ + public void setContext(Map context) { + this.context = context; + } + + /** + * Gets the object/target data map. + * + * @return the object map + */ + public Map getObject() { + return object; + } + + /** + * Sets the object/target data map. + * + * @param object the object map to set + */ + public void setObject(Map object) { + this.object = object; + } + + /** + * Gets the event data map. + * + * @return the edata map + */ + public Map getEdata() { + return edata; + } + + /** + * Sets the event data map. + * + * @param edata the edata map to set + */ + public void setEdata(Map edata) { + this.edata = edata; + } +} diff --git a/core/sunbird-platform-common/src/main/java/org/sunbird/telemetry/dto/TelemetryEnvKey.java b/core/sunbird-platform-common/src/main/java/org/sunbird/telemetry/dto/TelemetryEnvKey.java new file mode 100644 index 000000000..624427708 --- /dev/null +++ b/core/sunbird-platform-common/src/main/java/org/sunbird/telemetry/dto/TelemetryEnvKey.java @@ -0,0 +1,56 @@ +package org.sunbird.telemetry.dto; + +/** + * Constants for Telemetry Environment Keys. + * Defines the environment names used in various telemetry events. + */ +public class TelemetryEnvKey { + + /** Constant for User environment */ + public static final String USER = "User"; + + /** Constant for Organisation environment */ + public static final String ORGANISATION = "Organisation"; + + /** Constant for GeoLocation environment */ + public static final String GEO_LOCATION = "GeoLocation"; + + /** Constant for MasterKey environment */ + public static final String MASTER_KEY = "MasterKey"; + + /** Constant for ObjectStore environment */ + public static final String OBJECT_STORE = "ObjectStore"; + + /** Constant for Location environment */ + public static final String LOCATION = "Location"; + + /** Constant for Request environment */ + public static final String REQUEST_UPPER_CAMEL = "Request"; + + /** Constant for UserConsent environment */ + public static final String USER_CONSENT = "UserConsent"; + + /** Constant for Edata Type User Consent */ + public static final String EDATA_TYPE_USER_CONSENT = "user-consent"; + + /** Constant for CourseBatch environment */ + public static final String BATCH = "CourseBatch"; + + /** Constant for Page environment */ + public static final String PAGE = "Page"; + + /** Constant for PageSection environment */ + public static final String PAGE_SECTION = "PageSection"; + + /** Constant for QRCodeDownload environment */ + public static final String QR_CODE_DOWNLOAD = "QRCodeDownload"; + + /** Constant for COURSE_CREATE environment */ + public static final String COURSE_CREATE = "COURSE_CREATE"; + + /** Constant for Notification Created environment */ + public static final String NOTIFICATION_CREATED = "create-notification"; + + /** Private constructor to prevent instantiation. */ + private TelemetryEnvKey() {} +} diff --git a/core/sunbird-platform-common/src/main/java/org/sunbird/telemetry/util/TelemetryConstant.java b/core/sunbird-platform-common/src/main/java/org/sunbird/telemetry/util/TelemetryConstant.java new file mode 100644 index 000000000..059fa18ad --- /dev/null +++ b/core/sunbird-platform-common/src/main/java/org/sunbird/telemetry/util/TelemetryConstant.java @@ -0,0 +1,14 @@ +package org.sunbird.telemetry.util; + +/** + * Class contains Constants for telemetry. + * Defines standard constant values used for telemetry logging and processing. + */ +public class TelemetryConstant { + + /** Constant for Error log level */ + public static final String LOG_LEVEL_ERROR = "error"; + + /** Private constructor to prevent instantiation. */ + private TelemetryConstant() {} +} diff --git a/core/sunbird-platform-common/src/main/java/org/sunbird/telemetry/util/TelemetryEvents.java b/core/sunbird-platform-common/src/main/java/org/sunbird/telemetry/util/TelemetryEvents.java new file mode 100644 index 000000000..f76f282e6 --- /dev/null +++ b/core/sunbird-platform-common/src/main/java/org/sunbird/telemetry/util/TelemetryEvents.java @@ -0,0 +1,40 @@ +package org.sunbird.telemetry.util; + +/** + * Enumeration for telemetry events types. + * Defines the standard event names supported by the telemetry system. + */ +public enum TelemetryEvents { + + /** AUDIT Telemetry Event */ + AUDIT("AUDIT"), + + /** SEARCH Telemetry Event */ + SEARCH("SEARCH"), + + /** LOG Telemetry Event */ + LOG("LOG"), + + /** ERROR Telemetry Event */ + ERROR("ERROR"); + + private final String name; + + /** + * Private constructor for enum. + * + * @param name The name of the event + */ + TelemetryEvents(String name) { + this.name = name; + } + + /** + * Gets the name of the telemetry event. + * + * @return the name + */ + public String getName() { + return name; + } +} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/telemetry/util/TelemetryGenerator.java b/core/sunbird-platform-common/src/main/java/org/sunbird/telemetry/util/TelemetryGenerator.java similarity index 63% rename from course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/telemetry/util/TelemetryGenerator.java rename to core/sunbird-platform-common/src/main/java/org/sunbird/telemetry/util/TelemetryGenerator.java index 28a7c23b7..e7f40cd16 100644 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/telemetry/util/TelemetryGenerator.java +++ b/core/sunbird-platform-common/src/main/java/org/sunbird/telemetry/util/TelemetryGenerator.java @@ -1,42 +1,33 @@ package org.sunbird.telemetry.util; import com.fasterxml.jackson.databind.ObjectMapper; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; +import java.util.*; import java.util.stream.Collectors; import org.apache.commons.lang3.StringUtils; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.models.util.LoggerEnum; -import org.sunbird.common.models.util.ProjectLogger; -import org.sunbird.common.models.util.ProjectUtil; -import org.sunbird.common.models.util.TelemetryEnvKey; -import org.sunbird.telemetry.dto.Actor; -import org.sunbird.telemetry.dto.Context; -import org.sunbird.telemetry.dto.Producer; -import org.sunbird.telemetry.dto.Target; -import org.sunbird.telemetry.dto.Telemetry; +import org.sunbird.keys.JsonKey; +import org.sunbird.logging.LoggerUtil; +import org.sunbird.common.ProjectUtil; +import org.sunbird.telemetry.dto.*; +import org.sunbird.telemetry.dto.TelemetryEnvKey; /** - * class to transform the request data to telemetry events - * - * @author Arvind + * Utility class to generate telemetry events. + * Provides static methods to construct standard telemetry objects. */ public class TelemetryGenerator { - private static ObjectMapper mapper = new ObjectMapper(); + private static final ObjectMapper mapper = new ObjectMapper(); + private static final LoggerUtil logger = new LoggerUtil(TelemetryGenerator.class); + /** Private constructor to prevent instantiation. */ private TelemetryGenerator() {} /** - * To generate api_access LOG telemetry JSON string. + * Generates api_access AUDIT telemetry JSON string. * * @param context Map contains the telemetry context info like actor info, env info etc. - * @param params Map contains the telemetry event data info - * @return Telemetry event + * @param params Map contains the telemetry event data info + * @return Telemetry event as JSON string */ public static String audit(Map context, Map params) { if (!validateRequest(context, params)) { @@ -44,35 +35,49 @@ public static String audit(Map context, Map para } String actorId = (String) context.get(JsonKey.ACTOR_ID); String actorType = (String) context.get(JsonKey.ACTOR_TYPE); - Actor actor = new Actor(actorId, StringUtils.capitalize(actorType)); Target targetObject = generateTargetObject((Map) params.get(JsonKey.TARGET_OBJECT)); + + Actor actor = new Actor(actorId, StringUtils.capitalize(actorType)); Context eventContext = getContext(context); - // assign cdata into context from params correlated objects... + Map edata = generateAuditEdata(params); + + /* Assign cdata into context from params correlated objects */ if (params.containsKey(JsonKey.CORRELATED_OBJECTS)) { setCorrelatedDataToContext(params.get(JsonKey.CORRELATED_OBJECTS), eventContext); } - // assign request id into context cdata ... - String reqId = (String) context.get(JsonKey.REQUEST_ID); - if (!StringUtils.isBlank(reqId)) { + /* Assign request id into context cdata */ + String reqId = (String) context.get(JsonKey.X_REQUEST_ID); + if (StringUtils.isBlank(reqId)) { + reqId = (String) context.get(JsonKey.REQUEST_ID); + } + + if (StringUtils.isNotBlank(reqId)) { Map map = new HashMap<>(); map.put(JsonKey.ID, reqId); map.put(JsonKey.TYPE, TelemetryEnvKey.REQUEST_UPPER_CAMEL); eventContext.getCdata().add(map); } - Map edata = generateAuditEdata(params); - + /* Construct telemetry object and set message ID */ Telemetry telemetry = new Telemetry(TelemetryEvents.AUDIT.getName(), actor, eventContext, edata, targetObject); telemetry.setMid(reqId); return getTelemetry(telemetry); } + /** + * Sets correlated data (cdata) to the telemetry context. + * + * @param correlatedObjects List of correlated objects + * @param eventContext The context object to update + */ private static void setCorrelatedDataToContext(Object correlatedObjects, Context eventContext) { ArrayList> list = (ArrayList>) correlatedObjects; ArrayList> targetList = new ArrayList<>(); + + /* Convert correlated objects to standardized map format */ if (null != list && !list.isEmpty()) { for (Map m : list) { Map map = new HashMap<>(); @@ -84,8 +89,13 @@ private static void setCorrelatedDataToContext(Object correlatedObjects, Context eventContext.setCdata(targetList); } + /** + * Generates a Target object from the provided map. + * + * @param targetObject Map containing target object properties (ID, Type, Rollup) + * @return Constructed Target object + */ private static Target generateTargetObject(Map targetObject) { - Target target = new Target( (String) targetObject.get(JsonKey.ID), @@ -96,35 +106,55 @@ private static Target generateTargetObject(Map targetObject) { return target; } + /** + * Generates event data (edata) for AUDIT telemetry events. + * + * @param params Map containing event parameters (props, type, target object) + * @return Constructed edata map + */ private static Map generateAuditEdata(Map params) { - Map edata = new HashMap<>(); Map props = (Map) params.get(JsonKey.PROPS); + // TODO: need to rethink about this one .. if map is null then what to do if (null != props) { edata.put(JsonKey.PROPS, getProps(props)); } + String type = (String) params.get(JsonKey.TYPE); + if (null != type) { + edata.put(JsonKey.TYPE, type); + } + Map target = (Map) params.get(JsonKey.TARGET_OBJECT); - if (target.get(JsonKey.CURRENT_STATE) != null) { + if (target != null && target.get(JsonKey.CURRENT_STATE) != null) { edata.put(JsonKey.STATE, StringUtils.capitalize((String) target.get(JsonKey.CURRENT_STATE))); if (JsonKey.UPDATE.equalsIgnoreCase((String) target.get(JsonKey.CURRENT_STATE)) && edata.get(props) != null) { removeAttributes((Map) edata.get(props), JsonKey.ID); } } - if(params.containsKey("type")){ - edata.put("type", params.get("type")); - } return edata; } + /** + * Removes specified attributes from the map. + * + * @param map The map to modify + * @param properties The keys to remove + */ private static void removeAttributes(Map map, String... properties) { for (String property : properties) { map.remove(property); } } + /** + * Recursively extracts properties from a map, flattening nested keys. + * + * @param map The map to extract properties from + * @return List of property keys (dot-separated for nested keys) + */ private static List getProps(Map map) { try { return map.entrySet() @@ -144,11 +174,17 @@ private static List getProps(Map map) { .flatMap(List::stream) .collect(Collectors.toList()); } catch (Exception e) { - ProjectLogger.log("TelemetryGenerator:getProps error =" + e, LoggerEnum.ERROR.name()); + logger.error("TelemetryGenerator:getProps error =", e); } return new ArrayList<>(); } + /** + * Constructs the Context object from the context map. + * + * @param context Map containing context info + * @return Constructed Context object + */ private static Context getContext(Map context) { String channel = (String) context.get(JsonKey.CHANNEL); String env = (String) context.get(JsonKey.ENV); @@ -163,6 +199,12 @@ private static Context getContext(Map context) { return eventContext; } + /** + * Constructs a Producer object from the context map. + * + * @param context Map containing producer info + * @return Constructed Producer object + */ private static Producer getProducer(Map context) { String id = ""; if (context != null && context.size() != 0) { @@ -171,35 +213,40 @@ private static Producer getProducer(Map context) { } else { id = (String) context.get(JsonKey.PDATA_ID); } - return new Producer(id, "lms-service", "1.0"); + String pid = (String) context.get(JsonKey.PDATA_PID); + String ver = (String) context.get(JsonKey.PDATA_VERSION); + return new Producer(id, pid, ver); } else { - return new Producer("", "lms-service", "1.0"); + return new Producer("", "", ""); } } + /** + * Serializes the Telemetry object to a JSON string. + * + * @param telemetry Telemetry object + * @return JSON string representation + */ private static String getTelemetry(Telemetry telemetry) { String event = ""; try { event = mapper.writeValueAsString(telemetry); - ProjectLogger.log( - "TelemetryGenerator:getTelemetry = Telemetry Event : " + event, LoggerEnum.DEBUG.name()); + logger.info("TelemetryGenerator:getTelemetry = Telemetry Event : " + event); } catch (Exception e) { - ProjectLogger.log( - "TelemetryGenerator:getTelemetry = Telemetry Event: failed to generate audit events:" + e, - LoggerEnum.ERROR.name()); + logger.error( + "TelemetryGenerator:getTelemetry = Telemetry Event: failed to generate audit events:", e); } return event; } - + /** - * Method to generate the search type telemetry event. + * Generates SEARCH telemetry event. * * @param context Map contains the telemetry context info like actor info, env info etc. - * @param params Map contains the telemetry event data info - * @return Search Telemetry event + * @param params Map contains the telemetry event data info + * @return Search Telemetry event as JSON string */ public static String search(Map context, Map params) { - if (!validateRequest(context, params)) { return ""; } @@ -209,13 +256,19 @@ public static String search(Map context, Map par Context eventContext = getContext(context); - String reqId = (String) context.get(JsonKey.REQUEST_ID); - if (!StringUtils.isBlank(reqId)) { + /* Assign request id into context cdata */ + String reqId = (String) context.get(JsonKey.X_REQUEST_ID); + if (StringUtils.isBlank(reqId)) { + reqId = (String) context.get(JsonKey.REQUEST_ID); + } + + if (StringUtils.isNotBlank(reqId)) { Map map = new HashMap<>(); map.put(JsonKey.ID, reqId); map.put(JsonKey.TYPE, TelemetryEnvKey.REQUEST_UPPER_CAMEL); eventContext.getCdata().add(map); } + Map edata = generateSearchEdata(params); Telemetry telemetry = new Telemetry(TelemetryEvents.SEARCH.getName(), actor, eventContext, edata); @@ -223,8 +276,13 @@ public static String search(Map context, Map par return getTelemetry(telemetry); } + /** + * Generates event data (edata) for SEARCH telemetry events. + * + * @param params Map containing search event parameters + * @return Constructed edata map + */ private static Map generateSearchEdata(Map params) { - Map edata = new HashMap<>(); String type = (String) params.get(JsonKey.TYPE); String query = (String) params.get(JsonKey.QUERY); @@ -245,14 +303,13 @@ private static Map generateSearchEdata(Map param } /** - * Method to generate the log type telemetry event. + * Generates LOG telemetry event. * * @param context Map contains the telemetry context info like actor info, env info etc. - * @param params Map contains the telemetry event data info - * @return Search Telemetry event + * @param params Map contains the telemetry event data info + * @return Log Telemetry event as JSON string */ public static String log(Map context, Map params) { - if (!validateRequest(context, params)) { return ""; } @@ -262,9 +319,13 @@ public static String log(Map context, Map params Context eventContext = getContext(context); - // assign request id into context cdata ... - String reqId = (String) context.get(JsonKey.REQUEST_ID); - if (!StringUtils.isBlank(reqId)) { + /* Assign request id into context cdata */ + String reqId = (String) context.get(JsonKey.X_REQUEST_ID); + if (StringUtils.isBlank(reqId)) { + reqId = (String) context.get(JsonKey.REQUEST_ID); + } + + if (StringUtils.isNotBlank(reqId)) { Map map = new HashMap<>(); map.put(JsonKey.ID, reqId); map.put(JsonKey.TYPE, TelemetryEnvKey.REQUEST_UPPER_CAMEL); @@ -277,8 +338,13 @@ public static String log(Map context, Map params return getTelemetry(telemetry); } + /** + * Generates event data (edata) for LOG telemetry events. + * + * @param params Map containing log event parameters + * @return Constructed edata map + */ private static Map generateLogEdata(Map params) { - Map edata = new HashMap<>(); String logType = (String) params.get(JsonKey.LOG_TYPE); String logLevel = (String) params.get(JsonKey.LOG_LEVEL); @@ -294,13 +360,20 @@ private static Map generateLogEdata(Map params) return edata; } + /** + * Extracts parameters from a map, excluding specified keys. + * + * @param params Map to extract parameters from + * @param ignore List of keys to exclude + * @return List of parameter maps + */ private static List> getParamsList( Map params, List ignore) { - List> paramsList = new ArrayList>(); + List> paramsList = new ArrayList<>(); if (null != params && !params.isEmpty()) { - for (Entry entry : params.entrySet()) { + for (Map.Entry entry : params.entrySet()) { if (!ignore.contains(entry.getKey())) { - Map param = new HashMap(); + Map param = new HashMap<>(); param.put(entry.getKey(), entry.getValue()); paramsList.add(param); } @@ -310,14 +383,13 @@ private static List> getParamsList( } /** - * Method to generate the error type telemetry event. + * Generates ERROR telemetry event. * * @param context Map contains the telemetry context info like actor info, env info etc. - * @param params Map contains the error event data info - * @return Search Telemetry event + * @param params Map contains the error event data info + * @return Error Telemetry event as JSON string */ public static String error(Map context, Map params) { - if (!validateRequest(context, params)) { return ""; } @@ -327,9 +399,13 @@ public static String error(Map context, Map para Context eventContext = getContext(context); - // assign request id into context cdata ... - String reqId = (String) context.get(JsonKey.REQUEST_ID); - if (!StringUtils.isBlank(reqId)) { + /* Assign request id into context cdata */ + String reqId = (String) context.get(JsonKey.X_REQUEST_ID); + if (StringUtils.isBlank(reqId)) { + reqId = (String) context.get(JsonKey.REQUEST_ID); + } + + if (StringUtils.isNotBlank(reqId)) { Map map = new HashMap<>(); map.put(JsonKey.ID, reqId); map.put(JsonKey.TYPE, TelemetryEnvKey.REQUEST_UPPER_CAMEL); @@ -337,12 +413,19 @@ public static String error(Map context, Map para } Map edata = generateErrorEdata(params); + edata.put(JsonKey.REQUEST_ID, reqId); Telemetry telemetry = new Telemetry(TelemetryEvents.ERROR.getName(), actor, eventContext, edata); telemetry.setMid(reqId); return getTelemetry(telemetry); } + /** + * Generates event data (edata) for ERROR telemetry events. + * + * @param params Map contains error event parameters + * @return Constructed edata map + */ private static Map generateErrorEdata(Map params) { Map edata = new HashMap<>(); String error = (String) params.get(JsonKey.ERROR); @@ -350,16 +433,32 @@ private static Map generateErrorEdata(Map params String stackTrace = (String) params.get(JsonKey.STACKTRACE); edata.put(JsonKey.ERROR, error); edata.put(JsonKey.ERR_TYPE, errorType); - edata.put(JsonKey.STACKTRACE, ProjectUtil.getFirstNCharacterString(stackTrace, 100)); + + int stackTraceLength = 100; + try { + String lengthStr = ProjectUtil.getConfigValue(JsonKey.STACKTRACE_CHAR_LENGTH); + if (StringUtils.isNotBlank(lengthStr)) { + stackTraceLength = Integer.parseInt(lengthStr); + } + } catch (Exception e) { + logger.error("TelemetryGenerator:generateErrorEdata: Error parsing stacktrace length", e); + } + + edata.put( + JsonKey.STACKTRACE, + ProjectUtil.getFirstNCharacterString(stackTrace, stackTraceLength)); return edata; } - + + /** + * Validates if context and params are present. + * + * @param context Telemetry context map + * @param params Telemetry params map + * @return true if valid, false otherwise + */ private static boolean validateRequest(Map context, Map params) { - - boolean flag = true; - if (null == context || context.isEmpty() || params == null || params.isEmpty()) { - flag = false; - } - return flag; + return context != null && !context.isEmpty() && params != null && !params.isEmpty(); } -} + +} \ No newline at end of file diff --git a/core/sunbird-platform-common/src/main/java/org/sunbird/telemetry/util/TelemetryParams.java b/core/sunbird-platform-common/src/main/java/org/sunbird/telemetry/util/TelemetryParams.java new file mode 100644 index 000000000..b761258a0 --- /dev/null +++ b/core/sunbird-platform-common/src/main/java/org/sunbird/telemetry/util/TelemetryParams.java @@ -0,0 +1,21 @@ +package org.sunbird.telemetry.util; + +/** + * Enum to represent standard Telemetry parameters. + */ +public enum TelemetryParams { + /** + * Represents the channel ID. + */ + CHANNEL, + + /** + * Represents the environment ID. + */ + ENV, + + /** + * Represents the actor information. + */ + ACTOR; +} diff --git a/core/sunbird-platform-common/src/main/java/org/sunbird/telemetry/util/TelemetryUtil.java b/core/sunbird-platform-common/src/main/java/org/sunbird/telemetry/util/TelemetryUtil.java new file mode 100644 index 000000000..441f6a417 --- /dev/null +++ b/core/sunbird-platform-common/src/main/java/org/sunbird/telemetry/util/TelemetryUtil.java @@ -0,0 +1,149 @@ +package org.sunbird.telemetry.util; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.apache.commons.lang3.StringUtils; +import org.sunbird.keys.JsonKey; +import org.sunbird.request.Request; + +/** + * Utility class for generating and processing telemetry events. + * Provides helper methods to construct telemetry objects and requests. + */ +public final class TelemetryUtil { + + private TelemetryUtil() {} + + /** + * Generates a target object map for telemetry. + * + * @param id The ID of the target object. + * @param type The type of the target object. + * @param currentState The current state of the object. + * @param prevState The previous state of the object. + * @return A map representing the target object. + */ + public static Map generateTargetObject( + String id, String type, String currentState, String prevState) { + + Map target = new HashMap<>(); + target.put(JsonKey.ID, id); + target.put(JsonKey.TYPE, StringUtils.capitalize(type)); + target.put(JsonKey.CURRENT_STATE, currentState); + target.put(JsonKey.PREV_STATE, prevState); + return target; + } + + /** + * Generates the telemetry request map. + * + * @param targetObject The target object map. + * @param correlatedObject List of correlated objects. + * @param eventType The type of telemetry event. + * @param params Additional parameters for the event. + * @param context The context map. + * @return A map representing the telemetry request. + */ + public static Map generateTelemetryRequest( + Map targetObject, + List> correlatedObject, + String eventType, + Map params, + Map context) { + + Map map = new HashMap<>(); + map.put(JsonKey.TARGET_OBJECT, targetObject); + map.put(JsonKey.CORRELATED_OBJECTS, correlatedObject); + map.put(JsonKey.TELEMETRY_EVENT_TYPE, eventType); + map.put(JsonKey.PARAMS, params); + map.put(JsonKey.CONTEXT, context); + return map; + } + + /** + * Generates a correlated object and adds it to the provided list. + * + * @param id The ID of the correlated object. + * @param type The type of the correlated object. + * @param correlation The relation string. + * @param correlationList The list to which the correlated object will be added. + */ + public static void generateCorrelatedObject( + String id, String type, String correlation, List> correlationList) { + + Map correlatedObject = new HashMap<>(); + correlatedObject.put(JsonKey.ID, id); + correlatedObject.put(JsonKey.TYPE, StringUtils.capitalize(type)); + correlatedObject.put(JsonKey.RELATION, correlation); + + correlationList.add(correlatedObject); + } + + /** + * Adds rollup data to the target object. + * + * @param rollUpMap The rollup map. + * @param targetObject The target object to modify. + */ + public static void addTargetObjectRollUp( + Map rollUpMap, Map targetObject) { + targetObject.put(JsonKey.ROLLUP, rollUpMap); + } + + /** + * Processes the telemetry call for Audit events. + * + * @param request The request properties map. + * @param targetObject The target object map. + * @param correlatedObject List of correlated objects. + * @param context The context map. + */ + public static void telemetryProcessingCall( + Map request, + Map targetObject, + List> correlatedObject, + Map context) { + Map params = new HashMap<>(); + params.put(JsonKey.PROPS, request); + Request req = new Request(); + req.setRequest( + TelemetryUtil.generateTelemetryRequest( + targetObject, correlatedObject, TelemetryEvents.AUDIT.getName(), params, context)); + generateTelemetry(req); + } + + /** + * Processes the telemetry call for Audit events with a specific type. + * + * @param type The type of the event. + * @param request The request properties map. + * @param targetObject The target object map. + * @param correlatedObject List of correlated objects. + * @param context The context map. + */ + public static void telemetryProcessingCall( + String type, + Map request, + Map targetObject, + List> correlatedObject, + Map context) { + Map params = new HashMap<>(); + params.put(JsonKey.PROPS, request); + params.put(JsonKey.TYPE, type); + Request req = new Request(); + req.setRequest( + TelemetryUtil.generateTelemetryRequest( + targetObject, correlatedObject, TelemetryEvents.AUDIT.getName(), params, context)); + generateTelemetry(req); + } + + /** + * Helper method to trigger the telemetry writer. + * + * @param request The request object containing telemetry data. + */ + private static void generateTelemetry(Request request) { + TelemetryWriter.write(request); + } +} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/telemetry/util/TelemetryWriter.java b/core/sunbird-platform-common/src/main/java/org/sunbird/telemetry/util/TelemetryWriter.java similarity index 64% rename from course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/telemetry/util/TelemetryWriter.java rename to core/sunbird-platform-common/src/main/java/org/sunbird/telemetry/util/TelemetryWriter.java index 24b9e6dfc..d9e7a77fc 100644 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/telemetry/util/TelemetryWriter.java +++ b/core/sunbird-platform-common/src/main/java/org/sunbird/telemetry/util/TelemetryWriter.java @@ -5,22 +5,38 @@ import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.models.util.LoggerEnum; -import org.sunbird.common.models.util.ProjectLogger; -import org.sunbird.common.request.Request; +import org.sunbird.keys.JsonKey; +import org.sunbird.logging.LoggerUtil; +import org.sunbird.request.Request; import org.sunbird.telemetry.collector.TelemetryAssemblerFactory; import org.sunbird.telemetry.collector.TelemetryDataAssembler; import org.sunbird.telemetry.validator.TelemetryObjectValidator; import org.sunbird.telemetry.validator.TelemetryObjectValidatorV3; +/** + * This class writes telemetry events to the configured logger. + * It processes different types of telemetry events such as AUDIT, SEARCH, ERROR, and LOG. + */ 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 Logger telemetryEventLogger = LoggerFactory.getLogger("TelemetryEventLogger"); + private static final LoggerUtil logger = new LoggerUtil(TelemetryWriter.class); + private static final Logger telemetryEventLogger = + LoggerFactory.getLogger("TelemetryEventLogger"); + /** + * Private constructor to prevent instantiation. + */ + private TelemetryWriter() {} + + /** + * Writes the telemetry event based on the request content. + * + * @param request The request object containing telemetry data. + */ public static void write(Request request) { try { String eventType = (String) request.getRequest().get(JsonKey.TELEMETRY_EVENT_TYPE); @@ -35,72 +51,87 @@ public static void write(Request request) { processLogEvent(request); } } catch (Exception ex) { - ProjectLogger.log( - "TelemetryWriter:write: Exception occurred while writting telemetry: " - + " exception = " - + ex, - LoggerEnum.ERROR.name()); + logger.info("Exception occurred while writing telemetry"); } } + /** + * Processes LOG telemetry events. + * + * @param request The request object. + */ private static void processLogEvent(Request request) { Map context = (Map) request.getRequest().get(JsonKey.CONTEXT); Map params = (Map) request.getRequest().get(JsonKey.PARAMS); String telemetry = telemetryDataAssembler.log(context, params); + + // Validate and write telemetry event if (StringUtils.isNotBlank(telemetry) && telemetryObjectValidator.validateLog(telemetry)) { telemetryEventLogger.info(telemetry); } else { - ProjectLogger.log( - "TelemetryWriter:processLogEvent: Audit Telemetry validation failed: ", - telemetry, - LoggerEnum.ERROR.name()); + logger.info( + "TelemetryWriter:processLogEvent: Audit Telemetry validation failed: " + telemetry); } } + /** + * Processes ERROR telemetry events. + * + * @param request The request object. + */ private static void processErrorEvent(Request request) { Map context = (Map) request.get(JsonKey.CONTEXT); Map params = (Map) request.get(JsonKey.PARAMS); String telemetry = telemetryDataAssembler.error(context, params); + + // Validate and write telemetry event if (StringUtils.isNotBlank(telemetry) && telemetryObjectValidator.validateError(telemetry)) { telemetryEventLogger.info(telemetry); - } else { - ProjectLogger.log( - "TelemetryWriter:processLogEvent: Error Telemetry validation failed: ", - telemetry, - LoggerEnum.ERROR.name()); } } + /** + * Processes SEARCH telemetry events. + * + * @param request The request object. + */ private static void processSearchEvent(Request request) { Map context = (Map) request.get(JsonKey.CONTEXT); Map params = (Map) request.get(JsonKey.PARAMS); String telemetry = telemetryDataAssembler.search(context, params); + + // Validate and write telemetry event if (StringUtils.isNotBlank(telemetry) && telemetryObjectValidator.validateSearch(telemetry)) { telemetryEventLogger.info(telemetry); - } else { - ProjectLogger.log( - "TelemetryWriter:processLogEvent: Search Telemetry validation failed: ", - telemetry, - LoggerEnum.ERROR.name()); } } + /** + * Processes AUDIT telemetry events. + * + * @param request The request object. + */ private static void processAuditEvent(Request request) { Map context = (Map) request.get(JsonKey.CONTEXT); Map targetObject = (Map) request.get(JsonKey.TARGET_OBJECT); List> correlatedObjects = (List>) request.get(JsonKey.CORRELATED_OBJECTS); Map params = (Map) request.get(JsonKey.PARAMS); + Map props = (Map) params.get(JsonKey.PROPS); + + // Check for type in props and add to params if present + if (props != null && props.containsKey(JsonKey.TYPE)) { + String type = (String) props.get(JsonKey.TYPE); + params.put(JsonKey.TYPE, type); + } params.put(JsonKey.TARGET_OBJECT, targetObject); params.put(JsonKey.CORRELATED_OBJECTS, correlatedObjects); + String telemetry = telemetryDataAssembler.audit(context, params); + + // Validate and write telemetry event if (StringUtils.isNotBlank(telemetry) && telemetryObjectValidator.validateAudit(telemetry)) { telemetryEventLogger.info(telemetry); - } else { - ProjectLogger.log( - "TelemetryWriter:processLogEvent: Audit Telemetry validation failed: ", - telemetry, - LoggerEnum.ERROR.name()); } } } diff --git a/core/sunbird-platform-common/src/main/java/org/sunbird/telemetry/validator/TelemetryObjectValidator.java b/core/sunbird-platform-common/src/main/java/org/sunbird/telemetry/validator/TelemetryObjectValidator.java new file mode 100644 index 000000000..7c1f79778 --- /dev/null +++ b/core/sunbird-platform-common/src/main/java/org/sunbird/telemetry/validator/TelemetryObjectValidator.java @@ -0,0 +1,39 @@ +package org.sunbird.telemetry.validator; + +/** + * Interface for validating telemetry event objects against their schemas. + */ +public interface TelemetryObjectValidator { + + /** + * Validates an AUDIT telemetry event JSON string. + * + * @param jsonString The JSON string representation of the telemetry event. + * @return true if valid, false otherwise. + */ + boolean validateAudit(String jsonString); + + /** + * Validates a SEARCH telemetry event JSON string. + * + * @param jsonString The JSON string representation of the telemetry event. + * @return true if valid, false otherwise. + */ + boolean validateSearch(String jsonString); + + /** + * Validates a LOG telemetry event JSON string. + * + * @param jsonString The JSON string representation of the telemetry event. + * @return true if valid, false otherwise. + */ + boolean validateLog(String jsonString); + + /** + * Validates an ERROR telemetry event JSON string. + * + * @param jsonString The JSON string representation of the telemetry event. + * @return true if valid, false otherwise. + */ + boolean validateError(String jsonString); +} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/telemetry/validator/TelemetryObjectValidatorV3.java b/core/sunbird-platform-common/src/main/java/org/sunbird/telemetry/validator/TelemetryObjectValidatorV3.java similarity index 59% rename from course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/telemetry/validator/TelemetryObjectValidatorV3.java rename to core/sunbird-platform-common/src/main/java/org/sunbird/telemetry/validator/TelemetryObjectValidatorV3.java index 3624e8117..efb125f31 100644 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/telemetry/validator/TelemetryObjectValidatorV3.java +++ b/core/sunbird-platform-common/src/main/java/org/sunbird/telemetry/validator/TelemetryObjectValidatorV3.java @@ -1,73 +1,103 @@ package org.sunbird.telemetry.validator; -import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.commons.lang3.StringUtils; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.models.util.ProjectLogger; +import org.sunbird.keys.JsonKey; +import org.sunbird.logging.LoggerUtil; import org.sunbird.telemetry.dto.Telemetry; import org.sunbird.telemetry.util.TelemetryEvents; +import com.fasterxml.jackson.databind.ObjectMapper; -/** @author arvind */ +/** + * Validator class for Version 3 Telemetry events. + * Implements the TelemetryObjectValidator interface to provide validation logic for various telemetry event types. + */ public class TelemetryObjectValidatorV3 implements TelemetryObjectValidator { + + private static final LoggerUtil logger = new LoggerUtil(TelemetryObjectValidatorV3.class); + private static TelemetryObjectValidator telemetryObjectValidator = null; + private final ObjectMapper mapper = new ObjectMapper(); - ObjectMapper mapper = new ObjectMapper(); + /** + * Returns the singleton instance of TelemetryObjectValidatorV3. + * + * @return The singleton instance. + */ + public static TelemetryObjectValidator getInstance() { + if (telemetryObjectValidator == null) { + telemetryObjectValidator = new TelemetryObjectValidatorV3(); + } + return telemetryObjectValidator; + } @Override public boolean validateAudit(String jsonString) { - boolean validationSuccess = true; List missingFields = new ArrayList<>(); Telemetry telemetryObj = null; try { + // Parse JSON string to Telemetry object telemetryObj = mapper.readValue(jsonString, Telemetry.class); + + // Validate basic fields validateBasics(telemetryObj, missingFields); + // Validate Audit specific data validateAuditEventData(telemetryObj.getEdata(), missingFields); + if (!missingFields.isEmpty()) { - ProjectLogger.log( - "Telemetry Object Creation Error for event : " + logger.info( + "TelemetryObjectValidatorV3:validateAudit: Validation failed for event: " + TelemetryEvents.AUDIT.getName() - + " missing required fields :" - + String.join(",", missingFields)); + + ". Missing required fields: " + + String.join(", ", missingFields)); validationSuccess = false; } } catch (IOException e) { validationSuccess = false; - ProjectLogger.log(e.getMessage(), e); + logger.error("TelemetryObjectValidatorV3:validateAudit: Error parsing JSON: " + e.getMessage(), e); } return validationSuccess; } @Override public boolean validateSearch(String jsonString) { - boolean validationSuccess = true; List missingFields = new ArrayList<>(); Telemetry telemetryObj = null; try { + // Parse JSON string to Telemetry object telemetryObj = mapper.readValue(jsonString, Telemetry.class); + + // Validate basic fields validateBasics(telemetryObj, missingFields); + // Validate Search specific data validateSearchEventData(telemetryObj.getEdata(), missingFields); + if (!missingFields.isEmpty()) { - ProjectLogger.log( - "Telemetry Object Creation Error for event : " + logger.info( + "TelemetryObjectValidatorV3:validateSearch: Validation failed for event: " + TelemetryEvents.SEARCH.getName() - + " missing required fields :" - + String.join(",", missingFields)); + + ". Missing required fields: " + + String.join(", ", missingFields)); validationSuccess = false; } } catch (IOException e) { validationSuccess = false; - ProjectLogger.log(e.getMessage(), e); + logger.error("TelemetryObjectValidatorV3:validateSearch: Error parsing JSON: " + e.getMessage(), e); } return validationSuccess; } + /** + * Validates search event data structure. + * + * @param edata The event data map. + * @param missingFields List to populate with missing keys. + */ private void validateSearchEventData(Map edata, List missingFields) { - if (edata == null || edata.isEmpty()) { missingFields.add("edata"); } else { @@ -83,14 +113,26 @@ private void validateSearchEventData(Map edata, List mis } } + /** + * Validates audit event data presence. + * + * @param edata The event data map. + * @param missingFields List to populate with missing keys. + */ private void validateAuditEventData(Map edata, List missingFields) { if (edata == null) { missingFields.add("edata"); } } + /** + * Validates basic telemetry fields (eid, mid, ver, actor, context). + * + * @param telemetryObj The telemetry object. + * @param missingFields List to populate with missing keys. + */ private void validateBasics(Telemetry telemetryObj, List missingFields) { - + // Check mandatory top-level fields if (StringUtils.isBlank(telemetryObj.getEid())) { missingFields.add("eid"); } @@ -101,6 +143,7 @@ private void validateBasics(Telemetry telemetryObj, List missingFields) missingFields.add("ver"); } + // Check actor details if (null == telemetryObj.getActor()) { missingFields.add("actor"); } else { @@ -112,6 +155,7 @@ private void validateBasics(Telemetry telemetryObj, List missingFields) } } + // Check context details if (null == telemetryObj.getContext()) { missingFields.add(JsonKey.CONTEXT); } else { @@ -124,31 +168,47 @@ private void validateBasics(Telemetry telemetryObj, List missingFields) } } + /** + * Validates a LOG telemetry event. + * + * @param jsonString The JSON string representation of the telemetry event. + * @return true if valid, false otherwise. + */ @Override public boolean validateLog(String jsonString) { - boolean validationSuccess = true; List missingFields = new ArrayList<>(); Telemetry telemetryObj = null; try { + // Parse JSON string to Telemetry object telemetryObj = mapper.readValue(jsonString, Telemetry.class); + + // Validate basic fields validateBasics(telemetryObj, missingFields); + // Validate Log specific data validateLogEventData(telemetryObj.getEdata(), missingFields); + if (!missingFields.isEmpty()) { - ProjectLogger.log( - "Telemetry Object Creation Error for event : " + logger.info( + "TelemetryObjectValidatorV3:validateLog: Validation failed for event: " + TelemetryEvents.LOG.getName() - + " missing required fields :" - + String.join(",", missingFields)); + + ". Missing required fields: " + + String.join(", ", missingFields)); validationSuccess = false; } } catch (IOException e) { validationSuccess = false; - ProjectLogger.log(e.getMessage(), e); + logger.error("TelemetryObjectValidatorV3:validateLog: Error parsing JSON: " + e.getMessage(), e); } return validationSuccess; } + /** + * Validates log event data structure. + * + * @param edata The event data map. + * @param missingFields List to populate with missing keys. + */ private void validateLogEventData(Map edata, List missingFields) { if (edata == null || edata.isEmpty()) { missingFields.add("edata"); @@ -166,31 +226,47 @@ private void validateLogEventData(Map edata, List missin } } + /** + * Validates an ERROR telemetry event. + * + * @param jsonString The JSON string representation of the telemetry event. + * @return true if valid, false otherwise. + */ @Override public boolean validateError(String jsonString) { - boolean validationSuccess = true; List missingFields = new ArrayList<>(); Telemetry telemetryObj = null; try { + // Parse JSON string to Telemetry object telemetryObj = mapper.readValue(jsonString, Telemetry.class); + + // Validate basic fields validateBasics(telemetryObj, missingFields); + // Validate Error specific data validateErrorEventData(telemetryObj.getEdata(), missingFields); + if (!missingFields.isEmpty()) { - ProjectLogger.log( - "Telemetry Object Creation Error for event : " + logger.info( + "TelemetryObjectValidatorV3:validateError: Validation failed for event: " + TelemetryEvents.ERROR.getName() - + " missing required fields :" - + String.join(",", missingFields)); + + ". Missing required fields: " + + String.join(", ", missingFields)); validationSuccess = false; } } catch (IOException e) { validationSuccess = false; - ProjectLogger.log(e.getMessage(), e); + logger.error("TelemetryObjectValidatorV3:validateError: Error parsing JSON: " + e.getMessage(), e); } return validationSuccess; } + /** + * Validates error event data structure. + * + * @param edata The event data map. + * @param missingFields List to populate with missing keys. + */ private void validateErrorEventData(Map edata, List missingFields) { if (edata == null || edata.isEmpty()) { missingFields.add("edata"); diff --git a/core/sunbird-platform-common/src/main/java/org/sunbird/utils/CloudStorageUtil.java b/core/sunbird-platform-common/src/main/java/org/sunbird/utils/CloudStorageUtil.java new file mode 100644 index 000000000..c1c086bf3 --- /dev/null +++ b/core/sunbird-platform-common/src/main/java/org/sunbird/utils/CloudStorageUtil.java @@ -0,0 +1,168 @@ +package org.sunbird.utils; + +import static org.sunbird.keys.JsonKey.CLOUD_STORAGE_CNAME_URL; +import static org.sunbird.keys.JsonKey.CLOUD_STORE_BASE_PATH; +import static org.sunbird.common.ProjectUtil.getConfigValue; + +import java.util.HashMap; +import java.util.Map; +import org.apache.commons.lang.StringUtils; +import org.sunbird.cloud.storage.BaseStorageService; +import org.sunbird.cloud.storage.factory.StorageConfig; +import org.sunbird.cloud.storage.factory.StorageServiceFactory; +import org.sunbird.keys.JsonKey; +import org.sunbird.common.ProjectUtil; +import org.sunbird.common.PropertiesCache; +import scala.Option; +import scala.Some; + +public class CloudStorageUtil { + private static final int STORAGE_SERVICE_API_RETRY_COUNT = 3; + private static final Map storageServiceMap = new HashMap<>(); + + /** + * Uploads a file to the cloud storage. + * + * @param storageType The type of storage (e.g., azure, aws). + * @param container The container or bucket name. + * @param objectKey The key (path) for the object in storage. + * @param filePath The local path of the file to upload. + * @return The URL of the uploaded file. + */ + public static String upload( + String storageType, String container, String objectKey, String filePath) { + BaseStorageService storageService = getStorageService(storageType); + return storageService.upload( + container, + filePath, + objectKey, + Option.apply(false), + Option.apply(1), + Option.apply(STORAGE_SERVICE_API_RETRY_COUNT), + Option.empty()); + } + + /** + * Generates a signed URL for an object in cloud storage. + * + * @param storageType The type of storage. + * @param container The container or bucket name. + * @param objectKey The key of the object. + * @return The signed URL. + */ + public static String getSignedUrl(String storageType, String container, String objectKey) { + BaseStorageService storageService = getStorageService(storageType); + return getSignedUrl(storageService, container, objectKey, storageType); + } + + /** + * Generates a signed URL for an object using a specific storage service instance. + * + * @param storageService The storage service instance. + * @param container The container or bucket name. + * @param objectKey The key of the object. + * @param cloudType The cloud type (not directly used but part of signature). + * @return The signed URL. + */ + public static String getSignedUrl( + BaseStorageService storageService, String container, String objectKey, String cloudType) { + return storageService.getSignedURLV2( + container, + objectKey, + Some.apply(getTimeoutInSeconds()), + Some.apply("r"), + Some.apply("application/pdf"), + Option.empty()); + } + + /** + * Deletes a file from cloud storage. + * + * @param storageType The type of storage. + * @param container The container or bucket name. + * @param objectKey The key of the object to delete. + */ + public static void deleteFile(String storageType, String container, String objectKey) { + BaseStorageService storageService = getStorageService(storageType); + storageService.deleteObject(container, objectKey, Option.apply(false)); + } + + /** + * Gets the URI for a specific prefix in the container. + * + * @param storageType The type of storage. + * @param container The container name. + * @param prefix The prefix to list/get. + * @param isDirectory Whether it is a directory. + * @return The URI. + */ + public static String getUri( + String storageType, String container, String prefix, boolean isDirectory) { + BaseStorageService storageService = getStorageService(storageType); + return storageService.getUri(container, prefix, Option.apply(isDirectory)); + } + + /** + * Gets the base URL for cloud storage from configuration. + * + * @return The base URL. + */ + public static String getBaseUrl() { + String baseUrl = getConfigValue(CLOUD_STORAGE_CNAME_URL); + if (StringUtils.isEmpty(baseUrl)) baseUrl = getConfigValue(CLOUD_STORE_BASE_PATH); + return baseUrl; + } + + /** + * Retrieves a storage service instance based on the provided storage type. + * Loads account name and key from properties cache. + * + * @param storageType The type of storage (e.g., azure, aws). + * @return A BaseStorageService instance. + */ + private static BaseStorageService getStorageService(String storageType) { + String storageKey = PropertiesCache.getInstance().getProperty(JsonKey.ACCOUNT_NAME); + String storageSecret = PropertiesCache.getInstance().getProperty(JsonKey.ACCOUNT_KEY); + return getStorageService(storageType, storageKey, storageSecret); + } + + /** + * Retrieves or creates a storage service instance. + * Uses a composite key (type-key) to cache instances. + * + * @param storageType The type of storage. + * @param storageKey The storage account key/name. + * @param storageSecret The storage account secret. + * @return A BaseStorageService instance. + */ + private static BaseStorageService getStorageService( + String storageType, String storageKey, String storageSecret) { + String compositeKey = storageType + "-" + storageKey; + if (storageServiceMap.containsKey(compositeKey)) { + return storageServiceMap.get(compositeKey); + } + synchronized (CloudStorageUtil.class) { + if (storageServiceMap.containsKey(compositeKey)) { + return storageServiceMap.get(compositeKey); + } + scala.Option storageEndpoint = + scala.Option.apply(PropertiesCache.getInstance().getProperty(JsonKey.ACCOUNT_ENDPOINT)); + scala.Option storageRegion = scala.Option.apply(""); + StorageConfig storageConfig = + new StorageConfig(storageType, storageKey, storageSecret, storageEndpoint, storageRegion); + BaseStorageService storageService = StorageServiceFactory.getStorageService(storageConfig); + storageServiceMap.put(compositeKey, storageService); + } + return storageServiceMap.get(compositeKey); + } + + /** + * Retrieves the download link expiry timeout from configuration. + * + * @return The timeout in seconds. + */ + private static int getTimeoutInSeconds() { + String timeoutInSecondsStr = ProjectUtil.getConfigValue(JsonKey.DOWNLOAD_LINK_EXPIRY_TIMEOUT); + return Integer.parseInt(timeoutInSecondsStr); + } +} \ No newline at end of file diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/util/ConfigUtil.java b/core/sunbird-platform-common/src/main/java/org/sunbird/utils/ConfigUtil.java similarity index 52% rename from course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/util/ConfigUtil.java rename to core/sunbird-platform-common/src/main/java/org/sunbird/utils/ConfigUtil.java index 50a0be8ee..0b8e7cbd3 100644 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/util/ConfigUtil.java +++ b/core/sunbird-platform-common/src/main/java/org/sunbird/utils/ConfigUtil.java @@ -1,33 +1,31 @@ -package org.sunbird.common.util; +package org.sunbird.utils; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; import org.apache.commons.lang3.StringUtils; -import org.sunbird.common.exception.ProjectCommonException; -import org.sunbird.common.models.util.LoggerEnum; -import org.sunbird.common.models.util.ProjectLogger; -import org.sunbird.common.models.util.ProjectUtil; -import org.sunbird.common.responsecode.ResponseCode; +import org.sunbird.exception.ProjectCommonException; +import org.sunbird.logging.LoggerUtil; +import org.sunbird.common.ProjectUtil; +import org.sunbird.response.ResponseCode; /** - * This util class for providing type safe config to any service that requires it. - * - * @author Manzarul + * Utility class for type-safe configuration management. + * Provides methods to load configuration from system environment or files. */ public class ConfigUtil { + public static LoggerUtil logger = new LoggerUtil(ConfigUtil.class); private static Config config; private static final String DEFAULT_TYPE_SAFE_CONFIG_FILE_NAME = "service.conf"; private static final String INVALID_FILE_NAME = "Please provide a valid file name."; - /** Private default constructor. */ private ConfigUtil() {} /** - * This method will create a type safe config object and return to caller. It will read the config - * value from System env first and as a fall back it will use service.conf file. + * Loads the type-safe config object. + * Reads from system environment first, falling back to 'service.conf'. * - * @return Type safe config object + * @return The loaded type-safe Config object. */ public static Config getConfig() { if (config == null) { @@ -39,17 +37,16 @@ public static Config getConfig() { } /** - * This method will create a type safe config object and return to caller. It will read the config - * value from System env first and as a fall back it will use provided file name. If file name is - * null or empty then it will throw ProjectCommonException with status code as 500. + * Loads the type-safe config object from a specific file. + * Reads from system environment first, falling back to the provided file name. * - * @return Type safe config object + * @param fileName The name of the configuration file to load. + * @return The loaded type-safe Config object. + * @throws ProjectCommonException If the file name is null or empty. */ public static Config getConfig(String fileName) { if (StringUtils.isBlank(fileName)) { - ProjectLogger.log( - "ConfigUtil:getConfigWithFilename: Given file name is null or empty: " + fileName, - LoggerEnum.INFO.name()); + logger.info("ConfigUtil:getConfig: Given file name is null or empty: " + fileName); throw new ProjectCommonException( ResponseCode.internalError.getErrorCode(), INVALID_FILE_NAME, @@ -63,14 +60,17 @@ public static Config getConfig(String fileName) { return config; } + /** + * Validates if a mandatory configuration parameter is present. + * + * @param configParameter The configuration parameter value to check. + * @throws ProjectCommonException If the parameter is null or empty. + */ public static void validateMandatoryConfigValue(String configParameter) { if (StringUtils.isBlank(configParameter)) { - ProjectLogger.log( - "ConfigUtil:validateMandatoryConfigValue: Missing mandatory configuration parameter: " - + configParameter, - LoggerEnum.ERROR.name()); + logger.error("ConfigUtil:validateMandatoryConfigValue: Missing mandatory configuration parameter: " + configParameter, null); throw new ProjectCommonException( - ResponseCode.mandatoryConfigParamMissing.getErrorCode(), + ResponseCode.mandatoryConfigParamMissing, ResponseCode.mandatoryConfigParamMissing.getErrorMessage(), ResponseCode.SERVER_ERROR.getResponseCode(), configParameter); @@ -83,18 +83,17 @@ private static Config createConfig(String fileName) { return envConf.withFallback(defaultConf); } - /* - * Parse configuration in JSON format and return a type safe config object. + /** + * Parses a JSON string into a type-safe config object. * - * @param jsonString Configuration in JSON format - * @return Type safe config object + * @param jsonString The configuration string in JSON format. + * @param configType A label for the configuration type (used in error messages). + * @return The parsed Config object. + * @throws ProjectCommonException If the string is empty, parsing fails, or the result is empty. */ public static Config getConfigFromJsonString(String jsonString, String configType) { - ProjectLogger.log("ConfigUtil: getConfigFromJsonString called", LoggerEnum.DEBUG.name()); - - if (null == jsonString || StringUtils.isBlank(jsonString)) { - ProjectLogger.log( - "ConfigUtil:getConfigFromJsonString: Empty string", LoggerEnum.ERROR.name()); + if (StringUtils.isBlank(jsonString)) { + logger.error("ConfigUtil:getConfigFromJsonString: Empty string provided for " + configType, null); ProjectCommonException.throwServerErrorException( ResponseCode.errorConfigLoadEmptyString, ProjectUtil.formatMessage( @@ -104,30 +103,22 @@ public static Config getConfigFromJsonString(String jsonString, String configTyp Config jsonConfig = null; try { jsonConfig = ConfigFactory.parseString(jsonString); + logger.info("ConfigUtil:getConfigFromJsonString: Successfully constructed configuration for " + configType); } catch (Exception e) { - ProjectLogger.log( - "ConfigUtil:getConfigFromJsonString: Exception occurred during parse with error message = " - + e.getMessage(), - LoggerEnum.ERROR.name()); + logger.error("ConfigUtil:getConfigFromJsonString: Exception occurred during parse", e); ProjectCommonException.throwServerErrorException( ResponseCode.errorConfigLoadParseString, ProjectUtil.formatMessage( ResponseCode.errorConfigLoadParseString.getErrorMessage(), configType)); } - if (null == jsonConfig || jsonConfig.isEmpty()) { - ProjectLogger.log( - "ConfigUtil:getConfigFromJsonString: Empty configuration", LoggerEnum.ERROR.name()); + if (jsonConfig == null || jsonConfig.isEmpty()) { + logger.error("ConfigUtil:getConfigFromJsonString: Empty configuration resulting from parse for " + configType, null); ProjectCommonException.throwServerErrorException( ResponseCode.errorConfigLoadEmptyConfig, ProjectUtil.formatMessage( ResponseCode.errorConfigLoadEmptyConfig.getErrorMessage(), configType)); } - - ProjectLogger.log( - "ConfigUtil:getConfigFromJsonString: Successfully constructed type safe configuration", - LoggerEnum.DEBUG.name()); - return jsonConfig; } } diff --git a/core/sunbird-platform-common/src/main/java/org/sunbird/utils/EsConfigUtil.java b/core/sunbird-platform-common/src/main/java/org/sunbird/utils/EsConfigUtil.java new file mode 100644 index 000000000..7b7dab28e --- /dev/null +++ b/core/sunbird-platform-common/src/main/java/org/sunbird/utils/EsConfigUtil.java @@ -0,0 +1,26 @@ +package org.sunbird.utils; + +import org.apache.commons.lang3.StringUtils; + +/** + * Utility class for retrieving Elasticsearch configuration values. + * Checks system environment variables first, then falls back to properties cache. + */ +public class EsConfigUtil { + + private EsConfigUtil() {} + + /** + * Retrieves the configuration value for the given key. + * Priority: System Environment Variable -> Properties Cache. + * + * @param key The configuration key. + * @return The configuration value. + */ + public static String getConfigValue(String key) { + if (StringUtils.isNotBlank(System.getenv(key))) { + return System.getenv(key); + } + return org.sunbird.common.PropertiesCache.getInstance().getProperty(key); + } +} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/ExcelFileUtil.java b/core/sunbird-platform-common/src/main/java/org/sunbird/utils/ExcelFileUtil.java similarity index 60% rename from course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/ExcelFileUtil.java rename to core/sunbird-platform-common/src/main/java/org/sunbird/utils/ExcelFileUtil.java index bc1503be6..8d5394687 100644 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/ExcelFileUtil.java +++ b/core/sunbird-platform-common/src/main/java/org/sunbird/utils/ExcelFileUtil.java @@ -1,4 +1,4 @@ -package org.sunbird.common.models.util; +package org.sunbird.utils; import java.io.File; import java.io.FileOutputStream; @@ -8,9 +8,23 @@ import org.apache.poi.ss.usermodel.Row; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; +import org.sunbird.logging.LoggerUtil; +/** + * Utility class to generate Excel files using Apache POI. + * Extends basic FileUtil functionalities. + */ public class ExcelFileUtil extends FileUtil { + private static final LoggerUtil logger = new LoggerUtil(ExcelFileUtil.class); + + /** + * Writes the provided data values to an Excel file (.xlsx). + * + * @param fileName The name of the file to be created (without extension). + * @param dataValues A list of rows, where each row is a list of cell objects (Strings, Integers, etc.). + * @return The created File object, or null (and fails gracefully) if an error occurs. + */ @SuppressWarnings({"resource", "unused"}) public File writeToFile(String fileName, List> dataValues) { // Blank workbook @@ -20,6 +34,9 @@ public File writeToFile(String fileName, List> dataValues) { FileOutputStream out = null; File file = null; int rownum = 0; + + logger.info("ExcelFileUtil:writeToFile: Starting file creation for: " + fileName); + for (Object key : dataValues) { Row row = sheet.createRow(rownum); List objArr = dataValues.get(rownum); @@ -35,7 +52,7 @@ public File writeToFile(String fileName, List> dataValues) { } else if (obj instanceof Double) { cell.setCellValue((Double) obj); } else { - if (ProjectUtil.isNotNull(obj)) { + if (null != (obj)) { cell.setCellValue(obj.toString()); } } @@ -48,17 +65,22 @@ public File writeToFile(String fileName, List> dataValues) { file = new File(fileName + ".xlsx"); out = new FileOutputStream(file); workbook.write(out); - // out.close(); - ProjectLogger.log("File " + fileName + " created successfully"); + logger.info( + "ExcelFileUtil:writeToFile: File created successfully. Name: " + + fileName + + ", Rows: " + + rownum); } catch (Exception e) { - ProjectLogger.log(e.getMessage(), e); + logger.error( + "ExcelFileUtil:writeToFile: Error occurred while creating file: " + fileName, e); } finally { if (null != out) { try { out.close(); } catch (IOException e) { - ProjectLogger.log(e.getMessage(), e); + logger.error( + "ExcelFileUtil:writeToFile: Error closing output stream for file: " + fileName, e); } } } diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/FileUtil.java b/core/sunbird-platform-common/src/main/java/org/sunbird/utils/FileUtil.java similarity index 52% rename from course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/FileUtil.java rename to core/sunbird-platform-common/src/main/java/org/sunbird/utils/FileUtil.java index cda6931f6..e178995af 100644 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/FileUtil.java +++ b/core/sunbird-platform-common/src/main/java/org/sunbird/utils/FileUtil.java @@ -1,13 +1,30 @@ -package org.sunbird.common.models.util; +package org.sunbird.utils; import java.io.File; import java.util.List; import org.apache.commons.lang3.StringUtils; +/** + * Abstract factory and utility class for file operations. + * Provides methods to write list data to files and instantiate specific file utilities. + */ public abstract class FileUtil { + /** + * Abstract method to write data to a file. + * + * @param fileName The name of the file. + * @param dataValues The data to be written. + * @return The created File object. + */ public abstract File writeToFile(String fileName, List> dataValues); + /** + * Helper method to convert a List of objects into a comma-separated String. + * + * @param obj The object which must be a List. + * @return A comma-separated string representation of the list, or empty string if empty. + */ @SuppressWarnings("unchecked") protected static String getListValue(Object obj) { List data = (List) obj; @@ -22,6 +39,12 @@ protected static String getListValue(Object obj) { return ""; } + /** + * Factory method to get a specific FileUtil implementation based on format. + * + * @param format The desired file format (e.g., "excel"). + * @return An instance of the corresponding FileUtil implementation. + */ public static FileUtil getFileUtil(String format) { String tempformat = ""; if (!StringUtils.isBlank(format)) { diff --git a/core/sunbird-platform-common/src/main/java/org/sunbird/utils/JsonUtil.java b/core/sunbird-platform-common/src/main/java/org/sunbird/utils/JsonUtil.java new file mode 100644 index 000000000..64bab9eda --- /dev/null +++ b/core/sunbird-platform-common/src/main/java/org/sunbird/utils/JsonUtil.java @@ -0,0 +1,146 @@ +package org.sunbird.utils; + +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import java.io.InputStream; +import java.text.SimpleDateFormat; +import org.sunbird.logging.LoggerUtil; +import org.sunbird.request.RequestContext; + +/** + * Utility class for JSON operations using Jackson. + * Provides static methods for serialization, deserialization, and conversion. + */ +public class JsonUtil { + + private static final LoggerUtil logger = new LoggerUtil(JsonUtil.class); + private static ObjectMapper mapper = new ObjectMapper(); + private static ObjectMapper mapperWithDateFormat = new ObjectMapper(); + + static { + // Configure default mapper + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); + mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); + mapper.setSerializationInclusion(Include.NON_NULL); + + // Configure mapper with date format support base settings + mapperWithDateFormat.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + mapperWithDateFormat.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); + } + + /** + * Serializes an object to a JSON string. + * + * @param obj The object to serialize. + * @return The JSON string representation. + * @throws Exception If serialization fails. + */ + public static String serialize(Object obj) throws Exception { + return mapper.writeValueAsString(obj); + } + + /** + * Deserializes a JSON string to a POJO. + * + * @param value The JSON string. + * @param clazz The target class. + * @param The type of the target class. + * @return The deserialized object. + * @throws Exception If deserialization fails. + */ + public static T deserialize(String value, Class clazz) throws Exception { + return mapper.readValue(value, clazz); + } + + /** + * Deserializes an InputStream to a POJO. + * + * @param value The InputStream containing JSON. + * @param clazz The target class. + * @param The type of the target class. + * @return The deserialized object. + * @throws Exception If deserialization fails. + */ + public static T deserialize(InputStream value, Class clazz) throws Exception { + return mapper.readValue(value, clazz); + } + + /** + * Converts an object to the target class type using Jackson conversion. + * + * @param value The source object. + * @param clazz The target class. + * @param The type of the target class. + * @return The converted object. + * @throws Exception If conversion fails. + */ + public static T convert(Object value, Class clazz) throws Exception { + return mapper.convertValue(value, clazz); + } + + /** + * Converts an object to the target class using a specific date format. + * + * @param value The source object. + * @param clazz The target class. + * @param dateFormat The SimpleDateFormat to use. + * @param The type of the target class. + * @return The converted object. + * @throws Exception If conversion fails. + */ + public static T convertWithDateFormat( + Object value, Class clazz, SimpleDateFormat dateFormat) throws Exception { + mapperWithDateFormat.setDateFormat(dateFormat); + return mapperWithDateFormat.convertValue(value, clazz); + } + + /** + * Serializes an object to a JSON string, logging any errors instead of throwing. + * + * @param object The object to serialize. + * @param context The request context for logging. + * @return The JSON string, or null if an error occurs. + */ + public static String toJson(Object object, RequestContext context) { + try { + return mapper.writeValueAsString(object); + } catch (Exception e) { + logger.error(context, "JsonUtil:toJson: Error occurred while serializing object to JSON string.", e); + } + return null; + } + + /** + * Checks if a string is null or empty (after trimming). + * + * @param value The string to check. + * @return True if null or empty/whitespace, false otherwise. + */ + public static boolean isStringNullOREmpty(String value) { + return value == null || "".equals(value.trim()); + } + + /** + * Deserializes a JSON string to a POJO, logging any errors instead of throwing. + * + * @param res The JSON string. + * @param clazz The target class. + * @param context The request context for logging. + * @param The type of the target class. + * @return The deserialized object, or null if an error occurs. + */ + public static T getAsObject(String res, Class clazz, RequestContext context) { + T result = null; + try { + JsonNode node = mapper.readTree(res); + result = mapper.convertValue(node, clazz); + } catch (Exception e) { + logger.error(context, "JsonUtil:getAsObject: Error occurred while deserializing JSON string to Object.", e); + } + return result; + } +} diff --git a/core/sunbird-platform-common/src/main/java/org/sunbird/utils/Matcher.java b/core/sunbird-platform-common/src/main/java/org/sunbird/utils/Matcher.java new file mode 100644 index 000000000..117aea269 --- /dev/null +++ b/core/sunbird-platform-common/src/main/java/org/sunbird/utils/Matcher.java @@ -0,0 +1,35 @@ +package org.sunbird.utils; + +import org.apache.commons.lang3.StringUtils; + +/** + * Utility class for matching identifiers and other string values. + * + *

This class provides standardized static methods for string comparison, primarily dealing with + * case-insensitive matching logic used throughout the application for identifiers. + */ +public class Matcher { + + /** Private constructor to prevent instantiation of utility class. */ + private Matcher() {} + + /** + * Compares two identifier strings for equality, ignoring case considerations. + * + *

This method delegates to {@link StringUtils#equalsIgnoreCase(CharSequence, CharSequence)}. + * It handles {@code null} inputs gracefully: + * + *

    + *
  • If both identifiers are {@code null}, it returns {@code true}. + *
  • If one is {@code null} and the other is not, it returns {@code false}. + *
  • Otherwise, it compares them ignoring case (e.g., "abc" equals "ABC"). + *
+ * + * @param firstVal The first identifier string to compare. + * @param secondVal The second identifier string to compare. + * @return {@code true} if the identifiers are equal (ignoring case), {@code false} otherwise. + */ + public static boolean matchIdentifiers(String firstVal, String secondVal) { + return StringUtils.equalsIgnoreCase(firstVal, secondVal); + } +} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/RestUtil.java b/core/sunbird-platform-common/src/main/java/org/sunbird/utils/RestUtil.java similarity index 57% rename from course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/RestUtil.java rename to core/sunbird-platform-common/src/main/java/org/sunbird/utils/RestUtil.java index 28e5f23c0..1636f01ec 100644 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/RestUtil.java +++ b/core/sunbird-platform-common/src/main/java/org/sunbird/utils/RestUtil.java @@ -1,4 +1,4 @@ -package org.sunbird.common.models.util; +package org.sunbird.utils; import org.apache.pekko.dispatch.Futures; import com.mashape.unirest.http.HttpResponse; @@ -9,12 +9,20 @@ import com.mashape.unirest.request.BaseRequest; import org.apache.commons.lang3.StringUtils; import org.json.JSONObject; +import org.sunbird.logging.LoggerUtil; +import org.sunbird.keys.JsonKey; +import org.sunbird.common.PropertiesCache; import scala.concurrent.Future; import scala.concurrent.Promise; -/** @author Mahesh Kumar Gangula */ +/** + * Utility class for performing REST API operations using Unirest. + * Supports synchronous and asynchronous JSON requests. + */ public class RestUtil { + private static final LoggerUtil logger = new LoggerUtil(RestUtil.class); + static { String apiKey = System.getenv(JsonKey.EKSTEP_AUTHORIZATION); if (StringUtils.isBlank(apiKey)) { @@ -25,8 +33,16 @@ public class RestUtil { Unirest.setDefaultHeader("Connection", "Keep-Alive"); } + private RestUtil() {} + + /** + * Executes an asynchronous JSON request. + * + * @param request The Unirest BaseRequest to execute. + * @return A Future containing the HttpResponse with JsonNode. + */ public static Future> executeAsync(BaseRequest request) { - ProjectLogger.log("RestUtil:execute: request url = " + request.getHttpRequest().getUrl()); + logger.debug("RestUtil:executeAsync: request url = " + request.getHttpRequest().getUrl()); Promise> promise = Futures.promise(); request.asJsonAsync( @@ -51,25 +67,46 @@ public void cancelled() { return promise.future(); } + /** + * Executes a synchronous JSON request. + * + * @param request The Unirest BaseRequest to execute. + * @return The HttpResponse with JsonNode. + * @throws Exception If the request fails. + */ public static HttpResponse execute(BaseRequest request) throws Exception { return request.asJson(); } + /** + * Extracts a value from a nested JSON response using a dot-separated key. + * + * @param resp The HttpResponse containing the JSON body. + * @param key The dot-separated key to locate the value. + * @return The string value at the specified key. + * @throws Exception If extracting the value fails. + */ public static String getFromResponse(HttpResponse resp, String key) throws Exception { String[] nestedKeys = key.split("\\."); JSONObject obj = resp.getBody().getObject(); for (int i = 0; i < nestedKeys.length - 1; i++) { String nestedKey = nestedKeys[i]; - if (obj.has(nestedKey)) obj = obj.getJSONObject(nestedKey); + if (obj.has(nestedKey)) { + obj = obj.getJSONObject(nestedKey); + } } - String val = obj.getString(nestedKeys[nestedKeys.length - 1]); - return val; + return obj.getString(nestedKeys[nestedKeys.length - 1]); } + /** + * Checks if the response status indicates success (HTTP 200). + * + * @param resp The HttpResponse to check. + * @return True if status is 200, false otherwise. + */ public static boolean isSuccessful(HttpResponse resp) { - int status = resp.getStatus(); - return (status == 200); + return resp.getStatus() == 200; } } diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/Slug.java b/core/sunbird-platform-common/src/main/java/org/sunbird/utils/Slug.java similarity index 60% rename from course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/Slug.java rename to core/sunbird-platform-common/src/main/java/org/sunbird/utils/Slug.java index 04834715c..db80e7ee1 100644 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/Slug.java +++ b/core/sunbird-platform-common/src/main/java/org/sunbird/utils/Slug.java @@ -1,5 +1,4 @@ -/** */ -package org.sunbird.common.models.util; +package org.sunbird.utils; import java.net.URLDecoder; import java.text.Normalizer; @@ -10,36 +9,43 @@ import java.util.Set; import java.util.regex.Pattern; import net.sf.junidecode.Junidecode; +import org.sunbird.logging.LoggerUtil; /** - * This class will remove the special character,space from the provided String. - * - * @author Manzarul + * Utility class for slugifying strings. + * Removes special characters, spaces, and handles transliteration. */ public class Slug { + private static final LoggerUtil logger = new LoggerUtil(Slug.class); private static final Pattern NONLATIN = Pattern.compile("[^\\w-\\.]"); private static final Pattern WHITESPACE = Pattern.compile("[\\s]"); private static final Pattern DUPDASH = Pattern.compile("-+"); - private static LoggerUtil logger = new LoggerUtil(Slug.class); + private Slug() {} + + /** + * Creates a slug from the input string. + * + * @param input The string to slugify. + * @param transliterate Whether to transliterate characters to ASCII. + * @return The slugified string. + */ public static String makeSlug(String input, boolean transliterate) { String origInput = input; - String tempInputValue = ""; // Validate the input if (input == null) { - logger.info(null, "Provided input value is null"); + logger.debug("Slug:makeSlug: Provided input value is null."); return input; } // Remove extra spaces - tempInputValue = input.trim(); + String tempInputValue = input.trim(); // Remove URL encoding tempInputValue = urlDecode(tempInputValue); // If transliterate is required if (transliterate) { - // Tranlisterate & cleanup - String transliterated = transliterate(tempInputValue); - tempInputValue = transliterated; + // Transliterate & cleanup + tempInputValue = transliterate(tempInputValue); } // Replace all whitespace with dashes tempInputValue = WHITESPACE.matcher(tempInputValue).replaceAll("-"); @@ -58,30 +64,50 @@ public static String makeSlug(String input, boolean transliterate) { private static void validateResult(String input, String origInput) { // Check if we are not left with a blank if (input.length() == 0) { - logger.info(null,"Failed to cleanup the input " + origInput); + logger.debug( + "Slug:validateResult: Failed to cleanup the input, resulted in empty string. Original input: " + + origInput); } } + /** + * Transliterates the input string to ASCII. + * + * @param input The string to transliterate. + * @return The transliterated string. + */ public static String transliterate(String input) { return Junidecode.unidecode(input); } + /** + * Decodes a URL encoded string. + * + * @param input The URL encoded string. + * @return The decoded string, or the original if decoding fails. + */ public static String urlDecode(String input) { String value = ""; try { value = URLDecoder.decode(input, "UTF-8"); } catch (Exception ex) { - logger.error(null, ex.getMessage(), ex); + logger.error("Slug:urlDecode: Exception occurred while decoding url: " + ex.getMessage(), ex); } return value; } + /** + * Removes duplicate characters from a string. + * + * @param text The input string. + * @return The string with unique characters preserving order. + */ public static String removeDuplicateChars(String text) { - Set set = new LinkedHashSet<>(); - StringBuilder ret = new StringBuilder(text.length()); - if (text.length() == 0) { + if (text == null || text.length() == 0) { return ""; } + Set set = new LinkedHashSet<>(); + StringBuilder ret = new StringBuilder(text.length()); for (int i = 0; i < text.length(); i++) { set.add(text.charAt(i)); } @@ -92,10 +118,18 @@ public static String removeDuplicateChars(String text) { return ret.toString(); } + /** + * Normalizes dashes in the text (removes duplicates and leading/trailing dashes). + * + * @param text The input text. + * @return The text with normalized dashes. + */ public static String normalizeDashes(String text) { String clean = DUPDASH.matcher(text).replaceAll("-"); // Special case that only dashes remain - if ("-".equals(clean) || "--".equals(clean)) return ""; + if ("-".equals(clean) || "--".equals(clean)) { + return ""; + } int startIdx = (clean.startsWith("-") ? 1 : 0); int endIdx = (clean.endsWith("-") ? 1 : 0); clean = clean.substring(startIdx, (clean.length() - endIdx)); diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/StringFormatter.java b/core/sunbird-platform-common/src/main/java/org/sunbird/utils/StringFormatter.java similarity index 51% rename from course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/StringFormatter.java rename to core/sunbird-platform-common/src/main/java/org/sunbird/utils/StringFormatter.java index 61d8e1851..1122a092a 100644 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/StringFormatter.java +++ b/core/sunbird-platform-common/src/main/java/org/sunbird/utils/StringFormatter.java @@ -1,9 +1,8 @@ -package org.sunbird.common.models.util; +package org.sunbird.utils; /** * Helper class for String formatting operations. - * - * @author Amit Kumar + * Provides methods for joining strings with various delimiters (dot, comma, 'and', 'or'). */ public class StringFormatter { @@ -15,40 +14,40 @@ public class StringFormatter { private StringFormatter() {} /** - * Helper method to construct dot formatted string. + * Joins multiple strings with a dot delimiter. * - * @param params One or more strings to be joined by dot - * @return Dot formatted string + * @param params One or more strings to be joined. + * @return The dot-separated string. */ public static String joinByDot(String... params) { return String.join(DOT, params); } /** - * Helper method to construct or formatted string. + * Joins multiple strings with an 'or' delimiter. * - * @param params One or more strings to be joined by or - * @return Or formatted string + * @param params One or more strings to be joined. + * @return The 'or'-separated string. */ public static String joinByOr(String... params) { return String.join(OR, params); } /** - * Helper method to construct and formatted string. + * Joins multiple strings with an 'and' delimiter. * - * @param params One or more strings to be joined by and - * @return and formatted string + * @param params One or more strings to be joined. + * @return The 'and'-separated string. */ public static String joinByAnd(String... params) { return String.join(AND, params); } /** - * Helper method to construct and formatted string. + * Joins multiple strings with a comma delimiter. * - * @param params One or more strings to be joined by comma - * @return and formatted string + * @param params One or more strings to be joined. + * @return The comma-separated string. */ public static String joinByComma(String... params) { return String.join(COMMA, params); diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/TableNameUtil.java b/core/sunbird-platform-common/src/main/java/org/sunbird/utils/TableNameUtil.java similarity index 90% rename from course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/TableNameUtil.java rename to core/sunbird-platform-common/src/main/java/org/sunbird/utils/TableNameUtil.java index 2969607af..131c68c17 100644 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/TableNameUtil.java +++ b/core/sunbird-platform-common/src/main/java/org/sunbird/utils/TableNameUtil.java @@ -1,6 +1,12 @@ -package org.sunbird.common.models.util; +package org.sunbird.utils; +/** + * Utility class to hold table names used in the application. + */ public class TableNameUtil { + + private TableNameUtil() {} + public static final String USER_ENROLLMENTS_TABLENAME = "user_enrolments"; public static final String USER_CONTENT_CONSUMPTION_TABLENAME = "user_content_consumption"; public static final String COURSE_MANAGEMENT_TABLENAME = "course_management"; diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/request/BaseRequestValidator.java b/core/sunbird-platform-common/src/main/java/org/sunbird/validators/BaseRequestValidator.java similarity index 84% rename from course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/request/BaseRequestValidator.java rename to core/sunbird-platform-common/src/main/java/org/sunbird/validators/BaseRequestValidator.java index 22d4f789b..34d61431f 100644 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/request/BaseRequestValidator.java +++ b/core/sunbird-platform-common/src/main/java/org/sunbird/validators/BaseRequestValidator.java @@ -1,20 +1,24 @@ -package org.sunbird.common.request; +package org.sunbird.validators; +import com.typesafe.config.ConfigFactory; import java.text.MessageFormat; import java.util.Arrays; import java.util.List; import java.util.Map; - -import com.typesafe.config.ConfigFactory; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang.ArrayUtils; import org.apache.commons.lang.StringUtils; -import org.sunbird.common.exception.ProjectCommonException; -import org.sunbird.common.models.util.*; -import org.sunbird.common.responsecode.ResponseCode; +import org.sunbird.exception.ProjectCommonException; +import org.sunbird.common.ProjectUtil; +import org.sunbird.request.Request; +import org.sunbird.response.ResponseCode; +import org.sunbird.keys.JsonKey; +import org.sunbird.logging.LoggerUtil; +import org.sunbird.utils.StringFormatter; /** * Base request validator class to house common validation methods. + * Provides utility methods for validating request parameters, headers, and data types. * * @author B Vinaya Kumar */ @@ -54,7 +58,7 @@ public void validateParam(String value, ResponseCode error, String errorMsgArgum /** * Helper method which throws an exception if the given parameter list size exceeds the expected - * size + * size. * * @param paramName Configuration parameter name * @param key Request parameter name @@ -83,16 +87,16 @@ public void validateListParamSize(String paramName, String key, List lis } /** - * This method will create the ProjectCommonException by reading ResponseCode and errorCode. - * incase ResponseCode is null then it will throw invalidData error. + * This method will create the ProjectCommonException by reading ResponseCode and errorCode. Use + * case: If ResponseCode is null then it will throw invalidData error. * * @param code Error response code * @param errorCode (Http error code) - * @return custom project exception + * @return Custom project exception */ public ProjectCommonException createExceptionByResponseCode(ResponseCode code, int errorCode) { if (code == null) { - logger.info(null, "ResponseCode object is coming as null"); + logger.info(null, "ResponseCode object is coming as null"); return new ProjectCommonException( ResponseCode.invalidData.getErrorCode(), ResponseCode.invalidData.getErrorMessage(), @@ -102,17 +106,18 @@ public ProjectCommonException createExceptionByResponseCode(ResponseCode code, i } /** - * This method will create the ProjectCommonException by reading ResponseCode and errorCode. - * incase ResponseCode is null then it will throw invalidData error. + * This method will create the ProjectCommonException by reading ResponseCode and errorCode. Use + * case: If ResponseCode is null then it will throw invalidData error. * * @param code Error response code * @param errorCode (Http error code) - * @return custom project exception + * @param errorMsgArgument Argument for error message + * @return Custom project exception */ public ProjectCommonException createExceptionByResponseCode( ResponseCode code, int errorCode, String errorMsgArgument) { if (code == null) { - logger.info(null, "ResponseCode object is coming as null"); + logger.info(null, "ResponseCode object is coming as null"); return new ProjectCommonException( ResponseCode.invalidData.getErrorCode(), ResponseCode.invalidData.getErrorMessage(), @@ -127,7 +132,7 @@ public ProjectCommonException createExceptionByResponseCode( /** * Method to check whether given mandatory fields is in given map or not. * - * @param data Map contains the key value, + * @param data Map contains the key value. * @param keys List of string represents the mandatory fields. */ public void checkMandatoryFieldsPresent(Map data, String... keys) { @@ -142,19 +147,20 @@ public void checkMandatoryFieldsPresent(Map data, String... keys key -> { if (StringUtils.isEmpty((String) data.get(key))) { throw new ProjectCommonException( - ResponseCode.mandatoryParamsMissing.getErrorCode(), + ResponseCode.mandatoryParamsMissing, ResponseCode.mandatoryParamsMissing.getErrorMessage(), ResponseCode.CLIENT_ERROR.getResponseCode(), key); } }); } + /** - * Method to check whether given mandatory fields is in given map or not. also check the instance - * of request attributes + * Method to check whether given mandatory fields is in given map or not. Also checks the instance + * of request attributes. * - * @param data Map contains the key value, - * @param mandatoryParamsList List of string represents the mandatory fields. + * @param data Map contains the key value. + * @param mandatoryParamsList List of strings representing the mandatory fields. */ public void checkMandatoryFieldsPresent( Map data, List mandatoryParamsList) { @@ -168,7 +174,7 @@ public void checkMandatoryFieldsPresent( key -> { if (StringUtils.isEmpty((String) data.get(key))) { throw new ProjectCommonException( - ResponseCode.mandatoryParamsMissing.getErrorCode(), + ResponseCode.mandatoryParamsMissing, ResponseCode.mandatoryParamsMissing.getErrorMessage(), ResponseCode.CLIENT_ERROR.getResponseCode(), key); @@ -183,7 +189,7 @@ public void checkMandatoryFieldsPresent( } /** - * Method to check whether given mandatory fields is in given map or not . + * Method to check whether given mandatory fields is in given map or not. * * @param data Map contains the key value * @param keys List of string represents the mandatory fields @@ -202,7 +208,7 @@ public void checkMandatoryParamsPresent( key -> { if (StringUtils.isEmpty((String) data.get(key))) { throw new ProjectCommonException( - ResponseCode.mandatoryParamsMissing.getErrorCode(), + ResponseCode.mandatoryParamsMissing, ProjectUtil.formatMessage( ResponseCode.mandatoryParamsMissing.getErrorMessage(), exceptionMsg), ResponseCode.CLIENT_ERROR.getResponseCode(), @@ -212,12 +218,11 @@ public void checkMandatoryParamsPresent( } /** - * Method to check whether given fields is in given map or not .If it is there throw exception. - * because in some update request cases we don't want to update some props to , if it is there in - * request , throw exception. + * Method to check whether given fields are present in given map. If present, throws exception. + * Used for update requests where certain properties cannot be updated. * * @param data Map contains the key value - * @param keys List of string represents the must not present fields. + * @param keys List of string represents the fields that must NOT be present. */ public void checkReadOnlyAttributesAbsent(Map data, String... keys) { @@ -232,7 +237,7 @@ public void checkReadOnlyAttributesAbsent(Map data, String... ke key -> { if (data.containsKey(key)) { throw new ProjectCommonException( - ResponseCode.unupdatableField.getErrorCode(), + ResponseCode.unupdatableField, ResponseCode.unupdatableField.getErrorMessage(), ResponseCode.CLIENT_ERROR.getResponseCode(), key); @@ -258,7 +263,7 @@ public void checkMandatoryHeadersPresent(Map data, String... k key -> { if (ArrayUtils.isEmpty(data.get(key))) { throw new ProjectCommonException( - ResponseCode.mandatoryHeadersMissing.getErrorCode(), + ResponseCode.mandatoryHeadersMissing, ResponseCode.mandatoryHeadersMissing.getErrorMessage(), ResponseCode.CLIENT_ERROR.getResponseCode(), key); @@ -276,15 +281,15 @@ public void checkForFieldsNotAllowed(Map requestMap, List { - if (requestMap.containsKey(field)) { - throw new ProjectCommonException( - ResponseCode.invalidRequestParameter.getErrorCode(), - ProjectUtil.formatMessage( - ResponseCode.invalidRequestParameter.getErrorMessage(), field), - ResponseCode.CLIENT_ERROR.getResponseCode()); - } - }); + field -> { + if (requestMap.containsKey(field)) { + throw new ProjectCommonException( + ResponseCode.invalidRequestParameter.getErrorCode(), + ProjectUtil.formatMessage( + ResponseCode.invalidRequestParameter.getErrorMessage(), field), + ResponseCode.CLIENT_ERROR.getResponseCode()); + } + }); } /** @@ -347,6 +352,7 @@ public void validateDateParam(String dob) { /** * Helper method which throws an exception if given parameter value is blank (null or empty). * + * @param value Request parameter value. * @param error Error to be thrown in case of validation error. * @param errorMsg Error message. */ @@ -358,6 +364,7 @@ public void validateParamValue(String value, ResponseCode error, String errorMsg ResponseCode.CLIENT_ERROR.getResponseCode()); } } + /** * Helper method which throws an exception if user ID in request is not same as that in user * token. @@ -371,7 +378,7 @@ public static void validateUserId(Request request, String userIdKey) { .get(userIdKey) .equals(request.getContext().get(JsonKey.REQUESTED_BY)))) { throw new ProjectCommonException( - ResponseCode.invalidParameterValue.getErrorCode(), + ResponseCode.invalidParameterValue, ResponseCode.invalidParameterValue.getErrorMessage(), ResponseCode.CLIENT_ERROR.getResponseCode(), (String) request.getRequest().get(JsonKey.USER_ID), @@ -379,6 +386,11 @@ public static void validateUserId(Request request, String userIdKey) { } } + /** + * Validates a search request ensuring filters are present and correctly typed. + * + * @param request The search request. + */ public void validateSearchRequest(Request request) { if (null == request.getRequest().get(JsonKey.FILTERS)) { throw new ProjectCommonException( @@ -422,6 +434,7 @@ private void validateSearchRequestFieldsValues(Request request) { } } + @SuppressWarnings("unchecked") private void validateSearchRequestFiltersValues(Request request) { if (request.getRequest().containsKey(JsonKey.FILTERS) && ((request.getRequest().get(JsonKey.FILTERS) instanceof Map))) { @@ -440,14 +453,13 @@ private void validateSearchRequestFiltersValues(Request request) { validateListValues((List) val, key); } else if (val instanceof Map) { validateMapValues((Map) val); - } else if (val == null) - if (StringUtils.isEmpty((String) val)) { - throw new ProjectCommonException( - ResponseCode.invalidParameterValue.getErrorCode(), - MessageFormat.format( - ResponseCode.invalidParameterValue.getErrorMessage(), val, key), - ResponseCode.CLIENT_ERROR.getResponseCode()); - } + } else if (val != null && StringUtils.isEmpty((String) val)) { + throw new ProjectCommonException( + ResponseCode.invalidParameterValue.getErrorCode(), + MessageFormat.format( + ResponseCode.invalidParameterValue.getErrorMessage(), val, key), + ResponseCode.CLIENT_ERROR.getResponseCode()); + } }); } } @@ -476,6 +488,11 @@ private void validateListValues(List val, String key) { }); } + /** + * Validates the email format. + * + * @param email The email string to validate. + */ public void validateEmail(String email) { if (!EmailValidator.isEmailValid(email)) { throw new ProjectCommonException( @@ -485,6 +502,11 @@ public void validateEmail(String email) { } } + /** + * Validates the phone format. + * + * @param phone The phone string to validate. + */ public void validatePhone(String phone) { if (!ProjectUtil.validatePhone(phone, null)) { throw new ProjectCommonException( @@ -493,13 +515,19 @@ public void validatePhone(String phone) { ResponseCode.CLIENT_ERROR.getResponseCode()); } } - + + /** + * Validates if the requestedBy user is authorized. + * + * @param requestedBy The user ID making the request. + */ public void validateRequestedBy(String requestedBy) { if (ConfigFactory.load().getBoolean(JsonKey.AUTH_ENABLED)) { if (StringUtils.isBlank(requestedBy) || JsonKey.ANONYMOUS.contentEquals(requestedBy)) { - throw new ProjectCommonException(ResponseCode.unAuthorized.getErrorCode(), - ResponseCode.unAuthorized.getErrorMessage(), - ResponseCode.UNAUTHORIZED.getResponseCode()); + throw new ProjectCommonException( + ResponseCode.unAuthorized.getErrorCode(), + ResponseCode.unAuthorized.getErrorMessage(), + ResponseCode.UNAUTHORIZED.getResponseCode()); } } } diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/EmailValidator.java b/core/sunbird-platform-common/src/main/java/org/sunbird/validators/EmailValidator.java similarity index 68% rename from course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/EmailValidator.java rename to core/sunbird-platform-common/src/main/java/org/sunbird/validators/EmailValidator.java index 821c73d55..fc0566938 100644 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/EmailValidator.java +++ b/core/sunbird-platform-common/src/main/java/org/sunbird/validators/EmailValidator.java @@ -1,13 +1,12 @@ -package org.sunbird.common.models.util; +package org.sunbird.validators; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.lang.StringUtils; /** - * Helper class for validating email. - * - * @author Amit Kumar + * Helper class for validating email addresses. + * Uses regex patterns to ensure email format correctness. */ public class EmailValidator { @@ -23,10 +22,10 @@ private EmailValidator() {} } /** - * Validates format of email. + * Validates the format of an email address. * - * @param email Email value. - * @return True, if email format is valid. Otherwise, return false. + * @param email The email address to validate. + * @return True if the email format is valid, otherwise false. */ public static boolean isEmailValid(String email) { if (StringUtils.isBlank(email)) { diff --git a/core/sunbird-platform-common/src/main/java/org/sunbird/validators/LearnerStateRequestValidator.java b/core/sunbird-platform-common/src/main/java/org/sunbird/validators/LearnerStateRequestValidator.java new file mode 100644 index 000000000..7286bcb47 --- /dev/null +++ b/core/sunbird-platform-common/src/main/java/org/sunbird/validators/LearnerStateRequestValidator.java @@ -0,0 +1,49 @@ +package org.sunbird.validators; + +import org.apache.commons.collections.CollectionUtils; +import org.sunbird.keys.JsonKey; +import org.sunbird.request.Request; + +import java.util.List; + +/** + * Validator for Learner State related requests. + * Handles validation logic for fetching content state. + */ +public class LearnerStateRequestValidator extends BaseRequestValidator { + + /** + * Validates the 'get content state' request. + * Checks for mandatory parameters and validates course/collection IDs. + * + * @param request The request object containing payload. + */ + @SuppressWarnings("unchecked") + public void validateGetContentState(Request request) { + validateListParam(request.getRequest(), JsonKey.COURSE_IDS, JsonKey.CONTENT_IDS); + + if (request.getRequest().containsKey(JsonKey.COURSE_IDS)) { + List courseIds = (List) request.getRequest().get(JsonKey.COURSE_IDS); + request.getRequest().remove(JsonKey.COURSE_IDS); + + if (!request.getRequest().containsKey(JsonKey.COURSE_ID) + && !request.getRequest().containsKey(JsonKey.COLLECTION_ID) + && CollectionUtils.isNotEmpty(courseIds)) { + request.getRequest().put(JsonKey.COURSE_ID, courseIds.get(0)); + } + } + + String courseIdKey = + request.getRequest().containsKey(JsonKey.COURSE_ID) + ? JsonKey.COURSE_ID + : JsonKey.COLLECTION_ID; + + // Ensure the key exists before putting it back to avoid null values if logic changes + if (request.getRequest().containsKey(courseIdKey)) { + request.getRequest().put(JsonKey.COURSE_ID, request.getRequest().get(courseIdKey)); + } + + checkMandatoryFieldsPresent( + request.getRequest(), JsonKey.USER_ID, JsonKey.COURSE_ID, JsonKey.BATCH_ID); + } +} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/PhoneValidator.java b/core/sunbird-platform-common/src/main/java/org/sunbird/validators/PhoneValidator.java similarity index 68% rename from course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/PhoneValidator.java rename to core/sunbird-platform-common/src/main/java/org/sunbird/validators/PhoneValidator.java index bfc87a107..822beaf57 100644 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/PhoneValidator.java +++ b/core/sunbird-platform-common/src/main/java/org/sunbird/validators/PhoneValidator.java @@ -1,4 +1,4 @@ -package org.sunbird.common.models.util; +package org.sunbird.validators; import com.google.i18n.phonenumbers.NumberParseException; import com.google.i18n.phonenumbers.PhoneNumberUtil; @@ -6,20 +6,30 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.lang3.StringUtils; -import org.sunbird.common.exception.ProjectCommonException; -import org.sunbird.common.responsecode.ResponseCode; +import org.sunbird.exception.ProjectCommonException; +import org.sunbird.logging.LoggerUtil; +import org.sunbird.common.PropertiesCache; +import org.sunbird.response.ResponseCode; /** - * This class will provide helper method to validate phone number and its country code. - * - * @author Amit Kumar + * Utility class for validating phone numbers and country codes. + * Uses Google's libphonenumber for validation. */ public class PhoneValidator { + private static final LoggerUtil logger = new LoggerUtil(PhoneValidator.class); private static final int ERROR_CODE = ResponseCode.CLIENT_ERROR.getResponseCode(); private PhoneValidator() {} + /** + * Validates a phone number against a country code. + * + * @param phone The phone number to validate. + * @param countryCode The country code for the phone number. + * @return True if valid. + * @throws ProjectCommonException If the phone number or country code is invalid. + */ public static boolean validatePhoneNumber(String phone, String countryCode) { if (phone.contains("+")) { throw new ProjectCommonException( @@ -46,6 +56,12 @@ public static boolean validatePhoneNumber(String phone, String countryCode) { } } + /** + * Validates if the provided country code string is in a valid format. + * + * @param countryCode The country code to check. + * @return True if format is valid, false otherwise. + */ public static boolean validateCountryCode(String countryCode) { String countryCodePattern = "^(?:[+] ?){0,1}(?:[0-9] ?){1,3}"; try { @@ -57,6 +73,13 @@ public static boolean validateCountryCode(String countryCode) { } } + /** + * Validates phone number using Google's PhoneNumberUtil. + * + * @param phone The phone number. + * @param countryCode The country code. + * @return True if the number is valid for the region. + */ public static boolean validatePhone(String phone, String countryCode) { PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.getInstance(); String code = countryCode; @@ -72,12 +95,18 @@ public static boolean validatePhone(String phone, String countryCode) { phoneNumber = phoneNumberUtil.parse(phone, isoCode); return phoneNumberUtil.isValidNumber(phoneNumber); } catch (NumberParseException e) { - ProjectLogger.log( + logger.error( "PhoneValidator:validatePhone: Exception occurred while validating phone number = ", e); } return false; } + /** + * Validates a phone number using a basic regex pattern for Indian numbers. + * + * @param phoneNumber The phone number string. + * @return True if matches pattern. + */ public static boolean validatePhoneNumber(String phoneNumber) { if (StringUtils.isBlank(phoneNumber)) { return false; diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/request/RequestValidator.java b/core/sunbird-platform-common/src/main/java/org/sunbird/validators/RequestValidator.java similarity index 73% rename from course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/request/RequestValidator.java rename to core/sunbird-platform-common/src/main/java/org/sunbird/validators/RequestValidator.java index 9380d94c2..68d4b4ef3 100644 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/request/RequestValidator.java +++ b/core/sunbird-platform-common/src/main/java/org/sunbird/validators/RequestValidator.java @@ -1,4 +1,4 @@ -package org.sunbird.common.request; +package org.sunbird.validators; import java.text.MessageFormat; import java.text.SimpleDateFormat; @@ -11,150 +11,152 @@ import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang3.StringUtils; -import org.sunbird.common.exception.ProjectCommonException; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.models.util.ProjectLogger; -import org.sunbird.common.models.util.ProjectUtil; -import org.sunbird.common.models.util.ProjectUtil.ProgressStatus; -import org.sunbird.common.models.util.ProjectUtil.Source; -import org.sunbird.common.models.util.PropertiesCache; -import org.sunbird.common.models.util.StringFormatter; -import org.sunbird.common.responsecode.ResponseCode; -import org.sunbird.common.responsecode.ResponseMessage; -import org.sunbird.common.request.Request; +import org.sunbird.exception.ProjectCommonException; +import org.sunbird.keys.JsonKey; +import org.sunbird.logging.LoggerUtil; +import org.sunbird.common.ProjectUtil; +import org.sunbird.common.PropertiesCache; +import org.sunbird.utils.StringFormatter; +import org.sunbird.request.Request; +import org.sunbird.response.ResponseCode; +import org.sunbird.response.ResponseMessage; /** - * This call will do validation for all incoming request data. + * Validates the request structure and data for various operations. * * @author Manzarul */ public final class RequestValidator { + + private static final LoggerUtil logger = new LoggerUtil(RequestValidator.class); + private static final int ERROR_CODE = ResponseCode.CLIENT_ERROR.getResponseCode(); private RequestValidator() {} /** - * This method will do content state request data validation. if all mandatory data is coming then - * it won't do any thing if any mandatory data is missing then it will throw exception. + * Validates the request structure and data for updating content. + * Checks for mandatory fields and format validity. * - * @param contentRequestDto Request + * @param contentRequestDto The request object containing content update data. + * @throws ProjectCommonException If validation fails. */ @SuppressWarnings("unchecked") public static void validateUpdateContent(Request contentRequestDto) { List> list = - (List>) (contentRequestDto.getRequest().get(JsonKey.CONTENTS)); - if(CollectionUtils.isNotEmpty(list)) { + (List>) (contentRequestDto.getRequest().get(JsonKey.CONTENTS)); + if (CollectionUtils.isNotEmpty(list)) { for (Map map : list) { if (null != map.get(JsonKey.LAST_UPDATED_TIME)) { boolean bool = - ProjectUtil.isDateValidFormat( - "yyyy-MM-dd HH:mm:ss:SSSZ", (String) map.get(JsonKey.LAST_UPDATED_TIME)); + ProjectUtil.isDateValidFormat( + "yyyy-MM-dd HH:mm:ss:SSSZ", (String) map.get(JsonKey.LAST_UPDATED_TIME)); if (!bool) { throw new ProjectCommonException( - ResponseCode.dateFormatError.getErrorCode(), - ResponseCode.dateFormatError.getErrorMessage(), - ERROR_CODE); + ResponseCode.dateFormatError.getErrorCode(), + ResponseCode.dateFormatError.getErrorMessage(), + ERROR_CODE); } } if (null != map.get(JsonKey.LAST_COMPLETED_TIME)) { boolean bool = - ProjectUtil.isDateValidFormat( - "yyyy-MM-dd HH:mm:ss:SSSZ", (String) map.get(JsonKey.LAST_COMPLETED_TIME)); + ProjectUtil.isDateValidFormat( + "yyyy-MM-dd HH:mm:ss:SSSZ", (String) map.get(JsonKey.LAST_COMPLETED_TIME)); if (!bool) { throw new ProjectCommonException( - ResponseCode.dateFormatError.getErrorCode(), - ResponseCode.dateFormatError.getErrorMessage(), - ERROR_CODE); + ResponseCode.dateFormatError.getErrorCode(), + ResponseCode.dateFormatError.getErrorMessage(), + ERROR_CODE); } } if (map.containsKey(JsonKey.CONTENT_ID)) { - if (null == map.get(JsonKey.CONTENT_ID)) { throw new ProjectCommonException( - ResponseCode.contentIdRequired.getErrorCode(), - ResponseCode.contentIdRequiredError.getErrorMessage(), - ERROR_CODE); + ResponseCode.contentIdRequired.getErrorCode(), + ResponseCode.contentIdRequiredError.getErrorMessage(), + ERROR_CODE); } if (ProjectUtil.isNull(map.get(JsonKey.STATUS))) { throw new ProjectCommonException( - ResponseCode.contentStatusRequired.getErrorCode(), - ResponseCode.contentStatusRequired.getErrorMessage(), - ERROR_CODE); + ResponseCode.contentStatusRequired.getErrorCode(), + ResponseCode.contentStatusRequired.getErrorMessage(), + ERROR_CODE); } - } else { throw new ProjectCommonException( - ResponseCode.contentIdRequired.getErrorCode(), - ResponseCode.contentIdRequiredError.getErrorMessage(), - ERROR_CODE); + ResponseCode.contentIdRequired.getErrorCode(), + ResponseCode.contentIdRequiredError.getErrorMessage(), + ERROR_CODE); } } } - List> assessmentData = - (List>) contentRequestDto.getRequest().get(JsonKey.ASSESSMENT_EVENTS); - if (!CollectionUtils.isEmpty(assessmentData)) { - for (Map map : assessmentData) { - if (!map.containsKey(JsonKey.ASSESSMENT_TS)) { - throw new ProjectCommonException( - ResponseCode.assessmentAttemptDateRequired.getErrorCode(), - ResponseCode.assessmentAttemptDateRequired.getErrorMessage(), - ERROR_CODE); - } + List> assessmentData = + (List>) + contentRequestDto.getRequest().get(JsonKey.ASSESSMENT_EVENTS); + if (!CollectionUtils.isEmpty(assessmentData)) { + for (Map map : assessmentData) { + if (!map.containsKey(JsonKey.ASSESSMENT_TS)) { + throw new ProjectCommonException( + ResponseCode.assessmentAttemptDateRequired.getErrorCode(), + ResponseCode.assessmentAttemptDateRequired.getErrorMessage(), + ERROR_CODE); + } - if (!map.containsKey(JsonKey.COURSE_ID) - || StringUtils.isBlank((String) map.get(JsonKey.COURSE_ID))) { - throw new ProjectCommonException( - ResponseCode.courseIdRequired.getErrorCode(), - ResponseCode.courseIdRequiredError.getErrorMessage(), - ERROR_CODE); - } + if (!map.containsKey(JsonKey.COURSE_ID) + || StringUtils.isBlank((String) map.get(JsonKey.COURSE_ID))) { + throw new ProjectCommonException( + ResponseCode.courseIdRequired.getErrorCode(), + ResponseCode.courseIdRequiredError.getErrorMessage(), + ERROR_CODE); + } - if (!map.containsKey(JsonKey.CONTENT_ID) - || StringUtils.isBlank((String) map.get(JsonKey.CONTENT_ID))) { - throw new ProjectCommonException( - ResponseCode.contentIdRequired.getErrorCode(), - ResponseCode.contentIdRequiredError.getErrorMessage(), - ERROR_CODE); - } + if (!map.containsKey(JsonKey.CONTENT_ID) + || StringUtils.isBlank((String) map.get(JsonKey.CONTENT_ID))) { + throw new ProjectCommonException( + ResponseCode.contentIdRequired.getErrorCode(), + ResponseCode.contentIdRequiredError.getErrorMessage(), + ERROR_CODE); + } - if (!map.containsKey(JsonKey.BATCH_ID) - || StringUtils.isBlank((String) map.get(JsonKey.BATCH_ID))) { - throw new ProjectCommonException( - ResponseCode.courseBatchIdRequired.getErrorCode(), - ResponseCode.courseBatchIdRequired.getErrorMessage(), - ERROR_CODE); - } + if (!map.containsKey(JsonKey.BATCH_ID) + || StringUtils.isBlank((String) map.get(JsonKey.BATCH_ID))) { + throw new ProjectCommonException( + ResponseCode.courseBatchIdRequired.getErrorCode(), + ResponseCode.courseBatchIdRequired.getErrorMessage(), + ERROR_CODE); + } - if (!map.containsKey(JsonKey.USER_ID) - || StringUtils.isBlank((String) map.get(JsonKey.USER_ID))) { - throw new ProjectCommonException( - ResponseCode.userIdRequired.getErrorCode(), - ResponseCode.userIdRequired.getErrorMessage(), - ERROR_CODE); - } + if (!map.containsKey(JsonKey.USER_ID) + || StringUtils.isBlank((String) map.get(JsonKey.USER_ID))) { + throw new ProjectCommonException( + ResponseCode.userIdRequired.getErrorCode(), + ResponseCode.userIdRequired.getErrorMessage(), + ERROR_CODE); + } - if (!map.containsKey(JsonKey.ATTEMPT_ID) - || StringUtils.isBlank((String) map.get(JsonKey.ATTEMPT_ID))) { - throw new ProjectCommonException( - ResponseCode.attemptIdRequired.getErrorCode(), - ResponseCode.attemptIdRequired.getErrorMessage(), - ERROR_CODE); - } + if (!map.containsKey(JsonKey.ATTEMPT_ID) + || StringUtils.isBlank((String) map.get(JsonKey.ATTEMPT_ID))) { + throw new ProjectCommonException( + ResponseCode.attemptIdRequired.getErrorCode(), + ResponseCode.attemptIdRequired.getErrorMessage(), + ERROR_CODE); + } - if (!map.containsKey(JsonKey.EVENTS)) { - throw new ProjectCommonException( - ResponseCode.eventsRequired.getErrorCode(), - ResponseCode.eventsRequired.getErrorMessage(), - ERROR_CODE); - } + if (!map.containsKey(JsonKey.EVENTS)) { + throw new ProjectCommonException( + ResponseCode.eventsRequired.getErrorCode(), + ResponseCode.eventsRequired.getErrorMessage(), + ERROR_CODE); } } + } } /** - * This method will validate get page data api. + * Validates the request data for getting page data. * - * @param request Request + * @param request The request object. + * @throws ProjectCommonException If validation fails. */ public static void validateGetPageData(Request request) { if (request == null || (StringUtils.isBlank((String) request.get(JsonKey.SOURCE)))) { @@ -178,9 +180,8 @@ public static void validateGetPageData(Request request) { } private static boolean validPageSourceType(String source) { - - Boolean isValidSource = false; - for (Source src : ProjectUtil.Source.values()) { + boolean isValidSource = false; + for (ProjectUtil.Source src : ProjectUtil.Source.values()) { if (src.getValue().equalsIgnoreCase(source)) { isValidSource = true; break; @@ -190,12 +191,12 @@ private static boolean validPageSourceType(String source) { } /** - * This method will validate add course request data. + * Validates the request data for adding a batch to a course. * - * @param courseRequest Request + * @param courseRequest The request object. + * @throws ProjectCommonException If validation fails. */ public static void validateAddBatchCourse(Request courseRequest) { - if (courseRequest.getRequest().get(JsonKey.BATCH_ID) == null) { throw new ProjectCommonException( ResponseCode.courseBatchIdRequired.getErrorCode(), @@ -211,12 +212,12 @@ public static void validateAddBatchCourse(Request courseRequest) { } /** - * This method will validate add course request data. + * Validates the request data for getting a batch. * - * @param courseRequest Request + * @param courseRequest The request object. + * @throws ProjectCommonException If validation fails. */ public static void validateGetBatchCourse(Request courseRequest) { - if (courseRequest.getRequest().get(JsonKey.BATCH_ID) == null) { throw new ProjectCommonException( ResponseCode.courseBatchIdRequired.getErrorCode(), @@ -226,12 +227,12 @@ public static void validateGetBatchCourse(Request courseRequest) { } /** - * This method will validate update course request data. + * Validates the request data for updating a course. * - * @param request Request + * @param request The request object. + * @throws ProjectCommonException If validation fails. */ public static void validateUpdateCourse(Request request) { - if (request.getRequest().get(JsonKey.COURSE_ID) == null) { throw new ProjectCommonException( ResponseCode.courseIdRequired.getErrorCode(), @@ -241,9 +242,10 @@ public static void validateUpdateCourse(Request request) { } /** - * This method will validate published course request data. + * Validates the request data for publishing a course. * - * @param request Request + * @param request The request object. + * @throws ProjectCommonException If validation fails. */ public static void validatePublishCourse(Request request) { if (request.getRequest().get(JsonKey.COURSE_ID) == null) { @@ -255,9 +257,10 @@ public static void validatePublishCourse(Request request) { } /** - * This method will validate Delete course request data. + * Validates the request data for deleting a course. * - * @param request Request + * @param request The request object. + * @throws ProjectCommonException If validation fails. */ public static void validateDeleteCourse(Request request) { if (request.getRequest().get(JsonKey.COURSE_ID) == null) { @@ -268,10 +271,11 @@ public static void validateDeleteCourse(Request request) { } } - /* - * This method will validate create section data + /** + * Validates the request data for creating a section. * - * @param userRequest Request + * @param request The request object. + * @throws ProjectCommonException If validation fails. */ public static void validateCreateSection(Request request) { if (StringUtils.isBlank( @@ -297,9 +301,10 @@ public static void validateCreateSection(Request request) { } /** - * This method will validate update section request data + * Validates the request data for updating a section. * - * @param request Request + * @param request The request object. + * @throws ProjectCommonException If validation fails. */ public static void validateUpdateSection(Request request) { if (request.getRequest().containsKey(JsonKey.SECTION_NAME) @@ -337,9 +342,10 @@ public static void validateUpdateSection(Request request) { } /** - * This method will validate create page data + * Validates the request data for creating a page. * - * @param request Request + * @param request The request object. + * @throws ProjectCommonException If validation fails. */ public static void validateCreatePage(Request request) { if (StringUtils.isEmpty( @@ -355,9 +361,10 @@ public static void validateCreatePage(Request request) { } /** - * This method will validate update page request data + * Validates the request data for updating a page. * - * @param request Request + * @param request The request object. + * @throws ProjectCommonException If validation fails. */ public static void validateUpdatepage(Request request) { if (request.getRequest().containsKey(JsonKey.PAGE_NAME) @@ -384,9 +391,10 @@ public static void validateUpdatepage(Request request) { } /** - * This method will validate bulk user upload requested data. + * Validates the request data for uploading users. * - * @param reqObj Request + * @param reqObj The request object containing user upload data. + * @throws ProjectCommonException If validation fails. */ public static void validateUploadUser(Map reqObj) { if (StringUtils.isBlank((String) reqObj.get(JsonKey.ORGANISATION_ID)) @@ -415,14 +423,19 @@ public static void validateUploadUser(Map reqObj) { } /** - * courseId : Should be a valid courseId under EKStep. name : should not be null or empty - * enrolmentType: can have only following two values {"open","invite-only"} startDate : In - * yyyy-MM-DD format , and must be >= today date. endDate : In yyyy-MM-DD format and must be > - * startDate createdFor : List of valid organisation ids. this filed will be used in case of - * "invite-only" enrolmentType. for open type if createdFor values is coming then system will just - * save that value. mentors : List of user ids , who will work as a mentor. + * Validates the request data for creating a batch. + *
    + *
  • courseId : Should be a valid courseId under EKStep.
  • + *
  • name : should not be null or empty.
  • + *
  • enrolmentType: can have only following two values {"open","invite-only"}.
  • + *
  • startDate : In yyyy-MM-DD format, and must be >= today date.
  • + *
  • endDate : In yyyy-MM-DD format and must be > startDate.
  • + *
  • createdFor : List of valid organisation ids. Used in case of "invite-only" enrolmentType.
  • + *
  • mentors : List of user ids, who will work as a mentor.
  • + *
* - * @param request + * @param request The request object. + * @throws ProjectCommonException If validation fails. */ public static void validateCreateBatchReq(Request request) { if (StringUtils.isBlank((String) request.getRequest().get(JsonKey.COURSE_ID))) { @@ -454,7 +467,7 @@ public static void validateCreateBatchReq(Request request) { } private static boolean checkProgressStatus(int status) { - for (ProgressStatus pstatus : ProgressStatus.values()) { + for (ProjectUtil.ProgressStatus pstatus : ProjectUtil.ProgressStatus.values()) { if (pstatus.getValue() == status) { return true; } @@ -462,6 +475,12 @@ private static boolean checkProgressStatus(int status) { return false; } + /** + * Validates the request data for updating a batch. + * + * @param request The request object. + * @throws ProjectCommonException If validation fails. + */ public static void validateUpdateCourseBatchReq(Request request) { if (null != request.getRequest().get(JsonKey.STATUS)) { @@ -541,7 +560,7 @@ private static boolean validateBatchStatus(Request request) { status = checkProgressStatus(Integer.parseInt("" + request.getRequest().get(JsonKey.STATUS))); } catch (Exception e) { - ProjectLogger.log(e.getMessage(), e); + logger.error("RequestValidator:validateBatchStatus: Error validating batch status", e); } return status; } @@ -601,7 +620,12 @@ private static boolean validateDateWithTodayDate(String date) { return true; } - /** @param enrolmentType */ + /** + * Validates the enrollment type. + * + * @param enrolmentType The enrollment type string. + * @throws ProjectCommonException If validation fails. + */ public static void validateEnrolmentType(String enrolmentType) { if (StringUtils.isBlank(enrolmentType)) { throw new ProjectCommonException( @@ -618,7 +642,12 @@ public static void validateEnrolmentType(String enrolmentType) { } } - /** @param startDate */ + /** + * Validates the start date. + * + * @param startDate The start date string in yyyy-MM-dd format. + * @throws ProjectCommonException If validation fails. + */ private static void validateStartDate(String startDate) { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); format.setLenient(false); @@ -675,6 +704,12 @@ private static void validateEndDate(String startDate, String endDate) { } } + /** + * Validates the request data for sync operations. + * + * @param request The request object. + * @throws ProjectCommonException If validation fails. + */ public static void validateSyncRequest(Request request) { String operation = (String) request.getRequest().get(JsonKey.OPERATION_FOR); if ((null != operation) && (!operation.equalsIgnoreCase("keycloak"))) { @@ -699,6 +734,12 @@ public static void validateSyncRequest(Request request) { } } + /** + * Validates the request data for updating system settings. + * + * @param request The request object. + * @throws ProjectCommonException If validation fails. + */ public static void validateUpdateSystemSettingsRequest(Request request) { List list = new ArrayList<>( @@ -716,6 +757,13 @@ public static void validateUpdateSystemSettingsRequest(Request request) { } } + /** + * Validates the request data for sending an email. + * + * @param request The request object. + * @throws ProjectCommonException If validation fails. + */ + @SuppressWarnings("unchecked") public static void validateSendMail(Request request) { if (StringUtils.isBlank((String) request.getRequest().get(JsonKey.SUBJECT))) { throw new ProjectCommonException( @@ -750,6 +798,12 @@ public static void validateSendMail(Request request) { } } + /** + * Validates the request data for file upload. + * + * @param reqObj The request object. + * @throws ProjectCommonException If validation fails. + */ public static void validateFileUpload(Request reqObj) { if (StringUtils.isBlank((String) reqObj.get(JsonKey.CONTAINER))) { @@ -760,14 +814,24 @@ public static void validateFileUpload(Request reqObj) { } } - /** @param reqObj */ + /** + * Validates the request data for creating an organisation type. + * + * @param reqObj The request object. + * @throws ProjectCommonException If validation fails. + */ public static void validateCreateOrgType(Request reqObj) { if (StringUtils.isBlank((String) reqObj.getRequest().get(JsonKey.NAME))) { throw createExceptionInstance(ResponseCode.orgTypeMandatory.getErrorCode()); } } - /** @param reqObj */ + /** + * Validates the request data for updating an organisation type. + * + * @param reqObj The request object. + * @throws ProjectCommonException If validation fails. + */ public static void validateUpdateOrgType(Request reqObj) { if (StringUtils.isBlank((String) reqObj.getRequest().get(JsonKey.NAME))) { throw createExceptionInstance(ResponseCode.orgTypeMandatory.getErrorCode()); @@ -778,9 +842,10 @@ public static void validateUpdateOrgType(Request reqObj) { } /** - * Method to validate not for userId, title, note, courseId, contentId and tags + * Validates the request data for a note. * - * @param request + * @param request The request object. + * @throws ProjectCommonException If validation fails. */ @SuppressWarnings("rawtypes") public static void validateNote(Request request) { @@ -825,9 +890,10 @@ public static void validateNote(Request request) { } /** - * Method to validate noteId + * Validates the note ID. * - * @param noteId + * @param noteId The note ID string. + * @throws ProjectCommonException If validation fails. */ public static void validateNoteId(String noteId) { if (StringUtils.isBlank(noteId)) { @@ -836,9 +902,10 @@ public static void validateNoteId(String noteId) { } /** - * Method to validate + * Validates the request data for registering a client. * - * @param request + * @param request The request object. + * @throws ProjectCommonException If validation fails. */ public static void validateRegisterClient(Request request) { @@ -848,10 +915,11 @@ public static void validateRegisterClient(Request request) { } /** - * Method to validate the request for updating the client key + * Validates the request data for updating the client key. * - * @param clientId - * @param masterAccessToken + * @param clientId The client ID. + * @param masterAccessToken The master access token. + * @throws ProjectCommonException If validation fails. */ public static void validateUpdateClientKey(String clientId, String masterAccessToken) { validateClientId(clientId); @@ -861,10 +929,11 @@ public static void validateUpdateClientKey(String clientId, String masterAccessT } /** - * Method to validate the request for updating the client key + * Validates the request data for getting the client key. * - * @param id - * @param type + * @param id The client ID. + * @param type The client type. + * @throws ProjectCommonException If validation fails. */ public static void validateGetClientKey(String id, String type) { validateClientId(id); @@ -874,9 +943,10 @@ public static void validateGetClientKey(String id, String type) { } /** - * Method to validate clientId. + * Validates the client ID. * - * @param clientId + * @param clientId The client ID string. + * @throws ProjectCommonException If validation fails. */ public static void validateClientId(String clientId) { if (StringUtils.isBlank(clientId)) { @@ -885,9 +955,10 @@ public static void validateClientId(String clientId) { } /** - * Method to validate notification request data. + * Validates the request data for sending notifications. * - * @param request Request + * @param request The request object. + * @throws ProjectCommonException If validation fails. */ @SuppressWarnings("unchecked") public static void validateSendNotification(Request request) { @@ -908,6 +979,12 @@ public static void validateSendNotification(Request request) { } } + /** + * Validates the request data for getting user count. + * + * @param request The request object. + * @throws ProjectCommonException If validation fails. + */ @SuppressWarnings("rawtypes") public static void validateGetUserCount(Request request) { if (!validateListType(request, JsonKey.LOCATION_IDS)) { @@ -941,12 +1018,11 @@ public static void validateGetUserCount(Request request) { } /** - * if the request contains that key and key is not instance of List then it will return false. - * other cases it will return true. + * Validates if the request contains the key and the value is a list. * - * @param request Request - * @param key String - * @return boolean + * @param request The request object. + * @param key The key to check. + * @return True if valid, false otherwise. */ private static boolean validateListType(Request request, String key) { return !(request.getRequest().containsKey(key) @@ -955,12 +1031,11 @@ private static boolean validateListType(Request request, String key) { } /** - * If the request contains the key and key value is not Boolean type then it will return false , - * for any other case it will return true. + * Validates if the request contains the key and the value is a boolean. * - * @param request Request - * @param key String - * @return boolean + * @param request The request object. + * @param key The key to check. + * @return True if valid, false otherwise. */ private static boolean validateBooleanType(Request request, String key) { return !(request.getRequest().containsKey(key) @@ -984,32 +1059,38 @@ private static ProjectCommonException createExceptionInstance(String errorCode) ERROR_CODE); } + /** + * Validates the request data for group activity aggregates. + * + * @param request The request object. + * @throws ProjectCommonException If validation fails. + */ public static void validateGroupActivityAggregatesRequest(Request request) { try { String message = ""; - if(null == request || MapUtils.isEmpty(request.getRequest())){ + if (null == request || MapUtils.isEmpty(request.getRequest())) { message += "Error due to missing request body"; ProjectCommonException.throwClientErrorException( - ResponseCode.invalidRequestData, - MessageFormat.format(ResponseCode.invalidRequestData.getErrorMessage(), message)); + ResponseCode.invalidRequestData, + MessageFormat.format(ResponseCode.invalidRequestData.getErrorMessage(), message)); } - if (StringUtils.isBlank((String)request.get(JsonKey.GROUPID))) { + if (StringUtils.isBlank((String) request.get(JsonKey.GROUPID))) { message += "Error due to missing groupId"; ProjectCommonException.throwClientErrorException( - ResponseCode.groupIdMismatch, - MessageFormat.format(ResponseCode.groupIdMismatch.getErrorMessage(), message)); + ResponseCode.groupIdMismatch, + MessageFormat.format(ResponseCode.groupIdMismatch.getErrorMessage(), message)); } - if (StringUtils.isBlank((String)request.get(JsonKey.ACTIVITYID))) { + if (StringUtils.isBlank((String) request.get(JsonKey.ACTIVITYID))) { message += "Error due to missing activityId"; ProjectCommonException.throwClientErrorException( - ResponseCode.activityIdMismatch, - MessageFormat.format(ResponseCode.activityIdMismatch.getErrorMessage(), message)); + ResponseCode.activityIdMismatch, + MessageFormat.format(ResponseCode.activityIdMismatch.getErrorMessage(), message)); } - if (StringUtils.isBlank((String)request.get(JsonKey.ACTIVITYTYPE))) { + if (StringUtils.isBlank((String) request.get(JsonKey.ACTIVITYTYPE))) { message += "Error due to missing activity type"; ProjectCommonException.throwClientErrorException( - ResponseCode.activityTypeMismatch, - MessageFormat.format(ResponseCode.activityTypeMismatch.getErrorMessage(), message)); + ResponseCode.activityTypeMismatch, + MessageFormat.format(ResponseCode.activityTypeMismatch.getErrorMessage(), message)); } } catch (Exception ex) { throw ex; diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/resources/OTPSMSTemplate.vm b/core/sunbird-platform-common/src/main/resources/OTPSMSTemplate.vm similarity index 100% rename from course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/resources/OTPSMSTemplate.vm rename to core/sunbird-platform-common/src/main/resources/OTPSMSTemplate.vm diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/resources/acceptFlagMailTemplate.vm b/core/sunbird-platform-common/src/main/resources/acceptFlagMailTemplate.vm similarity index 100% rename from course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/resources/acceptFlagMailTemplate.vm rename to core/sunbird-platform-common/src/main/resources/acceptFlagMailTemplate.vm diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/resources/application.conf b/core/sunbird-platform-common/src/main/resources/application.conf similarity index 100% rename from course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/resources/application.conf rename to core/sunbird-platform-common/src/main/resources/application.conf diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/resources/cassandra.config.properties b/core/sunbird-platform-common/src/main/resources/cassandra.config.properties similarity index 100% rename from course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/resources/cassandra.config.properties rename to core/sunbird-platform-common/src/main/resources/cassandra.config.properties diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/resources/cassandratablecolumn.properties b/core/sunbird-platform-common/src/main/resources/cassandratablecolumn.properties similarity index 100% rename from course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/resources/cassandratablecolumn.properties rename to core/sunbird-platform-common/src/main/resources/cassandratablecolumn.properties diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/resources/contentFlaggedMailTemplate.vm b/core/sunbird-platform-common/src/main/resources/contentFlaggedMailTemplate.vm similarity index 100% rename from course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/resources/contentFlaggedMailTemplate.vm rename to core/sunbird-platform-common/src/main/resources/contentFlaggedMailTemplate.vm diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/resources/contentReviewMailTemplate.vm b/core/sunbird-platform-common/src/main/resources/contentReviewMailTemplate.vm similarity index 100% rename from course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/resources/contentReviewMailTemplate.vm rename to core/sunbird-platform-common/src/main/resources/contentReviewMailTemplate.vm diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/resources/dbconfig.properties b/core/sunbird-platform-common/src/main/resources/dbconfig.properties similarity index 100% rename from course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/resources/dbconfig.properties rename to core/sunbird-platform-common/src/main/resources/dbconfig.properties diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/resources/elasticsearch.config.properties b/core/sunbird-platform-common/src/main/resources/elasticsearch.config.properties similarity index 100% rename from course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/resources/elasticsearch.config.properties rename to core/sunbird-platform-common/src/main/resources/elasticsearch.config.properties diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/resources/emailtemplate.vm b/core/sunbird-platform-common/src/main/resources/emailtemplate.vm similarity index 100% rename from course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/resources/emailtemplate.vm rename to core/sunbird-platform-common/src/main/resources/emailtemplate.vm diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/resources/externalresource.properties b/core/sunbird-platform-common/src/main/resources/externalresource.properties similarity index 100% rename from course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/resources/externalresource.properties rename to core/sunbird-platform-common/src/main/resources/externalresource.properties diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/resources/forgotPasswordWithOTP.vm b/core/sunbird-platform-common/src/main/resources/forgotPasswordWithOTP.vm similarity index 100% rename from course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/resources/forgotPasswordWithOTP.vm rename to core/sunbird-platform-common/src/main/resources/forgotPasswordWithOTP.vm diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/resources/forgotpassword.vm b/core/sunbird-platform-common/src/main/resources/forgotpassword.vm similarity index 100% rename from course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/resources/forgotpassword.vm rename to core/sunbird-platform-common/src/main/resources/forgotpassword.vm diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/resources/mailTemplates.properties b/core/sunbird-platform-common/src/main/resources/mailTemplates.properties similarity index 100% rename from course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/resources/mailTemplates.properties rename to core/sunbird-platform-common/src/main/resources/mailTemplates.properties diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/resources/profilecompleteness.properties b/core/sunbird-platform-common/src/main/resources/profilecompleteness.properties similarity index 100% rename from course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/resources/profilecompleteness.properties rename to core/sunbird-platform-common/src/main/resources/profilecompleteness.properties diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/resources/publishContentMailTemplate.vm b/core/sunbird-platform-common/src/main/resources/publishContentMailTemplate.vm similarity index 100% rename from course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/resources/publishContentMailTemplate.vm rename to core/sunbird-platform-common/src/main/resources/publishContentMailTemplate.vm diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/resources/rejectContentMailTemplate.vm b/core/sunbird-platform-common/src/main/resources/rejectContentMailTemplate.vm similarity index 100% rename from course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/resources/rejectContentMailTemplate.vm rename to core/sunbird-platform-common/src/main/resources/rejectContentMailTemplate.vm diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/resources/rejectFlagMailTemplate.vm b/core/sunbird-platform-common/src/main/resources/rejectFlagMailTemplate.vm similarity index 100% rename from course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/resources/rejectFlagMailTemplate.vm rename to core/sunbird-platform-common/src/main/resources/rejectFlagMailTemplate.vm diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/resources/sso.properties b/core/sunbird-platform-common/src/main/resources/sso.properties similarity index 100% rename from course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/resources/sso.properties rename to core/sunbird-platform-common/src/main/resources/sso.properties diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/resources/unlistedPublishContentMailTemplate.vm b/core/sunbird-platform-common/src/main/resources/unlistedPublishContentMailTemplate.vm similarity index 100% rename from course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/resources/unlistedPublishContentMailTemplate.vm rename to core/sunbird-platform-common/src/main/resources/unlistedPublishContentMailTemplate.vm diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/resources/userencryption.properties b/core/sunbird-platform-common/src/main/resources/userencryption.properties similarity index 100% rename from course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/resources/userencryption.properties rename to core/sunbird-platform-common/src/main/resources/userencryption.properties diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/resources/welcomeMailTemplate.vm b/core/sunbird-platform-common/src/main/resources/welcomeMailTemplate.vm similarity index 100% rename from course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/resources/welcomeMailTemplate.vm rename to core/sunbird-platform-common/src/main/resources/welcomeMailTemplate.vm diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/resources/welcomeSmsTemplate.vm b/core/sunbird-platform-common/src/main/resources/welcomeSmsTemplate.vm similarity index 100% rename from course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/resources/welcomeSmsTemplate.vm rename to core/sunbird-platform-common/src/main/resources/welcomeSmsTemplate.vm diff --git a/course-mw/course-actors-common/pom.xml b/course-mw/course-actors-common/pom.xml index 79b88f388..479a99d1d 100644 --- a/course-mw/course-actors-common/pom.xml +++ b/course-mw/course-actors-common/pom.xml @@ -84,6 +84,11 @@ sunbird-notification 1.0-SNAPSHOT + + org.sunbird + sunbird-platform-common + 1.0-SNAPSHOT + org.reflections reflections diff --git a/course-mw/course-actors-common/src/main/java/org/sunbird/actor/base/BaseActor.java b/course-mw/course-actors-common/src/main/java/org/sunbird/actor/base/BaseActor.java index 7d738ce7a..d6c428405 100644 --- a/course-mw/course-actors-common/src/main/java/org/sunbird/actor/base/BaseActor.java +++ b/course-mw/course-actors-common/src/main/java/org/sunbird/actor/base/BaseActor.java @@ -1,12 +1,12 @@ package org.sunbird.actor.base; import org.apache.pekko.actor.UntypedAbstractActor; -import org.sunbird.common.exception.ProjectCommonException; -import org.sunbird.common.models.response.Response; -import org.sunbird.common.models.response.ResponseParams; -import org.sunbird.common.models.util.LoggerUtil; -import org.sunbird.common.request.Request; -import org.sunbird.common.responsecode.ResponseCode; +import org.sunbird.exception.ProjectCommonException; +import org.sunbird.response.Response; +import org.sunbird.response.ResponseParams; +import org.sunbird.logging.LoggerUtil; +import org.sunbird.request.Request; +import org.sunbird.response.ResponseCode; public abstract class BaseActor extends UntypedAbstractActor { diff --git a/course-mw/course-actors-common/src/main/java/org/sunbird/actor/exhaustjob/ExhaustJobActor.java b/course-mw/course-actors-common/src/main/java/org/sunbird/actor/exhaustjob/ExhaustJobActor.java index b26f6b14d..e9a4e5d4d 100644 --- a/course-mw/course-actors-common/src/main/java/org/sunbird/actor/exhaustjob/ExhaustJobActor.java +++ b/course-mw/course-actors-common/src/main/java/org/sunbird/actor/exhaustjob/ExhaustJobActor.java @@ -2,13 +2,13 @@ import com.fasterxml.jackson.databind.ObjectMapper; import org.sunbird.actor.base.BaseActor; -import org.sunbird.common.exception.ProjectCommonException; -import org.sunbird.common.models.response.Response; -import org.sunbird.common.models.util.ActorOperations; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.models.util.datasecurity.EncryptionService; -import org.sunbird.common.request.Request; -import org.sunbird.common.responsecode.ResponseCode; +import org.sunbird.exception.ProjectCommonException; +import org.sunbird.response.Response; +import org.sunbird.operations.lms.ActorOperations; +import org.sunbird.keys.JsonKey; +import org.sunbird.datasecurity.EncryptionService; +import org.sunbird.request.Request; +import org.sunbird.response.ResponseCode; import org.sunbird.util.ExhaustAPIUtil; import java.util.HashMap; @@ -17,7 +17,7 @@ public class ExhaustJobActor extends BaseActor { private ObjectMapper mapper = new ObjectMapper(); private EncryptionService encryptionService = - org.sunbird.common.models.util.datasecurity.impl.ServiceFactory.getEncryptionServiceInstance( + org.sunbird.datasecurity.impl.ServiceFactory.getEncryptionServiceInstance( null); @Override public void onReceive(Request request) throws Throwable { diff --git a/course-mw/course-actors-common/src/main/java/org/sunbird/common/cacheloader/PageCacheLoaderService.java b/course-mw/course-actors-common/src/main/java/org/sunbird/common/cacheloader/PageCacheLoaderService.java index 12543159e..7acfeb24a 100644 --- a/course-mw/course-actors-common/src/main/java/org/sunbird/common/cacheloader/PageCacheLoaderService.java +++ b/course-mw/course-actors-common/src/main/java/org/sunbird/common/cacheloader/PageCacheLoaderService.java @@ -4,11 +4,11 @@ import org.sunbird.cache.CacheFactory; import org.sunbird.cache.interfaces.Cache; import org.sunbird.cassandra.CassandraOperation; -import org.sunbird.common.models.response.Response; -import org.sunbird.common.models.util.ActorOperations; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.models.util.LoggerUtil; -import org.sunbird.common.models.util.ProjectUtil; +import org.sunbird.response.Response; +import org.sunbird.operations.lms.ActorOperations; +import org.sunbird.keys.JsonKey; +import org.sunbird.logging.LoggerUtil; +import org.sunbird.common.ProjectUtil; import org.sunbird.helper.ServiceFactory; import org.sunbird.learner.util.DataCacheHandler; diff --git a/course-mw/course-actors-common/src/main/java/org/sunbird/learner/actors/BackgroundJobManager.java b/course-mw/course-actors-common/src/main/java/org/sunbird/learner/actors/BackgroundJobManager.java index f495b38a6..4a49cff41 100644 --- a/course-mw/course-actors-common/src/main/java/org/sunbird/learner/actors/BackgroundJobManager.java +++ b/course-mw/course-actors-common/src/main/java/org/sunbird/learner/actors/BackgroundJobManager.java @@ -4,16 +4,16 @@ import org.apache.commons.lang3.StringUtils; import org.sunbird.actor.base.BaseActor; import org.sunbird.common.ElasticSearchHelper; -import org.sunbird.common.exception.ProjectCommonException; +import org.sunbird.exception.ProjectCommonException; import org.sunbird.common.factory.EsClientFactory; import org.sunbird.common.inf.ElasticSearchService; -import org.sunbird.common.models.util.ActorOperations; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.models.util.LoggerUtil; -import org.sunbird.common.models.util.ProjectUtil; -import org.sunbird.common.request.Request; -import org.sunbird.common.request.RequestContext; -import org.sunbird.common.responsecode.ResponseCode; +import org.sunbird.operations.lms.ActorOperations; +import org.sunbird.keys.JsonKey; +import org.sunbird.logging.LoggerUtil; +import org.sunbird.common.ProjectUtil; +import org.sunbird.request.Request; +import org.sunbird.request.RequestContext; +import org.sunbird.response.ResponseCode; import org.sunbird.learner.actors.coursebatch.service.UserCoursesService; import org.sunbird.learner.util.CourseBatchSchedulerUtil; import org.sunbird.learner.util.Util; diff --git a/course-mw/course-actors-common/src/main/java/org/sunbird/learner/actors/PageManagementActor.java b/course-mw/course-actors-common/src/main/java/org/sunbird/learner/actors/PageManagementActor.java index 76ef3fe6c..ec343a45a 100644 --- a/course-mw/course-actors-common/src/main/java/org/sunbird/learner/actors/PageManagementActor.java +++ b/course-mw/course-actors-common/src/main/java/org/sunbird/learner/actors/PageManagementActor.java @@ -14,15 +14,19 @@ import org.sunbird.common.CassandraUtil; import org.sunbird.common.ElasticSearchHelper; import org.sunbird.common.cacheloader.PageCacheLoaderService; -import org.sunbird.common.exception.ProjectCommonException; +import org.sunbird.exception.ProjectCommonException; import org.sunbird.common.factory.EsClientFactory; import org.sunbird.common.inf.ElasticSearchService; -import org.sunbird.common.models.response.Response; -import org.sunbird.common.models.util.*; -import org.sunbird.common.request.Request; -import org.sunbird.common.request.RequestContext; -import org.sunbird.common.responsecode.ResponseCode; -import org.sunbird.common.util.JsonUtil; +import org.sunbird.response.Response; +import org.sunbird.telemetry.dto.*; +import org.sunbird.request.Request; +import org.sunbird.request.RequestContext; +import org.sunbird.response.ResponseCode; +import org.sunbird.utils.JsonUtil; +import org.sunbird.logging.LoggerUtil; +import org.sunbird.keys.JsonKey; +import org.sunbird.operations.lms.ActorOperations; +import org.sunbird.common.*; import org.sunbird.dto.SearchDTO; import org.sunbird.helper.ServiceFactory; import org.sunbird.learner.util.ContentSearchUtil; @@ -41,7 +45,7 @@ import java.util.Map.Entry; import java.util.stream.Collectors; -import static org.sunbird.common.models.util.JsonKey.ID; +import static org.sunbird.keys.JsonKey.ID; /** * This actor will handle page management operation . diff --git a/course-mw/course-actors-common/src/main/java/org/sunbird/learner/actors/bulkupload/dao/BulkUploadProcessDao.java b/course-mw/course-actors-common/src/main/java/org/sunbird/learner/actors/bulkupload/dao/BulkUploadProcessDao.java index 69f4335d4..3896a4b2d 100644 --- a/course-mw/course-actors-common/src/main/java/org/sunbird/learner/actors/bulkupload/dao/BulkUploadProcessDao.java +++ b/course-mw/course-actors-common/src/main/java/org/sunbird/learner/actors/bulkupload/dao/BulkUploadProcessDao.java @@ -1,7 +1,7 @@ package org.sunbird.learner.actors.bulkupload.dao; -import org.sunbird.common.models.response.Response; -import org.sunbird.common.request.RequestContext; +import org.sunbird.response.Response; +import org.sunbird.request.RequestContext; import org.sunbird.learner.actors.bulkupload.model.BulkUploadProcess; /** Created by arvind on 24/4/18. */ diff --git a/course-mw/course-actors-common/src/main/java/org/sunbird/learner/actors/bulkupload/dao/impl/BulkUploadProcessDaoImpl.java b/course-mw/course-actors-common/src/main/java/org/sunbird/learner/actors/bulkupload/dao/impl/BulkUploadProcessDaoImpl.java index 0d5921d56..1b541c19e 100644 --- a/course-mw/course-actors-common/src/main/java/org/sunbird/learner/actors/bulkupload/dao/impl/BulkUploadProcessDaoImpl.java +++ b/course-mw/course-actors-common/src/main/java/org/sunbird/learner/actors/bulkupload/dao/impl/BulkUploadProcessDaoImpl.java @@ -3,12 +3,12 @@ import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.commons.collections.CollectionUtils; import org.sunbird.cassandra.CassandraOperation; -import org.sunbird.common.models.response.Response; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.models.util.LoggerUtil; -import org.sunbird.common.models.util.ProjectUtil; -import org.sunbird.common.models.util.TableNameUtil; -import org.sunbird.common.request.RequestContext; +import org.sunbird.response.Response; +import org.sunbird.keys.JsonKey; +import org.sunbird.logging.LoggerUtil; +import org.sunbird.common.ProjectUtil; +import org.sunbird.utils.TableNameUtil; +import org.sunbird.request.RequestContext; import org.sunbird.helper.ServiceFactory; import org.sunbird.learner.actors.bulkupload.dao.BulkUploadProcessDao; import org.sunbird.learner.actors.bulkupload.model.BulkUploadProcess; diff --git a/course-mw/course-actors-common/src/main/java/org/sunbird/learner/actors/bulkupload/model/BulkUploadProcess.java b/course-mw/course-actors-common/src/main/java/org/sunbird/learner/actors/bulkupload/model/BulkUploadProcess.java index 4bb1860d0..99212fa76 100644 --- a/course-mw/course-actors-common/src/main/java/org/sunbird/learner/actors/bulkupload/model/BulkUploadProcess.java +++ b/course-mw/course-actors-common/src/main/java/org/sunbird/learner/actors/bulkupload/model/BulkUploadProcess.java @@ -10,10 +10,10 @@ import java.io.IOException; import java.io.Serializable; import java.sql.Timestamp; -import org.sunbird.common.exception.ProjectCommonException; -import org.sunbird.common.models.util.datasecurity.DecryptionService; -import org.sunbird.common.models.util.datasecurity.EncryptionService; -import org.sunbird.common.responsecode.ResponseCode; +import org.sunbird.exception.ProjectCommonException; +import org.sunbird.datasecurity.DecryptionService; +import org.sunbird.datasecurity.EncryptionService; +import org.sunbird.response.ResponseCode; /** @author arvind. */ @JsonIgnoreProperties(ignoreUnknown = true) @@ -22,10 +22,10 @@ public class BulkUploadProcess implements Serializable { private static final long serialVersionUID = 1L; private EncryptionService encryptionService = - org.sunbird.common.models.util.datasecurity.impl.ServiceFactory.getEncryptionServiceInstance( + org.sunbird.datasecurity.impl.ServiceFactory.getEncryptionServiceInstance( null); private DecryptionService decryptionService = - org.sunbird.common.models.util.datasecurity.impl.ServiceFactory.getDecryptionServiceInstance( + org.sunbird.datasecurity.impl.ServiceFactory.getDecryptionServiceInstance( null); private String id; diff --git a/course-mw/course-actors-common/src/main/java/org/sunbird/learner/actors/cache/CacheManagementActor.java b/course-mw/course-actors-common/src/main/java/org/sunbird/learner/actors/cache/CacheManagementActor.java index 737340796..ce569355c 100644 --- a/course-mw/course-actors-common/src/main/java/org/sunbird/learner/actors/cache/CacheManagementActor.java +++ b/course-mw/course-actors-common/src/main/java/org/sunbird/learner/actors/cache/CacheManagementActor.java @@ -3,14 +3,14 @@ import org.sunbird.actor.base.BaseActor; import org.sunbird.cache.CacheFactory; import org.sunbird.cache.interfaces.Cache; -import org.sunbird.common.models.response.Response; -import org.sunbird.common.models.util.ActorOperations; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.models.util.LoggerEnum; -import org.sunbird.common.models.util.LoggerUtil; -import org.sunbird.common.models.util.ProjectLogger; -import org.sunbird.common.request.Request; -import org.sunbird.common.responsecode.ResponseCode; +import org.sunbird.response.Response; +import org.sunbird.operations.lms.ActorOperations; +import org.sunbird.keys.JsonKey; +import org.sunbird.logging.LoggerEnum; +import org.sunbird.logging.LoggerUtil; +import org.sunbird.logging.ProjectLogger; +import org.sunbird.request.Request; +import org.sunbird.response.ResponseCode; public class CacheManagementActor extends BaseActor { private Cache cache = CacheFactory.getInstance(); diff --git a/course-mw/course-actors-common/src/main/java/org/sunbird/learner/actors/certificate/service/CertificateActor.java b/course-mw/course-actors-common/src/main/java/org/sunbird/learner/actors/certificate/service/CertificateActor.java index d109cb229..a5e96d1be 100644 --- a/course-mw/course-actors-common/src/main/java/org/sunbird/learner/actors/certificate/service/CertificateActor.java +++ b/course-mw/course-actors-common/src/main/java/org/sunbird/learner/actors/certificate/service/CertificateActor.java @@ -7,16 +7,16 @@ import java.util.Map; import org.apache.commons.collections.CollectionUtils; import org.sunbird.actor.base.BaseActor; -import org.sunbird.common.exception.ProjectCommonException; -import org.sunbird.common.models.response.Response; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.models.util.LoggerUtil; -import org.sunbird.common.models.util.ProjectUtil; -import org.sunbird.common.models.util.TelemetryEnvKey; -import org.sunbird.common.models.util.datasecurity.OneWayHashing; -import org.sunbird.common.request.Request; -import org.sunbird.common.responsecode.ResponseCode; -import org.sunbird.kafka.client.InstructionEventGenerator; +import org.sunbird.exception.ProjectCommonException; +import org.sunbird.response.Response; +import org.sunbird.keys.JsonKey; +import org.sunbird.logging.LoggerUtil; +import org.sunbird.common.ProjectUtil; +import org.sunbird.telemetry.dto.TelemetryEnvKey; +import org.sunbird.datasecurity.OneWayHashing; +import org.sunbird.request.Request; +import org.sunbird.response.ResponseCode; +import org.sunbird.kafka.InstructionEventGenerator; import org.sunbird.learner.constants.CourseJsonKey; import org.sunbird.learner.constants.InstructionEvent; import org.sunbird.learner.util.CourseBatchUtil; diff --git a/course-mw/course-actors-common/src/main/java/org/sunbird/learner/actors/certificate/service/CourseBatchCertificateActor.java b/course-mw/course-actors-common/src/main/java/org/sunbird/learner/actors/certificate/service/CourseBatchCertificateActor.java index 327d5a91f..906e51c67 100644 --- a/course-mw/course-actors-common/src/main/java/org/sunbird/learner/actors/certificate/service/CourseBatchCertificateActor.java +++ b/course-mw/course-actors-common/src/main/java/org/sunbird/learner/actors/certificate/service/CourseBatchCertificateActor.java @@ -11,22 +11,22 @@ import org.apache.commons.collections.MapUtils; import org.apache.commons.lang3.StringUtils; import org.sunbird.actor.base.BaseActor; -import org.sunbird.common.exception.ProjectCommonException; -import org.sunbird.common.models.response.Response; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.models.util.TelemetryEnvKey; -import org.sunbird.common.request.Request; -import org.sunbird.common.request.RequestContext; -import org.sunbird.common.responsecode.ResponseCode; -import org.sunbird.common.util.CloudStorageUtil; +import org.sunbird.exception.ProjectCommonException; +import org.sunbird.response.Response; +import org.sunbird.keys.JsonKey; +import org.sunbird.telemetry.dto.TelemetryEnvKey; +import org.sunbird.request.Request; +import org.sunbird.request.RequestContext; +import org.sunbird.response.ResponseCode; +import org.sunbird.utils.CloudStorageUtil; import org.sunbird.learner.actors.coursebatch.dao.CourseBatchDao; import org.sunbird.learner.actors.coursebatch.dao.impl.CourseBatchDaoImpl; import org.sunbird.learner.constants.CourseJsonKey; import org.sunbird.learner.util.CourseBatchUtil; import org.sunbird.learner.util.Util; -import static org.sunbird.common.models.util.JsonKey.*; -import static org.sunbird.common.models.util.ProjectUtil.getConfigValue; +import static org.sunbird.keys.JsonKey.*; +import static org.sunbird.common.ProjectUtil.getConfigValue; public class CourseBatchCertificateActor extends BaseActor { diff --git a/course-mw/course-actors-common/src/main/java/org/sunbird/learner/actors/course/CourseManagementActor.java b/course-mw/course-actors-common/src/main/java/org/sunbird/learner/actors/course/CourseManagementActor.java index 1726d1a71..1d181dfbc 100644 --- a/course-mw/course-actors-common/src/main/java/org/sunbird/learner/actors/course/CourseManagementActor.java +++ b/course-mw/course-actors-common/src/main/java/org/sunbird/learner/actors/course/CourseManagementActor.java @@ -6,11 +6,11 @@ import org.apache.commons.collections.MapUtils; import org.apache.commons.lang3.StringUtils; import org.sunbird.actor.base.BaseActor; -import org.sunbird.common.exception.ProjectCommonException; -import org.sunbird.common.models.response.Response; -import org.sunbird.common.models.util.TelemetryEnvKey; -import org.sunbird.common.request.Request; -import org.sunbird.common.responsecode.ResponseCode; +import org.sunbird.exception.ProjectCommonException; +import org.sunbird.response.Response; +import org.sunbird.telemetry.dto.TelemetryEnvKey; +import org.sunbird.request.Request; +import org.sunbird.response.ResponseCode; import org.sunbird.keys.SunbirdKey; import org.sunbird.learner.util.Util; @@ -21,8 +21,8 @@ import java.util.Optional; import java.util.stream.Collectors; -import static org.sunbird.common.models.util.JsonKey.CONTENT_SERVICE_BASE_URL; -import static org.sunbird.common.models.util.ProjectUtil.getConfigValue; +import static org.sunbird.keys.JsonKey.CONTENT_SERVICE_BASE_URL; +import static org.sunbird.common.ProjectUtil.getConfigValue; public class CourseManagementActor extends BaseActor { private static ObjectMapper mapper = new ObjectMapper(); diff --git a/course-mw/course-actors-common/src/main/java/org/sunbird/learner/actors/course/HierarchyGenerationHelper.java b/course-mw/course-actors-common/src/main/java/org/sunbird/learner/actors/course/HierarchyGenerationHelper.java index d0303246a..706ad7a13 100644 --- a/course-mw/course-actors-common/src/main/java/org/sunbird/learner/actors/course/HierarchyGenerationHelper.java +++ b/course-mw/course-actors-common/src/main/java/org/sunbird/learner/actors/course/HierarchyGenerationHelper.java @@ -3,11 +3,11 @@ import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang3.StringUtils; -import org.sunbird.common.exception.ProjectCommonException; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.models.util.LoggerUtil; -import org.sunbird.common.request.Request; -import org.sunbird.common.responsecode.ResponseCode; +import org.sunbird.exception.ProjectCommonException; +import org.sunbird.keys.JsonKey; +import org.sunbird.logging.LoggerUtil; +import org.sunbird.request.Request; +import org.sunbird.response.ResponseCode; import org.sunbird.keys.SunbirdKey; import java.util.ArrayList; @@ -18,8 +18,8 @@ import java.util.UUID; import java.util.stream.Collectors; -import static org.sunbird.common.models.util.ProjectUtil.getConfigValue; -import static org.sunbird.common.responsecode.ResponseCode.CLIENT_ERROR; +import static org.sunbird.common.ProjectUtil.getConfigValue; +import static org.sunbird.response.ResponseCode.CLIENT_ERROR; public class HierarchyGenerationHelper { private static List metadataToBeAdded = Arrays.stream((StringUtils.isNotBlank(getConfigValue(JsonKey.CONTENT_PROPS_TO_ADD)) ? getConfigValue(JsonKey.CONTENT_PROPS_TO_ADD) : "mimeType,contentType,name,code,description,keywords,framework,copyright,topic").split(",")).map(String::trim).collect(Collectors.toList()); diff --git a/course-mw/course-actors-common/src/main/java/org/sunbird/learner/actors/coursebatch/dao/CourseBatchDao.java b/course-mw/course-actors-common/src/main/java/org/sunbird/learner/actors/coursebatch/dao/CourseBatchDao.java index 569000c11..0f09557b8 100644 --- a/course-mw/course-actors-common/src/main/java/org/sunbird/learner/actors/coursebatch/dao/CourseBatchDao.java +++ b/course-mw/course-actors-common/src/main/java/org/sunbird/learner/actors/coursebatch/dao/CourseBatchDao.java @@ -1,8 +1,8 @@ package org.sunbird.learner.actors.coursebatch.dao; import java.util.Map; -import org.sunbird.common.models.response.Response; -import org.sunbird.common.request.RequestContext; +import org.sunbird.response.Response; +import org.sunbird.request.RequestContext; import org.sunbird.models.course.batch.CourseBatch; public interface CourseBatchDao { diff --git a/course-mw/course-actors-common/src/main/java/org/sunbird/learner/actors/coursebatch/dao/UserCoursesDao.java b/course-mw/course-actors-common/src/main/java/org/sunbird/learner/actors/coursebatch/dao/UserCoursesDao.java index fc385e922..21d398f4c 100644 --- a/course-mw/course-actors-common/src/main/java/org/sunbird/learner/actors/coursebatch/dao/UserCoursesDao.java +++ b/course-mw/course-actors-common/src/main/java/org/sunbird/learner/actors/coursebatch/dao/UserCoursesDao.java @@ -2,8 +2,8 @@ import java.util.List; import java.util.Map; -import org.sunbird.common.models.response.Response; -import org.sunbird.common.request.RequestContext; +import org.sunbird.response.Response; +import org.sunbird.request.RequestContext; import org.sunbird.models.user.courses.UserCourses; public interface UserCoursesDao { diff --git a/course-mw/course-actors-common/src/main/java/org/sunbird/learner/actors/coursebatch/dao/impl/CourseBatchDaoImpl.java b/course-mw/course-actors-common/src/main/java/org/sunbird/learner/actors/coursebatch/dao/impl/CourseBatchDaoImpl.java index 2a2c92cc2..0ad551ccb 100644 --- a/course-mw/course-actors-common/src/main/java/org/sunbird/learner/actors/coursebatch/dao/impl/CourseBatchDaoImpl.java +++ b/course-mw/course-actors-common/src/main/java/org/sunbird/learner/actors/coursebatch/dao/impl/CourseBatchDaoImpl.java @@ -3,12 +3,11 @@ import com.fasterxml.jackson.databind.ObjectMapper; import org.sunbird.cassandra.CassandraOperation; import org.sunbird.common.CassandraUtil; -import org.sunbird.common.exception.ProjectCommonException; -import org.sunbird.common.models.response.Response; -import org.sunbird.common.models.util.CassandraPropertyReader; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.request.RequestContext; -import org.sunbird.common.responsecode.ResponseCode; +import org.sunbird.exception.ProjectCommonException; +import org.sunbird.response.Response; +import org.sunbird.keys.JsonKey; +import org.sunbird.request.RequestContext; +import org.sunbird.response.ResponseCode; import org.sunbird.helper.ServiceFactory; import org.sunbird.learner.actors.coursebatch.dao.CourseBatchDao; import org.sunbird.learner.constants.CourseJsonKey; @@ -23,8 +22,8 @@ public class CourseBatchDaoImpl implements CourseBatchDao { private CassandraOperation cassandraOperation = ServiceFactory.getInstance(); private Util.DbInfo courseBatchDb = Util.dbInfoMap.get(JsonKey.COURSE_BATCH_DB); - private static final CassandraPropertyReader propertiesCache = - CassandraPropertyReader.getInstance(); + // private static final CassandraPropertyReader propertiesCache = + // CassandraPropertyReader.getInstance(); private ObjectMapper mapper = new ObjectMapper(); private String dateFormat = "yyyy-MM-dd"; diff --git a/course-mw/course-actors-common/src/main/java/org/sunbird/learner/actors/coursebatch/dao/impl/UserCoursesDaoImpl.java b/course-mw/course-actors-common/src/main/java/org/sunbird/learner/actors/coursebatch/dao/impl/UserCoursesDaoImpl.java index ddaf8d1bd..f65bbf012 100644 --- a/course-mw/course-actors-common/src/main/java/org/sunbird/learner/actors/coursebatch/dao/impl/UserCoursesDaoImpl.java +++ b/course-mw/course-actors-common/src/main/java/org/sunbird/learner/actors/coursebatch/dao/impl/UserCoursesDaoImpl.java @@ -5,9 +5,9 @@ import java.util.stream.Collectors; import org.apache.commons.collections.CollectionUtils; import org.sunbird.cassandra.CassandraOperation; -import org.sunbird.common.models.response.Response; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.request.RequestContext; +import org.sunbird.response.Response; +import org.sunbird.keys.JsonKey; +import org.sunbird.request.RequestContext; import org.sunbird.helper.ServiceFactory; import org.sunbird.learner.actors.coursebatch.dao.UserCoursesDao; import org.sunbird.learner.util.Util; diff --git a/course-mw/course-actors-common/src/main/java/org/sunbird/learner/actors/coursebatch/service/UserCoursesService.java b/course-mw/course-actors-common/src/main/java/org/sunbird/learner/actors/coursebatch/service/UserCoursesService.java index 6daec6607..9c8d205d2 100644 --- a/course-mw/course-actors-common/src/main/java/org/sunbird/learner/actors/coursebatch/service/UserCoursesService.java +++ b/course-mw/course-actors-common/src/main/java/org/sunbird/learner/actors/coursebatch/service/UserCoursesService.java @@ -3,11 +3,11 @@ import org.sunbird.common.ElasticSearchHelper; import org.sunbird.common.factory.EsClientFactory; import org.sunbird.common.inf.ElasticSearchService; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.models.util.LoggerUtil; -import org.sunbird.common.models.util.ProjectUtil; -import org.sunbird.common.models.util.datasecurity.OneWayHashing; -import org.sunbird.common.request.RequestContext; +import org.sunbird.keys.JsonKey; +import org.sunbird.logging.LoggerUtil; +import org.sunbird.common.ProjectUtil; +import org.sunbird.datasecurity.OneWayHashing; +import org.sunbird.request.RequestContext; import org.sunbird.dto.SearchDTO; import org.sunbird.learner.actors.coursebatch.dao.UserCoursesDao; import org.sunbird.learner.actors.coursebatch.dao.impl.UserCoursesDaoImpl; diff --git a/course-mw/course-actors-common/src/main/java/org/sunbird/learner/actors/group/dao/impl/GroupDaoImpl.java b/course-mw/course-actors-common/src/main/java/org/sunbird/learner/actors/group/dao/impl/GroupDaoImpl.java index eaa3d395f..cd3391192 100644 --- a/course-mw/course-actors-common/src/main/java/org/sunbird/learner/actors/group/dao/impl/GroupDaoImpl.java +++ b/course-mw/course-actors-common/src/main/java/org/sunbird/learner/actors/group/dao/impl/GroupDaoImpl.java @@ -1,9 +1,9 @@ package org.sunbird.learner.actors.group.dao.impl; import org.sunbird.cassandra.CassandraOperation; -import org.sunbird.common.models.response.Response; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.request.RequestContext; +import org.sunbird.response.Response; +import org.sunbird.keys.JsonKey; +import org.sunbird.request.RequestContext; import org.sunbird.helper.ServiceFactory; import org.sunbird.keys.SunbirdKey; import org.sunbird.learner.util.Util; diff --git a/course-mw/course-actors-common/src/main/java/org/sunbird/learner/actors/health/HealthActor.java b/course-mw/course-actors-common/src/main/java/org/sunbird/learner/actors/health/HealthActor.java index 444f00baf..c2d3cfd3c 100644 --- a/course-mw/course-actors-common/src/main/java/org/sunbird/learner/actors/health/HealthActor.java +++ b/course-mw/course-actors-common/src/main/java/org/sunbird/learner/actors/health/HealthActor.java @@ -6,13 +6,18 @@ import org.sunbird.actor.base.BaseActor; import org.sunbird.cassandra.CassandraOperation; import org.sunbird.common.ElasticSearchHelper; -import org.sunbird.common.exception.ProjectCommonException; +import org.sunbird.exception.ProjectCommonException; import org.sunbird.common.factory.EsClientFactory; import org.sunbird.common.inf.ElasticSearchService; -import org.sunbird.common.models.response.Response; -import org.sunbird.common.models.util.*; -import org.sunbird.common.request.Request; -import org.sunbird.common.responsecode.ResponseCode; +import org.sunbird.response.Response; +import org.sunbird.telemetry.dto.*; +import org.sunbird.request.Request; +import org.sunbird.response.ResponseCode; +import org.sunbird.logging.LoggerUtil; +import org.sunbird.operations.lms.ActorOperations; +import org.sunbird.common.*; +import org.sunbird.keys.JsonKey; +import org.sunbird.http.HttpUtil; import org.sunbird.helper.ServiceFactory; import org.sunbird.learner.util.Util; import scala.concurrent.Future; diff --git a/course-mw/course-actors-common/src/main/java/org/sunbird/learner/actors/qrcodedownload/QRCodeDownloadManagementActor.java b/course-mw/course-actors-common/src/main/java/org/sunbird/learner/actors/qrcodedownload/QRCodeDownloadManagementActor.java index f924ca01f..d73826360 100644 --- a/course-mw/course-actors-common/src/main/java/org/sunbird/learner/actors/qrcodedownload/QRCodeDownloadManagementActor.java +++ b/course-mw/course-actors-common/src/main/java/org/sunbird/learner/actors/qrcodedownload/QRCodeDownloadManagementActor.java @@ -6,15 +6,15 @@ import org.apache.commons.io.FileUtils; import org.apache.commons.lang.StringUtils; import org.sunbird.actor.base.BaseActor; -import org.sunbird.common.exception.ProjectCommonException; -import org.sunbird.common.models.response.Response; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.models.util.ProjectUtil; -import org.sunbird.common.models.util.TelemetryEnvKey; -import org.sunbird.common.request.Request; -import org.sunbird.common.request.RequestContext; -import org.sunbird.common.responsecode.ResponseCode; -import org.sunbird.common.util.CloudStorageUtil; +import org.sunbird.exception.ProjectCommonException; +import org.sunbird.response.Response; +import org.sunbird.keys.JsonKey; +import org.sunbird.common.ProjectUtil; +import org.sunbird.telemetry.dto.TelemetryEnvKey; +import org.sunbird.request.Request; +import org.sunbird.request.RequestContext; +import org.sunbird.response.ResponseCode; +import org.sunbird.utils.CloudStorageUtil; import org.sunbird.learner.util.Util; import java.io.File; @@ -23,8 +23,8 @@ import java.util.stream.Collectors; import static java.io.File.separator; -import static org.sunbird.common.models.util.JsonKey.*; -import static org.sunbird.common.models.util.ProjectUtil.getConfigValue; +import static org.sunbird.keys.JsonKey.*; +import static org.sunbird.common.ProjectUtil.getConfigValue; /** * @Author : Rhea Fernandes This actor is used to create an html file for all the qr code images diff --git a/course-mw/course-actors-common/src/main/java/org/sunbird/learner/actors/qrcodedownload/QRCodeDownloadManager.java b/course-mw/course-actors-common/src/main/java/org/sunbird/learner/actors/qrcodedownload/QRCodeDownloadManager.java index 980b9854e..22adb96fd 100644 --- a/course-mw/course-actors-common/src/main/java/org/sunbird/learner/actors/qrcodedownload/QRCodeDownloadManager.java +++ b/course-mw/course-actors-common/src/main/java/org/sunbird/learner/actors/qrcodedownload/QRCodeDownloadManager.java @@ -6,9 +6,13 @@ import org.apache.commons.collections4.MapUtils; import org.apache.commons.lang.StringUtils; import org.apache.http.HttpHeaders; -import org.sunbird.common.models.util.*; -import org.sunbird.common.request.RequestContext; +import org.sunbird.telemetry.dto.*; +import org.sunbird.request.RequestContext; +import org.sunbird.logging.LoggerUtil; +import org.sunbird.keys.JsonKey; +import org.sunbird.common.*; import org.sunbird.keys.SunbirdKey; +import org.sunbird.http.HttpUtil; import org.sunbird.learner.util.ContentSearchUtil; import javax.ws.rs.core.MediaType; diff --git a/course-mw/course-actors-common/src/main/java/org/sunbird/learner/actors/search/SearchHandlerActor.java b/course-mw/course-actors-common/src/main/java/org/sunbird/learner/actors/search/SearchHandlerActor.java index 8052a9ca5..dd02305fb 100644 --- a/course-mw/course-actors-common/src/main/java/org/sunbird/learner/actors/search/SearchHandlerActor.java +++ b/course-mw/course-actors-common/src/main/java/org/sunbird/learner/actors/search/SearchHandlerActor.java @@ -7,11 +7,15 @@ import org.sunbird.common.ElasticSearchHelper; import org.sunbird.common.factory.EsClientFactory; import org.sunbird.common.inf.ElasticSearchService; -import org.sunbird.common.models.response.Response; -import org.sunbird.common.models.util.*; -import org.sunbird.common.models.util.ProjectUtil.EsType; -import org.sunbird.common.request.Request; -import org.sunbird.common.request.RequestContext; +import org.sunbird.response.Response; +import org.sunbird.telemetry.dto.*; +import org.sunbird.common.ProjectUtil.EsType; +import org.sunbird.request.Request; +import org.sunbird.common.*; +import org.sunbird.operations.lms.ActorOperations; +import org.sunbird.logging.LoggerUtil; +import org.sunbird.keys.JsonKey; +import org.sunbird.request.RequestContext; import org.sunbird.dto.SearchDTO; import org.sunbird.learner.actors.coursebatch.service.UserCoursesService; import org.sunbird.learner.util.Util; diff --git a/course-mw/course-actors-common/src/main/java/org/sunbird/learner/actors/syncjobmanager/EsSyncActor.java b/course-mw/course-actors-common/src/main/java/org/sunbird/learner/actors/syncjobmanager/EsSyncActor.java index c6106afcb..bc9649f7f 100644 --- a/course-mw/course-actors-common/src/main/java/org/sunbird/learner/actors/syncjobmanager/EsSyncActor.java +++ b/course-mw/course-actors-common/src/main/java/org/sunbird/learner/actors/syncjobmanager/EsSyncActor.java @@ -9,16 +9,16 @@ import org.sunbird.actor.base.BaseActor; import org.sunbird.cassandra.CassandraOperation; import org.sunbird.common.CassandraUtil; -import org.sunbird.common.exception.ProjectCommonException; +import org.sunbird.exception.ProjectCommonException; import org.sunbird.common.factory.EsClientFactory; import org.sunbird.common.inf.ElasticSearchService; -import org.sunbird.common.models.response.Response; -import org.sunbird.common.models.util.ActorOperations; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.models.util.ProjectUtil; -import org.sunbird.common.request.Request; -import org.sunbird.common.request.RequestContext; -import org.sunbird.common.responsecode.ResponseCode; +import org.sunbird.response.Response; +import org.sunbird.operations.lms.ActorOperations; +import org.sunbird.keys.JsonKey; +import org.sunbird.common.ProjectUtil; +import org.sunbird.request.Request; +import org.sunbird.request.RequestContext; +import org.sunbird.response.ResponseCode; import org.sunbird.helper.ServiceFactory; import org.sunbird.learner.actors.coursebatch.service.UserCoursesService; import org.sunbird.learner.util.Util; diff --git a/course-mw/course-actors-common/src/main/java/org/sunbird/learner/util/ContentSearchMock.java b/course-mw/course-actors-common/src/main/java/org/sunbird/learner/util/ContentSearchMock.java index 349570111..c076ffc41 100644 --- a/course-mw/course-actors-common/src/main/java/org/sunbird/learner/util/ContentSearchMock.java +++ b/course-mw/course-actors-common/src/main/java/org/sunbird/learner/util/ContentSearchMock.java @@ -4,7 +4,7 @@ import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockWebServer; import okhttp3.mockwebserver.RecordedRequest; -import org.sunbird.common.models.util.LoggerUtil; +import org.sunbird.logging.LoggerUtil; import java.io.IOException; import java.util.HashMap; diff --git a/course-mw/course-actors-common/src/main/java/org/sunbird/learner/util/ContentSearchUtil.java b/course-mw/course-actors-common/src/main/java/org/sunbird/learner/util/ContentSearchUtil.java index 672b13f33..4c672a2db 100644 --- a/course-mw/course-actors-common/src/main/java/org/sunbird/learner/util/ContentSearchUtil.java +++ b/course-mw/course-actors-common/src/main/java/org/sunbird/learner/util/ContentSearchUtil.java @@ -12,11 +12,11 @@ import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.models.util.LoggerUtil; -import org.sunbird.common.models.util.PropertiesCache; -import org.sunbird.common.models.util.RestUtil; -import org.sunbird.common.request.RequestContext; +import org.sunbird.keys.JsonKey; +import org.sunbird.logging.LoggerUtil; +import org.sunbird.common.PropertiesCache; +import org.sunbird.utils.RestUtil; +import org.sunbird.request.RequestContext; import scala.concurrent.ExecutionContextExecutor; import scala.concurrent.Future; diff --git a/course-mw/course-actors-common/src/main/java/org/sunbird/learner/util/ContentUtil.java b/course-mw/course-actors-common/src/main/java/org/sunbird/learner/util/ContentUtil.java index 02b1576ec..0ea0da8f4 100644 --- a/course-mw/course-actors-common/src/main/java/org/sunbird/learner/util/ContentUtil.java +++ b/course-mw/course-actors-common/src/main/java/org/sunbird/learner/util/ContentUtil.java @@ -13,13 +13,17 @@ import org.apache.commons.collections4.MapUtils; import org.apache.commons.lang3.StringUtils; import org.apache.http.HttpHeaders; -import org.sunbird.common.exception.ProjectCommonException; -import org.sunbird.common.models.response.HttpUtilResponse; -import org.sunbird.common.models.util.*; -import org.sunbird.common.request.Request; -import org.sunbird.common.request.RequestContext; -import org.sunbird.common.responsecode.ResponseCode; -import org.sunbird.common.util.JsonUtil; +import org.sunbird.exception.ProjectCommonException; +import org.sunbird.response.HttpUtilResponse; +import org.sunbird.telemetry.dto.*; +import org.sunbird.request.Request; +import org.sunbird.request.RequestContext; +import org.sunbird.response.ResponseCode; +import org.sunbird.utils.JsonUtil; +import org.sunbird.http.HttpUtil; +import org.sunbird.common.*; +import org.sunbird.logging.LoggerUtil; +import org.sunbird.keys.JsonKey; /** * This class will make the call to EkStep content search diff --git a/course-mw/course-actors-common/src/main/java/org/sunbird/learner/util/CourseBatchSchedulerUtil.java b/course-mw/course-actors-common/src/main/java/org/sunbird/learner/util/CourseBatchSchedulerUtil.java index 64866ff26..fcb0217cc 100644 --- a/course-mw/course-actors-common/src/main/java/org/sunbird/learner/util/CourseBatchSchedulerUtil.java +++ b/course-mw/course-actors-common/src/main/java/org/sunbird/learner/util/CourseBatchSchedulerUtil.java @@ -6,11 +6,15 @@ import org.sunbird.common.ElasticSearchHelper; import org.sunbird.common.factory.EsClientFactory; import org.sunbird.common.inf.ElasticSearchService; -import org.sunbird.common.models.util.*; -import org.sunbird.common.request.HeaderParam; -import org.sunbird.common.request.RequestContext; +import org.sunbird.telemetry.dto.*; +import org.sunbird.request.HeaderParam; +import org.sunbird.request.RequestContext; import org.sunbird.helper.ServiceFactory; import scala.concurrent.Future; +import org.sunbird.common.*; +import org.sunbird.logging.LoggerUtil; +import org.sunbird.keys.JsonKey; +import org.sunbird.http.HttpUtil; import java.util.HashMap; import java.util.List; diff --git a/course-mw/course-actors-common/src/main/java/org/sunbird/learner/util/CourseBatchUtil.java b/course-mw/course-actors-common/src/main/java/org/sunbird/learner/util/CourseBatchUtil.java index 1f6362a7e..87adbb356 100644 --- a/course-mw/course-actors-common/src/main/java/org/sunbird/learner/util/CourseBatchUtil.java +++ b/course-mw/course-actors-common/src/main/java/org/sunbird/learner/util/CourseBatchUtil.java @@ -6,16 +6,16 @@ import org.apache.commons.collections.MapUtils; import org.apache.commons.lang3.StringUtils; import org.sunbird.common.ElasticSearchHelper; -import org.sunbird.common.exception.ProjectCommonException; +import org.sunbird.exception.ProjectCommonException; import org.sunbird.common.factory.EsClientFactory; import org.sunbird.common.inf.ElasticSearchService; -import org.sunbird.common.models.response.Response; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.models.util.LoggerUtil; -import org.sunbird.common.models.util.ProjectUtil; -import org.sunbird.common.models.util.ProjectUtil.EsType; -import org.sunbird.common.request.RequestContext; -import org.sunbird.common.responsecode.ResponseCode; +import org.sunbird.response.Response; +import org.sunbird.keys.JsonKey; +import org.sunbird.logging.LoggerUtil; +import org.sunbird.common.ProjectUtil; +import org.sunbird.common.ProjectUtil.EsType; +import org.sunbird.request.RequestContext; +import org.sunbird.response.ResponseCode; import org.sunbird.learner.constants.CourseJsonKey; import org.sunbird.models.course.batch.CourseBatch; import scala.concurrent.Future; diff --git a/course-mw/course-actors-common/src/main/java/org/sunbird/learner/util/DataCacheHandler.java b/course-mw/course-actors-common/src/main/java/org/sunbird/learner/util/DataCacheHandler.java index 1c05d24e3..05a3abac4 100644 --- a/course-mw/course-actors-common/src/main/java/org/sunbird/learner/util/DataCacheHandler.java +++ b/course-mw/course-actors-common/src/main/java/org/sunbird/learner/util/DataCacheHandler.java @@ -2,11 +2,11 @@ package org.sunbird.learner.util; import org.sunbird.cassandra.CassandraOperation; -import org.sunbird.common.models.response.Response; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.models.util.ProjectUtil; -import org.sunbird.common.models.util.TableNameUtil; -import org.sunbird.common.models.util.LoggerUtil; +import org.sunbird.response.Response; +import org.sunbird.keys.JsonKey; +import org.sunbird.common.ProjectUtil; +import org.sunbird.utils.TableNameUtil; +import org.sunbird.logging.LoggerUtil; import org.sunbird.helper.ServiceFactory; import java.util.List; diff --git a/course-mw/course-actors-common/src/main/java/org/sunbird/learner/util/SchedulerManager.java b/course-mw/course-actors-common/src/main/java/org/sunbird/learner/util/SchedulerManager.java index f4784ba9f..0a80ea608 100644 --- a/course-mw/course-actors-common/src/main/java/org/sunbird/learner/util/SchedulerManager.java +++ b/course-mw/course-actors-common/src/main/java/org/sunbird/learner/util/SchedulerManager.java @@ -4,9 +4,9 @@ import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import org.sunbird.common.cacheloader.PageCacheLoaderService; -import org.sunbird.common.models.util.LoggerEnum; -import org.sunbird.common.models.util.LoggerUtil; -import org.sunbird.common.models.util.ProjectLogger; +import org.sunbird.logging.LoggerEnum; +import org.sunbird.logging.LoggerUtil; +import org.sunbird.logging.ProjectLogger; /** @author Manzarul All the scheduler job will be handle by this class. */ public class SchedulerManager { diff --git a/course-mw/course-actors-common/src/main/java/org/sunbird/learner/util/SearchTelemetryUtil.java b/course-mw/course-actors-common/src/main/java/org/sunbird/learner/util/SearchTelemetryUtil.java index f0249760c..224768acf 100644 --- a/course-mw/course-actors-common/src/main/java/org/sunbird/learner/util/SearchTelemetryUtil.java +++ b/course-mw/course-actors-common/src/main/java/org/sunbird/learner/util/SearchTelemetryUtil.java @@ -4,10 +4,10 @@ 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.keys.JsonKey; +import org.sunbird.logging.ProjectLogger; +import org.sunbird.common.PropertiesCache; +import org.sunbird.request.Request; import org.sunbird.dto.SearchDTO; import org.sunbird.telemetry.util.TelemetryUtil; import org.sunbird.telemetry.util.TelemetryWriter; diff --git a/course-mw/course-actors-common/src/main/java/org/sunbird/learner/util/Util.java b/course-mw/course-actors-common/src/main/java/org/sunbird/learner/util/Util.java index 6173cebd8..a53a692d2 100644 --- a/course-mw/course-actors-common/src/main/java/org/sunbird/learner/util/Util.java +++ b/course-mw/course-actors-common/src/main/java/org/sunbird/learner/util/Util.java @@ -1,11 +1,11 @@ package org.sunbird.learner.util; import org.apache.commons.lang3.StringUtils; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.models.util.LoggerUtil; -import org.sunbird.common.models.util.ProjectUtil; -import org.sunbird.common.models.util.TableNameUtil; -import org.sunbird.common.request.Request; +import org.sunbird.keys.JsonKey; +import org.sunbird.logging.LoggerUtil; +import org.sunbird.common.ProjectUtil; +import org.sunbird.utils.TableNameUtil; +import org.sunbird.request.Request; import org.sunbird.dto.SearchDTO; import org.sunbird.helper.CassandraConnectionManager; import org.sunbird.helper.CassandraConnectionMngrFactory; diff --git a/course-mw/course-actors-common/src/main/java/org/sunbird/models/course/batch/CourseBatch.java b/course-mw/course-actors-common/src/main/java/org/sunbird/models/course/batch/CourseBatch.java index 0d6890dd9..abecf6bc0 100644 --- a/course-mw/course-actors-common/src/main/java/org/sunbird/models/course/batch/CourseBatch.java +++ b/course-mw/course-actors-common/src/main/java/org/sunbird/models/course/batch/CourseBatch.java @@ -7,7 +7,7 @@ import java.util.List; import java.util.Map; -import org.sunbird.common.models.util.ProjectUtil; +import org.sunbird.common.ProjectUtil; @JsonIgnoreProperties(ignoreUnknown = true) @JsonInclude(JsonInclude.Include.NON_NULL) diff --git a/course-mw/course-actors-common/src/main/java/org/sunbird/userorg/UserOrgServiceImpl.java b/course-mw/course-actors-common/src/main/java/org/sunbird/userorg/UserOrgServiceImpl.java index 8776277ef..5c776a6e1 100644 --- a/course-mw/course-actors-common/src/main/java/org/sunbird/userorg/UserOrgServiceImpl.java +++ b/course-mw/course-actors-common/src/main/java/org/sunbird/userorg/UserOrgServiceImpl.java @@ -7,13 +7,13 @@ import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang3.StringUtils; -import org.sunbird.common.exception.ProjectCommonException; -import org.sunbird.common.models.response.Response; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.models.util.LoggerUtil; -import org.sunbird.common.request.RequestContext; -import org.sunbird.common.responsecode.ResponseCode; -import org.sunbird.common.util.KeycloakRequiredActionLinkUtil; +import org.sunbird.exception.ProjectCommonException; +import org.sunbird.response.Response; +import org.sunbird.keys.JsonKey; +import org.sunbird.logging.LoggerUtil; +import org.sunbird.request.RequestContext; +import org.sunbird.response.ResponseCode; +import org.sunbird.keycloak.KeycloakRequiredActionLinkUtil; import java.util.HashMap; import java.util.List; @@ -23,20 +23,20 @@ import java.util.stream.Collectors; import static org.apache.http.HttpHeaders.AUTHORIZATION; -import static org.sunbird.common.exception.ProjectCommonException.throwServerErrorException; -import static org.sunbird.common.models.util.JsonKey.BEARER; -import static org.sunbird.common.models.util.JsonKey.CONTENT; -import static org.sunbird.common.models.util.JsonKey.FILTERS; -import static org.sunbird.common.models.util.JsonKey.ID; -import static org.sunbird.common.models.util.JsonKey.RESPONSE; -import static org.sunbird.common.models.util.JsonKey.SUNBIRD_AUTHORIZATION; -import static org.sunbird.common.models.util.JsonKey.SUNBIRD_GET_MULTIPLE_USER_API; -import static org.sunbird.common.models.util.JsonKey.SUNBIRD_GET_ORGANISATION_API; -import static org.sunbird.common.models.util.JsonKey.SUNBIRD_GET_SINGLE_USER_API; -import static org.sunbird.common.models.util.JsonKey.SUNBIRD_USER_ORG_API_BASE_URL; -import static org.sunbird.common.models.util.ProjectUtil.getConfigValue; -import static org.sunbird.common.responsecode.ResponseCode.errorProcessingRequest; -import static org.sunbird.common.responsecode.ResponseCode.resourceNotFound; +import static org.sunbird.exception.ProjectCommonException.throwServerErrorException; +import static org.sunbird.keys.JsonKey.BEARER; +import static org.sunbird.keys.JsonKey.CONTENT; +import static org.sunbird.keys.JsonKey.FILTERS; +import static org.sunbird.keys.JsonKey.ID; +import static org.sunbird.keys.JsonKey.RESPONSE; +import static org.sunbird.keys.JsonKey.SUNBIRD_AUTHORIZATION; +import static org.sunbird.keys.JsonKey.SUNBIRD_GET_MULTIPLE_USER_API; +import static org.sunbird.keys.JsonKey.SUNBIRD_GET_ORGANISATION_API; +import static org.sunbird.keys.JsonKey.SUNBIRD_GET_SINGLE_USER_API; +import static org.sunbird.keys.JsonKey.SUNBIRD_USER_ORG_API_BASE_URL; +import static org.sunbird.common.ProjectUtil.getConfigValue; +import static org.sunbird.response.ResponseCode.errorProcessingRequest; +import static org.sunbird.response.ResponseCode.resourceNotFound; import static org.sunbird.learner.constants.CourseJsonKey.SUNBIRD_SEND_EMAIL_NOTIFICATION_API; public class UserOrgServiceImpl implements UserOrgService { diff --git a/course-mw/course-actors-common/src/main/java/org/sunbird/util/ExhaustAPIUtil.java b/course-mw/course-actors-common/src/main/java/org/sunbird/util/ExhaustAPIUtil.java index fa9112dff..dd8bbb8f8 100644 --- a/course-mw/course-actors-common/src/main/java/org/sunbird/util/ExhaustAPIUtil.java +++ b/course-mw/course-actors-common/src/main/java/org/sunbird/util/ExhaustAPIUtil.java @@ -9,13 +9,13 @@ import com.mashape.unirest.http.exceptions.UnirestException; import org.apache.commons.lang3.StringUtils; import org.apache.http.HttpHeaders; -import org.sunbird.common.exception.ProjectCommonException; -import org.sunbird.common.models.response.Response; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.models.util.LoggerUtil; -import org.sunbird.common.models.util.PropertiesCache; -import org.sunbird.common.request.RequestContext; -import org.sunbird.common.responsecode.ResponseCode; +import org.sunbird.exception.ProjectCommonException; +import org.sunbird.response.Response; +import org.sunbird.keys.JsonKey; +import org.sunbird.logging.LoggerUtil; +import org.sunbird.common.PropertiesCache; +import org.sunbird.request.RequestContext; +import org.sunbird.response.ResponseCode; import scala.concurrent.ExecutionContextExecutor; import javax.ws.rs.core.MediaType; diff --git a/course-mw/course-actors-common/src/test/java/org/sunbird/actor/exhaustjob/ExhaustJobActorTest.java b/course-mw/course-actors-common/src/test/java/org/sunbird/actor/exhaustjob/ExhaustJobActorTest.java index e42724416..4976707d7 100644 --- a/course-mw/course-actors-common/src/test/java/org/sunbird/actor/exhaustjob/ExhaustJobActorTest.java +++ b/course-mw/course-actors-common/src/test/java/org/sunbird/actor/exhaustjob/ExhaustJobActorTest.java @@ -18,11 +18,11 @@ import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.sunbird.application.test.SunbirdApplicationActorTest; -import org.sunbird.common.exception.ProjectCommonException; -import org.sunbird.common.models.response.Response; -import org.sunbird.common.models.util.ActorOperations; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.request.Request; +import org.sunbird.exception.ProjectCommonException; +import org.sunbird.response.Response; +import org.sunbird.operations.lms.ActorOperations; +import org.sunbird.keys.JsonKey; +import org.sunbird.request.Request; import java.util.HashMap; import java.util.Map; diff --git a/course-mw/course-actors-common/src/test/java/org/sunbird/application/test/SunbirdApplicationActorTest.java b/course-mw/course-actors-common/src/test/java/org/sunbird/application/test/SunbirdApplicationActorTest.java index 1aabfccbf..6ed30a50c 100644 --- a/course-mw/course-actors-common/src/test/java/org/sunbird/application/test/SunbirdApplicationActorTest.java +++ b/course-mw/course-actors-common/src/test/java/org/sunbird/application/test/SunbirdApplicationActorTest.java @@ -6,7 +6,7 @@ import org.apache.pekko.actor.Props; import org.apache.pekko.testkit.javadsl.TestKit; import java.time.Duration; -import org.sunbird.common.request.Request; +import org.sunbird.request.Request; /** @author rahul */ public class SunbirdApplicationActorTest { diff --git a/course-mw/course-actors-common/src/test/java/org/sunbird/builder/object/CustomObjectBuilder.java b/course-mw/course-actors-common/src/test/java/org/sunbird/builder/object/CustomObjectBuilder.java index cb198bff7..c5bb94aa4 100644 --- a/course-mw/course-actors-common/src/test/java/org/sunbird/builder/object/CustomObjectBuilder.java +++ b/course-mw/course-actors-common/src/test/java/org/sunbird/builder/object/CustomObjectBuilder.java @@ -1,9 +1,9 @@ package org.sunbird.builder.object; import org.apache.pekko.dispatch.Futures; -import org.sunbird.common.models.response.Response; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.models.util.ProjectUtil; +import org.sunbird.response.Response; +import org.sunbird.keys.JsonKey; +import org.sunbird.common.ProjectUtil; import scala.concurrent.Future; import scala.concurrent.Promise; diff --git a/course-mw/course-actors-common/src/test/java/org/sunbird/learner/actors/DialAssembleTest.java b/course-mw/course-actors-common/src/test/java/org/sunbird/learner/actors/DialAssembleTest.java index 1726c1844..72965105c 100644 --- a/course-mw/course-actors-common/src/test/java/org/sunbird/learner/actors/DialAssembleTest.java +++ b/course-mw/course-actors-common/src/test/java/org/sunbird/learner/actors/DialAssembleTest.java @@ -10,7 +10,7 @@ import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.modules.junit4.PowerMockRunner; -import org.sunbird.common.request.RequestContext; +import org.sunbird.request.RequestContext; import java.lang.reflect.Method; import java.util.Arrays; diff --git a/course-mw/course-actors-common/src/test/java/org/sunbird/learner/actors/HealthActorTest.java b/course-mw/course-actors-common/src/test/java/org/sunbird/learner/actors/HealthActorTest.java index 2a3dd499d..3f8c8c37c 100644 --- a/course-mw/course-actors-common/src/test/java/org/sunbird/learner/actors/HealthActorTest.java +++ b/course-mw/course-actors-common/src/test/java/org/sunbird/learner/actors/HealthActorTest.java @@ -11,10 +11,10 @@ import org.junit.Test; import org.mockito.Mockito; import org.powermock.api.mockito.PowerMockito; -import org.sunbird.common.models.response.Response; -import org.sunbird.common.models.util.ActorOperations; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.request.Request; +import org.sunbird.response.Response; +import org.sunbird.operations.lms.ActorOperations; +import org.sunbird.keys.JsonKey; +import org.sunbird.request.Request; import org.sunbird.learner.actors.health.HealthActor; import org.sunbird.learner.util.Util; diff --git a/course-mw/course-actors-common/src/test/java/org/sunbird/learner/actors/PageManagementActorTest.java b/course-mw/course-actors-common/src/test/java/org/sunbird/learner/actors/PageManagementActorTest.java index c50a052b9..bca9a4bd3 100644 --- a/course-mw/course-actors-common/src/test/java/org/sunbird/learner/actors/PageManagementActorTest.java +++ b/course-mw/course-actors-common/src/test/java/org/sunbird/learner/actors/PageManagementActorTest.java @@ -28,13 +28,13 @@ import org.powermock.modules.junit4.PowerMockRunner; import org.sunbird.cassandraimpl.CassandraOperationImpl; import org.sunbird.common.cacheloader.PageCacheLoaderService; -import org.sunbird.common.exception.ProjectCommonException; -import org.sunbird.common.models.response.Response; -import org.sunbird.common.models.util.ActorOperations; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.request.Request; -import org.sunbird.common.request.RequestContext; -import org.sunbird.common.responsecode.ResponseCode; +import org.sunbird.exception.ProjectCommonException; +import org.sunbird.response.Response; +import org.sunbird.operations.lms.ActorOperations; +import org.sunbird.keys.JsonKey; +import org.sunbird.request.Request; +import org.sunbird.request.RequestContext; +import org.sunbird.response.ResponseCode; import org.sunbird.helper.ServiceFactory; import org.sunbird.learner.util.ContentSearchUtil; import org.sunbird.learner.util.DataCacheHandler; diff --git a/course-mw/course-actors-common/src/test/java/org/sunbird/learner/actors/SearchHandlerActorTest.java b/course-mw/course-actors-common/src/test/java/org/sunbird/learner/actors/SearchHandlerActorTest.java index f33d351b6..270a557dc 100644 --- a/course-mw/course-actors-common/src/test/java/org/sunbird/learner/actors/SearchHandlerActorTest.java +++ b/course-mw/course-actors-common/src/test/java/org/sunbird/learner/actors/SearchHandlerActorTest.java @@ -24,18 +24,21 @@ import org.powermock.modules.junit4.PowerMockRunner; import org.sunbird.cassandraimpl.CassandraOperationImpl; import org.sunbird.common.ElasticSearchRestHighImpl; -import org.sunbird.common.exception.ProjectCommonException; +import org.sunbird.common.ElasticSearchHelper; +import org.sunbird.exception.ProjectCommonException; import org.sunbird.common.factory.EsClientFactory; import org.sunbird.common.inf.ElasticSearchService; -import org.sunbird.common.models.response.HttpUtilResponse; -import org.sunbird.common.models.response.Response; -import org.sunbird.common.models.util.ActorOperations; -import org.sunbird.common.models.util.HttpUtil; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.models.util.ProjectUtil; -import org.sunbird.common.request.Request; -import org.sunbird.common.request.RequestContext; -import org.sunbird.common.util.KeycloakRequiredActionLinkUtil; +import org.sunbird.response.HttpUtilResponse; +import org.sunbird.response.Response; +import org.sunbird.operations.lms.ActorOperations; + +import org.sunbird.keys.JsonKey; +import org.sunbird.common.ProjectUtil; +import org.sunbird.telemetry.dto.TelemetryEnvKey; +import org.sunbird.http.HttpUtil; +import org.sunbird.request.Request; +import org.sunbird.request.RequestContext; +import org.sunbird.keycloak.KeycloakRequiredActionLinkUtil; import org.sunbird.dto.SearchDTO; import org.sunbird.helper.ServiceFactory; import org.sunbird.learner.actors.coursebatch.dao.UserCoursesDao; diff --git a/course-mw/course-actors-common/src/test/java/org/sunbird/learner/actors/certificate/CertificateActorTest.java b/course-mw/course-actors-common/src/test/java/org/sunbird/learner/actors/certificate/CertificateActorTest.java index 29c4b6d23..206bbdebb 100644 --- a/course-mw/course-actors-common/src/test/java/org/sunbird/learner/actors/certificate/CertificateActorTest.java +++ b/course-mw/course-actors-common/src/test/java/org/sunbird/learner/actors/certificate/CertificateActorTest.java @@ -20,19 +20,19 @@ import org.sunbird.builder.object.CustomObjectBuilder; import org.sunbird.builder.object.CustomObjectBuilder.CustomObjectWrapper; import org.sunbird.common.ElasticSearchHelper; -import org.sunbird.common.exception.ProjectCommonException; +import org.sunbird.exception.ProjectCommonException; import org.sunbird.common.factory.EsClientFactory; -import org.sunbird.common.models.response.Response; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.request.Request; -import org.sunbird.common.request.RequestContext; -import org.sunbird.kafka.client.InstructionEventGenerator; -import org.sunbird.kafka.client.KafkaClient; +import org.sunbird.response.Response; +import org.sunbird.keys.JsonKey; +import org.sunbird.request.Request; +import org.sunbird.request.RequestContext; +import org.sunbird.kafka.InstructionEventGenerator; +import org.sunbird.kafka.KafkaClient; import org.sunbird.learner.actors.certificate.service.CertificateActor; @RunWith(PowerMockRunner.class) @PowerMockIgnore("javax.management.*") -@SuppressStaticInitializationFor("org.sunbird.kafka.client.KafkaClient") +@SuppressStaticInitializationFor("org.sunbird.kafka.KafkaClient") public class CertificateActorTest extends SunbirdApplicationActorTest { private MockerBuilder.MockersGroup group; diff --git a/course-mw/course-actors-common/src/test/java/org/sunbird/learner/actors/coursebatch/dao/CourseBatchDaoTest.java b/course-mw/course-actors-common/src/test/java/org/sunbird/learner/actors/coursebatch/dao/CourseBatchDaoTest.java index a4e79ffba..0b2002e35 100644 --- a/course-mw/course-actors-common/src/test/java/org/sunbird/learner/actors/coursebatch/dao/CourseBatchDaoTest.java +++ b/course-mw/course-actors-common/src/test/java/org/sunbird/learner/actors/coursebatch/dao/CourseBatchDaoTest.java @@ -18,11 +18,11 @@ import org.powermock.modules.junit4.PowerMockRunner; import org.sunbird.cassandra.CassandraOperation; import org.sunbird.cassandraimpl.CassandraOperationImpl; -import org.sunbird.common.exception.ProjectCommonException; -import org.sunbird.common.models.response.Response; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.models.util.ProjectUtil; -import org.sunbird.common.responsecode.ResponseCode; +import org.sunbird.exception.ProjectCommonException; +import org.sunbird.response.Response; +import org.sunbird.keys.JsonKey; +import org.sunbird.common.ProjectUtil; +import org.sunbird.response.ResponseCode; import org.sunbird.helper.ServiceFactory; import org.sunbird.learner.actors.coursebatch.dao.impl.CourseBatchDaoImpl; import org.sunbird.models.course.batch.CourseBatch; diff --git a/course-mw/course-actors-common/src/test/java/org/sunbird/learner/actors/coursebatch/dao/UserCoursesDaoTest.java b/course-mw/course-actors-common/src/test/java/org/sunbird/learner/actors/coursebatch/dao/UserCoursesDaoTest.java index fe4f21439..64590fc46 100644 --- a/course-mw/course-actors-common/src/test/java/org/sunbird/learner/actors/coursebatch/dao/UserCoursesDaoTest.java +++ b/course-mw/course-actors-common/src/test/java/org/sunbird/learner/actors/coursebatch/dao/UserCoursesDaoTest.java @@ -21,8 +21,8 @@ import org.powermock.modules.junit4.PowerMockRunner; import org.sunbird.cassandra.CassandraOperation; import org.sunbird.cassandraimpl.CassandraOperationImpl; -import org.sunbird.common.models.response.Response; -import org.sunbird.common.models.util.JsonKey; +import org.sunbird.response.Response; +import org.sunbird.keys.JsonKey; import org.sunbird.helper.ServiceFactory; import org.sunbird.learner.actors.coursebatch.dao.impl.UserCoursesDaoImpl; import org.sunbird.models.user.courses.UserCourses; diff --git a/course-mw/course-actors-common/src/test/java/org/sunbird/learner/actors/coursebatch/service/UserCourseServiceTest.java b/course-mw/course-actors-common/src/test/java/org/sunbird/learner/actors/coursebatch/service/UserCourseServiceTest.java index b25c02ef7..c98a3d614 100644 --- a/course-mw/course-actors-common/src/test/java/org/sunbird/learner/actors/coursebatch/service/UserCourseServiceTest.java +++ b/course-mw/course-actors-common/src/test/java/org/sunbird/learner/actors/coursebatch/service/UserCourseServiceTest.java @@ -16,9 +16,9 @@ import org.sunbird.common.ElasticSearchRestHighImpl; import org.sunbird.common.factory.EsClientFactory; import org.sunbird.common.inf.ElasticSearchService; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.models.util.ProjectUtil; -import org.sunbird.common.models.util.datasecurity.OneWayHashing; +import org.sunbird.keys.JsonKey; +import org.sunbird.common.ProjectUtil; +import org.sunbird.datasecurity.OneWayHashing; import org.sunbird.helper.ServiceFactory; import org.sunbird.learner.actors.coursebatch.dao.UserCoursesDao; import scala.concurrent.Promise; diff --git a/course-mw/course-actors-common/src/test/java/org/sunbird/learner/actors/coursemanagement/CourseManagementActorTest.java b/course-mw/course-actors-common/src/test/java/org/sunbird/learner/actors/coursemanagement/CourseManagementActorTest.java index 0aa6e3e21..ce1a8a5be 100644 --- a/course-mw/course-actors-common/src/test/java/org/sunbird/learner/actors/coursemanagement/CourseManagementActorTest.java +++ b/course-mw/course-actors-common/src/test/java/org/sunbird/learner/actors/coursemanagement/CourseManagementActorTest.java @@ -20,11 +20,11 @@ import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; -import org.sunbird.common.exception.ProjectCommonException; -import org.sunbird.common.models.response.Response; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.models.util.ProjectUtil; -import org.sunbird.common.request.Request; +import org.sunbird.exception.ProjectCommonException; +import org.sunbird.response.Response; +import org.sunbird.keys.JsonKey; +import org.sunbird.common.ProjectUtil; +import org.sunbird.request.Request; import org.sunbird.keys.*; import java.util.Arrays; diff --git a/course-mw/course-actors-common/src/test/java/org/sunbird/learner/actors/coursemanagement/HierarchyGenerationHelperTest.java b/course-mw/course-actors-common/src/test/java/org/sunbird/learner/actors/coursemanagement/HierarchyGenerationHelperTest.java index 195509d9b..9c93031b3 100644 --- a/course-mw/course-actors-common/src/test/java/org/sunbird/learner/actors/coursemanagement/HierarchyGenerationHelperTest.java +++ b/course-mw/course-actors-common/src/test/java/org/sunbird/learner/actors/coursemanagement/HierarchyGenerationHelperTest.java @@ -6,7 +6,7 @@ import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; -import org.sunbird.common.request.Request; +import org.sunbird.request.Request; import org.sunbird.learner.actors.course.HierarchyGenerationHelper; import java.util.Map; diff --git a/course-mw/course-actors-common/src/test/java/org/sunbird/learner/actors/group/dao/impl/GroupDaoImplTest.java b/course-mw/course-actors-common/src/test/java/org/sunbird/learner/actors/group/dao/impl/GroupDaoImplTest.java index 60c6fac03..ee5fa6bff 100644 --- a/course-mw/course-actors-common/src/test/java/org/sunbird/learner/actors/group/dao/impl/GroupDaoImplTest.java +++ b/course-mw/course-actors-common/src/test/java/org/sunbird/learner/actors/group/dao/impl/GroupDaoImplTest.java @@ -16,9 +16,9 @@ import org.powermock.modules.junit4.PowerMockRunner; import org.sunbird.cassandra.CassandraOperation; import org.sunbird.cassandraimpl.CassandraOperationImpl; -import org.sunbird.common.models.response.Response; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.responsecode.ResponseCode; +import org.sunbird.response.Response; +import org.sunbird.keys.JsonKey; +import org.sunbird.response.ResponseCode; import org.sunbird.helper.ServiceFactory; import org.sunbird.learner.util.JsonUtil; diff --git a/course-mw/course-actors-common/src/test/java/org/sunbird/learner/actors/qrcode/QRCodeDownloadManagerTest.java b/course-mw/course-actors-common/src/test/java/org/sunbird/learner/actors/qrcode/QRCodeDownloadManagerTest.java index caf5446b3..f2ca9ffd1 100644 --- a/course-mw/course-actors-common/src/test/java/org/sunbird/learner/actors/qrcode/QRCodeDownloadManagerTest.java +++ b/course-mw/course-actors-common/src/test/java/org/sunbird/learner/actors/qrcode/QRCodeDownloadManagerTest.java @@ -14,10 +14,11 @@ import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; -import org.sunbird.common.models.util.HttpUtil; -import org.sunbird.common.models.util.ProjectUtil; -import org.sunbird.common.models.util.RestUtil; -import org.sunbird.common.request.Request; +import org.sunbird.http.HttpUtil; +import org.sunbird.common.ProjectUtil; +import org.sunbird.utils.RestUtil; + +import org.sunbird.request.Request; import org.sunbird.learner.actors.qrcodedownload.QRCodeDownloadManager; import java.util.HashMap; diff --git a/course-mw/course-actors-common/src/test/java/org/sunbird/learner/util/ContentUtilTest.java b/course-mw/course-actors-common/src/test/java/org/sunbird/learner/util/ContentUtilTest.java index e8fc9d43b..37ab4f874 100644 --- a/course-mw/course-actors-common/src/test/java/org/sunbird/learner/util/ContentUtilTest.java +++ b/course-mw/course-actors-common/src/test/java/org/sunbird/learner/util/ContentUtilTest.java @@ -14,11 +14,11 @@ import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.sunbird.builder.mocker.MockerBuilder; -import org.sunbird.common.exception.ProjectCommonException; -import org.sunbird.common.models.response.HttpUtilResponse; -import org.sunbird.common.models.util.HttpUtil; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.responsecode.ResponseCode; +import org.sunbird.exception.ProjectCommonException; +import org.sunbird.response.HttpUtilResponse; +import org.sunbird.http.HttpUtil; +import org.sunbird.keys.JsonKey; +import org.sunbird.response.ResponseCode; /** @author rahul */ @RunWith(PowerMockRunner.class) diff --git a/course-mw/course-actors-common/src/test/java/org/sunbird/learner/util/CourseBatchSchedulerUtilTest.java b/course-mw/course-actors-common/src/test/java/org/sunbird/learner/util/CourseBatchSchedulerUtilTest.java index a8f27ecc3..f0690b763 100644 --- a/course-mw/course-actors-common/src/test/java/org/sunbird/learner/util/CourseBatchSchedulerUtilTest.java +++ b/course-mw/course-actors-common/src/test/java/org/sunbird/learner/util/CourseBatchSchedulerUtilTest.java @@ -19,10 +19,10 @@ import org.sunbird.builder.object.CustomObjectBuilder; import org.sunbird.common.ElasticSearchHelper; import org.sunbird.common.factory.EsClientFactory; -import org.sunbird.common.models.response.Response; -import org.sunbird.common.models.util.HttpUtil; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.models.util.ProjectUtil; +import org.sunbird.response.Response; +import org.sunbird.http.HttpUtil; +import org.sunbird.keys.JsonKey; +import org.sunbird.common.ProjectUtil; import org.sunbird.helper.ServiceFactory; @RunWith(PowerMockRunner.class) diff --git a/course-mw/course-actors-common/src/test/java/org/sunbird/learner/util/CourseBatchUtilTest.java b/course-mw/course-actors-common/src/test/java/org/sunbird/learner/util/CourseBatchUtilTest.java index 6b7332ba8..ad53f3b2c 100644 --- a/course-mw/course-actors-common/src/test/java/org/sunbird/learner/util/CourseBatchUtilTest.java +++ b/course-mw/course-actors-common/src/test/java/org/sunbird/learner/util/CourseBatchUtilTest.java @@ -21,11 +21,11 @@ import org.sunbird.builder.object.CustomObjectBuilder; import org.sunbird.builder.object.CustomObjectBuilder.CustomObjectWrapper; import org.sunbird.common.ElasticSearchHelper; -import org.sunbird.common.exception.ProjectCommonException; +import org.sunbird.exception.ProjectCommonException; import org.sunbird.common.factory.EsClientFactory; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.responsecode.ResponseCode; -import org.sunbird.common.util.JsonUtil; +import org.sunbird.keys.JsonKey; +import org.sunbird.response.ResponseCode; +import org.sunbird.utils.JsonUtil; import org.sunbird.models.course.batch.CourseBatch; import java.text.SimpleDateFormat; diff --git a/course-mw/course-actors-common/src/test/java/org/sunbird/learner/util/UtilTest.java b/course-mw/course-actors-common/src/test/java/org/sunbird/learner/util/UtilTest.java index 390e7741a..c42b8d883 100644 --- a/course-mw/course-actors-common/src/test/java/org/sunbird/learner/util/UtilTest.java +++ b/course-mw/course-actors-common/src/test/java/org/sunbird/learner/util/UtilTest.java @@ -14,8 +14,8 @@ import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.sunbird.builder.mocker.MockerBuilder; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.models.util.PropertiesCache; +import org.sunbird.keys.JsonKey; +import org.sunbird.common.PropertiesCache; import org.sunbird.dto.SearchDTO; import org.sunbird.helper.CassandraConnectionManager; import org.sunbird.helper.CassandraConnectionManagerImpl; diff --git a/course-mw/course-actors/src/main/java/org/sunbird/learner/actors/bulkupload/BaseBulkUploadActor.java b/course-mw/course-actors/src/main/java/org/sunbird/learner/actors/bulkupload/BaseBulkUploadActor.java index 5665291ce..3905ef69b 100644 --- a/course-mw/course-actors/src/main/java/org/sunbird/learner/actors/bulkupload/BaseBulkUploadActor.java +++ b/course-mw/course-actors/src/main/java/org/sunbird/learner/actors/bulkupload/BaseBulkUploadActor.java @@ -6,13 +6,13 @@ import org.apache.commons.io.IOUtils; import org.apache.commons.lang.ArrayUtils; import org.sunbird.actor.base.BaseActor; -import org.sunbird.common.exception.ProjectCommonException; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.models.util.LoggerUtil; -import org.sunbird.common.models.util.ProjectUtil; -import org.sunbird.common.models.util.ProjectUtil.BulkProcessStatus; -import org.sunbird.common.request.RequestContext; -import org.sunbird.common.responsecode.ResponseCode; +import org.sunbird.exception.ProjectCommonException; +import org.sunbird.keys.JsonKey; +import org.sunbird.logging.LoggerUtil; +import org.sunbird.common.ProjectUtil; +import org.sunbird.common.ProjectUtil.BulkProcessStatus; +import org.sunbird.request.RequestContext; +import org.sunbird.response.ResponseCode; import org.sunbird.learner.actors.bulkupload.dao.BulkUploadProcessDao; import org.sunbird.learner.actors.bulkupload.dao.impl.BulkUploadProcessDaoImpl; import org.sunbird.learner.actors.bulkupload.model.BulkUploadProcess; @@ -70,7 +70,7 @@ public void validateBulkUploadFields( } if (!(ArrayUtils.contains(csvHeaderLine, x))) { throw new ProjectCommonException( - ResponseCode.mandatoryParamsMissing.getErrorCode(), + ResponseCode.mandatoryParamsMissing, ResponseCode.mandatoryParamsMissing.getErrorMessage(), ResponseCode.CLIENT_ERROR.getResponseCode(), x); @@ -91,7 +91,7 @@ public void validateBulkUploadFields( private void throwInvalidColumnException(String invalidColumn, String validColumns) { throw new ProjectCommonException( - ResponseCode.invalidColumns.getErrorCode(), + ResponseCode.invalidColumns, ResponseCode.invalidColumns.getErrorMessage(), ResponseCode.CLIENT_ERROR.getResponseCode(), invalidColumn, diff --git a/course-mw/course-actors/src/main/java/org/sunbird/learner/actors/bulkupload/BulkUploadBackGroundJobActor.java b/course-mw/course-actors/src/main/java/org/sunbird/learner/actors/bulkupload/BulkUploadBackGroundJobActor.java index 5916eb8c5..4843f2236 100644 --- a/course-mw/course-actors/src/main/java/org/sunbird/learner/actors/bulkupload/BulkUploadBackGroundJobActor.java +++ b/course-mw/course-actors/src/main/java/org/sunbird/learner/actors/bulkupload/BulkUploadBackGroundJobActor.java @@ -10,15 +10,15 @@ import org.sunbird.common.ElasticSearchHelper; import org.sunbird.common.factory.EsClientFactory; import org.sunbird.common.inf.ElasticSearchService; -import org.sunbird.common.models.response.Response; -import org.sunbird.common.models.util.ActorOperations; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.models.util.ProjectUtil; -import org.sunbird.common.models.util.ProjectUtil.EsType; -import org.sunbird.common.models.util.TelemetryEnvKey; -import org.sunbird.common.request.Request; -import org.sunbird.common.request.RequestContext; -import org.sunbird.common.responsecode.ResponseCode; +import org.sunbird.response.Response; +import org.sunbird.operations.lms.ActorOperations; +import org.sunbird.keys.JsonKey; +import org.sunbird.common.ProjectUtil; +import org.sunbird.common.ProjectUtil.EsType; +import org.sunbird.telemetry.dto.TelemetryEnvKey; +import org.sunbird.request.Request; +import org.sunbird.request.RequestContext; +import org.sunbird.response.ResponseCode; import org.sunbird.helper.ServiceFactory; import org.sunbird.learner.actors.coursebatch.dao.UserCoursesDao; import org.sunbird.learner.actors.coursebatch.dao.impl.UserCoursesDaoImpl; diff --git a/course-mw/course-actors/src/main/java/org/sunbird/learner/actors/bulkupload/BulkUploadManagementActor.java b/course-mw/course-actors/src/main/java/org/sunbird/learner/actors/bulkupload/BulkUploadManagementActor.java index 63508a98c..3f1fb27d1 100644 --- a/course-mw/course-actors/src/main/java/org/sunbird/learner/actors/bulkupload/BulkUploadManagementActor.java +++ b/course-mw/course-actors/src/main/java/org/sunbird/learner/actors/bulkupload/BulkUploadManagementActor.java @@ -3,18 +3,17 @@ import org.apache.pekko.actor.ActorRef; import com.fasterxml.jackson.databind.ObjectMapper; import org.sunbird.cassandra.CassandraOperation; -import org.sunbird.common.exception.ProjectCommonException; -import org.sunbird.common.models.response.Response; -import org.sunbird.common.models.util.ActorOperations; -import org.sunbird.common.models.util.BulkUploadJsonKey; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.models.util.ProjectUtil; -import org.sunbird.common.models.util.PropertiesCache; -import org.sunbird.common.models.util.TelemetryEnvKey; -import org.sunbird.common.request.Request; -import org.sunbird.common.request.RequestContext; -import org.sunbird.common.responsecode.ResponseCode; -import org.sunbird.common.util.CloudStorageUtil; +import org.sunbird.exception.ProjectCommonException; +import org.sunbird.response.Response; +import org.sunbird.operations.lms.ActorOperations; +import org.sunbird.keys.BulkUploadJsonKey; +import org.sunbird.keys.JsonKey; +import org.sunbird.common.*; +import org.sunbird.telemetry.dto.TelemetryEnvKey; +import org.sunbird.request.Request; +import org.sunbird.request.RequestContext; +import org.sunbird.response.ResponseCode; +import org.sunbird.utils.CloudStorageUtil; import org.sunbird.helper.ServiceFactory; import org.sunbird.learner.actors.bulkupload.dao.impl.BulkUploadProcessDaoImpl; import org.sunbird.learner.actors.bulkupload.model.BulkUploadProcess; diff --git a/course-mw/course-actors/src/main/java/org/sunbird/learner/actors/coursebatch/CourseBatchManagementActor.java b/course-mw/course-actors/src/main/java/org/sunbird/learner/actors/coursebatch/CourseBatchManagementActor.java index 8ec57eeaa..e8af96bd0 100644 --- a/course-mw/course-actors/src/main/java/org/sunbird/learner/actors/coursebatch/CourseBatchManagementActor.java +++ b/course-mw/course-actors/src/main/java/org/sunbird/learner/actors/coursebatch/CourseBatchManagementActor.java @@ -7,16 +7,19 @@ import org.apache.commons.lang3.StringUtils; import org.sunbird.actor.base.BaseActor; import org.sunbird.common.ElasticSearchHelper; -import org.sunbird.common.exception.ProjectCommonException; +import org.sunbird.exception.ProjectCommonException; import org.sunbird.common.factory.EsClientFactory; import org.sunbird.common.inf.ElasticSearchService; -import org.sunbird.common.models.response.Response; -import org.sunbird.common.models.util.*; -import org.sunbird.common.models.util.ProjectUtil.ProgressStatus; -import org.sunbird.common.request.Request; -import org.sunbird.common.request.RequestContext; -import org.sunbird.common.responsecode.ResponseCode; -import org.sunbird.common.util.JsonUtil; +import org.sunbird.response.Response; +import org.sunbird.telemetry.dto.*; +import org.sunbird.common.ProjectUtil.ProgressStatus; +import org.sunbird.request.Request; +import org.sunbird.request.RequestContext; +import org.sunbird.response.ResponseCode; +import org.sunbird.utils.JsonUtil; +import org.sunbird.common.*; +import org.sunbird.keys.JsonKey; +import org.sunbird.operations.lms.ActorOperations; import org.sunbird.learner.actors.coursebatch.dao.CourseBatchDao; import org.sunbird.learner.actors.coursebatch.dao.impl.CourseBatchDaoImpl; import org.sunbird.learner.actors.coursebatch.service.UserCoursesService; @@ -296,7 +299,7 @@ private void validateMentors(CourseBatch courseBatch, String authToken, RequestC String mentorRootOrgId = getRootOrgFromUserMap(result); if (StringUtils.isEmpty(batchCreatorRootOrgId) || !batchCreatorRootOrgId.equals(mentorRootOrgId)) { throw new ProjectCommonException( - ResponseCode.userNotAssociatedToRootOrg.getErrorCode(), + ResponseCode.userNotAssociatedToRootOrg, ResponseCode.userNotAssociatedToRootOrg.getErrorMessage(), ResponseCode.CLIENT_ERROR.getResponseCode(), mentorId); diff --git a/course-mw/course-actors/src/main/java/org/sunbird/learner/actors/coursebatch/CourseBatchNotificationActor.java b/course-mw/course-actors/src/main/java/org/sunbird/learner/actors/coursebatch/CourseBatchNotificationActor.java index 2323b0ade..946ecf9fc 100644 --- a/course-mw/course-actors/src/main/java/org/sunbird/learner/actors/coursebatch/CourseBatchNotificationActor.java +++ b/course-mw/course-actors/src/main/java/org/sunbird/learner/actors/coursebatch/CourseBatchNotificationActor.java @@ -3,13 +3,13 @@ import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.commons.collections.CollectionUtils; import org.sunbird.actor.base.BaseActor; -import org.sunbird.common.models.util.ActorOperations; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.models.util.LoggerUtil; -import org.sunbird.common.models.util.PropertiesCache; -import org.sunbird.common.request.Request; -import org.sunbird.common.request.RequestContext; -import org.sunbird.common.util.JsonUtil; +import org.sunbird.operations.lms.ActorOperations; +import org.sunbird.keys.JsonKey; +import org.sunbird.logging.LoggerUtil; +import org.sunbird.common.PropertiesCache; +import org.sunbird.request.Request; +import org.sunbird.request.RequestContext; +import org.sunbird.utils.JsonUtil; import org.sunbird.learner.util.ContentUtil; import org.sunbird.learner.util.CourseBatchSchedulerUtil; import org.sunbird.models.course.batch.CourseBatch; diff --git a/course-mw/course-actors/src/test/java/org/sunbird/application/test/SunbirdApplicationActorTest.java b/course-mw/course-actors/src/test/java/org/sunbird/application/test/SunbirdApplicationActorTest.java index 1aabfccbf..6ed30a50c 100644 --- a/course-mw/course-actors/src/test/java/org/sunbird/application/test/SunbirdApplicationActorTest.java +++ b/course-mw/course-actors/src/test/java/org/sunbird/application/test/SunbirdApplicationActorTest.java @@ -6,7 +6,7 @@ import org.apache.pekko.actor.Props; import org.apache.pekko.testkit.javadsl.TestKit; import java.time.Duration; -import org.sunbird.common.request.Request; +import org.sunbird.request.Request; /** @author rahul */ public class SunbirdApplicationActorTest { diff --git a/course-mw/course-actors/src/test/java/org/sunbird/builder/object/CustomObjectBuilder.java b/course-mw/course-actors/src/test/java/org/sunbird/builder/object/CustomObjectBuilder.java index 350c20ef9..9b6e7ff30 100644 --- a/course-mw/course-actors/src/test/java/org/sunbird/builder/object/CustomObjectBuilder.java +++ b/course-mw/course-actors/src/test/java/org/sunbird/builder/object/CustomObjectBuilder.java @@ -8,9 +8,9 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import org.sunbird.common.models.response.Response; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.models.util.ProjectUtil; +import org.sunbird.response.Response; +import org.sunbird.keys.JsonKey; +import org.sunbird.common.ProjectUtil; import scala.concurrent.Future; import scala.concurrent.Promise; diff --git a/course-mw/course-actors/src/test/java/org/sunbird/learner/actors/SearchHandlerActorTest.java b/course-mw/course-actors/src/test/java/org/sunbird/learner/actors/SearchHandlerActorTest.java index 36c5d82fe..33db1b31b 100644 --- a/course-mw/course-actors/src/test/java/org/sunbird/learner/actors/SearchHandlerActorTest.java +++ b/course-mw/course-actors/src/test/java/org/sunbird/learner/actors/SearchHandlerActorTest.java @@ -14,13 +14,13 @@ import org.powermock.modules.junit4.PowerMockRunner; import org.sunbird.cassandraimpl.CassandraOperationImpl; import org.sunbird.common.ElasticSearchRestHighImpl; -import org.sunbird.common.exception.ProjectCommonException; +import org.sunbird.exception.ProjectCommonException; import org.sunbird.common.factory.EsClientFactory; import org.sunbird.common.inf.ElasticSearchService; -import org.sunbird.common.models.response.Response; -import org.sunbird.common.models.util.ActorOperations; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.request.Request; +import org.sunbird.response.Response; +import org.sunbird.operations.lms.ActorOperations; +import org.sunbird.keys.JsonKey; +import org.sunbird.request.Request; import org.sunbird.dto.SearchDTO; import org.sunbird.helper.ServiceFactory; import org.sunbird.learner.actors.coursebatch.dao.UserCoursesDao; diff --git a/course-mw/course-actors/src/test/java/org/sunbird/learner/actors/bulkupload/BulkUploadManagementActorTest.java b/course-mw/course-actors/src/test/java/org/sunbird/learner/actors/bulkupload/BulkUploadManagementActorTest.java index d245d0680..34409c1e5 100644 --- a/course-mw/course-actors/src/test/java/org/sunbird/learner/actors/bulkupload/BulkUploadManagementActorTest.java +++ b/course-mw/course-actors/src/test/java/org/sunbird/learner/actors/bulkupload/BulkUploadManagementActorTest.java @@ -25,14 +25,14 @@ import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.sunbird.cassandraimpl.CassandraOperationImpl; -import org.sunbird.common.exception.ProjectCommonException; -import org.sunbird.common.models.response.Response; -import org.sunbird.common.models.util.ActorOperations; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.models.util.ProjectLogger; -import org.sunbird.common.models.util.ProjectUtil; -import org.sunbird.common.request.Request; -import org.sunbird.common.request.RequestContext; +import org.sunbird.exception.ProjectCommonException; +import org.sunbird.response.Response; +import org.sunbird.operations.lms.ActorOperations; +import org.sunbird.keys.JsonKey; +import org.sunbird.logging.ProjectLogger; +import org.sunbird.common.ProjectUtil; +import org.sunbird.request.Request; +import org.sunbird.request.RequestContext; import org.sunbird.helper.ServiceFactory; import org.sunbird.learner.util.Util; diff --git a/course-mw/course-actors/src/test/java/org/sunbird/learner/actors/coursebatch/CourseBatchManagementActorTest.java b/course-mw/course-actors/src/test/java/org/sunbird/learner/actors/coursebatch/CourseBatchManagementActorTest.java index ed596fae4..cc05cc26f 100644 --- a/course-mw/course-actors/src/test/java/org/sunbird/learner/actors/coursebatch/CourseBatchManagementActorTest.java +++ b/course-mw/course-actors/src/test/java/org/sunbird/learner/actors/coursebatch/CourseBatchManagementActorTest.java @@ -25,18 +25,18 @@ import org.sunbird.builder.mocker.UserOrgMocker; import org.sunbird.builder.object.CustomObjectBuilder; import org.sunbird.common.factory.EsClientFactory; -import org.sunbird.common.models.response.Response; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.request.Request; -import org.sunbird.common.request.RequestContext; +import org.sunbird.response.Response; +import org.sunbird.keys.JsonKey; +import org.sunbird.request.Request; +import org.sunbird.request.RequestContext; import org.sunbird.helper.ServiceFactory; -import org.sunbird.kafka.client.InstructionEventGenerator; -import org.sunbird.kafka.client.KafkaClient; +import org.sunbird.kafka.InstructionEventGenerator; +import org.sunbird.kafka.KafkaClient; import org.sunbird.learner.util.ContentUtil; import org.sunbird.userorg.UserOrgServiceImpl; @RunWith(PowerMockRunner.class) -@SuppressStaticInitializationFor("org.sunbird.kafka.client.KafkaClient") +@SuppressStaticInitializationFor("org.sunbird.kafka.KafkaClient") @PrepareForTest({ServiceFactory.class, InstructionEventGenerator.class, KafkaClient.class}) @PowerMockIgnore({"javax.management.*", "javax.net.ssl.*", "javax.security.*", "jdk.internal.reflect.*", "sun.security.ssl.*", "javax.net.ssl.*", "javax.crypto.*", diff --git a/course-mw/course-actors/src/test/java/org/sunbird/learner/actors/coursebatch/CourseBatchUserManagementActorTest.java b/course-mw/course-actors/src/test/java/org/sunbird/learner/actors/coursebatch/CourseBatchUserManagementActorTest.java index 0aae3d23b..947ad17da 100644 --- a/course-mw/course-actors/src/test/java/org/sunbird/learner/actors/coursebatch/CourseBatchUserManagementActorTest.java +++ b/course-mw/course-actors/src/test/java/org/sunbird/learner/actors/coursebatch/CourseBatchUserManagementActorTest.java @@ -26,11 +26,11 @@ import org.sunbird.builder.object.CustomObjectBuilder; import org.sunbird.builder.object.CustomObjectBuilder.CustomObjectWrapper; import org.sunbird.common.factory.EsClientFactory; -import org.sunbird.common.models.response.Response; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.models.util.ProjectUtil.EsType; -import org.sunbird.common.request.Request; -import org.sunbird.common.request.RequestContext; +import org.sunbird.response.Response; +import org.sunbird.keys.JsonKey; +import org.sunbird.common.ProjectUtil.EsType; +import org.sunbird.request.Request; +import org.sunbird.request.RequestContext; import org.sunbird.helper.ServiceFactory; import org.sunbird.userorg.UserOrgServiceImpl; import scala.concurrent.Future; diff --git a/course-mw/course-actors/src/test/java/org/sunbird/learner/actors/coursemanagement/CourseBatchManagementActorTest.java b/course-mw/course-actors/src/test/java/org/sunbird/learner/actors/coursemanagement/CourseBatchManagementActorTest.java index 542a3faab..3b70bdaae 100644 --- a/course-mw/course-actors/src/test/java/org/sunbird/learner/actors/coursemanagement/CourseBatchManagementActorTest.java +++ b/course-mw/course-actors/src/test/java/org/sunbird/learner/actors/coursemanagement/CourseBatchManagementActorTest.java @@ -14,14 +14,14 @@ import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.sunbird.cassandraimpl.CassandraOperationImpl; -import org.sunbird.common.exception.ProjectCommonException; +import org.sunbird.exception.ProjectCommonException; import org.sunbird.common.factory.EsClientFactory; -import org.sunbird.common.models.response.Response; -import org.sunbird.common.models.util.ActorOperations; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.models.util.ProjectUtil; -import org.sunbird.common.request.Request; -import org.sunbird.common.responsecode.ResponseCode; +import org.sunbird.response.Response; +import org.sunbird.operations.lms.ActorOperations; +import org.sunbird.keys.JsonKey; +import org.sunbird.common.ProjectUtil; +import org.sunbird.request.Request; +import org.sunbird.response.ResponseCode; import org.sunbird.helper.ServiceFactory; import org.sunbird.learner.actors.coursebatch.CourseBatchManagementActor; import org.sunbird.learner.constants.CourseJsonKey; diff --git a/course-mw/enrolment-actor/pom.xml b/course-mw/enrolment-actor/pom.xml index 8b34b8f2b..0276bf8b9 100644 --- a/course-mw/enrolment-actor/pom.xml +++ b/course-mw/enrolment-actor/pom.xml @@ -40,8 +40,8 @@ org.sunbird - common-util - 0.0.1-SNAPSHOT + sunbird-platform-common + 1.0-SNAPSHOT org.scalatest diff --git a/course-mw/enrolment-actor/src/main/scala/org/sunbird/aggregate/CollectionSummaryAggregate.scala b/course-mw/enrolment-actor/src/main/scala/org/sunbird/aggregate/CollectionSummaryAggregate.scala index 0701157e9..ea8055d44 100644 --- a/course-mw/enrolment-actor/src/main/scala/org/sunbird/aggregate/CollectionSummaryAggregate.scala +++ b/course-mw/enrolment-actor/src/main/scala/org/sunbird/aggregate/CollectionSummaryAggregate.scala @@ -8,9 +8,12 @@ import org.joda.time.format.DateTimeFormat import org.joda.time.{DateTime, DateTimeZone} import org.sunbird.actor.base.BaseActor import org.sunbird.cache.util.RedisCacheUtil -import org.sunbird.common.models.response.Response -import org.sunbird.common.models.util.{JsonKey, ProjectLogger, ProjectUtil, TelemetryEnvKey} -import org.sunbird.common.request.{Request, RequestContext} +import org.sunbird.response.Response +import org.sunbird.keys.JsonKey +import org.sunbird.logging.ProjectLogger +import org.sunbird.common.ProjectUtil +import org.sunbird.telemetry.dto.TelemetryEnvKey +import org.sunbird.request.{Request, RequestContext} import org.sunbird.learner.actors.coursebatch.dao.CourseBatchDao import org.sunbird.learner.actors.coursebatch.dao.impl.CourseBatchDaoImpl import org.sunbird.learner.util.{JsonUtil, Util} diff --git a/course-mw/enrolment-actor/src/main/scala/org/sunbird/enrolments/AssessmentAuditRecorder.scala b/course-mw/enrolment-actor/src/main/scala/org/sunbird/enrolments/AssessmentAuditRecorder.scala index 200b3a417..646657948 100644 --- a/course-mw/enrolment-actor/src/main/scala/org/sunbird/enrolments/AssessmentAuditRecorder.scala +++ b/course-mw/enrolment-actor/src/main/scala/org/sunbird/enrolments/AssessmentAuditRecorder.scala @@ -3,8 +3,10 @@ package org.sunbird.enrolments import com.datastax.driver.core.{UDTValue, UserType} import com.fasterxml.jackson.databind.ObjectMapper import org.sunbird.cassandra.CassandraOperation -import org.sunbird.common.models.util.{JsonKey, LoggerUtil, ProjectUtil} -import org.sunbird.common.request.RequestContext +import org.sunbird.keys.JsonKey +import org.sunbird.logging.LoggerUtil +import org.sunbird.common.ProjectUtil +import org.sunbird.request.RequestContext import org.sunbird.helper.ServiceFactory import java.util import scala.collection.JavaConverters._ diff --git a/course-mw/enrolment-actor/src/main/scala/org/sunbird/enrolments/BaseEnrolmentActor.scala b/course-mw/enrolment-actor/src/main/scala/org/sunbird/enrolments/BaseEnrolmentActor.scala index 00445bd8a..8f7c39649 100644 --- a/course-mw/enrolment-actor/src/main/scala/org/sunbird/enrolments/BaseEnrolmentActor.scala +++ b/course-mw/enrolment-actor/src/main/scala/org/sunbird/enrolments/BaseEnrolmentActor.scala @@ -5,8 +5,9 @@ import org.sunbird.actor.base.BaseActor import org.sunbird.common.ElasticSearchHelper import org.sunbird.common.factory.EsClientFactory import org.sunbird.common.inf.ElasticSearchService -import org.sunbird.common.models.util.{JsonKey, ProjectUtil} -import org.sunbird.common.request.RequestContext +import org.sunbird.keys.JsonKey +import org.sunbird.common.ProjectUtil +import org.sunbird.request.RequestContext import org.sunbird.dto.SearchDTO import java.util diff --git a/course-mw/enrolment-actor/src/main/scala/org/sunbird/enrolments/ContentConsumptionActor.scala b/course-mw/enrolment-actor/src/main/scala/org/sunbird/enrolments/ContentConsumptionActor.scala index c160f4e56..2acec1d62 100644 --- a/course-mw/enrolment-actor/src/main/scala/org/sunbird/enrolments/ContentConsumptionActor.scala +++ b/course-mw/enrolment-actor/src/main/scala/org/sunbird/enrolments/ContentConsumptionActor.scala @@ -6,14 +6,16 @@ import org.apache.commons.collections4.{CollectionUtils, MapUtils} import org.apache.commons.lang3.StringUtils import org.sunbird.cassandra.CassandraOperation import org.sunbird.common.CassandraUtil -import org.sunbird.common.exception.ProjectCommonException -import org.sunbird.common.models.response.Response -import org.sunbird.common.models.util._ -import org.sunbird.common.request.{Request, RequestContext} -import org.sunbird.common.responsecode.ResponseCode -import org.sunbird.common.util.JsonUtil +import org.sunbird.exception.ProjectCommonException +import org.sunbird.response.Response +import org.sunbird.keys.JsonKey +import org.sunbird.telemetry.dto.TelemetryEnvKey +import org.sunbird.request.{Request, RequestContext} +import org.sunbird.response.ResponseCode +import org.sunbird.utils.JsonUtil +import org.sunbird.common.ProjectUtil import org.sunbird.helper.ServiceFactory -import org.sunbird.kafka.client.{InstructionEventGenerator, KafkaClient} +import org.sunbird.kafka.{InstructionEventGenerator, KafkaClient} import org.sunbird.learner.constants.{CourseJsonKey, InstructionEvent} import org.sunbird.learner.util.Util diff --git a/course-mw/enrolment-actor/src/main/scala/org/sunbird/enrolments/CourseEnrolmentActor.scala b/course-mw/enrolment-actor/src/main/scala/org/sunbird/enrolments/CourseEnrolmentActor.scala index a860aa86a..69cd9796f 100644 --- a/course-mw/enrolment-actor/src/main/scala/org/sunbird/enrolments/CourseEnrolmentActor.scala +++ b/course-mw/enrolment-actor/src/main/scala/org/sunbird/enrolments/CourseEnrolmentActor.scala @@ -6,12 +6,16 @@ import org.apache.commons.collections4.CollectionUtils import org.apache.commons.lang3.StringUtils import org.sunbird.cache.util.RedisCacheUtil import org.sunbird.common.CassandraUtil -import org.sunbird.common.exception.ProjectCommonException -import org.sunbird.common.models.response.Response -import org.sunbird.common.models.util.ProjectUtil.EnrolmentType -import org.sunbird.common.models.util._ -import org.sunbird.common.request.{Request, RequestContext} -import org.sunbird.common.responsecode.ResponseCode +import org.sunbird.exception.ProjectCommonException +import org.sunbird.response.Response +import org.sunbird.common.ProjectUtil +import org.sunbird.common.ProjectUtil.EnrolmentType +import org.sunbird.common.PropertiesCache +import org.sunbird.operations.lms.ActorOperations +import org.sunbird.keys.JsonKey +import org.sunbird.telemetry.dto.TelemetryEnvKey +import org.sunbird.request.{Request, RequestContext} +import org.sunbird.response.ResponseCode import org.sunbird.learner.actors.coursebatch.dao.impl.{CourseBatchDaoImpl, UserCoursesDaoImpl} import org.sunbird.learner.actors.coursebatch.dao.{CourseBatchDao, UserCoursesDao} import org.sunbird.learner.actors.group.dao.impl.GroupDaoImpl @@ -271,7 +275,7 @@ class CourseEnrolmentActor @Inject()(@Named("course-batch-notification-actor") c TelemetryUtil.generateCorrelatedObject(courseId, JsonKey.COURSE, correlation, correlationObject) TelemetryUtil.generateCorrelatedObject(batchId, TelemetryEnvKey.BATCH, "user.batch", correlationObject) val request: java.util.Map[String, AnyRef] = Map[String, AnyRef](JsonKey.USER_ID -> userId, JsonKey.COURSE_ID -> courseId, JsonKey.BATCH_ID -> batchId, JsonKey.COURSE_ENROLL_DATE -> data.get(JsonKey.COURSE_ENROLL_DATE), JsonKey.ACTIVE -> data.get(JsonKey.ACTIVE)).asJava - TelemetryUtil.telemetryProcessingCall(request, targetedObject, correlationObject, contextMap, "enrol") + TelemetryUtil.telemetryProcessingCall("enrol", request, targetedObject, correlationObject, contextMap) } def updateProgressData(enrolments: java.util.List[java.util.Map[String, AnyRef]], userId: String, courseIds: java.util.List[String], requestContext: RequestContext): util.List[java.util.Map[String, AnyRef]] = { diff --git a/course-mw/enrolment-actor/src/main/scala/org/sunbird/group/GroupAggregatesActor.scala b/course-mw/enrolment-actor/src/main/scala/org/sunbird/group/GroupAggregatesActor.scala index 0ff3a35db..ef3e48b12 100644 --- a/course-mw/enrolment-actor/src/main/scala/org/sunbird/group/GroupAggregatesActor.scala +++ b/course-mw/enrolment-actor/src/main/scala/org/sunbird/group/GroupAggregatesActor.scala @@ -4,11 +4,11 @@ import org.apache.commons.collections.CollectionUtils import org.apache.commons.lang3.StringUtils import org.sunbird.actor.base.BaseActor import org.sunbird.cache.util.RedisCacheUtil -import org.sunbird.common.exception.ProjectCommonException -import org.sunbird.common.models.response.Response -import org.sunbird.common.models.util.ProjectUtil -import org.sunbird.common.request.{Request, RequestContext} -import org.sunbird.common.responsecode.ResponseCode +import org.sunbird.exception.ProjectCommonException +import org.sunbird.response.Response +import org.sunbird.common.ProjectUtil +import org.sunbird.request.{Request, RequestContext} +import org.sunbird.response.ResponseCode import org.sunbird.keys.SunbirdKey import org.sunbird.learner.actors.group.dao.impl.GroupDaoImpl import org.sunbird.learner.util.JsonUtil diff --git a/course-mw/enrolment-actor/src/main/scala/org/sunbird/group/GroupAggregatesUtil.scala b/course-mw/enrolment-actor/src/main/scala/org/sunbird/group/GroupAggregatesUtil.scala index b813994a9..f216a2311 100644 --- a/course-mw/enrolment-actor/src/main/scala/org/sunbird/group/GroupAggregatesUtil.scala +++ b/course-mw/enrolment-actor/src/main/scala/org/sunbird/group/GroupAggregatesUtil.scala @@ -6,12 +6,13 @@ import java.util.Map import com.fasterxml.jackson.databind.ObjectMapper import com.mashape.unirest.http.Unirest import org.apache.commons.lang3.StringUtils -import org.sunbird.common.exception.ProjectCommonException -import org.sunbird.common.models.response.Response -import org.sunbird.common.models.util.ProjectUtil.getConfigValue -import org.sunbird.common.models.util.{JsonKey, LoggerEnum, LoggerUtil, ProjectLogger} -import org.sunbird.common.request.{HeaderParam, Request} -import org.sunbird.common.responsecode.ResponseCode +import org.sunbird.exception.ProjectCommonException +import org.sunbird.response.Response +import org.sunbird.common.ProjectUtil.getConfigValue +import org.sunbird.keys.JsonKey +import org.sunbird.logging.{LoggerEnum, LoggerUtil, ProjectLogger} +import org.sunbird.request.{HeaderParam, Request} +import org.sunbird.response.ResponseCode import org.sunbird.keys.SunbirdKey class GroupAggregatesUtil { diff --git a/course-mw/enrolment-actor/src/test/scala/org/sunbird/aggregate/CollectionSummaryAggregateTest.scala b/course-mw/enrolment-actor/src/test/scala/org/sunbird/aggregate/CollectionSummaryAggregateTest.scala index 7ef4f10df..d5b533ca7 100644 --- a/course-mw/enrolment-actor/src/test/scala/org/sunbird/aggregate/CollectionSummaryAggregateTest.scala +++ b/course-mw/enrolment-actor/src/test/scala/org/sunbird/aggregate/CollectionSummaryAggregateTest.scala @@ -14,10 +14,10 @@ import org.joda.time.{DateTime, DateTimeZone} import org.scalamock.scalatest.MockFactory import org.scalatest.{BeforeAndAfterAll, FlatSpec, Matchers} import org.sunbird.cache.util.RedisCacheUtil -import org.sunbird.common.exception.ProjectCommonException -import org.sunbird.common.models.response.Response -import org.sunbird.common.request.Request -import org.sunbird.common.responsecode.ResponseCode +import org.sunbird.exception.ProjectCommonException +import org.sunbird.response.Response +import org.sunbird.request.Request +import org.sunbird.response.ResponseCode import redis.clients.jedis.Jedis import java.io.IOException diff --git a/course-mw/enrolment-actor/src/test/scala/org/sunbird/enrolments/CourseConsumptionActorTest.scala b/course-mw/enrolment-actor/src/test/scala/org/sunbird/enrolments/CourseConsumptionActorTest.scala index 825ce2f43..ba9971502 100644 --- a/course-mw/enrolment-actor/src/test/scala/org/sunbird/enrolments/CourseConsumptionActorTest.scala +++ b/course-mw/enrolment-actor/src/test/scala/org/sunbird/enrolments/CourseConsumptionActorTest.scala @@ -8,12 +8,13 @@ import org.scalamock.scalatest.MockFactory import org.scalatest.{FlatSpec, Matchers} import org.sunbird.cassandra.CassandraOperation import org.sunbird.common.Constants -import org.sunbird.common.exception.ProjectCommonException +import org.sunbird.exception.ProjectCommonException import org.sunbird.common.inf.ElasticSearchService -import org.sunbird.common.models.response.Response -import org.sunbird.common.models.util.{JsonKey, ProjectUtil} -import org.sunbird.common.request.{Request, RequestContext} -import org.sunbird.common.responsecode.ResponseCode +import org.sunbird.response.Response +import org.sunbird.keys.JsonKey +import org.sunbird.common.ProjectUtil +import org.sunbird.request.{Request, RequestContext} +import org.sunbird.response.ResponseCode import org.sunbird.dto.SearchDTO import scala.concurrent.ExecutionContext diff --git a/course-mw/enrolment-actor/src/test/scala/org/sunbird/enrolments/CourseEnrolmentTest.scala b/course-mw/enrolment-actor/src/test/scala/org/sunbird/enrolments/CourseEnrolmentTest.scala index 77bc2a90b..3cf8beac0 100644 --- a/course-mw/enrolment-actor/src/test/scala/org/sunbird/enrolments/CourseEnrolmentTest.scala +++ b/course-mw/enrolment-actor/src/test/scala/org/sunbird/enrolments/CourseEnrolmentTest.scala @@ -6,14 +6,14 @@ import org.codehaus.jackson.map.ObjectMapper import org.scalamock.scalatest.MockFactory import org.scalatest.{FlatSpec, Matchers} import org.sunbird.cache.util.RedisCacheUtil -import org.sunbird.common.exception.ProjectCommonException -import org.sunbird.common.models.response.Response -import org.sunbird.common.models.util.ProjectUtil -import org.sunbird.common.request.{Request, RequestContext} -import org.sunbird.common.responsecode.ResponseCode +import org.sunbird.exception.ProjectCommonException +import org.sunbird.response.Response +import org.sunbird.common.ProjectUtil +import org.sunbird.request.{Request, RequestContext} +import org.sunbird.response.ResponseCode import org.sunbird.learner.actors.coursebatch.dao.impl.{CourseBatchDaoImpl, UserCoursesDaoImpl} import org.sunbird.learner.actors.group.dao.impl.GroupDaoImpl -import org.sunbird.learner.util.JsonUtil +import org.sunbird.utils.JsonUtil import org.sunbird.models.course.batch.CourseBatch import org.sunbird.models.user.courses.UserCourses diff --git a/course-mw/enrolment-actor/src/test/scala/org/sunbird/group/GroupAggregatesActorTest.scala b/course-mw/enrolment-actor/src/test/scala/org/sunbird/group/GroupAggregatesActorTest.scala index d3a7913da..c4cce5570 100644 --- a/course-mw/enrolment-actor/src/test/scala/org/sunbird/group/GroupAggregatesActorTest.scala +++ b/course-mw/enrolment-actor/src/test/scala/org/sunbird/group/GroupAggregatesActorTest.scala @@ -8,10 +8,10 @@ import org.apache.pekko.testkit.TestKit import org.scalamock.scalatest.MockFactory import org.scalatest.{FlatSpec, Matchers} import org.sunbird.cache.util.RedisCacheUtil -import org.sunbird.common.exception.ProjectCommonException -import org.sunbird.common.models.response.Response -import org.sunbird.common.request.{Request, RequestContext} -import org.sunbird.common.responsecode.ResponseCode +import org.sunbird.exception.ProjectCommonException +import org.sunbird.response.Response +import org.sunbird.request.{Request, RequestContext} +import org.sunbird.response.ResponseCode import org.sunbird.learner.actors.group.dao.impl.GroupDaoImpl import scala.concurrent.duration.FiniteDuration diff --git a/course-mw/sunbird-util/cache-utils/pom.xml b/course-mw/sunbird-util/cache-utils/pom.xml index 6fcde0753..c8ab5dcc9 100644 --- a/course-mw/sunbird-util/cache-utils/pom.xml +++ b/course-mw/sunbird-util/cache-utils/pom.xml @@ -36,8 +36,8 @@ org.sunbird - common-util - 0.0.1-SNAPSHOT + sunbird-platform-common + 1.0-SNAPSHOT ch.qos.logback diff --git a/course-mw/sunbird-util/cache-utils/src/main/scala/org/sunbird/cache/util/RedisCacheUtil.scala b/course-mw/sunbird-util/cache-utils/src/main/scala/org/sunbird/cache/util/RedisCacheUtil.scala index 7e60fe03b..59df51cc3 100644 --- a/course-mw/sunbird-util/cache-utils/src/main/scala/org/sunbird/cache/util/RedisCacheUtil.scala +++ b/course-mw/sunbird-util/cache-utils/src/main/scala/org/sunbird/cache/util/RedisCacheUtil.scala @@ -3,7 +3,8 @@ package org.sunbird.cache.util import java.time.Duration import org.apache.commons.lang3.StringUtils import org.sunbird.cache.platform.Platform -import org.sunbird.common.models.util.{JsonKey, LoggerUtil} +import org.sunbird.keys.JsonKey +import org.sunbird.logging.LoggerUtil import redis.clients.jedis.{Jedis, JedisPool, JedisPoolConfig} import scala.collection.JavaConverters._ diff --git a/course-mw/sunbird-util/sunbird-cache-utils/pom.xml b/course-mw/sunbird-util/sunbird-cache-utils/pom.xml index 81208e8e2..5813f85b7 100644 --- a/course-mw/sunbird-util/sunbird-cache-utils/pom.xml +++ b/course-mw/sunbird-util/sunbird-cache-utils/pom.xml @@ -61,8 +61,8 @@ org.sunbird - common-util - 0.0.1-SNAPSHOT + sunbird-platform-common + 1.0-SNAPSHOT org.powermock diff --git a/course-mw/sunbird-util/sunbird-cache-utils/src/main/java/org/sunbird/redis/RedisCache.java b/course-mw/sunbird-util/sunbird-cache-utils/src/main/java/org/sunbird/redis/RedisCache.java index ec42b1789..4daad3904 100644 --- a/course-mw/sunbird-util/sunbird-cache-utils/src/main/java/org/sunbird/redis/RedisCache.java +++ b/course-mw/sunbird-util/sunbird-cache-utils/src/main/java/org/sunbird/redis/RedisCache.java @@ -3,7 +3,7 @@ import org.redisson.api.RMap; import org.redisson.api.RedissonClient; import org.sunbird.cache.interfaces.Cache; -import org.sunbird.common.models.util.LoggerUtil; +import org.sunbird.logging.LoggerUtil; import org.sunbird.notification.utils.JsonUtil; import java.util.Map; diff --git a/course-mw/sunbird-util/sunbird-cache-utils/src/main/java/org/sunbird/redis/RedisConnectionManager.java b/course-mw/sunbird-util/sunbird-cache-utils/src/main/java/org/sunbird/redis/RedisConnectionManager.java index 9dd21e673..b998fa5f7 100644 --- a/course-mw/sunbird-util/sunbird-cache-utils/src/main/java/org/sunbird/redis/RedisConnectionManager.java +++ b/course-mw/sunbird-util/sunbird-cache-utils/src/main/java/org/sunbird/redis/RedisConnectionManager.java @@ -6,10 +6,10 @@ import org.redisson.config.ClusterServersConfig; import org.redisson.config.Config; import org.redisson.config.SingleServerConfig; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.models.util.LoggerEnum; -import org.sunbird.common.models.util.LoggerUtil; -import org.sunbird.common.models.util.ProjectUtil; +import org.sunbird.keys.JsonKey; +import org.sunbird.logging.LoggerEnum; +import org.sunbird.logging.LoggerUtil; +import org.sunbird.common.ProjectUtil; public class RedisConnectionManager { private static String host = ProjectUtil.getConfigValue(JsonKey.REDIS_HOST_VALUE); diff --git a/course-mw/sunbird-util/sunbird-platform-core/actor-core/pom.xml b/course-mw/sunbird-util/sunbird-platform-core/actor-core/pom.xml index 34f8159d8..74b6de72f 100644 --- a/course-mw/sunbird-util/sunbird-platform-core/actor-core/pom.xml +++ b/course-mw/sunbird-util/sunbird-platform-core/actor-core/pom.xml @@ -56,8 +56,8 @@ org.sunbird - common-util - 0.0.1-SNAPSHOT + sunbird-platform-common + 1.0-SNAPSHOT org.apache.pekko @@ -89,6 +89,7 @@ com.google.guava guava + 32.1.2-jre diff --git a/course-mw/sunbird-util/sunbird-platform-core/actor-core/src/main/java/org/sunbird/actor/core/BaseActor.java b/course-mw/sunbird-util/sunbird-platform-core/actor-core/src/main/java/org/sunbird/actor/core/BaseActor.java index d072c0a14..73e3af207 100644 --- a/course-mw/sunbird-util/sunbird-platform-core/actor-core/src/main/java/org/sunbird/actor/core/BaseActor.java +++ b/course-mw/sunbird-util/sunbird-platform-core/actor-core/src/main/java/org/sunbird/actor/core/BaseActor.java @@ -10,12 +10,12 @@ import org.sunbird.actor.router.RequestRouter; import org.sunbird.actor.service.BaseMWService; import org.sunbird.actor.service.SunbirdMWService; -import org.sunbird.common.exception.ProjectCommonException; -import org.sunbird.common.models.response.Response; -import org.sunbird.common.models.util.LoggerUtil; -import org.sunbird.common.models.util.ProjectLogger; -import org.sunbird.common.request.Request; -import org.sunbird.common.responsecode.ResponseCode; +import org.sunbird.exception.ProjectCommonException; +import org.sunbird.response.Response; +import org.sunbird.logging.LoggerUtil; +import org.sunbird.logging.ProjectLogger; +import org.sunbird.request.Request; +import org.sunbird.response.ResponseCode; import scala.concurrent.duration.Duration; public abstract class BaseActor extends UntypedAbstractActor { diff --git a/course-mw/sunbird-util/sunbird-platform-core/actor-core/src/main/java/org/sunbird/actor/core/BaseRouter.java b/course-mw/sunbird-util/sunbird-platform-core/actor-core/src/main/java/org/sunbird/actor/core/BaseRouter.java index b6722dc52..006b3315b 100644 --- a/course-mw/sunbird-util/sunbird-platform-core/actor-core/src/main/java/org/sunbird/actor/core/BaseRouter.java +++ b/course-mw/sunbird-util/sunbird-platform-core/actor-core/src/main/java/org/sunbird/actor/core/BaseRouter.java @@ -7,11 +7,11 @@ import org.apache.commons.lang3.StringUtils; import org.reflections.Reflections; import org.sunbird.actor.router.ActorConfig; -import org.sunbird.common.exception.ProjectCommonException; -import org.sunbird.common.models.util.ProjectLogger; -import org.sunbird.common.models.util.PropertiesCache; -import org.sunbird.common.request.Request; -import org.sunbird.common.responsecode.ResponseCode; +import org.sunbird.exception.ProjectCommonException; +import org.sunbird.logging.ProjectLogger; +import org.sunbird.common.PropertiesCache; +import org.sunbird.request.Request; +import org.sunbird.response.ResponseCode; /** @author Mahesh Kumar Gangula */ public abstract class BaseRouter extends BaseActor { diff --git a/course-mw/sunbird-util/sunbird-platform-core/actor-core/src/main/java/org/sunbird/actor/router/BackgroundRequestRouter.java b/course-mw/sunbird-util/sunbird-platform-core/actor-core/src/main/java/org/sunbird/actor/router/BackgroundRequestRouter.java index 85df23258..94cfb715e 100644 --- a/course-mw/sunbird-util/sunbird-platform-core/actor-core/src/main/java/org/sunbird/actor/router/BackgroundRequestRouter.java +++ b/course-mw/sunbird-util/sunbird-platform-core/actor-core/src/main/java/org/sunbird/actor/router/BackgroundRequestRouter.java @@ -5,8 +5,8 @@ import java.util.Map; import org.apache.commons.lang3.StringUtils; import org.sunbird.actor.core.BaseRouter; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.request.Request; +import org.sunbird.keys.JsonKey; +import org.sunbird.request.Request; /** @author Mahesh Kumar Gangula */ public class BackgroundRequestRouter extends BaseRouter { diff --git a/course-mw/sunbird-util/sunbird-platform-core/actor-core/src/main/java/org/sunbird/actor/router/RequestRouter.java b/course-mw/sunbird-util/sunbird-platform-core/actor-core/src/main/java/org/sunbird/actor/router/RequestRouter.java index 3452043b3..7876b32cb 100644 --- a/course-mw/sunbird-util/sunbird-platform-core/actor-core/src/main/java/org/sunbird/actor/router/RequestRouter.java +++ b/course-mw/sunbird-util/sunbird-platform-core/actor-core/src/main/java/org/sunbird/actor/router/RequestRouter.java @@ -9,12 +9,12 @@ import java.util.concurrent.TimeUnit; import org.apache.commons.lang3.StringUtils; import org.sunbird.actor.core.BaseRouter; -import org.sunbird.common.exception.ProjectCommonException; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.models.util.LoggerEnum; -import org.sunbird.common.models.util.ProjectLogger; -import org.sunbird.common.request.Request; -import org.sunbird.common.responsecode.ResponseCode; +import org.sunbird.exception.ProjectCommonException; +import org.sunbird.keys.JsonKey; +import org.sunbird.logging.LoggerEnum; +import org.sunbird.logging.ProjectLogger; +import org.sunbird.request.Request; +import org.sunbird.response.ResponseCode; import scala.concurrent.ExecutionContext; import scala.concurrent.Future; import scala.concurrent.duration.Duration; diff --git a/course-mw/sunbird-util/sunbird-platform-core/actor-core/src/main/java/org/sunbird/actor/service/BaseMWService.java b/course-mw/sunbird-util/sunbird-platform-core/actor-core/src/main/java/org/sunbird/actor/service/BaseMWService.java index b57836a0f..7a4d79184 100644 --- a/course-mw/sunbird-util/sunbird-platform-core/actor-core/src/main/java/org/sunbird/actor/service/BaseMWService.java +++ b/course-mw/sunbird-util/sunbird-platform-core/actor-core/src/main/java/org/sunbird/actor/service/BaseMWService.java @@ -14,9 +14,9 @@ import org.sunbird.actor.core.RouterMode; import org.sunbird.actor.router.BackgroundRequestRouter; import org.sunbird.actor.router.RequestRouter; -import org.sunbird.common.models.util.LoggerEnum; -import org.sunbird.common.models.util.LoggerUtil; -import org.sunbird.common.models.util.ProjectLogger; +import org.sunbird.logging.LoggerEnum; +import org.sunbird.logging.LoggerUtil; +import org.sunbird.logging.ProjectLogger; /** @author Mahesh Kumar Gangula */ public class BaseMWService { diff --git a/course-mw/sunbird-util/sunbird-platform-core/actor-core/src/main/java/org/sunbird/actor/service/SunbirdMWService.java b/course-mw/sunbird-util/sunbird-platform-core/actor-core/src/main/java/org/sunbird/actor/service/SunbirdMWService.java index 08bb8fc38..decc60f9d 100644 --- a/course-mw/sunbird-util/sunbird-platform-core/actor-core/src/main/java/org/sunbird/actor/service/SunbirdMWService.java +++ b/course-mw/sunbird-util/sunbird-platform-core/actor-core/src/main/java/org/sunbird/actor/service/SunbirdMWService.java @@ -4,8 +4,8 @@ import org.apache.pekko.actor.ActorSelection; import org.sunbird.actor.router.BackgroundRequestRouter; import org.sunbird.actor.router.RequestRouter; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.request.Request; +import org.sunbird.keys.JsonKey; +import org.sunbird.request.Request; /** @author Mahesh Kumar Gangula */ public class SunbirdMWService extends BaseMWService { diff --git a/course-mw/sunbird-util/sunbird-platform-core/actor-util/pom.xml b/course-mw/sunbird-util/sunbird-platform-core/actor-util/pom.xml index 28a9949c1..519bcefa5 100644 --- a/course-mw/sunbird-util/sunbird-platform-core/actor-util/pom.xml +++ b/course-mw/sunbird-util/sunbird-platform-core/actor-util/pom.xml @@ -54,8 +54,8 @@ org.sunbird - common-util - 0.0.1-SNAPSHOT + sunbird-platform-common + 1.0-SNAPSHOT junit diff --git a/course-mw/sunbird-util/sunbird-platform-core/actor-util/src/main/java/org/sunbird/actorutil/InterServiceCommunication.java b/course-mw/sunbird-util/sunbird-platform-core/actor-util/src/main/java/org/sunbird/actorutil/InterServiceCommunication.java index 87f3ae995..e2d9cc56d 100644 --- a/course-mw/sunbird-util/sunbird-platform-core/actor-util/src/main/java/org/sunbird/actorutil/InterServiceCommunication.java +++ b/course-mw/sunbird-util/sunbird-platform-core/actor-util/src/main/java/org/sunbird/actorutil/InterServiceCommunication.java @@ -1,7 +1,7 @@ package org.sunbird.actorutil; import org.apache.pekko.actor.ActorRef; -import org.sunbird.common.request.Request; +import org.sunbird.request.Request; import scala.concurrent.Future; /** Interface for actor to actor communication. */ diff --git a/course-mw/sunbird-util/sunbird-platform-core/actor-util/src/main/java/org/sunbird/actorutil/courseenrollment/CourseEnrollmentClient.java b/course-mw/sunbird-util/sunbird-platform-core/actor-util/src/main/java/org/sunbird/actorutil/courseenrollment/CourseEnrollmentClient.java index 7fbae5599..0d65dde8a 100644 --- a/course-mw/sunbird-util/sunbird-platform-core/actor-util/src/main/java/org/sunbird/actorutil/courseenrollment/CourseEnrollmentClient.java +++ b/course-mw/sunbird-util/sunbird-platform-core/actor-util/src/main/java/org/sunbird/actorutil/courseenrollment/CourseEnrollmentClient.java @@ -2,7 +2,7 @@ import org.apache.pekko.actor.ActorRef; import java.util.Map; -import org.sunbird.common.models.response.Response; +import org.sunbird.response.Response; public interface CourseEnrollmentClient { /** diff --git a/course-mw/sunbird-util/sunbird-platform-core/actor-util/src/main/java/org/sunbird/actorutil/courseenrollment/impl/CourseEnrollmentClientImpl.java b/course-mw/sunbird-util/sunbird-platform-core/actor-util/src/main/java/org/sunbird/actorutil/courseenrollment/impl/CourseEnrollmentClientImpl.java index ad495846e..099c56edb 100644 --- a/course-mw/sunbird-util/sunbird-platform-core/actor-util/src/main/java/org/sunbird/actorutil/courseenrollment/impl/CourseEnrollmentClientImpl.java +++ b/course-mw/sunbird-util/sunbird-platform-core/actor-util/src/main/java/org/sunbird/actorutil/courseenrollment/impl/CourseEnrollmentClientImpl.java @@ -5,11 +5,11 @@ import org.sunbird.actorutil.InterServiceCommunication; import org.sunbird.actorutil.InterServiceCommunicationFactory; import org.sunbird.actorutil.courseenrollment.CourseEnrollmentClient; -import org.sunbird.common.exception.ProjectCommonException; -import org.sunbird.common.models.response.Response; -import org.sunbird.common.models.util.ActorOperations; -import org.sunbird.common.request.Request; -import org.sunbird.common.responsecode.ResponseCode; +import org.sunbird.exception.ProjectCommonException; +import org.sunbird.response.Response; +import org.sunbird.operations.lms.ActorOperations; +import org.sunbird.request.Request; +import org.sunbird.response.ResponseCode; public class CourseEnrollmentClientImpl implements CourseEnrollmentClient { private static InterServiceCommunication interServiceCommunication = diff --git a/course-mw/sunbird-util/sunbird-platform-core/actor-util/src/main/java/org/sunbird/actorutil/email/EmailServiceClient.java b/course-mw/sunbird-util/sunbird-platform-core/actor-util/src/main/java/org/sunbird/actorutil/email/EmailServiceClient.java index 81c474caa..283f80356 100644 --- a/course-mw/sunbird-util/sunbird-platform-core/actor-util/src/main/java/org/sunbird/actorutil/email/EmailServiceClient.java +++ b/course-mw/sunbird-util/sunbird-platform-core/actor-util/src/main/java/org/sunbird/actorutil/email/EmailServiceClient.java @@ -2,7 +2,7 @@ import org.apache.pekko.actor.ActorRef; import java.util.Map; -import org.sunbird.common.models.response.Response; +import org.sunbird.response.Response; public interface EmailServiceClient { /** diff --git a/course-mw/sunbird-util/sunbird-platform-core/actor-util/src/main/java/org/sunbird/actorutil/email/impl/EmailServiceClientImpl.java b/course-mw/sunbird-util/sunbird-platform-core/actor-util/src/main/java/org/sunbird/actorutil/email/impl/EmailServiceClientImpl.java index 1d4f11217..cccf1d5f2 100644 --- a/course-mw/sunbird-util/sunbird-platform-core/actor-util/src/main/java/org/sunbird/actorutil/email/impl/EmailServiceClientImpl.java +++ b/course-mw/sunbird-util/sunbird-platform-core/actor-util/src/main/java/org/sunbird/actorutil/email/impl/EmailServiceClientImpl.java @@ -6,11 +6,11 @@ import org.sunbird.actorutil.InterServiceCommunication; import org.sunbird.actorutil.InterServiceCommunicationFactory; import org.sunbird.actorutil.email.EmailServiceClient; -import org.sunbird.common.exception.ProjectCommonException; -import org.sunbird.common.models.response.Response; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.request.Request; -import org.sunbird.common.responsecode.ResponseCode; +import org.sunbird.exception.ProjectCommonException; +import org.sunbird.response.Response; +import org.sunbird.keys.JsonKey; +import org.sunbird.request.Request; +import org.sunbird.response.ResponseCode; public class EmailServiceClientImpl implements EmailServiceClient { private static InterServiceCommunication interServiceCommunication = diff --git a/course-mw/sunbird-util/sunbird-platform-core/actor-util/src/main/java/org/sunbird/actorutil/impl/InterServiceCommunicationImpl.java b/course-mw/sunbird-util/sunbird-platform-core/actor-util/src/main/java/org/sunbird/actorutil/impl/InterServiceCommunicationImpl.java index 1c0237ffd..0d9ae7a0c 100644 --- a/course-mw/sunbird-util/sunbird-platform-core/actor-util/src/main/java/org/sunbird/actorutil/impl/InterServiceCommunicationImpl.java +++ b/course-mw/sunbird-util/sunbird-platform-core/actor-util/src/main/java/org/sunbird/actorutil/impl/InterServiceCommunicationImpl.java @@ -5,12 +5,12 @@ import org.apache.pekko.util.Timeout; import java.util.concurrent.TimeUnit; import org.sunbird.actorutil.InterServiceCommunication; -import org.sunbird.common.exception.ProjectCommonException; -import org.sunbird.common.models.util.LoggerEnum; -import org.sunbird.common.models.util.LoggerUtil; -import org.sunbird.common.models.util.ProjectLogger; -import org.sunbird.common.request.Request; -import org.sunbird.common.responsecode.ResponseCode; +import org.sunbird.exception.ProjectCommonException; +import org.sunbird.logging.LoggerEnum; +import org.sunbird.logging.LoggerUtil; +import org.sunbird.logging.ProjectLogger; +import org.sunbird.request.Request; +import org.sunbird.response.ResponseCode; import scala.concurrent.Await; import scala.concurrent.Future; import scala.concurrent.duration.Duration; diff --git a/course-mw/sunbird-util/sunbird-platform-core/actor-util/src/main/java/org/sunbird/actorutil/location/impl/LocationClientImpl.java b/course-mw/sunbird-util/sunbird-platform-core/actor-util/src/main/java/org/sunbird/actorutil/location/impl/LocationClientImpl.java index 2403d22a3..acacf3251 100644 --- a/course-mw/sunbird-util/sunbird-platform-core/actor-util/src/main/java/org/sunbird/actorutil/location/impl/LocationClientImpl.java +++ b/course-mw/sunbird-util/sunbird-platform-core/actor-util/src/main/java/org/sunbird/actorutil/location/impl/LocationClientImpl.java @@ -11,11 +11,13 @@ import org.sunbird.actorutil.InterServiceCommunication; import org.sunbird.actorutil.InterServiceCommunicationFactory; import org.sunbird.actorutil.location.LocationClient; -import org.sunbird.common.exception.ProjectCommonException; -import org.sunbird.common.models.response.Response; -import org.sunbird.common.models.util.*; -import org.sunbird.common.request.Request; -import org.sunbird.common.responsecode.ResponseCode; +import org.sunbird.exception.ProjectCommonException; +import org.sunbird.response.Response; +import org.sunbird.logging.LoggerUtil; +import org.sunbird.keys.*; +import org.sunbird.operations.lms.LocationActorOperation; +import org.sunbird.request.Request; +import org.sunbird.response.ResponseCode; import org.sunbird.models.location.Location; import org.sunbird.models.location.apirequest.UpsertLocationRequest; diff --git a/course-mw/sunbird-util/sunbird-platform-core/actor-util/src/main/java/org/sunbird/actorutil/org/impl/OrganisationClientImpl.java b/course-mw/sunbird-util/sunbird-platform-core/actor-util/src/main/java/org/sunbird/actorutil/org/impl/OrganisationClientImpl.java index de1a84fd6..7f565576e 100644 --- a/course-mw/sunbird-util/sunbird-platform-core/actor-util/src/main/java/org/sunbird/actorutil/org/impl/OrganisationClientImpl.java +++ b/course-mw/sunbird-util/sunbird-platform-core/actor-util/src/main/java/org/sunbird/actorutil/org/impl/OrganisationClientImpl.java @@ -8,16 +8,16 @@ import org.sunbird.actorutil.InterServiceCommunicationFactory; import org.sunbird.actorutil.org.OrganisationClient; import org.sunbird.common.ElasticSearchHelper; -import org.sunbird.common.exception.ProjectCommonException; +import org.sunbird.exception.ProjectCommonException; import org.sunbird.common.factory.EsClientFactory; import org.sunbird.common.inf.ElasticSearchService; -import org.sunbird.common.models.response.Response; -import org.sunbird.common.models.util.ActorOperations; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.models.util.LoggerUtil; -import org.sunbird.common.models.util.ProjectUtil; -import org.sunbird.common.request.Request; -import org.sunbird.common.responsecode.ResponseCode; +import org.sunbird.response.Response; +import org.sunbird.operations.lms.ActorOperations; +import org.sunbird.keys.JsonKey; +import org.sunbird.logging.LoggerUtil; +import org.sunbird.common.ProjectUtil; +import org.sunbird.request.Request; +import org.sunbird.response.ResponseCode; import org.sunbird.dto.SearchDTO; import org.sunbird.models.organisation.Organisation; import scala.concurrent.Future; diff --git a/course-mw/sunbird-util/sunbird-platform-core/actor-util/src/main/java/org/sunbird/actorutil/systemsettings/impl/SystemSettingClientImpl.java b/course-mw/sunbird-util/sunbird-platform-core/actor-util/src/main/java/org/sunbird/actorutil/systemsettings/impl/SystemSettingClientImpl.java index 52d820383..be0015b07 100644 --- a/course-mw/sunbird-util/sunbird-platform-core/actor-util/src/main/java/org/sunbird/actorutil/systemsettings/impl/SystemSettingClientImpl.java +++ b/course-mw/sunbird-util/sunbird-platform-core/actor-util/src/main/java/org/sunbird/actorutil/systemsettings/impl/SystemSettingClientImpl.java @@ -9,14 +9,14 @@ import org.sunbird.actorutil.InterServiceCommunication; import org.sunbird.actorutil.InterServiceCommunicationFactory; import org.sunbird.actorutil.systemsettings.SystemSettingClient; -import org.sunbird.common.exception.ProjectCommonException; -import org.sunbird.common.models.response.Response; -import org.sunbird.common.models.util.ActorOperations; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.models.util.LoggerEnum; -import org.sunbird.common.models.util.ProjectLogger; -import org.sunbird.common.request.Request; -import org.sunbird.common.responsecode.ResponseCode; +import org.sunbird.exception.ProjectCommonException; +import org.sunbird.response.Response; +import org.sunbird.operations.lms.ActorOperations; +import org.sunbird.keys.JsonKey; +import org.sunbird.logging.LoggerEnum; +import org.sunbird.logging.ProjectLogger; +import org.sunbird.request.Request; +import org.sunbird.response.ResponseCode; import org.sunbird.models.systemsetting.SystemSetting; public class SystemSettingClientImpl implements SystemSettingClient { diff --git a/course-mw/sunbird-util/sunbird-platform-core/actor-util/src/main/java/org/sunbird/actorutil/user/impl/UserClientImpl.java b/course-mw/sunbird-util/sunbird-platform-core/actor-util/src/main/java/org/sunbird/actorutil/user/impl/UserClientImpl.java index 287e53b70..2999eb62c 100644 --- a/course-mw/sunbird-util/sunbird-platform-core/actor-util/src/main/java/org/sunbird/actorutil/user/impl/UserClientImpl.java +++ b/course-mw/sunbird-util/sunbird-platform-core/actor-util/src/main/java/org/sunbird/actorutil/user/impl/UserClientImpl.java @@ -6,13 +6,17 @@ import org.sunbird.actorutil.InterServiceCommunicationFactory; import org.sunbird.actorutil.user.UserClient; import org.sunbird.common.ElasticSearchHelper; -import org.sunbird.common.exception.ProjectCommonException; +import org.sunbird.exception.ProjectCommonException; import org.sunbird.common.factory.EsClientFactory; import org.sunbird.common.inf.ElasticSearchService; -import org.sunbird.common.models.response.Response; -import org.sunbird.common.models.util.*; -import org.sunbird.common.request.Request; -import org.sunbird.common.responsecode.ResponseCode; +import org.sunbird.response.Response; +import org.sunbird.logging.ProjectLogger; +import org.sunbird.logging.LoggerEnum; +import org.sunbird.keys.JsonKey; +import org.sunbird.common.ProjectUtil; +import org.sunbird.operations.lms.ActorOperations; +import org.sunbird.request.Request; +import org.sunbird.response.ResponseCode; import org.sunbird.dto.SearchDTO; import scala.concurrent.Future; diff --git a/course-mw/sunbird-util/sunbird-platform-core/auth-verifier/pom.xml b/course-mw/sunbird-util/sunbird-platform-core/auth-verifier/pom.xml deleted file mode 100644 index 8032aa191..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/auth-verifier/pom.xml +++ /dev/null @@ -1,125 +0,0 @@ - - - - sunbird-platform-core - org.sunbird - 1.0-SNAPSHOT - - 4.0.0 - - auth-verifier - - UTF-8 - UTF-8 - - - - com.fasterxml.jackson.core - jackson-databind - ${jackson.version} - - - org.sunbird - common-util - 0.0.1-SNAPSHOT - - - org.powermock - powermock-api-mockito2 - ${powermock.version} - test - - - org.powermock - powermock-module-junit4 - ${powermock.version} - test - - - ch.qos.logback - logback-classic - 1.2.3 - - - ch.qos.logback - logback-core - 1.2.3 - - - net.logstash.logback - logstash-logback-encoder - ${logstash-logback-encoder.version} - - - com.fasterxml.jackson.core - jackson-core - - - com.fasterxml.jackson.core - jackson-databind - - - com.fasterxml.jackson.core - jackson-annotations - - - - - - - ${basedir}/src/main/java - ${basedir}/src/test/java - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.8.1 - - 11 - - - - org.apache.maven.plugins - maven-surefire-plugin - 3.0.0 - - - --illegal-access=warn - - - - - - - - - - org.jacoco - jacoco-maven-plugin - ${jacoco-maven-plugin.version} - - ${basedir}/target/coverage-reports/jacoco-unit.exec - ${basedir}/target/coverage-reports/jacoco-unit.exec - - - - jacoco-initialize - - prepare-agent - - - - jacoco-site - package - - report - - - - - - - \ No newline at end of file diff --git a/course-mw/sunbird-util/sunbird-platform-core/auth-verifier/src/main/java/org/sunbird/auth/verifier/AccessTokenValidator.java b/course-mw/sunbird-util/sunbird-platform-core/auth-verifier/src/main/java/org/sunbird/auth/verifier/AccessTokenValidator.java deleted file mode 100644 index 32a3ad8de..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/auth-verifier/src/main/java/org/sunbird/auth/verifier/AccessTokenValidator.java +++ /dev/null @@ -1,120 +0,0 @@ -package org.sunbird.auth.verifier; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.apache.commons.collections4.MapUtils; -import org.apache.commons.lang3.StringUtils; -import org.keycloak.common.util.Time; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.models.util.KeyCloakConnectionProvider; -import org.sunbird.common.models.util.LoggerUtil; - -import java.util.Collections; -import java.util.Map; - -public class AccessTokenValidator { - - private static ObjectMapper mapper = new ObjectMapper(); - private static LoggerUtil logger = new LoggerUtil(AccessTokenValidator.class); - - private static Map validateToken(String token, boolean checkActive) throws JsonProcessingException { - String[] tokenElements = token.split("\\."); - String header = tokenElements[0]; - String body = tokenElements[1]; - String signature = tokenElements[2]; - String payLoad = header + JsonKey.DOT_SEPARATOR + body; - Map headerData = - mapper.readValue(new String(decodeFromBase64(header)), Map.class); - String keyId = headerData.get("kid").toString(); - boolean isValid = - CryptoUtil.verifyRSASign( - payLoad, - decodeFromBase64(signature), - KeyManager.getPublicKey(keyId).getPublicKey(), - JsonKey.SHA_256_WITH_RSA); - if (isValid) { - Map tokenBody = - mapper.readValue(new String(decodeFromBase64(body)), Map.class); - if(checkActive) { - boolean isExp = isExpired((Integer) tokenBody.get("exp")); - if (isExp) { - return Collections.EMPTY_MAP; - } - } - return tokenBody; - } - return Collections.EMPTY_MAP; - } - - /** - * managedtoken is validated and requestedByUserID, requestedForUserID values are validated - * aganist the managedEncToken - * - * @param managedEncToken - * @param requestedByUserId - * @param requestedForUserId - * @return - */ - public static String verifyManagedUserToken( - String managedEncToken, String requestedByUserId, String requestedForUserId, String loggingHeaders) { - String managedFor = JsonKey.UNAUTHORIZED; - try { - Map payload = validateToken(managedEncToken, true); - if (MapUtils.isNotEmpty(payload)) { - String parentId = (String) payload.get(JsonKey.PARENT_ID); - String muaId = (String) payload.get(JsonKey.SUB); - logger.info( null, - "AccessTokenValidator: parent uuid: " - + parentId - + " managedBy uuid: " - + muaId - + " requestedByUserID: " - + requestedByUserId - + " requestedForUserId: " - + requestedForUserId); - boolean isValid = - parentId.equalsIgnoreCase(requestedByUserId); - if(!muaId.equalsIgnoreCase(requestedForUserId)) { - logger.info( null,"RequestedFor userid : " + requestedForUserId + " is not matching with the muaId : " + muaId + " Headers: " + loggingHeaders); - } - if (isValid) { - managedFor = muaId; - } - } - } catch (Exception ex) { - logger.error(null, "Exception in AccessTokenValidator: verify ", ex); - } - return managedFor; - } - - public static String verifyUserToken(String token, boolean checkActive) { - String userId = JsonKey.UNAUTHORIZED; - try { - Map payload = validateToken(token, checkActive); - if (MapUtils.isNotEmpty(payload) && checkIss((String) payload.get("iss"))) { - userId = (String) payload.get(JsonKey.SUB); - if (StringUtils.isNotBlank(userId)) { - int pos = userId.lastIndexOf(":"); - userId = userId.substring(pos + 1); - } - } - } catch (Exception ex) { - logger.error(null, "Exception in verifyUserAccessToken: verify ", ex); - } - return userId; - } - - private static boolean checkIss(String iss) { - String realmUrl = - KeyCloakConnectionProvider.SSO_URL + "realms/" + KeyCloakConnectionProvider.SSO_REALM; - return (realmUrl.equalsIgnoreCase(iss)); - } - - private static boolean isExpired(Integer expiration) { - return (Time.currentTime() > expiration); - } - - private static byte[] decodeFromBase64(String data) { - return Base64Util.decode(data, 11); - } -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/auth-verifier/src/main/java/org/sunbird/auth/verifier/Base64Util.java b/course-mw/sunbird-util/sunbird-platform-core/auth-verifier/src/main/java/org/sunbird/auth/verifier/Base64Util.java deleted file mode 100644 index 619330d24..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/auth-verifier/src/main/java/org/sunbird/auth/verifier/Base64Util.java +++ /dev/null @@ -1,741 +0,0 @@ -package org.sunbird.auth.verifier; - -/* - * Copyright (C) 2010 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -import java.io.UnsupportedEncodingException; - -/** - * Utilities for encoding and decoding the Base64 representation of - * binary data. See RFCs 2045 and 3548. - */ -public class Base64Util { - /** - * Default values for encoder/decoder flags. - */ - public static final int DEFAULT = 0; - - /** - * Encoder flag bit to omit the padding '=' characters at the end - * of the output (if any). - */ - public static final int NO_PADDING = 1; - - /** - * Encoder flag bit to omit all line terminators (i.e., the output - * will be on one long line). - */ - public static final int NO_WRAP = 2; - - /** - * Encoder flag bit to indicate lines should be terminated with a - * CRLF pair instead of just an LF. Has no effect if {@code - * NO_WRAP} is specified as well. - */ - public static final int CRLF = 4; - - /** - * Encoder/decoder flag bit to indicate using the "URL and - * filename safe" variant of Base64 (see RFC 3548 section 4) where - * {@code -} and {@code _} are used in place of {@code +} and - * {@code /}. - */ - public static final int URL_SAFE = 8; - - /** - * Flag to pass to {Base64OutputStream} to indicate that it - * should not close the output stream it is wrapping when it - * itself is closed. - */ - public static final int NO_CLOSE = 16; - - // -------------------------------------------------------- - // shared code - // -------------------------------------------------------- - - private Base64Util() { - } // don't instantiate - - // -------------------------------------------------------- - // decoding - // -------------------------------------------------------- - - /** - * Decode the Base64-encoded data in input and return the data in - * a new byte array. - *

- *

The padding '=' characters at the end are considered optional, but - * if any are present, there must be the correct number of them. - * - * @param str the input String to decode, which is converted to - * bytes using the default charset - * @param flags controls certain features of the decoded output. - * Pass {@code DEFAULT} to decode standard Base64. - * @throws IllegalArgumentException if the input contains - * incorrect padding - */ - public static byte[] decode(String str, int flags) { - return decode(str.getBytes(), flags); - } - - /** - * Decode the Base64-encoded data in input and return the data in - * a new byte array. - *

- *

The padding '=' characters at the end are considered optional, but - * if any are present, there must be the correct number of them. - * - * @param input the input array to decode - * @param flags controls certain features of the decoded output. - * Pass {@code DEFAULT} to decode standard Base64. - * @throws IllegalArgumentException if the input contains - * incorrect padding - */ - public static byte[] decode(byte[] input, int flags) { - return decode(input, 0, input.length, flags); - } - - /** - * Decode the Base64-encoded data in input and return the data in - * a new byte array. - *

- *

The padding '=' characters at the end are considered optional, but - * if any are present, there must be the correct number of them. - * - * @param input the data to decode - * @param offset the position within the input array at which to start - * @param len the number of bytes of input to decode - * @param flags controls certain features of the decoded output. - * Pass {@code DEFAULT} to decode standard Base64. - * @throws IllegalArgumentException if the input contains - * incorrect padding - */ - public static byte[] decode(byte[] input, int offset, int len, int flags) { - // Allocate space for the most data the input could represent. - // (It could contain less if it contains whitespace, etc.) - Decoder decoder = new Decoder(flags, new byte[len * 3 / 4]); - - if (!decoder.process(input, offset, len, true)) { - throw new IllegalArgumentException("bad base-64"); - } - - // Maybe we got lucky and allocated exactly enough output space. - if (decoder.op == decoder.output.length) { - return decoder.output; - } - - // Need to shorten the array, so allocate a new one of the - // right size and copy. - byte[] temp = new byte[decoder.op]; - System.arraycopy(decoder.output, 0, temp, 0, decoder.op); - return temp; - } - - /** - * Base64-encode the given data and return a newly allocated - * String with the result. - * - * @param input the data to encode - * @param flags controls certain features of the encoded output. - * Passing {@code DEFAULT} results in output that - * adheres to RFC 2045. - */ - public static String encodeToString(byte[] input, int flags) { - try { - return new String(encode(input, flags), "US-ASCII"); - } catch (UnsupportedEncodingException e) { - // US-ASCII is guaranteed to be available. - throw new AssertionError(e); - } - } - - // -------------------------------------------------------- - // encoding - // -------------------------------------------------------- - - /** - * Base64-encode the given data and return a newly allocated - * String with the result. - * - * @param input the data to encode - * @param offset the position within the input array at which to - * start - * @param len the number of bytes of input to encode - * @param flags controls certain features of the encoded output. - * Passing {@code DEFAULT} results in output that - * adheres to RFC 2045. - */ - public static String encodeToString(byte[] input, int offset, int len, int flags) { - try { - return new String(encode(input, offset, len, flags), "US-ASCII"); - } catch (UnsupportedEncodingException e) { - // US-ASCII is guaranteed to be available. - throw new AssertionError(e); - } - } - - /** - * Base64-encode the given data and return a newly allocated - * byte[] with the result. - * - * @param input the data to encode - * @param flags controls certain features of the encoded output. - * Passing {@code DEFAULT} results in output that - * adheres to RFC 2045. - */ - public static byte[] encode(byte[] input, int flags) { - return encode(input, 0, input.length, flags); - } - - /** - * Base64-encode the given data and return a newly allocated - * byte[] with the result. - * - * @param input the data to encode - * @param offset the position within the input array at which to - * start - * @param len the number of bytes of input to encode - * @param flags controls certain features of the encoded output. - * Passing {@code DEFAULT} results in output that - * adheres to RFC 2045. - */ - public static byte[] encode(byte[] input, int offset, int len, int flags) { - Encoder encoder = new Encoder(flags, null); - - // Compute the exact length of the array we will produce. - int output_len = len / 3 * 4; - - // Account for the tail of the data and the padding bytes, if any. - if (encoder.do_padding) { - if (len % 3 > 0) { - output_len += 4; - } - } else { - switch (len % 3) { - case 0: - break; - case 1: - output_len += 2; - break; - case 2: - output_len += 3; - break; - } - } - - // Account for the newlines, if any. - if (encoder.do_newline && len > 0) { - output_len += (((len - 1) / (3 * Encoder.LINE_GROUPS)) + 1) * - (encoder.do_cr ? 2 : 1); - } - - encoder.output = new byte[output_len]; - encoder.process(input, offset, len, true); - - assert encoder.op == output_len; - - return encoder.output; - } - - /* package */ static abstract class Coder { - public byte[] output; - public int op; - - /** - * Encode/decode another block of input data. this.output is - * provided by the caller, and must be big enough to hold all - * the coded data. On exit, this.opwill be set to the length - * of the coded data. - * - * @param finish true if this is the final call to process for - * this object. Will finalize the coder state and - * include any final bytes in the output. - * @return true if the input so far is good; false if some - * error has been detected in the input stream.. - */ - public abstract boolean process(byte[] input, int offset, int len, boolean finish); - - /** - * @return the maximum number of bytes a call to process() - * could produce for the given number of input bytes. This may - * be an overestimate. - */ - public abstract int maxOutputSize(int len); - } - - /* package */ static class Decoder extends Coder { - /** - * Lookup table for turning bytes into their position in the - * Base64 alphabet. - */ - private static final int DECODE[] = { - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, - 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -2, -1, -1, - -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, - 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, - -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, - 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - }; - - /** - * Decode lookup table for the "web safe" variant (RFC 3548 - * sec. 4) where - and _ replace + and /. - */ - private static final int DECODE_WEBSAFE[] = { - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, - 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -2, -1, -1, - -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, - 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, 63, - -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, - 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - }; - - /** - * Non-data values in the DECODE arrays. - */ - private static final int SKIP = -1; - private static final int EQUALS = -2; - final private int[] alphabet; - /** - * States 0-3 are reading through the next input tuple. - * State 4 is having read one '=' and expecting exactly - * one more. - * State 5 is expecting no more data or padding characters - * in the input. - * State 6 is the error state; an error has been detected - * in the input and no future input can "fix" it. - */ - private int state; // state number (0 to 6) - private int value; - - public Decoder(int flags, byte[] output) { - this.output = output; - - alphabet = ((flags & URL_SAFE) == 0) ? DECODE : DECODE_WEBSAFE; - state = 0; - value = 0; - } - - /** - * @return an overestimate for the number of bytes {@code - * len} bytes could decode to. - */ - public int maxOutputSize(int len) { - return len * 3 / 4 + 10; - } - - /** - * Decode another block of input data. - * - * @return true if the state machine is still healthy. false if - * bad base-64 data has been detected in the input stream. - */ - public boolean process(byte[] input, int offset, int len, boolean finish) { - if (this.state == 6) return false; - - int p = offset; - len += offset; - - // Using local variables makes the decoder about 12% - // faster than if we manipulate the member variables in - // the loop. (Even alphabet makes a measurable - // difference, which is somewhat surprising to me since - // the member variable is final.) - int state = this.state; - int value = this.value; - int op = 0; - final byte[] output = this.output; - final int[] alphabet = this.alphabet; - - while (p < len) { - // Try the fast path: we're starting a new tuple and the - // next four bytes of the input stream are all data - // bytes. This corresponds to going through states - // 0-1-2-3-0. We expect to use this method for most of - // the data. - // - // If any of the next four bytes of input are non-data - // (whitespace, etc.), value will end up negative. (All - // the non-data values in decode are small negative - // numbers, so shifting any of them up and or'ing them - // together will result in a value with its top bit set.) - // - // You can remove this whole block and the output should - // be the same, just slower. - if (state == 0) { - while (p + 4 <= len && - (value = ((alphabet[input[p] & 0xff] << 18) | - (alphabet[input[p + 1] & 0xff] << 12) | - (alphabet[input[p + 2] & 0xff] << 6) | - (alphabet[input[p + 3] & 0xff]))) >= 0) { - output[op + 2] = (byte) value; - output[op + 1] = (byte) (value >> 8); - output[op] = (byte) (value >> 16); - op += 3; - p += 4; - } - if (p >= len) break; - } - - // The fast path isn't available -- either we've read a - // partial tuple, or the next four input bytes aren't all - // data, or whatever. Fall back to the slower state - // machine implementation. - - int d = alphabet[input[p++] & 0xff]; - - switch (state) { - case 0: - if (d >= 0) { - value = d; - ++state; - } else if (d != SKIP) { - this.state = 6; - return false; - } - break; - - case 1: - if (d >= 0) { - value = (value << 6) | d; - ++state; - } else if (d != SKIP) { - this.state = 6; - return false; - } - break; - - case 2: - if (d >= 0) { - value = (value << 6) | d; - ++state; - } else if (d == EQUALS) { - // Emit the last (partial) output tuple; - // expect exactly one more padding character. - output[op++] = (byte) (value >> 4); - state = 4; - } else if (d != SKIP) { - this.state = 6; - return false; - } - break; - - case 3: - if (d >= 0) { - // Emit the output triple and return to state 0. - value = (value << 6) | d; - output[op + 2] = (byte) value; - output[op + 1] = (byte) (value >> 8); - output[op] = (byte) (value >> 16); - op += 3; - state = 0; - } else if (d == EQUALS) { - // Emit the last (partial) output tuple; - // expect no further data or padding characters. - output[op + 1] = (byte) (value >> 2); - output[op] = (byte) (value >> 10); - op += 2; - state = 5; - } else if (d != SKIP) { - this.state = 6; - return false; - } - break; - - case 4: - if (d == EQUALS) { - ++state; - } else if (d != SKIP) { - this.state = 6; - return false; - } - break; - - case 5: - if (d != SKIP) { - this.state = 6; - return false; - } - break; - } - } - - if (!finish) { - // We're out of input, but a future call could provide - // more. - this.state = state; - this.value = value; - this.op = op; - return true; - } - - // Done reading input. Now figure out where we are left in - // the state machine and finish up. - - switch (state) { - case 0: - // Output length is a multiple of three. Fine. - break; - case 1: - // Read one extra input byte, which isn't enough to - // make another output byte. Illegal. - this.state = 6; - return false; - case 2: - // Read two extra input bytes, enough to emit 1 more - // output byte. Fine. - output[op++] = (byte) (value >> 4); - break; - case 3: - // Read three extra input bytes, enough to emit 2 more - // output bytes. Fine. - output[op++] = (byte) (value >> 10); - output[op++] = (byte) (value >> 2); - break; - case 4: - // Read one padding '=' when we expected 2. Illegal. - this.state = 6; - return false; - case 5: - // Read all the padding '='s we expected and no more. - // Fine. - break; - } - - this.state = state; - this.op = op; - return true; - } - } - - /* package */ static class Encoder extends Coder { - /** - * Emit a new line every this many output tuples. Corresponds to - * a 76-character line length (the maximum allowable according to - * RFC 2045). - */ - public static final int LINE_GROUPS = 19; - - /** - * Lookup table for turning Base64 alphabet positions (6 bits) - * into output bytes. - */ - private static final byte ENCODE[] = { - 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', - 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', - 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', - 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/', - }; - - /** - * Lookup table for turning Base64 alphabet positions (6 bits) - * into output bytes. - */ - private static final byte ENCODE_WEBSAFE[] = { - 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', - 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', - 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', - 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', '_', - }; - final public boolean do_padding; - final public boolean do_newline; - final public boolean do_cr; - final private byte[] tail; - final private byte[] alphabet; - /* package */ int tailLen; - private int count; - - public Encoder(int flags, byte[] output) { - this.output = output; - - do_padding = (flags & NO_PADDING) == 0; - do_newline = (flags & NO_WRAP) == 0; - do_cr = (flags & CRLF) != 0; - alphabet = ((flags & URL_SAFE) == 0) ? ENCODE : ENCODE_WEBSAFE; - - tail = new byte[2]; - tailLen = 0; - - count = do_newline ? LINE_GROUPS : -1; - } - - /** - * @return an overestimate for the number of bytes {@code - * len} bytes could encode to. - */ - public int maxOutputSize(int len) { - return len * 8 / 5 + 10; - } - - public boolean process(byte[] input, int offset, int len, boolean finish) { - // Using local variables makes the encoder about 9% faster. - final byte[] alphabet = this.alphabet; - final byte[] output = this.output; - int op = 0; - int count = this.count; - - int p = offset; - len += offset; - int v = -1; - - // First we need to concatenate the tail of the previous call - // with any input bytes available now and see if we can empty - // the tail. - - switch (tailLen) { - case 0: - // There was no tail. - break; - - case 1: - if (p + 2 <= len) { - // A 1-byte tail with at least 2 bytes of - // input available now. - v = ((tail[0] & 0xff) << 16) | - ((input[p++] & 0xff) << 8) | - (input[p++] & 0xff); - tailLen = 0; - } - ; - break; - - case 2: - if (p + 1 <= len) { - // A 2-byte tail with at least 1 byte of input. - v = ((tail[0] & 0xff) << 16) | - ((tail[1] & 0xff) << 8) | - (input[p++] & 0xff); - tailLen = 0; - } - break; - } - - if (v != -1) { - output[op++] = alphabet[(v >> 18) & 0x3f]; - output[op++] = alphabet[(v >> 12) & 0x3f]; - output[op++] = alphabet[(v >> 6) & 0x3f]; - output[op++] = alphabet[v & 0x3f]; - if (--count == 0) { - if (do_cr) output[op++] = '\r'; - output[op++] = '\n'; - count = LINE_GROUPS; - } - } - - // At this point either there is no tail, or there are fewer - // than 3 bytes of input available. - - // The main loop, turning 3 input bytes into 4 output bytes on - // each iteration. - while (p + 3 <= len) { - v = ((input[p] & 0xff) << 16) | - ((input[p + 1] & 0xff) << 8) | - (input[p + 2] & 0xff); - output[op] = alphabet[(v >> 18) & 0x3f]; - output[op + 1] = alphabet[(v >> 12) & 0x3f]; - output[op + 2] = alphabet[(v >> 6) & 0x3f]; - output[op + 3] = alphabet[v & 0x3f]; - p += 3; - op += 4; - if (--count == 0) { - if (do_cr) output[op++] = '\r'; - output[op++] = '\n'; - count = LINE_GROUPS; - } - } - - if (finish) { - // Finish up the tail of the input. Note that we need to - // consume any bytes in tail before any bytes - // remaining in input; there should be at most two bytes - // total. - - if (p - tailLen == len - 1) { - int t = 0; - v = ((tailLen > 0 ? tail[t++] : input[p++]) & 0xff) << 4; - tailLen -= t; - output[op++] = alphabet[(v >> 6) & 0x3f]; - output[op++] = alphabet[v & 0x3f]; - if (do_padding) { - output[op++] = '='; - output[op++] = '='; - } - if (do_newline) { - if (do_cr) output[op++] = '\r'; - output[op++] = '\n'; - } - } else if (p - tailLen == len - 2) { - int t = 0; - v = (((tailLen > 1 ? tail[t++] : input[p++]) & 0xff) << 10) | - (((tailLen > 0 ? tail[t++] : input[p++]) & 0xff) << 2); - tailLen -= t; - output[op++] = alphabet[(v >> 12) & 0x3f]; - output[op++] = alphabet[(v >> 6) & 0x3f]; - output[op++] = alphabet[v & 0x3f]; - if (do_padding) { - output[op++] = '='; - } - if (do_newline) { - if (do_cr) output[op++] = '\r'; - output[op++] = '\n'; - } - } else if (do_newline && op > 0 && count != LINE_GROUPS) { - if (do_cr) output[op++] = '\r'; - output[op++] = '\n'; - } - - assert tailLen == 0; - assert p == len; - } else { - // Save the leftovers in tail to be consumed on the next - // call to encodeInternal. - - if (p == len - 1) { - tail[tailLen++] = input[p]; - } else if (p == len - 2) { - tail[tailLen++] = input[p]; - tail[tailLen++] = input[p + 1]; - } - } - - this.op = op; - this.count = count; - - return true; - } - } -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/auth-verifier/src/main/java/org/sunbird/auth/verifier/CryptoUtil.java b/course-mw/sunbird-util/sunbird-platform-core/auth-verifier/src/main/java/org/sunbird/auth/verifier/CryptoUtil.java deleted file mode 100755 index a95307278..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/auth-verifier/src/main/java/org/sunbird/auth/verifier/CryptoUtil.java +++ /dev/null @@ -1,25 +0,0 @@ -package org.sunbird.auth.verifier; - -import java.nio.charset.Charset; -import java.security.*; - -public class CryptoUtil { - private static final Charset US_ASCII = Charset.forName("US-ASCII"); - - public static boolean verifyRSASign(String payLoad, byte[] signature, PublicKey key, String algorithm) { - Signature sign; - try { - sign = Signature.getInstance(algorithm); - sign.initVerify(key); - sign.update(payLoad.getBytes(US_ASCII)); - return sign.verify(signature); - } catch (NoSuchAlgorithmException e) { - return false; - } catch (InvalidKeyException e){ - return false; - } catch (SignatureException e){ - return false; - } - } - -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/auth-verifier/src/test/java/org/sunbird/auth/verifier/AccessTokenValidatorTest.java b/course-mw/sunbird-util/sunbird-platform-core/auth-verifier/src/test/java/org/sunbird/auth/verifier/AccessTokenValidatorTest.java deleted file mode 100644 index 93c479abb..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/auth-verifier/src/test/java/org/sunbird/auth/verifier/AccessTokenValidatorTest.java +++ /dev/null @@ -1,170 +0,0 @@ -package org.sunbird.auth.verifier; - -import static org.junit.Assert.*; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import java.security.PublicKey; -import java.util.HashMap; -import java.util.Map; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.keycloak.common.util.Time; -import org.mockito.Mockito; -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; - -@RunWith(PowerMockRunner.class) -@PrepareForTest({CryptoUtil.class, KeyManager.class, Base64Util.class}) -@PowerMockIgnore({"javax.management.*"}) -public class AccessTokenValidatorTest { - @Test - public void verifyUserAccessToken() throws JsonProcessingException { - PowerMockito.mockStatic(CryptoUtil.class); - PowerMockito.mockStatic(Base64Util.class); - PowerMockito.mockStatic(KeyManager.class); - 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 payload = new HashMap<>(); - int expTime = Time.currentTime() + 3600000; - payload.put("exp", expTime); - payload.put("iss", "nullrealms/null"); - 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())) - .thenReturn(true); - String userId = - AccessTokenValidator.verifyUserToken( - "eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICI5emhhVnZDbl81OEtheHpldHBzYXNZQ2lEallkemJIX3U2LV93SDk4SEc0In0.eyJqdGkiOiI5ZmQzNzgzYy01YjZmLTQ3OWQtYmMzYy0yZWEzOGUzZmRmYzgiLCJleHAiOjE1MDUxMTQyNDYsIm5iZiI6MCwiaWF0IjoxNTA1MTEzNjQ2LCJpc3MiOiJodHRwOi8vbG9jYWxob3N0OjgwODAvYXV0aC9yZWFsbXMvbWFzdGVyIiwiYXVkIjoic2VjdXJpdHktYWRtaW4tY29uc29sZSIsInN1YiI6ImIzYTZkMTY4LWJjZmQtNDE2MS1hYzVmLTljZjYyODIyNzlmMyIsInR5cCI6IkJlYXJlciIsImF6cCI6InNlY3VyaXR5LWFkbWluLWNvbnNvbGUiLCJub25jZSI6ImMxOGVlMDM2LTAyMWItNGVlZC04NWVhLTc0MjMyYzg2ZmI4ZSIsImF1dGhfdGltZSI6MTUwNTExMzY0Niwic2Vzc2lvbl9zdGF0ZSI6ImRiZTU2NDlmLTY4MDktNDA3NS05Njk5LTVhYjIyNWMwZTkyMiIsImFjciI6IjEiLCJhbGxvd2VkLW9yaWdpbnMiOltdLCJyZXNvdXJjZV9hY2Nlc3MiOnt9LCJuYW1lIjoiTWFuemFydWwgaGFxdWUiLCJwcmVmZXJyZWRfdXNlcm5hbWUiOiJ0ZXN0MTIzNDU2NyIsImdpdmVuX25hbWUiOiJNYW56YXJ1bCBoYXF1ZSIsImVtYWlsIjoidGVzdDEyM0B0LmNvbSJ9.Xdjqe16MSkiR94g-Uj_pVZ2L3gnIdKpkJ6aB82W_w_c3yEmx1mXYBdkxe4zMz3ks4OX_PWwSFEbJECHcnujUwF6Ula0xtXTfuESB9hFyiWHtVAhuh5UlCCwPnsihv5EqK6u-Qzo0aa6qZOiQK3Zo7FLpnPUDxn4yHyo3mRZUiWf76KTl8PhSMoXoWxcR2vGW0b-cPixILTZPV0xXUZoozCui70QnvTgOJDWqr7y80EWDkS4Ptn-QM3q2nJlw63mZreOG3XTdraOlcKIP5vFK992dyyHlYGqWVzigortS9Ah4cprFVuLlX8mu1cQvqHBtW-0Dq_JlcTMaztEnqvJ6XA" - , true); - assertNotNull(userId); - } - - @Test - public void verifyUserAccessTokenInvalidToken() throws JsonProcessingException { - PowerMockito.mockStatic(CryptoUtil.class); - PowerMockito.mockStatic(Base64Util.class); - PowerMockito.mockStatic(KeyManager.class); - 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 payload = new HashMap<>(); - int expTime = Time.currentTime() + 3600000; - payload.put("exp", expTime); - payload.put("kid", "kid"); - 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())) - .thenReturn(false); - String userId = - AccessTokenValidator.verifyUserToken( - "eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICI5emhhVnZDbl81OEtheHpldHBzYXNZQ2lEallkemJIX3U2LV93SDk4SEc0In0.eyJqdGkiOiI5ZmQzNzgzYy01YjZmLTQ3OWQtYmMzYy0yZWEzOGUzZmRmYzgiLCJleHAiOjE1MDUxMTQyNDYsIm5iZiI6MCwiaWF0IjoxNTA1MTEzNjQ2LCJpc3MiOiJodHRwOi8vbG9jYWxob3N0OjgwODAvYXV0aC9yZWFsbXMvbWFzdGVyIiwiYXVkIjoic2VjdXJpdHktYWRtaW4tY29uc29sZSIsInN1YiI6ImIzYTZkMTY4LWJjZmQtNDE2MS1hYzVmLTljZjYyODIyNzlmMyIsInR5cCI6IkJlYXJlciIsImF6cCI6InNlY3VyaXR5LWFkbWluLWNvbnNvbGUiLCJub25jZSI6ImMxOGVlMDM2LTAyMWItNGVlZC04NWVhLTc0MjMyYzg2ZmI4ZSIsImF1dGhfdGltZSI6MTUwNTExMzY0Niwic2Vzc2lvbl9zdGF0ZSI6ImRiZTU2NDlmLTY4MDktNDA3NS05Njk5LTVhYjIyNWMwZTkyMiIsImFjciI6IjEiLCJhbGxvd2VkLW9yaWdpbnMiOltdLCJyZXNvdXJjZV9hY2Nlc3MiOnt9LCJuYW1lIjoiTWFuemFydWwgaGFxdWUiLCJwcmVmZXJyZWRfdXNlcm5hbWUiOiJ0ZXN0MTIzNDU2NyIsImdpdmVuX25hbWUiOiJNYW56YXJ1bCBoYXF1ZSIsImVtYWlsIjoidGVzdDEyM0B0LmNvbSJ9.Xdjqe16MSkiR94g-Uj_pVZ2L3gnIdKpkJ6aB82W_w_c3yEmx1mXYBdkxe4zMz3ks4OX_PWwSFEbJECHcnujUwF6Ula0xtXTfuESB9hFyiWHtVAhuh5UlCCwPnsihv5EqK6u-Qzo0aa6qZOiQK3Zo7FLpnPUDxn4yHyo3mRZUiWf76KTl8PhSMoXoWxcR2vGW0b-cPixILTZPV0xXUZoozCui70QnvTgOJDWqr7y80EWDkS4Ptn-QM3q2nJlw63mZreOG3XTdraOlcKIP5vFK992dyyHlYGqWVzigortS9Ah4cprFVuLlX8mu1cQvqHBtW-0Dq_JlcTMaztEnqvJ6XA", - true); - assertEquals("Unauthorized", userId); - } - - @Test - public void verifyUserAccessTokenExpiredToken() throws JsonProcessingException { - PowerMockito.mockStatic(CryptoUtil.class); - PowerMockito.mockStatic(Base64Util.class); - PowerMockito.mockStatic(KeyManager.class); - 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 payload = new HashMap<>(); - int expTime = Time.currentTime() - 3600000; - payload.put("exp", expTime); - payload.put("kid", "kid"); - 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())) - .thenReturn(true); - String userId = - AccessTokenValidator.verifyUserToken( - "eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICI5emhhVnZDbl81OEtheHpldHBzYXNZQ2lEallkemJIX3U2LV93SDk4SEc0In0.eyJqdGkiOiI5ZmQzNzgzYy01YjZmLTQ3OWQtYmMzYy0yZWEzOGUzZmRmYzgiLCJleHAiOjE1MDUxMTQyNDYsIm5iZiI6MCwiaWF0IjoxNTA1MTEzNjQ2LCJpc3MiOiJodHRwOi8vbG9jYWxob3N0OjgwODAvYXV0aC9yZWFsbXMvbWFzdGVyIiwiYXVkIjoic2VjdXJpdHktYWRtaW4tY29uc29sZSIsInN1YiI6ImIzYTZkMTY4LWJjZmQtNDE2MS1hYzVmLTljZjYyODIyNzlmMyIsInR5cCI6IkJlYXJlciIsImF6cCI6InNlY3VyaXR5LWFkbWluLWNvbnNvbGUiLCJub25jZSI6ImMxOGVlMDM2LTAyMWItNGVlZC04NWVhLTc0MjMyYzg2ZmI4ZSIsImF1dGhfdGltZSI6MTUwNTExMzY0Niwic2Vzc2lvbl9zdGF0ZSI6ImRiZTU2NDlmLTY4MDktNDA3NS05Njk5LTVhYjIyNWMwZTkyMiIsImFjciI6IjEiLCJhbGxvd2VkLW9yaWdpbnMiOltdLCJyZXNvdXJjZV9hY2Nlc3MiOnt9LCJuYW1lIjoiTWFuemFydWwgaGFxdWUiLCJwcmVmZXJyZWRfdXNlcm5hbWUiOiJ0ZXN0MTIzNDU2NyIsImdpdmVuX25hbWUiOiJNYW56YXJ1bCBoYXF1ZSIsImVtYWlsIjoidGVzdDEyM0B0LmNvbSJ9.Xdjqe16MSkiR94g-Uj_pVZ2L3gnIdKpkJ6aB82W_w_c3yEmx1mXYBdkxe4zMz3ks4OX_PWwSFEbJECHcnujUwF6Ula0xtXTfuESB9hFyiWHtVAhuh5UlCCwPnsihv5EqK6u-Qzo0aa6qZOiQK3Zo7FLpnPUDxn4yHyo3mRZUiWf76KTl8PhSMoXoWxcR2vGW0b-cPixILTZPV0xXUZoozCui70QnvTgOJDWqr7y80EWDkS4Ptn-QM3q2nJlw63mZreOG3XTdraOlcKIP5vFK992dyyHlYGqWVzigortS9Ah4cprFVuLlX8mu1cQvqHBtW-0Dq_JlcTMaztEnqvJ6XA", - true); - assertEquals("Unauthorized", userId); - } - - @Test - public void verifyToken() throws JsonProcessingException { - PowerMockito.mockStatic(CryptoUtil.class); - PowerMockito.mockStatic(Base64Util.class); - PowerMockito.mockStatic(KeyManager.class); - 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 payload = new HashMap<>(); - int expTime = Time.currentTime() + 3600000; - payload.put("exp", expTime); - payload.put("requestedByUserId", "386c7960-7f85-4a24-8131-a8aba519ce7d"); - payload.put("requestedForUserId", "386c7960-7f85-4a24-8131-a8aba519ce7e"); - payload.put("kid", "kid"); - payload.put("parentId", "386c7960-7f85-4a24-8131-a8aba519ce7d"); - payload.put("sub", "386c7960-7f85-4a24-8131-a8aba519ce7e"); - 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())) - .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-a8aba519ce7d", ""); - assertNotNull(userId); - } - - @Test - public void verifyTokenWithNullParentId() throws JsonProcessingException { - PowerMockito.mockStatic(CryptoUtil.class); - PowerMockito.mockStatic(Base64Util.class); - PowerMockito.mockStatic(KeyManager.class); - 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 payload = new HashMap<>(); - int expTime = Time.currentTime() + 3600000; - payload.put("exp", expTime); - payload.put("requestedByUserId", "386c7960-7f85-4a24-8131-a8aba519ce7d"); - payload.put("requestedForUserId", "386c7960-7f85-4a24-8131-a8aba519ce7e"); - payload.put("kid", "kid"); - payload.put("sub", "386c7960-7f85-4a24-8131-a8aba519ce7e"); - 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())) - .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-a8aba519ce7d",""); - } catch (Exception e) { - assertNotNull(e); - } - } -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/auth-verifier/src/test/java/org/sunbird/auth/verifier/KeyManagerTest.java b/course-mw/sunbird-util/sunbird-platform-core/auth-verifier/src/test/java/org/sunbird/auth/verifier/KeyManagerTest.java deleted file mode 100644 index 5ac88f9ab..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/auth-verifier/src/test/java/org/sunbird/auth/verifier/KeyManagerTest.java +++ /dev/null @@ -1,32 +0,0 @@ -package org.sunbird.auth.verifier; - -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; - -import java.security.PublicKey; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; -import org.sunbird.common.models.util.PropertiesCache; - -@RunWith(PowerMockRunner.class) -@PrepareForTest({PropertiesCache.class}) -@PowerMockIgnore({"javax.management.*"}) -public class KeyManagerTest { - - @Test - public void testLoadPublicKey() throws Exception { - PublicKey key = - KeyManager.loadPublicKey( - "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAysH/wWtg0IjBL1JZZDYvUJC42JCxVobalckr2/3d3eEiWkk7Zh/4DAPYOs4UPjAevTs5VMUjq9EZu/u4H5hNzoVmYNvhtxbhWNY3n4mxpA4Lgt4sNGiGYNNGrN34ML+7+TR3Z1dlrhA271PiuanHI11YymskQRPhBfuwK923Kl/lgI4rS9OQ4GnkvwkUPvMUIRfNt8wL9uTbWm3V9p8VTcmQbW+pPw9QhO9v95NOgXQrLnT8xwnzQE6UCTY2al3B0fc3ULmcxvK+7P1R3/0w1qJLEKSiHl0xnv4WNEfS+2UmN+8jfdSCfoyVIglQl5/tb05j89nfZZp8k24AWLxIJQIDAQAB"); - assertNotNull(key); - } - - @Test - public void testGetPublicKey() { - KeyData key = KeyManager.getPublicKey("keyId"); - assertNull(key); - } -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/.gitignore b/course-mw/sunbird-util/sunbird-platform-core/common-util/.gitignore deleted file mode 100644 index 55977f8f9..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/.gitignore +++ /dev/null @@ -1,7 +0,0 @@ -/target/ -.classpath -.project -.settings -/bin/ - -*.iml diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/exception/ProjectCommonException.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/exception/ProjectCommonException.java deleted file mode 100644 index 4fddff180..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/exception/ProjectCommonException.java +++ /dev/null @@ -1,128 +0,0 @@ -/** */ -package org.sunbird.common.exception; - -import java.text.MessageFormat; -import org.apache.commons.lang3.StringUtils; -import org.sunbird.common.responsecode.ResponseCode; - -/** - * This exception will be used across all backend code. This will send status code and error message - * - * @author Manzarul.Haque - */ -public class ProjectCommonException extends RuntimeException { - - /** serialVersionUID. */ - private static final long serialVersionUID = 1L; - /** code String code ResponseCode. */ - private String code; - /** message String ResponseCode. */ - private String message; - /** responseCode int ResponseCode. */ - private int responseCode; - - /** - * This code is for client to identify the error and based on that do the message localization. - * - * @return String - */ - public String getCode() { - return code; - } - - /** - * To set the client code. - * - * @param code String - */ - public void setCode(String code) { - this.code = code; - } - - /** - * message for client in english. - * - * @return String - */ - @Override - public String getMessage() { - return message; - } - - /** @param message String */ - public void setMessage(String message) { - this.message = message; - } - - /** - * This method will provide response code, this code will be used in response header. - * - * @return int - */ - public int getResponseCode() { - return responseCode; - } - - /** @param responseCode int */ - public void setResponseCode(int responseCode) { - this.responseCode = responseCode; - } - - /** - * three argument constructor. - * - * @param code String - * @param message String - * @param responseCode int - */ - public ProjectCommonException(String code, String message, int responseCode) { - super(); - this.code = code; - this.message = message; - this.responseCode = responseCode; - } - - public ProjectCommonException( - String code, String messageWithPlaceholder, int responseCode, String... placeholderValue) { - super(); - this.code = code; - this.message = MessageFormat.format(messageWithPlaceholder, placeholderValue); - this.responseCode = responseCode; - } - - public static void throwClientErrorException(ResponseCode responseCode, String exceptionMessage) { - throw new ProjectCommonException( - responseCode.getErrorCode(), - StringUtils.isBlank(exceptionMessage) ? responseCode.getErrorMessage() : exceptionMessage, - ResponseCode.CLIENT_ERROR.getResponseCode()); - } - - public static void throwResourceNotFoundException() { - throw new ProjectCommonException( - ResponseCode.resourceNotFound.getErrorCode(), - ResponseCode.resourceNotFound.getErrorMessage(), - ResponseCode.RESOURCE_NOT_FOUND.getResponseCode()); - } - - public static void throwServerErrorException(ResponseCode responseCode, String exceptionMessage) { - throw new ProjectCommonException( - responseCode.getErrorCode(), - StringUtils.isBlank(exceptionMessage) ? responseCode.getErrorMessage() : exceptionMessage, - ResponseCode.SERVER_ERROR.getResponseCode()); - } - - public static void throwServerErrorException(ResponseCode responseCode) { - throwServerErrorException(responseCode, responseCode.getErrorMessage()); - } - - public static void throwClientErrorException(ResponseCode responseCode) { - throwClientErrorException(responseCode, responseCode.getErrorMessage()); - } - - public static void throwUnauthorizedErrorException() { - throw new ProjectCommonException( - ResponseCode.unAuthorized.getErrorCode(), - ResponseCode.unAuthorized.getErrorMessage(), - ResponseCode.UNAUTHORIZED.getResponseCode()); - } -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/exception/package-info.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/exception/package-info.java deleted file mode 100644 index 18e910d04..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/exception/package-info.java +++ /dev/null @@ -1,3 +0,0 @@ -/** */ -/** @author Manzarul */ -package org.sunbird.common.exception; diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/hash/HashGeneratorUtil.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/hash/HashGeneratorUtil.java deleted file mode 100644 index 0f28662df..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/hash/HashGeneratorUtil.java +++ /dev/null @@ -1,33 +0,0 @@ -package org.sunbird.common.hash; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import org.sunbird.common.models.util.datasecurity.OneWayHashing; - -public class HashGeneratorUtil { - private static List primes = null; - private static int MAX_NUMBER = 300; - private static int numPrimes = 7; - - private static List getPrimes() { - List list = new ArrayList<>(); - boolean prime[] = new boolean[MAX_NUMBER + 1]; - Arrays.fill(prime, true); - for (int p = 2; p * p <= MAX_NUMBER; p++) { - if (prime[p] == true) { - for (int i = p * p; i <= MAX_NUMBER; i += p) prime[i] = false; - } - } - for (int i = numPrimes; i <= MAX_NUMBER; i++) { - if (prime[i] == true) { - list.add(i); - } - } - return list; - } - - public static String getHashCode(String jsonString) { - return OneWayHashing.encryptVal(jsonString); - } -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/response/ClientErrorResponse.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/response/ClientErrorResponse.java deleted file mode 100644 index d1f8c7fd5..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/response/ClientErrorResponse.java +++ /dev/null @@ -1,21 +0,0 @@ -package org.sunbird.common.models.response; - -import org.sunbird.common.exception.ProjectCommonException; -import org.sunbird.common.responsecode.ResponseCode; - -public class ClientErrorResponse extends Response { - - private ProjectCommonException exception = null; - - public ClientErrorResponse() { - responseCode = ResponseCode.CLIENT_ERROR; - } - - public ProjectCommonException getException() { - return exception; - } - - public void setException(ProjectCommonException exception) { - this.exception = exception; - } -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/response/HttpUtilResponse.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/response/HttpUtilResponse.java deleted file mode 100644 index 501b957f2..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/response/HttpUtilResponse.java +++ /dev/null @@ -1,33 +0,0 @@ -package org.sunbird.common.models.response; - -public class HttpUtilResponse { - private String body; - private int statusCode; - - public HttpUtilResponse() {} - - public HttpUtilResponse(String body, int statusCode) { - this.body = body; - this.statusCode = statusCode; - } - - /** @return the body */ - public String getBody() { - return body; - } - - /** @param body the body to set */ - public void setBody(String body) { - this.body = body; - } - - /** @return the statusCode */ - public int getStatusCode() { - return statusCode; - } - - /** @param statusCode the statusCode to set */ - public void setStatusCode(int statusCode) { - this.statusCode = statusCode; - } -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/response/Params.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/response/Params.java deleted file mode 100644 index 9d740f5c6..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/response/Params.java +++ /dev/null @@ -1,68 +0,0 @@ -package org.sunbird.common.models.response; - -import java.io.Serializable; - -/** - * Common response parameter bean - * - * @author Manzarul - */ -public class Params implements Serializable { - - private static final long serialVersionUID = -8786004970726124473L; - private String resmsgid; - private String msgid; - private String err; - private String status; - private String errmsg; - - /** @return String */ - public String getResmsgid() { - return resmsgid; - } - - /** @param resmsgid Stirng */ - public void setResmsgid(String resmsgid) { - this.resmsgid = resmsgid; - } - - /** @return Stirng */ - public String getMsgid() { - return msgid; - } - - /** @param msgid String */ - public void setMsgid(String msgid) { - this.msgid = msgid; - } - - /** @return String */ - public String getErr() { - return err; - } - - /** @param err String */ - public void setErr(String err) { - this.err = err; - } - - /** @return String */ - public String getStatus() { - return status; - } - - /** @param status Stirng */ - public void setStatus(String status) { - this.status = status; - } - - /** @return Stirng */ - public String getErrmsg() { - return errmsg; - } - - /** @param errmsg Stirng */ - public void setErrmsg(String errmsg) { - this.errmsg = errmsg; - } -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/response/Response.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/response/Response.java deleted file mode 100644 index 24e3d9ef3..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/response/Response.java +++ /dev/null @@ -1,153 +0,0 @@ -package org.sunbird.common.models.response; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import org.sunbird.common.responsecode.ResponseCode; - -import java.io.Serializable; -import java.util.HashMap; -import java.util.Map; - -/** - * This is a common response class for all the layer. All layer will send same response object. - * - * @author Manzarul - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public class Response implements Serializable, Cloneable { - - private static final long serialVersionUID = -3773253896160786443L; - protected String id; - protected String ver; - protected String ts; - protected ResponseParams params; - protected ResponseCode responseCode = ResponseCode.OK; - protected Map result = new HashMap<>(); - - /** - * This will provide request unique id. - * - * @return String - */ - public String getId() { - return id; - } - - /** - * set the unique id - * - * @param id String - */ - public void setId(String id) { - this.id = id; - } - - /** - * this will provide api version - * - * @return String - */ - public String getVer() { - return ver; - } - - /** - * set the api version - * - * @param ver String - */ - public void setVer(String ver) { - this.ver = ver; - } - - /** - * this will provide complete time value - * - * @return String - */ - public String getTs() { - return ts; - } - - /** - * set the time value - * - * @param ts String - */ - public void setTs(String ts) { - this.ts = ts; - } - - /** @return Map */ - public Map getResult() { - return result; - } - - /** - * @param key String - * @return Object - */ - public Object get(String key) { - return result.get(key); - } - - /** - * @param key String - * @param vo Object - */ - public void put(String key, Object vo) { - result.put(key, vo); - } - - /** @param map Map */ - public void putAll(Map map) { - result.putAll(map); - } - - public boolean containsKey(String key) { - return result.containsKey(key); - } - - /** - * This will provide response parameter object. - * - * @return ResponseParams - */ - public ResponseParams getParams() { - return params; - } - - /** - * set the response parameter object. - * - * @param params ResponseParams - */ - public void setParams(ResponseParams params) { - this.params = params; - } - - /** - * Set the response code for header. - * - * @param code ResponseCode - */ - public void setResponseCode(ResponseCode code) { - this.responseCode = code; - } - - /** - * get the response code - * - * @return ResponseCode - */ - public ResponseCode getResponseCode() { - return this.responseCode; - } - - public Response clone(Response response) { - try { - return (Response) response.clone(); - } catch (CloneNotSupportedException e) { - return null; - } - } -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/response/package-info.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/response/package-info.java deleted file mode 100644 index db2569117..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/response/package-info.java +++ /dev/null @@ -1,3 +0,0 @@ -/** */ -/** @author Manzarul */ -package org.sunbird.common.models.response; diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/AuditLog.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/AuditLog.java deleted file mode 100644 index 9c5d6d721..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/AuditLog.java +++ /dev/null @@ -1,70 +0,0 @@ -package org.sunbird.common.models.util; - -import java.util.Map; - -public class AuditLog { - - private String requestId; - private String objectId; - private String objectType; - private String operationType; - private String date; - private String userId; - private Map logRecord; - - public String getRequestId() { - return requestId; - } - - public void setRequestId(String requestId) { - this.requestId = requestId; - } - - public String getObjectId() { - return objectId; - } - - public void setObjectId(String objectId) { - this.objectId = objectId; - } - - public String getObjectType() { - return objectType; - } - - public void setObjectType(String objectType) { - this.objectType = objectType; - } - - public String getOperationType() { - return operationType; - } - - public void setOperationType(String operationType) { - this.operationType = operationType; - } - - public String getDate() { - return date; - } - - public void setDate(String date) { - this.date = date; - } - - public String getUserId() { - return userId; - } - - public void setUserId(String userId) { - this.userId = userId; - } - - public Map getLogRecord() { - return logRecord; - } - - public void setLogRecord(Map logRecord) { - this.logRecord = logRecord; - } -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/CassandraPropertyReader.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/CassandraPropertyReader.java deleted file mode 100644 index 9b73fb648..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/CassandraPropertyReader.java +++ /dev/null @@ -1,66 +0,0 @@ -package org.sunbird.common.models.util; - -import java.io.IOException; -import java.io.InputStream; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.stream.Collectors; - -/** - * This class will be used to read cassandratablecolumn properties file. - * - * @author Amit Kumar - */ -public class CassandraPropertyReader { - - private final Properties properties = new Properties(); - private static final String file = "cassandratablecolumn.properties"; - private static CassandraPropertyReader cassandraPropertyReader = null; - public LoggerUtil logger = new LoggerUtil(this.getClass()); - - /** private default constructor */ - private CassandraPropertyReader() { - InputStream in = this.getClass().getClassLoader().getResourceAsStream(file); - try { - properties.load(in); - } catch (IOException e) { - logger.error(null, "Error in properties cache", e); - } - } - - public static CassandraPropertyReader getInstance() { - if (null == cassandraPropertyReader) { - synchronized (CassandraPropertyReader.class) { - if (null == cassandraPropertyReader) { - cassandraPropertyReader = new CassandraPropertyReader(); - } - } - } - return cassandraPropertyReader; - } - - /** - * Method to read value from resource file . - * - * @param key property value to read - * @return value corresponding to given key if found else will return key itself. - */ - public String readProperty(String key) { - return properties.getProperty(key) != null ? properties.getProperty(key) : key; - } - - /** - * Method to read value from resource file . - * - * @param key to read property key - * @return key corresponding to given value if found else will return value itself. - */ - public String readPropertyValue(String key) { - List> s = properties.entrySet() - .stream() - .filter(entry -> key.equals(entry.getValue())) - .collect(Collectors.toList()); - return s.isEmpty() ? key : (String) s.get(0).getKey(); - } -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/CustomLogFormat.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/CustomLogFormat.java deleted file mode 100644 index ca00a5919..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/CustomLogFormat.java +++ /dev/null @@ -1,47 +0,0 @@ -package org.sunbird.common.models.util; - -import org.sunbird.common.request.RequestContext; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; - -public class CustomLogFormat { - private String edataType = "system"; - private String eid = "LOG"; - private String ver = "3.0"; - private Map edata = new HashMap<>(); - private Map eventMap = new HashMap<>(); - - CustomLogFormat(RequestContext requestContext, String msg, Map object, Map params) { - if (params != null) - this.edata.put("params", new ArrayList>(){{add(params);}}); - setEventMap(requestContext, msg); - if (object != null) - this.eventMap.put("object", object); - } - - public Map getEventMap() { - return this.eventMap; - } - - public void setEventMap(RequestContext requestContext, String msg) { - this.edata.put("type", edataType); - this.edata.put("requestid", requestContext.getRequestId()); - this.edata.put("message", msg); - this.edata.put("level", requestContext.getLoggerLevel()); - this.eventMap.putAll(new HashMap() {{ - put("eid", eid); - put("ets", System.currentTimeMillis()); - put("ver", ver); - put("mid", "LOG:" + UUID.randomUUID().toString()); - put("context", requestContext.getContextMap()); - put("actor", new HashMap() {{ - put("id", requestContext.getActorId()); - put("type", requestContext.getActorType()); - }}); - put("edata", edata); - }}); - } -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/DbConstant.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/DbConstant.java deleted file mode 100644 index 7ea3d27f9..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/DbConstant.java +++ /dev/null @@ -1,21 +0,0 @@ -package org.sunbird.common.models.util; - -/** - * Enum contains the database related constants - * - * @author arvind - */ -public enum DbConstant { - sunbirdKeyspaceName("sunbird"), - userTableName("user"); - - DbConstant(String value) { - this.value = value; - } - - String value; - - public String getValue() { - return this.value; - } -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/LoggerEnum.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/LoggerEnum.java deleted file mode 100644 index fc78efae5..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/LoggerEnum.java +++ /dev/null @@ -1,11 +0,0 @@ -package org.sunbird.common.models.util; - -/** @author Manzarul */ -public enum LoggerEnum { - INFO, - WARN, - DEBUG, - ERROR, - BE_LOG, - PERF_LOG; -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/LoggerUtil.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/LoggerUtil.java deleted file mode 100644 index a054b5276..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/LoggerUtil.java +++ /dev/null @@ -1,144 +0,0 @@ -package org.sunbird.common.models.util; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.sunbird.common.exception.ProjectCommonException; -import org.sunbird.common.request.Request; -import org.sunbird.common.request.RequestContext; -import org.sunbird.common.responsecode.ResponseCode; -import org.sunbird.telemetry.util.TelemetryEvents; -import org.sunbird.telemetry.util.TelemetryWriter; - -import java.util.Map; - -public class LoggerUtil { - - private Logger logger; - private String infoLevel = "INFO"; - private String debugLevel = "DEBUG"; - private String errorLevel = "ERROR"; - private String warnLevel = "WARN"; - private Logger defaultLogger; - private final ObjectMapper mapper = new ObjectMapper(); - - public LoggerUtil(Class c) { - logger = LoggerFactory.getLogger(c); - defaultLogger = LoggerFactory.getLogger("defaultLogger"); - } - - public void info(RequestContext requestContext, String message, Map object, - Map param) { - if (requestContext != null) { - requestContext.setLoggerLevel(infoLevel); - logger.info(jsonMapper(requestContext, message, object, param)); - } else - defaultLogger.info(message); - } - - public void info(RequestContext requestContext, String message) { - info(requestContext, message, null, null); - } - - public void debug(RequestContext requestContext, String message, Map object, - Map param) { - if (isDebugEnabled(requestContext)) { - requestContext.setLoggerLevel(debugLevel); - logger.info(jsonMapper(requestContext, message, object, param)); - } else - defaultLogger.debug(message); - } - - public void debug(RequestContext requestContext, String message) { - debug(requestContext, message, null, null); - } - - public void error(RequestContext requestContext, String message, Map object, - Map param, Throwable e) { - if (requestContext != null) { - requestContext.setLoggerLevel(errorLevel); - logger.error(jsonMapper(requestContext, message, object, param), e); - } else - defaultLogger.error(message, e); - } - - public void error(RequestContext requestContext, String message, Map object, - Map param, Throwable e, Map telemetryInfo) { - if (requestContext != null) { - requestContext.setLoggerLevel(errorLevel); - logger.error(jsonMapper(requestContext, message, object, param), e); - } else - defaultLogger.error(message, e); - telemetryProcess(requestContext, telemetryInfo, e); - } - - public void error(RequestContext requestContext, String message, Throwable e) { - error(requestContext, message, null, null, e); - } - - public void error(RequestContext requestContext, String message, Throwable e, Map telemetryInfo) { - error(requestContext, message, null, null, e, telemetryInfo); - } - - public void warn(RequestContext requestContext, String message, Map object, - Map param, Throwable e) { - if (requestContext != null) { - requestContext.setLoggerLevel(warnLevel); - logger.warn((jsonMapper(requestContext, message, object, param)), e); - } else - defaultLogger.warn(message, e); - } - - public void warn(RequestContext requestContext, String message, Throwable e) { - warn(requestContext, message, null, null, e); - } - - public void warn(RequestContext requestContext, String message) { - warn(requestContext, message, null, null, null); - } - - private static boolean isDebugEnabled(RequestContext requestContext) { - return (null != requestContext && StringUtils.equalsIgnoreCase("true", requestContext.getDebugEnabled())); - } - - private void telemetryProcess(RequestContext requestContext, Map telemetryInfo, Throwable e) { - ProjectCommonException projectCommonException = null; - if (e instanceof ProjectCommonException) { - projectCommonException = (ProjectCommonException) e; - } else { - projectCommonException = new ProjectCommonException( - ResponseCode.internalError.getErrorCode(), - ResponseCode.internalError.getErrorMessage(), - ResponseCode.SERVER_ERROR.getResponseCode()); - } - Request request = new Request(requestContext); - telemetryInfo.put(JsonKey.TELEMETRY_EVENT_TYPE, TelemetryEvents.ERROR.getName()); - - Map params = (Map) telemetryInfo.get(JsonKey.PARAMS); - params.put(JsonKey.ERROR, projectCommonException.getCode()); - params.put(JsonKey.STACKTRACE, generateStackTrace(e.getStackTrace())); - request.setRequest(telemetryInfo); - // lmaxWriter.submitMessage(request); - TelemetryWriter.write(request); - } - - private String generateStackTrace(StackTraceElement[] elements) { - StringBuilder builder = new StringBuilder(""); - for (StackTraceElement element : elements) { - builder.append(element.toString()); - } - return builder.toString(); - } - - private String jsonMapper(RequestContext requestContext, String message, Map object, - Map param) { - try { - return mapper.writeValueAsString(new CustomLogFormat(requestContext, message, object, param).getEventMap()); - } catch (JsonProcessingException e) { - error(requestContext, e.getMessage(), e); - } - return ""; - } -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/MapperUtil.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/MapperUtil.java deleted file mode 100644 index 20797eb7b..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/MapperUtil.java +++ /dev/null @@ -1,23 +0,0 @@ -package org.sunbird.common.models.util; - -import java.util.Map; - -public class MapperUtil { - public static void put( - Map inMap, String inKey, Map outMap, String outKey) { - String[] inputKeys = inKey.split("\\."); - String lastKey = inputKeys[inputKeys.length - 1]; - - Map map = inMap; - - for (int i = 0; i < (inputKeys.length - 1); i++) { - if (map.containsKey(inputKeys[i])) { - map = (Map) inMap.get(inputKeys[i]); - } - } - - if (map.containsKey(lastKey)) { - outMap.put(outKey, map.get(lastKey)); - } - } -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/PropertiesCache.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/PropertiesCache.java deleted file mode 100644 index 4ab67c6fd..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/PropertiesCache.java +++ /dev/null @@ -1,101 +0,0 @@ -package org.sunbird.common.models.util; - -import java.io.IOException; -import java.io.InputStream; -import java.util.Map; -import java.util.Properties; -import java.util.concurrent.ConcurrentHashMap; -import org.apache.commons.lang3.StringUtils; - -/* - * @author Amit Kumar - * - * this class is used for reading properties file - */ -public class PropertiesCache { - - private final String[] fileName = { - "elasticsearch.config.properties", - "cassandra.config.properties", - "dbconfig.properties", - "externalresource.properties", - "sso.properties", - "userencryption.properties", - "profilecompleteness.properties", - "mailTemplates.properties" - }; - private final Properties configProp = new Properties(); - public final Map attributePercentageMap = new ConcurrentHashMap<>(); - private static PropertiesCache propertiesCache = null; - - /** private default constructor */ - private PropertiesCache() { - for (String file : fileName) { - InputStream in = this.getClass().getClassLoader().getResourceAsStream(file); - try { - configProp.load(in); - } catch (IOException e) { - ProjectLogger.log("Error in properties cache", e); - } - } - loadWeighted(); - } - - public static PropertiesCache getInstance() { - - // change the lazy holder implementation to simple singleton implementation ... - if (null == propertiesCache) { - synchronized (PropertiesCache.class) { - if (null == propertiesCache) { - propertiesCache = new PropertiesCache(); - } - } - } - - return propertiesCache; - } - - public void saveConfigProperty(String key, String value) { - configProp.setProperty(key, value); - } - - public String getProperty(String key) { - String value = System.getenv(key); - if (StringUtils.isNotBlank(value)) return value; - return configProp.getProperty(key) != null ? configProp.getProperty(key) : key; - } - - private void loadWeighted() { - String key = configProp.getProperty("user.profile.attribute"); - String value = configProp.getProperty("user.profile.weighted"); - if (StringUtils.isBlank(key)) { - ProjectLogger.log("Profile completeness value is not set==", LoggerEnum.INFO.name()); - } else { - String keys[] = key.split(","); - String values[] = value.split(","); - if (keys.length == value.length()) { - // then take the value from user - ProjectLogger.log("weighted value is provided by user."); - for (int i = 0; i < keys.length; i++) - attributePercentageMap.put(keys[i], new Float(values[i])); - } else { - // equally divide all the provided field. - ProjectLogger.log("weighted value is not provided by user."); - float perc = (float) 100.0 / keys.length; - for (int i = 0; i < keys.length; i++) attributePercentageMap.put(keys[i], perc); - } - } - } - - /** - * Method to read value from resource file . - * - * @param key - * @return - */ - public String readProperty(String key) { - String value = System.getenv(key); - if (StringUtils.isNotBlank(value)) return value; - return configProp.getProperty(key); - } -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/TelemetryEnvKey.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/TelemetryEnvKey.java deleted file mode 100644 index e4b6bb254..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/TelemetryEnvKey.java +++ /dev/null @@ -1,13 +0,0 @@ -package org.sunbird.common.models.util; - -/** Created by arvind on 9/4/18. */ -public class TelemetryEnvKey { - - public static final String USER = "User"; - public static final String BATCH = "CourseBatch"; - public static final String PAGE = "Page"; - public static final String PAGE_SECTION = "PageSection"; - public static final String REQUEST_UPPER_CAMEL = "Request"; - public static final String QR_CODE_DOWNLOAD = "QRCodeDownload"; - public static final String COURSE_CREATE = "COURSE_CREATE"; -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/datasecurity/DataMaskingService.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/datasecurity/DataMaskingService.java deleted file mode 100644 index ffe7d91f4..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/datasecurity/DataMaskingService.java +++ /dev/null @@ -1,58 +0,0 @@ -/** */ -package org.sunbird.common.models.util.datasecurity; - -import org.apache.commons.lang3.StringUtils; -import org.sunbird.common.models.util.JsonKey; - -/** @author Manzarul */ -public interface DataMaskingService { - - /** - * This method will allow to mask user phone number. - * - * @param phone String - * @return String - */ - String maskPhone(String phone); - - /** - * This method will allow user to mask email. - * - * @param email String - * @return String - */ - String maskEmail(String email); - - /** - * @param data - * @return - */ - default String maskData(String data) { - if (StringUtils.isBlank(data) || data.length() <= 3) { - return data; - } - int lenght = data.length() - 4; - StringBuilder builder = new StringBuilder(); - for (int i = 0; i < data.length(); i++) { - if (i < lenght) { - builder.append(JsonKey.REPLACE_WITH_ASTERISK); - } else { - builder.append(data.charAt(i)); - } - } - return builder.toString(); - } - - /** - * Mask an OTP - * @param otp - * @return Depending on the length - 6, 4, masks 1 character - */ - default String maskOTP(String otp) { - if (otp.length() >= 6) { - return otp.replaceAll("(^[^*]{5}|(?!^)\\G)[^*]", "$1*"); - } else { - return otp.replaceAll("(^[^*]{3}|(?!^)\\G)[^*]", "$1*"); - } - } -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/datasecurity/DecryptionService.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/datasecurity/DecryptionService.java deleted file mode 100644 index 0d32b2c13..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/datasecurity/DecryptionService.java +++ /dev/null @@ -1,56 +0,0 @@ -package org.sunbird.common.models.util.datasecurity; - -import java.util.List; -import java.util.Map; - -/** - * This service will have data decryption methods. decryption logic will differ based on imp - * classes. - * - * @author Manzarul - */ -public interface DecryptionService { - - String ALGORITHM = "AES"; - int ITERATIONS = 3; - byte[] keyValue = - new byte[] {'T', 'h', 'i', 's', 'A', 's', 'I', 'S', 'e', 'r', 'c', 'e', 'K', 't', 'e', 'y'}; - - /** - * This method will take input as key value pair , value can be any primitive or String or both or - * can have another map as values. inner map will also have values as primitive or String or both - * - * @param data Map - * @return Map - * @throws Exception - */ - Map decryptData(Map data); - - /** - * This method will take list of map as an input to decrypt the data, after decryption it will - * return same map with decrypted values. values in side map can have primitive , String or - * another map have primitive , String values. - * - * @param data List> - * @return List> - * @throws Exception - */ - List> decryptData(List> data); - - /** - * Decrypt given data. - * - * @param data Input data - * @return Decrypted data - */ - String decryptData(String data); - - /** - * Decrypt given data. - * - * @param data Input data - * @return Decrypted data - * @throws ProjectCommonException in case of an error during decryption. - */ - String decryptData(String data, boolean throwExceptionOnFailure); -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/datasecurity/EncryptionService.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/datasecurity/EncryptionService.java deleted file mode 100644 index 33db2d2b6..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/datasecurity/EncryptionService.java +++ /dev/null @@ -1,49 +0,0 @@ -/** */ -package org.sunbird.common.models.util.datasecurity; - -import java.util.List; -import java.util.Map; - -/** - * This service will have the data encryption logic. these logic will differ based on implementation - * class. - * - * @author Manzarul - */ -public interface EncryptionService { - - String ALGORITHM = "AES"; - int ITERATIONS = 3; - byte[] keyValue = - new byte[] {'T', 'h', 'i', 's', 'A', 's', 'I', 'S', 'e', 'r', 'c', 'e', 'K', 't', 'e', 'y'}; - - /** - * This method will take input as key value pair , value can be any primitive or String or both or - * can have another map as values. inner map will also have values as primitive or String or both - * - * @param data Map - * @return Map - * @throws Exception - */ - Map encryptData(Map data) throws Exception; - - /** - * This method will take list of map as an input to encrypt the data, after encryption it will - * return same map with encrypted values. values in side map can have primitive , String or - * another map have primitive , String values. - * - * @param data List> - * @return List> - * @throws Exception - */ - List> encryptData(List> data) throws Exception; - - /** - * This method will take String as an input and encrypt the String and return back. - * - * @param data String - * @return String - * @throws Exception - */ - String encryptData(String data) throws Exception; -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/datasecurity/OneWayHashing.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/datasecurity/OneWayHashing.java deleted file mode 100644 index 6065bbe22..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/datasecurity/OneWayHashing.java +++ /dev/null @@ -1,40 +0,0 @@ -/** */ -package org.sunbird.common.models.util.datasecurity; - -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import org.sunbird.common.models.util.ProjectLogger; - -/** - * This class will do one way data hashing. - * - * @author Manzarul - */ -public class OneWayHashing { - - private OneWayHashing() {} - - /** - * This method will encrypt value using SHA-256 . it is one way encryption. - * - * @param val String - * @return String encrypted value or empty in case of exception - */ - public static String encryptVal(String val) { - try { - MessageDigest md = MessageDigest.getInstance("SHA-256"); - md.update(val.getBytes(StandardCharsets.UTF_8)); - byte byteData[] = md.digest(); - // convert the byte to hex format method 1 - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < byteData.length; i++) { - sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1)); - } - ProjectLogger.log("encrypted value is==: " + sb.toString()); - return sb.toString(); - } catch (Exception e) { - ProjectLogger.log("Error while encrypting", e); - } - return ""; - } -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/datasecurity/impl/DefaultDecryptionServiceImpl.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/datasecurity/impl/DefaultDecryptionServiceImpl.java deleted file mode 100644 index 64aa9d17c..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/datasecurity/impl/DefaultDecryptionServiceImpl.java +++ /dev/null @@ -1,123 +0,0 @@ -package org.sunbird.common.models.util.datasecurity.impl; - -import java.nio.charset.StandardCharsets; -import java.security.Key; -import java.util.Base64; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import javax.crypto.Cipher; -import javax.crypto.spec.SecretKeySpec; -import org.apache.commons.lang3.StringUtils; -import org.sunbird.common.exception.ProjectCommonException; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.models.util.LoggerEnum; -import org.sunbird.common.models.util.ProjectLogger; -import org.sunbird.common.models.util.PropertiesCache; -import org.sunbird.common.models.util.datasecurity.DecryptionService; -import org.sunbird.common.responsecode.ResponseCode; - -public class DefaultDecryptionServiceImpl implements DecryptionService { - private static String sunbird_encryption = ""; - - private String sunbirdEncryption = ""; - - private static Cipher c; - - static { - try { - sunbird_encryption = DefaultEncryptionServivceImpl.getSalt(); - Key key = generateKey(); - c = Cipher.getInstance(ALGORITHM); - c.init(Cipher.DECRYPT_MODE, key); - } catch (Exception e) { - ProjectLogger.log(e.getMessage(), e); - } - } - - public DefaultDecryptionServiceImpl() { - sunbirdEncryption = System.getenv(JsonKey.SUNBIRD_ENCRYPTION); - if (StringUtils.isBlank(sunbirdEncryption)) { - sunbirdEncryption = PropertiesCache.getInstance().getProperty(JsonKey.SUNBIRD_ENCRYPTION); - } - } - - @Override - public Map decryptData(Map data) { - if (JsonKey.ON.equalsIgnoreCase(sunbirdEncryption)) { - if (data == null) { - return data; - } - Iterator> itr = data.entrySet().iterator(); - while (itr.hasNext()) { - Entry entry = itr.next(); - if (!(entry.getValue() instanceof Map || entry.getValue() instanceof List) - && null != entry.getValue()) { - data.put(entry.getKey(), decrypt(entry.getValue() + "", false)); - } - } - } - return data; - } - - @Override - public List> decryptData(List> data) { - if (JsonKey.ON.equalsIgnoreCase(sunbirdEncryption)) { - if (data == null || data.isEmpty()) { - return data; - } - - for (Map map : data) { - decryptData(map); - } - } - return data; - } - - @Override - public String decryptData(String data) { - return decryptData(data, false); - } - - @Override - public String decryptData(String data, boolean throwExceptionOnFailure) { - if (JsonKey.ON.equalsIgnoreCase(sunbirdEncryption)) { - if (StringUtils.isBlank(data)) { - return data; - } else { - return decrypt(data, throwExceptionOnFailure); - } - } else { - return data; - } - } - - public static String decrypt(String value, boolean throwExceptionOnFailure) { - try { - String dValue = null; - String valueToDecrypt = value.trim(); - for (int i = 0; i < ITERATIONS; i++) { - byte[] decordedValue = Base64.getDecoder().decode(valueToDecrypt); - byte[] decValue = c.doFinal(decordedValue); - dValue = - new String(decValue, StandardCharsets.UTF_8).substring(sunbird_encryption.length()); - valueToDecrypt = dValue; - } - return dValue; - } catch (Exception ex) { - ProjectLogger.log( - "DefaultDecryptionServiceImpl:decrypt: Exception occurred with error message = " - + ex.getMessage(), - LoggerEnum.ERROR.name()); - if (throwExceptionOnFailure) { - ProjectCommonException.throwClientErrorException(ResponseCode.userDataEncryptionError); - } - } - return value; - } - - private static Key generateKey() { - return new SecretKeySpec(keyValue, ALGORITHM); - } -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/datasecurity/impl/DefaultEncryptionServivceImpl.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/datasecurity/impl/DefaultEncryptionServivceImpl.java deleted file mode 100644 index bcb051871..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/datasecurity/impl/DefaultEncryptionServivceImpl.java +++ /dev/null @@ -1,156 +0,0 @@ -/** */ -package org.sunbird.common.models.util.datasecurity.impl; - -import java.io.UnsupportedEncodingException; -import java.nio.charset.StandardCharsets; -import java.security.InvalidKeyException; -import java.security.Key; -import java.security.NoSuchAlgorithmException; -import java.util.Base64; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import javax.crypto.BadPaddingException; -import javax.crypto.Cipher; -import javax.crypto.IllegalBlockSizeException; -import javax.crypto.NoSuchPaddingException; -import javax.crypto.spec.SecretKeySpec; -import org.apache.commons.lang3.StringUtils; -import org.sunbird.common.exception.ProjectCommonException; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.models.util.LoggerEnum; -import org.sunbird.common.models.util.ProjectLogger; -import org.sunbird.common.models.util.PropertiesCache; -import org.sunbird.common.models.util.datasecurity.EncryptionService; -import org.sunbird.common.responsecode.ResponseCode; - -/** - * Default data encryption service - * - * @author Manzarul - */ -public class DefaultEncryptionServivceImpl implements EncryptionService { - - private static String encryption_key = ""; - - private String sunbirdEncryption = ""; - - private static Cipher c; - - static { - try { - encryption_key = getSalt(); - Key key = generateKey(); - c = Cipher.getInstance(ALGORITHM); - c.init(Cipher.ENCRYPT_MODE, key); - } catch (Exception e) { - ProjectLogger.log(e.getMessage(), e); - } - } - - public DefaultEncryptionServivceImpl() { - sunbirdEncryption = System.getenv(JsonKey.SUNBIRD_ENCRYPTION); - if (StringUtils.isBlank(sunbirdEncryption)) { - sunbirdEncryption = PropertiesCache.getInstance().getProperty(JsonKey.SUNBIRD_ENCRYPTION); - } - } - - @Override - public Map encryptData(Map data) throws Exception { - if (JsonKey.ON.equalsIgnoreCase(sunbirdEncryption)) { - if (data == null) { - return data; - } - Iterator> itr = data.entrySet().iterator(); - while (itr.hasNext()) { - Entry entry = itr.next(); - if (!(entry.getValue() instanceof Map || entry.getValue() instanceof List) - && null != entry.getValue()) { - data.put(entry.getKey(), encrypt(entry.getValue() + "")); - } - } - } - return data; - } - - @Override - public List> encryptData(List> data) throws Exception { - if (JsonKey.ON.equalsIgnoreCase(sunbirdEncryption)) { - if (data == null || data.isEmpty()) { - return data; - } - for (Map map : data) { - encryptData(map); - } - } - return data; - } - - @Override - public String encryptData(String data) throws Exception { - if (JsonKey.ON.equalsIgnoreCase(sunbirdEncryption)) { - if (StringUtils.isBlank(data)) { - return data; - } - if (null != data) { - return encrypt(data); - } else { - return data; - } - } else { - return data; - } - } - - /** - * this method is used to encrypt the password. - * - * @param value String password - * @return encrypted password. - * @throws NoSuchPaddingException - * @throws NoSuchAlgorithmException - * @throws InvalidKeyException - * @throws BadPaddingException - * @throws IllegalBlockSizeException - * @throws UnsupportedEncodingException - */ - @SuppressWarnings("restriction") - public static String encrypt(String value) - throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, - IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException { - String valueToEnc = null; - String eValue = value; - for (int i = 0; i < ITERATIONS; i++) { - valueToEnc = encryption_key + eValue; - byte[] encValue = c.doFinal(valueToEnc.getBytes(StandardCharsets.UTF_8)); - eValue = new String(Base64.getEncoder().encode(encValue), StandardCharsets.UTF_8); - } - return eValue; - } - - private static Key generateKey() { - return new SecretKeySpec(keyValue, ALGORITHM); - } - - /** @return */ - public static String getSalt() { - if (!StringUtils.isBlank(encryption_key)) { - return encryption_key; - } else { - encryption_key = System.getenv(JsonKey.ENCRYPTION_KEY); - if (StringUtils.isBlank(encryption_key)) { - ProjectLogger.log("Salt value is not provided by Env"); - encryption_key = PropertiesCache.getInstance().getProperty(JsonKey.ENCRYPTION_KEY); - } - } - if (StringUtils.isBlank(encryption_key)) { - ProjectLogger.log("throwing exception for invalid salt==", LoggerEnum.INFO.name()); - throw new ProjectCommonException( - ResponseCode.saltValue.getErrorCode(), - ResponseCode.saltValue.getErrorMessage(), - ResponseCode.SERVER_ERROR.getResponseCode()); - } - return encryption_key; - } -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/datasecurity/impl/LogMaskServiceImpl.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/datasecurity/impl/LogMaskServiceImpl.java deleted file mode 100644 index 90399b977..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/datasecurity/impl/LogMaskServiceImpl.java +++ /dev/null @@ -1,28 +0,0 @@ -package org.sunbird.common.models.util.datasecurity.impl; - -import org.sunbird.common.models.util.datasecurity.DataMaskingService; - -public class LogMaskServiceImpl implements DataMaskingService { - /** - * Mask an email - * @param email - * @return the first 4 or 2 characters in plain and masks the rest. The domain is - * still in plain - */ - public String maskEmail(String email) { - if (email.indexOf("@") > 4) { - return email.replaceAll("(^[^@]{4}|(?!^)\\G)[^@]", "$1*"); - } else { - return email.replaceAll("(^[^@]{2}|(?!^)\\G)[^@]", "$1*"); - } - } - - /** - * Mask a phone number - * @param phone - * @return a string with the last digit masked - */ - public String maskPhone(String phone) { - return phone.replaceAll("(^[^*]{9}|(?!^)\\G)[^*]", "$1*"); - } -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/datasecurity/impl/ServiceFactory.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/datasecurity/impl/ServiceFactory.java deleted file mode 100644 index 91a783c85..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/datasecurity/impl/ServiceFactory.java +++ /dev/null @@ -1,78 +0,0 @@ -/** */ -package org.sunbird.common.models.util.datasecurity.impl; - -import org.apache.commons.lang3.StringUtils; -import org.sunbird.common.models.util.datasecurity.DataMaskingService; -import org.sunbird.common.models.util.datasecurity.DecryptionService; -import org.sunbird.common.models.util.datasecurity.EncryptionService; - -/** - * This factory will provide encryption service instance and decryption service instance with - * default implementation. - * - * @author Manzarul - */ -public class ServiceFactory { - - private static EncryptionService encryptionService; - private static DecryptionService decryptionService; - private static DataMaskingService maskingService; - - static { - encryptionService = new DefaultEncryptionServivceImpl(); - decryptionService = new DefaultDecryptionServiceImpl(); - maskingService = new DefaultDataMaskServiceImpl(); - } - - /** - * this method will provide encryptionServiceImple instance. by default it will provide - * DefaultEncryptionServiceImpl instance to get a particular service impl instance , need to - * change the object creation and provided logic. - * - * @param val String ( pass null or empty in case of defaultImple object.) - * @return EncryptionService - */ - public static EncryptionService getEncryptionServiceInstance(String val) { - if (StringUtils.isBlank(val)) { - return encryptionService; - } - switch (val) { - case "defaultEncryption": - return encryptionService; - default: - return encryptionService; - } - } - - /** - * this method will provide decryptionServiceImple instance. by default it will provide - * DefaultDecryptionServiceImpl instance to get a particular service impl instance , need to - * change the object creation and provided logic. - * - * @param val String ( pass null or empty in case of defaultImple object.) - * @return DecryptionService - */ - public static DecryptionService getDecryptionServiceInstance(String val) { - if (StringUtils.isBlank(val)) { - return decryptionService; - } - switch (val) { - case "defaultDecryption": - return decryptionService; - default: - return decryptionService; - } - } - - public static DataMaskingService getMaskingServiceInstance(String val) { - if (StringUtils.isBlank(val)) { - return maskingService; - } - switch (val) { - case "defaultMasking": - return maskingService; - default: - return maskingService; - } - } -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/datasecurity/impl/package-info.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/datasecurity/impl/package-info.java deleted file mode 100644 index c601093b4..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/datasecurity/impl/package-info.java +++ /dev/null @@ -1,3 +0,0 @@ -/** */ -/** @author Manzarul */ -package org.sunbird.common.models.util.datasecurity.impl; diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/datasecurity/package-info.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/datasecurity/package-info.java deleted file mode 100644 index 09c3c5704..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/datasecurity/package-info.java +++ /dev/null @@ -1,3 +0,0 @@ -/** */ -/** @author Manzarul */ -package org.sunbird.common.models.util.datasecurity; diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/fcm/Notification.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/fcm/Notification.java deleted file mode 100644 index 8daea20ae..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/fcm/Notification.java +++ /dev/null @@ -1,61 +0,0 @@ -/** */ -package org.sunbird.common.models.util.fcm; - -import java.util.HashMap; -import java.util.Map; -import org.apache.commons.lang3.StringUtils; -import org.json.JSONObject; -import org.sunbird.common.models.util.HttpUtil; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.models.util.LoggerEnum; -import org.sunbird.common.models.util.ProjectLogger; -import org.sunbird.common.models.util.PropertiesCache; - -/** @author Manzarul */ -public class Notification { - /** FCM_URL URL of FCM server */ - public static final String FCM_URL = PropertiesCache.getInstance().getProperty(JsonKey.FCM_URL); - /** FCM_ACCOUNT_KEY FCM server key. */ - private static final String FCM_ACCOUNT_KEY = System.getenv(JsonKey.SUNBIRD_FCM_ACCOUNT_KEY); - - private static Map headerMap = new HashMap<>(); - private static final String TOPIC_SUFFIX = "/topics/"; - - static { - headerMap.put(JsonKey.AUTHORIZATION, FCM_ACCOUNT_KEY); - headerMap.put("Content-Type", "application/json"); - } - - /** - * This method will send notification to FCM. - * - * @param topic String - * @param data Map - * @param url String - * @return String as Json.{"message_id": 7253391319867149192} - */ - public static String sendNotification(String topic, Map data, String url) { - if (StringUtils.isBlank(FCM_ACCOUNT_KEY) || StringUtils.isBlank(url)) { - ProjectLogger.log( - "FCM account key or URL is not provided===" + FCM_URL, LoggerEnum.INFO.name()); - return JsonKey.FAILURE; - } - String response = null; - try { - JSONObject object1 = new JSONObject(data); - JSONObject object = new JSONObject(); - object.put(JsonKey.DATA, object1); - object.put(JsonKey.TO, TOPIC_SUFFIX + topic); - response = HttpUtil.sendPostRequest(FCM_URL, object.toString(), headerMap); - ProjectLogger.log("FCM Notification response== for topic " + topic + response); - object1 = null; - object1 = new JSONObject(response); - long val = object1.getLong(JsonKey.MESSAGE_Id); - response = val + ""; - } catch (Exception e) { - response = JsonKey.FAILURE; - ProjectLogger.log(e.getMessage(), e); - } - return response; - } -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/fcm/package-info.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/fcm/package-info.java deleted file mode 100644 index 676f493d8..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/fcm/package-info.java +++ /dev/null @@ -1,3 +0,0 @@ -/** */ -/** @author Manzarul */ -package org.sunbird.common.models.util.fcm; diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/package-info.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/package-info.java deleted file mode 100644 index be4d48c50..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/package-info.java +++ /dev/null @@ -1,3 +0,0 @@ -/** */ -/** @author Manzarul */ -package org.sunbird.common.models.util; diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/url/EsConfigUtil.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/url/EsConfigUtil.java deleted file mode 100644 index 47fd9fe46..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/url/EsConfigUtil.java +++ /dev/null @@ -1,15 +0,0 @@ -package org.sunbird.common.models.util.url; - -import org.apache.commons.lang.StringUtils; - -import static org.sunbird.common.models.util.ProjectUtil.propertiesCache; - -public class EsConfigUtil { - - public static String getConfigValue(String key) { - if (StringUtils.isNotBlank(System.getenv(key))) { - return System.getenv(key); - } - return propertiesCache.readProperty(key); - } -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/url/URLShortner.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/url/URLShortner.java deleted file mode 100644 index 823d7e51d..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/url/URLShortner.java +++ /dev/null @@ -1,6 +0,0 @@ -package org.sunbird.common.models.util.url; - -public interface URLShortner { - - public String shortUrl(String url); -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/url/URLShortnerImpl.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/url/URLShortnerImpl.java deleted file mode 100644 index e74b2046b..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/models/util/url/URLShortnerImpl.java +++ /dev/null @@ -1,70 +0,0 @@ -package org.sunbird.common.models.util.url; - -import com.fasterxml.jackson.databind.ObjectMapper; -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; -import org.apache.commons.lang3.StringUtils; -import org.sunbird.common.models.util.HttpUtil; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.models.util.ProjectLogger; -import org.sunbird.common.models.util.ProjectUtil; -import org.sunbird.common.models.util.PropertiesCache; - -/** @author Amit Kumar */ -public class URLShortnerImpl implements URLShortner { - - private static String resUrl = null; - private static final String SUNBIRD_WEB_URL = "sunbird_web_url"; - - @Override - public String shortUrl(String url) { - boolean flag = false; - try { - flag = Boolean.parseBoolean(ProjectUtil.getConfigValue(JsonKey.SUNBIRD_URL_SHORTNER_ENABLE)); - } catch (Exception ex) { - ProjectLogger.log( - "URLShortnerImpl:shortUrl : Exception occurred while parsing sunbird_url_shortner_enable key"); - } - if (flag) { - String baseUrl = PropertiesCache.getInstance().getProperty("sunbird_url_shortner_base_url"); - String accessToken = System.getenv("url_shortner_access_token"); - if (StringUtils.isBlank(accessToken)) { - accessToken = - PropertiesCache.getInstance().getProperty("sunbird_url_shortner_access_token"); - } - String requestURL = baseUrl + accessToken + "&longUrl=" + url; - String response = ""; - try { - response = HttpUtil.sendGetRequest(requestURL, null); - } catch (Exception e) { - ProjectLogger.log("Exception occurred while sending request for URL shortening", e); - } - ObjectMapper mapper = new ObjectMapper(); - Map map = null; - if (!StringUtils.isBlank(response)) { - try { - map = mapper.readValue(response, HashMap.class); - Map dataMap = (Map) map.get("data"); - return dataMap.get("url"); - } catch (IOException | ClassCastException e) { - ProjectLogger.log(e.getMessage(), e); - } - } - } - return url; - } - - /** @return the url */ - public String getUrl() { - if (StringUtils.isBlank(resUrl)) { - String webUrl = System.getenv(SUNBIRD_WEB_URL); - if (StringUtils.isBlank(webUrl)) { - webUrl = PropertiesCache.getInstance().getProperty(SUNBIRD_WEB_URL); - } - return shortUrl(webUrl); - } else { - return resUrl; - } - } -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/request/AddressRequestValidator.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/request/AddressRequestValidator.java deleted file mode 100644 index 615bf6e6d..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/request/AddressRequestValidator.java +++ /dev/null @@ -1,58 +0,0 @@ -package org.sunbird.common.request; - -import java.util.Map; -import org.apache.commons.lang3.StringUtils; -import org.sunbird.common.exception.ProjectCommonException; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.models.util.ProjectUtil; -import org.sunbird.common.models.util.ProjectUtil.AddressType; -import org.sunbird.common.responsecode.ResponseCode; - -public class AddressRequestValidator extends BaseRequestValidator { - - private static final int ERROR_CODE = ResponseCode.CLIENT_ERROR.getResponseCode(); - - public void validateAddress(Map address, String type) { - if (StringUtils.isBlank((String) address.get(JsonKey.ADDRESS_LINE1))) { - throw new ProjectCommonException( - ResponseCode.addressError.getErrorCode(), - ProjectUtil.formatMessage( - ResponseCode.addressError.getErrorMessage(), type, JsonKey.ADDRESS_LINE1), - ERROR_CODE); - } - if (StringUtils.isBlank((String) address.get(JsonKey.CITY))) { - throw new ProjectCommonException( - ResponseCode.addressError.getErrorCode(), - ProjectUtil.formatMessage( - ResponseCode.addressError.getErrorMessage(), type, JsonKey.CITY), - ERROR_CODE); - } - if (address.containsKey(JsonKey.ADD_TYPE)) { - - if (StringUtils.isBlank((String) address.get(JsonKey.ADD_TYPE))) { - throw new ProjectCommonException( - ResponseCode.addressError.getErrorCode(), - ProjectUtil.formatMessage( - ResponseCode.addressError.getErrorMessage(), JsonKey.ADDRESS, JsonKey.TYPE), - ERROR_CODE); - } - - if (!StringUtils.isBlank((String) address.get(JsonKey.ADD_TYPE)) - && !checkAddressType((String) address.get(JsonKey.ADD_TYPE))) { - throw new ProjectCommonException( - ResponseCode.addressTypeError.getErrorCode(), - ResponseCode.addressTypeError.getErrorMessage(), - ERROR_CODE); - } - } - } - - private static boolean checkAddressType(String addrType) { - for (AddressType type : AddressType.values()) { - if (type.getTypeName().equals(addrType)) { - return true; - } - } - return false; - } -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/request/LearnerStateRequestValidator.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/request/LearnerStateRequestValidator.java deleted file mode 100644 index bf74e0ebb..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/request/LearnerStateRequestValidator.java +++ /dev/null @@ -1,30 +0,0 @@ -package org.sunbird.common.request; - -import org.apache.commons.collections.CollectionUtils; -import org.sunbird.common.models.util.JsonKey; - -import java.util.List; - -/** @author arvind */ -public class LearnerStateRequestValidator extends BaseRequestValidator { - - /** - * Method to validate the get content state request. - * - * @param request Representing the request object. - */ - public void validateGetContentState(Request request) { - - validateListParam(request.getRequest(), JsonKey.COURSE_IDS, JsonKey.CONTENT_IDS); - if (request.getRequest().containsKey(JsonKey.COURSE_IDS)) { - List courseIds = (List) request.getRequest().get(JsonKey.COURSE_IDS); - request.getRequest().remove(JsonKey.COURSE_IDS); - if (!request.getRequest().containsKey(JsonKey.COURSE_ID) && !request.getRequest().containsKey(JsonKey.COLLECTION_ID) && CollectionUtils.isNotEmpty(courseIds)) { - request.getRequest().put(JsonKey.COURSE_ID, courseIds.get(0)); - } - } - String courseId = request.getRequest().containsKey(JsonKey.COURSE_ID) ? JsonKey.COURSE_ID : JsonKey.COLLECTION_ID; - request.getRequest().put(JsonKey.COURSE_ID, request.getRequest().get(courseId)); - checkMandatoryFieldsPresent(request.getRequest(), JsonKey.USER_ID, JsonKey.COURSE_ID, JsonKey.BATCH_ID); - } -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/request/Request.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/request/Request.java deleted file mode 100644 index 23544b214..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/request/Request.java +++ /dev/null @@ -1,194 +0,0 @@ -package org.sunbird.common.request; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import java.io.Serializable; -import java.text.MessageFormat; -import java.util.Arrays; -import java.util.Map; -import java.util.WeakHashMap; -import org.apache.commons.lang3.StringUtils; -import org.sunbird.common.exception.ProjectCommonException; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.models.util.ProjectUtil; -import org.sunbird.common.responsecode.ResponseCode; - -/** @author Manzarul */ -@JsonIgnoreProperties(ignoreUnknown = true) -public class Request implements Serializable { - - private static final long serialVersionUID = -2362783406031347676L; - private static final Integer MIN_TIMEOUT = 0; - private static final Integer MAX_TIMEOUT = 30; - private static final int WAIT_TIME_VALUE = 30; - - protected Map context; - - private RequestContext requestContext; - - private String id; - private String ver; - private String ts; - private RequestParams params; - - private Map request = new WeakHashMap<>(); - - private String managerName; - private String operation; - private String requestId; - private int env; - - private Integer timeout; // in seconds - - public Request() { - this.context = new WeakHashMap<>(); - this.params = new RequestParams(); - } - - public Request(RequestContext requestContext) { - this.context = new WeakHashMap<>(); - this.params = new RequestParams(); - this.requestContext = requestContext; - } - - - public void toLower() { - Arrays.asList( - ProjectUtil.getConfigValue(JsonKey.SUNBIRD_API_REQUEST_LOWER_CASE_FIELDS).split(",")) - .stream() - .forEach( - field -> { - if (StringUtils.isNotBlank((String) this.getRequest().get(field))) { - this.getRequest().put(field, ((String) this.getRequest().get(field)).toLowerCase()); - } - }); - } - - public String getRequestId() { - return requestId; - } - - public Map getContext() { - return context; - } - - public void setContext(Map context) { - this.context = context; - } - - /** @return the requestValueObjects */ - public Map getRequest() { - return request; - } - - public void setRequest(Map request) { - this.request = request; - } - - public Object get(String key) { - return request.get(key); - } - - public void setRequestId(String requestId) { - this.requestId = requestId; - } - - public void put(String key, Object vo) { - request.put(key, vo); - } - - public String getManagerName() { - return managerName; - } - - public void setManagerName(String managerName) { - this.managerName = managerName; - } - - public String getOperation() { - return operation; - } - - public void setOperation(String operation) { - this.operation = operation; - } - - @Override - public String toString() { - return "Request [" - + (context != null ? "context=" + context + ", " : "") - + (request != null ? "requestValueObjects=" + request : "") - + "]"; - } - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public String getVer() { - return ver; - } - - public void setVer(String ver) { - this.ver = ver; - } - - public String getTs() { - return ts; - } - - public void setTs(String ts) { - this.ts = ts; - } - - public RequestParams getParams() { - return params; - } - - public void setParams(RequestParams params) { - this.params = params; - if (this.params.getMsgid() == null && requestId != null) this.params.setMsgid(requestId); - } - - /** @return the env */ - public int getEnv() { - return env; - } - - /** @param env the env to set */ - public void setEnv(int env) { - this.env = env; - } - - public Integer getTimeout() { - return timeout == null ? WAIT_TIME_VALUE : timeout; - } - - public void setTimeout(Integer timeout) { - if (timeout < MIN_TIMEOUT && timeout > MAX_TIMEOUT) { - ProjectCommonException.throwServerErrorException( - ResponseCode.invalidRequestTimeout, - MessageFormat.format(ResponseCode.invalidRequestTimeout.getErrorMessage(), timeout)); - } - this.timeout = timeout; - } - - public RequestContext getRequestContext() { - return requestContext; - } - - public void setRequestContext(RequestContext requestContext) { - this.requestContext = requestContext; - } - - public Object getOrDefault(String key, Object defaultVal) { - return request.getOrDefault(key, defaultVal); - } - - public Boolean contains(String key) { - return request.containsKey(key); - } -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/request/RequestContext.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/request/RequestContext.java deleted file mode 100644 index 604484e05..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/request/RequestContext.java +++ /dev/null @@ -1,87 +0,0 @@ -package org.sunbird.common.request; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class RequestContext { - - private String uid; - private String did; - private String sid; - private String debugEnabled; - private String actorId; - private String actorType; - private String loggerLevel; - private String requestId; - private String env; - private Map contextMap = new HashMap<>(); - private String channel; - private Map pdata = new HashMap<>(); - - public RequestContext(String channel, String pdataId, String env, String did, String sid, String pid, String pver, List cdata) { - this.did = did; - this.sid = sid; - this.channel = channel; - this.pdata.put("id", pdataId); - this.pdata.put("pid", pid); - this.pdata.put("ver", pver); - this.contextMap.putAll(new HashMap() {{ - put("did", did); - put("sid", sid); - put("channel", channel); - put("env", env); - put("pdata", pdata); - if (cdata != null) - put("cdata", cdata); - }}); - } - - public String getActorId() { - return actorId; - } - - public void setActorId(String actorId) { - this.actorId = actorId; - } - - public String getActorType() { - return actorType; - } - - public void setActorType(String actorType) { - this.actorType = actorType; - } - - public String getLoggerLevel() { - return loggerLevel; - } - - public void setLoggerLevel(String loggerLevel) { - this.loggerLevel = loggerLevel; - } - - public String getRequestId() { - return requestId; - } - - public void setRequestId(String requestId) { - this.requestId = requestId; - } - - public String getDebugEnabled() { - return debugEnabled; - } - - public String getEnv() { - return env; - } - - public void setEnv(String env) { - this.env = env; - } - - public Map getContextMap() { - return contextMap; - } -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/request/TelemetryV3Request.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/request/TelemetryV3Request.java deleted file mode 100644 index 5360274a3..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/request/TelemetryV3Request.java +++ /dev/null @@ -1,92 +0,0 @@ -package org.sunbird.common.request; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -/** Created by arvind on 23/3/18. */ -public class TelemetryV3Request implements Serializable { - - private String id; - private String ver; - private Long ets; - private Params params; - - private List> events = new ArrayList<>(); - - public TelemetryV3Request() { - params = new Params(); - } - - class Params implements Serializable { - - private String did; - private String key; - private String msgid; - - public String getDid() { - return did; - } - - public void setDid(String did) { - this.did = did; - } - - public String getKey() { - return key; - } - - public void setKey(String key) { - this.key = key; - } - - public String getMsgid() { - return msgid; - } - - public void setMsgid(String msgid) { - this.msgid = msgid; - } - } - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public String getVer() { - return ver; - } - - public void setVer(String ver) { - this.ver = ver; - } - - public Long getEts() { - return ets; - } - - public void setEts(Long ets) { - this.ets = ets; - } - - public Params getParams() { - return params; - } - - public void setParams(Params params) { - this.params = params; - } - - public List> getEvents() { - return events; - } - - public void setEvents(List> events) { - this.events = events; - } -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/request/UserFreeUpRequestValidator.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/request/UserFreeUpRequestValidator.java deleted file mode 100644 index abd93780c..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/request/UserFreeUpRequestValidator.java +++ /dev/null @@ -1,95 +0,0 @@ -package org.sunbird.common.request; - -import org.sunbird.common.exception.ProjectCommonException; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.models.util.ProjectUtil; -import org.sunbird.common.responsecode.ResponseCode; - -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -public class UserFreeUpRequestValidator extends BaseRequestValidator { - - private Request request; - private static List identifiers = new ArrayList<>(); - static { - identifiers.add(JsonKey.EMAIL); - identifiers.add(JsonKey.PHONE); - } - - private static final int ERROR_CODE = ResponseCode.CLIENT_ERROR.getResponseCode(); - - - /** - * this method is used to get the instance to UserFreeUpRequestValidator class - * @param request - * @return - */ - public static UserFreeUpRequestValidator getInstance(Request request) { - return new UserFreeUpRequestValidator(request); - } - - private UserFreeUpRequestValidator(Request request) { - this.request = request; - } - - /** - * this is the method we need to call to validate the IdentifierFreeUpUser request. - */ - public void validate() { - validateIdPresence(); - validateIdentifier(); - } - - - private void validateIdPresence() { - validateParam( - (String) request.getRequest().get(JsonKey.ID), - ResponseCode.mandatoryParamsMissing, - JsonKey.ID); - } - - private void validateIdentifier() { - validatePresence(); - validateObject(); - validateSubset(); - } - - - private void validatePresence() { - if (!request.getRequest().containsKey(JsonKey.IDENTIFIER)) { - throw new ProjectCommonException( - ResponseCode.mandatoryParamsMissing.getErrorCode(), - MessageFormat.format(ResponseCode.mandatoryParamsMissing.getErrorMessage(), JsonKey.IDENTIFIER), - ResponseCode.CLIENT_ERROR.getResponseCode()); - } - - } - - private void validateObject() { - Object identifierType = request.getRequest().get(JsonKey.IDENTIFIER); - if (!(identifierType instanceof List)) { - throw new ProjectCommonException( - ResponseCode.dataTypeError.getErrorCode(), - ProjectUtil.formatMessage( - ResponseCode.dataTypeError.getErrorMessage(), JsonKey.IDENTIFIER, JsonKey.LIST), - ERROR_CODE); - } - } - - private void validateSubset() { - List identifierVal = (List) request.getRequest().get(JsonKey.IDENTIFIER); - if (!identifiers.containsAll(identifierVal)) { - throw new ProjectCommonException( - ResponseCode.dataTypeError.getErrorCode(), - ProjectUtil.formatMessage( - String.format("%s %s",ResponseCode.invalidIdentifier.getErrorMessage(),Arrays.toString(identifiers.toArray())), JsonKey.IDENTIFIER, JsonKey.DATA), - ERROR_CODE); - } - } - -} - - diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/request/UserProfileRequestValidator.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/request/UserProfileRequestValidator.java deleted file mode 100644 index 3ae7f5241..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/request/UserProfileRequestValidator.java +++ /dev/null @@ -1,47 +0,0 @@ -package org.sunbird.common.request; - -import java.util.List; -import org.sunbird.common.exception.ProjectCommonException; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.responsecode.ResponseCode; - -public class UserProfileRequestValidator extends BaseRequestValidator { - - @SuppressWarnings("unchecked") - public void validateProfileVisibility(Request request) { - validateParam( - (String) request.getRequest().get(JsonKey.USER_ID), - ResponseCode.mandatoryParamsMissing, - JsonKey.USER_ID); - validateUserId(request, JsonKey.USER_ID); - validatePublicAndPrivateFields(request); - } - - private void validatePublicAndPrivateFields(Request request) { - List publicList = (List) request.getRequest().get(JsonKey.PUBLIC); - List privateList = (List) request.getRequest().get(JsonKey.PRIVATE); - - if (publicList == null && privateList == null) { - throw new ProjectCommonException( - ResponseCode.invalidData.getErrorCode(), - ResponseCode.invalidData.getErrorMessage(), - ResponseCode.CLIENT_ERROR.getResponseCode()); - } - - validateListElementsAreDisjoint(publicList, privateList); - } - - private void validateListElementsAreDisjoint(List list1, List list2) { - if (list1 == null || list2 == null) { - return; - } - for (String field : list2) { - if (list1.contains(field)) { - throw new ProjectCommonException( - ResponseCode.visibilityInvalid.getErrorCode(), - ResponseCode.visibilityInvalid.getErrorMessage(), - ResponseCode.CLIENT_ERROR.getResponseCode()); - } - } - } -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/request/UserRequestValidator.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/request/UserRequestValidator.java deleted file mode 100644 index e2861028a..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/request/UserRequestValidator.java +++ /dev/null @@ -1,1072 +0,0 @@ -package org.sunbird.common.request; - -import java.text.MessageFormat; -import java.util.*; -import java.util.stream.Collectors; -import org.apache.commons.collections.CollectionUtils; -import org.apache.commons.collections.MapUtils; -import org.apache.commons.lang3.BooleanUtils; -import org.apache.commons.lang3.StringUtils; -import org.sunbird.common.exception.ProjectCommonException; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.models.util.ProjectUtil; -import org.sunbird.common.models.util.StringFormatter; -import org.sunbird.common.responsecode.ResponseCode; - -public class UserRequestValidator extends BaseRequestValidator { - - private static final int ERROR_CODE = ResponseCode.CLIENT_ERROR.getResponseCode(); - - public void validateCreateUserRequest(Request userRequest) { - externalIdsValidation(userRequest, JsonKey.CREATE); - fieldsNotAllowed( - Arrays.asList( - JsonKey.REGISTERED_ORG_ID, - JsonKey.ROOT_ORG_ID, - JsonKey.PROVIDER, - JsonKey.EXTERNAL_ID, - JsonKey.EXTERNAL_ID_PROVIDER, - JsonKey.EXTERNAL_ID_TYPE, - JsonKey.ID_TYPE), - userRequest); - createUserBasicValidation(userRequest); - validateUserType(userRequest); - phoneValidation(userRequest); - addressValidation(userRequest); - educationValidation(userRequest); - jobProfileValidation(userRequest); - validateWebPages(userRequest); - validateLocationCodes(userRequest); - validatePassword((String) userRequest.getRequest().get(JsonKey.PASSWORD)); - } - - public static boolean isGoodPassword(String password) { - return password.matches(ProjectUtil.getConfigValue(JsonKey.SUNBIRD_PASS_REGEX)); - } - - private static void validatePassword(String password) { - if (StringUtils.isNotBlank(password)) { - boolean response = isGoodPassword(password); - if (!response) { - throw new ProjectCommonException( - ResponseCode.passwordValidation.getErrorCode(), - ResponseCode.passwordValidation.getErrorMessage(), - ERROR_CODE); - } - } - } - - private void validateLocationCodes(Request userRequest) { - Object locationCodes = userRequest.getRequest().get(JsonKey.LOCATION_CODES); - if ((locationCodes != null) && !(locationCodes instanceof List)) { - throw new ProjectCommonException( - ResponseCode.dataTypeError.getErrorCode(), - ProjectUtil.formatMessage( - ResponseCode.dataTypeError.getErrorMessage(), JsonKey.LOCATION_CODES, JsonKey.LIST), - ERROR_CODE); - } - if (locationCodes != null) { - List set = new ArrayList(new HashSet<>((List) locationCodes)); - userRequest.getRequest().put(JsonKey.LOCATION_CODES, set); - } - } - - private void validateUserName(Request userRequest) { - validateParam( - (String) userRequest.getRequest().get(JsonKey.USERNAME), - ResponseCode.mandatoryParamsMissing, - JsonKey.USERNAME); - } - - public void validateUserCreateV3(Request userRequest) { - validateParam( - (String) userRequest.getRequest().get(JsonKey.FIRST_NAME), - ResponseCode.mandatoryParamsMissing, - JsonKey.FIRST_NAME); - if (StringUtils.isBlank((String) userRequest.getRequest().get(JsonKey.EMAIL)) - && StringUtils.isBlank((String) userRequest.getRequest().get(JsonKey.PHONE))) { - ProjectCommonException.throwClientErrorException(ResponseCode.emailorPhoneRequired); - } - phoneVerifiedValidation(userRequest); - emailVerifiedValidation(userRequest); - validatePassword((String) userRequest.getRequest().get(JsonKey.PASSWORD)); - if (StringUtils.isNotBlank((String) userRequest.getRequest().get(JsonKey.EMAIL))) { - validateEmail((String) userRequest.getRequest().get(JsonKey.EMAIL)); - } - if (StringUtils.isNotBlank((String) userRequest.getRequest().get(JsonKey.PHONE))) { - validatePhone((String) userRequest.getRequest().get(JsonKey.PHONE)); - } - } - - public void validateCreateUserV3Request(Request userRequest) { - validateCreateUserRequest(userRequest); - } - - public void validateCreateUserV1Request(Request userRequest) { - validateUserName(userRequest); - validateCreateUserV3Request(userRequest); - } - - public void validateCreateUserV2Request(Request userRequest) { - validateCreateUserRequest(userRequest); - } - - public void fieldsNotAllowed(List fields, Request userRequest) { - for (String field : fields) { - if (((userRequest.getRequest().get(field) instanceof String) - && StringUtils.isNotBlank((String) userRequest.getRequest().get(field))) - || (null != userRequest.getRequest().get(field))) { - throw new ProjectCommonException( - ResponseCode.invalidRequestParameter.getErrorCode(), - ProjectUtil.formatMessage( - ResponseCode.invalidRequestParameter.getErrorMessage(), field), - ERROR_CODE); - } - } - } - - public void phoneValidation(Request userRequest) { - if (!StringUtils.isBlank((String) userRequest.getRequest().get(JsonKey.COUNTRY_CODE))) { - boolean bool = - ProjectUtil.validateCountryCode( - (String) userRequest.getRequest().get(JsonKey.COUNTRY_CODE)); - if (!bool) { - ProjectCommonException.throwClientErrorException(ResponseCode.invalidCountryCode); - } - } - if (StringUtils.isNotBlank((String) userRequest.getRequest().get(JsonKey.PHONE))) { - validatePhoneNo( - (String) userRequest.getRequest().get(JsonKey.PHONE), - (String) userRequest.getRequest().get(JsonKey.COUNTRY_CODE)); - } - phoneVerifiedValidation(userRequest); - } - - private void phoneVerifiedValidation(Request userRequest) { - if (!StringUtils.isBlank((String) userRequest.getRequest().get(JsonKey.PHONE))) { - if (null != userRequest.getRequest().get(JsonKey.PHONE_VERIFIED)) { - if (userRequest.getRequest().get(JsonKey.PHONE_VERIFIED) instanceof Boolean) { - if (!((boolean) userRequest.getRequest().get(JsonKey.PHONE_VERIFIED))) { - ProjectCommonException.throwClientErrorException(ResponseCode.phoneVerifiedError); - } - } else { - ProjectCommonException.throwClientErrorException(ResponseCode.phoneVerifiedError); - } - } else { - ProjectCommonException.throwClientErrorException(ResponseCode.phoneVerifiedError); - } - } - } - - /** - * This method will do basic validation for user request object. - * - * @param userRequest - */ - public void createUserBasicValidation(Request userRequest) { - - createUserBasicProfileFieldsValidation(userRequest); - if (userRequest.getRequest().containsKey(JsonKey.ROLES) - && null != userRequest.getRequest().get(JsonKey.ROLES) - && !(userRequest.getRequest().get(JsonKey.ROLES) instanceof List)) { - throw new ProjectCommonException( - ResponseCode.dataTypeError.getErrorCode(), - ProjectUtil.formatMessage( - ResponseCode.dataTypeError.getErrorMessage(), JsonKey.ROLES, JsonKey.LIST), - ERROR_CODE); - } - if (userRequest.getRequest().containsKey(JsonKey.LANGUAGE) - && null != userRequest.getRequest().get(JsonKey.LANGUAGE) - && !(userRequest.getRequest().get(JsonKey.LANGUAGE) instanceof List)) { - throw new ProjectCommonException( - ResponseCode.dataTypeError.getErrorCode(), - ProjectUtil.formatMessage( - ResponseCode.dataTypeError.getErrorMessage(), JsonKey.LANGUAGE, JsonKey.LIST), - ERROR_CODE); - } - } - - private void createUserBasicProfileFieldsValidation(Request userRequest) { - validateParam( - (String) userRequest.getRequest().get(JsonKey.FIRST_NAME), - ResponseCode.mandatoryParamsMissing, - JsonKey.FIRST_NAME); - if (StringUtils.isBlank((String) userRequest.getRequest().get(JsonKey.EMAIL)) - && StringUtils.isBlank((String) userRequest.getRequest().get(JsonKey.PHONE))) { - ProjectCommonException.throwClientErrorException(ResponseCode.emailorPhoneRequired); - } - - if (null != userRequest.getRequest().get(JsonKey.DOB)) { - boolean bool = - ProjectUtil.isDateValidFormat( - ProjectUtil.YEAR_MONTH_DATE_FORMAT, - (String) userRequest.getRequest().get(JsonKey.DOB)); - if (!bool) { - ProjectCommonException.throwClientErrorException(ResponseCode.dateFormatError); - } - } - - if (!StringUtils.isBlank((String) userRequest.getRequest().get(JsonKey.EMAIL)) - && !ProjectUtil.isEmailvalid((String) userRequest.getRequest().get(JsonKey.EMAIL))) { - ProjectCommonException.throwClientErrorException(ResponseCode.emailFormatError); - } else { - emailVerifiedValidation(userRequest); - } - } - - private void emailVerifiedValidation(Request userRequest) { - if (!StringUtils.isBlank((String) userRequest.getRequest().get(JsonKey.EMAIL))) { - if (null != userRequest.getRequest().get(JsonKey.EMAIL_VERIFIED)) { - if (userRequest.getRequest().get(JsonKey.EMAIL_VERIFIED) instanceof Boolean) { - if (!((boolean) userRequest.getRequest().get(JsonKey.EMAIL_VERIFIED))) { - ProjectCommonException.throwClientErrorException(ResponseCode.emailVerifiedError); - } - } else { - ProjectCommonException.throwClientErrorException(ResponseCode.emailVerifiedError); - } - } else { - ProjectCommonException.throwClientErrorException(ResponseCode.emailVerifiedError); - } - } - } - - /** - * Method to validate Address - * - * @param userRequest - */ - @SuppressWarnings("unchecked") - private void addressValidation(Request userRequest) { - Map addrReqMap; - if (userRequest.getRequest().containsKey(JsonKey.ADDRESS) - && null != userRequest.getRequest().get(JsonKey.ADDRESS)) { - if (!(userRequest.getRequest().get(JsonKey.ADDRESS) instanceof List)) { - throw new ProjectCommonException( - ResponseCode.dataTypeError.getErrorCode(), - ProjectUtil.formatMessage( - ResponseCode.dataTypeError.getErrorMessage(), JsonKey.ADDRESS, JsonKey.LIST), - ERROR_CODE); - } else if (userRequest.getRequest().get(JsonKey.ADDRESS) instanceof List) { - List> reqList = - (List>) userRequest.get(JsonKey.ADDRESS); - for (int i = 0; i < reqList.size(); i++) { - addrReqMap = reqList.get(i); - new AddressRequestValidator().validateAddress(addrReqMap, JsonKey.ADDRESS); - } - } - } - } - - /** - * Method to validate educational details of the user - * - * @param userRequest - */ - @SuppressWarnings("unchecked") - private void educationValidation(Request userRequest) { - Map addrReqMap; - Map reqMap; - if (userRequest.getRequest().containsKey(JsonKey.EDUCATION) - && null != userRequest.getRequest().get(JsonKey.EDUCATION)) { - if (!(userRequest.getRequest().get(JsonKey.EDUCATION) instanceof List)) { - throw new ProjectCommonException( - ResponseCode.dataTypeError.getErrorCode(), - ProjectUtil.formatMessage( - ResponseCode.dataTypeError.getErrorMessage(), JsonKey.EDUCATION, JsonKey.LIST), - ERROR_CODE); - } else if (userRequest.getRequest().get(JsonKey.EDUCATION) instanceof List) { - List> reqList = - (List>) userRequest.get(JsonKey.EDUCATION); - for (int i = 0; i < reqList.size(); i++) { - reqMap = reqList.get(i); - if (StringUtils.isBlank((String) reqMap.get(JsonKey.NAME))) { - ProjectCommonException.throwClientErrorException(ResponseCode.educationNameError); - } - if (StringUtils.isBlank((String) reqMap.get(JsonKey.DEGREE))) { - ProjectCommonException.throwClientErrorException(ResponseCode.educationDegreeError); - } - if (reqMap.containsKey(JsonKey.ADDRESS) && null != reqMap.get(JsonKey.ADDRESS)) { - addrReqMap = (Map) reqMap.get(JsonKey.ADDRESS); - new AddressRequestValidator().validateAddress(addrReqMap, JsonKey.EDUCATION); - } - } - } - } - } - - /** - * Method to validate jobProfile of a user - * - * @param userRequest - */ - private void jobProfileValidation(Request userRequest) { - if (userRequest.getRequest().containsKey(JsonKey.JOB_PROFILE) - && null != userRequest.getRequest().get(JsonKey.JOB_PROFILE)) { - if (!(userRequest.getRequest().get(JsonKey.JOB_PROFILE) instanceof List)) { - throw new ProjectCommonException( - ResponseCode.dataTypeError.getErrorCode(), - ProjectUtil.formatMessage( - ResponseCode.dataTypeError.getErrorMessage(), JsonKey.JOB_PROFILE, JsonKey.LIST), - ERROR_CODE); - } else if (userRequest.getRequest().get(JsonKey.JOB_PROFILE) instanceof List) { - validateJob(userRequest); - } - } - } - - private void validateJob(Request userRequest) { - - Map reqMap = null; - List> reqList = - (List>) userRequest.get(JsonKey.JOB_PROFILE); - for (int i = 0; i < reqList.size(); i++) { - reqMap = reqList.get(i); - validateJoinEndDate(reqMap); - validateJobOrgNameAndAddress(reqMap); - } - } - - private void validateJoinEndDate(Map reqMap) { - if (null != reqMap.get(JsonKey.JOINING_DATE)) { - boolean bool = - ProjectUtil.isDateValidFormat( - ProjectUtil.YEAR_MONTH_DATE_FORMAT, (String) reqMap.get(JsonKey.JOINING_DATE)); - if (!bool) { - ProjectCommonException.throwClientErrorException(ResponseCode.dateFormatError); - } - } - if (null != reqMap.get(JsonKey.END_DATE)) { - boolean bool = - ProjectUtil.isDateValidFormat( - ProjectUtil.YEAR_MONTH_DATE_FORMAT, (String) reqMap.get(JsonKey.END_DATE)); - if (!bool) { - ProjectCommonException.throwClientErrorException(ResponseCode.dateFormatError); - } - } - } - - private void validateJobOrgNameAndAddress(Map reqMap) { - Map addrReqMap = null; - if (StringUtils.isBlank((String) reqMap.get(JsonKey.JOB_NAME))) { - ProjectCommonException.throwClientErrorException(ResponseCode.jobNameError); - } - if (StringUtils.isBlank((String) reqMap.get(JsonKey.ORG_NAME))) { - ProjectCommonException.throwClientErrorException(ResponseCode.organisationNameError); - } - if (reqMap.containsKey(JsonKey.ADDRESS) && null != reqMap.get(JsonKey.ADDRESS)) { - addrReqMap = (Map) reqMap.get(JsonKey.ADDRESS); - new AddressRequestValidator().validateAddress(addrReqMap, JsonKey.JOB_PROFILE); - } - } - - @SuppressWarnings("unchecked") - public void validateWebPages(Request request) { - if (request.getRequest().containsKey(JsonKey.WEB_PAGES)) { - List> data = - (List>) request.getRequest().get(JsonKey.WEB_PAGES); - if (null == data || data.isEmpty()) { - ProjectCommonException.throwClientErrorException(ResponseCode.invalidWebPageData); - } - } - } - - private boolean validatePhoneNo(String phone, String countryCode) { - if (phone.contains("+")) { - ProjectCommonException.throwClientErrorException(ResponseCode.invalidPhoneNumber); - } - if (ProjectUtil.validatePhone(phone, countryCode)) { - return true; - } else { - ProjectCommonException.throwClientErrorException(ResponseCode.phoneNoFormatError); - } - return false; - } - - /** - * This method will validate update user data. - * - * @param userRequest Request - */ - public void validateUpdateUserRequest(Request userRequest) { - externalIdsValidation(userRequest, JsonKey.UPDATE); - phoneValidation(userRequest); - updateUserBasicValidation(userRequest); - validateAddressField(userRequest); - validateJobProfileField(userRequest); - validateEducationField(userRequest); - validateUserType(userRequest); - validateUserOrgField(userRequest); - - if (userRequest.getRequest().containsKey(JsonKey.ROOT_ORG_ID) - && StringUtils.isBlank((String) userRequest.getRequest().get(JsonKey.ROOT_ORG_ID))) { - ProjectCommonException.throwClientErrorException(ResponseCode.invalidRootOrganisationId); - } - validateLocationCodes(userRequest); - validateExtIdTypeAndProvider(userRequest); - validateFrameworkDetails(userRequest); - validateRecoveryEmailOrPhone(userRequest); - } - - private void validateUserOrgField(Request userRequest) { - Map request = userRequest.getRequest(); - boolean isPrivate = - BooleanUtils.isTrue((Boolean) userRequest.getContext().get(JsonKey.PRIVATE)); - if (isPrivate - && StringUtils.isBlank((String) request.get(JsonKey.USER_ID)) - && request.containsKey(JsonKey.ORGANISATIONS)) { - ProjectCommonException.throwClientErrorException( - ResponseCode.mandatoryParamsMissing, - ProjectUtil.formatMessage( - ResponseCode.mandatoryParamsMissing.getErrorMessage(), JsonKey.USER_ID)); - } - - if (!isPrivate && request.containsKey(JsonKey.ORGANISATIONS)) { - ProjectCommonException.throwClientErrorException( - ResponseCode.errorUnsupportedField, - ProjectUtil.formatMessage( - ResponseCode.errorUnsupportedField.getErrorMessage(), JsonKey.ORGANISATIONS)); - } - - if (isPrivate - && request.containsKey(JsonKey.ORGANISATIONS) - && !(request.get(JsonKey.ORGANISATIONS) instanceof List)) { - throwInvalidUserOrgData(); - } - - if (isPrivate && request.containsKey(JsonKey.ORGANISATIONS)) { - List list = (List) request.get(JsonKey.ORGANISATIONS); - for (Object map : list) { - if (!(map instanceof Map)) { - throwInvalidUserOrgData(); - } else { - validRolesDataType((Map) map); - } - } - } - } - - private void validRolesDataType(Map map) { - String organisationId = (String) map.get(JsonKey.ORGANISATION_ID); - if (StringUtils.isBlank(organisationId)) { - ProjectCommonException.throwClientErrorException( - ResponseCode.mandatoryParamsMissing, - ProjectUtil.formatMessage( - ResponseCode.mandatoryParamsMissing.getErrorMessage(), JsonKey.ORGANISATION_ID)); - } - if (map.containsKey(JsonKey.ROLES)) { - if (!(map.get(JsonKey.ROLES) instanceof List)) { - ProjectCommonException.throwClientErrorException( - ResponseCode.dataTypeError, - MessageFormat.format( - ResponseCode.dataTypeError.getErrorMessage(), JsonKey.ROLES, JsonKey.LIST)); - } else if (CollectionUtils.isEmpty((List) map.get(JsonKey.ROLES))) { - ProjectCommonException.throwClientErrorException( - ResponseCode.emptyRolesProvided, ResponseCode.emptyRolesProvided.getErrorMessage()); - } - } - } - - private void throwInvalidUserOrgData() { - ProjectCommonException.throwClientErrorException( - ResponseCode.dataTypeError, - MessageFormat.format( - ResponseCode.dataTypeError.getErrorMessage(), - JsonKey.ORGANISATIONS, - String.join(" ", JsonKey.LIST, " of ", JsonKey.MAP))); - } - - private void validateAddressField(Request userRequest) { - if (userRequest.getRequest().get(JsonKey.ADDRESS) != null - && ((List) userRequest.getRequest().get(JsonKey.ADDRESS)).isEmpty()) { - ProjectCommonException.throwClientErrorException(ResponseCode.addressRequired); - } - - if (userRequest.getRequest().get(JsonKey.ADDRESS) != null - && (!((List) userRequest.getRequest().get(JsonKey.ADDRESS)).isEmpty())) { - validateUpdateUserAddress(userRequest); - } - } - - private void validateJobProfileField(Request userRequest) { - if (userRequest.getRequest().get(JsonKey.JOB_PROFILE) != null - && ((List) userRequest.getRequest().get(JsonKey.JOB_PROFILE)).isEmpty()) { - ProjectCommonException.throwClientErrorException(ResponseCode.jobDetailsRequired); - } - - if (userRequest.getRequest().get(JsonKey.JOB_PROFILE) != null - && (!((List) userRequest.getRequest().get(JsonKey.JOB_PROFILE)).isEmpty())) { - validateUpdateUserJobProfile(userRequest); - } - } - - private void validateEducationField(Request userRequest) { - if (userRequest.getRequest().get(JsonKey.EDUCATION) != null - && ((List) userRequest.getRequest().get(JsonKey.EDUCATION)).isEmpty()) { - ProjectCommonException.throwClientErrorException(ResponseCode.educationRequired); - } - - if (userRequest.getRequest().get(JsonKey.EDUCATION) != null - && (!((List) userRequest.getRequest().get(JsonKey.EDUCATION)).isEmpty())) { - validateUpdateUserEducation(userRequest); - } - } - - public void externalIdsValidation(Request userRequest, String operation) { - if (userRequest.getRequest().containsKey(JsonKey.EXTERNAL_IDS) - && (null != userRequest.getRequest().get(JsonKey.EXTERNAL_IDS))) { - if (!(userRequest.getRequest().get(JsonKey.EXTERNAL_IDS) instanceof List)) { - throw new ProjectCommonException( - ResponseCode.dataTypeError.getErrorCode(), - ProjectUtil.formatMessage( - ResponseCode.dataTypeError.getErrorMessage(), JsonKey.EXTERNAL_IDS, JsonKey.LIST), - ERROR_CODE); - } - List> externalIds = - (List>) userRequest.getRequest().get(JsonKey.EXTERNAL_IDS); - validateIndividualExternalId(operation, externalIds); - if (operation.equalsIgnoreCase(JsonKey.CREATE)) { - checkForDuplicateExternalId(externalIds); - } - } - } - - private void validateIndividualExternalId( - String operation, List> externalIds) { - // valid operation type for externalIds in user api. - List operationTypeList = Arrays.asList(JsonKey.ADD, JsonKey.REMOVE, JsonKey.EDIT); - externalIds - .stream() - .forEach( - identity -> { - // check for invalid operation type - if (StringUtils.isNotBlank(identity.get(JsonKey.OPERATION)) - && (!operationTypeList.contains( - (identity.get(JsonKey.OPERATION)).toLowerCase()))) { - throw new ProjectCommonException( - ResponseCode.invalidValue.getErrorCode(), - ProjectUtil.formatMessage( - ResponseCode.invalidValue.getErrorMessage(), - StringFormatter.joinByDot(JsonKey.EXTERNAL_IDS, JsonKey.OPERATION), - identity.get(JsonKey.OPERATION), - String.join(StringFormatter.COMMA, operationTypeList)), - ERROR_CODE); - } - // throw exception for invalid operation if other operation type is coming in - // request - // other than add or null for create user api - if (JsonKey.CREATE.equalsIgnoreCase(operation) - && StringUtils.isNotBlank(identity.get(JsonKey.OPERATION)) - && (!JsonKey.ADD.equalsIgnoreCase(((identity.get(JsonKey.OPERATION)))))) { - throw new ProjectCommonException( - ResponseCode.invalidValue.getErrorCode(), - ProjectUtil.formatMessage( - ResponseCode.invalidValue.getErrorMessage(), - StringFormatter.joinByDot(JsonKey.EXTERNAL_IDS, JsonKey.OPERATION), - identity.get(JsonKey.OPERATION), - JsonKey.ADD), - ERROR_CODE); - } - validateExternalIdMandatoryParam(JsonKey.ID, identity.get(JsonKey.ID)); - validateExternalIdMandatoryParam(JsonKey.PROVIDER, identity.get(JsonKey.PROVIDER)); - validateExternalIdMandatoryParam(JsonKey.ID_TYPE, identity.get(JsonKey.ID_TYPE)); - }); - } - - private void validateExternalIdMandatoryParam(String param, String paramValue) { - if (StringUtils.isBlank(paramValue)) { - throw new ProjectCommonException( - ResponseCode.mandatoryParamsMissing.getErrorCode(), - ProjectUtil.formatMessage( - ResponseCode.mandatoryParamsMissing.getErrorMessage(), - StringFormatter.joinByDot(JsonKey.EXTERNAL_IDS, param)), - ERROR_CODE); - } - } - - private void validateUpdateUserEducation(Request userRequest) { - List> reqList = - (List>) userRequest.get(JsonKey.EDUCATION); - for (int i = 0; i < reqList.size(); i++) { - Map reqMap = reqList.get(i); - if (reqMap.containsKey(JsonKey.IS_DELETED) - && null != reqMap.get(JsonKey.IS_DELETED) - && ((boolean) reqMap.get(JsonKey.IS_DELETED)) - && StringUtils.isBlank((String) reqMap.get(JsonKey.ID))) { - ProjectCommonException.throwClientErrorException(ResponseCode.idRequired); - } - if (!reqMap.containsKey(JsonKey.IS_DELETED) - || (reqMap.containsKey(JsonKey.IS_DELETED) - && (null == reqMap.get(JsonKey.IS_DELETED) - || !(boolean) reqMap.get(JsonKey.IS_DELETED)))) { - educationValidation(userRequest); - } - } - } - - private void validateUpdateUserJobProfile(Request userRequest) { - List> reqList = - (List>) userRequest.get(JsonKey.JOB_PROFILE); - for (int i = 0; i < reqList.size(); i++) { - Map reqMap = reqList.get(i); - if (reqMap.containsKey(JsonKey.IS_DELETED) - && null != reqMap.get(JsonKey.IS_DELETED) - && ((boolean) reqMap.get(JsonKey.IS_DELETED)) - && StringUtils.isBlank((String) reqMap.get(JsonKey.ID))) { - ProjectCommonException.throwClientErrorException(ResponseCode.idRequired); - } - if (!reqMap.containsKey(JsonKey.IS_DELETED) - || (reqMap.containsKey(JsonKey.IS_DELETED) - && (null == reqMap.get(JsonKey.IS_DELETED) - || !(boolean) reqMap.get(JsonKey.IS_DELETED)))) { - jobProfileValidation(userRequest); - } - } - } - - private void validateUpdateUserAddress(Request userRequest) { - List> reqList = - (List>) userRequest.get(JsonKey.ADDRESS); - for (int i = 0; i < reqList.size(); i++) { - Map reqMap = reqList.get(i); - - if (reqMap.containsKey(JsonKey.IS_DELETED) - && null != reqMap.get(JsonKey.IS_DELETED) - && ((boolean) reqMap.get(JsonKey.IS_DELETED)) - && StringUtils.isBlank((String) reqMap.get(JsonKey.ID))) { - ProjectCommonException.throwClientErrorException(ResponseCode.idRequired); - } - if (!reqMap.containsKey(JsonKey.IS_DELETED) - || (reqMap.containsKey(JsonKey.IS_DELETED) - && (null == reqMap.get(JsonKey.IS_DELETED) - || !(boolean) reqMap.get(JsonKey.IS_DELETED)))) { - new AddressRequestValidator().validateAddress(reqMap, JsonKey.ADDRESS); - } - } - } - - @SuppressWarnings("rawtypes") - private void updateUserBasicValidation(Request userRequest) { - fieldsNotAllowed( - Arrays.asList( - JsonKey.REGISTERED_ORG_ID, - JsonKey.ROOT_ORG_ID, - JsonKey.CHANNEL, - JsonKey.USERNAME, - JsonKey.PROVIDER, - JsonKey.ID_TYPE), - userRequest); - validateUserIdOrExternalId(userRequest); - if (userRequest.getRequest().containsKey(JsonKey.FIRST_NAME) - && (StringUtils.isBlank((String) userRequest.getRequest().get(JsonKey.FIRST_NAME)))) { - ProjectCommonException.throwClientErrorException(ResponseCode.firstNameRequired); - } - - if ((userRequest.getRequest().containsKey(JsonKey.EMAIL) - && userRequest.getRequest().get(JsonKey.EMAIL) != null) - && !ProjectUtil.isEmailvalid((String) userRequest.getRequest().get(JsonKey.EMAIL))) { - ProjectCommonException.throwClientErrorException(ResponseCode.emailFormatError); - } - - if (userRequest.getRequest().containsKey(JsonKey.ROLES) - && null != userRequest.getRequest().get(JsonKey.ROLES)) { - if (userRequest.getRequest().get(JsonKey.ROLES) instanceof List - && ((List) userRequest.getRequest().get(JsonKey.ROLES)).isEmpty()) { - ProjectCommonException.throwClientErrorException(ResponseCode.rolesRequired); - } else if (!(userRequest.getRequest().get(JsonKey.ROLES) instanceof List)) { - throw new ProjectCommonException( - ResponseCode.dataTypeError.getErrorCode(), - ProjectUtil.formatMessage( - ResponseCode.dataTypeError.getErrorMessage(), JsonKey.ROLES, JsonKey.LIST), - ERROR_CODE); - } - } - validateLangaugeFields(userRequest); - } - - private void validateUserIdOrExternalId(Request userRequest) { - if ((StringUtils.isBlank((String) userRequest.getRequest().get(JsonKey.USER_ID)) - && StringUtils.isBlank((String) userRequest.getRequest().get(JsonKey.ID))) - && (StringUtils.isBlank((String) userRequest.getRequest().get(JsonKey.EXTERNAL_ID)) - || StringUtils.isBlank( - (String) userRequest.getRequest().get(JsonKey.EXTERNAL_ID_PROVIDER)) - || StringUtils.isBlank( - (String) userRequest.getRequest().get(JsonKey.EXTERNAL_ID_TYPE)))) { - throw new ProjectCommonException( - ResponseCode.mandatoryParamsMissing.getErrorCode(), - ProjectUtil.formatMessage( - ResponseCode.mandatoryParamsMissing.getErrorMessage(), - (StringFormatter.joinByOr( - JsonKey.USER_ID, - StringFormatter.joinByAnd( - StringFormatter.joinByComma(JsonKey.EXTERNAL_ID, JsonKey.EXTERNAL_ID_TYPE), - JsonKey.EXTERNAL_ID_PROVIDER)))), - ERROR_CODE); - } - } - - private void validateLangaugeFields(Request userRequest) { - if (userRequest.getRequest().containsKey(JsonKey.LANGUAGE) - && null != userRequest.getRequest().get(JsonKey.LANGUAGE)) { - if (userRequest.getRequest().get(JsonKey.LANGUAGE) instanceof List - && ((List) userRequest.getRequest().get(JsonKey.LANGUAGE)).isEmpty()) { - ProjectCommonException.throwClientErrorException(ResponseCode.languageRequired); - } else if (!(userRequest.getRequest().get(JsonKey.LANGUAGE) instanceof List)) { - throw new ProjectCommonException( - ResponseCode.dataTypeError.getErrorCode(), - ProjectUtil.formatMessage( - ResponseCode.dataTypeError.getErrorMessage(), JsonKey.LANGUAGE, JsonKey.LIST), - ERROR_CODE); - } - } - } - - /** - * This method will validate change password requested data. - * - * @param userRequest Request - */ - public void validateChangePassword(Request userRequest) { - if (userRequest.getRequest().get(JsonKey.PASSWORD) == null - || (StringUtils.isBlank((String) userRequest.getRequest().get(JsonKey.PASSWORD)))) { - ProjectCommonException.throwClientErrorException(ResponseCode.passwordRequired); - } - if (userRequest.getRequest().get(JsonKey.NEW_PASSWORD) == null) { - ProjectCommonException.throwClientErrorException(ResponseCode.newPasswordRequired); - } - if (StringUtils.isBlank((String) userRequest.getRequest().get(JsonKey.NEW_PASSWORD))) { - ProjectCommonException.throwClientErrorException(ResponseCode.newPasswordEmpty); - } - } - - /** - * This method will validate verifyUser requested data. - * - * @param userRequest Request - */ - public void validateVerifyUser(Request userRequest) { - if (StringUtils.isBlank((String) userRequest.getRequest().get(JsonKey.LOGIN_ID))) { - ProjectCommonException.throwClientErrorException(ResponseCode.loginIdRequired); - } - } - - /** - * Either user will send UserId or (provider and externalId). - * - * @param request - */ - public void validateAssignRole(Request request) { - if (StringUtils.isBlank((String) request.getRequest().get(JsonKey.USER_ID))) { - ProjectCommonException.throwClientErrorException(ResponseCode.userIdRequired); - } - - if (request.getRequest().get(JsonKey.ROLES) == null - || !(request.getRequest().get(JsonKey.ROLES) instanceof List)) { - throw new ProjectCommonException( - ResponseCode.dataTypeError.getErrorCode(), - ProjectUtil.formatMessage( - ResponseCode.dataTypeError.getErrorMessage(), JsonKey.ROLES, JsonKey.LIST), - ERROR_CODE); - } - - String organisationId = (String) request.getRequest().get(JsonKey.ORGANISATION_ID); - String externalId = (String) request.getRequest().get(JsonKey.EXTERNAL_ID); - String provider = (String) request.getRequest().get(JsonKey.PROVIDER); - if (StringUtils.isBlank(organisationId) - && (StringUtils.isBlank(externalId) || StringUtils.isBlank(provider))) { - throw new ProjectCommonException( - ResponseCode.mandatoryParamsMissing.getErrorCode(), - ProjectUtil.formatMessage( - ResponseCode.mandatoryParamsMissing.getErrorMessage(), - (StringFormatter.joinByOr( - JsonKey.ORGANISATION_ID, - StringFormatter.joinByAnd(JsonKey.EXTERNAL_ID, JsonKey.PROVIDER)))), - ERROR_CODE); - } - } - - /** @param request */ - public void validateForgotPassword(Request request) { - if (request.getRequest().get(JsonKey.USERNAME) == null - || StringUtils.isBlank((String) request.getRequest().get(JsonKey.USERNAME))) { - throw new ProjectCommonException( - ResponseCode.userNameRequired.getErrorCode(), - ResponseCode.userNameRequired.getErrorMessage(), - ERROR_CODE); - } - } - - /** - * This method will validate bulk api user data. - * - * @param userRequest Request - */ - public void validateBulkUserData(Request userRequest) { - externalIdsValidation(userRequest, JsonKey.BULK_USER_UPLOAD); - createUserBasicValidation(userRequest); - phoneValidation(userRequest); - validateWebPages(userRequest); - validateExtIdTypeAndProvider(userRequest); - if (StringUtils.isBlank((String) userRequest.getRequest().get(JsonKey.USERNAME)) - && (StringUtils.isBlank((String) userRequest.getRequest().get(JsonKey.EXTERNAL_ID_PROVIDER)) - || StringUtils.isBlank((String) userRequest.getRequest().get(JsonKey.EXTERNAL_ID)) - || StringUtils.isBlank( - (String) userRequest.getRequest().get(JsonKey.EXTERNAL_ID_TYPE)))) { - throw new ProjectCommonException( - ResponseCode.mandatoryParamsMissing.getErrorCode(), - ProjectUtil.formatMessage( - ResponseCode.mandatoryParamsMissing.getErrorMessage(), - (StringFormatter.joinByOr( - JsonKey.USERNAME, - StringFormatter.joinByAnd( - StringFormatter.joinByComma(JsonKey.EXTERNAL_ID, JsonKey.EXTERNAL_ID_TYPE), - JsonKey.EXTERNAL_ID_PROVIDER)))), - ERROR_CODE); - } - } - - private void validateExtIdTypeAndProvider(Request userRequest) { - if ((StringUtils.isNotBlank((String) userRequest.getRequest().get(JsonKey.EXTERNAL_ID_PROVIDER)) - && StringUtils.isNotBlank((String) userRequest.getRequest().get(JsonKey.EXTERNAL_ID)) - && StringUtils.isNotBlank( - (String) userRequest.getRequest().get(JsonKey.EXTERNAL_ID_TYPE)))) { - return; - } else if (StringUtils.isBlank( - (String) userRequest.getRequest().get(JsonKey.EXTERNAL_ID_PROVIDER)) - && StringUtils.isBlank((String) userRequest.getRequest().get(JsonKey.EXTERNAL_ID)) - && StringUtils.isBlank((String) userRequest.getRequest().get(JsonKey.EXTERNAL_ID_TYPE))) { - return; - } else { - throw new ProjectCommonException( - ResponseCode.dependentParamsMissing.getErrorCode(), - ProjectUtil.formatMessage( - ResponseCode.dependentParamsMissing.getErrorMessage(), - StringFormatter.joinByComma( - JsonKey.EXTERNAL_ID, JsonKey.EXTERNAL_ID_TYPE, JsonKey.EXTERNAL_ID_PROVIDER)), - ERROR_CODE); - } - } - - private void checkForDuplicateExternalId(List> list) { - List> checkedList = new ArrayList<>(); - for (Map externalId : list) { - for (Map checkedExternalId : checkedList) { - String provider = checkedExternalId.get(JsonKey.PROVIDER); - String idType = checkedExternalId.get(JsonKey.ID_TYPE); - if (provider.equalsIgnoreCase(externalId.get(JsonKey.PROVIDER)) - && idType.equalsIgnoreCase(externalId.get(JsonKey.ID_TYPE))) { - String exceptionMsg = - MessageFormat.format( - ResponseCode.duplicateExternalIds.getErrorMessage(), idType, provider); - ProjectCommonException.throwClientErrorException( - ResponseCode.duplicateExternalIds, exceptionMsg); - } - } - checkedList.add(externalId); - } - } - - @SuppressWarnings("unchecked") - private void validateFrameworkDetails(Request request) { - if (request.getRequest().containsKey(JsonKey.FRAMEWORK) - && (!(request.getRequest().get(JsonKey.FRAMEWORK) instanceof Map))) { - throw new ProjectCommonException( - ResponseCode.dataTypeError.getErrorCode(), - ResponseCode.dataTypeError.getErrorMessage(), - ERROR_CODE, - JsonKey.FRAMEWORK, - JsonKey.MAP); - } else { - Map framework = - (Map) request.getRequest().get(JsonKey.FRAMEWORK); - if (!MapUtils.isEmpty(framework)) { - if (framework.get(JsonKey.ID) instanceof List) { - List frameworkId = (List) framework.get(JsonKey.ID); - if (CollectionUtils.isEmpty(frameworkId)) { - ProjectCommonException.throwClientErrorException( - ResponseCode.mandatoryParamsMissing, - MessageFormat.format( - ResponseCode.mandatoryParamsMissing.getErrorMessage(), - StringFormatter.joinByDot(JsonKey.FRAMEWORK, JsonKey.ID))); - } else if (frameworkId.size() > 1) { - throw new ProjectCommonException( - ResponseCode.errorInvalidParameterSize.getErrorCode(), - ResponseCode.errorInvalidParameterSize.getErrorMessage(), - ERROR_CODE, - StringFormatter.joinByDot(JsonKey.FRAMEWORK, JsonKey.ID), - "1", - String.valueOf(frameworkId.size())); - } - } else if (framework.get(JsonKey.ID) instanceof String) { - String frameworkId = (String) framework.get(JsonKey.ID); - if (StringUtils.isBlank(frameworkId)) { - ProjectCommonException.throwClientErrorException( - ResponseCode.mandatoryParamsMissing, - MessageFormat.format( - ResponseCode.mandatoryParamsMissing.getErrorMessage(), - StringFormatter.joinByDot(JsonKey.FRAMEWORK, JsonKey.ID))); - } - } - } - } - } - - @SuppressWarnings("unchecked") - public void validateMandatoryFrameworkFields( - Map userMap, - List frameworkFields, - List frameworkMandatoryFields) { - if (userMap.containsKey(JsonKey.FRAMEWORK)) { - Map frameworkRequest = (Map) userMap.get(JsonKey.FRAMEWORK); - for (String field : frameworkFields) { - if (CollectionUtils.isNotEmpty(frameworkMandatoryFields) - && frameworkMandatoryFields.contains(field)) { - if (!frameworkRequest.containsKey(field)) { - validateParam(null, ResponseCode.mandatoryParamsMissing, field); - } - validateListParamWithPrefix(frameworkRequest, JsonKey.FRAMEWORK, field); - List fieldValue = (List) frameworkRequest.get(field); - if (fieldValue.isEmpty()) { - throw new ProjectCommonException( - ResponseCode.errorMandatoryParamsEmpty.getErrorCode(), - ResponseCode.errorMandatoryParamsEmpty.getErrorMessage(), - ERROR_CODE, - StringFormatter.joinByDot(JsonKey.FRAMEWORK, field)); - } - } else { - if (frameworkRequest.containsKey(field) - && frameworkRequest.get(field) != null - && !(frameworkRequest.get(field) instanceof List)) { - throw new ProjectCommonException( - ResponseCode.dataTypeError.getErrorCode(), - ResponseCode.dataTypeError.getErrorMessage(), - ERROR_CODE, - field, - JsonKey.LIST); - } - } - } - List frameworkRequestFieldList = - frameworkRequest.keySet().stream().collect(Collectors.toList()); - for (String frameworkRequestField : frameworkRequestFieldList) { - if (!frameworkFields.contains(frameworkRequestField)) { - throw new ProjectCommonException( - ResponseCode.errorUnsupportedField.getErrorCode(), - ResponseCode.errorUnsupportedField.getErrorMessage(), - ERROR_CODE, - StringFormatter.joinByDot(JsonKey.FRAMEWORK, frameworkRequestField)); - } - } - } - } - - @SuppressWarnings("unchecked") - public void validateFrameworkCategoryValues( - Map userMap, Map>> frameworkMap) { - Map> fwRequest = - (Map>) userMap.get(JsonKey.FRAMEWORK); - for (Map.Entry> fwRequestFieldEntry : fwRequest.entrySet()) { - if (!fwRequestFieldEntry.getValue().isEmpty()) { - List allowedFieldValues = - getKeyValueFromFrameWork(fwRequestFieldEntry.getKey(), frameworkMap) - .stream() - .map(fieldMap -> fieldMap.get(JsonKey.NAME)) - .collect(Collectors.toList()); - - List fwRequestFieldList = fwRequestFieldEntry.getValue(); - - for (String fwRequestField : fwRequestFieldList) { - if (!allowedFieldValues.contains(fwRequestField)) { - throw new ProjectCommonException( - ResponseCode.invalidParameterValue.getErrorCode(), - ResponseCode.invalidParameterValue.getErrorMessage(), - ResponseCode.CLIENT_ERROR.getResponseCode(), - fwRequestField, - StringFormatter.joinByDot(JsonKey.FRAMEWORK, fwRequestFieldEntry.getKey())); - } - } - } - } - } - - private List> getKeyValueFromFrameWork( - String key, Map>> frameworkMap) { - if (frameworkMap.get(key) == null) { - throw new ProjectCommonException( - ResponseCode.errorUnsupportedField.getErrorCode(), - MessageFormat.format( - ResponseCode.errorUnsupportedField.getErrorMessage(), - key + " in " + JsonKey.FRAMEWORK), - ResponseCode.CLIENT_ERROR.getResponseCode()); - } - return frameworkMap.get(key); - } - - private void validateUserType(Request userRequest) { - String userType = (String) userRequest.getRequest().get(JsonKey.USER_TYPE); - - if (userType != null - && (!JsonKey.OTHER.equalsIgnoreCase(userType)) - && (!JsonKey.TEACHER.equalsIgnoreCase(userType))) { - ProjectCommonException.throwClientErrorException( - ResponseCode.invalidParameterValue, - MessageFormat.format( - ResponseCode.invalidParameterValue.getErrorMessage(), - new String[] {userType, JsonKey.USER_TYPE})); - } - } - - public void validateUserMergeRequest( - Request request, String authUserToken, String sourceUserToken) { - if (StringUtils.isBlank((String) request.getRequest().get(JsonKey.FROM_ACCOUNT_ID))) { - throw new ProjectCommonException( - ResponseCode.fromAccountIdRequired.getErrorCode(), - ResponseCode.fromAccountIdRequired.getErrorMessage(), - ERROR_CODE); - } - - if (StringUtils.isBlank((String) request.getRequest().get(JsonKey.TO_ACCOUNT_ID))) { - throw new ProjectCommonException( - ResponseCode.toAccountIdRequired.getErrorCode(), - ResponseCode.toAccountIdRequired.getErrorMessage(), - ERROR_CODE); - } - - if (StringUtils.isBlank(authUserToken)) { - createClientError( - ResponseCode.mandatoryHeaderParamsMissing, JsonKey.X_AUTHENTICATED_USER_TOKEN); - } - - if (StringUtils.isBlank(authUserToken)) { - createClientError( - ResponseCode.mandatoryHeaderParamsMissing, JsonKey.X_AUTHENTICATED_USER_TOKEN); - } - if (StringUtils.isBlank(sourceUserToken)) { - createClientError(ResponseCode.mandatoryHeaderParamsMissing, JsonKey.X_SOURCE_USER_TOKEN); - } - } - - public void validateCertValidationRequest(Request request) { - if (StringUtils.isBlank((String) request.getRequest().get(JsonKey.CERT_ID))) { - createClientError(ResponseCode.mandatoryParamsMissing, JsonKey.CERT_ID); - } - if (StringUtils.isBlank((String) request.getRequest().get(JsonKey.ACCESS_CODE))) { - createClientError(ResponseCode.mandatoryParamsMissing, JsonKey.ACCESS_CODE); - } - } - - private void createClientError(ResponseCode responseCode, String field) { - throw new ProjectCommonException( - responseCode.getErrorCode(), - ProjectUtil.formatMessage(responseCode.getErrorMessage(), field), - ERROR_CODE); - } - - private void validateRecoveryEmailOrPhone(Request userRequest) { - if (StringUtils.isNotBlank((String) userRequest.get(JsonKey.RECOVERY_EMAIL))) { - validateEmail((String) userRequest.get(JsonKey.RECOVERY_EMAIL)); - } - if (StringUtils.isNotBlank((String) userRequest.get(JsonKey.RECOVERY_PHONE))) { - validatePhone((String) userRequest.get(JsonKey.RECOVERY_PHONE)); - } - } -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/request/UserTenantMigrationRequestValidator.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/request/UserTenantMigrationRequestValidator.java deleted file mode 100644 index cc1539747..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/request/UserTenantMigrationRequestValidator.java +++ /dev/null @@ -1,26 +0,0 @@ -package org.sunbird.common.request; - -import java.util.Map; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.responsecode.ResponseCode; - -/** - * 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 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/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/request/certificatevalidator/CertAddRequestValidator.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/request/certificatevalidator/CertAddRequestValidator.java deleted file mode 100644 index 7fccb6cb0..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/request/certificatevalidator/CertAddRequestValidator.java +++ /dev/null @@ -1,81 +0,0 @@ -package org.sunbird.common.request.certificatevalidator; - -import com.google.common.collect.Lists; -import java.text.MessageFormat; -import java.util.List; -import java.util.Map; -import org.apache.commons.lang.StringUtils; -import org.sunbird.common.exception.ProjectCommonException; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.request.BaseRequestValidator; -import org.sunbird.common.request.Request; -import org.sunbird.common.responsecode.ResponseCode; - - -/** - * this class is responsible to validate the certificate add request - * - * @author anmolgupta - */ -public class CertAddRequestValidator extends BaseRequestValidator { - public static final String PDF_URL = "pdfUrl"; - - private Request request; - static List mandatoryParamsList = - Lists.newArrayList(JsonKey.ID, JsonKey.ACCESS_CODE, JsonKey.PDF_URL, JsonKey.USER_ID); - - private CertAddRequestValidator(Request request) { - this.request = request; - } - - /** - * this method we should use to get the instance of the validator class - * - * @param request - * @return - */ - public static CertAddRequestValidator getInstance(Request request) { - return new CertAddRequestValidator(request); - } - - /** this method should be call to validate the request */ - public void validate() { - checkMandatoryFieldsPresent(request.getRequest(), mandatoryParamsList); - validateMandatoryJsonData(); - } - - private void validateMandatoryJsonData() { - validatePresence(); - validateDataType(); - } - - private void validateDataType() { - if (!(request.get(JsonKey.JSON_DATA) instanceof Map)) { - throw new ProjectCommonException( - ResponseCode.dataTypeError.getErrorCode(), - MessageFormat.format( - ResponseCode.dataTypeError.getErrorMessage(), JsonKey.JSON_DATA, "MAP"), - ResponseCode.CLIENT_ERROR.getResponseCode()); - } - } - - private void validatePresence() { - if (null == request.get(JsonKey.JSON_DATA)) { - throw new ProjectCommonException( - ResponseCode.mandatoryParamsMissing.getErrorCode(), - ResponseCode.mandatoryParamsMissing.getErrorMessage(), - ResponseCode.CLIENT_ERROR.getResponseCode(), - JsonKey.JSON_DATA); - } - } - - public void validateDownlaodFileData() { - if (StringUtils.isBlank((String) request.getRequest().get(PDF_URL))) { - throw new ProjectCommonException( - ResponseCode.mandatoryParamsMissing.getErrorCode(), - ResponseCode.mandatoryParamsMissing.getErrorMessage(), - ResponseCode.CLIENT_ERROR.getResponseCode(), - PDF_URL); - } - } -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/request/orgvalidator/BaseOrgRequestValidator.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/request/orgvalidator/BaseOrgRequestValidator.java deleted file mode 100644 index 376622fb8..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/request/orgvalidator/BaseOrgRequestValidator.java +++ /dev/null @@ -1,35 +0,0 @@ -package org.sunbird.common.request.orgvalidator; - -import java.text.MessageFormat; -import org.apache.commons.lang3.StringUtils; -import org.sunbird.common.exception.ProjectCommonException; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.request.BaseRequestValidator; -import org.sunbird.common.request.Request; -import org.sunbird.common.responsecode.ResponseCode; - -public class BaseOrgRequestValidator extends BaseRequestValidator { - - public static final int ERROR_CODE = ResponseCode.CLIENT_ERROR.getResponseCode(); - - public void validateOrgReference(Request request) { - validateParam( - (String) request.getRequest().get(JsonKey.ORGANISATION_ID), - ResponseCode.mandatoryParamsMissing, - JsonKey.ORGANISATION_ID); - } - - public void validateRootOrgChannel(Request request) { - if ((null != request.getRequest().get(JsonKey.IS_ROOT_ORG) - && (Boolean) request.getRequest().get(JsonKey.IS_ROOT_ORG)) - && StringUtils.isEmpty((String) request.getRequest().get(JsonKey.CHANNEL))) { - throw new ProjectCommonException( - ResponseCode.dependentParameterMissing.getErrorCode(), - MessageFormat.format( - ResponseCode.dependentParameterMissing.getErrorMessage(), - JsonKey.CHANNEL, - JsonKey.IS_ROOT_ORG), - ERROR_CODE); - } - } -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/request/orgvalidator/KeyManagementValidator.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/request/orgvalidator/KeyManagementValidator.java deleted file mode 100644 index 3d2ff61fc..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/request/orgvalidator/KeyManagementValidator.java +++ /dev/null @@ -1,92 +0,0 @@ -package org.sunbird.common.request.orgvalidator; - -import org.sunbird.common.exception.ProjectCommonException; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.request.BaseRequestValidator; -import org.sunbird.common.request.Request; -import org.sunbird.common.responsecode.ResponseCode; - -import java.text.MessageFormat; -import java.util.List; - -/** - * this class is used to validate the request of the OrgAssignKeys Controller - * @author anmolgupta - */ -public class KeyManagementValidator extends BaseRequestValidator { - - - private Request request; - - private KeyManagementValidator(Request request) { - this.request = request; - } - - - /** - * this method should be used to get the instance of the class - * @param request - * @return - */ - public static KeyManagementValidator getInstance(Request request){ - return new KeyManagementValidator(request); - } - - - /** - * this method should be used to validate the OrgAssignKeysController request. - */ - public void validate(){ - id(); - signKeys(); - encKeys(); - - } - - private void id(){ - validateParam( - (String) request.getRequest().get(JsonKey.ID), - ResponseCode.mandatoryParamsMissing, - JsonKey.ID); - } - - private void signKeys(){ - validateKeyPresence(JsonKey.SIGN_KEYS); - validateListTypeObject(JsonKey.SIGN_KEYS); - validateSize(JsonKey.SIGN_KEYS); - } - - private void encKeys(){ - validateKeyPresence(JsonKey.ENC_KEYS); - validateListTypeObject(JsonKey.ENC_KEYS); - validateSize(JsonKey.ENC_KEYS); - } - - private void validateListTypeObject(String key){ - if(!(request.get(key) instanceof List)){ - throw new ProjectCommonException( - ResponseCode.dataTypeError.getErrorCode(), - MessageFormat.format( - ResponseCode.dataTypeError.getErrorMessage(), key, "List"), - ResponseCode.CLIENT_ERROR.getResponseCode()); - } - } - private void validateKeyPresence(String key){ - if(!request.getRequest().containsKey(key)){ - throw new ProjectCommonException( - ResponseCode.mandatoryParamsMissing.getErrorCode(), - ResponseCode.mandatoryParamsMissing.getErrorMessage(), - ResponseCode.CLIENT_ERROR.getResponseCode(),key); - } - } - - private void validateSize(String key){ - if(((List)request.get(key)).size()==0){ - throw new ProjectCommonException( - ResponseCode.errorMandatoryParamsEmpty.getErrorCode(), - ResponseCode.errorMandatoryParamsEmpty.getErrorMessage(), - ResponseCode.CLIENT_ERROR.getResponseCode(),key); - } - - } -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/request/orgvalidator/OrgMemberRequestValidator.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/request/orgvalidator/OrgMemberRequestValidator.java deleted file mode 100644 index 21e9b9356..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/request/orgvalidator/OrgMemberRequestValidator.java +++ /dev/null @@ -1,74 +0,0 @@ -package org.sunbird.common.request.orgvalidator; - -import java.text.MessageFormat; -import java.util.List; -import org.apache.commons.lang3.StringUtils; -import org.sunbird.common.exception.ProjectCommonException; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.models.util.ProjectLogger; -import org.sunbird.common.request.Request; -import org.sunbird.common.responsecode.ResponseCode; - -public class OrgMemberRequestValidator extends BaseOrgRequestValidator { - - public void validateAddMemberRequest(Request request) { - validateCommonParams(request); - if (request.getRequest().containsKey(JsonKey.ROLES) - && (!(request.getRequest().get(JsonKey.ROLES) instanceof List))) { - throw new ProjectCommonException( - ResponseCode.dataTypeError.getErrorCode(), - MessageFormat.format( - ResponseCode.dataTypeError.getErrorMessage(), JsonKey.ROLES, JsonKey.LIST), - ERROR_CODE); - } - } - - private void validateCommonParams(Request request) { - if (StringUtils.isBlank((String) request.getRequest().get(JsonKey.USER_ID))) { - ProjectLogger.log( - "OrgMemberRequestValidator : validateCommonParams : UserId is missing. Validating userExternalId"); - validateCommonUserParams(request); - } - if (StringUtils.isBlank((String) request.getRequest().get(JsonKey.ORGANISATION_ID))) { - ProjectLogger.log( - "OrgMemberRequestValidator : validateCommonParams : OrganizationId is missing. Validating ExternalId"); - validateCommonOrgParams(request); - } - } - - private void validateCommonOrgParams(Request request) { - if (StringUtils.isBlank((String) request.getRequest().get(JsonKey.EXTERNAL_ID))) { - ProjectCommonException.throwClientErrorException( - ResponseCode.mandatoryParamsMissing, - " Please provide organizationId or ExternalId,Provider "); - } - validateParam( - (String) request.getRequest().get(JsonKey.PROVIDER), - ResponseCode.mandatoryParamsMissing, - JsonKey.PROVIDER); - } - - private void validateCommonUserParams(Request request) { - if (StringUtils.isBlank((String) request.getRequest().get(JsonKey.USER_EXTERNAL_ID))) { - ProjectCommonException.throwClientErrorException( - ResponseCode.mandatoryParamsMissing, - " Please provide userId or userExternalId,userProvider,userIdType "); - } - validateParam( - (String) request.getRequest().get(JsonKey.USER_PROVIDER), - ResponseCode.mandatoryParamsMissing, - JsonKey.USER_PROVIDER); - validateParam( - (String) request.getRequest().get(JsonKey.USER_ID_TYPE), - ResponseCode.mandatoryParamsMissing, - JsonKey.USER_ID_TYPE); - } - - public void validateCommon(Request request) { - validateOrgReference(request); - validateParam( - (String) request.getRequest().get(JsonKey.USER_ID), - ResponseCode.mandatoryParamsMissing, - JsonKey.USER_ID); - } -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/request/orgvalidator/OrgRequestValidator.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/request/orgvalidator/OrgRequestValidator.java deleted file mode 100644 index 06456dd02..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/request/orgvalidator/OrgRequestValidator.java +++ /dev/null @@ -1,105 +0,0 @@ -package org.sunbird.common.request.orgvalidator; - -import java.text.MessageFormat; -import java.util.Map; -import org.apache.commons.collections.MapUtils; -import org.apache.commons.lang3.StringUtils; -import org.sunbird.common.exception.ProjectCommonException; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.models.util.ProjectUtil; -import org.sunbird.common.request.AddressRequestValidator; -import org.sunbird.common.request.Request; -import org.sunbird.common.responsecode.ResponseCode; - -public class OrgRequestValidator extends BaseOrgRequestValidator { - - private static final int ERROR_CODE = ResponseCode.CLIENT_ERROR.getResponseCode(); - - public void validateCreateOrgRequest(Request orgRequest) { - - validateParam( - (String) orgRequest.getRequest().get(JsonKey.ORG_NAME), - ResponseCode.mandatoryParamsMissing, - JsonKey.ORG_NAME); - validateRootOrgChannel(orgRequest); - validateLicense(orgRequest); - - Map address = - (Map) orgRequest.getRequest().get(JsonKey.ADDRESS); - if (MapUtils.isNotEmpty(address)) { - new AddressRequestValidator().validateAddress(address, JsonKey.ORGANISATION); - } - validateLocationIdOrCode(orgRequest); - } - - private void validateLicense(Request orgRequest) { - if (orgRequest.getRequest().containsKey(JsonKey.IS_ROOT_ORG) - && (boolean) orgRequest.getRequest().get(JsonKey.IS_ROOT_ORG) - && orgRequest.getRequest().containsKey(JsonKey.LICENSE) - && StringUtils.isBlank((String) orgRequest.getRequest().get(JsonKey.LICENSE))) { - throw new ProjectCommonException( - ResponseCode.invalidParameterValue.getErrorCode(), - MessageFormat.format( - ResponseCode.invalidParameterValue.getErrorMessage(), - (String) orgRequest.getRequest().get(JsonKey.LICENSE), - JsonKey.LICENSE), - ERROR_CODE); - } - } - - public void validateUpdateOrgRequest(Request request) { - validateOrgReference(request); - if (request.getRequest().containsKey(JsonKey.ROOT_ORG_ID) - && StringUtils.isEmpty((String) request.getRequest().get(JsonKey.ROOT_ORG_ID))) { - throw new ProjectCommonException( - ResponseCode.invalidRootOrganisationId.getErrorCode(), - ResponseCode.invalidRootOrganisationId.getErrorMessage(), - ERROR_CODE); - } - if (request.getRequest().get(JsonKey.STATUS) != null) { - throw new ProjectCommonException( - ResponseCode.invalidRequestParameter.getErrorCode(), - ProjectUtil.formatMessage( - ResponseCode.invalidRequestParameter.getErrorMessage(), JsonKey.STATUS), - ERROR_CODE); - } - - validateRootOrgChannel(request); - validateLocationIdOrCode(request); - Map address = (Map) request.getRequest().get(JsonKey.ADDRESS); - if (MapUtils.isNotEmpty(address)) { - new AddressRequestValidator().validateAddress(address, JsonKey.ORGANISATION); - } - } - - public void validateUpdateOrgStatusRequest(Request request) { - validateOrgReference(request); - - if (!request.getRequest().containsKey(JsonKey.STATUS)) { - throw new ProjectCommonException( - ResponseCode.invalidRequestData.getErrorCode(), - ResponseCode.invalidRequestData.getErrorMessage(), - ERROR_CODE); - } - - if (!(request.getRequest().get(JsonKey.STATUS) instanceof Integer)) { - throw new ProjectCommonException( - ResponseCode.invalidRequestData.getErrorCode(), - ResponseCode.invalidRequestData.getErrorMessage(), - ERROR_CODE); - } - } - - private void validateLocationIdOrCode(Request orgRequest) { - validateListParam(orgRequest.getRequest(), JsonKey.LOCATION_IDS, JsonKey.LOCATION_CODE); - if (orgRequest.getRequest().get(JsonKey.LOCATION_IDS) != null - && orgRequest.getRequest().get(JsonKey.LOCATION_CODE) != null) { - ProjectCommonException.throwClientErrorException( - ResponseCode.errorAttributeConflict, - MessageFormat.format( - ResponseCode.errorAttributeConflict.getErrorMessage(), - JsonKey.LOCATION_CODE, - JsonKey.LOCATION_IDS)); - } - } -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/request/orgvalidator/OrgTypeRequestValidator.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/request/orgvalidator/OrgTypeRequestValidator.java deleted file mode 100644 index ad16b3884..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/request/orgvalidator/OrgTypeRequestValidator.java +++ /dev/null @@ -1,23 +0,0 @@ -package org.sunbird.common.request.orgvalidator; - -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.request.Request; -import org.sunbird.common.responsecode.ResponseCode; - -public class OrgTypeRequestValidator extends BaseOrgRequestValidator { - - public void validateUpdateOrgTypeRequest(Request request) { - validateCreateOrgTypeRequest(request); - validateParam( - (String) request.getRequest().get(JsonKey.ID), - ResponseCode.mandatoryParamsMissing, - JsonKey.ID); - } - - public void validateCreateOrgTypeRequest(Request request) { - validateParam( - (String) request.getRequest().get(JsonKey.NAME), - ResponseCode.mandatoryParamsMissing, - JsonKey.NAME); - } -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/request/package-info.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/request/package-info.java deleted file mode 100644 index af17271ba..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/request/package-info.java +++ /dev/null @@ -1,3 +0,0 @@ -/** */ -/** @author Manzarul */ -package org.sunbird.common.request; diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/responsecode/package-info.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/responsecode/package-info.java deleted file mode 100644 index b6c7ea9e2..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/responsecode/package-info.java +++ /dev/null @@ -1,3 +0,0 @@ -/** */ -/** @author Manzarul */ -package org.sunbird.common.responsecode; diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/services/ProfileCompletenessService.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/services/ProfileCompletenessService.java deleted file mode 100644 index 63d0e10ec..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/services/ProfileCompletenessService.java +++ /dev/null @@ -1,21 +0,0 @@ -/** */ -package org.sunbird.common.services; - -import java.util.Map; - -/** - * This interface will have method to compute the profile completeness. - * - * @author Manzarul - */ -public interface ProfileCompletenessService { - - /** - * This method will compute the user profile completeness percentage based on attribute weighted - * settings. it will provide completeness percentage value and list of all missing keys. - * - * @param profileData Map - * @return Map - */ - Map computeProfile(Map profileData); -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/services/impl/ProfileCompletenessFactory.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/services/impl/ProfileCompletenessFactory.java deleted file mode 100644 index d544cf95f..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/services/impl/ProfileCompletenessFactory.java +++ /dev/null @@ -1,13 +0,0 @@ -/** */ -package org.sunbird.common.services.impl; - -import org.sunbird.common.services.ProfileCompletenessService; - -/** @author Manzarul */ -public class ProfileCompletenessFactory { - - /** @return */ - public static ProfileCompletenessService getInstance() { - return new ProfileCompletenessServiceImpl(); - } -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/services/impl/ProfileCompletenessServiceImpl.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/services/impl/ProfileCompletenessServiceImpl.java deleted file mode 100644 index e14dbbbda..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/services/impl/ProfileCompletenessServiceImpl.java +++ /dev/null @@ -1,101 +0,0 @@ -/** */ -package org.sunbird.common.services.impl; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import org.apache.commons.lang3.StringUtils; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.models.util.PropertiesCache; -import org.sunbird.common.services.ProfileCompletenessService; - -/** @author Manzarul */ -public class ProfileCompletenessServiceImpl implements ProfileCompletenessService { - - @Override - public Map computeProfile(Map profileData) { - Map response = new HashMap<>(); - float completedCount = 0; - if (profileData == null || profileData.size() == 0) { - response.put(JsonKey.COMPLETENESS, (int) Math.ceil(completedCount)); - response.put(JsonKey.MISSING_FIELDS, findMissingAttribute(profileData)); - return response; - } - Iterator> itr = profileData.entrySet().iterator(); - while (itr.hasNext()) { - Entry entry = itr.next(); - Object value = entry.getValue(); - if (value instanceof List) { - List list = (List) value; - if (list.size() > 0) { - completedCount = completedCount + getValue(entry.getKey()); - } - } else if (value instanceof Map) { - Map map = (Map) value; - if (map != null && map.size() > 0) { - completedCount = completedCount + getValue(entry.getKey()); - } - } else { - if (value != null && !StringUtils.isBlank(value.toString())) { - completedCount = completedCount + getValue(entry.getKey()); - } - } - } - response.put(JsonKey.COMPLETENESS, (int) Math.ceil(completedCount)); - response.put(JsonKey.MISSING_FIELDS, findMissingAttribute(profileData)); - return response; - } - - /** - * This method will provide weighted value for particular attribute - * - * @param key String - * @return float - */ - private float getValue(String key) { - return PropertiesCache.getInstance().attributePercentageMap.get(key) != null - ? PropertiesCache.getInstance().attributePercentageMap.get(key) - : 0; - } - - /** - * This method will provide all the missing filed list - * - * @param profileData Map - * @return List - */ - private List findMissingAttribute(Map profileData) { - List attribute = new ArrayList<>(); - Iterator> itr = - PropertiesCache.getInstance().attributePercentageMap.entrySet().iterator(); - while (itr.hasNext()) { - Entry entry = itr.next(); - if (profileData == null || !profileData.containsKey(entry.getKey())) { - attribute.add(entry.getKey()); - } else { - Object val = profileData.get(entry.getKey()); - if (val == null) { - attribute.add(entry.getKey()); - } else if (val instanceof List) { - List list = (List) val; - if (list.size() == 0) { - attribute.add(entry.getKey()); - } - } else if (val instanceof Map) { - Map map = (Map) val; - if (map == null || map.size() == 0) { - attribute.add(entry.getKey()); - } - } else { - if (StringUtils.isBlank(val.toString())) { - attribute.add(entry.getKey()); - } - } - } - } - return attribute; - } -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/services/impl/package-info.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/services/impl/package-info.java deleted file mode 100644 index 9513083f3..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/services/impl/package-info.java +++ /dev/null @@ -1,3 +0,0 @@ -/** */ -/** @author Manzarul */ -package org.sunbird.common.services.impl; diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/services/package-info.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/services/package-info.java deleted file mode 100644 index 38e8eba94..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/services/package-info.java +++ /dev/null @@ -1,3 +0,0 @@ -/** */ -/** @author Manzarul */ -package org.sunbird.common.services; diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/util/CloudStorageUtil.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/util/CloudStorageUtil.java deleted file mode 100644 index 5c3ee57af..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/util/CloudStorageUtil.java +++ /dev/null @@ -1,97 +0,0 @@ -package org.sunbird.common.util; - -import java.util.HashMap; -import java.util.Map; - -import org.apache.commons.lang.StringUtils; -import org.sunbird.cloud.storage.BaseStorageService; -import org.sunbird.cloud.storage.factory.StorageConfig; -import org.sunbird.cloud.storage.factory.StorageServiceFactory; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.models.util.ProjectUtil; -import org.sunbird.common.models.util.PropertiesCache; -import scala.Option; -import scala.Some; - -import static org.sunbird.common.models.util.JsonKey.CLOUD_STORAGE_CNAME_URL; -import static org.sunbird.common.models.util.JsonKey.CLOUD_STORE_BASE_PATH; -import static org.sunbird.common.models.util.ProjectUtil.getConfigValue; - -public class CloudStorageUtil { - private static final int STORAGE_SERVICE_API_RETRY_COUNT = 3; - - private static final Map storageServiceMap = new HashMap<>(); - - public static String upload( - String storageType, String container, String objectKey, String filePath) { - - BaseStorageService storageService = getStorageService(storageType); - - return storageService.upload( - container, - filePath, - objectKey, - Option.apply(false), - Option.apply(1), - Option.apply(STORAGE_SERVICE_API_RETRY_COUNT), - Option.empty()); - } - - public static String getSignedUrl( - String storageType, String container, String objectKey) { - BaseStorageService storageService = getStorageService(storageType); - return getSignedUrl(storageService, container, objectKey,storageType); - } - - public static String getSignedUrl( - BaseStorageService storageService, - String container, - String objectKey, String cloudType) { - return storageService.getSignedURLV2(container, objectKey, Some.apply(getTimeoutInSeconds()), - Some.apply("r"), Some.apply("application/pdf"), Option.empty()); - } - - - - private static BaseStorageService getStorageService(String storageType) { - String storageKey = PropertiesCache.getInstance().getProperty(JsonKey.ACCOUNT_NAME); - String storageSecret = PropertiesCache.getInstance().getProperty(JsonKey.ACCOUNT_KEY); - return getStorageService(storageType, storageKey, storageSecret); - } - - private static BaseStorageService getStorageService( - String storageType, String storageKey, String storageSecret) { - String compositeKey = storageType + "-" + storageKey; - scala.Option storageEndpoint = scala.Option.apply(PropertiesCache.getInstance().getProperty(JsonKey.ACCOUNT_ENDPOINT)); - scala.Option storageRegion = scala.Option.apply(""); - if (storageServiceMap.containsKey(compositeKey)) { - return storageServiceMap.get(compositeKey); - } - synchronized (CloudStorageUtil.class) { - StorageConfig storageConfig = - new StorageConfig(storageType, storageKey, storageSecret,storageEndpoint,storageRegion); - BaseStorageService storageService = StorageServiceFactory.getStorageService(storageConfig); - storageServiceMap.put(compositeKey, storageService); - } - return storageServiceMap.get(compositeKey); - } - - - private static int getTimeoutInSeconds() { - String timeoutInSecondsStr = ProjectUtil.getConfigValue(JsonKey.DOWNLOAD_LINK_EXPIRY_TIMEOUT); - return Integer.parseInt(timeoutInSecondsStr); - } - - public static String getUri( - String storageType, String container, String prefix, boolean isDirectory) { - BaseStorageService storageService = getStorageService(storageType); - return storageService.getUri(container, prefix, Option.apply(isDirectory)); - } - - public static String getBaseUrl() { - String baseUrl = getConfigValue(CLOUD_STORAGE_CNAME_URL); - if(StringUtils.isEmpty(baseUrl)) - baseUrl = getConfigValue(CLOUD_STORE_BASE_PATH); - return baseUrl; - } -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/util/JsonUtil.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/util/JsonUtil.java deleted file mode 100644 index c9e6a2623..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/util/JsonUtil.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.sunbird.common.util; - -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.ObjectMapper; - -import java.io.InputStream; -import java.text.SimpleDateFormat; - -public class JsonUtil { - - private static ObjectMapper mapper = new ObjectMapper(); - private static ObjectMapper mapperWithDateFormat = new ObjectMapper(); - static { - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - } - - public static String serialize(Object obj) throws Exception { - mapper.configure(com.fasterxml.jackson.databind.SerializationFeature.WRITE_DATES_AS_TIMESTAMPS , false); - return mapper.writeValueAsString(obj); - } - - public static T deserialize(String value, Class clazz) throws Exception { - return mapper.readValue(value, clazz); - } - - public static T deserialize(InputStream value, Class clazz) throws Exception { - return mapper.readValue(value, clazz); - } - - public static T convert(Object value, Class clazz) throws Exception { - return mapper.convertValue(value, clazz); - } - - // pass @dateFormat with timezone for serialization of dateType variables - public static T convertWithDateFormat(Object value, Class clazz, SimpleDateFormat dateFormat) throws Exception { - mapperWithDateFormat.setDateFormat(dateFormat); - return mapperWithDateFormat.convertValue(value, clazz); - } -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/util/KeycloakRequiredActionLinkUtil.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/util/KeycloakRequiredActionLinkUtil.java deleted file mode 100644 index f0c8b52bc..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/util/KeycloakRequiredActionLinkUtil.java +++ /dev/null @@ -1,134 +0,0 @@ -package org.sunbird.common.util; - -import com.fasterxml.jackson.databind.ObjectMapper; -import com.mashape.unirest.http.HttpResponse; -import com.mashape.unirest.http.JsonNode; -import com.mashape.unirest.http.Unirest; -import com.mashape.unirest.request.BaseRequest; -import com.mashape.unirest.request.body.RequestBodyEntity; -import java.util.HashMap; -import java.util.Map; -import javax.ws.rs.core.MediaType; -import org.apache.commons.lang3.StringUtils; -import org.apache.http.HttpHeaders; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.models.util.LoggerEnum; -import org.sunbird.common.models.util.ProjectLogger; -import org.sunbird.common.models.util.ProjectUtil; - -/** - * Keycloak utility to create required action links. - * - * @author Amit Kumar - */ -public class KeycloakRequiredActionLinkUtil { - - public static final String VERIFY_EMAIL = "VERIFY_EMAIL"; - public static final String UPDATE_PASSWORD = "UPDATE_PASSWORD"; - private static final String CLIENT_ID = "clientId"; - private static final String REQUIRED_ACTION = "requiredAction"; - private static final String USERNAME = "userName"; - private static final String EXPIRATION_IN_SEC = "expirationInSecs"; - private static final String REDIRECT_URI = "redirectUri"; - private static final String ACCESS_TOKEN = "access_token"; - private static final String SUNBIRD_KEYCLOAK_LINK_EXPIRATION_TIME = - "sunbird_keycloak_required_action_link_expiration_seconds"; - private static final String SUNBIRD_KEYCLOAK_REQD_ACTION_LINK = "/get-required-action-link"; - private static final String LINK = "link"; - - private static ObjectMapper mapper = new ObjectMapper(); - - /** - * Get generated link for specified type and user from Keycloak service. - * - * @param userName User name - * @param requiredAction Type of link to be generated. Supported types are UPDATE_PASSWORD and - * VERIFY_EMAIL. - * @return Generated link from Keycloak service - */ - public static String getLink(String userName, String redirectUri, String requiredAction) { - Map request = new HashMap<>(); - - request.put(CLIENT_ID, ProjectUtil.getConfigValue(JsonKey.SUNBIRD_SSO_CLIENT_ID)); - request.put(USERNAME, userName); - request.put(REQUIRED_ACTION, requiredAction); - - String expirationInSecs = ProjectUtil.getConfigValue(SUNBIRD_KEYCLOAK_LINK_EXPIRATION_TIME); - if (StringUtils.isNotBlank(expirationInSecs)) { - request.put(EXPIRATION_IN_SEC, expirationInSecs); - } - request.put(REDIRECT_URI, redirectUri); - - try { - Thread.sleep( - Integer.parseInt(ProjectUtil.getConfigValue(JsonKey.SUNBIRD_SYNC_READ_WAIT_TIME))); - return generateLink(request); - } catch (Exception ex) { - ProjectLogger.log( - "KeycloakRequiredActionLinkUtil:getLink: Exception occurred with error message = " - + ex.getMessage(), - ex); - } - return null; - } - - private static String generateLink(Map request) throws Exception { - Map headers = new HashMap<>(); - - headers.put(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON); - headers.put(JsonKey.AUTHORIZATION, JsonKey.BEARER + getAdminAccessToken()); - - ProjectLogger.log( - "KeycloakRequiredActionLinkUtil:generateLink: complete URL " - + ProjectUtil.getConfigValue(JsonKey.SUNBIRD_SSO_URL) - + "realms/" - + ProjectUtil.getConfigValue(JsonKey.SUNBIRD_SSO_RELAM) - + SUNBIRD_KEYCLOAK_REQD_ACTION_LINK, - LoggerEnum.INFO.name()); - ProjectLogger.log( - "KeycloakRequiredActionLinkUtil:generateLink: request body " - + mapper.writeValueAsString(request), - LoggerEnum.INFO.name()); - RequestBodyEntity baseRequest = - Unirest.post( - ProjectUtil.getConfigValue(JsonKey.SUNBIRD_SSO_URL) - + "realms/" - + ProjectUtil.getConfigValue(JsonKey.SUNBIRD_SSO_RELAM) - + SUNBIRD_KEYCLOAK_REQD_ACTION_LINK) - .headers(headers) - .body(mapper.writeValueAsString(request)); - HttpResponse response = baseRequest.asJson(); - - ProjectLogger.log( - "KeycloakRequiredActionLinkUtil:generateLink: Response status = " - + response.getStatus() - + " body " - + response.getBody(), - LoggerEnum.INFO.name()); - - return response.getBody().getObject().getString(LINK); - } - - public static String getAdminAccessToken() throws Exception { - Map headers = new HashMap<>(); - headers.put(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED); - BaseRequest request = - Unirest.post( - ProjectUtil.getConfigValue(JsonKey.SUNBIRD_SSO_URL) - + "realms/" - + ProjectUtil.getConfigValue(JsonKey.SUNBIRD_SSO_RELAM) - + "/protocol/openid-connect/token") - .headers(headers) - .field("client_id", ProjectUtil.getConfigValue(JsonKey.SUNBIRD_SSO_CLIENT_ID)) - .field("client_secret", ProjectUtil.getConfigValue(JsonKey.SUNBIRD_SSO_CLIENT_SECRET)) - .field("grant_type", "client_credentials"); - - HttpResponse response = request.asJson(); - ProjectLogger.log( - "KeycloakRequiredActionLinkUtil:getAdminAccessToken: Response status = " - + response.getStatus(), - LoggerEnum.INFO.name()); - - return response.getBody().getObject().getString(ACCESS_TOKEN); - } -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/util/Matcher.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/util/Matcher.java deleted file mode 100644 index 148321605..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/common/util/Matcher.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.sunbird.common.util; - -import org.apache.commons.lang3.StringUtils; - -/** this class is used to match the identifiers. */ -public class Matcher { - - /** - * this method will match the two arguments , equal or not if two string is null or empty this - * method will return true - * - * @param firstVal - * @param secondVal - * @return boolean - */ - public static boolean matchIdentifiers(String firstVal, String secondVal) { - return StringUtils.equalsIgnoreCase(firstVal, secondVal); - } -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/kafka/client/InstructionEventGenerator.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/kafka/client/InstructionEventGenerator.java deleted file mode 100644 index b148e0d13..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/kafka/client/InstructionEventGenerator.java +++ /dev/null @@ -1,105 +0,0 @@ -package org.sunbird.kafka.client; - -import com.fasterxml.jackson.databind.ObjectMapper; -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; -import org.apache.commons.collections.MapUtils; -import org.apache.commons.lang3.StringUtils; -import org.sunbird.common.exception.ProjectCommonException; -import org.sunbird.common.models.util.ProjectLogger; -import org.sunbird.common.responsecode.ResponseCode; -import org.sunbird.telemetry.dto.TelemetryBJREvent; - -public class InstructionEventGenerator { - - private static ObjectMapper mapper = new ObjectMapper(); - private static String beJobRequesteventId = "BE_JOB_REQUEST"; - private static int iteration = 1; - - private static String actorId = "Sunbird LMS Samza Job"; - private static String actorType = "System"; - private static String pdataId = "org.sunbird.platform"; - private static String pdataVersion = "1.0"; - - public static void pushInstructionEvent(String topic, Map data) throws Exception { - pushInstructionEvent("", topic, data); - } - - public static void pushInstructionEvent(String key, String topic, Map data) - throws Exception { - String beJobRequestEvent = generateInstructionEventMetadata(data); - if (StringUtils.isBlank(beJobRequestEvent)) { - throw new ProjectCommonException( - "BE_JOB_REQUEST_EXCEPTION", - "Event is not generated properly.", - ResponseCode.CLIENT_ERROR.getResponseCode()); - } - if (StringUtils.isNotBlank(topic)) { - if (StringUtils.isNotBlank(key)) KafkaClient.send(key, beJobRequestEvent, topic); - else KafkaClient.send(beJobRequestEvent, topic); - } else { - throw new ProjectCommonException( - "BE_JOB_REQUEST_EXCEPTION", - "Invalid topic id.", - ResponseCode.CLIENT_ERROR.getResponseCode()); - } - } - - private static String generateInstructionEventMetadata(Map data) { - Map actor = new HashMap<>(); - Map context = new HashMap<>(); - Map object = new HashMap<>(); - Map edata = new HashMap<>(); - if (MapUtils.isNotEmpty((Map) data.get("actor"))) { - actor.putAll((Map) data.get("actor")); - } else { - actor.put("id", actorId); - actor.put("type", actorType); - } - - if (MapUtils.isNotEmpty((Map) data.get("context"))) { - context.putAll((Map) data.get("context")); - } - Map pdata = new HashMap<>(); - pdata.put("id", pdataId); - pdata.put("ver", pdataVersion); - context.put("pdata", pdata); - if (MapUtils.isNotEmpty((Map) data.get("object"))) object.putAll((Map) data.get("object")); - - if (MapUtils.isNotEmpty((Map) data.get("edata"))) edata.putAll((Map) data.get("edata")); - - if (StringUtils.isNotBlank((String) data.get("action"))) - edata.put("action", data.get("action")); - - return logInstructionEvent(actor, context, object, edata); - } - - private static String logInstructionEvent( - Map actor, - Map context, - Map object, - Map edata) { - - TelemetryBJREvent te = new TelemetryBJREvent(); - long unixTime = System.currentTimeMillis(); - String mid = "LP." + System.currentTimeMillis() + "." + UUID.randomUUID(); - edata.put("iteration", iteration); - - te.setEid(beJobRequesteventId); - te.setEts(unixTime); - te.setMid(mid); - te.setActor(actor); - te.setContext(context); - te.setObject(object); - te.setEdata(edata); - - String jsonMessage = null; - try { - jsonMessage = mapper.writeValueAsString(te); - } catch (Exception e) { - ProjectLogger.log("Error logging BE_JOB_REQUEST event: " + e.getMessage(), e); - } - return jsonMessage; - } -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/kafka/client/KafkaClient.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/kafka/client/KafkaClient.java deleted file mode 100644 index b728f9c46..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/kafka/client/KafkaClient.java +++ /dev/null @@ -1,112 +0,0 @@ -package org.sunbird.kafka.client; - -import java.util.List; -import java.util.Map; -import java.util.Properties; -import org.apache.kafka.clients.consumer.Consumer; -import org.apache.kafka.clients.consumer.ConsumerConfig; -import org.apache.kafka.clients.consumer.KafkaConsumer; -import org.apache.kafka.clients.producer.KafkaProducer; -import org.apache.kafka.clients.producer.Producer; -import org.apache.kafka.clients.producer.ProducerConfig; -import org.apache.kafka.clients.producer.ProducerRecord; -import org.apache.kafka.common.PartitionInfo; -import org.apache.kafka.common.serialization.StringDeserializer; -import org.apache.kafka.common.serialization.StringSerializer; -import org.sunbird.common.exception.ProjectCommonException; -import org.sunbird.common.models.util.LoggerEnum; -import org.sunbird.common.models.util.LoggerUtil; -import org.sunbird.common.models.util.ProjectLogger; -import org.sunbird.common.models.util.ProjectUtil; -import org.sunbird.common.responsecode.ResponseCode; - -/** - * Helper class for creating a Kafka consumer and producer. - * - * @author Pradyumna - */ -public class KafkaClient { - - private static final String BOOTSTRAP_SERVERS = ProjectUtil.getConfigValue("kafka_urls"); - private static Producer producer; - private static Consumer consumer; - private static volatile Map> topics; - public static LoggerUtil logger = new LoggerUtil(KafkaClient.class); - - static { - loadProducerProperties(); - loadConsumerProperties(); - loadTopics(); - } - - private static void loadProducerProperties() { - Properties props = new Properties(); - props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, BOOTSTRAP_SERVERS); - props.put(ProducerConfig.CLIENT_ID_CONFIG, "KafkaClientProducer"); - props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName()); - props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName()); - props.put(ProducerConfig.LINGER_MS_CONFIG, ProjectUtil.getConfigValue("kafka_linger_ms")); - producer = new KafkaProducer(props); - } - - private static void loadTopics() { - if (consumer == null) { - loadConsumerProperties(); - } - topics = consumer.listTopics(); - logger.info(null, - "KafkaClient:loadTopics Kafka topic infos =>" + topics); - } - - private static void loadConsumerProperties() { - Properties props = new Properties(); - props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, BOOTSTRAP_SERVERS); - props.put(ConsumerConfig.CLIENT_ID_CONFIG, "KafkaClientConsumer"); - props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName()); - props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName()); - consumer = new KafkaConsumer<>(props); - } - - public static Producer getProducer() { - return producer; - } - - public static Consumer getConsumer() { - return consumer; - } - - public static void send(String event, String topic) throws Exception { - if (validate(topic)) { - final Producer producer = getProducer(); - ProducerRecord record = new ProducerRecord(topic, event); - producer.send(record); - } else { - logger.error(null, "Topic id: " + topic + ", does not exists.", null); - throw new ProjectCommonException( - "TOPIC_NOT_EXISTS_EXCEPTION", - "Topic id: " + topic + ", does not exists.", - ResponseCode.CLIENT_ERROR.getResponseCode()); - } - } - - public static void send(String key, String event, String topic) throws Exception { - if (validate(topic)) { - final Producer producer = getProducer(); - ProducerRecord record = new ProducerRecord(topic, key, event); - producer.send(record); - } else { - logger.error(null, "Topic id: " + topic + ", does not exists.", null); - throw new ProjectCommonException( - "TOPIC_NOT_EXISTS_EXCEPTION", - "Topic id: " + topic + ", does not exists.", - ResponseCode.CLIENT_ERROR.getResponseCode()); - } - } - - private static boolean validate(String topic) throws Exception { - if (topics == null) { - loadTopics(); - } - return topics.keySet().contains(topic); - } -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/telemetry/collector/TelemetryAssemblerFactory.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/telemetry/collector/TelemetryAssemblerFactory.java deleted file mode 100644 index 86d4e8988..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/telemetry/collector/TelemetryAssemblerFactory.java +++ /dev/null @@ -1,18 +0,0 @@ -package org.sunbird.telemetry.collector; - -/** Created by arvind on 16/1/18. */ -public class TelemetryAssemblerFactory { - - private static TelemetryDataAssembler telemetryDataAssembler = null; - - public static TelemetryDataAssembler get() { - if (telemetryDataAssembler == null) { - synchronized (TelemetryAssemblerFactory.class) { - if (telemetryDataAssembler == null) { - telemetryDataAssembler = new TelemetryDataAssemblerImpl(); - } - } - } - return telemetryDataAssembler; - } -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/telemetry/collector/TelemetryDataAssembler.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/telemetry/collector/TelemetryDataAssembler.java deleted file mode 100644 index 748b3315b..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/telemetry/collector/TelemetryDataAssembler.java +++ /dev/null @@ -1,15 +0,0 @@ -package org.sunbird.telemetry.collector; - -import java.util.Map; - -/** Created by arvind on 16/1/18. */ -public interface TelemetryDataAssembler { - - public String audit(Map context, Map params); - - public String search(Map context, Map params); - - public String log(Map context, Map params); - - public String error(Map context, Map params); -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/telemetry/collector/TelemetryDataAssemblerImpl.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/telemetry/collector/TelemetryDataAssemblerImpl.java deleted file mode 100644 index 7047c3849..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/telemetry/collector/TelemetryDataAssemblerImpl.java +++ /dev/null @@ -1,28 +0,0 @@ -package org.sunbird.telemetry.collector; - -import java.util.Map; -import org.sunbird.telemetry.util.TelemetryGenerator; - -/** Created by arvind on 5/1/18. */ -public class TelemetryDataAssemblerImpl implements TelemetryDataAssembler { - - @Override - public String audit(Map context, Map params) { - return TelemetryGenerator.audit(context, params); - } - - @Override - public String search(Map context, Map params) { - return TelemetryGenerator.search(context, params); - } - - @Override - public String log(Map context, Map params) { - return TelemetryGenerator.log(context, params); - } - - @Override - public String error(Map context, Map params) { - return TelemetryGenerator.error(context, params); - } -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/telemetry/dto/Actor.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/telemetry/dto/Actor.java deleted file mode 100644 index c69b605b1..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/telemetry/dto/Actor.java +++ /dev/null @@ -1,35 +0,0 @@ -package org.sunbird.telemetry.dto; - -public class Actor { - - private String id; - private String type; - - public Actor() {} - - public Actor(String id, String type) { - super(); - this.id = id; - this.type = type; - } - - /** @return the id */ - public String getId() { - return id; - } - - /** @param id the id to set */ - public void setId(String id) { - this.id = id; - } - - /** @return the type */ - public String getType() { - return type; - } - - /** @param type the type to set */ - public void setType(String type) { - this.type = type; - } -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/telemetry/dto/Producer.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/telemetry/dto/Producer.java deleted file mode 100644 index be56b1e05..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/telemetry/dto/Producer.java +++ /dev/null @@ -1,56 +0,0 @@ -package org.sunbird.telemetry.dto; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonInclude.Include; - -@JsonInclude(Include.NON_NULL) -public class Producer { - - private String id; - private String pid; - private String ver; - - public Producer() {} - - public Producer(String id, String ver) { - super(); - this.id = id; - this.ver = ver; - } - - public Producer(String id, String pid, String ver) { - this.id = id; - this.pid = pid; - this.ver = ver; - } - - /** @return the id */ - public String getId() { - return id; - } - - /** @param id the id to set */ - public void setId(String id) { - this.id = id; - } - - /** @return the pid */ - public String getPid() { - return pid; - } - - /** @param pid the pid to set */ - public void setPid(String pid) { - this.pid = pid; - } - - /** @return the ver */ - public String getVer() { - return ver; - } - - /** @param ver the ver to set */ - public void setVer(String ver) { - this.ver = ver; - } -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/telemetry/dto/Target.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/telemetry/dto/Target.java deleted file mode 100644 index 071311494..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/telemetry/dto/Target.java +++ /dev/null @@ -1,60 +0,0 @@ -package org.sunbird.telemetry.dto; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonInclude.Include; -import java.util.Map; - -@JsonInclude(Include.NON_NULL) -public class Target { - - private String id; - private String type; - private String ver; - private Map rollup; - - public Target() {} - - public Target(String id, String type) { - super(); - this.id = id; - this.type = type; - } - - public Map getRollup() { - return rollup; - } - - public void setRollup(Map rollup) { - this.rollup = rollup; - } - - /** @return the id */ - public String getId() { - return id; - } - - /** @param id the id to set */ - public void setId(String id) { - this.id = id; - } - - /** @return the type */ - public String getType() { - return type; - } - - /** @param type the type to set */ - public void setType(String type) { - this.type = type; - } - - /** @return the ver */ - public String getVer() { - return ver; - } - - /** @param ver the ver to set */ - public void setVer(String ver) { - this.ver = ver; - } -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/telemetry/dto/TelemetryBJREvent.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/telemetry/dto/TelemetryBJREvent.java deleted file mode 100644 index a94a365d3..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/telemetry/dto/TelemetryBJREvent.java +++ /dev/null @@ -1,70 +0,0 @@ -package org.sunbird.telemetry.dto; - -import java.util.Map; - -public class TelemetryBJREvent { - - private String eid; - private long ets; - private String mid; - private Map actor; - private Map context; - private Map object; - private Map edata; - - public String getEid() { - return eid; - } - - public void setEid(String eid) { - this.eid = eid; - } - - public long getEts() { - return ets; - } - - public void setEts(long ets) { - this.ets = ets; - } - - public String getMid() { - return mid; - } - - public void setMid(String mid) { - this.mid = mid; - } - - public Map getActor() { - return actor; - } - - public void setActor(Map actor) { - this.actor = actor; - } - - public Map getContext() { - return context; - } - - public void setContext(Map context) { - this.context = context; - } - - public Map getObject() { - return object; - } - - public void setObject(Map object) { - this.object = object; - } - - public Map getEdata() { - return edata; - } - - public void setEdata(Map edata) { - this.edata = edata; - } -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/telemetry/util/TelemetryConstant.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/telemetry/util/TelemetryConstant.java deleted file mode 100644 index b4394cc25..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/telemetry/util/TelemetryConstant.java +++ /dev/null @@ -1,11 +0,0 @@ -package org.sunbird.telemetry.util; - -/** - * Class contains Constants for telemetry. - * - * @author arvind. - */ -public class TelemetryConstant { - - public static final String LOG_LEVEL_ERROR = "error"; -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/telemetry/util/TelemetryEvents.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/telemetry/util/TelemetryEvents.java deleted file mode 100644 index 76d8b6114..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/telemetry/util/TelemetryEvents.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.sunbird.telemetry.util; - -/** - * enum for telemetry events - * - * @author arvind. - */ -public enum TelemetryEvents { - AUDIT("AUDIT"), - SEARCH("SEARCH"), - LOG("LOG"), - ERROR("ERROR"); - private String name; - - TelemetryEvents(String name) { - this.name = name; - } - - public String getName() { - return name; - } -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/telemetry/util/TelemetryParams.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/telemetry/util/TelemetryParams.java deleted file mode 100644 index 82df24f79..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/telemetry/util/TelemetryParams.java +++ /dev/null @@ -1,7 +0,0 @@ -package org.sunbird.telemetry.util; - -public enum TelemetryParams { - CHANNEL, - ENV, - ACTOR; -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/telemetry/util/TelemetryUtil.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/telemetry/util/TelemetryUtil.java deleted file mode 100644 index 2cb14deb5..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/telemetry/util/TelemetryUtil.java +++ /dev/null @@ -1,91 +0,0 @@ -package org.sunbird.telemetry.util; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import org.apache.commons.lang3.StringUtils; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.request.Request; - -/** @author arvind */ -public final class TelemetryUtil { - - private TelemetryUtil() {} - - public static Map generateTargetObject( - String id, String type, String currentState, String prevState) { - - Map target = new HashMap<>(); - target.put(JsonKey.ID, id); - target.put(JsonKey.TYPE, StringUtils.capitalize(type)); - target.put(JsonKey.CURRENT_STATE, currentState); - target.put(JsonKey.PREV_STATE, prevState); - return target; - } - - public static Map genarateTelemetryRequest( - Map targetObject, - List> correlatedObject, - String eventType, - Map params, - Map context) { - - Map map = new HashMap<>(); - map.put(JsonKey.TARGET_OBJECT, targetObject); - map.put(JsonKey.CORRELATED_OBJECTS, correlatedObject); - map.put(JsonKey.TELEMETRY_EVENT_TYPE, eventType); - map.put(JsonKey.PARAMS, params); - map.put(JsonKey.CONTEXT, context); - return map; - } - - public static void generateCorrelatedObject( - String id, String type, String corelation, List> correlationList) { - - Map correlatedObject = new HashMap<>(); - correlatedObject.put(JsonKey.ID, id); - correlatedObject.put(JsonKey.TYPE, StringUtils.capitalize(type)); - correlatedObject.put(JsonKey.RELATION, corelation); - - correlationList.add(correlatedObject); - } - - public static void addTargetObjectRollUp( - Map rollUpMap, Map targetObject) { - targetObject.put(JsonKey.ROLLUP, rollUpMap); - } - - public static void telemetryProcessingCall( - Map request, - Map targetObject, - List> correlatedObject, - Map context) { - Map params = new HashMap<>(); - params.put(JsonKey.PROPS, request); - Request req = new Request(); - req.setRequest( - TelemetryUtil.genarateTelemetryRequest( - targetObject, correlatedObject, TelemetryEvents.AUDIT.getName(), params, context)); - generateTelemetry(req); - } - - public static void telemetryProcessingCall( - Map request, - Map targetObject, - List> correlatedObject, - Map context, String type) { - Map params = new HashMap<>(); - params.put(JsonKey.PROPS, request); - params.put(JsonKey.TYPE, type); - - Request req = new Request(); - req.setRequest( - TelemetryUtil.genarateTelemetryRequest( - targetObject, correlatedObject, TelemetryEvents.AUDIT.getName(), params, context)); - generateTelemetry(req); - } - - private static void generateTelemetry(Request request) { - TelemetryWriter.write(request); - } -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/telemetry/validator/TelemetryObjectValidator.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/telemetry/validator/TelemetryObjectValidator.java deleted file mode 100644 index fe5a281d5..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/main/java/org/sunbird/telemetry/validator/TelemetryObjectValidator.java +++ /dev/null @@ -1,13 +0,0 @@ -package org.sunbird.telemetry.validator; - -/** @author arvind */ -public interface TelemetryObjectValidator { - - public boolean validateAudit(String jsonString); - - public boolean validateSearch(String jsonString); - - public boolean validateLog(String jsonString); - - public boolean validateError(String jsonString); -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/common/exception/ExceptionTest.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/common/exception/ExceptionTest.java deleted file mode 100644 index f1d336165..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/common/exception/ExceptionTest.java +++ /dev/null @@ -1,40 +0,0 @@ -/** */ -package org.sunbird.common.exception; - -import org.junit.Assert; -import org.junit.Test; -import org.sunbird.common.responsecode.ResponseCode; - -/** @author Manzarul */ -public class ExceptionTest { - - @Test - public void testProjectCommonException() { - ProjectCommonException exception = - new ProjectCommonException( - ResponseCode.apiKeyRequired.getErrorCode(), - ResponseCode.apiKeyRequired.getErrorMessage(), - ResponseCode.CLIENT_ERROR.getResponseCode()); - Assert.assertEquals(exception.getCode(), ResponseCode.apiKeyRequired.getErrorCode()); - Assert.assertEquals(exception.getMessage(), ResponseCode.apiKeyRequired.getErrorMessage()); - Assert.assertEquals(exception.getResponseCode(), ResponseCode.CLIENT_ERROR.getResponseCode()); - } - - @Test - public void testProjectCommonExceptionUsingSetters() { - ProjectCommonException exception = - new ProjectCommonException( - ResponseCode.apiKeyRequired.getErrorCode(), - ResponseCode.apiKeyRequired.getErrorMessage(), - ResponseCode.CLIENT_ERROR.getResponseCode()); - Assert.assertEquals(exception.getCode(), ResponseCode.apiKeyRequired.getErrorCode()); - Assert.assertEquals(exception.getMessage(), ResponseCode.apiKeyRequired.getErrorMessage()); - Assert.assertEquals(exception.getResponseCode(), ResponseCode.CLIENT_ERROR.getResponseCode()); - exception.setCode(ResponseCode.userAlreadyExists.getErrorCode()); - exception.setMessage(ResponseCode.userAlreadyExists.getErrorMessage()); - exception.setResponseCode(ResponseCode.SERVER_ERROR.getResponseCode()); - Assert.assertEquals(exception.getCode(), ResponseCode.userAlreadyExists.getErrorCode()); - Assert.assertEquals(exception.getMessage(), ResponseCode.userAlreadyExists.getErrorMessage()); - Assert.assertEquals(exception.getResponseCode(), ResponseCode.SERVER_ERROR.getResponseCode()); - } -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/common/models/AppTest.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/common/models/AppTest.java deleted file mode 100644 index 1c6d582b5..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/common/models/AppTest.java +++ /dev/null @@ -1,79 +0,0 @@ -package org.sunbird.common.models; - -import java.util.HashMap; -import java.util.Map; -import org.apache.commons.lang3.StringUtils; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.sunbird.common.models.util.BaseHttpTest; -import org.sunbird.common.models.util.HttpUtil; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.models.util.ProjectLogger; -import org.sunbird.common.models.util.PropertiesCache; - -public class AppTest extends BaseHttpTest { - String data = - "{\"request\": { \"search\": {\"contentType\": [\"Story\"] }}}"; - Map headers = new HashMap(); - - @Before - public void setup() { - headers.put("content-type", "application/json"); - headers.put("accept", "application/json"); - headers.put("user-id", "mahesh"); - String header = System.getenv(JsonKey.EKSTEP_AUTHORIZATION); - if (StringUtils.isBlank(header)) { - header = PropertiesCache.getInstance().getProperty(JsonKey.EKSTEP_AUTHORIZATION); - } - headers.put("authorization", "Bearer " + header); - } - - @Test - public void testSendPostRequestSuccess() throws Exception { - String ekStepBaseUrl = System.getenv(JsonKey.CONTENT_SERVICE_BASE_URL); - if (StringUtils.isBlank(ekStepBaseUrl)) { - ekStepBaseUrl = PropertiesCache.getInstance().getProperty(JsonKey.CONTENT_SERVICE_BASE_URL); - } - String response = HttpUtil.sendPostRequest(ekStepBaseUrl + "/content/v3/list", data, headers); - Assert.assertNotNull(response); - } - - @Test() - public void testSendPostRequestFailureWithWrongUrl() { - String ekStepBaseUrl = System.getenv(JsonKey.CONTENT_SERVICE_BASE_URL); - if (StringUtils.isBlank(ekStepBaseUrl)) { - ekStepBaseUrl = PropertiesCache.getInstance().getProperty(JsonKey.CONTENT_SERVICE_BASE_URL); - } - String response = null; - try { - Map data = new HashMap<>(); - data.put("search", "\"contentType\": [\"Story\"]"); - response = HttpUtil.sendPostRequest(ekStepBaseUrl + "/content/wrong/v3/list", data, headers); - } catch (Exception e) { - ProjectLogger.log(e.getMessage(), e); - } - Assert.assertNull(response); - } - - @Test() - public void testSendPatchRequestSuccess() { - String response = null; - try { - String ekStepBaseUrl = System.getenv(JsonKey.CONTENT_SERVICE_BASE_URL); - if (StringUtils.isBlank(ekStepBaseUrl)) { - ekStepBaseUrl = PropertiesCache.getInstance().getProperty(JsonKey.CONTENT_SERVICE_BASE_URL); - } - response = - HttpUtil.sendPatchRequest( - ekStepBaseUrl - + PropertiesCache.getInstance().getProperty(JsonKey.EKSTEP_TAG_API_URL) - + "/" - + "testt123", - "{}", - headers); - } catch (Exception e) { - } - Assert.assertNotNull(response); - } -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/common/models/ClientErrorResponseTest.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/common/models/ClientErrorResponseTest.java deleted file mode 100644 index 8e5d64b88..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/common/models/ClientErrorResponseTest.java +++ /dev/null @@ -1,42 +0,0 @@ -package org.sunbird.common.models; - -import java.util.HashMap; -import org.junit.Assert; -import org.junit.Test; -import org.sunbird.common.models.response.ResponseParams; -import org.sunbird.common.responsecode.ResponseCode; - -public class ClientErrorResponseTest { - - @Test - public void responseCreate() { - org.sunbird.common.models.response.Response response = - new org.sunbird.common.models.response.ClientErrorResponse(); - response.setId("test"); - response.setTs("1233444555"); - response.setVer("v1"); - ResponseParams params = new ResponseParams(); - params.setErr("Server Error"); - params.setErrmsg("test msg"); - params.setMsgid("123"); - params.setResmsgid("4566"); - params.setStatus("OK"); - response.setParams(params); - Assert.assertEquals(response.getId(), "test"); - Assert.assertEquals(response.getTs(), "1233444555"); - Assert.assertEquals(response.getVer(), "v1"); - Assert.assertEquals(response.getParams(), params); - Assert.assertEquals(response.getResponseCode(), ResponseCode.CLIENT_ERROR); - Assert.assertEquals(response.getParams().getErr(), params.getErr()); - Assert.assertEquals(response.getParams().getErrmsg(), params.getErrmsg()); - Assert.assertEquals(response.getParams().getMsgid(), params.getMsgid()); - Assert.assertEquals(response.getParams().getResmsgid(), params.getResmsgid()); - Assert.assertEquals(response.getParams().getStatus(), params.getStatus()); - Assert.assertEquals(response.getResult().size(), 0); - Assert.assertNotEquals(response.get("Test"), "test"); - response.putAll(new HashMap()); - response.put("test", "test123"); - org.sunbird.common.models.response.Response responseClone = response.clone(response); - Assert.assertNotEquals(response, responseClone); - } -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/common/models/RequestParamsTest.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/common/models/RequestParamsTest.java deleted file mode 100644 index 3a2178e13..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/common/models/RequestParamsTest.java +++ /dev/null @@ -1,29 +0,0 @@ -/** */ -package org.sunbird.common.models; - -import org.junit.Assert; -import org.junit.Test; -import org.sunbird.common.request.RequestParams; - -/** @author Manzarul */ -public class RequestParamsTest { - - @Test - public void testResponseParamBean() { - RequestParams params = new RequestParams(); - params.setAuthToken("auth_1233"); - params.setCid("cid"); - params.setDid("deviceId"); - params.setKey("account key"); - params.setMsgid("uniqueMsgId"); - params.setSid("sid"); - params.setUid("UUID"); - Assert.assertEquals(params.getAuthToken(), "auth_1233"); - Assert.assertEquals(params.getCid(), "cid"); - Assert.assertEquals(params.getMsgid(), "uniqueMsgId"); - Assert.assertEquals(params.getDid(), "deviceId"); - Assert.assertEquals(params.getKey(), "account key"); - Assert.assertEquals(params.getSid(), "sid"); - Assert.assertEquals(params.getUid(), "UUID"); - } -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/common/models/ResponseParamsTest.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/common/models/ResponseParamsTest.java deleted file mode 100644 index 36ec08b42..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/common/models/ResponseParamsTest.java +++ /dev/null @@ -1,29 +0,0 @@ -/** */ -package org.sunbird.common.models; - -import org.junit.Assert; -import org.junit.Test; -import org.sunbird.common.models.response.ResponseParams; -import org.sunbird.common.responsecode.ResponseCode; - -/** @author Manzarul */ -public class ResponseParamsTest { - - @Test - public void testResponseParamBean() { - ResponseParams params = new ResponseParams(); - params.setErr(ResponseCode.addressError.getErrorCode()); - params.setErrmsg(ResponseCode.addressError.getErrorMessage()); - params.setMsgid("test"); - params.setResmsgid("test-1"); - params.setStatus("OK"); - Assert.assertEquals(params.getErr(), ResponseCode.addressError.getErrorCode()); - Assert.assertEquals(params.getErrmsg(), ResponseCode.addressError.getErrorMessage()); - Assert.assertEquals(params.getMsgid(), "test"); - Assert.assertEquals(params.getResmsgid(), "test-1"); - Assert.assertEquals(params.getStatus(), "OK"); - Assert.assertEquals(ResponseParams.StatusType.FAILED.name(), "FAILED"); - Assert.assertEquals(ResponseParams.StatusType.SUCCESSFUL.name(), "SUCCESSFUL"); - Assert.assertEquals(ResponseParams.StatusType.WARNING.name(), "WARNING"); - } -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/common/models/ResponseTest.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/common/models/ResponseTest.java deleted file mode 100644 index 484c86487..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/common/models/ResponseTest.java +++ /dev/null @@ -1,45 +0,0 @@ -/** */ -package org.sunbird.common.models; - -import java.util.HashMap; -import org.junit.Assert; -import org.junit.Test; -import org.sunbird.common.models.response.ResponseParams; -import org.sunbird.common.responsecode.ResponseCode; - -/** @author Manzarul */ -public class ResponseTest { - - @Test - public void responseCreate() { - org.sunbird.common.models.response.Response response = - new org.sunbird.common.models.response.Response(); - response.setId("test"); - response.setResponseCode(ResponseCode.SERVER_ERROR); - response.setTs("1233444555"); - response.setVer("v1"); - ResponseParams params = new ResponseParams(); - params.setErr("Server Error"); - params.setErrmsg("test msg"); - params.setMsgid("123"); - params.setResmsgid("4566"); - params.setStatus("OK"); - response.setParams(params); - Assert.assertEquals(response.getId(), "test"); - Assert.assertEquals(response.getTs(), "1233444555"); - Assert.assertEquals(response.getVer(), "v1"); - Assert.assertEquals(response.getParams(), params); - Assert.assertEquals(response.getResponseCode(), ResponseCode.SERVER_ERROR); - Assert.assertEquals(response.getParams().getErr(), params.getErr()); - Assert.assertEquals(response.getParams().getErrmsg(), params.getErrmsg()); - Assert.assertEquals(response.getParams().getMsgid(), params.getMsgid()); - Assert.assertEquals(response.getParams().getResmsgid(), params.getResmsgid()); - Assert.assertEquals(response.getParams().getStatus(), params.getStatus()); - Assert.assertEquals(response.getResult().size(), 0); - Assert.assertNotEquals(response.get("Test"), "test"); - response.putAll(new HashMap()); - response.put("test", "test123"); - org.sunbird.common.models.response.Response responseClone = response.clone(response); - Assert.assertNotEquals(response, responseClone); - } -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/common/models/util/ActorOperationTest.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/common/models/util/ActorOperationTest.java deleted file mode 100644 index e87599a3f..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/common/models/util/ActorOperationTest.java +++ /dev/null @@ -1,152 +0,0 @@ -/** */ -package org.sunbird.common.models.util; - -import org.junit.Assert; -import org.junit.Test; - -/** @author Manzarul */ -public class ActorOperationTest { - - @Test - public void testActorOperation() { - Assert.assertEquals("enrollCourse", ActorOperations.ENROLL_COURSE.getValue()); - Assert.assertEquals("getCourse", ActorOperations.GET_COURSE.getValue()); - Assert.assertEquals("getContent", ActorOperations.GET_CONTENT.getValue()); - Assert.assertEquals("addContent", ActorOperations.ADD_CONTENT.getValue()); - Assert.assertEquals("createCourse", ActorOperations.CREATE_COURSE.getValue()); - Assert.assertEquals("updateCourse", ActorOperations.UPDATE_COURSE.getValue()); - Assert.assertEquals("publishCourse", ActorOperations.PUBLISH_COURSE.getValue()); - Assert.assertEquals("searchCourse", ActorOperations.SEARCH_COURSE.getValue()); - Assert.assertEquals("deleteCourse", ActorOperations.DELETE_COURSE.getValue()); - Assert.assertEquals("sendNotification", ActorOperations.SEND_NOTIFICATION.getValue()); - Assert.assertEquals("syncKeycloak", ActorOperations.SYNC_KEYCLOAK.getValue()); - Assert.assertEquals("updateSystemSettings", ActorOperations.UPDATE_SYSTEM_SETTINGS.getValue()); - Assert.assertEquals("deleteGeoLocation", ActorOperations.DELETE_GEO_LOCATION.getValue()); - Assert.assertEquals("getUserCount", ActorOperations.GET_USER_COUNT.getValue()); - Assert.assertEquals("updateGeoLocation", ActorOperations.UPDATE_GEO_LOCATION.getValue()); - Assert.assertEquals("getGeoLocation", ActorOperations.GET_GEO_LOCATION.getValue()); - Assert.assertEquals("registerClient", ActorOperations.REGISTER_CLIENT.getValue()); - Assert.assertEquals("updateClientKey", ActorOperations.UPDATE_CLIENT_KEY.getValue()); - Assert.assertEquals("getClientKey", ActorOperations.GET_CLIENT_KEY.getValue()); - Assert.assertEquals("createGeoLocation", ActorOperations.CREATE_GEO_LOCATION.getValue()); - Assert.assertEquals( - "updateTenantPreference", ActorOperations.UPDATE_TENANT_PREFERENCE.getValue()); - Assert.assertEquals("getTenantPreference", ActorOperations.GET_TENANT_PREFERENCE.getValue()); - Assert.assertEquals("addSkill", ActorOperations.ADD_SKILL.getValue()); - Assert.assertEquals("getSkill", ActorOperations.GET_SKILL.getValue()); - Assert.assertEquals("getSkillsList", ActorOperations.GET_SKILLS_LIST.getValue()); - Assert.assertEquals("profileVisibility", ActorOperations.PROFILE_VISIBILITY.getValue()); - Assert.assertEquals( - "createTanentPreference", ActorOperations.CREATE_TENANT_PREFERENCE.getValue()); - Assert.assertEquals("createUser", ActorOperations.CREATE_USER.getValue()); - Assert.assertEquals("updateUser", ActorOperations.UPDATE_USER.getValue()); - Assert.assertEquals("userAuth", ActorOperations.USER_AUTH.getValue()); - Assert.assertEquals("getUserProfile", ActorOperations.GET_USER_PROFILE.getValue()); - Assert.assertEquals("createOrg", ActorOperations.CREATE_ORG.getValue()); - Assert.assertEquals("updateOrg", ActorOperations.UPDATE_ORG.getValue()); - Assert.assertEquals("updateOrgStatus", ActorOperations.UPDATE_ORG_STATUS.getValue()); - Assert.assertEquals("getOrgDetails", ActorOperations.GET_ORG_DETAILS.getValue()); - Assert.assertEquals("userAuth", ActorOperations.USER_AUTH.getValue()); - Assert.assertEquals("createPage", ActorOperations.CREATE_PAGE.getValue()); - Assert.assertEquals("updatePage", ActorOperations.UPDATE_PAGE.getValue()); - Assert.assertEquals("deletePage", ActorOperations.DELETE_PAGE.getValue()); - Assert.assertEquals("getPageSettings", ActorOperations.GET_PAGE_SETTINGS.getValue()); - Assert.assertEquals("getPageData", ActorOperations.GET_PAGE_DATA.getValue()); - Assert.assertEquals("createSection", ActorOperations.CREATE_SECTION.getValue()); - Assert.assertEquals("updateSection", ActorOperations.UPDATE_SECTION.getValue()); - Assert.assertEquals("getAllSection", ActorOperations.GET_ALL_SECTION.getValue()); - Assert.assertEquals("getSection", ActorOperations.GET_SECTION.getValue()); - Assert.assertEquals("getCourseById", ActorOperations.GET_COURSE_BY_ID.getValue()); - Assert.assertEquals("updateUserCount", ActorOperations.UPDATE_USER_COUNT.getValue()); - Assert.assertEquals( - "getRecommendedCourses", ActorOperations.GET_RECOMMENDED_COURSES.getValue()); - Assert.assertEquals( - "updateUserInfoToElastic", ActorOperations.UPDATE_USER_INFO_ELASTIC.getValue()); - Assert.assertEquals("getRoles", ActorOperations.GET_ROLES.getValue()); - Assert.assertEquals("approveOrganisation", ActorOperations.APPROVE_ORGANISATION.getValue()); - Assert.assertEquals( - "addMemberOrganisation", ActorOperations.ADD_MEMBER_ORGANISATION.getValue()); - Assert.assertEquals( - "removeMemberOrganisation", ActorOperations.REMOVE_MEMBER_ORGANISATION.getValue()); - Assert.assertEquals("compositeSearch", ActorOperations.COMPOSITE_SEARCH.getValue()); - Assert.assertEquals( - "getUserDetailsByLoginId", ActorOperations.GET_USER_DETAILS_BY_LOGINID.getValue()); - Assert.assertEquals( - "updateOrgInfoToElastic", ActorOperations.UPDATE_ORG_INFO_ELASTIC.getValue()); - Assert.assertEquals( - "insertOrgInfoToElastic", ActorOperations.INSERT_ORG_INFO_ELASTIC.getValue()); - Assert.assertEquals("downlaodOrg", ActorOperations.DOWNLOAD_ORGS.getValue()); - Assert.assertEquals("blockUser", ActorOperations.BLOCK_USER.getValue()); - Assert.assertEquals("deleteByIdentifier", ActorOperations.DELETE_BY_IDENTIFIER.getValue()); - Assert.assertEquals("bulkUpload", ActorOperations.BULK_UPLOAD.getValue()); - Assert.assertEquals("processBulkUpload", ActorOperations.PROCESS_BULK_UPLOAD.getValue()); - Assert.assertEquals("assignRoles", ActorOperations.ASSIGN_ROLES.getValue()); - Assert.assertEquals("unblockUser", ActorOperations.UNBLOCK_USER.getValue()); - Assert.assertEquals("createBatch", ActorOperations.CREATE_BATCH.getValue()); - Assert.assertEquals("updateBatch", ActorOperations.UPDATE_BATCH.getValue()); - Assert.assertEquals("removeBatch", ActorOperations.REMOVE_BATCH.getValue()); - Assert.assertEquals("addUserBatch", ActorOperations.ADD_USER_TO_BATCH.getValue()); - Assert.assertEquals("removeUserFromBatch", ActorOperations.REMOVE_USER_FROM_BATCH.getValue()); - Assert.assertEquals("getBatch", ActorOperations.GET_BATCH.getValue()); - Assert.assertEquals("insertCourseBatchToEs", ActorOperations.INSERT_COURSE_BATCH_ES.getValue()); - Assert.assertEquals("updateCourseBatchToEs", ActorOperations.UPDATE_COURSE_BATCH_ES.getValue()); - Assert.assertEquals("getBulkOpStatus", ActorOperations.GET_BULK_OP_STATUS.getValue()); - Assert.assertEquals("orgCreationMetrics", ActorOperations.ORG_CREATION_METRICS.getValue()); - Assert.assertEquals( - "orgConsumptionMetrics", ActorOperations.ORG_CONSUMPTION_METRICS.getValue()); - Assert.assertEquals( - "orgCreationMetricsData", ActorOperations.ORG_CREATION_METRICS_DATA.getValue()); - Assert.assertEquals( - "courseProgressMetrics", ActorOperations.COURSE_PROGRESS_METRICS.getValue()); - Assert.assertEquals("userCreationMetrics", ActorOperations.USER_CREATION_METRICS.getValue()); - Assert.assertEquals( - "userConsumptionMetrics", ActorOperations.USER_CONSUMPTION_METRICS.getValue()); - Assert.assertEquals("getCourseBatchDetail", ActorOperations.GET_COURSE_BATCH_DETAIL.getValue()); - Assert.assertEquals("updateUserOrgES", ActorOperations.UPDATE_USER_ORG_ES.getValue()); - Assert.assertEquals("removeUserOrgES", ActorOperations.REMOVE_USER_ORG_ES.getValue()); - Assert.assertEquals("updateUserRoles", ActorOperations.UPDATE_USER_ROLES_ES.getValue()); - Assert.assertEquals("sync", ActorOperations.SYNC.getValue()); - Assert.assertEquals( - "insertUserCoursesInfoToElastic", - ActorOperations.INSERT_USR_COURSES_INFO_ELASTIC.getValue()); - Assert.assertEquals( - "updateUserCoursesInfoToElastic", - ActorOperations.UPDATE_USR_COURSES_INFO_ELASTIC.getValue()); - Assert.assertEquals("scheduleBulkUpload", ActorOperations.SCHEDULE_BULK_UPLOAD.getValue()); - Assert.assertEquals( - "courseProgressMetricsReport", ActorOperations.COURSE_PROGRESS_METRICS_REPORT.getValue()); - Assert.assertEquals( - "courseConsumptionMetricsReport", - ActorOperations.COURSE_CREATION_METRICS_REPORT.getValue()); - Assert.assertEquals( - "orgCreationMetricsReport", ActorOperations.ORG_CREATION_METRICS_REPORT.getValue()); - Assert.assertEquals( - "orgConsumptionMetricsReport", ActorOperations.ORG_CONSUMPTION_METRICS_REPORT.getValue()); - Assert.assertEquals("fileStorageService", ActorOperations.FILE_STORAGE_SERVICE.getValue()); - Assert.assertEquals( - "fileGenerationAndUpload", ActorOperations.FILE_GENERATION_AND_UPLOAD.getValue()); - Assert.assertEquals("healthCheck", ActorOperations.HEALTH_CHECK.getValue()); - Assert.assertEquals("sendMail", ActorOperations.SEND_MAIL.getValue()); - Assert.assertEquals("processData", ActorOperations.PROCESS_DATA.getValue()); - Assert.assertEquals("actor", ActorOperations.ACTOR.getValue()); - Assert.assertEquals("cassandra", ActorOperations.CASSANDRA.getValue()); - Assert.assertEquals("es", ActorOperations.ES.getValue()); - Assert.assertEquals("ekstep", ActorOperations.EKSTEP.getValue()); - Assert.assertEquals("getOrgTypeList", ActorOperations.GET_ORG_TYPE_LIST.getValue()); - Assert.assertEquals("createOrgType", ActorOperations.CREATE_ORG_TYPE.getValue()); - Assert.assertEquals("updateOrgType", ActorOperations.UPDATE_ORG_TYPE.getValue()); - Assert.assertEquals("createNote", ActorOperations.CREATE_NOTE.getValue()); - Assert.assertEquals("updateNote", ActorOperations.UPDATE_NOTE.getValue()); - Assert.assertEquals("searchNote", ActorOperations.SEARCH_NOTE.getValue()); - Assert.assertEquals("getNote", ActorOperations.GET_NOTE.getValue()); - Assert.assertEquals("deleteNote", ActorOperations.DELETE_NOTE.getValue()); - Assert.assertEquals( - "insertUserNotesToElastic", ActorOperations.INSERT_USER_NOTES_ES.getValue()); - Assert.assertEquals("encryptUserData", ActorOperations.ENCRYPT_USER_DATA.getValue()); - Assert.assertEquals("decryptUserData", ActorOperations.DECRYPT_USER_DATA.getValue()); - Assert.assertEquals( - "updateUserNotesToElastic", ActorOperations.UPDATE_USER_NOTES_ES.getValue()); - Assert.assertEquals("userCurrentLogin", ActorOperations.USER_CURRENT_LOGIN.getValue()); - Assert.assertEquals("getMediaTypes", ActorOperations.GET_MEDIA_TYPES.getValue()); - } -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/common/models/util/AuditLogTest.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/common/models/util/AuditLogTest.java deleted file mode 100644 index 88309fb62..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/common/models/util/AuditLogTest.java +++ /dev/null @@ -1,31 +0,0 @@ -/** */ -package org.sunbird.common.models.util; - -import java.util.HashMap; -import java.util.Map; -import org.junit.Assert; -import org.junit.Test; - -/** @author Manzarul */ -public class AuditLogTest { - - @Test - public void createAuditLog() { - AuditLog log = new AuditLog(); - log.setDate("2017-12-29"); - log.setObjectId("objectId"); - log.setObjectType("User"); - log.setOperationType("create"); - log.setRequestId("requesterId"); - log.setUserId("userId"); - Map map = new HashMap<>(); - log.setLogRecord(map); - Assert.assertEquals("2017-12-29", log.getDate()); - Assert.assertEquals("objectId", log.getObjectId()); - Assert.assertEquals("User", log.getObjectType()); - Assert.assertEquals("create", log.getOperationType()); - Assert.assertEquals("requesterId", log.getRequestId()); - Assert.assertEquals("userId", log.getUserId()); - Assert.assertEquals(0, log.getLogRecord().size()); - } -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/common/models/util/BaseHttpTest.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/common/models/util/BaseHttpTest.java deleted file mode 100644 index c6b6744f6..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/common/models/util/BaseHttpTest.java +++ /dev/null @@ -1,82 +0,0 @@ -package org.sunbird.common.models.util; - -import static org.powermock.api.mockito.PowerMockito.doThrow; -import static org.powermock.api.mockito.PowerMockito.mock; -import static org.powermock.api.mockito.PowerMockito.when; -import static org.powermock.api.mockito.PowerMockito.whenNew; - -import java.io.BufferedReader; -import java.io.FileNotFoundException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.net.HttpURLConnection; -import java.net.URL; - -import com.mashape.unirest.http.Unirest; -import org.apache.http.impl.client.HttpClients; -import org.junit.Assert; -import org.junit.Before; -import org.junit.runner.RunWith; -import org.mockito.Mockito; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; -import org.sunbird.common.util.KeycloakRequiredActionLinkUtil; - -@RunWith(PowerMockRunner.class) -@PowerMockIgnore({"javax.management.*", "javax.net.ssl.*", "javax.security.*", "jdk.internal.reflect.*", "sun.security.ssl.*", "javax.net.ssl.*" , "javax.crypto.*"}) -@PrepareForTest({ - OutputStreamWriter.class, - URL.class, - BufferedReader.class, - HttpUtil.class, - HttpClients.class, - KeyCloakConnectionProvider.class, - KeycloakRequiredActionLinkUtil.class, Unirest.class -}) -public abstract class BaseHttpTest { - - @Before - public void addMockRules() { - - mockHttpUrlResponse("content/v3/list", "not-empty-output"); - mockHttpUrlResponse("/search/health", "not-empty-output"); - mockHttpUrlResponse("/content/wrong/v3/list", null, true, null); - mockHttpUrlResponse("v1/issuer/issuers", "{\"message\":\"success\"}"); - mockHttpUrlResponse("https://dev.ekstep.in/api/data/v3", "{\"message\":\"success\"}"); - } - - protected void mockHttpUrlResponse(String urlContains, String outputExpected) { - mockHttpUrlResponse(urlContains, outputExpected, false, null); - } - - protected void mockHttpUrlResponse( - String urlContains, String outputExpected, boolean throwError, String paramContains) { - URL url = mock(URL.class); - HttpURLConnection connection = mock(HttpURLConnection.class); - OutputStream outStream = mock(OutputStream.class); - OutputStreamWriter outStreamWriter = mock(OutputStreamWriter.class); - InputStream inStream = mock(InputStream.class); - BufferedReader reader = mock(BufferedReader.class); - try { - - whenNew(URL.class).withArguments(Mockito.contains(urlContains)).thenReturn(url); - whenNew(OutputStreamWriter.class).withAnyArguments().thenReturn(outStreamWriter); - when(url.openConnection()).thenReturn(connection); - when(connection.getOutputStream()).thenReturn(outStream); - if (paramContains != null && throwError) { - doThrow(new FileNotFoundException()).when(outStreamWriter).write(Mockito.anyString()); - } - if (throwError) { - when(connection.getInputStream()).thenThrow(new FileNotFoundException()); - } else { - when(connection.getInputStream()).thenReturn(inStream); - } - whenNew(BufferedReader.class).withAnyArguments().thenReturn(reader); - when(reader.readLine()).thenReturn(outputExpected, null); - } catch (Exception e) { - Assert.fail("Mock rules addition failed " + e.getMessage()); - } - } -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/common/models/util/ExcelFileUtilTest.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/common/models/util/ExcelFileUtilTest.java deleted file mode 100644 index 38e1078cf..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/common/models/util/ExcelFileUtilTest.java +++ /dev/null @@ -1,55 +0,0 @@ -package org.sunbird.common.models.util; - -import java.io.File; -import java.util.ArrayList; -import java.util.List; -import org.apache.commons.lang3.StringUtils; -import org.junit.After; -import org.junit.Assert; -import org.junit.Test; - -public class ExcelFileUtilTest { - - @Test - public void testWriteToFile() { - String fileName = "test"; - List> data = new ArrayList<>(); - List dataObjects = new ArrayList<>(); - dataObjects.add("test1"); - dataObjects.add(new ArrayList<>()); - dataObjects.add(1); - dataObjects.add(2.0D); - data.add(dataObjects); - ExcelFileUtil excelFileUtil = new ExcelFileUtil(); - File file = excelFileUtil.writeToFile(fileName, data); - String[] expectedFileName = StringUtils.split(file.getName(), '.'); - Assert.assertEquals("test", expectedFileName[0]); - Assert.assertEquals("xlsx", expectedFileName[1]); - } - - @Test - public void testgetFileUtil() { - FileUtil util = FileUtil.getFileUtil("Excel"); - Assert.assertNotNull(util); - } - - @Test - public void testgetListValue() { - List list = new ArrayList<>(); - list.add("column1"); - list.add("column2"); - String response = FileUtil.getListValue(list); - Assert.assertEquals("column1,column2", response); - list.clear(); - response = FileUtil.getListValue(list); - Assert.assertEquals("", response); - } - - @After - public void deleteFileGenerated() { - File file = new File("test.xlsx"); - if (file.exists()) { - file.delete(); - } - } -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/common/models/util/HttpUtilTest.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/common/models/util/HttpUtilTest.java deleted file mode 100644 index 090e9f8dc..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/common/models/util/HttpUtilTest.java +++ /dev/null @@ -1,92 +0,0 @@ -package org.sunbird.common.models.util; - -import com.mashape.unirest.http.Unirest; -import com.microsoft.azure.storage.CloudStorageAccount; -import com.microsoft.azure.storage.blob.CloudBlobClient; -import com.microsoft.azure.storage.blob.CloudBlobContainer; -import com.microsoft.azure.storage.blob.ListBlobItem; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.MethodSorters; -import org.mockito.Mockito; -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 java.util.HashMap; -import java.util.Map; - -import static org.junit.Assert.assertTrue; - -@RunWith(PowerMockRunner.class) -@PowerMockIgnore({ "javax.management.*", "javax.net.ssl.*", "javax.security.*", "com.microsoft.azure.storage.*", - "jdk.internal.reflect.*", "sun.security.ssl.*", "javax.crypto.*", "com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*"}) -public class HttpUtilTest extends BaseHttpTest { - String JSON_STRING_DATA = "asdasasfasfsdfdsfdsfgsd"; - - @Test - public void testSendPatchRequestSuccess() { - - Map headers = new HashMap<>(); - headers.put("Authorization", "123456"); - String url = "http://localhost:8000/v1/issuer/issuers"; - try { - PowerMockito.mockStatic(Unirest.class); - Mockito.doReturn("SUCCESS").when(Unirest.patch(url)); - String response = HttpUtil.sendPatchRequest(url, "{\"message\":\"success\"}", headers); - assertTrue("SUCCESS".equals(response)); - } catch (Exception e) { - ProjectLogger.log(e.getMessage()); - } - } - - @Test - public void testSendPostRequestSuccess() { - Map headers = new HashMap<>(); - headers.put("Authorization", "123456"); - String url = "http://localhost:8000/v1/issuer/issuers"; - try { - String response = HttpUtil.sendPostRequest(url, "{\"message\":\"success\"}", headers); - assertTrue("{\"message\":\"success\"}".equals(response)); - } catch (Exception e) { - ProjectLogger.log(e.getMessage()); - } - } - - @Test - public void testSendGetRequestSuccess() { - Map headers = new HashMap<>(); - headers.put("Authorization", "123456"); - String urlString = "http://localhost:8000/v1/issuer/issuers"; - try { - String response = HttpUtil.sendGetRequest(urlString, headers); - assertTrue("{\"message\":\"success\"}".equals(response)); - } catch (Exception e) { - ProjectLogger.log(e.getMessage()); - } - } - - @Test - public void testGetHeaderWithInput() throws Exception { - Map input = new HashMap(){{ - put("x-channel-id", "test-channel"); - put("x-device-id", "test-device"); - }}; - Map headers = HttpUtil.getHeader(input); - assertTrue(!headers.isEmpty()); - assertTrue(headers.size()==3); - assertTrue(headers.containsKey("Content-Type")); - assertTrue(headers.containsKey("x-channel-id")); - assertTrue(headers.containsKey("x-device-id")); - } - - @Test - public void testGetHeaderWithoutInput() throws Exception { - Map headers = HttpUtil.getHeader(null); - assertTrue(!headers.isEmpty()); - assertTrue(headers.size()==1); - assertTrue(headers.containsKey("Content-Type")); - } -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/common/models/util/ProjectUtilTest.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/common/models/util/ProjectUtilTest.java deleted file mode 100644 index 18e2bddc8..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/common/models/util/ProjectUtilTest.java +++ /dev/null @@ -1,455 +0,0 @@ -package org.sunbird.common.models.util; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import java.text.SimpleDateFormat; -import java.util.Calendar; -import java.util.HashMap; -import java.util.Map; -import java.util.TimeZone; -import org.apache.commons.lang3.StringUtils; -import org.apache.velocity.VelocityContext; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.modules.junit4.PowerMockRunner; -import org.sunbird.common.exception.ProjectCommonException; -import org.sunbird.common.request.Request; -import org.sunbird.common.responsecode.ResponseCode; - -/** Created by arvind on 6/10/17. */ -@RunWith(PowerMockRunner.class) -@PowerMockIgnore({ "javax.management.*", "javax.net.ssl.*", "javax.security.*", "com.microsoft.azure.storage.*", - "jdk.internal.reflect.*", "sun.security.ssl.*", "javax.crypto.*", "com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*"}) -public class ProjectUtilTest extends BaseHttpTest { - - PropertiesCache propertiesCache = ProjectUtil.propertiesCache; - - static Map headers = new HashMap(); - - @BeforeClass - public static void init() { - headers.put("content-type", "application/json"); - headers.put("accept", "application/json"); - headers.put("user-id", "mahesh"); - String header = System.getenv(JsonKey.EKSTEP_AUTHORIZATION); - if (StringUtils.isBlank(header)) { - header = PropertiesCache.getInstance().getProperty(JsonKey.EKSTEP_AUTHORIZATION); - } - headers.put("authorization", "Bearer " + header); - } - - @Ignore - public void testGetContextFailureWithNameAbsent() { - - Map templateMap = new HashMap<>(); - templateMap.put(JsonKey.ACTION_URL, "googli.com"); - - VelocityContext context = ProjectUtil.getContext(templateMap); - assertEquals(false, context.internalContainsKey(JsonKey.NAME)); - } - - @Test - public void testGetContextFailureWithoutActionUrl() { - - Map templateMap = new HashMap<>(); - templateMap.put(JsonKey.NAME, "userName"); - - VelocityContext context = ProjectUtil.getContext(templateMap); - assertEquals(false, context.internalContainsKey(JsonKey.ACTION_URL)); - } - - @Test - public void testGetContextSuccessWithFromMail() { - - Map templateMap = new HashMap<>(); - templateMap.put(JsonKey.ACTION_URL, "googli.com"); - templateMap.put(JsonKey.NAME, "userName"); - - Boolean envVal = !StringUtils.isBlank(System.getenv(JsonKey.EMAIL_SERVER_FROM)); - Boolean cacheVal = propertiesCache.getProperty(JsonKey.EMAIL_SERVER_FROM) != null; - - VelocityContext context = ProjectUtil.getContext(templateMap); - if (envVal) { - assertEquals( - System.getenv(JsonKey.EMAIL_SERVER_FROM), context.internalGet(JsonKey.FROM_EMAIL)); - } else if (cacheVal) { - assertEquals( - propertiesCache.getProperty(JsonKey.EMAIL_SERVER_FROM), - context.internalGet(JsonKey.FROM_EMAIL)); - } - } - - @Test - public void testGetContextSuccessWithOrgImageUrl() { - - Map templateMap = new HashMap<>(); - templateMap.put(JsonKey.ACTION_URL, "googli.com"); - templateMap.put(JsonKey.NAME, "userName"); - - boolean envVal = !StringUtils.isBlank(System.getenv(JsonKey.SUNBIRD_ENV_LOGO_URL)); - boolean cacheVal = propertiesCache.getProperty(JsonKey.SUNBIRD_ENV_LOGO_URL) != null; - - VelocityContext context = ProjectUtil.getContext(templateMap); - if (envVal) { - assertEquals( - System.getenv(JsonKey.SUNBIRD_ENV_LOGO_URL), context.internalGet(JsonKey.ORG_IMAGE_URL)); - } else if (cacheVal) { - assertEquals( - propertiesCache.getProperty(JsonKey.SUNBIRD_ENV_LOGO_URL), - context.internalGet(JsonKey.ORG_IMAGE_URL)); - } - } - - @Test - public void testCreateAuthTokenSuccess() { - String authToken = ProjectUtil.createAuthToken("test", "tset1234"); - assertNotNull(authToken); - } - - @Test - public void testValidatePhoneNumberFailureWithInvalidPhoneNumber() { - assertFalse(ProjectUtil.validatePhoneNumber("312")); - } - - @Test - public void testValidatePhoneNumberSuccess() { - assertTrue(ProjectUtil.validatePhoneNumber("9844016699")); - } - - @Test - public void testGenerateRandomPasswordSuccess() { - assertNotNull(ProjectUtil.generateRandomPassword()); - } - - @Test - public void testCreateCheckResponseSuccess() { - Map responseMap = - ProjectUtil.createCheckResponse("LearnerService", false, null); - assertEquals(true, responseMap.get(JsonKey.Healthy)); - } - - @Test - public void testCreateCheckResponseFailureWithException() { - Map responseMap = - ProjectUtil.createCheckResponse( - "LearnerService", - true, - new ProjectCommonException( - ResponseCode.invalidObjectType.getErrorCode(), - ResponseCode.invalidObjectType.getErrorMessage(), - ResponseCode.CLIENT_ERROR.getResponseCode())); - assertEquals(false, responseMap.get(JsonKey.Healthy)); - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), responseMap.get(JsonKey.ERROR)); - assertEquals( - ResponseCode.invalidObjectType.getErrorMessage(), responseMap.get(JsonKey.ERRORMSG)); - } - - @Ignore - public void testSetRequestSuccessWithLowerCaseValues() { - Request request = new Request(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.SOURCE, "Test"); - requestObj.put(JsonKey.LOGIN_ID, "SunbirdUser"); - requestObj.put(JsonKey.EXTERNAL_ID, "testExternal"); - requestObj.put(JsonKey.USER_NAME, "username"); - requestObj.put(JsonKey.USERNAME, "userName"); - requestObj.put(JsonKey.PROVIDER, "Provider"); - requestObj.put(JsonKey.ID, "TEST123"); - request.setRequest(requestObj); - assertEquals("test", requestObj.get(JsonKey.SOURCE)); - assertEquals("sunbirduser", requestObj.get(JsonKey.LOGIN_ID)); - assertEquals("testexternal", requestObj.get(JsonKey.EXTERNAL_ID)); - assertEquals("username", requestObj.get(JsonKey.USER_NAME)); - assertEquals("username", requestObj.get(JsonKey.USERNAME)); - assertEquals("provider", requestObj.get(JsonKey.PROVIDER)); - assertEquals("TEST123", requestObj.get(JsonKey.ID)); - } - - @Test - public void testFormatMessageSuccess() { - String msg = ProjectUtil.formatMessage("Hello {0}", "user"); - assertEquals("Hello user", msg); - } - - @Test - public void testFormatMessageFailureWithInvalidVariable() { - String msg = ProjectUtil.formatMessage("Hello ", "user"); - assertNotEquals("Hello user", msg); - } - - @Test - public void testIsEmailValidFailureWithWrongEmail() { - boolean msg = ProjectUtil.isEmailvalid("Hello "); - assertFalse(msg); - } - - @Test - public void testIsDateValidFormatSuccess() { - boolean bool = ProjectUtil.isDateValidFormat("yyyy-MM-dd", "2017-12-18"); - assertTrue(bool); - } - - @Test - public void testIsDateValidFormatFailureWithEmptyDate() { - boolean bool = ProjectUtil.isDateValidFormat("yyyy-MM-dd", ""); - assertFalse(bool); - } - - @Test - public void testIsDateValidFormatFailureWithInvalidDate() { - boolean bool = ProjectUtil.isDateValidFormat("yyyy-MM-dd", "2017-12-18"); - assertTrue(bool); - } - - @Test - public void testIsDateValidFormatFailureWithEmptyDateTime() { - boolean bool = ProjectUtil.isDateValidFormat("yyyy-MM-dd HH:mm:ss:SSSZ", ""); - assertFalse(bool); - } - - @Test - public void testGetEkstepHeaderSuccess() { - Map map = ProjectUtil.getEkstepHeader(); - assertEquals(map.get("Content-Type"), "application/json"); - assertNotNull(map.get(JsonKey.AUTHORIZATION)); - } - - @Ignore - public void testRegisterTagSuccess() { - String response = null; - try { - response = ProjectUtil.registertag("testTag", "{}", ProjectUtil.getEkstepHeader()); - } catch (Exception e) { - - } - assertNotNull(response); - } - - @Test - public void testReportTrackingStatusSuccess() { - assertEquals(0, ProjectUtil.ReportTrackingStatus.NEW.getValue()); - assertEquals(1, ProjectUtil.ReportTrackingStatus.GENERATING_DATA.getValue()); - assertEquals(2, ProjectUtil.ReportTrackingStatus.UPLOADING_FILE.getValue()); - assertEquals(3, ProjectUtil.ReportTrackingStatus.UPLOADING_FILE_SUCCESS.getValue()); - assertEquals(4, ProjectUtil.ReportTrackingStatus.SENDING_MAIL.getValue()); - assertEquals(5, ProjectUtil.ReportTrackingStatus.SENDING_MAIL_SUCCESS.getValue()); - assertEquals(9, ProjectUtil.ReportTrackingStatus.FAILED.getValue()); - } - - @Test - public void testEsTypeSuccess() { - assertEquals("cbatch", ProjectUtil.EsType.course.getTypeName()); - assertEquals("course-batch", ProjectUtil.EsType.courseBatch.getTypeName()); - assertEquals("user", ProjectUtil.EsType.user.getTypeName()); - assertEquals("org", ProjectUtil.EsType.organisation.getTypeName()); - assertEquals("user-courses", ProjectUtil.EsType.usercourses.getTypeName()); - } - - @Test - public void testEsIndexSuccess() { - assertEquals("searchindex", ProjectUtil.EsIndex.sunbird.getIndexName()); - } - - @Test - public void testUserRoleSuccess() { - assertEquals("PUBLIC", ProjectUtil.UserRole.PUBLIC.getValue()); - assertEquals("CONTENT_CREATOR", ProjectUtil.UserRole.CONTENT_CREATOR.getValue()); - assertEquals("CONTENT_REVIEWER", ProjectUtil.UserRole.CONTENT_REVIEWER.getValue()); - assertEquals("ORG_ADMIN", ProjectUtil.UserRole.ORG_ADMIN.getValue()); - assertEquals("ORG_MEMBER", ProjectUtil.UserRole.ORG_MEMBER.getValue()); - } - - @Test - public void testBulkProcessStatusSuccess() { - assertEquals(0, ProjectUtil.BulkProcessStatus.NEW.getValue()); - assertEquals(1, ProjectUtil.BulkProcessStatus.IN_PROGRESS.getValue()); - assertEquals(2, ProjectUtil.BulkProcessStatus.INTERRUPT.getValue()); - assertEquals(3, ProjectUtil.BulkProcessStatus.COMPLETED.getValue()); - assertEquals(9, ProjectUtil.BulkProcessStatus.FAILED.getValue()); - } - - @Test - public void testOrgStatusSuccess() { - assertEquals(new Integer(0), ProjectUtil.OrgStatus.INACTIVE.getValue()); - assertEquals(new Integer(1), ProjectUtil.OrgStatus.ACTIVE.getValue()); - assertEquals(new Integer(2), ProjectUtil.OrgStatus.BLOCKED.getValue()); - assertEquals(new Integer(3), ProjectUtil.OrgStatus.RETIRED.getValue()); - } - - @Test - public void testCourseMgmtStatusSuccess() { - assertEquals("draft", ProjectUtil.CourseMgmtStatus.DRAFT.getValue()); - assertEquals("live", ProjectUtil.CourseMgmtStatus.LIVE.getValue()); - assertEquals("retired", ProjectUtil.CourseMgmtStatus.RETIRED.getValue()); - } - - @Test - public void testProgressStatusSuccess() { - assertEquals(0, ProjectUtil.ProgressStatus.NOT_STARTED.getValue()); - assertEquals(1, ProjectUtil.ProgressStatus.STARTED.getValue()); - assertEquals(2, ProjectUtil.ProgressStatus.COMPLETED.getValue()); - } - - @Test - public void testEnvironmentSuccess() { - assertEquals(1, ProjectUtil.Environment.dev.getValue()); - assertEquals(2, ProjectUtil.Environment.qa.getValue()); - assertEquals(3, ProjectUtil.Environment.prod.getValue()); - } - - @Test - public void testObjectTypesSuccess() { - assertEquals("batch", ProjectUtil.ObjectTypes.batch.getValue()); - assertEquals("user", ProjectUtil.ObjectTypes.user.getValue()); - assertEquals("organisation", ProjectUtil.ObjectTypes.organisation.getValue()); - } - - @Test - public void testSourceSuccess() { - assertEquals("web", ProjectUtil.Source.WEB.getValue()); - assertEquals("android", ProjectUtil.Source.ANDROID.getValue()); - assertEquals("ios", ProjectUtil.Source.IOS.getValue()); - } - - @Test - public void testSectionDataTypeSuccess() { - assertEquals("course", ProjectUtil.SectionDataType.course.getTypeName()); - assertEquals("content", ProjectUtil.SectionDataType.content.getTypeName()); - } - - @Test - public void testStatusSuccess() { - assertEquals(1, ProjectUtil.Status.ACTIVE.getValue()); - assertEquals(0, ProjectUtil.Status.INACTIVE.getValue()); - assertEquals(false, ProjectUtil.ActiveStatus.INACTIVE.getValue()); - assertEquals(true, ProjectUtil.ActiveStatus.ACTIVE.getValue()); - } - - @Test - public void testCreateAndThrowServerErrorSuccess() { - try { - ProjectUtil.createAndThrowServerError(); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.SERVER_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.SERVER_ERROR.getErrorCode(), e.getCode()); - } - } - - @Test - public void testCreateAndThrowInvalidUserDataExceptionSuccess() { - try { - ProjectUtil.createAndThrowInvalidUserDataException(); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.invalidUsrData.getErrorCode(), e.getCode()); - } - } - - @Test - public void testGetDateRangeSuccess() { - int noOfDays = 7; - Map map = ProjectUtil.getDateRange(noOfDays); - Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT")); - cal.add(Calendar.DATE, -noOfDays); - assertEquals(map.get("startDate"), new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime())); - cal = Calendar.getInstance(TimeZone.getTimeZone("GMT")); - cal.add(Calendar.DATE, -1); - assertEquals(map.get("endDate"), new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime())); - } - - @Test - public void testGetDateRangeFailure() { - int noOfDays = 14; - Map map = ProjectUtil.getDateRange(noOfDays); - Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT")); - cal.add(Calendar.DATE, -noOfDays); - assertEquals(map.get("startDate"), new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime())); - cal = Calendar.getInstance(TimeZone.getTimeZone("GMT")); - cal.add(Calendar.DATE, noOfDays); - assertNotEquals(map.get("endDate"), new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime())); - } - - @Test - public void testGetDateRangeFailureWithZeroDays() { - int noOfDays = 0; - Map map = ProjectUtil.getDateRange(noOfDays); - assertNull(map.get("startDate")); - assertNull(map.get("endDate")); - } - - @Test - public void testGetDateRangeFailureWithNegativeValue() { - int noOfDays = -100; - Map map = ProjectUtil.getDateRange(noOfDays); - assertNull(map.get("startDate")); - assertNull(map.get("endDate")); - } - - @Test - public void testIsEmailValidFailureWithInvalidFormat() { - boolean bool = ProjectUtil.isEmailvalid("amit.kumartarento.com"); - Assert.assertFalse(bool); - } - - @Test - public void testIsEmailValidSuccess() { - boolean bool = ProjectUtil.isEmailvalid("amit.kumar@tarento.com"); - assertTrue(bool); - } - - @Test - public void testSendGetRequestSuccessWithEkStepBaseUrl() throws Exception { - String ekStepBaseUrl = System.getenv(JsonKey.CONTENT_SERVICE_BASE_URL); - if (StringUtils.isBlank(ekStepBaseUrl)) { - ekStepBaseUrl = PropertiesCache.getInstance().getProperty(JsonKey.CONTENT_SERVICE_BASE_URL); - } - String response = HttpUtil.sendGetRequest(ekStepBaseUrl + "/search/health", headers); - assertNotNull(response); - } - - @Test - public void testGetLmsUserIdSuccessWithoutFedUserId() { - String userid = ProjectUtil.getLmsUserId("1234567890"); - assertEquals("1234567890", userid); - } - - @Test - public void testGetLmsUserIdSuccessWithFedUserId() { - String userid = - ProjectUtil.getLmsUserId( - "f:" - + ProjectUtil.getConfigValue(JsonKey.SUNBIRD_KEYCLOAK_USER_FEDERATION_PROVIDER_ID) - + ":" - + "1234567890"); - assertEquals("1234567890", userid); - } - - @Test - public void testMigrateActionAcceptValueFailure() { - Assert.assertNotEquals("ok", ProjectUtil.MigrateAction.ACCEPT.getValue()); - } - - @Test - public void testMigrateActionRejectValueFailure() { - Assert.assertNotEquals("no", ProjectUtil.MigrateAction.REJECT.getValue()); - } - - @Test - public void testMigrateActionAcceptValueSuccess() { - Assert.assertEquals("accept", ProjectUtil.MigrateAction.ACCEPT.getValue()); - } - - @Test - public void testMigrateActionRejectValueSuccess() { - Assert.assertEquals("reject", ProjectUtil.MigrateAction.REJECT.getValue()); - } -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/common/models/util/SlugTest.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/common/models/util/SlugTest.java deleted file mode 100644 index e5b819662..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/common/models/util/SlugTest.java +++ /dev/null @@ -1,26 +0,0 @@ -package org.sunbird.common.models.util; - -import org.junit.Assert; -import org.junit.Test; - -public class SlugTest { - - @Test - public void createSlugWithNullValue() { - String slug = Slug.makeSlug(null, true); - Assert.assertEquals(null, slug); - } - - @Test - public void createSlug() { - String val = "NTP@#Test"; - String slug = Slug.makeSlug(val, true); - Assert.assertEquals("ntptest", slug); - } - - @Test - public void removeDuplicateChar() { - String val = Slug.removeDuplicateChars("ntpntest"); - Assert.assertEquals("ntpes", val); - } -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/common/models/util/URLShortnerImplTest.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/common/models/util/URLShortnerImplTest.java deleted file mode 100644 index bec50deaf..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/common/models/util/URLShortnerImplTest.java +++ /dev/null @@ -1,32 +0,0 @@ -package org.sunbird.common.models.util; - -import org.apache.commons.lang3.StringUtils; -import org.junit.Assert; -import org.junit.Test; -import org.sunbird.common.models.util.url.URLShortner; -import org.sunbird.common.models.util.url.URLShortnerImpl; - -public class URLShortnerImplTest { - - @Test - public void urlShortTest() { - URLShortner shortner = new URLShortnerImpl(); - String url = shortner.shortUrl("https://staging.open-sunbird.org/"); - Assert.assertNotNull(url); - } - - @Test - public void getShortUrlTest() { - - String SUNBIRD_WEB_URL = "sunbird_web_url"; - - String webUrl = System.getenv(SUNBIRD_WEB_URL); - if (StringUtils.isBlank(webUrl)) { - webUrl = PropertiesCache.getInstance().getProperty(SUNBIRD_WEB_URL); - } - - URLShortnerImpl shortnerImpl = new URLShortnerImpl(); - String url = shortnerImpl.getUrl(); - Assert.assertEquals(url, webUrl); - } -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/common/models/util/datasecurity/impl/EncryptionDecriptionServiceTest.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/common/models/util/datasecurity/impl/EncryptionDecriptionServiceTest.java deleted file mode 100644 index d6af62789..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/common/models/util/datasecurity/impl/EncryptionDecriptionServiceTest.java +++ /dev/null @@ -1,252 +0,0 @@ -package org.sunbird.common.models.util.datasecurity.impl; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import org.apache.commons.lang3.StringUtils; -import org.junit.BeforeClass; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runners.MethodSorters; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.models.util.PropertiesCache; -import org.sunbird.common.models.util.datasecurity.DataMaskingService; -import org.sunbird.common.models.util.datasecurity.DecryptionService; -import org.sunbird.common.models.util.datasecurity.EncryptionService; - -/** @author Amit Kumar */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -public class EncryptionDecriptionServiceTest { - - private static String data = "hello sunbird"; - private static String encryptedData = ""; - private static String decryptedData = ""; - private static EncryptionService encryptionService = null; - private static DecryptionService decryptionService = null; - private static DataMaskingService maskingService = null; - private static Map map = null; - private static List> mapList = null; - private static Map map2 = null; - private static List> mapList2 = null; - private static String sunbirdEncryption = ""; - - @BeforeClass - public static void setUp() { - sunbirdEncryption = System.getenv(JsonKey.SUNBIRD_ENCRYPTION); - if (StringUtils.isBlank(sunbirdEncryption)) { - sunbirdEncryption = PropertiesCache.getInstance().getProperty(JsonKey.SUNBIRD_ENCRYPTION); - } - map = new HashMap<>(); - map.put(JsonKey.FIRST_NAME, "Amit"); - map.put(JsonKey.LAST_NAME, "KUMAR"); - mapList = new ArrayList<>(); - mapList.add(map); - map2 = new HashMap<>(); - map2.put(JsonKey.EMAIL, "amit.ec006@gmail.com"); - map2.put(JsonKey.FIRST_NAME, "Amit"); - map2.put(JsonKey.LAST_NAME, "KUMAR"); - mapList2 = new ArrayList<>(); - mapList2.add(map2); - encryptionService = ServiceFactory.getEncryptionServiceInstance(null); - decryptionService = ServiceFactory.getDecryptionServiceInstance(null); - maskingService = ServiceFactory.getMaskingServiceInstance(null); - try { - encryptedData = encryptionService.encryptData(data); - decryptedData = decryptionService.decryptData(encryptedData); - } catch (Exception e) { - } - } - - @Test - public void testDataDecryptionFrMap() { - try { - assertEquals( - decryptionService - .decryptData(encryptionService.encryptData(map2)) - .get(JsonKey.FIRST_NAME), - "Amit"); - } catch (Exception e) { - } - } - - @Test - public void testDataDecryptionFrMapWithNullValue() { - try { - map2.put(JsonKey.LOCATION, null); - assertEquals( - decryptionService.decryptData(encryptionService.encryptData(map2)).get(JsonKey.LOCATION), - null); - } catch (Exception e) { - } - } - - @Test - public void testDataDecryptionFrMapWithEmptyValue() { - try { - map2.put(JsonKey.LOCATION, ""); - assertEquals( - decryptionService.decryptData(encryptionService.encryptData(map2)).get(JsonKey.LOCATION), - ""); - } catch (Exception e) { - } - } - - @Test - public void testDataDecryptionFrMapWithMapList() { - try { - map2.put(JsonKey.LOCATION, ""); - assertEquals( - decryptionService - .decryptData(encryptionService.encryptData(mapList2)) - .get(0) - .get(JsonKey.LOCATION), - ""); - } catch (Exception e) { - } - } - - @Test - public void testDataEncryptionFrMap() { - try { - if (JsonKey.ON.equalsIgnoreCase(sunbirdEncryption)) { - assertNotEquals(encryptionService.encryptData(map).get(JsonKey.FIRST_NAME), "Amit"); - } - } catch (Exception e) { - } - } - - @Test - public void testDataEncryptionFrListMap() { - try { - if (JsonKey.ON.equalsIgnoreCase(sunbirdEncryption)) { - assertNotEquals( - encryptionService.encryptData(mapList).get(0).get(JsonKey.FIRST_NAME), "Amit"); - } - } catch (Exception e) { - } - } - - @Test - public void testDataEncryptionFrMapWithNullValue() { - try { - if (JsonKey.ON.equalsIgnoreCase(sunbirdEncryption)) { - map.put(JsonKey.LAST_NAME, null); - assertEquals(encryptionService.encryptData(map).get(JsonKey.LAST_NAME), null); - } - } catch (Exception e) { - } - } - - @Test - public void testDataEncryptionFrMapWithEmptyValue() { - try { - if (JsonKey.ON.equalsIgnoreCase(sunbirdEncryption)) { - map.put(JsonKey.LAST_NAME, ""); - assertNotEquals(encryptionService.encryptData(map).get(JsonKey.LAST_NAME), ""); - } - } catch (Exception e) { - } - } - - @Test - public void testDataEncryption() { - try { - assertEquals(encryptedData, encryptionService.encryptData(data)); - } catch (Exception e) { - } - } - - @Test - public void testDataDecryption() { - try { - assertEquals(decryptedData, decryptionService.decryptData(encryptedData)); - } catch (Exception e) { - } - } - - @Test - public void testADataEncryption() { - try { - if (JsonKey.ON.equalsIgnoreCase(sunbirdEncryption)) { - assertNotEquals("Hello", encryptionService.encryptData("Hello")); - } else { - assertEquals("Hello", encryptionService.encryptData("Hello")); - } - } catch (Exception e) { - } - } - - @Test - public void testADataDecryption() { - try { - assertEquals("Hello", decryptionService.decryptData(encryptionService.encryptData("Hello"))); - } catch (Exception e) { - } - } - - @Test - public void testBDataDecryption() { - try { - if (JsonKey.ON.equalsIgnoreCase(sunbirdEncryption)) { - assertNotEquals( - encryptionService.encryptData("Hello"), - decryptionService.decryptData(encryptionService.encryptData("Hello"))); - } - } catch (Exception e) { - } - } - - @Test - public void testEmptyPhoneMasking() { - assertEquals(maskingService.maskPhone(""), ""); - } - - @Test - public void testNullPhoneMasking() { - assertEquals(maskingService.maskPhone(null), null); - } - - @Test - public void testPhoneMasking() { - assertEquals(maskingService.maskPhone("1234567890"), "******7890"); - } - - @Test - public void testEmptyEmailMasking() { - assertEquals(maskingService.maskEmail(""), ""); - } - - @Test - public void testNullEmailMasking() { - assertEquals(maskingService.maskEmail(null), null); - } - - @Test - public void testEmailMasking() { - assertEquals(maskingService.maskEmail("amit.ec006@gmail.com"), "am********@gmail.com"); - } - - @Test - public void testEmptyDataMasking() { - assertEquals(maskingService.maskData(""), ""); - } - - @Test - public void testNullDataMasking() { - assertEquals(maskingService.maskData(null), null); - } - - @Test - public void testDataMasking() { - assertEquals(maskingService.maskData("qwerty"), "**erty"); - } - - @Test - public void testDataOfLengthLessThanEqualTo4Masking() { - assertEquals(maskingService.maskData("qwer"), "qwer"); - } -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/common/models/util/datasecurity/impl/LogMaskServiceImplTest.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/common/models/util/datasecurity/impl/LogMaskServiceImplTest.java deleted file mode 100644 index ac9940422..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/common/models/util/datasecurity/impl/LogMaskServiceImplTest.java +++ /dev/null @@ -1,56 +0,0 @@ -package org.sunbird.common.models.util.datasecurity.impl; - -import org.junit.Test; -import org.sunbird.common.request.UserRequestValidator; - -import java.util.HashMap; - -import static org.junit.Assert.*; - -public class LogMaskServiceImplTest { - private LogMaskServiceImpl logMaskService = new LogMaskServiceImpl(); - - @Test - public void maskEmail() { - HashMap emailMaskExpectations = new HashMap(){ - { - put("abc@gmail.com", "ab*@gmail.com"); - put("abcd@yahoo.com", "ab**@yahoo.com"); - put("abcdefgh@testmail.org", "abcd****@testmail.org"); - } - }; - emailMaskExpectations.forEach((email, expectedResult) -> { - assertEquals(expectedResult, logMaskService.maskEmail(email)); - }); - } - - @Test - public void maskPhone() { - HashMap phoneMaskExpectations = new HashMap(){ - { - put("0123456789", "012345678*"); - put("123-456-789", "123-456-7**"); - put("123", "123"); - } - }; - phoneMaskExpectations.forEach((phone, expectedResult) -> { - assertEquals(expectedResult, logMaskService.maskPhone(phone)); - }); - } - - @Test - public void maskOTP() { - HashMap phoneMaskExpectations = new HashMap(){ - { - put("123456", "12345*"); - put("1234567", "12345**"); - - put("1234", "123*"); - put("123", "123"); - } - }; - phoneMaskExpectations.forEach((otp, expectedResult) -> { - assertEquals(expectedResult, logMaskService.maskOTP(otp)); - }); - } -} \ No newline at end of file diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/common/models/util/datasecurity/impl/OnWayhashingTest.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/common/models/util/datasecurity/impl/OnWayhashingTest.java deleted file mode 100644 index 3af48865a..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/common/models/util/datasecurity/impl/OnWayhashingTest.java +++ /dev/null @@ -1,30 +0,0 @@ -/** */ -package org.sunbird.common.models.util.datasecurity.impl; - -import static org.junit.Assert.assertEquals; - -import org.junit.Assert; -import org.junit.Test; -import org.sunbird.common.models.util.datasecurity.OneWayHashing; - -/** @author Manzarul */ -public class OnWayhashingTest { - public static String data = "test1234$5"; - - @Test - public void validateDataHashingSuccess() { - String encryptval = OneWayHashing.encryptVal("test1234$5"); - Assert.assertNotEquals(encryptval.length(), 0); - assertEquals(encryptval, OneWayHashing.encryptVal(data)); - } - - @Test - public void validateDataHashingFailure() { - assertEquals(OneWayHashing.encryptVal(null).length(), 0); - } - - @Test - public void validateDataHashingWithEmptyKey() { - Assert.assertNotEquals((OneWayHashing.encryptVal("")).length(), 0); - } -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/common/models/util/fcm/FCMNotificationTest.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/common/models/util/fcm/FCMNotificationTest.java deleted file mode 100644 index 398785751..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/common/models/util/fcm/FCMNotificationTest.java +++ /dev/null @@ -1,120 +0,0 @@ -/** */ -package org.sunbird.common.models.util.fcm; - -import static org.powermock.api.mockito.PowerMockito.mock; -import static org.powermock.api.mockito.PowerMockito.when; -import static org.powermock.api.mockito.PowerMockito.whenNew; - -import java.io.BufferedReader; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.HttpURLConnection; -import java.net.URL; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import com.mashape.unirest.http.Unirest; -import org.apache.http.impl.client.HttpClients; -import org.junit.Assert; -import org.junit.Before; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.MethodSorters; -import org.mockito.AdditionalMatchers; -import org.mockito.Mockito; -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.common.models.util.HttpUtil; -import org.sunbird.common.models.util.JsonKey; - -/** - * Test cases for FCM notification service. - * - * @author Manzarul - */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@RunWith(PowerMockRunner.class) -@PrepareForTest({ - HttpClients.class, - URL.class, - BufferedReader.class, - HttpUtil.class, - System.class, - Notification.class, Unirest.class -}) -@PowerMockIgnore({ "javax.management.*", "javax.net.ssl.*", "javax.security.*", "com.microsoft.azure.storage.*", - "jdk.internal.reflect.*", "sun.security.ssl.*", "javax.crypto.*", "com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*"}) -public class FCMNotificationTest { - - @Test - public void testSendNotificationSuccessWithListAndStringData() throws Exception { - Map map = new HashMap<>(); - map.put("title", "some title"); - map.put("summary", "some value"); - List list = new ArrayList<>(); - list.add("test12"); - list.add("test45"); - map.put("extra", list); - Map innerMap = new HashMap<>(); - innerMap.put("title", "some value"); - innerMap.put("link", "https://google.com"); - map.put("map", innerMap); - - String val = Notification.sendNotification("nameOFTopic", map, Notification.FCM_URL); - Assert.assertNotEquals(JsonKey.FAILURE, val); - } - - @Test - public void testSendNotificationSuccessWithStringData() { - Map map = new HashMap<>(); - map.put("title", "some title"); - map.put("summary", "some value"); - String val = Notification.sendNotification("nameOFTopic", map, Notification.FCM_URL); - Assert.assertNotEquals(JsonKey.FAILURE, val); - } - - @Test - public void testSendNotificationFailureWithEmptyFcmUrl() { - Map map = new HashMap<>(); - map.put("title", "some title"); - map.put("summary", "some value"); - String val = Notification.sendNotification("nameOFTopic", map, ""); - Assert.assertEquals(JsonKey.FAILURE, val); - } - - @Test - public void testSendNotificationFailureWithNullData() { - Map map = null; - String val = Notification.sendNotification("nameOFTopic", map, ""); - Assert.assertEquals(JsonKey.FAILURE, val); - } - - @Test - public void testSendNotificationFailureWithEmptyTopic() { - Map map = new HashMap<>(); - map.put("title", "some title"); - map.put("summary", "some value"); - String val = Notification.sendNotification("", map, ""); - Assert.assertEquals(JsonKey.FAILURE, val); - } - - @Before - public void addMockRules() { - PowerMockito.mockStatic(System.class); - PowerMockito.mockStatic(HttpUtil.class); - try { - when(System.getenv(JsonKey.SUNBIRD_FCM_ACCOUNT_KEY)).thenReturn("FCM_KEY"); - when(System.getenv(AdditionalMatchers.not(Mockito.eq(JsonKey.SUNBIRD_FCM_ACCOUNT_KEY)))) - .thenCallRealMethod(); - when(HttpUtil.sendPostRequest(Mockito.anyString(),Mockito.anyString(),Mockito.anyMap())).thenReturn("{\"" + JsonKey.MESSAGE_Id + "\": 123}"); - } catch (Exception e) { - e.printStackTrace(); - Assert.fail("Mock rules addition failed " + e.getMessage()); - } - } -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/common/request/BaseRequestValidatorTest.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/common/request/BaseRequestValidatorTest.java deleted file mode 100644 index ba0d20c27..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/common/request/BaseRequestValidatorTest.java +++ /dev/null @@ -1,132 +0,0 @@ -package org.sunbird.common.request; - -import static org.junit.Assert.assertEquals; - -import java.text.MessageFormat; -import java.util.*; -import org.junit.Test; -import org.sunbird.common.exception.ProjectCommonException; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.responsecode.ResponseCode; - -/** Created by rajatgupta on 20/03/19. */ -public class BaseRequestValidatorTest { - private static final BaseRequestValidator baseRequestValidator = new BaseRequestValidator(); - - @Test - public void testValidateSearchRequestFailureWithInvalidFieldType() { - Request request = new Request(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.FILTERS, new HashMap<>()); - requestObj.put(JsonKey.FIELDS, "invalid"); - request.setRequest(requestObj); - try { - baseRequestValidator.validateSearchRequest(request); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.dataTypeError.getErrorCode(), e.getCode()); - assertEquals( - MessageFormat.format( - ResponseCode.dataTypeError.getErrorMessage(), JsonKey.FIELDS, "List"), - e.getMessage()); - } - } - - @Test - public void testValidateSearchRequestFailureWithInvalidFieldsValueInList() { - Request request = new Request(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.FILTERS, new HashMap<>()); - requestObj.put(JsonKey.FIELDS, Arrays.asList(1)); - request.setRequest(requestObj); - try { - baseRequestValidator.validateSearchRequest(request); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.dataTypeError.getErrorCode(), e.getCode()); - assertEquals( - MessageFormat.format( - ResponseCode.dataTypeError.getErrorMessage(), JsonKey.FIELDS, "List of String"), - e.getMessage()); - } - } - - @Test - public void testValidateSearchRequestFailureWithInvalidFiltersKeyAsNull() { - Request request = new Request(); - Map requestObj = new HashMap<>(); - Map filterMap = new HashMap<>(); - filterMap.put(null, "data"); - requestObj.put(JsonKey.FILTERS, filterMap); - - request.setRequest(requestObj); - try { - baseRequestValidator.validateSearchRequest(request); - } catch (ProjectCommonException e) { - assertEquals( - MessageFormat.format( - ResponseCode.invalidParameterValue.getErrorMessage(), null, JsonKey.FILTERS), - e.getMessage()); - } - } - - @Test - public void testValidateSearchRequestFailureWithInvalidFiltersNullValueInList() { - Request request = new Request(); - Map requestObj = new HashMap<>(); - Map filterMap = new HashMap<>(); - List data = new ArrayList<>(); - data.add(null); - filterMap.put(JsonKey.FIRST_NAME, data); - requestObj.put(JsonKey.FILTERS, filterMap); - - request.setRequest(requestObj); - try { - baseRequestValidator.validateSearchRequest(request); - } catch (ProjectCommonException e) { - assertEquals( - MessageFormat.format( - ResponseCode.invalidParameterValue.getErrorMessage(), null, JsonKey.FIRST_NAME), - e.getMessage()); - } - } - - @Test - public void testValidateSearchRequestFailureWithInvalidFiltersNullValueInMap() { - Request request = new Request(); - Map requestObj = new HashMap<>(); - Map filterMap = new HashMap<>(); - Map data = new HashMap<>(); - data.put(JsonKey.FIRST_NAME, null); - filterMap.put(JsonKey.FIELD, data); - requestObj.put(JsonKey.FILTERS, filterMap); - - request.setRequest(requestObj); - try { - baseRequestValidator.validateSearchRequest(request); - } catch (ProjectCommonException e) { - assertEquals( - MessageFormat.format( - ResponseCode.invalidParameterValue.getErrorMessage(), null, JsonKey.FIRST_NAME), - e.getMessage()); - } - } - - @Test - public void testValidateSearchRequestFailureWithInvalidFiltersNullValueInString() { - Request request = new Request(); - Map requestObj = new HashMap<>(); - Map data = new HashMap<>(); - data.put(JsonKey.FIRST_NAME, null); - - requestObj.put(JsonKey.FILTERS, data); - - request.setRequest(requestObj); - try { - baseRequestValidator.validateSearchRequest(request); - } catch (ProjectCommonException e) { - assertEquals( - MessageFormat.format( - ResponseCode.invalidParameterValue.getErrorMessage(), null, JsonKey.FIRST_NAME), - e.getMessage()); - } - } -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/common/request/CourseBatchValidatorTest.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/common/request/CourseBatchValidatorTest.java deleted file mode 100644 index d7ae70a35..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/common/request/CourseBatchValidatorTest.java +++ /dev/null @@ -1,440 +0,0 @@ -/** */ -package org.sunbird.common.request; - -import static org.junit.Assert.assertEquals; - -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import org.junit.Assert; -import org.junit.Test; -import org.sunbird.common.exception.ProjectCommonException; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.responsecode.ResponseCode; - -/** @author Manzarul */ -public class CourseBatchValidatorTest { - - private static SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); - - @Test - public void validateCreateBatchSuccess() { - Request request = new Request(); - boolean response = false; - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.STATUS, 1); - requestObj.put(JsonKey.COURSE_ID, "do_123233434"); - requestObj.put(JsonKey.NAME, "TestCourse"); - requestObj.put(JsonKey.ENROLLMENT_TYPE, "Open"); - requestObj.put(JsonKey.START_DATE, format.format(new Date())); - Calendar cal = Calendar.getInstance(); - cal.add(Calendar.DAY_OF_MONTH, 2); - requestObj.put(JsonKey.END_DATE, format.format(cal.getTime())); - List userIds = new ArrayList(); - userIds.add("test123345"); - request.put(JsonKey.COURSE_CREATED_FOR, userIds); - request.setRequest(requestObj); - try { - RequestValidator.validateCreateBatchReq(request); - response = true; - } catch (ProjectCommonException e) { - Assert.assertNull(e); - } - assertEquals(true, response); - } - - @Test - public void validateUpdateCourseBatch() { - Request request = new Request(); - boolean response = false; - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.COURSE_ID, "do_123233434"); - requestObj.put(JsonKey.NAME, "TestCourse"); - requestObj.put(JsonKey.ENROLLMENT_TYPE, "Open"); - requestObj.put(JsonKey.START_DATE, format.format(new Date())); - Calendar cal = Calendar.getInstance(); - cal.add(Calendar.DAY_OF_MONTH, 2); - requestObj.put(JsonKey.END_DATE, format.format(cal.getTime())); - List userIds = new ArrayList(); - userIds.add("test123345"); - request.put(JsonKey.COURSE_CREATED_FOR, userIds); - request.setRequest(requestObj); - try { - RequestValidator.validateUpdateCourseBatchReq(request); - response = true; - } catch (ProjectCommonException e) { - Assert.assertNull(e); - } - assertEquals(true, response); - } - - @Test - public void validateCreateBatchWithOutCourseId() { - Request request = new Request(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.COURSE_ID, ""); - requestObj.put(JsonKey.NAME, "TestCourse"); - requestObj.put(JsonKey.ENROLLMENT_TYPE, "Open"); - requestObj.put(JsonKey.START_DATE, format.format(new Date())); - Calendar cal = Calendar.getInstance(); - cal.add(Calendar.DAY_OF_MONTH, 2); - requestObj.put(JsonKey.END_DATE, format.format(cal.getTime())); - List userIds = new ArrayList(); - userIds.add("test123345"); - request.put(JsonKey.COURSE_CREATED_FOR, userIds); - request.setRequest(requestObj); - try { - RequestValidator.validateCreateBatchReq(request); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.invalidCourseId.getErrorCode(), e.getCode()); - } - } - - @Test - public void validateCreateBatchWithOutName() { - Request request = new Request(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.COURSE_ID, "do_123233434"); - requestObj.put(JsonKey.ENROLLMENT_TYPE, "Open"); - requestObj.put(JsonKey.NAME, "TestCourse"); - requestObj.put(JsonKey.START_DATE, format.format(new Date())); - Calendar cal = Calendar.getInstance(); - cal.add(Calendar.DAY_OF_MONTH, 2); - requestObj.put(JsonKey.END_DATE, format.format(cal.getTime())); - List userIds = new ArrayList(); - userIds.add("test123345"); - request.put(JsonKey.COURSE_CREATED_FOR, userIds); - request.setRequest(requestObj); - try { - RequestValidator.validateCreateBatchReq(request); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.courseNameRequired.getErrorCode(), e.getCode()); - } - } - - @Test - public void validateCreateBatchWithOutStartDate() { - Request request = new Request(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.COURSE_ID, "do_123233434"); - requestObj.put(JsonKey.ENROLLMENT_TYPE, "Open"); - requestObj.put(JsonKey.NAME, "TestCourse"); - Calendar cal = Calendar.getInstance(); - cal.add(Calendar.DAY_OF_MONTH, 2); - requestObj.put(JsonKey.END_DATE, format.format(cal.getTime())); - List userIds = new ArrayList(); - userIds.add("test123345"); - request.put(JsonKey.COURSE_CREATED_FOR, userIds); - request.setRequest(requestObj); - try { - RequestValidator.validateCreateBatchReq(request); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.courseBatchStartDateRequired.getErrorCode(), e.getCode()); - } - } - - @Test - public void validateCreateBatchWithPastStartDate() { - Request request = new Request(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.COURSE_ID, "do_123233434"); - requestObj.put(JsonKey.ENROLLMENT_TYPE, "Open"); - requestObj.put(JsonKey.START_DATE, "2017-01-05"); - requestObj.put(JsonKey.NAME, "TestCourse"); - Calendar cal = Calendar.getInstance(); - cal.add(Calendar.DAY_OF_MONTH, 2); - requestObj.put(JsonKey.END_DATE, format.format(cal.getTime())); - List userIds = new ArrayList(); - userIds.add("test123345"); - request.put(JsonKey.COURSE_CREATED_FOR, userIds); - request.setRequest(requestObj); - try { - RequestValidator.validateCreateBatchReq(request); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.courseBatchStartDateError.getErrorCode(), e.getCode()); - } - } - - @Test - public void validateCreateBatchWithInvalidStartDateFormat() { - Request request = new Request(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.COURSE_ID, "do_123233434"); - requestObj.put(JsonKey.ENROLLMENT_TYPE, "Open"); - requestObj.put(JsonKey.START_DATE, format.format(new Date()) + " 23:58:59"); - requestObj.put(JsonKey.NAME, "TestCourse"); - Calendar cal = Calendar.getInstance(); - cal.add(Calendar.DAY_OF_MONTH, 2); - requestObj.put(JsonKey.END_DATE, format.format(cal.getTime())); - List userIds = new ArrayList(); - userIds.add("test123345"); - request.put(JsonKey.COURSE_CREATED_FOR, userIds); - request.setRequest(requestObj); - try { - RequestValidator.validateCreateBatchReq(request); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.dateFormatError.getErrorCode(), e.getCode()); - } - } - - @Test - public void validateCreateBatchWithEmptyEndDate() { - Request request = new Request(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.COURSE_ID, "do_123233434"); - requestObj.put(JsonKey.ENROLLMENT_TYPE, "Open"); - requestObj.put(JsonKey.NAME, "TestCourse"); - requestObj.put(JsonKey.START_DATE, "2017-01-05"); - Calendar cal = Calendar.getInstance(); - cal.add(Calendar.DAY_OF_MONTH, 2); - requestObj.put(JsonKey.END_DATE, ""); - List userIds = new ArrayList(); - userIds.add("test123345"); - request.put(JsonKey.COURSE_CREATED_FOR, userIds); - request.setRequest(requestObj); - try { - RequestValidator.validateCreateBatchReq(request); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.courseBatchStartDateError.getErrorCode(), e.getCode()); - } - } - - @Test - public void validateCreateBatchWithPastEndDate() { - Request request = new Request(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.COURSE_ID, "do_123233434"); - requestObj.put(JsonKey.ENROLLMENT_TYPE, "Open"); - requestObj.put(JsonKey.NAME, "TestCourse"); - requestObj.put(JsonKey.START_DATE, format.format(new Date())); - Calendar cal = Calendar.getInstance(); - cal.add(Calendar.DAY_OF_MONTH, -2); - requestObj.put(JsonKey.END_DATE, format.format(cal.getTime())); - List userIds = new ArrayList(); - userIds.add("test123345"); - request.put(JsonKey.COURSE_CREATED_FOR, userIds); - request.setRequest(requestObj); - try { - RequestValidator.validateCreateBatchReq(request); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.endDateError.getErrorCode(), e.getCode()); - } - } - - @Test - public void validateCreateBatchWithInvalidEndDateFormat() { - Request request = new Request(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.COURSE_ID, "do_123233434"); - requestObj.put(JsonKey.ENROLLMENT_TYPE, "Open"); - requestObj.put(JsonKey.NAME, "TestCourse"); - requestObj.put(JsonKey.START_DATE, format.format(new Date())); - Calendar cal = Calendar.getInstance(); - cal.add(Calendar.DAY_OF_MONTH, 2); - requestObj.put(JsonKey.END_DATE, format.format(cal.getTime()) + " 23:59:59+Z:50"); - List userIds = new ArrayList(); - userIds.add("test123345"); - request.put(JsonKey.COURSE_CREATED_FOR, userIds); - request.setRequest(requestObj); - try { - RequestValidator.validateCreateBatchReq(request); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.dateFormatError.getErrorCode(), e.getCode()); - } - } - - @Test - public void validateAddBatchCourse() { - Request request = new Request(); - boolean response = false; - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.BATCH_ID, "cassandra batch id"); - List list = new ArrayList<>(); - list.add("user id whome need to join"); - requestObj.put(JsonKey.USER_IDs, list); - request.setRequest(requestObj); - try { - RequestValidator.validateAddBatchCourse(request); - response = true; - } catch (ProjectCommonException e) { - Assert.assertNull(e); - } - assertEquals(true, response); - } - - @Test - public void validateAddBatchCourseWithEmptyBatchId() { - Request request = new Request(); - boolean response = false; - Map requestObj = new HashMap<>(); - List list = new ArrayList<>(); - list.add("user id whome need to join"); - requestObj.put(JsonKey.USER_IDs, list); - request.setRequest(requestObj); - try { - RequestValidator.validateAddBatchCourse(request); - response = true; - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.courseBatchIdRequired.getErrorCode(), e.getCode()); - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - } - assertEquals(false, response); - } - - @Test - public void validateAddBatchCourseWithEmptyUserId() { - Request request = new Request(); - boolean response = false; - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.BATCH_ID, "cassandra batch id"); - request.setRequest(requestObj); - try { - RequestValidator.validateAddBatchCourse(request); - response = true; - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.userIdRequired.getErrorCode(), e.getCode()); - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - } - assertEquals(false, response); - } - - @Test - public void validateGetBatchCourse() { - Request request = new Request(); - boolean response = false; - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.BATCH_ID, "cassandra batch id"); - request.setRequest(requestObj); - try { - RequestValidator.validateGetBatchCourse(request); - response = true; - } catch (ProjectCommonException e) { - Assert.assertNull(e); - } - assertEquals(true, response); - } - - @Test - public void validateGetBatchCourseWithOutBatchId() { - Request request = new Request(); - boolean response = false; - Map requestObj = new HashMap<>(); - request.setRequest(requestObj); - try { - RequestValidator.validateGetBatchCourse(request); - response = true; - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.courseBatchIdRequired.getErrorCode(), e.getCode()); - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - } - assertEquals(false, response); - } - - @Test - public void validateUpdateCourse() { - Request request = new Request(); - boolean response = false; - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.COURSE_ID, "cassandra batch id"); - request.setRequest(requestObj); - try { - RequestValidator.validateUpdateCourse(request); - response = true; - } catch (ProjectCommonException e) { - Assert.assertNull(e); - } - assertEquals(true, response); - } - - @Test - public void validateUpdateCourseWithOurBatchId() { - Request request = new Request(); - boolean response = false; - Map requestObj = new HashMap<>(); - request.setRequest(requestObj); - try { - RequestValidator.validateUpdateCourse(request); - response = true; - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.courseIdRequired.getErrorCode(), e.getCode()); - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - } - assertEquals(false, response); - } - - @Test - public void validatePublishedCourse() { - Request request = new Request(); - boolean response = false; - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.COURSE_ID, "cassandra batch id"); - request.setRequest(requestObj); - try { - RequestValidator.validatePublishCourse(request); - response = true; - } catch (ProjectCommonException e) { - Assert.assertNull(e); - } - assertEquals(true, response); - } - - @Test - public void validatePublishedCourseWithOutCourseId() { - Request request = new Request(); - boolean response = false; - Map requestObj = new HashMap<>(); - request.setRequest(requestObj); - try { - RequestValidator.validatePublishCourse(request); - response = true; - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.courseIdRequiredError.getErrorCode(), e.getCode()); - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - } - assertEquals(false, response); - } - - @Test - public void validateDeleteCourse() { - Request request = new Request(); - boolean response = false; - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.COURSE_ID, "cassandra batch id"); - request.setRequest(requestObj); - try { - RequestValidator.validateDeleteCourse(request); - response = true; - } catch (ProjectCommonException e) { - Assert.assertNull(e); - } - assertEquals(true, response); - } - - @Test - public void validateDeleteCourseWithOutCourseId() { - Request request = new Request(); - boolean response = false; - Map requestObj = new HashMap<>(); - request.setRequest(requestObj); - try { - RequestValidator.validateDeleteCourse(request); - response = true; - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.courseIdRequiredError.getErrorCode(), e.getCode()); - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - } - assertEquals(false, response); - } -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/common/request/NotesRequestValidatorTest.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/common/request/NotesRequestValidatorTest.java deleted file mode 100644 index a0ded1328..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/common/request/NotesRequestValidatorTest.java +++ /dev/null @@ -1,133 +0,0 @@ -package org.sunbird.common.request; - -import static org.junit.Assert.assertEquals; - -import java.util.HashMap; -import java.util.Map; -import org.junit.Test; -import org.sunbird.common.exception.ProjectCommonException; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.responsecode.ResponseCode; - -/** Test class for notes request validation */ -public class NotesRequestValidatorTest { - - /** Method to test create note when userId in request is empty */ - @Test - public void testCreateNoteBlankUserId() { - try { - Request request = new Request(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.USER_ID, ""); - requestObj.put(JsonKey.TITLE, "test title"); - requestObj.put(JsonKey.NOTE, "This is a test Note"); - requestObj.put(JsonKey.COURSE_ID, "org.ekstep.test"); - requestObj.put(JsonKey.CONTENT_ID, "org.ekstep.test"); - request.setRequest(requestObj); - RequestValidator.validateNote(request); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.userIdRequired.getErrorCode(), e.getCode()); - } - } - - /** Method to test create note when title in request is empty */ - @Test - public void testCreateNoteBlankTitle() { - try { - Request request = new Request(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.USER_ID, "testUser"); - requestObj.put(JsonKey.TITLE, ""); - requestObj.put(JsonKey.NOTE, "This is a test Note"); - requestObj.put(JsonKey.COURSE_ID, "org.ekstep.test"); - requestObj.put(JsonKey.CONTENT_ID, "org.ekstep.test"); - request.setRequest(requestObj); - RequestValidator.validateNote(request); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.titleRequired.getErrorCode(), e.getCode()); - } - } - - /** Method to test create note when note in request is empty */ - @Test - public void testCreateNoteBlankNote() { - try { - Request request = new Request(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.USER_ID, "testUser"); - requestObj.put(JsonKey.TITLE, "test title"); - requestObj.put(JsonKey.NOTE, ""); - requestObj.put(JsonKey.COURSE_ID, "org.ekstep.test"); - requestObj.put(JsonKey.CONTENT_ID, "org.ekstep.test"); - request.setRequest(requestObj); - RequestValidator.validateNote(request); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.noteRequired.getErrorCode(), e.getCode()); - } - } - - /** Method to test create note without courseId and contentId in request */ - @Test - public void testCreateNoteWithoutCourseAndContentId() { - try { - Request request = new Request(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.USER_ID, "testUser"); - requestObj.put(JsonKey.TITLE, "test title"); - requestObj.put(JsonKey.NOTE, "This is a test Note"); - requestObj.put(JsonKey.COURSE_ID, ""); - requestObj.put(JsonKey.CONTENT_ID, ""); - request.setRequest(requestObj); - RequestValidator.validateNote(request); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.contentIdError.getErrorCode(), e.getCode()); - } - } - - /** Method to test create note when tags in request is string */ - @Test - public void testCreateNoteWithTagsAsString() { - try { - Request request = new Request(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.USER_ID, "testUser"); - requestObj.put(JsonKey.TITLE, "test title"); - requestObj.put(JsonKey.NOTE, "This is a test Note"); - requestObj.put(JsonKey.COURSE_ID, "org.ekstep.test"); - requestObj.put(JsonKey.TAGS, "test tag"); - request.setRequest(requestObj); - RequestValidator.validateNote(request); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.invalidTags.getErrorCode(), e.getCode()); - } - } - - /** Method to test validate node id when note id is empty */ - @Test - public void testValidateNoteOperationWithOutNoteId() { - try { - String noteId = ""; - RequestValidator.validateNoteId(noteId); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.invalidNoteId.getErrorCode(), e.getCode()); - } - } - - /** Method to test validate node id when note id is null */ - @Test - public void testValidateNoteOperationWithNoteIdAsNull() { - try { - String noteId = null; - RequestValidator.validateNoteId(noteId); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.invalidNoteId.getErrorCode(), e.getCode()); - } - } -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/common/request/NotificationRequestValidatorTest.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/common/request/NotificationRequestValidatorTest.java deleted file mode 100644 index ccc09d11f..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/common/request/NotificationRequestValidatorTest.java +++ /dev/null @@ -1,140 +0,0 @@ -/** */ -package org.sunbird.common.request; - -import static org.junit.Assert.assertEquals; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import org.junit.Assert; -import org.junit.Test; -import org.sunbird.common.exception.ProjectCommonException; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.responsecode.ResponseCode; - -/** @author Manzarul */ -public class NotificationRequestValidatorTest { - - @Test - public void validateSendNotificationSuccess() { - Request request = new Request(); - boolean response = false; - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.TO, "test"); - requestObj.put(JsonKey.TYPE, "FCM"); - Map data = new HashMap<>(); - data.put("url", "www.google.com"); - requestObj.put(JsonKey.DATA, data); - request.setRequest(requestObj); - try { - RequestValidator.validateSendNotification(request); - response = true; - } catch (ProjectCommonException e) { - Assert.assertNull(e); - } - assertEquals(true, response); - } - - @Test - public void validateSendNotificationWithOutTOParam() { - Request request = new Request(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.TYPE, "FCM"); - Map data = new HashMap<>(); - data.put("url", "www.google.com"); - requestObj.put(JsonKey.DATA, data); - request.setRequest(requestObj); - try { - RequestValidator.validateSendNotification(request); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.invalidTopic.getErrorCode(), e.getCode()); - } - } - - @Test - public void validateSendNotificationWithOutType() { - Request request = new Request(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.TO, "test"); - Map data = new HashMap<>(); - data.put("url", "www.google.com"); - requestObj.put(JsonKey.DATA, data); - request.setRequest(requestObj); - try { - RequestValidator.validateSendNotification(request); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.invalidNotificationType.getErrorCode(), e.getCode()); - } - } - - @Test - public void validateSendNotificationWithWrongType() { - Request request = new Request(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.TO, "test"); - requestObj.put(JsonKey.TYPE, "GCM"); - Map data = new HashMap<>(); - data.put("url", "www.google.com"); - requestObj.put(JsonKey.DATA, data); - request.setRequest(requestObj); - try { - RequestValidator.validateSendNotification(request); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.notificationTypeSupport.getErrorCode(), e.getCode()); - } - } - - @Test - public void validateSendNotificationWithEmptyData() { - Request request = new Request(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.TO, "test"); - requestObj.put(JsonKey.TYPE, "FCM"); - request.setRequest(requestObj); - try { - RequestValidator.validateSendNotification(request); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.invalidTopicData.getErrorCode(), e.getCode()); - } - } - - @Test - public void validateSendNotificationWithWrongObjectType() { - Request request = new Request(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.TO, "test"); - requestObj.put(JsonKey.TYPE, "FCM"); - List data = new ArrayList(); - data.add("www.google.com"); - requestObj.put(JsonKey.DATA, data); - request.setRequest(requestObj); - try { - RequestValidator.validateSendNotification(request); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.invalidTopicData.getErrorCode(), e.getCode()); - } - } - - @Test - public void validateSendNotificationWithEmptyDataMap() { - Request request = new Request(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.TO, "test"); - requestObj.put(JsonKey.TYPE, "FCM"); - Map data = new HashMap<>(); - requestObj.put(JsonKey.DATA, data); - request.setRequest(requestObj); - try { - RequestValidator.validateSendNotification(request); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.invalidTopicData.getErrorCode(), e.getCode()); - } - } -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/common/request/OrgValidatorTest.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/common/request/OrgValidatorTest.java deleted file mode 100644 index d41dfa8a9..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/common/request/OrgValidatorTest.java +++ /dev/null @@ -1,228 +0,0 @@ -/** */ -package org.sunbird.common.request; - -import static org.junit.Assert.assertEquals; - -import java.util.HashMap; -import java.util.Map; -import org.junit.Assert; -import org.junit.Test; -import org.sunbird.common.exception.ProjectCommonException; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.request.orgvalidator.OrgRequestValidator; -import org.sunbird.common.responsecode.ResponseCode; - -/** @author Manzarul */ -public class OrgValidatorTest { - - @Test - public void validateCreateOrgSuccess() { - Request request = new Request(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.ORG_NAME, "test"); - requestObj.put(JsonKey.IS_ROOT_ORG, true); - requestObj.put(JsonKey.CHANNEL, "tpp"); - request.setRequest(requestObj); - try { - // this method will either throw projectCommonException or it return void - new OrgRequestValidator().validateCreateOrgRequest(request); - requestObj.put("ext", "success"); - } catch (ProjectCommonException e) { - Assert.assertNull(e); - } - assertEquals("success", requestObj.get("ext")); - } - - @Test - public void validateCreateRootOrgWithLicenseSuccess() { - Request request = new Request(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.ORG_NAME, "test"); - requestObj.put(JsonKey.IS_ROOT_ORG, true); - requestObj.put(JsonKey.CHANNEL, "tpp"); - requestObj.put(JsonKey.LICENSE, "Test license"); - request.setRequest(requestObj); - try { - // this method will either throw projectCommonException or it return void - new OrgRequestValidator().validateCreateOrgRequest(request); - requestObj.put("ext", "success"); - } catch (ProjectCommonException e) { - Assert.assertNull(e); - } - assertEquals("success", requestObj.get("ext")); - } - - @Test - public void validateCreateRootOrgWithEmptyLicenseFailure() { - Request request = new Request(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.ORG_NAME, "test"); - requestObj.put(JsonKey.IS_ROOT_ORG, true); - requestObj.put(JsonKey.CHANNEL, "tpp"); - requestObj.put(JsonKey.LICENSE, ""); - request.setRequest(requestObj); - try { - // this method will either throw projectCommonException or it return void - new OrgRequestValidator().validateCreateOrgRequest(request); - requestObj.put("ext", "success"); - } catch (ProjectCommonException e) { - Assert.assertNotNull(e); - } - assertEquals(requestObj.get("ext"), null); - } - - @Test - public void validateCreateOrgWithOutName() { - Request request = new Request(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.IS_ROOT_ORG, true); - requestObj.put(JsonKey.CHANNEL, "tpp"); - request.setRequest(requestObj); - try { - // this method will either throw projectCommonException or it return void - new OrgRequestValidator().validateCreateOrgRequest(request); - requestObj.put("ext", "success"); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.mandatoryParamsMissing.getErrorCode(), e.getCode()); - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - } - assertEquals(null, requestObj.get("ext")); - } - - @Test - public void validateCreateOrgWithRootOrgTrueAndWithOutChannel() { - Request request = new Request(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.ORG_NAME, "test"); - requestObj.put(JsonKey.IS_ROOT_ORG, true); - requestObj.put(JsonKey.CHANNEL, ""); - request.setRequest(requestObj); - try { - // this method will either throw projectCommonException or it return void - new OrgRequestValidator().validateCreateOrgRequest(request); - requestObj.put("ext", "success"); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.dependentParamsMissing.getErrorCode(), e.getCode()); - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - } - assertEquals(null, requestObj.get("ext")); - } - - @Test - public void validateUpdateCreateOrgSuccess() { - Request request = new Request(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.ORG_NAME, "test"); - requestObj.put(JsonKey.ORGANISATION_ID, "test12344"); - requestObj.put(JsonKey.IS_ROOT_ORG, true); - requestObj.put(JsonKey.CHANNEL, "tpp"); - request.setRequest(requestObj); - try { - // this method will either throw projectCommonException or it return void - new OrgRequestValidator().validateUpdateOrgRequest(request); - requestObj.put("ext", "success"); - } catch (ProjectCommonException e) { - Assert.assertNull(e); - } - assertEquals("success", requestObj.get("ext")); - } - - @Test - public void validateUpdateOrgFailure() { - Request request = new Request(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.ORGANISATION_ID, "test2344"); - requestObj.put(JsonKey.ROOT_ORG_ID, ""); - requestObj.put(JsonKey.ORG_NAME, "test"); - requestObj.put(JsonKey.IS_ROOT_ORG, true); - requestObj.put(JsonKey.CHANNEL, "tpp"); - request.setRequest(requestObj); - try { - // this method will either throw projectCommonException or it return void - new OrgRequestValidator().validateUpdateOrgRequest(request); - requestObj.put("ext", "success"); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.invalidRootOrganisationId.getErrorCode(), e.getCode()); - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - } - assertEquals(null, requestObj.get("ext")); - } - - @Test - public void validateUpdateOrgWithStatus() { - Request request = new Request(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.STATUS, "true"); - requestObj.put(JsonKey.ORG_NAME, "test"); - requestObj.put(JsonKey.IS_ROOT_ORG, true); - requestObj.put(JsonKey.CHANNEL, "tpp"); - requestObj.put(JsonKey.ORGANISATION_ID, "test123444"); - request.setRequest(requestObj); - try { - // this method will either throw projectCommonException or it return void - new OrgRequestValidator().validateUpdateOrgRequest(request); - requestObj.put("ext", "success"); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.invalidRequestParameter.getErrorCode(), e.getCode()); - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - } - assertEquals(null, requestObj.get("ext")); - } - - @Test - public void validateUpdateOrgWithEmptyChannel() { - Request request = new Request(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.ORG_NAME, "test"); - requestObj.put(JsonKey.IS_ROOT_ORG, true); - requestObj.put(JsonKey.CHANNEL, ""); - requestObj.put(JsonKey.ORGANISATION_ID, "test123444"); - request.setRequest(requestObj); - try { - // this method will either throw projectCommonException or it return void - new OrgRequestValidator().validateUpdateOrgRequest(request); - requestObj.put("ext", "success"); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.dependentParamsMissing.getErrorCode(), e.getCode()); - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - } - assertEquals(null, requestObj.get("ext")); - } - - @Test - public void validateUpdateOrgStatus() { - Request request = new Request(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.ORG_NAME, "test"); - requestObj.put(JsonKey.STATUS, 2); - requestObj.put(JsonKey.ORGANISATION_ID, "test-12334"); - request.setRequest(requestObj); - try { - // this method will either throw projectCommonException or it return void - new OrgRequestValidator().validateUpdateOrgStatusRequest(request); - requestObj.put("ext", "success"); - } catch (ProjectCommonException e) { - Assert.assertNull(e); - } - assertEquals("success", requestObj.get("ext")); - } - - @Test - public void validateUpdateOrgStatusWithInvalidStatus() { - Request request = new Request(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.ORG_NAME, "test"); - requestObj.put(JsonKey.STATUS, "true"); - requestObj.put(JsonKey.ORGANISATION_ID, "test-12334"); - request.setRequest(requestObj); - try { - // this method will either throw projectCommonException or it return void - new OrgRequestValidator().validateUpdateOrgStatusRequest(request); - requestObj.put("ext", "success"); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.invalidRequestData.getErrorCode(), e.getCode()); - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - } - assertEquals(null, requestObj.get("ext")); - } -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/common/request/PageSectionValidatorTest.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/common/request/PageSectionValidatorTest.java deleted file mode 100644 index 9f0d387bd..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/common/request/PageSectionValidatorTest.java +++ /dev/null @@ -1,284 +0,0 @@ -/** */ -package org.sunbird.common.request; - -import static org.junit.Assert.assertEquals; - -import java.util.HashMap; -import java.util.Map; -import org.junit.Assert; -import org.junit.Test; -import org.sunbird.common.exception.ProjectCommonException; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.responsecode.ResponseCode; - -/** @author Manzarul */ -public class PageSectionValidatorTest { - - @Test - public void testValidateGetPageDataSuccess() { - Request request = new Request(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.SOURCE, "web"); - requestObj.put(JsonKey.PAGE_NAME, "resource"); - request.setRequest(requestObj); - try { - // this method will either throw projectCommonException or it return void - RequestValidator.validateGetPageData(request); - requestObj.put("ext", "success"); - } catch (ProjectCommonException e) { - Assert.assertNull(e); - } - assertEquals("success", (String) requestObj.get("ext")); - } - - @Test - public void testValidateGetPageDataFailureWithoutSource() { - Request request = new Request(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.PAGE_NAME, "resource"); - request.setRequest(requestObj); - try { - // this method will either throw projectCommonException or it return void - RequestValidator.validateGetPageData(request); - requestObj.put("ext", "success"); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.sourceRequired.getErrorCode(), e.getCode()); - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - } - assertEquals(null, (String) requestObj.get("ext")); - } - - @Test - public void testValidateGetPageDataFailureWithoutPageName() { - Request request = new Request(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.SOURCE, "web"); - request.setRequest(requestObj); - try { - // this method will either throw projectCommonException or it return void - RequestValidator.validateGetPageData(request); - requestObj.put("ext", "success"); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.pageNameRequired.getErrorCode(), e.getCode()); - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - } - assertEquals(null, (String) requestObj.get("ext")); - } - - @Test - public void testValidateCreateSectionSuccess() { - Request request = new Request(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.SECTION_NAME, "latest resource"); - requestObj.put( - JsonKey.SECTION_DATA_TYPE, "{\"request\": { \"search\": {\"contentType\": [\"Story\"] }}}"); - request.setRequest(requestObj); - try { - // this method will either throw projectCommonException or it return void - RequestValidator.validateCreateSection(request); - requestObj.put("ext", "success"); - } catch (ProjectCommonException e) { - Assert.assertNull(e); - } - assertEquals("success", (String) requestObj.get("ext")); - } - - @Test - public void testValidateCreateSectionFailureWithoutSectionName() { - Request request = new Request(); - Map requestObj = new HashMap<>(); - requestObj.put( - JsonKey.SECTION_DATA_TYPE, "{\"request\": { \"search\": {\"contentType\": [\"Story\"] }}}"); - request.setRequest(requestObj); - try { - // this method will either throw projectCommonException or it return void - RequestValidator.validateCreateSection(request); - requestObj.put("ext", "success"); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.sectionNameRequired.getErrorCode(), e.getCode()); - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - } - assertEquals(null, (String) requestObj.get("ext")); - } - - @Test - public void testValidateCreateSectionFailureWithoutSectionDataType() { - Request request = new Request(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.SECTION_NAME, "latest resource"); - request.setRequest(requestObj); - try { - // this method will either throw projectCommonException or it return void - RequestValidator.validateCreateSection(request); - requestObj.put("ext", "success"); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.sectionDataTypeRequired.getErrorCode(), e.getCode()); - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - } - assertEquals(null, (String) requestObj.get("ext")); - } - - @Test - public void testValidateUpdateSectionSuccess() { - Request request = new Request(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.SECTION_NAME, "latest resource"); - requestObj.put( - JsonKey.SECTION_DATA_TYPE, "{\"request\": { \"search\": {\"contentType\": [\"Story\"] }}}"); - requestObj.put(JsonKey.ID, "some section id"); - request.setRequest(requestObj); - try { - // this method will either throw projectCommonException or it return void - RequestValidator.validateUpdateSection(request); - requestObj.put("ext", "success"); - } catch (ProjectCommonException e) { - Assert.assertNull(e); - } - assertEquals("success", (String) requestObj.get("ext")); - } - - @Test - public void testValidateUpdateSectionFailureWithoutId() { - Request request = new Request(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.SECTION_NAME, "latest resource"); - requestObj.put( - JsonKey.SECTION_DATA_TYPE, "{\"request\": { \"search\": {\"contentType\": [\"Story\"] }}}"); - request.setRequest(requestObj); - try { - // this method will either throw projectCommonException or it return void - RequestValidator.validateUpdateSection(request); - requestObj.put("ext", "success"); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.sectionIdRequired.getErrorCode(), e.getCode()); - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - } - assertEquals(null, (String) requestObj.get("ext")); - } - - @Test - public void testValidateUpdateSectionFailureWithoutSectioName() { - Request request = new Request(); - boolean reqSuccess = false; - Map requestObj = new HashMap<>(); - requestObj.put( - JsonKey.SECTION_DATA_TYPE, "{\"request\": { \"search\": {\"contentType\": [\"Story\"] }}}"); - requestObj.put(JsonKey.ID, "some section id"); - requestObj.put(JsonKey.SECTION_NAME, ""); - request.setRequest(requestObj); - try { - // this method will either throw projectCommonException or it return void - RequestValidator.validateUpdateSection(request); - reqSuccess = true; - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.sectionNameRequired.getErrorCode(), e.getCode()); - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - } - assertEquals(false, reqSuccess); - } - - @Test - public void testValidateUpdateSectionFailureWithoutSectioData() { - Request request = new Request(); - boolean reqSuccess = false; - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.SECTION_NAME, "latest resource"); - requestObj.put(JsonKey.SECTION_DATA_TYPE, ""); - requestObj.put(JsonKey.ID, "some section id"); - request.setRequest(requestObj); - try { - // this method will either throw projectCommonException or it return void - RequestValidator.validateUpdateSection(request); - reqSuccess = true; - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.sectionDataTypeRequired.getErrorCode(), e.getCode()); - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - } - assertEquals(false, reqSuccess); - } - - @Test - public void testValidateCreatePageSuccess() { - Request request = new Request(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.PAGE_NAME, "some page name that need to be build"); - request.setRequest(requestObj); - try { - // this method will either throw projectCommonException or it return void - RequestValidator.validateCreatePage(request); - requestObj.put("ext", "success"); - } catch (ProjectCommonException e) { - Assert.assertNull(e); - } - assertEquals("success", (String) requestObj.get("ext")); - } - - @Test - public void testValidateCreatePageFailureWithoutPageName() { - Request request = new Request(); - Map requestObj = new HashMap<>(); - request.setRequest(requestObj); - try { - // this method will either throw projectCommonException or it return void - RequestValidator.validateCreatePage(request); - requestObj.put("ext", "success"); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.pageNameRequired.getErrorCode(), e.getCode()); - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - } - assertEquals(null, (String) requestObj.get("ext")); - } - - @Test - public void testValidateUpdatePageSuccess() { - Request request = new Request(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.PAGE_NAME, "some page name that need to be build"); - requestObj.put(JsonKey.ID, "identifier of the page"); - request.setRequest(requestObj); - try { - // this method will either throw projectCommonException or it return void - RequestValidator.validateUpdatepage(request); - requestObj.put("ext", "success"); - } catch (ProjectCommonException e) { - Assert.assertNull(e); - } - assertEquals("success", requestObj.get("ext")); - } - - @Test - public void testValidateUpdatePageFailureWithoutPageName() { - boolean reqSuccess = false; - Request request = new Request(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.ID, "identifier of the page"); - requestObj.put(JsonKey.PAGE_NAME, null); - request.setRequest(requestObj); - try { - // this method will either throw projectCommonException or it return void - RequestValidator.validateUpdatepage(request); - reqSuccess = false; - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.pageNameRequired.getErrorCode(), e.getCode()); - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - } - assertEquals(false, reqSuccess); - } - - @Test - public void testValidateUpdatePageFailureWithoutId() { - Request request = new Request(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.PAGE_NAME, "some page name that need to be build"); - request.setRequest(requestObj); - try { - // this method will either throw projectCommonException or it return void - RequestValidator.validateUpdatepage(request); - requestObj.put("ext", "success"); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.pageIdRequired.getErrorCode(), e.getCode()); - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - } - assertEquals(null, (String) requestObj.get("ext")); - } -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/common/request/RequestTest.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/common/request/RequestTest.java deleted file mode 100644 index db29d28dc..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/common/request/RequestTest.java +++ /dev/null @@ -1,37 +0,0 @@ -/** */ -package org.sunbird.common.request; - -import java.util.HashMap; -import org.junit.Assert; -import org.junit.Test; - -/** @author Manzarul */ -public class RequestTest { - - @Test - public void testRequestBeanWithDefaultConstructor() { - Request request = new Request(); - request.setEnv(1); - long val = System.currentTimeMillis(); - request.setId(val + ""); - request.setManagerName("name"); - request.setOperation("operation name"); - request.setRequestId("unique req id"); - request.setTs(val + ""); - request.setVer("v1"); - request.setContext(new HashMap<>()); - request.setRequest(new HashMap<>()); - request.setParams(new RequestParams()); - Assert.assertEquals(request.getEnv(), 1); - Assert.assertEquals(request.getId(), val + ""); - Assert.assertEquals(request.getManagerName(), "name"); - Assert.assertEquals(request.getOperation(), "operation name"); - Assert.assertEquals(request.getRequestId(), "unique req id"); - Assert.assertEquals(request.getTs(), val + ""); - Assert.assertEquals(request.getVer(), "v1"); - Assert.assertEquals(request.getContext().size(), 0); - Assert.assertEquals(request.getRequest().size(), 0); - Assert.assertNotNull(request.getParams()); - Assert.assertNotNull(request.toString()); - } -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/common/request/RequestValidatorTest.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/common/request/RequestValidatorTest.java deleted file mode 100644 index d3551e1be..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/common/request/RequestValidatorTest.java +++ /dev/null @@ -1,553 +0,0 @@ -/** */ -package org.sunbird.common.request; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import org.junit.Assert; -import org.junit.Test; -import org.sunbird.common.exception.ProjectCommonException; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.models.util.ProjectUtil; -import org.sunbird.common.responsecode.ResponseCode; - -/** @author Manzarul */ -public class RequestValidatorTest { - - @Test - public void testValidateUpdateContentSuccess() { - Request request = new Request(); - boolean response = false; - List> listOfMap = new ArrayList<>(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.CONTENT_ID, "do_1233343"); - requestObj.put(JsonKey.STATUS, "Completed"); - listOfMap.add(requestObj); - Map innerMap = new HashMap<>(); - innerMap.put(JsonKey.CONTENTS, listOfMap); - request.setRequest(innerMap); - try { - RequestValidator.validateUpdateContent(request); - response = true; - } catch (ProjectCommonException e) { - Assert.assertNull(e); - } - assertEquals(true, response); - } - - @Test - public void testValdateUpdateContentFailureWithNullContentId() { - Request request = new Request(); - boolean response = false; - List> listOfMap = new ArrayList<>(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.CONTENT_ID, null); - requestObj.put(JsonKey.STATUS, "Completed"); - listOfMap.add(requestObj); - Map innerMap = new HashMap<>(); - innerMap.put(JsonKey.CONTENTS, listOfMap); - request.setRequest(innerMap); - try { - RequestValidator.validateUpdateContent(request); - response = true; - } catch (ProjectCommonException e) { - Assert.assertNotNull(e); - } - assertEquals(false, response); - } - - @Test - public void testValidteUpdateContentFailureWithoutContentId() { - Request request = new Request(); - List> listOfMap = new ArrayList<>(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.STATUS, "Completed"); - listOfMap.add(requestObj); - Map innerMap = new HashMap<>(); - innerMap.put(JsonKey.CONTENTS, listOfMap); - request.setRequest(innerMap); - try { - RequestValidator.validateUpdateContent(request); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.contentIdRequiredError.getErrorCode(), e.getCode()); - } - } - - @Test - public void testValidteUpdateContentFailureWithoutStatus() { - Request request = new Request(); - List> listOfMap = new ArrayList<>(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.CONTENT_ID, "do_1233343"); - listOfMap.add(requestObj); - Map innerMap = new HashMap<>(); - innerMap.put(JsonKey.CONTENTS, listOfMap); - request.setRequest(innerMap); - try { - RequestValidator.validateUpdateContent(request); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.contentStatusRequired.getErrorCode(), e.getCode()); - } - } - - @Test - public void testValidteUpdateContentFailureWithEmptyContents() { - Request request = new Request(); - List> listOfMap = new ArrayList<>(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.CONTENT_ID, "do_1233343"); - Map innerMap = new HashMap<>(); - innerMap.put(JsonKey.CONTENTS, listOfMap); - request.setRequest(innerMap); - try { - RequestValidator.validateUpdateContent(request); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.contentIdRequiredError.getErrorCode(), e.getCode()); - } - } - - @Test - public void testValidateRegisterClientFailureWithEmptyClientName() { - Request request = new Request(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.CLIENT_NAME, ""); - request.setRequest(requestObj); - try { - RequestValidator.validateRegisterClient(request); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.invalidClientName.getErrorCode(), e.getCode()); - } - } - - @Test - public void testValidateRegisterClientSuccess() { - Request request = new Request(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.CLIENT_NAME, "1234"); - request.setRequest(requestObj); - try { - RequestValidator.validateRegisterClient(request); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.invalidClientName.getErrorCode(), e.getCode()); - } - } - - @Test - public void testValidateUpdateClientKeyFailureWithEmptyToken() { - try { - RequestValidator.validateUpdateClientKey("1234", ""); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.invalidRequestData.getErrorCode(), e.getCode()); - } - } - - @Test - public void testValidateUpdateClientKeySuccess() { - try { - RequestValidator.validateUpdateClientKey("1234", "test123"); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.invalidRequestData.getErrorCode(), e.getCode()); - } - } - - @Test - public void testValidateClientIdFailureWithEmptyId() { - try { - RequestValidator.validateClientId(""); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.invalidClientId.getErrorCode(), e.getCode()); - } - } - - @Test - public void testValidateFileUploadFailureWithoutContainerName() { - Request request = new Request(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.CONTAINER, ""); - request.setRequest(requestObj); - try { - RequestValidator.validateFileUpload(request); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.storageContainerNameMandatory.getErrorCode(), e.getCode()); - } - } - - @Test - public void testValidateSendEmailSuccess() { - boolean response = false; - Request request = new Request(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.SUBJECT, "test123"); - requestObj.put(JsonKey.BODY, "test"); - List data = new ArrayList<>(); - data.add("test123@gmail.com"); - requestObj.put(JsonKey.RECIPIENT_EMAILS, data); - requestObj.put(JsonKey.RECIPIENT_USERIDS, new ArrayList<>()); - request.setRequest(requestObj); - try { - RequestValidator.validateSendMail(request); - response = true; - } catch (ProjectCommonException e) { - - } - assertTrue(response); - } - - @Test - public void testValidateSendMailFailureWithNullRecipients() { - Request request = new Request(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.SUBJECT, "test123"); - requestObj.put(JsonKey.BODY, "test"); - requestObj.put(JsonKey.RECIPIENT_EMAILS, null); - request.setRequest(requestObj); - try { - RequestValidator.validateSendMail(request); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.mandatoryParamsMissing.getErrorCode(), e.getCode()); - } - } - - @Test - public void testValidateSendMailFailureWithEmptyBody() { - Request request = new Request(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.SUBJECT, "test123"); - requestObj.put(JsonKey.BODY, ""); - request.setRequest(requestObj); - try { - RequestValidator.validateSendMail(request); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.emailBodyError.getErrorCode(), e.getCode()); - } - } - - @Test - public void testValidateSendMailFailureWithEmptySubject() { - Request request = new Request(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.SUBJECT, ""); - request.setRequest(requestObj); - try { - RequestValidator.validateSendMail(request); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.emailSubjectError.getErrorCode(), e.getCode()); - } - } - - @Test - public void testValidateEnrolmentTypeFailureWithEmptyType() { - try { - RequestValidator.validateEnrolmentType(""); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.enrolmentTypeRequired.getErrorCode(), e.getCode()); - } - } - - @Test - public void testValidateEnrolmentTypeFailureWithWrongType() { - try { - RequestValidator.validateEnrolmentType("test"); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.enrolmentIncorrectValue.getErrorCode(), e.getCode()); - } - } - - @Test - public void testValidateEnrolmentTypeSuccessWithOpenType() { - boolean response = false; - try { - RequestValidator.validateEnrolmentType(ProjectUtil.EnrolmentType.open.getVal()); - response = true; - } catch (ProjectCommonException e) { - Assert.assertNull(e); - } - Assert.assertTrue(response); - } - - @Test - public void testValidateEnrolmentTypeSuccessWithInviteType() { - boolean response = false; - try { - RequestValidator.validateEnrolmentType(ProjectUtil.EnrolmentType.inviteOnly.getVal()); - response = true; - } catch (ProjectCommonException e) { - Assert.assertNull(e); - } - Assert.assertTrue(response); - } - - @Test - public void testValidateSyncRequestSuccess() { - Request request = new Request(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.OPERATION_FOR, "keycloak"); - requestObj.put(JsonKey.OBJECT_TYPE, JsonKey.USER); - request.setRequest(requestObj); - boolean response = false; - try { - RequestValidator.validateSyncRequest(request); - response = true; - } catch (ProjectCommonException e) { - Assert.assertNull(e); - } - Assert.assertTrue(response); - } - - @Test - public void testValidateSyncRequestFailureWithNullObjectType() { - Request request = new Request(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.OPERATION_FOR, "not keycloack"); - requestObj.put(JsonKey.OBJECT_TYPE, null); - request.setRequest(requestObj); - boolean response = false; - try { - RequestValidator.validateSyncRequest(request); - response = true; - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.dataTypeError.getErrorCode(), e.getCode()); - } - Assert.assertFalse(response); - } - - @Test - public void testValidateSyncRequestFailureWithInvalidObjectType() { - Request request = new Request(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.OPERATION_FOR, "not keycloack"); - List objectLsit = new ArrayList<>(); - objectLsit.add("testval"); - requestObj.put(JsonKey.OBJECT_TYPE, objectLsit); - request.setRequest(requestObj); - boolean response = false; - try { - RequestValidator.validateSyncRequest(request); - response = true; - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.invalidObjectType.getErrorCode(), e.getCode()); - } - Assert.assertFalse(response); - } - - @Test - public void testValidateUserOrgTypeSuccess() { - Request request = new Request(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.NAME, "orgtypeName"); - requestObj.put(JsonKey.ID, "orgtypeId"); - request.setRequest(requestObj); - boolean response = false; - try { - RequestValidator.validateUpdateOrgType(request); - response = true; - } catch (ProjectCommonException e) { - Assert.assertNull(e); - } - Assert.assertTrue(response); - } - - @Test - public void testValidateUserOrgTypeFailureWithEmptyName() { - Request request = new Request(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.NAME, ""); - requestObj.put(JsonKey.ID, "orgtypeId"); - request.setRequest(requestObj); - boolean response = false; - try { - RequestValidator.validateUpdateOrgType(request); - response = true; - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.orgTypeMandatory.getErrorCode(), e.getCode()); - } - Assert.assertFalse(response); - } - - @Test - public void testValidateUserOrgTypeFailureWithEmptyId() { - Request request = new Request(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.NAME, "orgTypeName"); - requestObj.put(JsonKey.ID, ""); - request.setRequest(requestObj); - boolean response = false; - try { - RequestValidator.validateUpdateOrgType(request); - response = true; - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.orgTypeIdRequired.getErrorCode(), e.getCode()); - } - Assert.assertFalse(response); - } - - @Test - public void testValidateCreateOrgTypeSuccess() { - Request request = new Request(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.NAME, "OrgTypeName"); - request.setRequest(requestObj); - boolean response = false; - try { - RequestValidator.validateCreateOrgType(request); - response = true; - } catch (ProjectCommonException e) { - Assert.assertNull(e); - } - Assert.assertTrue(response); - } - - @Test - public void testValidateCreateOrgTypeFailureWithNullName() { - Request request = new Request(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.NAME, null); - request.setRequest(requestObj); - boolean response = false; - try { - RequestValidator.validateCreateOrgType(request); - response = true; - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.orgTypeMandatory.getErrorCode(), e.getCode()); - } - Assert.assertFalse(response); - } - - @Test - public void testValidateGetClientKeySuccess() { - boolean response = false; - try { - RequestValidator.validateGetClientKey("clientId", "clientType"); - response = true; - } catch (ProjectCommonException e) { - Assert.assertNull(e); - } - Assert.assertTrue(response); - } - - @Test - public void testValidateGetClientKeyFailureWithEmptyClientId() { - boolean response = false; - try { - RequestValidator.validateGetClientKey("", "clientType"); - response = true; - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.invalidClientId.getErrorCode(), e.getCode()); - } - Assert.assertFalse(response); - } - - @Test - public void testValidateGetClientKeyFailureWithEmptyClientType() { - boolean response = false; - try { - RequestValidator.validateGetClientKey("clientId", ""); - response = true; - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.invalidRequestData.getErrorCode(), e.getCode()); - } - Assert.assertFalse(response); - } - - @Test - public void testValidateGroupActivityAggregatesRequestSuccess() { - Request request = new Request(); - boolean response = false; - - request.setRequest(new HashMap(){{ - put(JsonKey.GROUPID, "mockGroupId"); - put(JsonKey.ACTIVITYID, "mockActivityId"); - put(JsonKey.ACTIVITYTYPE, "Course"); - }}); - - try { - RequestValidator.validateGroupActivityAggregatesRequest(request); - response = true; - } catch (ProjectCommonException e) { - Assert.assertNull(e); - } - assertEquals(true, response); - - request.setRequest(new HashMap(){{ - put(JsonKey.ACTIVITYID, "mockActivityId"); - put(JsonKey.ACTIVITYTYPE, "Course"); - }}); - - try { - RequestValidator.validateGroupActivityAggregatesRequest(request); - response = true; - } catch (ProjectCommonException e) { - Assert.assertNotNull(e); - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - response = false; - } - assertEquals(false, response); - - request.setRequest(new HashMap(){{ - put(JsonKey.GROUPID, "mockGroupId"); - put(JsonKey.ACTIVITYTYPE, "Course"); - }}); - - try { - RequestValidator.validateGroupActivityAggregatesRequest(request); - response = true; - } catch (ProjectCommonException e) { - Assert.assertNotNull(e); - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - response = false; - } - assertEquals(false, response); - - request.setRequest(new HashMap(){{ - put(JsonKey.GROUPID, "mockGroupId"); - put(JsonKey.ACTIVITYID, "mockActivityId"); - }}); - - try { - RequestValidator.validateGroupActivityAggregatesRequest(request); - response = true; - } catch (ProjectCommonException e) { - Assert.assertNotNull(e); - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - response = false; - } - assertEquals(false, response); - - request.setRequest(null); - - try { - RequestValidator.validateGroupActivityAggregatesRequest(request); - response = true; - } catch (ProjectCommonException e) { - Assert.assertNotNull(e); - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - response = false; - } - assertEquals(false, response); - } -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/common/request/UserProfileRequestValidatorTest.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/common/request/UserProfileRequestValidatorTest.java deleted file mode 100644 index 19cc0ff2b..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/common/request/UserProfileRequestValidatorTest.java +++ /dev/null @@ -1,76 +0,0 @@ -package org.sunbird.common.request; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import org.junit.Assert; -import org.junit.Test; -import org.sunbird.common.exception.ProjectCommonException; -import org.sunbird.common.models.util.JsonKey; - -public class UserProfileRequestValidatorTest { - - private static final UserProfileRequestValidator userProfileRequestValidator = - new UserProfileRequestValidator(); - - @Test - public void testValidateProfileVisibilityFailureWithFieldInPrivateAndPublic() { - Request request = new Request(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.USER_ID, "9878888888"); - List publicList = new ArrayList<>(); - publicList.add("Education"); - requestObj.put(JsonKey.PUBLIC, publicList); - List privateList = new ArrayList<>(); - privateList.add("Education"); - requestObj.put(JsonKey.PRIVATE, privateList); - request.setRequest(requestObj); - try { - userProfileRequestValidator.validateProfileVisibility(request); - } catch (ProjectCommonException e) { - Assert.assertNotNull(e); - } - } - - @Test - public void testValidateProfileVisibilityFailureWithEmptyUserId() { - Request request = new Request(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.USER_ID, ""); - request.setRequest(requestObj); - try { - userProfileRequestValidator.validateProfileVisibility(request); - } catch (ProjectCommonException e) { - Assert.assertNotNull(e); - } - } - - @Test - public void testValidateProfileVisibilityFailureWithInvalidPrivateType() { - Request request = new Request(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.USER_ID, "123"); - requestObj.put(JsonKey.PRIVATE, ""); - request.setRequest(requestObj); - try { - userProfileRequestValidator.validateProfileVisibility(request); - } catch (ProjectCommonException e) { - Assert.assertNotNull(e); - } - } - - @Test - public void testValidateProfileVisibilityFailureWithInvalidPublicType() { - Request request = new Request(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.USER_ID, "123"); - requestObj.put(JsonKey.PUBLIC, ""); - request.setRequest(requestObj); - try { - userProfileRequestValidator.validateProfileVisibility(request); - } catch (ProjectCommonException e) { - Assert.assertNotNull(e); - } - } -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/common/request/UserRequestValidatorTest.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/common/request/UserRequestValidatorTest.java deleted file mode 100644 index 94ba838d3..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/common/request/UserRequestValidatorTest.java +++ /dev/null @@ -1,1442 +0,0 @@ -/** */ -package org.sunbird.common.request; - -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; -import org.sunbird.common.exception.ProjectCommonException; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.responsecode.ResponseCode; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import static org.junit.Assert.assertEquals; - -public class UserRequestValidatorTest { - - private static final UserRequestValidator userRequestValidator = new UserRequestValidator(); - - @Test - public void testValidatePasswordFailure() { - Request request = initailizeRequest(); - Map requestObj = request.getRequest(); - requestObj.put(JsonKey.PASSWORD, "password"); - request.setRequest(requestObj); - try { - userRequestValidator.validateCreateUserRequest(request); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.passwordValidation.getErrorCode(), e.getCode()); - } - } - - @Test - public void testIsGoodPassword() { - HashMap passwordExpectations = new HashMap(){ - { - // Bad ones. - put("Test 1234", false); // space is not a valid char - put("hello1234", false); // no uppercase - put("helloABCD", false); // no numeral - put("hello#$%&'", false); // no uppercase/numeral - put("sho!1", false); // too short, not 8 char - put("B1!\"#$%&'()*+,-./:;<=>?@[]^_`{|}~", false); // no lowercase - put("Test @1234", false); // contains space - - // Good ones. - put("Test123!", true); // good - put("ALongPassword@123", true); // more than 8 char - put("Abc1!\"#$%&'()*+,-./:;<=>?@[]^_`{|}~", true); // with all spl char, PASS - } - }; - - passwordExpectations.forEach((pwd, expectedResult) -> { - assertEquals(expectedResult, UserRequestValidator.isGoodPassword(pwd)); - }); - } - - @Test - public void testValidateCreateUserBasicValidationFailure() { - Request request = initailizeRequest(); - Map requestObj = request.getRequest(); - requestObj.put(JsonKey.ROLES, "admin"); - request.setRequest(requestObj); - try { - userRequestValidator.createUserBasicValidation(request); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.dataTypeError.getErrorCode(), e.getCode()); - } - } - - @Test - public void testValidateFieldsNotAllowedFailure() { - Request request = initailizeRequest(); - Map requestObj = request.getRequest(); - requestObj.put(JsonKey.PROVIDER, "AP"); - request.setRequest(requestObj); - try { - userRequestValidator.fieldsNotAllowed( - Arrays.asList( - JsonKey.REGISTERED_ORG_ID, - JsonKey.ROOT_ORG_ID, - JsonKey.PROVIDER, - JsonKey.EXTERNAL_ID, - JsonKey.EXTERNAL_ID_PROVIDER, - JsonKey.EXTERNAL_ID_TYPE, - JsonKey.ID_TYPE), - request); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.invalidRequestParameter.getErrorCode(), e.getCode()); - } - } - - @Test - public void testValidateValidateCreateUserV3RequestSuccess() { - boolean response = false; - Request request = initailizeRequest(); - Map requestObj = request.getRequest(); - requestObj.put(JsonKey.PASSWORD, "Password@1"); - request.setRequest(requestObj); - try { - userRequestValidator.validateCreateUserV3Request(request); - response = true; - } catch (ProjectCommonException e) { - Assert.assertNull(e); - } - assertEquals(true, response); - } - - @Test - public void testValidatePasswordSuccess() { - boolean response = false; - Request request = initailizeRequest(); - Map requestObj = request.getRequest(); - requestObj.put(JsonKey.PASSWORD, "Password@1"); - request.setRequest(requestObj); - try { - userRequestValidator.validateCreateUserRequest(request); - response = true; - } catch (ProjectCommonException e) { - Assert.assertNull(e); - } - assertEquals(true, response); - } - - @Test - public void testValidateUserCreateV3Success() { - boolean response = false; - Request request = initailizeRequest(); - Map requestObj = request.getRequest(); - requestObj.put(JsonKey.PASSWORD, "Password@1"); - request.setRequest(requestObj); - try { - userRequestValidator.validateUserCreateV3(request); - response = true; - } catch (ProjectCommonException e) { - Assert.assertNull(e); - } - assertEquals(true, response); - } - - @Test - public void testValidateUserCreateV3Failure() { - Request request = initailizeRequest(); - Map requestObj = request.getRequest(); - requestObj.put(JsonKey.FIRST_NAME, ""); - request.setRequest(requestObj); - try { - userRequestValidator.validateUserCreateV3(request); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.mandatoryParamsMissing.getErrorCode(), e.getCode()); - } - } - - @Test - public void testValidateUserNameFailure() { - Request request = initailizeRequest(); - Map requestObj = request.getRequest(); - requestObj.put(JsonKey.USERNAME, ""); - request.setRequest(requestObj); - try { - userRequestValidator.validateCreateUserV1Request(request); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.mandatoryParamsMissing.getErrorCode(), e.getCode()); - } - } - - @Test - public void testValidateLocationCodesSuccess() { - boolean response = false; - Request request = initailizeRequest(); - Map requestObj = request.getRequest(); - List location = new ArrayList<>(); - location.add("KA"); - location.add("AP"); - requestObj.put(JsonKey.LOCATION_CODES, location); - request.setRequest(requestObj); - try { - userRequestValidator.validateCreateUserRequest(request); - response = true; - } catch (ProjectCommonException e) { - Assert.assertNull(e); - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.dataTypeError.getErrorCode(), e.getCode()); - } - assertEquals(true, response); - } - - @Test - public void testValidateLocationCodesFailure() { - Request request = initailizeRequest(); - Map requestObj = request.getRequest(); - - requestObj.put(JsonKey.LOCATION_CODES, "AP"); - request.setRequest(requestObj); - try { - userRequestValidator.validateCreateUserRequest(request); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.dataTypeError.getErrorCode(), e.getCode()); - } - } - - @Test - public void testValidateForgotPasswordSuccess() { - Request request = new Request(); - boolean response = false; - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.USERNAME, "manzarul07"); - request.setRequest(requestObj); - try { - userRequestValidator.validateForgotPassword(request); - response = true; - } catch (ProjectCommonException e) { - Assert.assertNull(e); - } - assertEquals(true, response); - } - - @Test - public void testValidateForgotPasswordFailureWithEmptyName() { - try { - Request request = new Request(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.USERNAME, ""); - request.setRequest(requestObj); - userRequestValidator.validateForgotPassword(request); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.userNameRequired.getErrorCode(), e.getCode()); - } - } - - @Test - public void testValidateForgotPasswordFailureWithoutName() { - try { - Request request = new Request(); - Map requestObj = new HashMap<>(); - request.setRequest(requestObj); - userRequestValidator.validateForgotPassword(request); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.userNameRequired.getErrorCode(), e.getCode()); - } - } - - @Test - public void testValidateChangePasswordSuccess() { - Request request = new Request(); - boolean response = false; - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.NEW_PASSWORD, "password1"); - requestObj.put(JsonKey.PASSWORD, "password"); - request.setRequest(requestObj); - try { - userRequestValidator.validateChangePassword(request); - response = true; - } catch (ProjectCommonException e) { - Assert.assertNull(e); - } - assertEquals(true, response); - } - - @Test - public void testValidateChangePasswordFailureWithEmptyNewPassword() { - Request request = new Request(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.NEW_PASSWORD, ""); - requestObj.put(JsonKey.PASSWORD, "password"); - request.setRequest(requestObj); - try { - userRequestValidator.validateChangePassword(request); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.newPasswordEmpty.getErrorCode(), e.getCode()); - } - } - - @Test - public void testValidateChangePasswordFailureWithoutNewPassword() { - Request request = new Request(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.PASSWORD, "password"); - request.setRequest(requestObj); - try { - userRequestValidator.validateChangePassword(request); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.newPasswordRequired.getErrorCode(), e.getCode()); - } - } - - @Test - public void testValidateChangePasswordFailureWithSameOldPassword() { - Request request = new Request(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.NEW_PASSWORD, "password"); - requestObj.put(JsonKey.PASSWORD, "password"); - request.setRequest(requestObj); - try { - userRequestValidator.validateChangePassword(request); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.samePasswordError.getErrorCode(), e.getCode()); - } - } - - @Test - public void testValidateChangePasswordFailureWithPasswordMissing() { - Request request = new Request(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.NEW_PASSWORD, "password"); - request.setRequest(requestObj); - try { - userRequestValidator.validateChangePassword(request); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.passwordRequired.getErrorCode(), e.getCode()); - } - } - - @Test - public void testCreateUserSuccess() { - boolean response = false; - Request request = initailizeRequest(); - Map requestObj = request.getRequest(); - List roles = new ArrayList(); - roles.add("PUBLIC"); - roles.add("CONTENT-CREATOR"); - requestObj.put(JsonKey.ROLE, roles); - List language = new ArrayList<>(); - language.add("English"); - requestObj.put(JsonKey.LANGUAGE, language); - List> addressList = new ArrayList<>(); - Map map = new HashMap<>(); - map.put(JsonKey.ADDRESS_LINE1, "test"); - map.put(JsonKey.CITY, "Bangalore"); - map.put(JsonKey.COUNTRY, "India"); - map.put(JsonKey.ADD_TYPE, "current"); - addressList.add(map); - requestObj.put(JsonKey.ADDRESS, addressList); - - List> educationList = new ArrayList<>(); - Map map1 = new HashMap<>(); - map1.put(JsonKey.COURSE_NAME, "M.C.A"); - map1.put(JsonKey.DEGREE, "Master"); - map1.put(JsonKey.NAME, "CUSAT"); - educationList.add(map1); - requestObj.put(JsonKey.EDUCATION, educationList); - - List> jobProfileList = new ArrayList<>(); - map1 = new HashMap<>(); - map1.put(JsonKey.JOB_NAME, "SE"); - map1.put(JsonKey.ORGANISATION_NAME, "Tarento"); - jobProfileList.add(map1); - requestObj.put(JsonKey.JOB_PROFILE, jobProfileList); - request.setRequest(requestObj); - try { - userRequestValidator.validateCreateUserRequest(request); - response = true; - } catch (ProjectCommonException e) { - Assert.assertNull(e); - } - assertEquals(true, response); - } - - @Test - public void testValidateCreateUserFailureWithWrongAddType() { - Request request = initailizeRequest(); - Map requestObj = request.getRequest(); - List roles = new ArrayList(); - roles.add("PUBLIC"); - roles.add("CONTENT-CREATOR"); - requestObj.put(JsonKey.ROLE, roles); - List language = new ArrayList<>(); - language.add("English"); - requestObj.put(JsonKey.LANGUAGE, language); - List> addressList = new ArrayList<>(); - Map map = new HashMap<>(); - map.put(JsonKey.ADDRESS_LINE1, "test"); - map.put(JsonKey.CITY, "Bangalore"); - map.put(JsonKey.COUNTRY, "India"); - map.put(JsonKey.ADD_TYPE, "lmlkmkl"); - addressList.add(map); - requestObj.put(JsonKey.ADDRESS, addressList); - - List> educationList = new ArrayList<>(); - Map map1 = new HashMap<>(); - map1.put(JsonKey.COURSE_NAME, "M.C.A"); - map1.put(JsonKey.DEGREE, "Master"); - map1.put(JsonKey.NAME, "CUSAT"); - educationList.add(map1); - requestObj.put(JsonKey.EDUCATION, educationList); - - List> jobProfileList = new ArrayList<>(); - map1 = new HashMap<>(); - map1.put(JsonKey.JOB_NAME, "SE"); - map1.put(JsonKey.ORGANISATION_NAME, "Tarento"); - jobProfileList.add(map1); - requestObj.put(JsonKey.JOB_PROFILE, jobProfileList); - request.setRequest(requestObj); - try { - userRequestValidator.validateCreateUserRequest(request); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.addressTypeError.getErrorCode(), e.getCode()); - } - } - - @Test - public void testValidateCreateUserFailureWithEmptyAddType() { - Request request = initailizeRequest(); - Map requestObj = request.getRequest(); - List roles = new ArrayList(); - roles.add("PUBLIC"); - roles.add("CONTENT-CREATOR"); - requestObj.put(JsonKey.ROLE, roles); - List language = new ArrayList<>(); - language.add("English"); - requestObj.put(JsonKey.LANGUAGE, language); - List> addressList = new ArrayList<>(); - Map map = new HashMap<>(); - map.put(JsonKey.ADDRESS_LINE1, "test"); - map.put(JsonKey.CITY, "Bangalore"); - map.put(JsonKey.COUNTRY, "India"); - map.put(JsonKey.ADD_TYPE, ""); - addressList.add(map); - requestObj.put(JsonKey.ADDRESS, addressList); - - List> educationList = new ArrayList<>(); - Map map1 = new HashMap<>(); - map1.put(JsonKey.COURSE_NAME, "M.C.A"); - map1.put(JsonKey.DEGREE, "Master"); - map1.put(JsonKey.NAME, "CUSAT"); - educationList.add(map1); - requestObj.put(JsonKey.EDUCATION, educationList); - - List> jobProfileList = new ArrayList<>(); - map1 = new HashMap<>(); - map1.put(JsonKey.JOB_NAME, "SE"); - map1.put(JsonKey.ORGANISATION_NAME, "Tarento"); - jobProfileList.add(map1); - requestObj.put(JsonKey.JOB_PROFILE, jobProfileList); - request.setRequest(requestObj); - try { - userRequestValidator.validateCreateUserRequest(request); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.addressError.getErrorCode(), e.getCode()); - } - } - - @Test - public void testPhoneValidationSuccess() { - Request request = new Request(); - boolean response = false; - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.PHONE, "9321234123"); - requestObj.put(JsonKey.COUNTRY_CODE, "+91"); - requestObj.put(JsonKey.PROVIDER, "sunbird"); - requestObj.put(JsonKey.PHONE_VERIFIED, true); - requestObj.put(JsonKey.EMAIL_VERIFIED, true); - request.setRequest(requestObj); - try { - userRequestValidator.phoneValidation(request); - response = true; - } catch (ProjectCommonException e) { - Assert.assertNull(e); - } - assertEquals(true, response); - } - - @Test - public void testPhoneValidationFailureWithInvalidPhone() { - Request request = new Request(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.PHONE, "+9321234123"); - requestObj.put(JsonKey.COUNTRY_CODE, "+91"); - requestObj.put(JsonKey.PROVIDER, "sunbird"); - requestObj.put(JsonKey.PHONE_VERIFIED, true); - requestObj.put(JsonKey.EMAIL_VERIFIED, true); - request.setRequest(requestObj); - try { - userRequestValidator.phoneValidation(request); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.invalidPhoneNumber.getErrorCode(), e.getCode()); - } - } - - @Test - public void testPhoneValidationFailureWithInvalidCountryCode() { - Request request = new Request(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.PHONE, "+9321234123"); - requestObj.put(JsonKey.COUNTRY_CODE, "+91968"); - requestObj.put(JsonKey.PROVIDER, "sunbird"); - requestObj.put(JsonKey.PHONE_VERIFIED, true); - requestObj.put(JsonKey.EMAIL_VERIFIED, true); - request.setRequest(requestObj); - try { - userRequestValidator.phoneValidation(request); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.invalidCountryCode.getErrorCode(), e.getCode()); - } - } - - @Test - public void testPhoneValidationFailureWithEmptyPhoneVerified() { - Request request = new Request(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.PHONE, "9321234123"); - requestObj.put(JsonKey.COUNTRY_CODE, "+91"); - requestObj.put(JsonKey.PROVIDER, "sunbird"); - requestObj.put(JsonKey.PHONE_VERIFIED, ""); - request.setRequest(requestObj); - try { - userRequestValidator.phoneValidation(request); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.phoneVerifiedError.getErrorCode(), e.getCode()); - } - } - - @Test - public void testPhoneValidationFailureWithPhoneVerifiedFalse() { - Request request = new Request(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.PHONE, "9321234123"); - requestObj.put(JsonKey.COUNTRY_CODE, "+91"); - requestObj.put(JsonKey.PROVIDER, "sunbird"); - requestObj.put(JsonKey.PHONE_VERIFIED, false); - request.setRequest(requestObj); - try { - userRequestValidator.phoneValidation(request); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.phoneVerifiedError.getErrorCode(), e.getCode()); - } - } - - @Test - public void testPhoneValidationFailureWithPhoneVerifiedNull() { - Request request = new Request(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.PHONE, "9321234123"); - requestObj.put(JsonKey.COUNTRY_CODE, "+91"); - requestObj.put(JsonKey.PROVIDER, "sunbird"); - requestObj.put(JsonKey.PHONE_VERIFIED, null); - request.setRequest(requestObj); - try { - userRequestValidator.phoneValidation(request); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.phoneVerifiedError.getErrorCode(), e.getCode()); - } - } - - @Test - public void testUpdateUserSuccess() { - Request request = initailizeRequest(); - Map requestObj = request.getRequest(); - requestObj.remove(JsonKey.USERNAME); - requestObj.put(JsonKey.USER_ID, "userId"); - - List roles = new ArrayList(); - roles.add("PUBLIC"); - roles.add("CONTENT-CREATOR"); - requestObj.put(JsonKey.ROLE, roles); - List language = new ArrayList<>(); - language.add("English"); - requestObj.put(JsonKey.LANGUAGE, language); - List> addressList = new ArrayList<>(); - Map map = new HashMap<>(); - map.put(JsonKey.ADDRESS_LINE1, "test"); - map.put(JsonKey.CITY, "Bangalore"); - map.put(JsonKey.COUNTRY, "India"); - map.put(JsonKey.ADD_TYPE, "current"); - addressList.add(map); - requestObj.put(JsonKey.ADDRESS, addressList); - - List> educationList = new ArrayList<>(); - Map map1 = new HashMap<>(); - map1.put(JsonKey.COURSE_NAME, "M.C.A"); - map1.put(JsonKey.DEGREE, "Master"); - map1.put(JsonKey.NAME, "CUSAT"); - educationList.add(map1); - requestObj.put(JsonKey.EDUCATION, educationList); - - List> jobProfileList = new ArrayList<>(); - map1 = new HashMap<>(); - map1.put(JsonKey.JOB_NAME, "SE"); - map1.put(JsonKey.ORGANISATION_NAME, "Tarento"); - jobProfileList.add(map1); - requestObj.put(JsonKey.JOB_PROFILE, jobProfileList); - boolean response = false; - request.setRequest(requestObj); - try { - userRequestValidator.validateUpdateUserRequest(request); - response = true; - } catch (ProjectCommonException e) { - Assert.assertNull(e); - } - assertEquals(true, response); - } - - @Test - public void testValidateUploadUserSuccessWithOrgId() { - boolean response = false; - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.ORGANISATION_ID, "ORG-1233"); - requestObj.put(JsonKey.EXTERNAL_ID_PROVIDER, "EXT_ID_PROVIDER"); - requestObj.put(JsonKey.FILE, "EXT_ID_PROVIDER"); - - try { - RequestValidator.validateUploadUser(requestObj); - response = true; - } catch (ProjectCommonException e) { - Assert.assertNull(e); - } - assertEquals(true, response); - } - - @Test - public void testValidateUploadUserSuccessWithExternalId() { - boolean response = false; - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.PROVIDER, "ORG-provider"); - requestObj.put(JsonKey.EXTERNAL_ID, "ORG-1233"); - requestObj.put(JsonKey.ORGANISATION_ID, "ORG-1233"); - requestObj.put(JsonKey.ORG_PROVIDER, "ORG-Provider"); - requestObj.put(JsonKey.FILE, "ORG-Provider"); - try { - RequestValidator.validateUploadUser(requestObj); - response = true; - } catch (ProjectCommonException e) { - Assert.assertNull(e); - } - assertEquals(true, response); - } - - @Test - public void testValidateAssignRoleSuccess() { - Request request = new Request(); - boolean response = false; - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.USER_ID, "ORG-provider"); - requestObj.put(JsonKey.EXTERNAL_ID, "EXT_ID"); - requestObj.put(JsonKey.ORGANISATION_ID, "ORG_ID"); - requestObj.put(JsonKey.ORG_PROVIDER, "ORG_PROVIDER"); - List roles = new ArrayList<>(); - roles.add("PUBLIC"); - requestObj.put(JsonKey.ROLES, roles); - request.setRequest(requestObj); - try { - userRequestValidator.validateAssignRole(request); - response = true; - } catch (ProjectCommonException e) { - Assert.assertNull(e); - } - assertEquals(true, response); - } - - @Test - public void testValidateAssignRoleSuccessWithProviderAndExternalId() { - Request request = new Request(); - boolean response = false; - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.PROVIDER, "ORG-provider"); - requestObj.put(JsonKey.EXTERNAL_ID, "ORG-1233"); - requestObj.put(JsonKey.USER_ID, "User1"); - List roles = new ArrayList<>(); - roles.add("PUBLIC"); - requestObj.put(JsonKey.ROLES, roles); - request.setRequest(requestObj); - try { - userRequestValidator.validateAssignRole(request); - response = true; - } catch (ProjectCommonException e) { - Assert.assertNull(e); - } - assertEquals(true, response); - } - - @Test - public void testValidateWebPagesFailureWithEmptyWebPages() { - Request request = new Request(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.WEB_PAGES, new ArrayList<>()); - request.setRequest(requestObj); - try { - userRequestValidator.validateWebPages(request); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.invalidWebPageData.getErrorCode(), e.getCode()); - } - } - - @Test - public void testValidateWebPagesFailureWithNullWebPages() { - Request request = new Request(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.WEB_PAGES, null); - request.setRequest(requestObj); - try { - userRequestValidator.validateWebPages(request); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.invalidWebPageData.getErrorCode(), e.getCode()); - } - } - - @Ignore - public void testCreateUserBasicValidationFailureWithEmptyFirstName() { - Request request = new Request(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.FIRST_NAME, ""); - request.setRequest(requestObj); - try { - userRequestValidator.createUserBasicValidation(request); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.firstNameRequired.getErrorCode(), e.getCode()); - } - } - - @Ignore - public void testCreateUserBasicValidationFailureWithInvalidDOB() { - Request request = new Request(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.USERNAME, "test123"); - requestObj.put(JsonKey.FIRST_NAME, "test123"); - requestObj.put(JsonKey.DOB, "20-10-15"); - request.setRequest(requestObj); - try { - userRequestValidator.createUserBasicValidation(request); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.dateFormatError.getErrorCode(), e.getCode()); - } - } - - @Test - public void testCreateUserBasicValidationFailureWithoutEmailAndPhone() { - Request request = new Request(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.USERNAME, "test123"); - requestObj.put(JsonKey.FIRST_NAME, "test123"); - requestObj.put(JsonKey.DOB, "2018-10-15"); - request.setRequest(requestObj); - try { - userRequestValidator.createUserBasicValidation(request); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.emailorPhoneRequired.getErrorCode(), e.getCode()); - } - } - - @Test - public void testCreateUserBasicValidationFailureWithInvalidEmail() { - Request request = new Request(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.USERNAME, "test123"); - requestObj.put(JsonKey.FIRST_NAME, "test123"); - requestObj.put(JsonKey.DOB, "2018-10-15"); - requestObj.put(JsonKey.EMAIL, "asd@as"); - request.setRequest(requestObj); - try { - userRequestValidator.createUserBasicValidation(request); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.emailFormatError.getErrorCode(), e.getCode()); - } - } - - @Ignore - public void testCreateUserBasicValidationFailureWithInvalidRoles() { - Request request = new Request(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.USERNAME, "test123"); - requestObj.put(JsonKey.FIRST_NAME, "test123"); - requestObj.put(JsonKey.ROLES, ""); - request.setRequest(requestObj); - try { - userRequestValidator.createUserBasicValidation(request); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.dataTypeError.getErrorCode(), e.getCode()); - } - } - - @Test - public void testValidateCreateUserRequestFailureWithInvalidLanguage() { - Request request = new Request(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.PHONE, "9321234123"); - requestObj.put(JsonKey.EMAIL, "test123@test.com"); - requestObj.put(JsonKey.EMAIL_VERIFIED, true); - requestObj.put(JsonKey.USERNAME, "test123"); - requestObj.put(JsonKey.FIRST_NAME, "test123"); - requestObj.put(JsonKey.LANGUAGE, ""); - request.setRequest(requestObj); - try { - userRequestValidator.validateCreateUserRequest(request); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.dataTypeError.getErrorCode(), e.getCode()); - } - } - - @Test - public void testValidateCreateUserRequestFailureWithInvalidAddress() { - Request request = new Request(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.PHONE, "9321234123"); - requestObj.put(JsonKey.PHONE_VERIFIED, true); - requestObj.put(JsonKey.EMAIL, "test123@test.com"); - requestObj.put(JsonKey.EMAIL_VERIFIED, true); - requestObj.put(JsonKey.USERNAME, "test123"); - requestObj.put(JsonKey.FIRST_NAME, "test123"); - requestObj.put(JsonKey.ADDRESS, ""); - request.setRequest(requestObj); - try { - userRequestValidator.validateCreateUserRequest(request); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.dataTypeError.getErrorCode(), e.getCode()); - } - } - - @Test - public void testValidaeCreateUserRequestFailureWithInvalidEducation() { - Request request = new Request(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.PHONE, "9321234123"); - requestObj.put(JsonKey.PHONE_VERIFIED, true); - requestObj.put(JsonKey.EMAIL, "test123@test.com"); - requestObj.put(JsonKey.EMAIL_VERIFIED, true); - requestObj.put(JsonKey.USERNAME, "test123"); - requestObj.put(JsonKey.FIRST_NAME, "test123"); - requestObj.put(JsonKey.EDUCATION, ""); - request.setRequest(requestObj); - try { - userRequestValidator.validateCreateUserRequest(request); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.dataTypeError.getErrorCode(), e.getCode()); - } - } - - @Test - public void testValidateCreateUserRequestFailureWithInvalidAddressType() { - Request request = new Request(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.PHONE, "9321234123"); - requestObj.put(JsonKey.PHONE_VERIFIED, true); - requestObj.put(JsonKey.EMAIL, "test123@test.com"); - requestObj.put(JsonKey.EMAIL_VERIFIED, true); - requestObj.put(JsonKey.USERNAME, "test123"); - requestObj.put(JsonKey.FIRST_NAME, "test123"); - List> addressList = new ArrayList<>(); - Map map = new HashMap<>(); - map.put(JsonKey.ADDRESS_LINE1, "test"); - map.put(JsonKey.CITY, "Bangalore"); - map.put(JsonKey.COUNTRY, "India"); - map.put(JsonKey.ADD_TYPE, "localr"); - addressList.add(map); - requestObj.put(JsonKey.ADDRESS, addressList); - request.setRequest(requestObj); - try { - userRequestValidator.validateCreateUserRequest(request); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.addressTypeError.getErrorCode(), e.getCode()); - } - } - - @Test - public void testValidateCreateUserRequestFailureWithInvalidCountryCode() { - Request request = new Request(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.PHONE, "9321234123"); - requestObj.put(JsonKey.PHONE_VERIFIED, true); - requestObj.put(JsonKey.EMAIL, "test123@test.com"); - requestObj.put(JsonKey.EMAIL_VERIFIED, true); - requestObj.put(JsonKey.USERNAME, "test123"); - requestObj.put(JsonKey.FIRST_NAME, "test123"); - request.setRequest(requestObj); - request.getRequest().put(JsonKey.COUNTRY_CODE, "+as"); - - try { - userRequestValidator.validateCreateUserRequest(request); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.invalidCountryCode.getErrorCode(), e.getCode()); - } - } - - @Test - public void testValidateCreateUserRequestFailureWithEmptyEmailAndPhone() { - Request request = new Request(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.USERNAME, "test123"); - requestObj.put(JsonKey.PHONE, "9321234123"); - requestObj.put(JsonKey.PHONE_VERIFIED, true); - requestObj.put(JsonKey.FIRST_NAME, "test123"); - requestObj.put(JsonKey.EMAIL, ""); - requestObj.put(JsonKey.PHONE, ""); - request.setRequest(requestObj); - - try { - userRequestValidator.validateCreateUserRequest(request); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.emailorPhoneRequired.getErrorCode(), e.getCode()); - } - } - - @Test - public void testValidateCreateUserFailureWithInvalidEmail() { - Request request = initailizeRequest(); - request.getRequest().put(JsonKey.EMAIL, "am@ds@cmo"); - - try { - userRequestValidator.validateCreateUserRequest(request); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.emailFormatError.getErrorCode(), e.getCode()); - } - } - - @Test - public void testValidateCreateUserFailureWithoutPhoneVerified() { - Request request = initailizeRequest(); - request.getRequest().put(JsonKey.PHONE, "7894561230"); - - try { - userRequestValidator.validateCreateUserRequest(request); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.phoneVerifiedError.getErrorCode(), e.getCode()); - } - } - - @Test - public void testValidateCreateUserSuccess() { - Request request = initailizeRequest(); - request.getRequest().put(JsonKey.PHONE, "7894561230"); - request.getRequest().put(JsonKey.PHONE_VERIFIED, ""); - try { - userRequestValidator.validateCreateUserRequest(request); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.phoneVerifiedError.getErrorCode(), e.getCode()); - } - } - - @Test - public void testValidateCreateUserFailureWithPhoneVerifiedFalse() { - Request request = initailizeRequest(); - request.getRequest().put(JsonKey.PHONE, "7894561230"); - request.getRequest().put(JsonKey.PHONE_VERIFIED, false); - try { - userRequestValidator.validateCreateUserRequest(request); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.phoneVerifiedError.getErrorCode(), e.getCode()); - } - } - - @Test - public void testValidateCreateUserFailureWithEmptyEducationName() { - Request request = initailizeRequest(); - request.getRequest().put(JsonKey.PHONE_VERIFIED, true); - Map map = new HashMap<>(); - map.put(JsonKey.NAME, ""); - List> list = new ArrayList<>(); - list.add(map); - - request.getRequest().put(JsonKey.EDUCATION, list); - try { - userRequestValidator.validateCreateUserRequest(request); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.educationNameError.getErrorCode(), e.getCode()); - } - } - - @Test - public void testValidateCreateUserFailureWithEmptyEducationDegree() { - Request request = initailizeRequest(); - request.getRequest().put(JsonKey.PHONE_VERIFIED, true); - Map map = new HashMap<>(); - map.put(JsonKey.NAME, "name"); - map.put(JsonKey.DEGREE, ""); - List> list = new ArrayList<>(); - list.add(map); - - request.getRequest().put(JsonKey.EDUCATION, list); - try { - userRequestValidator.validateCreateUserRequest(request); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.educationDegreeError.getErrorCode(), e.getCode()); - } - } - - @Test - public void testValidateCreateUserFailureWithEmptyEducationAddress() { - Request request = initailizeRequest(); - request.getRequest().put(JsonKey.PHONE_VERIFIED, true); - Map map = new HashMap<>(); - map.put(JsonKey.NAME, "name"); - map.put(JsonKey.DEGREE, "degree"); - Map address = new HashMap<>(); - address.put(JsonKey.ADDRESS_LINE1, ""); - map.put(JsonKey.ADDRESS, address); - List> list = new ArrayList<>(); - list.add(map); - request.getRequest().put(JsonKey.EDUCATION, list); - try { - userRequestValidator.validateCreateUserRequest(request); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.addressError.getErrorCode(), e.getCode()); - } - } - - @Test - public void testValidateCreateUserFailureWithEmptyEducationCity() { - Request request = initailizeRequest(); - request.getRequest().put(JsonKey.PHONE_VERIFIED, true); - - Map map = new HashMap<>(); - map.put(JsonKey.NAME, "name"); - map.put(JsonKey.DEGREE, "degree"); - Map address = new HashMap<>(); - address.put(JsonKey.ADDRESS_LINE1, "line1"); - address.put(JsonKey.CITY, ""); - map.put(JsonKey.ADDRESS, address); - List> list = new ArrayList<>(); - list.add(map); - request.getRequest().put(JsonKey.EDUCATION, list); - try { - userRequestValidator.validateCreateUserRequest(request); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.addressError.getErrorCode(), e.getCode()); - } - } - - @Test - public void testValidateCreateUserFailureWithEmptyJobProfile() { - Request request = initailizeRequest(); - request.getRequest().put(JsonKey.PHONE_VERIFIED, true); - request.getRequest().put(JsonKey.JOB_PROFILE, ""); - try { - userRequestValidator.validateCreateUserRequest(request); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.dataTypeError.getErrorCode(), e.getCode()); - } - } - - @Test - public void testValidateCreateUserFailureWithEmptyJobName() { - Request request = initailizeRequest(); - Map map = new HashMap<>(); - map.put(JsonKey.JOB_NAME, ""); - map.put(JsonKey.ORG_NAME, "degree"); - List> list = new ArrayList<>(); - list.add(map); - request.getRequest().put(JsonKey.JOB_PROFILE, list); - try { - userRequestValidator.validateCreateUserRequest(request); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.jobNameError.getErrorCode(), e.getCode()); - } - } - - @Test - public void testValidateCreateUserFailureWithInvalidJobProfileJoiningDate() { - Request request = initailizeRequest(); - Map map = new HashMap<>(); - map.put(JsonKey.JOB_NAME, "kijklo"); - map.put(JsonKey.ORG_NAME, "degree"); - map.put(JsonKey.JOINING_DATE, "20-15-18"); - List> list = new ArrayList<>(); - list.add(map); - request.getRequest().put(JsonKey.JOB_PROFILE, list); - try { - userRequestValidator.validateCreateUserRequest(request); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.dateFormatError.getErrorCode(), e.getCode()); - } - } - - @Test - public void testValidateCreateUserFailureWithInvalidJobProfileEndDate() { - Request request = initailizeRequest(); - Map map = new HashMap<>(); - map.put(JsonKey.JOB_NAME, "kijklo"); - map.put(JsonKey.ORG_NAME, "degree"); - map.put(JsonKey.END_DATE, "20-15-18"); - List> list = new ArrayList<>(); - list.add(map); - request.getRequest().put(JsonKey.JOB_PROFILE, list); - try { - userRequestValidator.validateCreateUserRequest(request); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.dateFormatError.getErrorCode(), e.getCode()); - } - } - - @Test - public void testValidateCreateUserFailureWithEmptyJobProfileOrgName() { - Request request = initailizeRequest(); - Map map = new HashMap<>(); - map.put(JsonKey.JOB_NAME, "kijklo"); - map.put(JsonKey.ORG_NAME, ""); - List> list = new ArrayList<>(); - list.add(map); - request.getRequest().put(JsonKey.JOB_PROFILE, list); - try { - userRequestValidator.validateCreateUserRequest(request); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.organisationNameError.getErrorCode(), e.getCode()); - } - } - - @Test - public void testValidateCreateUserFailureWithEmptyJobProfileCity() { - Request request = initailizeRequest(); - Map map = new HashMap<>(); - map.put(JsonKey.JOB_NAME, "jabName"); - map.put(JsonKey.ORG_NAME, "orgName"); - Map address = new HashMap<>(); - address.put(JsonKey.ADDRESS_LINE1, "line1"); - address.put(JsonKey.CITY, ""); - map.put(JsonKey.ADDRESS, address); - List> list = new ArrayList<>(); - list.add(map); - request.getRequest().put(JsonKey.JOB_PROFILE, list); - try { - userRequestValidator.validateCreateUserRequest(request); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.addressError.getErrorCode(), e.getCode()); - } - } - - @Test - public void testValidateCreateUserFailureWithInvalidPhoneFormat() { - Request request = new Request(); - request.getRequest().put(JsonKey.EMAIL, "asd@asd.com"); - request.getRequest().put(JsonKey.EMAIL_VERIFIED, true); - request.getRequest().put(JsonKey.PHONE, "9874561230"); - request.getRequest().put(JsonKey.COUNTRY_CODE, "+001"); - request.getRequest().put(JsonKey.USERNAME, "98745"); - request.getRequest().put(JsonKey.FIRST_NAME, "98745"); - try { - userRequestValidator.validateCreateUserRequest(request); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.phoneNoFormatError.getErrorCode(), e.getCode()); - } - } - - @Test - public void testValidateGerUserCountFailureWithInvalidLocationIds() { - Request request = new Request(); - request.getRequest().put(JsonKey.LOCATION_IDS, ""); - - try { - RequestValidator.validateGetUserCount(request); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.dataTypeError.getErrorCode(), e.getCode()); - } - } - - @Test - public void testValidateGerUserCountFailureWithEmptyLocationIds() { - Request request = new Request(); - List list = new ArrayList<>(); - list.add(""); - request.getRequest().put(JsonKey.LOCATION_IDS, list); - - try { - RequestValidator.validateGetUserCount(request); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.locationIdRequired.getErrorCode(), e.getCode()); - } - } - - @Test - public void testValidateGerUserCountFailureWithInvalidUserLstReq() { - Request request = new Request(); - List list = new ArrayList<>(); - list.add("4645"); - request.getRequest().put(JsonKey.LOCATION_IDS, list); - request.getRequest().put(JsonKey.USER_LIST_REQ, null); - - try { - RequestValidator.validateGetUserCount(request); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.dataTypeError.getErrorCode(), e.getCode()); - } - } - - @Test - public void testValidateGerUserCountFailureWithUserLstReqTrue() { - Request request = new Request(); - List list = new ArrayList<>(); - list.add("4645"); - request.getRequest().put(JsonKey.LOCATION_IDS, list); - request.getRequest().put(JsonKey.USER_LIST_REQ, true); - - try { - RequestValidator.validateGetUserCount(request); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.functionalityMissing.getErrorCode(), e.getCode()); - } - } - - @Test - public void testValidateGerUserCountFailureWithEmptyEstCntReq() { - Request request = new Request(); - List list = new ArrayList<>(); - list.add("4645"); - request.getRequest().put(JsonKey.LOCATION_IDS, list); - request.getRequest().put(JsonKey.ESTIMATED_COUNT_REQ, ""); - - try { - RequestValidator.validateGetUserCount(request); - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.dataTypeError.getErrorCode(), e.getCode()); - } - } - - @Test - public void testValidateVerifyUserSuccess() { - Request request = new Request(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.LOGIN_ID, "username@provider"); - request.setRequest(requestObj); - boolean response = false; - try { - new UserRequestValidator().validateVerifyUser(request); - response = true; - } catch (ProjectCommonException e) { - Assert.assertNull(e); - } - Assert.assertTrue(response); - } - - @Test - public void testValidateGerUserCountFailureWithEstCntReqTrue() { - Request request = new Request(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.LOGIN_ID, ""); - request.setRequest(requestObj); - boolean response = false; - try { - new UserRequestValidator().validateVerifyUser(request); - response = true; - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.loginIdRequired.getErrorCode(), e.getCode()); - } - Assert.assertFalse(response); - } - - @Test - public void validateUserCreateV3Sussess() { - boolean response = true; - try { - Request request = new Request(); - request.getRequest().put(JsonKey.FIRST_NAME, "test name"); - request.getRequest().put(JsonKey.EMAIL, "test@test.com"); - request.getRequest().put(JsonKey.EMAIL_VERIFIED, true); - request.getRequest().put(JsonKey.PHONE, "9663890445"); - request.getRequest().put(JsonKey.PHONE_VERIFIED, true); - new UserRequestValidator().validateUserCreateV3(request); - } catch (Exception e) { - response = false; - } - Assert.assertTrue(response); - } - - private Request initailizeRequest() { - Request request = new Request(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.USERNAME, "test123"); - requestObj.put(JsonKey.PHONE, "9321234123"); - requestObj.put(JsonKey.PHONE_VERIFIED, true); - requestObj.put(JsonKey.FIRST_NAME, "test123"); - request.setRequest(requestObj); - return request; - } - - @Test - public void testValidateVerifyUserFailureWithEmptyId() { - Request request = new Request(); - Map requestObj = new HashMap<>(); - requestObj.put(JsonKey.LOGIN_ID, ""); - request.setRequest(requestObj); - boolean response = false; - try { - userRequestValidator.validateVerifyUser(request); - response = true; - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.loginIdRequired.getErrorCode(), e.getCode()); - } - Assert.assertFalse(response); - } - - @Test - public void testValidateMandatoryFrameworkFieldsSuccess() { - Request request = initailizeRequest(); - request.getRequest().put(JsonKey.FRAMEWORK, createFrameWork()); - boolean response = false; - try { - new UserRequestValidator() - .validateMandatoryFrameworkFields( - request.getRequest(), getSupportedFileds(), getMandatoryFields()); - response = true; - } catch (Exception e) { - Assert.assertTrue(response); - } - Assert.assertTrue(response); - } - - @Test - public void testValidateMandatoryFrameworkFieldValueAsString() { - Request request = initailizeRequest(); - Map frameworkMap = createFrameWork(); - frameworkMap.put("medium", "hindi"); - request.getRequest().put(JsonKey.FRAMEWORK, frameworkMap); - boolean response = false; - try { - new UserRequestValidator() - .validateMandatoryFrameworkFields( - request.getRequest(), getSupportedFileds(), getMandatoryFields()); - response = true; - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.dataTypeError.getErrorCode(), e.getCode()); - } - Assert.assertFalse(response); - } - - @Test - public void testValidateFrameworkUnknownField() { - Request request = initailizeRequest(); - Map frameworkMap = createFrameWork(); - frameworkMap.put("school", Arrays.asList("school1")); - request.getRequest().put(JsonKey.FRAMEWORK, frameworkMap); - boolean response = false; - try { - new UserRequestValidator() - .validateMandatoryFrameworkFields( - request.getRequest(), getSupportedFileds(), getMandatoryFields()); - response = true; - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.errorUnsupportedField.getErrorCode(), e.getCode()); - } - Assert.assertFalse(response); - } - - @Test - public void testValidateFrameworkWithEmptyValue() { - Request request = initailizeRequest(); - Map frameworkMap = createFrameWork(); - frameworkMap.put("medium", Arrays.asList()); - request.getRequest().put(JsonKey.FRAMEWORK, frameworkMap); - boolean response = false; - try { - new UserRequestValidator() - .validateMandatoryFrameworkFields( - request.getRequest(), getSupportedFileds(), getMandatoryFields()); - response = true; - } catch (Exception e) { - Assert.assertTrue(response); - } - Assert.assertTrue(response); - } - - @Test - public void testValidateFrameworkWithNullValue() { - Request request = initailizeRequest(); - Map frameworkMap = createFrameWork(); - frameworkMap.put("medium", null); - request.getRequest().put(JsonKey.FRAMEWORK, frameworkMap); - - boolean response = false; - try { - new UserRequestValidator() - .validateMandatoryFrameworkFields( - request.getRequest(), getSupportedFileds(), getMandatoryFields()); - response = true; - } catch (Exception e) { - Assert.assertTrue(response); - } - Assert.assertTrue(response); - } - - private static Map createFrameWork() { - Map frameworkMap = new HashMap(); - frameworkMap.put("gradeLevel", Arrays.asList("Kindergarten")); - frameworkMap.put("subject", Arrays.asList("English")); - frameworkMap.put("id", Arrays.asList("NCF")); - return frameworkMap; - } - - private static List getSupportedFileds() { - List frameworkSupportedFields = new ArrayList(); - frameworkSupportedFields.add("id"); - frameworkSupportedFields.add("gradeLevel"); - frameworkSupportedFields.add("subject"); - frameworkSupportedFields.add("board"); - frameworkSupportedFields.add("medium"); - return frameworkSupportedFields; - } - - private static List getMandatoryFields() { - List frameworkMandatoryFields = new ArrayList(1); - frameworkMandatoryFields.add("id"); - return frameworkMandatoryFields; - } -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/common/responsecode/ResponseCodeTest.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/common/responsecode/ResponseCodeTest.java deleted file mode 100644 index fbe99401e..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/common/responsecode/ResponseCodeTest.java +++ /dev/null @@ -1,53 +0,0 @@ -package org.sunbird.common.responsecode; - -import static org.junit.Assert.assertEquals; - -import org.junit.Assert; -import org.junit.Test; - -public class ResponseCodeTest { - - @Test - public void testGetHeaderResponseCodeClientError() { - ResponseCode respCode = - ResponseCode.getHeaderResponseCode(ResponseCode.CLIENT_ERROR.getResponseCode()); - assertEquals(ResponseCode.CLIENT_ERROR, respCode); - } - - @Test - public void testGetHeaderResponseCodeServerError() { - ResponseCode respCode = ResponseCode.getHeaderResponseCode(0); - assertEquals(ResponseCode.SERVER_ERROR, respCode); - } - - @Test - public void testGetResponse() { - ResponseCode respCode = ResponseCode.getResponse(ResponseCode.invalidData.getErrorCode()); - assertEquals(ResponseCode.invalidData, respCode); - } - - @Test - public void testGetResponseNullCheck() { - ResponseCode respCode = ResponseCode.getResponse(null); - Assert.assertNull(respCode); - } - - @Test - public void testGetResponseMessage() { - String respMsg = ResponseCode.getResponseMessage(ResponseCode.unAuthorized.getErrorCode()); - assertEquals(ResponseCode.unAuthorized.getErrorMessage(), respMsg); - } - - @Test - public void testGetResponseMessageEmpty() { - String respMsg = ResponseCode.getResponseMessage(""); - assertEquals("", respMsg); - } - - @Test - public void testInvalidElementValueSuccess() { - ResponseCode respCode = - ResponseCode.getResponse(ResponseCode.invalidElementInList.getErrorCode()); - assertEquals(ResponseCode.invalidElementInList, respCode); - } -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/common/util/CloudStorageUtilTest.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/common/util/CloudStorageUtilTest.java deleted file mode 100644 index 9376ed311..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/common/util/CloudStorageUtilTest.java +++ /dev/null @@ -1,104 +0,0 @@ -package org.sunbird.common.util; - -import static org.junit.Assert.assertTrue; -import static org.powermock.api.mockito.PowerMockito.mock; -import static org.powermock.api.mockito.PowerMockito.mockStatic; -import static org.powermock.api.mockito.PowerMockito.when; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mockito; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; -import org.sunbird.cloud.storage.BaseStorageService; -import org.sunbird.cloud.storage.factory.StorageServiceFactory; -import org.sunbird.common.models.util.JsonKey; -import scala.Option; - -@RunWith(PowerMockRunner.class) -@PowerMockIgnore({ "javax.management.*", "javax.net.ssl.*", "javax.security.*", "com.microsoft.azure.storage.*", - "jdk.internal.reflect.*", "sun.security.ssl.*", "javax.crypto.*", "com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*"}) -@PrepareForTest({StorageServiceFactory.class, CloudStorageUtil.class}) -public class CloudStorageUtilTest { - - String SIGNED_URL = "singedUrl"; - String UPLOAD_URL = "uploadUrl"; - String PUT_SIGNED_URL = "gcpSignedUrl"; - - @Before - public void initTest() { - BaseStorageService service = mock(BaseStorageService.class); - mockStatic(StorageServiceFactory.class); - - try { - when(StorageServiceFactory.class, "getStorageService", Mockito.any()).thenReturn(service); - - when(service.upload( - Mockito.anyString(), - Mockito.anyString(), - Mockito.anyString(), - Mockito.any(Option.class), - Mockito.any(Option.class), - Mockito.any(Option.class), - Mockito.any(Option.class))) - .thenReturn(UPLOAD_URL); - - when(service.getSignedURL( - Mockito.anyString(), - Mockito.anyString(), - Mockito.any(Option.class), - Mockito.any(Option.class))) - .thenReturn(SIGNED_URL); - when(service.getPutSignedURL( - Mockito.anyString(), - Mockito.anyString(), - Mockito.any(Option.class), - Mockito.any(Option.class), - Mockito.any(Option.class), - Mockito.any(Option.class))) - .thenReturn(PUT_SIGNED_URL); - when(service.getSignedURLV2( - Mockito.eq("azurecontainer"), - Mockito.anyString(), - Mockito.any(Option.class), - Mockito.any(Option.class), - Mockito.any(Option.class), - Mockito.any(Option.class))) - .thenReturn(SIGNED_URL); - when(service.getSignedURLV2( - Mockito.eq("gcpcontainer"), - Mockito.anyString(), - Mockito.any(Option.class), - Mockito.any(Option.class), - Mockito.any(Option.class), - Mockito.any(Option.class))) - .thenReturn(PUT_SIGNED_URL); - - } catch (Exception e) { - Assert.fail(e.getMessage()); - } - } - - @Test - public void testUploadSuccess() { - String result = - CloudStorageUtil.upload("azure", "container", "key", "/file/path"); - assertTrue(UPLOAD_URL.equals(result)); - } - - @Test - public void testGetSignedUrlSuccess() { - String signedUrl = CloudStorageUtil.getSignedUrl("azure", "azurecontainer", "key"); - assertTrue(SIGNED_URL.equals(signedUrl)); - } - - @Test - public void testGetSignedUrlGCPSuccess() { - String signedUrl = CloudStorageUtil.getSignedUrl(JsonKey.GCP, "gcpcontainer", "key"); - assertTrue(PUT_SIGNED_URL.equals(signedUrl)); - } -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/common/util/ConfigUtilTest.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/common/util/ConfigUtilTest.java deleted file mode 100644 index 6a52c735e..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/common/util/ConfigUtilTest.java +++ /dev/null @@ -1,64 +0,0 @@ -package org.sunbird.common.util; - -import com.typesafe.config.Config; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mockito; -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.common.exception.ProjectCommonException; -import org.sunbird.common.responsecode.ResponseCode; - -@PrepareForTest(ConfigUtil.class) -@PowerMockIgnore({"javax.management.*", "javax.net.ssl.*", "javax.security.*"}) -public class ConfigUtilTest { - - String configType = "user"; - String validJson = "{\"key\" : \"value\"}"; - ConfigUtil configUtilMock; - - @Before - public void setup() throws Exception { - configUtilMock = Mockito.mock(ConfigUtil.class); - PowerMockito.whenNew(ConfigUtil.class).withAnyArguments().thenReturn(configUtilMock); - } - - @Test(expected = ProjectCommonException.class) - public void testGetConfigFromJsonStringFailureWithNullString() { - try { - ConfigUtil.getConfigFromJsonString(null, configType); - } catch (ProjectCommonException e) { - Assert.assertTrue(e.getCode().equals(ResponseCode.errorConfigLoadEmptyString.getErrorCode())); - throw e; - } - } - - @Test(expected = ProjectCommonException.class) - public void testGetConfigFromJsonStringFailureWithEmptyString() { - try { - ConfigUtil.getConfigFromJsonString("", configType); - } catch (ProjectCommonException e) { - Assert.assertTrue(e.getCode().equals(ResponseCode.errorConfigLoadEmptyString.getErrorCode())); - throw e; - } - } - - @Test(expected = ProjectCommonException.class) - public void testGetConfigFromJsonStringFailureWithInvalidJsonString() { - try { - ConfigUtil.getConfigFromJsonString("{dummy}", configType); - } catch (ProjectCommonException e) { - Assert.assertTrue(e.getCode().equals(ResponseCode.errorConfigLoadParseString.getErrorCode())); - throw e; - } - } - - @Test - public void testGetConfigFromJsonStringSuccess() { - Config config = ConfigUtil.getConfigFromJsonString(validJson, configType); - Assert.assertTrue("value".equals(config.getString("key"))); - } -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/service/profile/ProfileCompletenessTest.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/service/profile/ProfileCompletenessTest.java deleted file mode 100644 index bd77fb61a..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/service/profile/ProfileCompletenessTest.java +++ /dev/null @@ -1,188 +0,0 @@ -/** */ -package org.sunbird.service.profile; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import org.junit.Assert; -import org.junit.Test; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.services.ProfileCompletenessService; -import org.sunbird.common.services.impl.ProfileCompletenessFactory; - -/** - * This test class have the assumption that each profile attribute have the same weighted. - * for more details look at profilecompleteness.properties. - * - * @author Manzarul - */ -public class ProfileCompletenessTest { - - private ProfileCompletenessService service = ProfileCompletenessFactory.getInstance(); - - @Test - public void allCompleteProfilePercentageTest() { - Map requestMap = new HashMap<>(); - requestMap.put(JsonKey.FIRST_NAME, "test"); - requestMap.put(JsonKey.LAST_NAME, "dsj"); - requestMap.put(JsonKey.EMAIL, "test@test.com"); - requestMap.put(JsonKey.PHONE, "3455556656"); - requestMap.put(JsonKey.PROFILE_SUMMARY, "profile is completed"); - requestMap.put(JsonKey.SUBJECT, "Math,Physics"); - requestMap.put(JsonKey.LANGUAGE, "Hindi"); - requestMap.put(JsonKey.DOB, "1995-08-09"); - requestMap.put("avatar", "some img url"); - requestMap.put(JsonKey.GRADE, "5th,6th,7th"); - requestMap.put(JsonKey.GENDER, "MALE"); - requestMap.put(JsonKey.LOCATION, "hdsvdjdjsfkf"); - requestMap.put(JsonKey.USERNAME, "test@test"); - Map address = new HashMap<>(); - address.put(JsonKey.CITY, "Bangalore"); - address.put(JsonKey.STATE, "sdkjdfjks"); - List> list = new ArrayList<>(); - list.add(address); - requestMap.put(JsonKey.ADDRESS, list); - Map edu = new HashMap<>(); - edu.put(JsonKey.COURSE, "M.C.A"); - edu.put(JsonKey.PERCENTAGE, 98); - List> eduList = new ArrayList<>(); - eduList.add(edu); - requestMap.put(JsonKey.EDUCATION, eduList); - Map job = new HashMap<>(); - job.put(JsonKey.JOB_NAME, "teacher"); - List> jobList = new ArrayList<>(); - jobList.add(job); - requestMap.put(JsonKey.JOB_PROFILE, jobList); - Map response = service.computeProfile(requestMap); - int val = (int) response.get(JsonKey.COMPLETENESS); - if(val>100) {val =100;} - Assert.assertEquals(100, val); - } - - @Test - public void allCompleteProfileErrorFieldTest() { - Map requestMap = new HashMap<>(); - requestMap.put(JsonKey.FIRST_NAME, "test"); - requestMap.put(JsonKey.LAST_NAME, "dsj"); - requestMap.put(JsonKey.EMAIL, "test@test.com"); - requestMap.put(JsonKey.PHONE, "3455556656"); - requestMap.put(JsonKey.PROFILE_SUMMARY, "profile is completed"); - requestMap.put(JsonKey.SUBJECT, "Math,Physics"); - requestMap.put(JsonKey.LANGUAGE, "Hindi"); - requestMap.put(JsonKey.DOB, "1995-08-09"); - requestMap.put("avatar", "some img url"); - requestMap.put(JsonKey.GRADE, "5th,6th,7th"); - requestMap.put(JsonKey.GENDER, "MALE"); - requestMap.put(JsonKey.LOCATION, "hdsvdjdjsfkf"); - requestMap.put(JsonKey.USERNAME, "test@test"); - Map address = new HashMap<>(); - address.put(JsonKey.CITY, "Bangalore"); - address.put(JsonKey.STATE, "sdkjdfjks"); - List> list = new ArrayList<>(); - list.add(address); - requestMap.put(JsonKey.ADDRESS, list); - Map edu = new HashMap<>(); - edu.put(JsonKey.COURSE, "M.C.A"); - edu.put(JsonKey.PERCENTAGE, 98); - List> eduList = new ArrayList<>(); - eduList.add(edu); - requestMap.put(JsonKey.EDUCATION, eduList); - Map job = new HashMap<>(); - job.put(JsonKey.JOB_NAME, "teacher"); - List> jobList = new ArrayList<>(); - jobList.add(job); - requestMap.put(JsonKey.JOB_PROFILE, jobList); - Map response = service.computeProfile(requestMap); - List val = (List) response.get(JsonKey.MISSING_FIELDS); - Assert.assertEquals(0, val.size()); - } - - @Test - public void zeroPercentageTest() { - Map requestMap = new HashMap<>(); - Map response = service.computeProfile(requestMap); - int val = - (int) (response.get(JsonKey.COMPLETENESS) != null ? response.get(JsonKey.COMPLETENESS) : 0); - Assert.assertEquals(0, val); - } - - @Test - public void zeroPercentageErrorTest() { - Map requestMap = new HashMap<>(); - Map response = service.computeProfile(requestMap); - List val = (List) response.get(JsonKey.MISSING_FIELDS); - Assert.assertEquals(14, val.size()); - } - - @Test - public void basicProfilePercentageTest() { - Map requestMap = new HashMap<>(); - requestMap.put(JsonKey.FIRST_NAME, "test"); - requestMap.put(JsonKey.LAST_NAME, "dsj"); - requestMap.put(JsonKey.EMAIL, "test@test.com"); - requestMap.put(JsonKey.PHONE, "3455556656"); - requestMap.put(JsonKey.PROFILE_SUMMARY, "profile is completed"); - requestMap.put(JsonKey.SUBJECT, "Math,Physics"); - requestMap.put(JsonKey.LANGUAGE, "Hindi"); - requestMap.put(JsonKey.DOB, "1995-08-09"); - requestMap.put("avatar", "some img url"); - requestMap.put(JsonKey.GRADE, "5th,6th,7th"); - requestMap.put(JsonKey.GENDER, "MALE"); - requestMap.put(JsonKey.LOCATION, "hdsvdjdjsfkf"); - requestMap.put(JsonKey.USERNAME, "test@test"); - Map response = service.computeProfile(requestMap); - int val = (int) response.get(JsonKey.COMPLETENESS); - Assert.assertEquals(79, val); - requestMap.remove("avatar"); - response = service.computeProfile(requestMap); - val = (int) response.get(JsonKey.COMPLETENESS); - Assert.assertEquals(72, val); - requestMap.put("avatar", "some value"); - response = service.computeProfile(requestMap); - val = (int) response.get(JsonKey.COMPLETENESS); - Assert.assertEquals(79, val); - Map address = new HashMap<>(); - address.put(JsonKey.CITY, "Bangalore"); - address.put(JsonKey.STATE, "sdkjdfjks"); - List> list = new ArrayList<>(); - list.add(address); - requestMap.put(JsonKey.ADDRESS, list); - response = service.computeProfile(requestMap); - val = (int) response.get(JsonKey.COMPLETENESS); - Assert.assertEquals(86, val); - } - - @Test - public void profileCompletenessWithNullAttribute() { - Map requestMap = null; - Map response = service.computeProfile(requestMap); - int val = - (int) (response.get(JsonKey.COMPLETENESS) != null ? response.get(JsonKey.COMPLETENESS) : 0); - Assert.assertEquals(0, val); - } - - @Test - public void profileCompletenessWithList() { - Map requestMap = new HashMap<>(); - List attribute = new ArrayList<>(); - attribute.add("pro"); - requestMap.put("list", attribute); - Map response = service.computeProfile(requestMap); - int val = - (int) (response.get(JsonKey.COMPLETENESS) != null ? response.get(JsonKey.COMPLETENESS) : 0); - Assert.assertEquals(0, val); - } - - @Test - public void profileCompletenessWithMap() { - Map requestMap = new HashMap<>(); - Map attribute = new HashMap<>(); - attribute.put("pro", "test"); - requestMap.put("list", attribute); - Map response = service.computeProfile(requestMap); - int val = - (int) (response.get(JsonKey.COMPLETENESS) != null ? response.get(JsonKey.COMPLETENESS) : 0); - Assert.assertEquals(0, val); - } -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/telemetry/util/validator/TelemetryGeneratorTest.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/telemetry/util/validator/TelemetryGeneratorTest.java deleted file mode 100644 index aec76bc68..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/telemetry/util/validator/TelemetryGeneratorTest.java +++ /dev/null @@ -1,107 +0,0 @@ -package org.sunbird.telemetry.util.validator; - -import static org.junit.Assert.*; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.HashMap; -import java.util.Map; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; -import org.powermock.reflect.Whitebox; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.telemetry.dto.Context; -import org.sunbird.telemetry.dto.Producer; -import org.sunbird.telemetry.util.TelemetryGenerator; - -@RunWith(PowerMockRunner.class) -@PowerMockIgnore({ "javax.management.*", "javax.net.ssl.*", "javax.security.*", "com.microsoft.azure.storage.*", - "jdk.internal.reflect.*", "sun.security.ssl.*", "javax.crypto.*", "com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*"}) -@PrepareForTest({TelemetryGenerator.class}) -public class TelemetryGeneratorTest { - - static Map context; - static Map rollup; - - @Before - public void setUp() throws Exception { - context = new HashMap(); - rollup = new HashMap(); - context.put("actorType", "consumer"); - context.put("telemetry_pdata_pid", "learning-service"); - context.put("actorId", "X-Consumer-ID"); - context.put("requestId", "8e27cbf5-e299-43b0-bca7-8347f7e5abcf"); - context.put("channel", "ORG_001"); - context.put("telemetry_pdata_ver", "1.15"); - context.put("REQUEST_ID", "8e27cbf5-e299-43b0-bca7-8347f7e5abcf"); - context.put("env", "User"); - context.put("did", "postman"); - } - - @Test - public void testGetContextWithoutRollUp() - throws InvocationTargetException, IllegalAccessException { - Method method = Whitebox.getMethod(TelemetryGenerator.class, "getContext", Map.class); - Context ctx = (Context) method.invoke(null, context); - assertEquals("postman", ctx.getDid()); - assertEquals("ORG_001", ctx.getChannel()); - assertEquals("User", ctx.getEnv()); - } - - @Test - public void testGetContextWithRollUp() throws InvocationTargetException, IllegalAccessException { - rollup.put("id", 1); - context.put("rollup", rollup); - Method method = Whitebox.getMethod(TelemetryGenerator.class, "getContext", Map.class); - Context ctx = (Context) method.invoke(null, context); - assertTrue(rollup.equals(ctx.getRollup())); - } - - @Test - public void testRemoveAttributes() throws InvocationTargetException, IllegalAccessException { - Method method = - Whitebox.getMethod(TelemetryGenerator.class, "removeAttributes", Map.class, String.class); - String[] removableProperty = {JsonKey.DEVICE_ID}; - method.invoke(null, context, removableProperty); - assertFalse(context.containsKey(JsonKey.DEVICE_ID)); - } - - @Test() - public void testGetProducerWithContextNull() - throws InvocationTargetException, IllegalAccessException { - - Map nullContext = null; - Method method = Whitebox.getMethod(TelemetryGenerator.class, "getProducer", Map.class); - Producer producer = (Producer) method.invoke(null, nullContext); - assertEquals("", producer.getId()); - assertEquals("lms-service", producer.getPid()); - assertEquals("1.0", producer.getVer()); - } - - @Test - public void testGetProducerWithAppId() throws InvocationTargetException, IllegalAccessException { - context.put("appId", "random"); - Method method = Whitebox.getMethod(TelemetryGenerator.class, "getProducer", Map.class); - Producer producer = (Producer) method.invoke(null, context); - assertEquals("random", producer.getId()); - } - - @Test - public void testGetProducerWithoutAppId() - throws InvocationTargetException, IllegalAccessException { - context.put("telemetry_pdata_id", "local.sunbird.learning.service"); - Method method = Whitebox.getMethod(TelemetryGenerator.class, "getProducer", Map.class); - Producer producer = (Producer) method.invoke(null, context); - assertEquals("local.sunbird.learning.service", producer.getId()); - } - - @AfterClass - public static void tearDown() throws Exception { - context.clear(); - } -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/telemetry/util/validator/TelemetryObjectValidatorV3Test.java b/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/telemetry/util/validator/TelemetryObjectValidatorV3Test.java deleted file mode 100644 index f47bf968d..000000000 --- a/course-mw/sunbird-util/sunbird-platform-core/common-util/src/test/java/org/sunbird/telemetry/util/validator/TelemetryObjectValidatorV3Test.java +++ /dev/null @@ -1,385 +0,0 @@ -package org.sunbird.telemetry.util.validator; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import org.junit.Assert; -import org.junit.Test; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.models.util.ProjectLogger; -import org.sunbird.telemetry.dto.Actor; -import org.sunbird.telemetry.dto.Context; -import org.sunbird.telemetry.dto.Telemetry; -import org.sunbird.telemetry.util.TelemetryEvents; -import org.sunbird.telemetry.validator.TelemetryObjectValidatorV3; - -/** Created by arvind on 30/1/18. */ -public class TelemetryObjectValidatorV3Test { - - private TelemetryObjectValidatorV3 validatorV3 = new TelemetryObjectValidatorV3(); - private ObjectMapper mapper = new ObjectMapper(); - - @Test - public void testAuditWithValidData() { - - Telemetry telemetry = new Telemetry(); - telemetry.setEid(TelemetryEvents.AUDIT.getName()); - telemetry.setMid("dummy msg id"); - telemetry.setVer("3.0"); - - Actor actor = new Actor(); - actor.setId("1"); - actor.setType(JsonKey.USER); - telemetry.setActor(actor); - - Context context = new Context(); - context.setEnv(JsonKey.ORGANISATION); - context.setChannel("channel"); - - telemetry.setContext(context); - - Map auditEdata = new HashMap<>(); - List props = new ArrayList<>(); - props.add("username"); - props.add("org"); - auditEdata.put(JsonKey.PROPS, props); - telemetry.setEdata(auditEdata); - - boolean result = false; - try { - result = validatorV3.validateAudit(mapper.writeValueAsString(telemetry)); - } catch (JsonProcessingException e) { - ProjectLogger.log(e.getMessage(), e); - } - Assert.assertTrue(result); - } - - @Test - public void testAuditWithoutActor() { - - Telemetry telemetry = new Telemetry(); - telemetry.setEid(TelemetryEvents.AUDIT.getName()); - telemetry.setMid("dummy msg id"); - telemetry.setVer("3.0"); - - Context context = new Context(); - context.setEnv(JsonKey.ORGANISATION); - context.setChannel("channel"); - - telemetry.setContext(context); - - Map auditEdata = new HashMap<>(); - List props = new ArrayList<>(); - props.add("username"); - props.add("org"); - auditEdata.put(JsonKey.PROPS, props); - telemetry.setEdata(auditEdata); - - boolean result = true; - try { - result = validatorV3.validateAudit(mapper.writeValueAsString(telemetry)); - } catch (JsonProcessingException e) { - ProjectLogger.log(e.getMessage(), e); - } - Assert.assertFalse(result); - } - - @Test - public void testAuditWithoutChannel() { - - Telemetry telemetry = new Telemetry(); - telemetry.setEid(TelemetryEvents.AUDIT.getName()); - telemetry.setMid("dummy msg id"); - telemetry.setVer("3.0"); - - Actor actor = new Actor(); - actor.setId("1"); - actor.setType(JsonKey.USER); - telemetry.setActor(actor); - - Context context = new Context(); - context.setEnv(JsonKey.ORGANISATION); - // context.setChannel("channel"); - - telemetry.setContext(context); - - Map auditEdata = new HashMap<>(); - List props = new ArrayList<>(); - props.add("username"); - props.add("org"); - auditEdata.put(JsonKey.PROPS, props); - telemetry.setEdata(auditEdata); - - boolean result = true; - try { - result = validatorV3.validateAudit(mapper.writeValueAsString(telemetry)); - } catch (JsonProcessingException e) { - ProjectLogger.log(e.getMessage(), e); - } - Assert.assertFalse(result); - } - - @Test - public void testAuditWithoutEnv() { - - Telemetry telemetry = new Telemetry(); - telemetry.setEid(TelemetryEvents.AUDIT.getName()); - telemetry.setMid("dummy msg id"); - telemetry.setVer("3.0"); - - Actor actor = new Actor(); - actor.setId("1"); - actor.setType(JsonKey.USER); - telemetry.setActor(actor); - - Context context = new Context(); - // context.setEnv(JsonKey.ORGANISATION); - context.setChannel("channel"); - - telemetry.setContext(context); - - Map auditEdata = new HashMap<>(); - List props = new ArrayList<>(); - props.add("username"); - props.add("org"); - auditEdata.put(JsonKey.PROPS, props); - telemetry.setEdata(auditEdata); - - boolean result = true; - try { - result = validatorV3.validateAudit(mapper.writeValueAsString(telemetry)); - } catch (JsonProcessingException e) { - ProjectLogger.log(e.getMessage(), e); - } - Assert.assertFalse(result); - } - - @Test - public void testAuditWithoutEData() { - - Telemetry telemetry = new Telemetry(); - telemetry.setEid(TelemetryEvents.AUDIT.getName()); - telemetry.setMid("dummy msg id"); - telemetry.setVer("3.0"); - - Actor actor = new Actor(); - actor.setId("1"); - actor.setType(JsonKey.USER); - telemetry.setActor(actor); - - Context context = new Context(); - context.setEnv(JsonKey.ORGANISATION); - context.setChannel("channel"); - - telemetry.setContext(context); - - boolean result = true; - try { - result = validatorV3.validateAudit(mapper.writeValueAsString(telemetry)); - } catch (JsonProcessingException e) { - ProjectLogger.log(e.getMessage(), e); - } - Assert.assertFalse(result); - } - - @Test - public void testSearchWithValidData() { - - Telemetry telemetry = new Telemetry(); - telemetry.setEid(TelemetryEvents.SEARCH.getName()); - telemetry.setMid("dummy msg id"); - telemetry.setVer("3.0"); - - Actor actor = new Actor(); - actor.setId("1"); - actor.setType(JsonKey.USER); - telemetry.setActor(actor); - - Context context = new Context(); - context.setEnv(JsonKey.ORGANISATION); - context.setChannel("channel"); - - telemetry.setContext(context); - - Map searchEdata = new HashMap<>(); - searchEdata.put(JsonKey.TYPE, "user"); - searchEdata.put( - JsonKey.QUERY, - "\"filters\":{\n" + " \"lastName\": \"Test\"\n" + " \n" + " }"); - searchEdata.put(JsonKey.SIZE, new Long(10)); - searchEdata.put(JsonKey.TOPN, new ArrayList<>()); - telemetry.setEdata(searchEdata); - - boolean result = false; - try { - result = validatorV3.validateSearch(mapper.writeValueAsString(telemetry)); - } catch (JsonProcessingException e) { - ProjectLogger.log(e.getMessage(), e); - } - Assert.assertTrue(result); - } - - @Test - public void testSearchWithoutQuerySize() { - - Telemetry telemetry = new Telemetry(); - telemetry.setEid(TelemetryEvents.SEARCH.getName()); - telemetry.setMid("dummy msg id"); - telemetry.setVer("3.0"); - - Actor actor = new Actor(); - actor.setId("1"); - actor.setType(JsonKey.USER); - telemetry.setActor(actor); - - Context context = new Context(); - context.setEnv(JsonKey.ORGANISATION); - context.setChannel("channel"); - - telemetry.setContext(context); - - Map searchEdata = new HashMap<>(); - searchEdata.put(JsonKey.TYPE, "user"); - telemetry.setEdata(searchEdata); - - boolean result = true; - try { - result = validatorV3.validateSearch(mapper.writeValueAsString(telemetry)); - } catch (JsonProcessingException e) { - ProjectLogger.log(e.getMessage(), e); - } - Assert.assertFalse(result); - } - - @Test - public void testLogWithValidData() { - - Telemetry telemetry = new Telemetry(); - telemetry.setEid(TelemetryEvents.LOG.getName()); - telemetry.setMid("dummy msg id"); - telemetry.setVer("3.0"); - - Actor actor = new Actor(); - actor.setId("1"); - actor.setType(JsonKey.USER); - telemetry.setActor(actor); - - Context context = new Context(); - context.setEnv(JsonKey.ORGANISATION); - context.setChannel("channel"); - - telemetry.setContext(context); - - Map logEdata = new HashMap<>(); - logEdata.put(JsonKey.TYPE, "info"); - logEdata.put(JsonKey.LEVEL, JsonKey.API_ACCESS); - logEdata.put(JsonKey.MESSAGE, ""); - telemetry.setEdata(logEdata); - - boolean result = false; - try { - result = validatorV3.validateLog(mapper.writeValueAsString(telemetry)); - } catch (JsonProcessingException e) { - ProjectLogger.log(e.getMessage(), e); - } - Assert.assertTrue(result); - } - - @Test - public void testLogWithoutLogLevelType() { - - Telemetry telemetry = new Telemetry(); - telemetry.setEid(TelemetryEvents.LOG.getName()); - telemetry.setMid("dummy msg id"); - telemetry.setVer("3.0"); - - Actor actor = new Actor(); - actor.setId("1"); - actor.setType(JsonKey.USER); - telemetry.setActor(actor); - - Context context = new Context(); - context.setEnv(JsonKey.ORGANISATION); - context.setChannel("channel"); - - telemetry.setContext(context); - - Map logEdata = new HashMap<>(); - logEdata.put(JsonKey.MESSAGE, ""); - telemetry.setEdata(logEdata); - - boolean result = true; - try { - result = validatorV3.validateLog(mapper.writeValueAsString(telemetry)); - } catch (JsonProcessingException e) { - ProjectLogger.log(e.getMessage(), e); - } - Assert.assertFalse(result); - } - - @Test - public void testErrorWithValidData() { - - Telemetry telemetry = new Telemetry(); - telemetry.setEid(TelemetryEvents.ERROR.getName()); - telemetry.setMid("dummy msg id"); - telemetry.setVer("3.0"); - - Actor actor = new Actor(); - actor.setId("1"); - actor.setType(JsonKey.USER); - telemetry.setActor(actor); - - Context context = new Context(); - context.setEnv(JsonKey.ORGANISATION); - context.setChannel("channel"); - telemetry.setContext(context); - - Map errorEdata = new HashMap<>(); - errorEdata.put(JsonKey.ERROR, "invalid user"); - errorEdata.put(JsonKey.ERR_TYPE, JsonKey.API_ACCESS); - errorEdata.put(JsonKey.STACKTRACE, "error msg"); - telemetry.setEdata(errorEdata); - - boolean result = false; - try { - result = validatorV3.validateError(mapper.writeValueAsString(telemetry)); - } catch (JsonProcessingException e) { - ProjectLogger.log(e.getMessage(), e); - } - Assert.assertTrue(result); - } - - @Test - public void testErrorWithoutErrorTypeStackTrace() { - - Telemetry telemetry = new Telemetry(); - telemetry.setEid(TelemetryEvents.ERROR.getName()); - telemetry.setMid("dummy msg id"); - telemetry.setVer("3.0"); - - Actor actor = new Actor(); - actor.setId("1"); - actor.setType(JsonKey.USER); - telemetry.setActor(actor); - - Context context = new Context(); - context.setEnv(JsonKey.ORGANISATION); - context.setChannel("channel"); - telemetry.setContext(context); - - Map errorEdata = new HashMap<>(); - telemetry.setEdata(errorEdata); - - boolean result = true; - try { - result = validatorV3.validateError(mapper.writeValueAsString(telemetry)); - } catch (JsonProcessingException e) { - ProjectLogger.log(e.getMessage(), e); - } - Assert.assertFalse(result); - } -} diff --git a/course-mw/sunbird-util/sunbird-platform-core/pom.xml b/course-mw/sunbird-util/sunbird-platform-core/pom.xml index e705be78a..695f05e80 100644 --- a/course-mw/sunbird-util/sunbird-platform-core/pom.xml +++ b/course-mw/sunbird-util/sunbird-platform-core/pom.xml @@ -13,10 +13,8 @@ sunbird-platform-core - common-util actor-util actor-core sunbird-commons - auth-verifier diff --git a/course-mw/sunbird-util/sunbird-platform-core/sunbird-commons/pom.xml b/course-mw/sunbird-util/sunbird-platform-core/sunbird-commons/pom.xml index 95b9ad517..f5f819d57 100644 --- a/course-mw/sunbird-util/sunbird-platform-core/sunbird-commons/pom.xml +++ b/course-mw/sunbird-util/sunbird-platform-core/sunbird-commons/pom.xml @@ -20,16 +20,11 @@ actor-util 0.0.1-SNAPSHOT - + org.sunbird - common-util - 0.0.1-SNAPSHOT + sunbird-platform-common + 1.0-SNAPSHOT - - org.sunbird - auth-verifier - 1.0-SNAPSHOT - com.squareup.okhttp3 mockwebserver diff --git a/service/app/controllers/BaseController.java b/service/app/controllers/BaseController.java index 7f6644e23..049f2f2b0 100644 --- a/service/app/controllers/BaseController.java +++ b/service/app/controllers/BaseController.java @@ -10,16 +10,16 @@ import modules.ApplicationStart; import modules.OnRequestHandler; import org.apache.commons.lang3.StringUtils; -import org.sunbird.common.exception.ProjectCommonException; -import org.sunbird.common.models.response.Response; -import org.sunbird.common.models.response.ResponseParams; -import org.sunbird.common.models.util.ActorOperations; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.models.util.LoggerUtil; -import org.sunbird.common.models.util.ProjectUtil; -import org.sunbird.common.request.HeaderParam; -import org.sunbird.common.request.RequestContext; -import org.sunbird.common.responsecode.ResponseCode; +import org.sunbird.exception.ProjectCommonException; +import org.sunbird.response.Response; +import org.sunbird.response.ResponseParams; +import org.sunbird.operations.lms.ActorOperations; +import org.sunbird.keys.JsonKey; +import org.sunbird.logging.LoggerUtil; +import org.sunbird.common.ProjectUtil; +import org.sunbird.request.HeaderParam; +import org.sunbird.request.RequestContext; +import org.sunbird.response.ResponseCode; import org.sunbird.keys.SunbirdKey; import org.sunbird.telemetry.util.TelemetryEvents; import org.sunbird.telemetry.util.TelemetryWriter; @@ -59,8 +59,8 @@ public class BaseController extends Controller { private static final String debugEnabled = "false"; public static final LoggerUtil logger = new LoggerUtil(BaseController.class); - private org.sunbird.common.request.Request initRequest( - org.sunbird.common.request.Request request, String operation, Http.Request httpRequest) { + private org.sunbird.request.Request initRequest( + org.sunbird.request.Request request, String operation, Http.Request httpRequest) { request.setOperation(operation); request.setRequestId(httpRequest.attrs().getOptional(Attrs.REQUEST_ID).orElse(null)); request.setEnv(getEnvironment()); @@ -74,7 +74,7 @@ private org.sunbird.common.request.Request initRequest( return request; } - private RequestContext getRequestContext(Http.Request httpRequest, org.sunbird.common.request.Request request) { + private RequestContext getRequestContext(Http.Request httpRequest, org.sunbird.request.Request request) { RequestContext requestContext = new RequestContext( JsonKey.SERVICE_NAME, JsonKey.PRODUCER_NAME, @@ -93,16 +93,16 @@ private RequestContext getRequestContext(Http.Request httpRequest, org.sunbird.c * * @param operation A defined actor operation * @param requestBodyJson Optional information received in request body (JSON) - * @return Created and initialised Request (@see {@link org.sunbird.common.request.Request}) + * @return Created and initialised Request (@see {@link org.sunbird.request.Request}) * instance. */ - protected org.sunbird.common.request.Request createAndInitRequest( + protected org.sunbird.request.Request createAndInitRequest( String operation, JsonNode requestBodyJson, Http.Request httpRequest) { try { - org.sunbird.common.request.Request request = - (org.sunbird.common.request.Request) + org.sunbird.request.Request request = + (org.sunbird.request.Request) mapper.RequestMapper.mapRequest( - requestBodyJson, org.sunbird.common.request.Request.class); + requestBodyJson, org.sunbird.request.Request.class); return initRequest(request, operation, httpRequest); } catch (Exception e) { ProjectCommonException.throwServerErrorException(ResponseCode.SERVER_ERROR); @@ -114,12 +114,12 @@ protected org.sunbird.common.request.Request createAndInitRequest( * Helper method for creating and initialising a request for given operation. * * @param operation A defined actor operation - * @return Created and initialised Request (@see {@link org.sunbird.common.request.Request}) + * @return Created and initialised Request (@see {@link org.sunbird.request.Request}) * instance. */ - protected org.sunbird.common.request.Request createAndInitRequest( + protected org.sunbird.request.Request createAndInitRequest( String operation, Http.Request httpRequest) { - org.sunbird.common.request.Request request = new org.sunbird.common.request.Request(); + org.sunbird.request.Request request = new org.sunbird.request.Request(); return initRequest(request, operation, httpRequest); } @@ -229,7 +229,7 @@ protected CompletionStage handleRequest( boolean isJsonBodyRequired, Http.Request httpRequest) { try { - org.sunbird.common.request.Request request = null; + org.sunbird.request.Request request = null; if (!isJsonBodyRequired) { request = createAndInitRequest(operation, httpRequest); } else { @@ -262,7 +262,7 @@ protected CompletionStage handleSearchRequest( String esObjectType, Http.Request httpRequest) { try { - org.sunbird.common.request.Request request = null; + org.sunbird.request.Request request = null; if (null != requestBodyJson) { request = createAndInitRequest(operation, requestBodyJson, httpRequest); } else { @@ -530,7 +530,7 @@ private long calculateApiTimeTaken(Long startTime) { */ public CompletionStage actorResponseHandler( Object actorRef, - org.sunbird.common.request.Request request, + org.sunbird.request.Request request, Timeout timeout, String responseKey, Http.Request httpReq) { @@ -686,7 +686,7 @@ private static Map genarateTelemetryInfoForError(Http.Request re } public void setChannelAndActorInfo( - Http.Request httpReq, org.sunbird.common.request.Request reqObj) { + Http.Request httpReq, org.sunbird.request.Request reqObj) { reqObj.getContext().put(JsonKey.CHANNEL, httpReq.attrs().getOptional(Attrs.CHANNEL).orElse(null)); reqObj.getContext().put(JsonKey.ACTOR_ID, httpReq.attrs().getOptional(Attrs.ACTOR_ID).orElse(null)); @@ -753,8 +753,8 @@ public static String getResponseSize(String response) throws UnsupportedEncoding return "0.0"; } - public org.sunbird.common.request.Request transformUserId( - org.sunbird.common.request.Request request) { + public org.sunbird.request.Request transformUserId( + org.sunbird.request.Request request) { if (request != null && request.getRequest() != null) { String id = (String) request.getRequest().get(JsonKey.ID); request.getRequest().put(JsonKey.ID, ProjectUtil.getLmsUserId(id)); @@ -801,7 +801,7 @@ public static String getResponseId(String requestPath) { return builder.toString(); } - public void setContextData(Http.Request httpReq, org.sunbird.common.request.Request reqObj) { + public void setContextData(Http.Request httpReq, org.sunbird.request.Request reqObj) { try { String reqContext = httpReq.attrs().get(Attrs.CONTEXT); Map requestInfo = @@ -818,7 +818,7 @@ private void generateExceptionTelemetry(Request request, ProjectCommonException try { String reqContext = request.attrs().get(Attrs.CONTEXT); Map requestInfo = objectMapper.readValue(reqContext, new TypeReference>() {}); - org.sunbird.common.request.Request reqForTelemetry = new org.sunbird.common.request.Request(); + org.sunbird.request.Request reqForTelemetry = new org.sunbird.request.Request(); Map params = (Map) requestInfo.getOrDefault(JsonKey.ADDITIONAL_INFO, new HashMap<>()); params.put(JsonKey.LOG_TYPE, JsonKey.API_ACCESS); params.put(JsonKey.MESSAGE, ""); diff --git a/service/app/controllers/LearnerController.java b/service/app/controllers/LearnerController.java index 74942a973..9118c87f7 100644 --- a/service/app/controllers/LearnerController.java +++ b/service/app/controllers/LearnerController.java @@ -4,9 +4,9 @@ import org.apache.pekko.actor.ActorRef; import com.fasterxml.jackson.databind.JsonNode; import org.apache.commons.lang3.StringUtils; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.request.LearnerStateRequestValidator; -import org.sunbird.common.request.Request; +import org.sunbird.keys.JsonKey; +import org.sunbird.validators.LearnerStateRequestValidator; +import org.sunbird.request.Request; import org.sunbird.keys.SunbirdKey; import play.mvc.Http; import java.util.List; diff --git a/service/app/controllers/activityaggregate/ActivityAggregateController.java b/service/app/controllers/activityaggregate/ActivityAggregateController.java index 7ce8ac16c..b4b770ad3 100644 --- a/service/app/controllers/activityaggregate/ActivityAggregateController.java +++ b/service/app/controllers/activityaggregate/ActivityAggregateController.java @@ -3,8 +3,8 @@ import controllers.BaseController; import controllers.activityaggregate.validator.ActivityAggregateRequestValidator; import org.apache.pekko.actor.ActorRef; -import org.sunbird.common.models.util.ActorOperations; -import org.sunbird.common.request.Request; +import org.sunbird.operations.lms.ActorOperations; +import org.sunbird.request.Request; import play.mvc.Http; import play.mvc.Result; diff --git a/service/app/controllers/activityaggregate/validator/ActivityAggregateRequestValidator.java b/service/app/controllers/activityaggregate/validator/ActivityAggregateRequestValidator.java index 7a2243eec..133728788 100644 --- a/service/app/controllers/activityaggregate/validator/ActivityAggregateRequestValidator.java +++ b/service/app/controllers/activityaggregate/validator/ActivityAggregateRequestValidator.java @@ -1,9 +1,9 @@ package controllers.activityaggregate.validator; -import org.sunbird.common.exception.ProjectCommonException; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.responsecode.ResponseCode; -import org.sunbird.common.request.Request; +import org.sunbird.exception.ProjectCommonException; +import org.sunbird.keys.JsonKey; +import org.sunbird.response.ResponseCode; +import org.sunbird.request.Request; import java.util.List; import java.util.Map; diff --git a/service/app/controllers/bulkapimanagement/BaseBulkUploadController.java b/service/app/controllers/bulkapimanagement/BaseBulkUploadController.java index b2cf90ef9..8be82e108 100644 --- a/service/app/controllers/bulkapimanagement/BaseBulkUploadController.java +++ b/service/app/controllers/bulkapimanagement/BaseBulkUploadController.java @@ -4,10 +4,10 @@ import controllers.BaseController; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; -import org.sunbird.common.exception.ProjectCommonException; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.models.util.ProjectUtil; -import org.sunbird.common.responsecode.ResponseCode; +import org.sunbird.exception.ProjectCommonException; +import org.sunbird.keys.JsonKey; +import org.sunbird.common.ProjectUtil; +import org.sunbird.response.ResponseCode; import play.libs.Files; import play.mvc.Http; import play.mvc.Http.MultipartFormData; @@ -40,14 +40,14 @@ public class BaseBulkUploadController extends BaseController { * * @param operation A defined actor operation * @param objectType A defined type of object to set in he request body - * @return Created and initialised Request (@see {@link org.sunbird.common.request.Request}) + * @return Created and initialised Request (@see {@link org.sunbird.request.Request}) * instance. */ - protected org.sunbird.common.request.Request createAndInitBulkRequest( + protected org.sunbird.request.Request createAndInitBulkRequest( String operation, String objectType, Boolean validateFileZize, Http.Request httpRequest) throws IOException, Exception { logger.info(null, "API call for operation : " + operation); - org.sunbird.common.request.Request reqObj = new org.sunbird.common.request.Request(); + org.sunbird.request.Request reqObj = new org.sunbird.request.Request(); Map map = new HashMap<>(); byte[] byteArray = null; MultipartFormData body = httpRequest.body().asMultipartFormData(); @@ -74,9 +74,9 @@ protected org.sunbird.common.request.Request createAndInitBulkRequest( byteArray = IOUtils.toByteArray(is); } else if (null != requestData) { reqObj = - (org.sunbird.common.request.Request) + (org.sunbird.request.Request) mapper.RequestMapper.mapRequest( - httpRequest.body().asJson(), org.sunbird.common.request.Request.class); + httpRequest.body().asJson(), org.sunbird.request.Request.class); InputStream is = new ByteArrayInputStream( ((String) reqObj.getRequest().get(JsonKey.DATA)).getBytes(StandardCharsets.UTF_8)); @@ -85,7 +85,7 @@ protected org.sunbird.common.request.Request createAndInitBulkRequest( map.putAll(reqObj.getRequest()); } else { throw new ProjectCommonException( - ResponseCode.invalidData.getErrorCode(), + ResponseCode.invalidData, ResponseCode.invalidData.getErrorMessage(), ResponseCode.CLIENT_ERROR.getResponseCode()); } @@ -108,7 +108,7 @@ private void checkFileSize(byte[] byteArray, String objectType) { if (null == byteArray) { throw new ProjectCommonException( - ResponseCode.missingFileAttachment.getErrorCode(), + ResponseCode.missingFileAttachment, ResponseCode.missingFileAttachment.getErrorMessage(), ResponseCode.CLIENT_ERROR.getResponseCode()); } @@ -117,7 +117,7 @@ private void checkFileSize(byte[] byteArray, String objectType) { String allowedMaxSize = ProjectUtil.getConfigValue(JsonKey.UPLOAD_FILE_MAX_SIZE); if (StringUtils.isEmpty(allowedMaxSize)) { throw new ProjectCommonException( - ResponseCode.fileAttachmentSizeNotConfigured.getErrorCode(), + ResponseCode.fileAttachmentSizeNotConfigured, ResponseCode.fileAttachmentSizeNotConfigured.getErrorMessage(), ResponseCode.CLIENT_ERROR.getResponseCode()); } @@ -127,8 +127,8 @@ private void checkFileSize(byte[] byteArray, String objectType) { Long allowedSize = filesize.longValue(); if (byteArray.length > allowedSize) { throw new ProjectCommonException( - ResponseCode.sizeLimitExceed.getErrorCode(), - ResponseCode.sizeLimitExceed.getErrorMessage(), + ResponseCode.errorMaxSizeExceeded, + ResponseCode.errorMaxSizeExceeded.getErrorMessage(), ResponseCode.CLIENT_ERROR.getResponseCode(), allowedMaxSize + FILE_SIZE_UNIT); } diff --git a/service/app/controllers/bulkapimanagement/BulkUploadController.java b/service/app/controllers/bulkapimanagement/BulkUploadController.java index 65d0d8b2f..2ace93370 100644 --- a/service/app/controllers/bulkapimanagement/BulkUploadController.java +++ b/service/app/controllers/bulkapimanagement/BulkUploadController.java @@ -1,10 +1,10 @@ package controllers.bulkapimanagement; import org.apache.pekko.actor.ActorRef; -import org.sunbird.common.models.util.ActorOperations; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.request.BaseRequestValidator; -import org.sunbird.common.request.Request; +import org.sunbird.operations.lms.ActorOperations; +import org.sunbird.keys.JsonKey; +import org.sunbird.validators.BaseRequestValidator; +import org.sunbird.request.Request; import play.mvc.Http; import play.mvc.Result; diff --git a/service/app/controllers/cache/CacheController.java b/service/app/controllers/cache/CacheController.java index e36d4ee64..a4b450697 100644 --- a/service/app/controllers/cache/CacheController.java +++ b/service/app/controllers/cache/CacheController.java @@ -2,8 +2,8 @@ import org.apache.pekko.actor.ActorRef; import controllers.BaseController; -import org.sunbird.common.models.util.ActorOperations; -import org.sunbird.common.models.util.JsonKey; +import org.sunbird.operations.lms.ActorOperations; +import org.sunbird.keys.JsonKey; import play.mvc.Http; import play.mvc.Result; diff --git a/service/app/controllers/certificate/CertificateController.java b/service/app/controllers/certificate/CertificateController.java index a4b36fbb3..54a7cad70 100644 --- a/service/app/controllers/certificate/CertificateController.java +++ b/service/app/controllers/certificate/CertificateController.java @@ -2,8 +2,8 @@ import org.apache.pekko.actor.ActorRef; import controllers.BaseController; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.request.Request; +import org.sunbird.keys.JsonKey; +import org.sunbird.request.Request; import org.sunbird.learner.actor.operations.CourseActorOperations; import play.mvc.Http; import play.mvc.Result; diff --git a/service/app/controllers/certificate/CertificateRequestValidator.java b/service/app/controllers/certificate/CertificateRequestValidator.java index 307720524..6407489dd 100644 --- a/service/app/controllers/certificate/CertificateRequestValidator.java +++ b/service/app/controllers/certificate/CertificateRequestValidator.java @@ -2,11 +2,11 @@ import org.apache.commons.collections.MapUtils; import org.apache.commons.lang3.StringUtils; -import org.sunbird.common.exception.ProjectCommonException; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.request.BaseRequestValidator; -import org.sunbird.common.request.Request; -import org.sunbird.common.responsecode.ResponseCode; +import org.sunbird.exception.ProjectCommonException; +import org.sunbird.keys.JsonKey; +import org.sunbird.validators.BaseRequestValidator; +import org.sunbird.request.Request; +import org.sunbird.response.ResponseCode; import org.sunbird.learner.constants.CourseJsonKey; import java.text.MessageFormat; diff --git a/service/app/controllers/collectionsummaryaggregate/CollectionSummaryAggregateController.java b/service/app/controllers/collectionsummaryaggregate/CollectionSummaryAggregateController.java index 0cff12e3d..ae64e282c 100644 --- a/service/app/controllers/collectionsummaryaggregate/CollectionSummaryAggregateController.java +++ b/service/app/controllers/collectionsummaryaggregate/CollectionSummaryAggregateController.java @@ -3,8 +3,8 @@ import org.apache.pekko.actor.ActorRef; import controllers.BaseController; import controllers.collectionsummaryaggregate.validator.Validator; -import org.sunbird.common.models.util.ActorOperations; -import org.sunbird.common.request.Request; +import org.sunbird.operations.lms.ActorOperations; +import org.sunbird.request.Request; import play.mvc.Http; import play.mvc.Result; diff --git a/service/app/controllers/collectionsummaryaggregate/validator/Validator.java b/service/app/controllers/collectionsummaryaggregate/validator/Validator.java index 075b2ad45..c88173e89 100644 --- a/service/app/controllers/collectionsummaryaggregate/validator/Validator.java +++ b/service/app/controllers/collectionsummaryaggregate/validator/Validator.java @@ -1,9 +1,9 @@ package controllers.collectionsummaryaggregate.validator; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.request.BaseRequestValidator; -import org.sunbird.common.request.Request; -import org.sunbird.common.responsecode.ResponseCode; +import org.sunbird.keys.JsonKey; +import org.sunbird.validators.BaseRequestValidator; +import org.sunbird.request.Request; +import org.sunbird.response.ResponseCode; import java.util.Map; diff --git a/service/app/controllers/courseenrollment/CourseEnrollmentController.java b/service/app/controllers/courseenrollment/CourseEnrollmentController.java index 04134c198..94b6c4ce0 100644 --- a/service/app/controllers/courseenrollment/CourseEnrollmentController.java +++ b/service/app/controllers/courseenrollment/CourseEnrollmentController.java @@ -3,9 +3,9 @@ import org.apache.pekko.actor.ActorRef; import controllers.BaseController; import controllers.courseenrollment.validator.CourseEnrollmentRequestValidator; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.models.util.ProjectUtil; -import org.sunbird.common.request.Request; +import org.sunbird.keys.JsonKey; +import org.sunbird.common.ProjectUtil; +import org.sunbird.request.Request; import play.mvc.Http; import play.mvc.Result; diff --git a/service/app/controllers/courseenrollment/validator/CourseEnrollmentRequestValidator.java b/service/app/controllers/courseenrollment/validator/CourseEnrollmentRequestValidator.java index a7229e5ba..d698515bf 100644 --- a/service/app/controllers/courseenrollment/validator/CourseEnrollmentRequestValidator.java +++ b/service/app/controllers/courseenrollment/validator/CourseEnrollmentRequestValidator.java @@ -1,9 +1,9 @@ package controllers.courseenrollment.validator; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.request.BaseRequestValidator; -import org.sunbird.common.request.Request; -import org.sunbird.common.responsecode.ResponseCode; +import org.sunbird.keys.JsonKey; +import org.sunbird.validators.BaseRequestValidator; +import org.sunbird.request.Request; +import org.sunbird.response.ResponseCode; public class CourseEnrollmentRequestValidator extends BaseRequestValidator { diff --git a/service/app/controllers/coursemanagement/CourseBatchController.java b/service/app/controllers/coursemanagement/CourseBatchController.java index 23c820663..cc0257840 100644 --- a/service/app/controllers/coursemanagement/CourseBatchController.java +++ b/service/app/controllers/coursemanagement/CourseBatchController.java @@ -5,10 +5,10 @@ import com.fasterxml.jackson.databind.JsonNode; import controllers.BaseController; import controllers.coursemanagement.validator.CourseBatchRequestValidator; -import org.sunbird.common.models.util.ActorOperations; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.models.util.ProjectUtil.EsType; -import org.sunbird.common.request.Request; +import org.sunbird.operations.lms.ActorOperations; +import org.sunbird.keys.JsonKey; +import org.sunbird.common.ProjectUtil.EsType; +import org.sunbird.request.Request; import play.mvc.Http; import play.mvc.Result; import util.Attrs; diff --git a/service/app/controllers/coursemanagement/CourseController.java b/service/app/controllers/coursemanagement/CourseController.java index 1cfd544df..2e26e1ed3 100644 --- a/service/app/controllers/coursemanagement/CourseController.java +++ b/service/app/controllers/coursemanagement/CourseController.java @@ -3,8 +3,8 @@ import org.apache.pekko.actor.ActorRef; import controllers.BaseController; import controllers.coursemanagement.validator.CourseCreateRequestValidator; -import org.sunbird.common.models.util.ActorOperations; -import org.sunbird.common.request.Request; +import org.sunbird.operations.lms.ActorOperations; +import org.sunbird.request.Request; import play.mvc.Http; import play.mvc.Result; diff --git a/service/app/controllers/coursemanagement/validator/CourseBatchRequestValidator.java b/service/app/controllers/coursemanagement/validator/CourseBatchRequestValidator.java index 79850842a..5879f495f 100644 --- a/service/app/controllers/coursemanagement/validator/CourseBatchRequestValidator.java +++ b/service/app/controllers/coursemanagement/validator/CourseBatchRequestValidator.java @@ -2,12 +2,12 @@ import org.apache.commons.collections.MapUtils; import org.apache.commons.lang3.StringUtils; -import org.sunbird.common.exception.ProjectCommonException; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.models.util.ProjectUtil; -import org.sunbird.common.request.BaseRequestValidator; -import org.sunbird.common.request.Request; -import org.sunbird.common.responsecode.ResponseCode; +import org.sunbird.exception.ProjectCommonException; +import org.sunbird.keys.JsonKey; +import org.sunbird.common.ProjectUtil; +import org.sunbird.validators.BaseRequestValidator; +import org.sunbird.request.Request; +import org.sunbird.response.ResponseCode; import java.text.MessageFormat; import java.text.SimpleDateFormat; @@ -48,7 +48,7 @@ public void validateUpdateCourseBatchRequest(Request request) { boolean status = validateBatchStatus(request); if (!status) { throw new ProjectCommonException( - ResponseCode.progressStatusError.getErrorCode(), + ResponseCode.progressStatusError, ResponseCode.progressStatusError.getErrorMessage(), ERROR_CODE); } @@ -56,7 +56,7 @@ public void validateUpdateCourseBatchRequest(Request request) { if (request.getRequest().containsKey(JsonKey.NAME) && StringUtils.isBlank((String) request.getRequest().get(JsonKey.NAME))) { throw new ProjectCommonException( - ResponseCode.invalidParameterValue.getErrorCode(), + ResponseCode.invalidParameterValue, ResponseCode.invalidParameterValue.getErrorMessage(), ERROR_CODE, (String) request.getRequest().get(JsonKey.NAME), @@ -78,7 +78,7 @@ public void validateUpdateCourseBatchRequest(Request request) { boolean bool = validateDateWithTodayDate(endDate); if (!bool) { throw new ProjectCommonException( - ResponseCode.invalidBatchEndDateError.getErrorCode(), + ResponseCode.invalidBatchEndDateError, ResponseCode.invalidBatchEndDateError.getErrorMessage(), ERROR_CODE); } @@ -95,7 +95,7 @@ public void validateAddUserToCourseBatchRequest(Request courseRequest) { private void validateBatchId(Request courseRequest) { if (courseRequest.getRequest().get(JsonKey.BATCH_ID) == null) { throw new ProjectCommonException( - ResponseCode.courseBatchIdRequired.getErrorCode(), + ResponseCode.courseBatchIdRequired, ResponseCode.courseBatchIdRequired.getErrorMessage(), ERROR_CODE); } @@ -104,7 +104,7 @@ private void validateBatchId(Request courseRequest) { public void validateUserId(Request courseRequest) { if (courseRequest.getRequest().get(JsonKey.USER_IDs) == null) { throw new ProjectCommonException( - ResponseCode.userIdRequired.getErrorCode(), + ResponseCode.userIdRequired, ResponseCode.userIdRequired.getErrorMessage(), ERROR_CODE); } @@ -119,7 +119,7 @@ private void validateEnrolmentType(Request request) { if (!(ProjectUtil.EnrolmentType.open.getVal().equalsIgnoreCase(enrolmentType) || ProjectUtil.EnrolmentType.inviteOnly.getVal().equalsIgnoreCase(enrolmentType))) { throw new ProjectCommonException( - ResponseCode.invalidParameterValue.getErrorCode(), + ResponseCode.invalidParameterValue, ResponseCode.invalidParameterValue.getErrorMessage(), ResponseCode.CLIENT_ERROR.getResponseCode(), enrolmentType, @@ -140,7 +140,7 @@ private void validateStartDate(String startDate) { cal2.setTime(todayDate); if (batchStartDate.before(todayDate)) { throw new ProjectCommonException( - ResponseCode.courseBatchStartDateError.getErrorCode(), + ResponseCode.courseBatchStartDateError, ResponseCode.courseBatchStartDateError.getErrorMessage(), ResponseCode.CLIENT_ERROR.getResponseCode()); } @@ -148,7 +148,7 @@ private void validateStartDate(String startDate) { throw e; } catch (Exception e) { throw new ProjectCommonException( - ResponseCode.dateFormatError.getErrorCode(), + ResponseCode.dateFormatError, ResponseCode.dateFormatError.getErrorMessage(), ResponseCode.CLIENT_ERROR.getResponseCode()); } @@ -166,13 +166,13 @@ private static void validateEndDate(String startDate, String endDate) { } } catch (Exception e) { throw new ProjectCommonException( - ResponseCode.dateFormatError.getErrorCode(), + ResponseCode.dateFormatError, ResponseCode.dateFormatError.getErrorMessage(), ResponseCode.CLIENT_ERROR.getResponseCode()); } if (StringUtils.isNotEmpty(endDate) && batchStartDate.getTime() >= batchEndDate.getTime()) { throw new ProjectCommonException( - ResponseCode.endDateError.getErrorCode(), + ResponseCode.endDateError, ResponseCode.endDateError.getErrorMessage(), ResponseCode.CLIENT_ERROR.getResponseCode()); } @@ -196,14 +196,14 @@ private static void validateEnrollmentEndDate( } catch (Exception e) { throw new ProjectCommonException( - ResponseCode.dateFormatError.getErrorCode(), + ResponseCode.dateFormatError, ResponseCode.dateFormatError.getErrorMessage(), ResponseCode.CLIENT_ERROR.getResponseCode()); } if (StringUtils.isNotEmpty(enrollmentEndDate) && batchStartDate.getTime() > batchenrollmentEndDate.getTime()) { throw new ProjectCommonException( - ResponseCode.enrollmentEndDateStartError.getErrorCode(), + ResponseCode.enrollmentEndDateStartError, ResponseCode.enrollmentEndDateStartError.getErrorMessage(), ResponseCode.CLIENT_ERROR.getResponseCode()); } @@ -211,7 +211,7 @@ private static void validateEnrollmentEndDate( && StringUtils.isNotEmpty(endDate) && batchEndDate.getTime() < batchenrollmentEndDate.getTime()) { throw new ProjectCommonException( - ResponseCode.enrollmentEndDateEndError.getErrorCode(), + ResponseCode.enrollmentEndDateEndError, ResponseCode.enrollmentEndDateEndError.getErrorMessage(), ResponseCode.CLIENT_ERROR.getResponseCode()); } @@ -221,7 +221,7 @@ private void validateCreatedForAndMentors(Request request) { if (request.getRequest().containsKey(JsonKey.COURSE_CREATED_FOR) && !(request.getRequest().get(JsonKey.COURSE_CREATED_FOR) instanceof List)) { throw new ProjectCommonException( - ResponseCode.dataTypeError.getErrorCode(), + ResponseCode.dataTypeError, ResponseCode.dataTypeError.getErrorMessage(), ERROR_CODE, JsonKey.COURSE_CREATED_FOR, @@ -231,7 +231,7 @@ private void validateCreatedForAndMentors(Request request) { if (request.getRequest().containsKey(JsonKey.MENTORS) && !(request.getRequest().get(JsonKey.MENTORS) instanceof List)) { throw new ProjectCommonException( - ResponseCode.dataTypeError.getErrorCode(), + ResponseCode.dataTypeError, ResponseCode.dataTypeError.getErrorMessage(), ERROR_CODE, JsonKey.MENTORS, @@ -245,7 +245,7 @@ private void validateUpdateBatchStartDate(String startDate) { format.parse(startDate); } catch (Exception e) { throw new ProjectCommonException( - ResponseCode.dateFormatError.getErrorCode(), + ResponseCode.dateFormatError, ResponseCode.dateFormatError.getErrorMessage(), ERROR_CODE); } @@ -268,7 +268,7 @@ private boolean validateDateWithTodayDate(String date) { } } catch (Exception e) { throw new ProjectCommonException( - ResponseCode.dateFormatError.getErrorCode(), + ResponseCode.dateFormatError, ResponseCode.dateFormatError.getErrorMessage(), ERROR_CODE); } @@ -293,13 +293,13 @@ private void validateUpdateBatchEndDate(Request request) { cal2.setTime(batchEndDate); } catch (Exception e) { throw new ProjectCommonException( - ResponseCode.dateFormatError.getErrorCode(), + ResponseCode.dateFormatError, ResponseCode.dateFormatError.getErrorMessage(), ERROR_CODE); } if (batchEndDate.before(batchStartDate)) { throw new ProjectCommonException( - ResponseCode.invalidBatchEndDateError.getErrorCode(), + ResponseCode.invalidBatchEndDateError, ResponseCode.invalidBatchEndDateError.getErrorMessage(), ERROR_CODE); } @@ -329,7 +329,7 @@ private boolean checkProgressStatus(int status) { public void validateGetParticipantsRequest(Request request) { if(MapUtils.isEmpty((Map) request.getRequest().get(JsonKey.BATCH))){ throw new ProjectCommonException( - ResponseCode.invalidRequestData.getErrorCode(), + ResponseCode.invalidRequestData, MessageFormat.format(ResponseCode.invalidRequestData.getErrorMessage(), JsonKey.BATCH), ResponseCode.CLIENT_ERROR.getResponseCode()); } diff --git a/service/app/controllers/coursemanagement/validator/CourseCreateRequestValidator.java b/service/app/controllers/coursemanagement/validator/CourseCreateRequestValidator.java index 0f2a88cea..0ab4e8e5a 100644 --- a/service/app/controllers/coursemanagement/validator/CourseCreateRequestValidator.java +++ b/service/app/controllers/coursemanagement/validator/CourseCreateRequestValidator.java @@ -1,9 +1,9 @@ package controllers.coursemanagement.validator; import org.apache.commons.lang3.StringUtils; -import org.sunbird.common.exception.ProjectCommonException; -import org.sunbird.common.request.Request; -import org.sunbird.common.responsecode.ResponseCode; +import org.sunbird.exception.ProjectCommonException; +import org.sunbird.request.Request; +import org.sunbird.response.ResponseCode; import org.sunbird.keys.SunbirdKey; import java.text.MessageFormat; diff --git a/service/app/controllers/exhaustjob/ExhaustJobController.java b/service/app/controllers/exhaustjob/ExhaustJobController.java index 3e2eb12f6..bc97a28b2 100644 --- a/service/app/controllers/exhaustjob/ExhaustJobController.java +++ b/service/app/controllers/exhaustjob/ExhaustJobController.java @@ -4,9 +4,9 @@ import org.apache.pekko.actor.ActorRef; import controllers.BaseController; import controllers.exhaustjob.validator.ExhaustJobRequestValidator; -import org.sunbird.common.models.util.ActorOperations; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.request.Request; +import org.sunbird.operations.lms.ActorOperations; +import org.sunbird.keys.JsonKey; +import org.sunbird.request.Request; import play.mvc.Http; import play.mvc.Result; diff --git a/service/app/controllers/exhaustjob/validator/ExhaustJobRequestValidator.java b/service/app/controllers/exhaustjob/validator/ExhaustJobRequestValidator.java index abbd3fbea..977f22bbd 100644 --- a/service/app/controllers/exhaustjob/validator/ExhaustJobRequestValidator.java +++ b/service/app/controllers/exhaustjob/validator/ExhaustJobRequestValidator.java @@ -2,10 +2,10 @@ import org.apache.commons.lang3.StringUtils; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.request.BaseRequestValidator; -import org.sunbird.common.request.Request; -import org.sunbird.common.responsecode.ResponseCode; +import org.sunbird.keys.JsonKey; +import org.sunbird.validators.BaseRequestValidator; +import org.sunbird.request.Request; +import org.sunbird.response.ResponseCode; public class ExhaustJobRequestValidator extends BaseRequestValidator { private static final int ERROR_CODE = ResponseCode.CLIENT_ERROR.getResponseCode(); diff --git a/service/app/controllers/group/GroupAggController.java b/service/app/controllers/group/GroupAggController.java index 14356aad4..55b201bdd 100644 --- a/service/app/controllers/group/GroupAggController.java +++ b/service/app/controllers/group/GroupAggController.java @@ -2,9 +2,9 @@ import org.apache.pekko.actor.ActorRef; import controllers.BaseController; -import org.sunbird.common.models.util.ActorOperations; -import org.sunbird.common.request.Request; -import org.sunbird.common.request.RequestValidator; +import org.sunbird.operations.lms.ActorOperations; +import org.sunbird.request.Request; +import org.sunbird.validators.RequestValidator; import play.mvc.Http; import play.mvc.Result; diff --git a/service/app/controllers/healthmanager/HealthController.java b/service/app/controllers/healthmanager/HealthController.java index d9587d6bb..066dc65c3 100644 --- a/service/app/controllers/healthmanager/HealthController.java +++ b/service/app/controllers/healthmanager/HealthController.java @@ -3,11 +3,11 @@ import org.apache.pekko.actor.ActorRef; import controllers.BaseController; -import org.sunbird.common.models.response.Response; -import org.sunbird.common.models.util.ActorOperations; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.models.util.ProjectUtil; -import org.sunbird.common.request.Request; +import org.sunbird.response.Response; +import org.sunbird.operations.lms.ActorOperations; +import org.sunbird.keys.JsonKey; +import org.sunbird.common.ProjectUtil; +import org.sunbird.request.Request; import play.mvc.Http; import play.mvc.Result; import util.Attrs; diff --git a/service/app/controllers/pagemanagement/PageController.java b/service/app/controllers/pagemanagement/PageController.java index 333a7186f..bd075e188 100644 --- a/service/app/controllers/pagemanagement/PageController.java +++ b/service/app/controllers/pagemanagement/PageController.java @@ -5,10 +5,10 @@ import com.fasterxml.jackson.databind.JsonNode; import controllers.BaseController; import org.apache.commons.lang3.StringUtils; -import org.sunbird.common.models.util.ActorOperations; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.request.Request; -import org.sunbird.common.request.RequestValidator; +import org.sunbird.operations.lms.ActorOperations; +import org.sunbird.keys.JsonKey; +import org.sunbird.request.Request; +import util.RequestValidator; import play.mvc.Http; import play.mvc.Result; import util.Attrs; diff --git a/service/app/controllers/qrcodedownload/QRCodeDownloadController.java b/service/app/controllers/qrcodedownload/QRCodeDownloadController.java index 731a13617..cebe6800a 100644 --- a/service/app/controllers/qrcodedownload/QRCodeDownloadController.java +++ b/service/app/controllers/qrcodedownload/QRCodeDownloadController.java @@ -3,8 +3,8 @@ import org.apache.pekko.actor.ActorRef; import controllers.BaseController; import controllers.qrcodedownload.validator.QRCodeDownloadRequestValidator; -import org.sunbird.common.models.util.ActorOperations; -import org.sunbird.common.request.Request; +import org.sunbird.operations.lms.ActorOperations; +import org.sunbird.request.Request; import play.mvc.Http; import play.mvc.Result; diff --git a/service/app/controllers/qrcodedownload/validator/QRCodeDownloadRequestValidator.java b/service/app/controllers/qrcodedownload/validator/QRCodeDownloadRequestValidator.java index b35638b0f..85a866d6c 100644 --- a/service/app/controllers/qrcodedownload/validator/QRCodeDownloadRequestValidator.java +++ b/service/app/controllers/qrcodedownload/validator/QRCodeDownloadRequestValidator.java @@ -1,9 +1,9 @@ package controllers.qrcodedownload.validator; -import org.sunbird.common.exception.ProjectCommonException; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.request.Request; -import org.sunbird.common.responsecode.ResponseCode; +import org.sunbird.exception.ProjectCommonException; +import org.sunbird.keys.JsonKey; +import org.sunbird.request.Request; +import org.sunbird.response.ResponseCode; import java.util.List; import java.util.Map; diff --git a/service/app/controllers/search/SearchController.java b/service/app/controllers/search/SearchController.java index 343ca2bb0..b48d0bea0 100644 --- a/service/app/controllers/search/SearchController.java +++ b/service/app/controllers/search/SearchController.java @@ -4,10 +4,10 @@ import org.apache.pekko.actor.ActorRef; import com.fasterxml.jackson.databind.JsonNode; import controllers.BaseController; -import org.sunbird.common.models.util.ActorOperations; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.request.Request; -import org.sunbird.common.request.RequestValidator; +import org.sunbird.operations.lms.ActorOperations; +import org.sunbird.keys.JsonKey; +import org.sunbird.request.Request; +import org.sunbird.validators.RequestValidator; import play.mvc.Http; import play.mvc.Result; import util.Attrs; diff --git a/service/app/filters/AccessLogFilter.java b/service/app/filters/AccessLogFilter.java index 3c3f27c94..f9aea9ee4 100644 --- a/service/app/filters/AccessLogFilter.java +++ b/service/app/filters/AccessLogFilter.java @@ -4,8 +4,8 @@ import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.commons.lang3.StringUtils; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.models.util.LoggerUtil; +import org.sunbird.keys.JsonKey; +import org.sunbird.logging.LoggerUtil; import org.sunbird.telemetry.util.TelemetryEvents; import org.sunbird.telemetry.util.TelemetryWriter; import play.libs.streams.Accumulator; @@ -43,7 +43,7 @@ public EssentialAction apply(EssentialAction next) { long endTime = System.currentTimeMillis(); long requestTime = endTime - startTime; try { - org.sunbird.common.request.Request req = new org.sunbird.common.request.Request(); + org.sunbird.request.Request req = new org.sunbird.request.Request(); Map params = new WeakHashMap<>(); params.put(JsonKey.URL, request.uri()); params.put(JsonKey.METHOD, request.method()); diff --git a/service/app/filters/CustomGzipFilter.java b/service/app/filters/CustomGzipFilter.java index 2f3561008..f04922dc6 100644 --- a/service/app/filters/CustomGzipFilter.java +++ b/service/app/filters/CustomGzipFilter.java @@ -2,9 +2,9 @@ import org.apache.pekko.stream.Materializer; import org.apache.http.HttpHeaders; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.models.util.ProjectUtil; -import org.sunbird.common.request.HeaderParam; +import org.sunbird.keys.JsonKey; +import org.sunbird.common.ProjectUtil; +import org.sunbird.request.HeaderParam; import play.filters.gzip.GzipFilter; import play.filters.gzip.GzipFilterConfig; import play.mvc.EssentialAction; diff --git a/service/app/filters/ResponseFilter.scala b/service/app/filters/ResponseFilter.scala index d41d04733..b228ab004 100644 --- a/service/app/filters/ResponseFilter.scala +++ b/service/app/filters/ResponseFilter.scala @@ -3,9 +3,9 @@ package filters import org.apache.pekko.stream.Materializer import org.apache.pekko.util.ByteString import org.apache.commons.lang.StringUtils -import org.sunbird.common.models.util.JsonKey -import org.sunbird.common.models.util.JsonKey.{CLOUD_STORAGE_CNAME_URL, CLOUD_STORE_BASE_PATH, CONTENT_CLOUD_STORAGE_CONTAINER} -import org.sunbird.common.models.util.ProjectUtil.getConfigValue +import org.sunbird.keys.JsonKey +import org.sunbird.keys.JsonKey.{CLOUD_STORAGE_CNAME_URL, CLOUD_STORE_BASE_PATH, CONTENT_CLOUD_STORAGE_CONTAINER} +import org.sunbird.common.ProjectUtil.getConfigValue import play.api.Logging import play.api.http.HttpEntity.Strict import play.api.mvc.{Filter, RequestHeader, Result} diff --git a/service/app/mapper/RequestMapper.java b/service/app/mapper/RequestMapper.java index 79df14868..6620d8a22 100644 --- a/service/app/mapper/RequestMapper.java +++ b/service/app/mapper/RequestMapper.java @@ -4,10 +4,10 @@ import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; -import org.sunbird.common.models.util.LoggerUtil; -import org.sunbird.common.models.util.ProjectUtil; -import org.sunbird.common.request.Request; -import org.sunbird.common.responsecode.ResponseCode; +import org.sunbird.logging.LoggerUtil; +import org.sunbird.common.ProjectUtil; +import org.sunbird.request.Request; +import org.sunbird.response.ResponseCode; import play.libs.Json; import java.util.ArrayList; import java.util.HashMap; diff --git a/service/app/modules/ApplicationStart.java b/service/app/modules/ApplicationStart.java index d98f564bd..9d5acd7a0 100644 --- a/service/app/modules/ApplicationStart.java +++ b/service/app/modules/ApplicationStart.java @@ -1,9 +1,9 @@ package modules; import org.sunbird.auth.verifier.KeyManager; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.models.util.LoggerUtil; -import org.sunbird.common.models.util.ProjectUtil; +import org.sunbird.keys.JsonKey; +import org.sunbird.logging.LoggerUtil; +import org.sunbird.common.ProjectUtil; import org.sunbird.learner.util.ContentSearchMock; import org.sunbird.learner.util.SchedulerManager; import org.sunbird.learner.util.Util; diff --git a/service/app/modules/ErrorHandler.java b/service/app/modules/ErrorHandler.java index 5eb231a95..4d14f1aaf 100644 --- a/service/app/modules/ErrorHandler.java +++ b/service/app/modules/ErrorHandler.java @@ -2,10 +2,10 @@ import com.typesafe.config.Config; import controllers.BaseController; -import org.sunbird.common.exception.ProjectCommonException; -import org.sunbird.common.models.response.Response; -import org.sunbird.common.models.util.LoggerUtil; -import org.sunbird.common.responsecode.ResponseCode; +import org.sunbird.exception.ProjectCommonException; +import org.sunbird.response.Response; +import org.sunbird.logging.LoggerUtil; +import org.sunbird.response.ResponseCode; import play.Environment; import play.api.OptionalSourceMapper; import play.api.routing.Router; diff --git a/service/app/modules/OnRequestHandler.java b/service/app/modules/OnRequestHandler.java index 48b24ae1e..5651d3742 100644 --- a/service/app/modules/OnRequestHandler.java +++ b/service/app/modules/OnRequestHandler.java @@ -7,14 +7,14 @@ import org.apache.commons.lang3.StringUtils; import org.sunbird.auth.verifier.AccessTokenValidator; import org.sunbird.cache.platform.Platform; -import org.sunbird.common.exception.ProjectCommonException; -import org.sunbird.common.models.response.Response; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.models.util.LoggerUtil; -import org.sunbird.common.models.util.ProjectUtil; -import org.sunbird.common.request.HeaderParam; -import org.sunbird.common.responsecode.ResponseCode; -import org.sunbird.common.util.JsonUtil; +import org.sunbird.exception.ProjectCommonException; +import org.sunbird.response.Response; +import org.sunbird.keys.JsonKey; +import org.sunbird.logging.LoggerUtil; +import org.sunbird.common.ProjectUtil; +import org.sunbird.request.HeaderParam; +import org.sunbird.response.ResponseCode; +import org.sunbird.utils.JsonUtil; import play.http.ActionCreator; import play.libs.Json; import play.mvc.Action; diff --git a/service/app/util/Attrs.java b/service/app/util/Attrs.java index e63775602..dac279a35 100644 --- a/service/app/util/Attrs.java +++ b/service/app/util/Attrs.java @@ -1,6 +1,6 @@ package util; -import org.sunbird.common.models.util.JsonKey; +import org.sunbird.keys.JsonKey; import play.libs.typedmap.TypedKey; public class Attrs { diff --git a/service/app/util/AuthenticationHelper.java b/service/app/util/AuthenticationHelper.java index 57109bfa5..f01168feb 100644 --- a/service/app/util/AuthenticationHelper.java +++ b/service/app/util/AuthenticationHelper.java @@ -2,9 +2,9 @@ import org.sunbird.auth.verifier.Base64Util; import org.sunbird.cassandra.CassandraOperation; -import org.sunbird.common.models.response.Response; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.models.util.LoggerUtil; +import org.sunbird.response.Response; +import org.sunbird.keys.JsonKey; +import org.sunbird.logging.LoggerUtil; import org.sunbird.helper.ServiceFactory; import org.sunbird.learner.util.Util; import org.sunbird.learner.util.Util.DbInfo; diff --git a/service/app/util/RequestInterceptor.java b/service/app/util/RequestInterceptor.java index 8e72f563b..934e8ad09 100644 --- a/service/app/util/RequestInterceptor.java +++ b/service/app/util/RequestInterceptor.java @@ -2,9 +2,9 @@ import org.apache.commons.lang3.StringUtils; import org.sunbird.auth.verifier.AccessTokenValidator; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.models.util.LoggerUtil; -import org.sunbird.common.request.HeaderParam; +import org.sunbird.keys.JsonKey; +import org.sunbird.logging.LoggerUtil; +import org.sunbird.request.HeaderParam; import play.mvc.Http; import java.util.ArrayList; diff --git a/service/app/util/RequestValidator.java b/service/app/util/RequestValidator.java index 8146de6df..3b330ff76 100644 --- a/service/app/util/RequestValidator.java +++ b/service/app/util/RequestValidator.java @@ -3,13 +3,18 @@ import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang3.StringUtils; -import org.sunbird.common.exception.ProjectCommonException; -import org.sunbird.common.models.util.*; -import org.sunbird.common.models.util.ProjectUtil.ProgressStatus; -import org.sunbird.common.models.util.ProjectUtil.Source; -import org.sunbird.common.request.Request; -import org.sunbird.common.responsecode.ResponseCode; -import org.sunbird.common.responsecode.ResponseMessage; +import org.sunbird.exception.ProjectCommonException; +import org.sunbird.telemetry.dto.*; +import org.sunbird.common.ProjectUtil.ProgressStatus; +import org.sunbird.common.ProjectUtil.Source; +import org.sunbird.keys.JsonKey; +import org.sunbird.common.ProjectUtil; +import org.sunbird.common.PropertiesCache; +import org.sunbird.utils.StringFormatter; +import org.sunbird.request.Request; +import org.sunbird.response.ResponseCode; +import org.sunbird.response.ResponseMessage; +import org.sunbird.logging.LoggerUtil; import java.text.MessageFormat; import java.text.SimpleDateFormat; @@ -49,7 +54,7 @@ public static void validateUpdateContent(Request contentRequestDto) { "yyyy-MM-dd HH:mm:ss:SSSZ", (String) map.get(JsonKey.LAST_UPDATED_TIME)); if (!bool) { throw new ProjectCommonException( - ResponseCode.dateFormatError.getErrorCode(), + ResponseCode.dateFormatError, ResponseCode.dateFormatError.getErrorMessage(), ERROR_CODE); } @@ -60,7 +65,7 @@ public static void validateUpdateContent(Request contentRequestDto) { "yyyy-MM-dd HH:mm:ss:SSSZ", (String) map.get(JsonKey.LAST_COMPLETED_TIME)); if (!bool) { throw new ProjectCommonException( - ResponseCode.dateFormatError.getErrorCode(), + ResponseCode.dateFormatError, ResponseCode.dateFormatError.getErrorMessage(), ERROR_CODE); } @@ -69,7 +74,7 @@ public static void validateUpdateContent(Request contentRequestDto) { map.put(JsonKey.COURSE_ID, map.get(courseId)); if (StringUtils.isBlank((String) map.get(JsonKey.COURSE_ID))) { throw new ProjectCommonException( - ResponseCode.courseIdRequired.getErrorCode(), + ResponseCode.courseIdRequired, ResponseCode.courseIdRequiredError.getErrorMessage(), ERROR_CODE); } @@ -77,20 +82,20 @@ public static void validateUpdateContent(Request contentRequestDto) { if (null == map.get(JsonKey.CONTENT_ID)) { throw new ProjectCommonException( - ResponseCode.contentIdRequired.getErrorCode(), + ResponseCode.contentIdRequired, ResponseCode.contentIdRequiredError.getErrorMessage(), ERROR_CODE); } if (ProjectUtil.isNull(map.get(JsonKey.STATUS))) { throw new ProjectCommonException( - ResponseCode.contentStatusRequired.getErrorCode(), + ResponseCode.contentStatusRequired, ResponseCode.contentStatusRequired.getErrorMessage(), ERROR_CODE); } } else { throw new ProjectCommonException( - ResponseCode.contentIdRequired.getErrorCode(), + ResponseCode.contentIdRequired, ResponseCode.contentIdRequiredError.getErrorMessage(), ERROR_CODE); } @@ -102,7 +107,7 @@ public static void validateUpdateContent(Request contentRequestDto) { for (Map map : assessmentData) { if (!map.containsKey(JsonKey.ASSESSMENT_TS)) { throw new ProjectCommonException( - ResponseCode.assessmentAttemptDateRequired.getErrorCode(), + ResponseCode.assessmentAttemptDateRequired, ResponseCode.assessmentAttemptDateRequired.getErrorMessage(), ERROR_CODE); } @@ -110,7 +115,7 @@ public static void validateUpdateContent(Request contentRequestDto) { if (!map.containsKey(JsonKey.COURSE_ID) || StringUtils.isBlank((String) map.get(JsonKey.COURSE_ID))) { throw new ProjectCommonException( - ResponseCode.courseIdRequired.getErrorCode(), + ResponseCode.courseIdRequired, ResponseCode.courseIdRequiredError.getErrorMessage(), ERROR_CODE); } @@ -118,7 +123,7 @@ public static void validateUpdateContent(Request contentRequestDto) { if (!map.containsKey(JsonKey.CONTENT_ID) || StringUtils.isBlank((String) map.get(JsonKey.CONTENT_ID))) { throw new ProjectCommonException( - ResponseCode.contentIdRequired.getErrorCode(), + ResponseCode.contentIdRequired, ResponseCode.contentIdRequiredError.getErrorMessage(), ERROR_CODE); } @@ -126,7 +131,7 @@ public static void validateUpdateContent(Request contentRequestDto) { if (!map.containsKey(JsonKey.BATCH_ID) || StringUtils.isBlank((String) map.get(JsonKey.BATCH_ID))) { throw new ProjectCommonException( - ResponseCode.courseBatchIdRequired.getErrorCode(), + ResponseCode.courseBatchIdRequired, ResponseCode.courseBatchIdRequired.getErrorMessage(), ERROR_CODE); } @@ -134,7 +139,7 @@ public static void validateUpdateContent(Request contentRequestDto) { if (!map.containsKey(JsonKey.USER_ID) || StringUtils.isBlank((String) map.get(JsonKey.USER_ID))) { throw new ProjectCommonException( - ResponseCode.userIdRequired.getErrorCode(), + ResponseCode.userIdRequired, ResponseCode.userIdRequired.getErrorMessage(), ERROR_CODE); } @@ -142,14 +147,14 @@ public static void validateUpdateContent(Request contentRequestDto) { if (!map.containsKey(JsonKey.ATTEMPT_ID) || StringUtils.isBlank((String) map.get(JsonKey.ATTEMPT_ID))) { throw new ProjectCommonException( - ResponseCode.attemptIdRequired.getErrorCode(), + ResponseCode.attemptIdRequired, ResponseCode.attemptIdRequired.getErrorMessage(), ERROR_CODE); } if (!map.containsKey(JsonKey.EVENTS)) { throw new ProjectCommonException( - ResponseCode.eventsRequired.getErrorCode(), + ResponseCode.eventsRequired, ResponseCode.eventsRequired.getErrorMessage(), ERROR_CODE); } @@ -160,20 +165,20 @@ public static void validateUpdateContent(Request contentRequestDto) { contentRequestDto.getRequest().put(JsonKey.COURSE_ID, contentRequestDto.getOrDefault(JsonKey.COURSE_ID, contentRequestDto.getOrDefault(JsonKey.COLLECTION_ID, ""))); if (StringUtils.isBlank((String) contentRequestDto.getOrDefault(JsonKey.COURSE_ID, ""))) { throw new ProjectCommonException( - ResponseCode.courseIdRequired.getErrorCode(), + ResponseCode.courseIdRequired, ResponseCode.courseIdRequiredError.getErrorMessage(), ERROR_CODE); } if (StringUtils.isBlank((String) contentRequestDto.getOrDefault(JsonKey.BATCH_ID, ""))) { throw new ProjectCommonException( - ResponseCode.courseBatchIdRequired.getErrorCode(), + ResponseCode.courseBatchIdRequired, ResponseCode.courseBatchIdRequired.getErrorMessage(), ERROR_CODE); } if (StringUtils.isBlank((String) contentRequestDto.getOrDefault(JsonKey.USER_ID, ""))) { throw new ProjectCommonException( - ResponseCode.userIdRequired.getErrorCode(), + ResponseCode.userIdRequired, ResponseCode.userIdRequired.getErrorMessage(), ERROR_CODE); } @@ -188,19 +193,19 @@ public static void validateUpdateContent(Request contentRequestDto) { public static void validateGetPageData(Request request) { if (request == null || (StringUtils.isBlank((String) request.get(JsonKey.SOURCE)))) { throw new ProjectCommonException( - ResponseCode.sourceRequired.getErrorCode(), + ResponseCode.sourceRequired, ResponseCode.sourceRequired.getErrorMessage(), ERROR_CODE); } if (!validPageSourceType((String) request.get(JsonKey.SOURCE))) { throw new ProjectCommonException( - ResponseCode.invalidPageSource.getErrorCode(), + ResponseCode.invalidPageSource, ResponseCode.invalidPageSource.getErrorMessage(), ERROR_CODE); } if (StringUtils.isBlank((String) request.get(JsonKey.PAGE_NAME))) { throw new ProjectCommonException( - ResponseCode.pageNameRequired.getErrorCode(), + ResponseCode.pageNameRequired, ResponseCode.pageNameRequired.getErrorMessage(), ERROR_CODE); } @@ -227,13 +232,13 @@ public static void validateAddBatchCourse(Request courseRequest) { if (courseRequest.getRequest().get(JsonKey.BATCH_ID) == null) { throw new ProjectCommonException( - ResponseCode.courseBatchIdRequired.getErrorCode(), + ResponseCode.courseBatchIdRequired, ResponseCode.courseBatchIdRequired.getErrorMessage(), ERROR_CODE); } if (courseRequest.getRequest().get(JsonKey.USER_IDs) == null) { throw new ProjectCommonException( - ResponseCode.userIdRequired.getErrorCode(), + ResponseCode.userIdRequired, ResponseCode.userIdRequired.getErrorMessage(), ERROR_CODE); } @@ -248,7 +253,7 @@ public static void validateGetBatchCourse(Request courseRequest) { if (courseRequest.getRequest().get(JsonKey.BATCH_ID) == null) { throw new ProjectCommonException( - ResponseCode.courseBatchIdRequired.getErrorCode(), + ResponseCode.courseBatchIdRequired, ResponseCode.courseBatchIdRequired.getErrorMessage(), ERROR_CODE); } @@ -263,7 +268,7 @@ public static void validateUpdateCourse(Request request) { if (request.getRequest().get(JsonKey.COURSE_ID) == null) { throw new ProjectCommonException( - ResponseCode.courseIdRequired.getErrorCode(), + ResponseCode.courseIdRequired, ResponseCode.courseIdRequired.getErrorMessage(), ERROR_CODE); } @@ -277,7 +282,7 @@ public static void validateUpdateCourse(Request request) { public static void validatePublishCourse(Request request) { if (request.getRequest().get(JsonKey.COURSE_ID) == null) { throw new ProjectCommonException( - ResponseCode.courseIdRequiredError.getErrorCode(), + ResponseCode.courseIdRequiredError, ResponseCode.courseIdRequiredError.getErrorMessage(), ERROR_CODE); } @@ -291,7 +296,7 @@ public static void validatePublishCourse(Request request) { public static void validateDeleteCourse(Request request) { if (request.getRequest().get(JsonKey.COURSE_ID) == null) { throw new ProjectCommonException( - ResponseCode.courseIdRequiredError.getErrorCode(), + ResponseCode.courseIdRequiredError, ResponseCode.courseIdRequiredError.getErrorMessage(), ERROR_CODE); } @@ -309,7 +314,7 @@ public static void validateCreateSection(Request request) { ? request.getRequest().get(JsonKey.SECTION_NAME) : ""))) { throw new ProjectCommonException( - ResponseCode.sectionNameRequired.getErrorCode(), + ResponseCode.sectionNameRequired, ResponseCode.sectionNameRequired.getErrorMessage(), ERROR_CODE); } @@ -319,7 +324,7 @@ public static void validateCreateSection(Request request) { ? request.getRequest().get(JsonKey.SECTION_DATA_TYPE) : ""))) { throw new ProjectCommonException( - ResponseCode.sectionDataTypeRequired.getErrorCode(), + ResponseCode.sectionDataTypeRequired, ResponseCode.sectionDataTypeRequired.getErrorMessage(), ERROR_CODE); } @@ -338,7 +343,7 @@ public static void validateUpdateSection(Request request) { ? request.getRequest().get(JsonKey.SECTION_NAME) : ""))) { throw new ProjectCommonException( - ResponseCode.sectionNameRequired.getErrorCode(), + ResponseCode.sectionNameRequired, ResponseCode.sectionNameRequired.getErrorMessage(), ERROR_CODE); } @@ -348,7 +353,7 @@ public static void validateUpdateSection(Request request) { ? request.getRequest().get(JsonKey.ID) : ""))) { throw new ProjectCommonException( - ResponseCode.sectionIdRequired.getErrorCode(), + ResponseCode.sectionIdRequired, ResponseCode.sectionIdRequired.getErrorMessage(), ERROR_CODE); } @@ -359,7 +364,7 @@ public static void validateUpdateSection(Request request) { ? request.getRequest().get(JsonKey.SECTION_DATA_TYPE) : ""))) { throw new ProjectCommonException( - ResponseCode.sectionDataTypeRequired.getErrorCode(), + ResponseCode.sectionDataTypeRequired, ResponseCode.sectionDataTypeRequired.getErrorMessage(), ERROR_CODE); } @@ -377,7 +382,7 @@ public static void validateCreatePage(Request request) { ? request.getRequest().get(JsonKey.PAGE_NAME) : ""))) { throw new ProjectCommonException( - ResponseCode.pageNameRequired.getErrorCode(), + ResponseCode.pageNameRequired, ResponseCode.pageNameRequired.getErrorMessage(), ERROR_CODE); } @@ -396,7 +401,7 @@ public static void validateUpdatepage(Request request) { ? request.getRequest().get(JsonKey.PAGE_NAME) : ""))) { throw new ProjectCommonException( - ResponseCode.pageNameRequired.getErrorCode(), + ResponseCode.pageNameRequired, ResponseCode.pageNameRequired.getErrorMessage(), ERROR_CODE); } @@ -406,7 +411,7 @@ public static void validateUpdatepage(Request request) { ? request.getRequest().get(JsonKey.ID) : ""))) { throw new ProjectCommonException( - ResponseCode.pageIdRequired.getErrorCode(), + ResponseCode.pageIdRequired, ResponseCode.pageIdRequired.getErrorMessage(), ERROR_CODE); } @@ -422,7 +427,7 @@ public static void validateUploadUser(Map reqObj) { && (StringUtils.isBlank((String) reqObj.get(JsonKey.ORG_EXTERNAL_ID)) || StringUtils.isBlank((String) reqObj.get(JsonKey.ORG_PROVIDER)))) { throw new ProjectCommonException( - ResponseCode.mandatoryParamsMissing.getErrorCode(), + ResponseCode.mandatoryParamsMissing, ProjectUtil.formatMessage( ResponseCode.mandatoryParamsMissing.getErrorMessage(), (ProjectUtil.formatMessage( @@ -436,7 +441,7 @@ public static void validateUploadUser(Map reqObj) { } if (null == reqObj.get(JsonKey.FILE)) { throw new ProjectCommonException( - ResponseCode.mandatoryParamsMissing.getErrorCode(), + ResponseCode.mandatoryParamsMissing, ProjectUtil.formatMessage( ResponseCode.mandatoryParamsMissing.getErrorMessage(), JsonKey.FILE), ERROR_CODE); @@ -456,13 +461,13 @@ public static void validateUploadUser(Map reqObj) { public static void validateCreateBatchReq(Request request) { if (StringUtils.isBlank((String) request.getRequest().get(JsonKey.COURSE_ID))) { throw new ProjectCommonException( - ResponseCode.invalidCourseId.getErrorCode(), + ResponseCode.invalidCourseId, ResponseCode.invalidCourseId.getErrorMessage(), ERROR_CODE); } if (StringUtils.isBlank((String) request.getRequest().get(JsonKey.NAME))) { throw new ProjectCommonException( - ResponseCode.courseNameRequired.getErrorCode(), + ResponseCode.courseNameRequired, ResponseCode.courseNameRequired.getErrorMessage(), ERROR_CODE); } @@ -476,7 +481,7 @@ public static void validateCreateBatchReq(Request request) { if (request.getRequest().containsKey(JsonKey.COURSE_CREATED_FOR) && !(request.getRequest().get(JsonKey.COURSE_CREATED_FOR) instanceof List)) { throw new ProjectCommonException( - ResponseCode.dataTypeError.getErrorCode(), + ResponseCode.dataTypeError, ResponseCode.dataTypeError.getErrorMessage(), ERROR_CODE); } @@ -497,7 +502,7 @@ public static void validateUpdateCourseBatchReq(Request request) { boolean status = validateBatchStatus(request); if (!status) { throw new ProjectCommonException( - ResponseCode.progressStatusError.getErrorCode(), + ResponseCode.progressStatusError, ResponseCode.progressStatusError.getErrorMessage(), ERROR_CODE); } @@ -505,7 +510,7 @@ public static void validateUpdateCourseBatchReq(Request request) { if (request.getRequest().containsKey(JsonKey.NAME) && StringUtils.isEmpty((String) request.getRequest().get(JsonKey.NAME))) { throw new ProjectCommonException( - ResponseCode.courseNameRequired.getErrorCode(), + ResponseCode.courseNameRequired, ResponseCode.courseNameRequired.getErrorMessage(), ERROR_CODE); } @@ -522,7 +527,7 @@ public static void validateUpdateCourseBatchReq(Request request) { boolean bool = validateDateWithTodayDate(endDate); if (!bool) { throw new ProjectCommonException( - ResponseCode.invalidBatchEndDateError.getErrorCode(), + ResponseCode.invalidBatchEndDateError, ResponseCode.invalidBatchEndDateError.getErrorMessage(), ERROR_CODE); } @@ -531,7 +536,7 @@ public static void validateUpdateCourseBatchReq(Request request) { if (request.getRequest().containsKey(JsonKey.COURSE_CREATED_FOR) && !(request.getRequest().get(JsonKey.COURSE_CREATED_FOR) instanceof List)) { throw new ProjectCommonException( - ResponseCode.dataTypeError.getErrorCode(), + ResponseCode.dataTypeError, ResponseCode.dataTypeError.getErrorMessage(), ERROR_CODE); } @@ -539,7 +544,7 @@ public static void validateUpdateCourseBatchReq(Request request) { if (request.getRequest().containsKey(JsonKey.MENTORS) && !(request.getRequest().get(JsonKey.MENTORS) instanceof List)) { throw new ProjectCommonException( - ResponseCode.dataTypeError.getErrorCode(), + ResponseCode.dataTypeError, ResponseCode.dataTypeError.getErrorMessage(), ERROR_CODE); } @@ -552,13 +557,13 @@ private static void validateUpdateBatchStartDate(String startDate) { format.parse(startDate); } catch (Exception e) { throw new ProjectCommonException( - ResponseCode.dateFormatError.getErrorCode(), + ResponseCode.dateFormatError, ResponseCode.dateFormatError.getErrorMessage(), ERROR_CODE); } } else { throw new ProjectCommonException( - ResponseCode.courseBatchStartDateRequired.getErrorCode(), + ResponseCode.courseBatchStartDateRequired, ResponseCode.courseBatchStartDateRequired.getErrorMessage(), ERROR_CODE); } @@ -593,13 +598,13 @@ private static void validateUpdateBatchEndDate(Request request) { cal2.setTime(batchEndDate); } catch (Exception e) { throw new ProjectCommonException( - ResponseCode.dateFormatError.getErrorCode(), + ResponseCode.dateFormatError, ResponseCode.dateFormatError.getErrorMessage(), ERROR_CODE); } if (batchEndDate.before(batchStartDate)) { throw new ProjectCommonException( - ResponseCode.invalidBatchEndDateError.getErrorCode(), + ResponseCode.invalidBatchEndDateError, ResponseCode.invalidBatchEndDateError.getErrorMessage(), ERROR_CODE); } @@ -623,7 +628,7 @@ private static boolean validateDateWithTodayDate(String date) { } } catch (Exception e) { throw new ProjectCommonException( - ResponseCode.dateFormatError.getErrorCode(), + ResponseCode.dateFormatError, ResponseCode.dateFormatError.getErrorMessage(), ERROR_CODE); } @@ -634,14 +639,14 @@ private static boolean validateDateWithTodayDate(String date) { public static void validateEnrolmentType(String enrolmentType) { if (StringUtils.isBlank(enrolmentType)) { throw new ProjectCommonException( - ResponseCode.enrolmentTypeRequired.getErrorCode(), + ResponseCode.enrolmentTypeRequired, ResponseCode.enrolmentTypeRequired.getErrorMessage(), ERROR_CODE); } if (!(ProjectUtil.EnrolmentType.open.getVal().equalsIgnoreCase(enrolmentType) || ProjectUtil.EnrolmentType.inviteOnly.getVal().equalsIgnoreCase(enrolmentType))) { throw new ProjectCommonException( - ResponseCode.enrolmentIncorrectValue.getErrorCode(), + ResponseCode.enrolmentIncorrectValue, ResponseCode.enrolmentIncorrectValue.getErrorMessage(), ERROR_CODE); } @@ -653,7 +658,7 @@ private static void validateStartDate(String startDate) { format.setLenient(false); if (StringUtils.isBlank(startDate)) { throw new ProjectCommonException( - ResponseCode.courseBatchStartDateRequired.getErrorCode(), + ResponseCode.courseBatchStartDateRequired, ResponseCode.courseBatchStartDateRequired.getErrorMessage(), ERROR_CODE); } @@ -666,7 +671,7 @@ private static void validateStartDate(String startDate) { cal2.setTime(todayDate); if (batchStartDate.before(todayDate)) { throw new ProjectCommonException( - ResponseCode.courseBatchStartDateError.getErrorCode(), + ResponseCode.courseBatchStartDateError, ResponseCode.courseBatchStartDateError.getErrorMessage(), ERROR_CODE); } @@ -674,7 +679,7 @@ private static void validateStartDate(String startDate) { throw e; } catch (Exception e) { throw new ProjectCommonException( - ResponseCode.dateFormatError.getErrorCode(), + ResponseCode.dateFormatError, ResponseCode.dateFormatError.getErrorMessage(), ERROR_CODE); } @@ -692,13 +697,13 @@ private static void validateEndDate(String startDate, String endDate) { } } catch (Exception e) { throw new ProjectCommonException( - ResponseCode.dateFormatError.getErrorCode(), + ResponseCode.dateFormatError, ResponseCode.dateFormatError.getErrorMessage(), ERROR_CODE); } if (StringUtils.isNotEmpty(endDate) && batchStartDate.getTime() >= batchEndDate.getTime()) { throw new ProjectCommonException( - ResponseCode.endDateError.getErrorCode(), + ResponseCode.endDateError, ResponseCode.endDateError.getErrorMessage(), ERROR_CODE); } @@ -709,7 +714,7 @@ public static void validateSyncRequest(Request request) { if ((null != operation) && (!operation.equalsIgnoreCase("keycloak"))) { if (request.getRequest().get(JsonKey.OBJECT_TYPE) == null) { throw new ProjectCommonException( - ResponseCode.dataTypeError.getErrorCode(), + ResponseCode.dataTypeError, ResponseCode.dataTypeError.getErrorMessage(), ERROR_CODE); } @@ -721,7 +726,7 @@ public static void validateSyncRequest(Request request) { })); if (!list.contains(request.getRequest().get(JsonKey.OBJECT_TYPE))) { throw new ProjectCommonException( - ResponseCode.invalidObjectType.getErrorCode(), + ResponseCode.invalidObjectType, ResponseCode.invalidObjectType.getErrorMessage(), ERROR_CODE); } @@ -738,7 +743,7 @@ public static void validateUpdateSystemSettingsRequest(Request request) { for (String str : request.getRequest().keySet()) { if (!list.contains(str)) { throw new ProjectCommonException( - ResponseCode.invalidPropertyError.getErrorCode(), + ResponseCode.invalidPropertyError, MessageFormat.format(ResponseCode.invalidPropertyError.getErrorMessage(), str), ERROR_CODE); } @@ -748,13 +753,13 @@ public static void validateUpdateSystemSettingsRequest(Request request) { public static void validateSendMail(Request request) { if (StringUtils.isBlank((String) request.getRequest().get(JsonKey.SUBJECT))) { throw new ProjectCommonException( - ResponseCode.emailSubjectError.getErrorCode(), + ResponseCode.emailSubjectError, ResponseCode.emailSubjectError.getErrorMessage(), ERROR_CODE); } if (StringUtils.isBlank((String) request.getRequest().get(JsonKey.BODY))) { throw new ProjectCommonException( - ResponseCode.emailBodyError.getErrorCode(), + ResponseCode.emailBodyError, ResponseCode.emailBodyError.getErrorMessage(), ERROR_CODE); } @@ -766,7 +771,7 @@ public static void validateSendMail(Request request) { && CollectionUtils.isEmpty( (List) (request.getRequest().get(JsonKey.RECIPIENT_PHONES)))) { throw new ProjectCommonException( - ResponseCode.mandatoryParamsMissing.getErrorCode(), + ResponseCode.mandatoryParamsMissing, MessageFormat.format( ResponseCode.mandatoryParamsMissing.getErrorMessage(), StringFormatter.joinByOr( @@ -783,7 +788,7 @@ public static void validateFileUpload(Request reqObj) { if (StringUtils.isBlank((String) reqObj.get(JsonKey.CONTAINER))) { throw new ProjectCommonException( - ResponseCode.storageContainerNameMandatory.getErrorCode(), + ResponseCode.storageContainerNameMandatory, ResponseCode.storageContainerNameMandatory.getErrorMessage(), ERROR_CODE); } @@ -792,17 +797,17 @@ public static void validateFileUpload(Request reqObj) { /** @param reqObj */ public static void validateCreateOrgType(Request reqObj) { if (StringUtils.isBlank((String) reqObj.getRequest().get(JsonKey.NAME))) { - throw createExceptionInstance(ResponseCode.orgTypeMandatory.getErrorCode()); + throw createExceptionInstance(ResponseCode.orgTypeMandatory); } } /** @param reqObj */ public static void validateUpdateOrgType(Request reqObj) { if (StringUtils.isBlank((String) reqObj.getRequest().get(JsonKey.NAME))) { - throw createExceptionInstance(ResponseCode.orgTypeMandatory.getErrorCode()); + throw createExceptionInstance(ResponseCode.orgTypeMandatory); } if (StringUtils.isBlank((String) reqObj.getRequest().get(JsonKey.ID))) { - throw createExceptionInstance(ResponseCode.orgTypeIdRequired.getErrorCode()); + throw createExceptionInstance(ResponseCode.orgTypeIdRequired); } } @@ -815,26 +820,26 @@ public static void validateUpdateOrgType(Request reqObj) { public static void validateNote(Request request) { if (StringUtils.isBlank((String) request.get(JsonKey.USER_ID))) { throw new ProjectCommonException( - ResponseCode.userIdRequired.getErrorCode(), + ResponseCode.userIdRequired, ResponseCode.userIdRequired.getErrorMessage(), ERROR_CODE); } if (StringUtils.isBlank((String) request.get(JsonKey.TITLE))) { throw new ProjectCommonException( - ResponseCode.titleRequired.getErrorCode(), + ResponseCode.titleRequired, ResponseCode.titleRequired.getErrorMessage(), ERROR_CODE); } if (StringUtils.isBlank((String) request.get(JsonKey.NOTE))) { throw new ProjectCommonException( - ResponseCode.noteRequired.getErrorCode(), + ResponseCode.noteRequired, ResponseCode.noteRequired.getErrorMessage(), ERROR_CODE); } if (StringUtils.isBlank((String) request.get(JsonKey.CONTENT_ID)) && StringUtils.isBlank((String) request.get(JsonKey.COURSE_ID))) { throw new ProjectCommonException( - ResponseCode.contentIdError.getErrorCode(), + ResponseCode.contentIdError, ResponseCode.contentIdError.getErrorMessage(), ERROR_CODE); } @@ -842,12 +847,12 @@ public static void validateNote(Request request) { && ((request.getRequest().get(JsonKey.TAGS) instanceof List) && ((List) request.getRequest().get(JsonKey.TAGS)).isEmpty())) { throw new ProjectCommonException( - ResponseCode.invalidTags.getErrorCode(), + ResponseCode.invalidTags, ResponseCode.invalidTags.getErrorMessage(), ERROR_CODE); } else if (request.getRequest().get(JsonKey.TAGS) instanceof String) { throw new ProjectCommonException( - ResponseCode.invalidTags.getErrorCode(), + ResponseCode.invalidTags, ResponseCode.invalidTags.getErrorMessage(), ERROR_CODE); } @@ -860,7 +865,7 @@ public static void validateNote(Request request) { */ public static void validateNoteId(String noteId) { if (StringUtils.isBlank(noteId)) { - throw createExceptionInstance(ResponseCode.invalidNoteId.getErrorCode()); + throw createExceptionInstance(ResponseCode.invalidNoteId); } } @@ -872,7 +877,7 @@ public static void validateNoteId(String noteId) { public static void validateRegisterClient(Request request) { if (StringUtils.isBlank((String) request.getRequest().get(JsonKey.CLIENT_NAME))) { - throw createExceptionInstance(ResponseCode.invalidClientName.getErrorCode()); + throw createExceptionInstance(ResponseCode.invalidClientName); } } @@ -885,7 +890,7 @@ public static void validateRegisterClient(Request request) { public static void validateUpdateClientKey(String clientId, String masterAccessToken) { validateClientId(clientId); if (StringUtils.isBlank(masterAccessToken)) { - throw createExceptionInstance(ResponseCode.invalidRequestData.getErrorCode()); + throw createExceptionInstance(ResponseCode.invalidRequestData); } } @@ -898,7 +903,7 @@ public static void validateUpdateClientKey(String clientId, String masterAccessT public static void validateGetClientKey(String id, String type) { validateClientId(id); if (StringUtils.isBlank(type)) { - throw createExceptionInstance(ResponseCode.invalidRequestData.getErrorCode()); + throw createExceptionInstance(ResponseCode.invalidRequestData); } } @@ -909,7 +914,7 @@ public static void validateGetClientKey(String id, String type) { */ public static void validateClientId(String clientId) { if (StringUtils.isBlank(clientId)) { - throw createExceptionInstance(ResponseCode.invalidClientId.getErrorCode()); + throw createExceptionInstance(ResponseCode.invalidClientId); } } @@ -921,19 +926,19 @@ public static void validateClientId(String clientId) { @SuppressWarnings("unchecked") public static void validateSendNotification(Request request) { if (StringUtils.isBlank((String) request.getRequest().get(JsonKey.TO))) { - throw createExceptionInstance(ResponseCode.invalidTopic.getErrorCode()); + throw createExceptionInstance(ResponseCode.invalidTopic); } if (request.getRequest().get(JsonKey.DATA) == null || !(request.getRequest().get(JsonKey.DATA) instanceof Map) || ((Map) request.getRequest().get(JsonKey.DATA)).size() == 0) { - throw createExceptionInstance(ResponseCode.invalidTopicData.getErrorCode()); + throw createExceptionInstance(ResponseCode.invalidTopicData); } if (StringUtils.isBlank((String) request.getRequest().get(JsonKey.TYPE))) { - throw createExceptionInstance(ResponseCode.invalidNotificationType.getErrorCode()); + throw createExceptionInstance(ResponseCode.invalidNotificationType); } if (!(JsonKey.FCM.equalsIgnoreCase((String) request.getRequest().get(JsonKey.TYPE)))) { - throw createExceptionInstance(ResponseCode.notificationTypeSupport.getErrorCode()); + throw createExceptionInstance(ResponseCode.notificationTypeSupport); } } @@ -941,31 +946,31 @@ public static void validateSendNotification(Request request) { public static void validateGetUserCount(Request request) { if (!validateListType(request, JsonKey.LOCATION_IDS)) { throw createDataTypeException( - ResponseCode.dataTypeError.getErrorCode(), JsonKey.LOCATION_IDS, JsonKey.LIST); + ResponseCode.dataTypeError, JsonKey.LOCATION_IDS, JsonKey.LIST); } if (null == request.getRequest().get(JsonKey.LOCATION_IDS) && ((List) request.getRequest().get(JsonKey.LOCATION_IDS)).isEmpty()) { - throw createExceptionInstance(ResponseCode.locationIdRequired.getErrorCode()); + throw createExceptionInstance(ResponseCode.locationIdRequired); } if (!validateBooleanType(request, JsonKey.USER_LIST_REQ)) { throw createDataTypeException( - ResponseCode.dataTypeError.getErrorCode(), JsonKey.USER_LIST_REQ, "Boolean"); + ResponseCode.dataTypeError, JsonKey.USER_LIST_REQ, "Boolean"); } if (null != request.getRequest().get(JsonKey.USER_LIST_REQ) && (Boolean) request.getRequest().get(JsonKey.USER_LIST_REQ)) { - throw createExceptionInstance(ResponseCode.functionalityMissing.getErrorCode()); + throw createExceptionInstance(ResponseCode.functionalityMissing); } if (!validateBooleanType(request, JsonKey.ESTIMATED_COUNT_REQ)) { throw createDataTypeException( - ResponseCode.dataTypeError.getErrorCode(), JsonKey.ESTIMATED_COUNT_REQ, "Boolean"); + ResponseCode.dataTypeError, JsonKey.ESTIMATED_COUNT_REQ, "Boolean"); } if (null != request.getRequest().get(JsonKey.ESTIMATED_COUNT_REQ) && (Boolean) request.getRequest().get(JsonKey.ESTIMATED_COUNT_REQ)) { - throw createExceptionInstance(ResponseCode.functionalityMissing.getErrorCode()); + throw createExceptionInstance(ResponseCode.functionalityMissing); } } @@ -998,18 +1003,18 @@ private static boolean validateBooleanType(Request request, String key) { } private static ProjectCommonException createDataTypeException( - String errorCode, String key1, String key2) { + ResponseCode responseCode, String key1, String key2) { return new ProjectCommonException( - ResponseCode.getResponse(errorCode).getErrorCode(), + responseCode, ProjectUtil.formatMessage( - ResponseCode.getResponse(errorCode).getErrorMessage(), key1, key2), + responseCode.getErrorMessage(), key1, key2), ERROR_CODE); } - private static ProjectCommonException createExceptionInstance(String errorCode) { + private static ProjectCommonException createExceptionInstance(ResponseCode responseCode) { return new ProjectCommonException( - ResponseCode.getResponse(errorCode).getErrorCode(), - ResponseCode.getResponse(errorCode).getErrorMessage(), + responseCode, + responseCode.getErrorMessage(), ERROR_CODE); } } diff --git a/service/conf/application.conf b/service/conf/application.conf index c35d87e2a..7f0147c11 100644 --- a/service/conf/application.conf +++ b/service/conf/application.conf @@ -18,8 +18,8 @@ pekko { java = "org.apache.pekko.serialization.JavaSerializer" } serialization-bindings { - "org.sunbird.common.request.Request" = java - "org.sunbird.common.models.response.Response" = java + "org.sunbird.request.Request" = java + "org.sunbird.response.Response" = java } default-dispatcher { # This will be used if you have set "executor = "fork-join-executor"" diff --git a/service/test/actors/DummyActor.java b/service/test/actors/DummyActor.java index 9943169d8..844d2e6fa 100644 --- a/service/test/actors/DummyActor.java +++ b/service/test/actors/DummyActor.java @@ -2,7 +2,7 @@ import org.apache.pekko.actor.ActorRef; import org.apache.pekko.actor.UntypedAbstractActor; -import org.sunbird.common.models.response.Response; +import org.sunbird.response.Response; /** Created by arvind on 30/11/17. */ public class DummyActor extends UntypedAbstractActor { diff --git a/service/test/actors/DummyErrorActor.java b/service/test/actors/DummyErrorActor.java index af860f9a0..5350b9ba7 100644 --- a/service/test/actors/DummyErrorActor.java +++ b/service/test/actors/DummyErrorActor.java @@ -2,7 +2,7 @@ import org.apache.pekko.actor.ActorRef; import org.apache.pekko.actor.UntypedAbstractActor; -import org.sunbird.common.exception.ProjectCommonException; +import org.sunbird.exception.ProjectCommonException; public class DummyErrorActor extends UntypedAbstractActor { diff --git a/service/test/actors/DummyHealthActor.java b/service/test/actors/DummyHealthActor.java index 04b26bde4..62166b629 100644 --- a/service/test/actors/DummyHealthActor.java +++ b/service/test/actors/DummyHealthActor.java @@ -2,8 +2,8 @@ import org.apache.pekko.actor.ActorRef; import org.apache.pekko.actor.UntypedAbstractActor; -import org.sunbird.common.models.response.Response; -import org.sunbird.common.models.util.JsonKey; +import org.sunbird.response.Response; +import org.sunbird.keys.JsonKey; import java.util.HashMap; import java.util.Map; diff --git a/service/test/controllers/ApplicationStartTest.java b/service/test/controllers/ApplicationStartTest.java index 3976f6c54..bff31ca8f 100644 --- a/service/test/controllers/ApplicationStartTest.java +++ b/service/test/controllers/ApplicationStartTest.java @@ -2,9 +2,9 @@ import org.junit.Test; import org.mockito.Mockito; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.models.util.LoggerUtil; -import org.sunbird.common.request.RequestContext; +import org.sunbird.keys.JsonKey; +import org.sunbird.logging.LoggerUtil; +import org.sunbird.request.RequestContext; import static modules.ApplicationStart.mockServiceSetup; diff --git a/service/test/controllers/LearnerControllerTest.java b/service/test/controllers/LearnerControllerTest.java index 498eeb4c5..fcebe3352 100644 --- a/service/test/controllers/LearnerControllerTest.java +++ b/service/test/controllers/LearnerControllerTest.java @@ -11,7 +11,7 @@ import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.modules.junit4.PowerMockRunner; -import org.sunbird.common.models.util.JsonKey; +import org.sunbird.keys.JsonKey; import play.libs.Json; import play.mvc.Http; import play.mvc.Result; diff --git a/service/test/controllers/QRcodedownload/QRCodeDownloadControllerTest.java b/service/test/controllers/QRcodedownload/QRCodeDownloadControllerTest.java index d32002f2e..8b55d9b26 100644 --- a/service/test/controllers/QRcodedownload/QRCodeDownloadControllerTest.java +++ b/service/test/controllers/QRcodedownload/QRCodeDownloadControllerTest.java @@ -9,7 +9,7 @@ import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.modules.junit4.PowerMockRunner; -import org.sunbird.common.models.util.JsonKey; +import org.sunbird.keys.JsonKey; import play.libs.Json; import play.mvc.Http; import play.mvc.Result; diff --git a/service/test/controllers/bulkapimanagement/BulkUploadControllerTest.java b/service/test/controllers/bulkapimanagement/BulkUploadControllerTest.java index 2192b4acb..85c2572e9 100644 --- a/service/test/controllers/bulkapimanagement/BulkUploadControllerTest.java +++ b/service/test/controllers/bulkapimanagement/BulkUploadControllerTest.java @@ -10,8 +10,8 @@ import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.modules.junit4.PowerMockRunner; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.models.util.ProjectLogger; +import org.sunbird.keys.JsonKey; +import org.sunbird.logging.ProjectLogger; import play.libs.Json; import play.mvc.Http; import play.mvc.Result; diff --git a/service/test/controllers/cache/CacheControllerTest.java b/service/test/controllers/cache/CacheControllerTest.java index d7c16e999..cc32a208d 100644 --- a/service/test/controllers/cache/CacheControllerTest.java +++ b/service/test/controllers/cache/CacheControllerTest.java @@ -14,8 +14,8 @@ import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.core.classloader.annotations.SuppressStaticInitializationFor; import org.powermock.modules.junit4.PowerMockRunner; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.request.HeaderParam; +import org.sunbird.keys.JsonKey; +import org.sunbird.request.HeaderParam; import play.mvc.Http; import play.mvc.Result; import play.test.Helpers; diff --git a/service/test/controllers/certificate/CertificateControllerTest.java b/service/test/controllers/certificate/CertificateControllerTest.java index 21866417d..f32ce3ed3 100644 --- a/service/test/controllers/certificate/CertificateControllerTest.java +++ b/service/test/controllers/certificate/CertificateControllerTest.java @@ -10,8 +10,8 @@ import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.modules.junit4.PowerMockRunner; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.models.util.ProjectLogger; +import org.sunbird.keys.JsonKey; +import org.sunbird.logging.ProjectLogger; import org.sunbird.learner.constants.CourseJsonKey; import play.libs.Json; import play.mvc.Http; diff --git a/service/test/controllers/courseenrollment/CourseEnrollmentControllerTest.java b/service/test/controllers/courseenrollment/CourseEnrollmentControllerTest.java index 640efecf2..8af354cf4 100644 --- a/service/test/controllers/courseenrollment/CourseEnrollmentControllerTest.java +++ b/service/test/controllers/courseenrollment/CourseEnrollmentControllerTest.java @@ -12,7 +12,7 @@ import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.modules.junit4.PowerMockRunner; -import org.sunbird.common.models.util.JsonKey; +import org.sunbird.keys.JsonKey; import play.libs.Json; import play.mvc.Http; import play.mvc.Result; diff --git a/service/test/controllers/courseenrollment/CourseEnrollmentControllerTest2.java b/service/test/controllers/courseenrollment/CourseEnrollmentControllerTest2.java index 23a81c53b..ebaf44739 100644 --- a/service/test/controllers/courseenrollment/CourseEnrollmentControllerTest2.java +++ b/service/test/controllers/courseenrollment/CourseEnrollmentControllerTest2.java @@ -12,7 +12,7 @@ import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.modules.junit4.PowerMockRunner; -import org.sunbird.common.models.util.JsonKey; +import org.sunbird.keys.JsonKey; import play.libs.Json; import play.mvc.Http; import play.mvc.Result; diff --git a/service/test/controllers/coursemanagement/CourseBatchControllerTest.java b/service/test/controllers/coursemanagement/CourseBatchControllerTest.java index 058a84568..e8003ae82 100644 --- a/service/test/controllers/coursemanagement/CourseBatchControllerTest.java +++ b/service/test/controllers/coursemanagement/CourseBatchControllerTest.java @@ -11,8 +11,8 @@ import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.modules.junit4.PowerMockRunner; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.models.util.ProjectLogger; +import org.sunbird.keys.JsonKey; +import org.sunbird.logging.ProjectLogger; import play.libs.Json; import play.mvc.Http; import play.mvc.Result; diff --git a/service/test/controllers/exhaustjob/ExhaustJobControllerTest.java b/service/test/controllers/exhaustjob/ExhaustJobControllerTest.java index 5df94e9e7..3e9ad7e56 100644 --- a/service/test/controllers/exhaustjob/ExhaustJobControllerTest.java +++ b/service/test/controllers/exhaustjob/ExhaustJobControllerTest.java @@ -10,8 +10,8 @@ import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.modules.junit4.PowerMockRunner; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.models.util.ProjectLogger; +import org.sunbird.keys.JsonKey; +import org.sunbird.logging.ProjectLogger; import play.libs.Json; import play.mvc.Http; import play.mvc.Result; diff --git a/service/test/controllers/healthmanager/HealthControllerTest.java b/service/test/controllers/healthmanager/HealthControllerTest.java index 8504aabf8..df8133551 100644 --- a/service/test/controllers/healthmanager/HealthControllerTest.java +++ b/service/test/controllers/healthmanager/HealthControllerTest.java @@ -10,7 +10,7 @@ import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; -import org.sunbird.common.models.util.HttpUtil; +import org.sunbird.http.HttpUtil; import play.mvc.Http; import play.mvc.Http.RequestBuilder; import play.mvc.Result; diff --git a/service/test/controllers/pagemanagement/PageControllerTest.java b/service/test/controllers/pagemanagement/PageControllerTest.java index 6deeb2c9d..f110755d1 100644 --- a/service/test/controllers/pagemanagement/PageControllerTest.java +++ b/service/test/controllers/pagemanagement/PageControllerTest.java @@ -10,8 +10,8 @@ import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.modules.junit4.PowerMockRunner; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.models.util.ProjectLogger; +import org.sunbird.keys.JsonKey; +import org.sunbird.logging.ProjectLogger; import play.libs.Json; import play.mvc.Http; import play.mvc.Result; diff --git a/service/test/controllers/search/SearchControllerTest.java b/service/test/controllers/search/SearchControllerTest.java index d3e1a7e9f..c92688810 100644 --- a/service/test/controllers/search/SearchControllerTest.java +++ b/service/test/controllers/search/SearchControllerTest.java @@ -11,8 +11,8 @@ import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.SuppressStaticInitializationFor; import org.powermock.modules.junit4.PowerMockRunner; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.models.util.ProjectLogger; +import org.sunbird.keys.JsonKey; +import org.sunbird.logging.ProjectLogger; import play.libs.Json; import play.mvc.Http; import play.mvc.Result; diff --git a/service/test/mapper/RequestMapperTest.java b/service/test/mapper/RequestMapperTest.java index 21a1b3284..c631c3b04 100644 --- a/service/test/mapper/RequestMapperTest.java +++ b/service/test/mapper/RequestMapperTest.java @@ -9,10 +9,10 @@ import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; -import org.sunbird.common.exception.ProjectCommonException; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.request.Request; -import org.sunbird.common.responsecode.ResponseCode; +import org.sunbird.exception.ProjectCommonException; +import org.sunbird.keys.JsonKey; +import org.sunbird.request.Request; +import org.sunbird.response.ResponseCode; import play.libs.Json; import java.util.HashMap; diff --git a/service/test/util/RequestInterceptorTest.java b/service/test/util/RequestInterceptorTest.java index 605972ffa..4823f5e24 100644 --- a/service/test/util/RequestInterceptorTest.java +++ b/service/test/util/RequestInterceptorTest.java @@ -12,9 +12,9 @@ import org.powermock.modules.junit4.PowerMockRunner; import org.sunbird.auth.verifier.AccessTokenValidator; import org.sunbird.cassandraimpl.CassandraOperationImpl; -import org.sunbird.common.models.response.Response; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.models.util.PropertiesCache; +import org.sunbird.response.Response; +import org.sunbird.keys.JsonKey; +import org.sunbird.common.PropertiesCache; import org.sunbird.helper.ServiceFactory; import play.Application; import play.Mode; diff --git a/service/test/util/RequestValidatorTest.java b/service/test/util/RequestValidatorTest.java index 8c9a670d2..8064cd7ab 100644 --- a/service/test/util/RequestValidatorTest.java +++ b/service/test/util/RequestValidatorTest.java @@ -3,11 +3,11 @@ import org.junit.Assert; import org.junit.Test; -import org.sunbird.common.exception.ProjectCommonException; -import org.sunbird.common.models.util.JsonKey; -import org.sunbird.common.models.util.ProjectUtil; -import org.sunbird.common.request.Request; -import org.sunbird.common.responsecode.ResponseCode; +import org.sunbird.exception.ProjectCommonException; +import org.sunbird.keys.JsonKey; +import org.sunbird.common.ProjectUtil; +import org.sunbird.request.Request; +import org.sunbird.response.ResponseCode; import java.util.ArrayList; import java.util.HashMap; diff --git a/service/test/util/TestUtil.java b/service/test/util/TestUtil.java index 730a4484e..5b1a7b935 100644 --- a/service/test/util/TestUtil.java +++ b/service/test/util/TestUtil.java @@ -1,7 +1,7 @@ package util; import com.fasterxml.jackson.databind.ObjectMapper; -import org.sunbird.common.models.util.ProjectLogger; +import org.sunbird.logging.ProjectLogger; import java.io.IOException; import java.util.Map;