diff --git a/git-hooks/pre-commit b/git-hooks/pre-commit new file mode 100755 index 0000000000..3a37089b52 --- /dev/null +++ b/git-hooks/pre-commit @@ -0,0 +1,12 @@ +#!/bin/bash + +REPO_ROOT_DIR="$(git rev-parse --show-toplevel)" + +FORMAT_JAR_LOCATION="${REPO_ROOT_DIR}/tools/java-format/google-java-format-1.5-all-deps.jar" + +for staged_file in $(git diff --cached --name-only); do + [ -f "${staged_file}" ] || continue + + "${REPO_ROOT_DIR}/scripts/check-java-file-format" "${FORMAT_JAR_LOCATION}" "${staged_file}" + git add "${staged_file}" +done diff --git a/scripts/check-java-file-format b/scripts/check-java-file-format new file mode 100755 index 0000000000..45b1883785 --- /dev/null +++ b/scripts/check-java-file-format @@ -0,0 +1,17 @@ +#!/bin/sh + +FILES_TO_SKIP="^(src-gen|third-party|(test/.*\/testdata\/)).*\.java$" + +JAR_PATH=$1 +FILE_PATH=$2 + +# Test if the file is Java file +echo "${FILE_PATH}" | grep -Eqi "\.java$" || exit 1 + +# Test if the file should be skipped +echo "${FILE_PATH}" | grep -Eqi "${FILES_TO_SKIP}" && exit 0 + +# Try to format the file +java -jar "${JAR_PATH}" -i "${FILE_PATH}" + +exit 0 diff --git a/scripts/setup.sh b/scripts/setup.sh new file mode 100755 index 0000000000..e0966cf58c --- /dev/null +++ b/scripts/setup.sh @@ -0,0 +1,5 @@ +#!/bin/bash + +REPO_ROOT_DIR="$(git rev-parse --show-toplevel)" + +cp "${REPO_ROOT_DIR}/git-hooks/pre-commit" "${REPO_ROOT_DIR}/.git/hooks/" diff --git a/service/app/controllers/BaseController.java b/service/app/controllers/BaseController.java index ce35b375e5..bbc5042ee8 100644 --- a/service/app/controllers/BaseController.java +++ b/service/app/controllers/BaseController.java @@ -1,9 +1,13 @@ package controllers; +import akka.actor.ActorRef; +import akka.actor.ActorSelection; +import akka.pattern.Patterns; +import akka.util.Timeout; +import com.fasterxml.jackson.databind.JsonNode; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; - import org.apache.commons.lang3.StringUtils; import org.sunbird.actor.service.SunbirdMWService; import org.sunbird.common.exception.ProjectCommonException; @@ -17,13 +21,6 @@ import org.sunbird.common.responsecode.ResponseCode; import org.sunbird.telemetry.util.TelemetryLmaxWriter; import org.sunbird.telemetry.util.lmaxdisruptor.TelemetryEvents; - -import com.fasterxml.jackson.databind.JsonNode; - -import akka.actor.ActorRef; -import akka.actor.ActorSelection; -import akka.pattern.Patterns; -import akka.util.Timeout; import play.libs.F.Function; import play.libs.F.Promise; import play.libs.Json; @@ -37,548 +34,539 @@ /** * This controller we can use for writing some common method. - * + * * @author Manzarul */ public class BaseController extends Controller { - public static final int AKKA_WAIT_TIME = 10; - private static Object actorRef = null; - private TelemetryLmaxWriter lmaxWriter = TelemetryLmaxWriter.getInstance(); - protected Timeout timeout = new Timeout(AKKA_WAIT_TIME, TimeUnit.SECONDS); - - static { - try { - actorRef = SunbirdMWService.getRequestRouter(); - } catch (Exception ex) { - ProjectLogger.log("Exception occured while getting actor ref in base controller " + ex); - } - } - - /** - * Helper method for creating and initialising a request for given operation and - * request body. - * - * @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}) instance. - */ - protected org.sunbird.common.request.Request createAndInitRequest(String operation, JsonNode requestBodyJson) { - org.sunbird.common.request.Request request; - - if (requestBodyJson != null) { - request = (org.sunbird.common.request.Request) mapper.RequestMapper.mapRequest(requestBodyJson, - org.sunbird.common.request.Request.class); - } else { - request = new org.sunbird.common.request.Request(); - } - - request.setOperation(operation); - request.setRequestId(ExecutionContext.getRequestId()); - request.setEnv(getEnvironment()); - - return request; - } - - /** - * 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}) instance. - */ - protected org.sunbird.common.request.Request createAndInitRequest(String operation) { - return createAndInitRequest(operation, null); - } - - /** - * This method will provide remote Actor selection - * - * @return Object - */ - public Object getActorRef() { - - return actorRef; - } - - /** - * This method will create failure response - * - * @param request - * Request - * @param code - * ResponseCode - * @param headerCode - * ResponseCode - * @return Response - */ - public static Response createFailureResponse(Request request, ResponseCode code, ResponseCode headerCode) { - - Response response = new Response(); - response.setVer(getApiVersion(request.path())); - response.setId(getApiResponseId(request)); - response.setTs(ProjectUtil.getFormattedDate()); - response.setResponseCode(headerCode); - response.setParams(createResponseParamObj(code)); - return response; - } - - /** - * This method will create response parameter - * - * @param code - * ResponseCode - * @return ResponseParams - */ - public static ResponseParams createResponseParamObj(ResponseCode code) { - ResponseParams params = new ResponseParams(); - if (code.getResponseCode() != 200) { - params.setErr(code.getErrorCode()); - params.setErrmsg(code.getErrorMessage()); - } - params.setMsgid(ExecutionContext.getRequestId()); - params.setStatus(ResponseCode.getHeaderResponseCode(code.getResponseCode()).name()); - return params; - } - - /** - * This method will create data for success response. - * - * @param request - * play.mvc.Http.Request - * @param response - * Response - * @return Response - */ - public static Response createSuccessResponse(Request request, Response response) { - - if (request != null) { - response.setVer(getApiVersion(request.path())); - } else { - response.setVer(""); - } - response.setId(getApiResponseId(request)); - response.setTs(ProjectUtil.getFormattedDate()); - ResponseCode code = ResponseCode.getResponse(ResponseCode.success.getErrorCode()); - code.setResponseCode(ResponseCode.OK.getResponseCode()); - response.setParams(createResponseParamObj(code)); - return response; - } - - /** - * This method will provide api version. - * - * @param request - * String - * @return String - */ - public static String getApiVersion(String request) { - - return request.split("[/]")[1]; - } - - /** - * This method will handle response in case of exception - * - * @param request - * play.mvc.Http.Request - * @param exception - * ProjectCommonException - * @return Response - */ - public static Response createResponseOnException(Request request, ProjectCommonException exception) { - ProjectLogger.log(exception != null ? exception.getMessage() : "Message is not coming", exception, - genarateTelemetryInfoForError()); - Response response = new Response(); - response.setVer(""); - if (request != null) { - response.setVer(getApiVersion(request.path())); - } - response.setId(getApiResponseId(request)); - response.setTs(ProjectUtil.getFormattedDate()); - response.setResponseCode(ResponseCode.getHeaderResponseCode(exception.getResponseCode())); - ResponseCode code = ResponseCode.getResponse(exception.getCode()); - if (code == null) { - code = ResponseCode.SERVER_ERROR; - } - response.setParams(createResponseParamObj(code)); - if (response.getParams() != null) { - response.getParams().setStatus(response.getParams().getStatus()); - if (exception.getCode() != null) { - response.getParams().setStatus(exception.getCode()); - } - if (!StringUtils.isBlank(response.getParams().getErrmsg()) - && response.getParams().getErrmsg().contains("{0}")) { - response.getParams().setErrmsg(exception.getMessage()); - } - } - Global.requestInfo.remove(ctx().flash().get(JsonKey.REQUEST_ID)); - return response; - } - - /** - * - * @param path - * String - * @param method - * String - * @param exception - * ProjectCommonException - * @return Response - */ - public static Response createResponseOnException(String path, String method, ProjectCommonException exception) { - - Response response = new Response(); - response.setVer(getApiVersion(path)); - response.setId(getApiResponseId(path, method)); - response.setTs(ProjectUtil.getFormattedDate()); - response.setResponseCode(ResponseCode.getHeaderResponseCode(exception.getResponseCode())); - ResponseCode code = ResponseCode.getResponse(exception.getCode()); - response.setParams(createResponseParamObj(code)); - return response; - } - - /** - * This method will create common response for all controller method - * - * @param response - * Object - * @param key - * String - * @param request - * play.mvc.Http.Request - * @return Result - */ - public Result createCommonResponse(Object response, String key, Request request) { - - Map requestInfo = Global.requestInfo.get(ctx().flash().get(JsonKey.REQUEST_ID)); - org.sunbird.common.request.Request req = new org.sunbird.common.request.Request(); - - Map params = (Map) requestInfo.get(JsonKey.ADDITIONAL_INFO); - - params.put(JsonKey.LOG_TYPE, JsonKey.API_ACCESS); - params.put(JsonKey.MESSAGE, ""); - params.put(JsonKey.METHOD, request.method()); - // calculate the total time consume - long startTime = (Long) params.get(JsonKey.START_TIME); - params.put(JsonKey.DURATION , calculateApiTimeTaken(startTime)); - removeFields(params , JsonKey.START_TIME); - params.put(JsonKey.STATUS, String.valueOf(((Response) response).getResponseCode().getResponseCode())); - params.put(JsonKey.LOG_LEVEL, JsonKey.INFO); - req.setRequest(generateTelemetryRequestForController(TelemetryEvents.LOG.getName(), params, - (Map) requestInfo.get(JsonKey.CONTEXT))); - //if any request is coming form /v1/telemetry/save then don't generate the telemetry log - //for it. - lmaxWriter.submitMessage(req); - - Response courseResponse = (Response) response; - if (!StringUtils.isBlank(key)) { - Object value = courseResponse.getResult().get(JsonKey.RESPONSE); - courseResponse.getResult().remove(JsonKey.RESPONSE); - courseResponse.getResult().put(key, value); - } - - // remove request info from map - Global.requestInfo.remove(ctx().flash().get(JsonKey.REQUEST_ID)); - return Results.ok(Json.toJson(BaseController.createSuccessResponse(request, (Response) courseResponse))); - // } - /* - * else { - * - * ProjectCommonException exception = (ProjectCommonException) response; return - * Results.status(exception.getResponseCode(), - * Json.toJson(BaseController.createResponseOnException(request, exception))); } - */ - } - - private void removeFields(Map params, String... properties) { - for(String property: properties){ - params.remove(property); - } - } - - private String generateStackTrace(StackTraceElement[] elements) { - StringBuilder builder = new StringBuilder(""); - for (StackTraceElement element : elements) { - - builder.append(element.toString()); - builder.append("\n"); - } - return builder.toString(); - } - - private Map generateTelemetryRequestForController(String eventType, Map params, - Map context) { - - Map map = new HashMap<>(); - map.put(JsonKey.TELEMETRY_EVENT_TYPE, eventType); - map.put(JsonKey.CONTEXT, context); - map.put(JsonKey.PARAMS, params); - return map; - } - - /** - * Common exception response handler method. - * - * @param e - * Exception - * @param request - * play.mvc.Http.Request - * @return Result - */ - public Result createCommonExceptionResponse(Exception e, Request request) { - Request req = request; - ProjectLogger.log(e.getMessage(), e, genarateTelemetryInfoForError()); - if (req == null) { - req = request(); - } - ProjectCommonException exception = null; - if (e instanceof ProjectCommonException) { - exception = (ProjectCommonException) e; - } else { - exception = new ProjectCommonException(ResponseCode.internalError.getErrorCode(), - ResponseCode.internalError.getErrorMessage(), ResponseCode.SERVER_ERROR.getResponseCode()); - } - - - Map requestInfo = Global.requestInfo.get(ctx().flash().get(JsonKey.REQUEST_ID)); - org.sunbird.common.request.Request reqForTelemetry = new org.sunbird.common.request.Request(); - Map params = (Map) requestInfo.get(JsonKey.ADDITIONAL_INFO); - params.put(JsonKey.LOG_TYPE, JsonKey.API_ACCESS); - params.put(JsonKey.MESSAGE, ""); - params.put(JsonKey.METHOD, request.method()); - // calculate the total time consume - long startTime = (Long) params.get(JsonKey.START_TIME); - params.put(JsonKey.DURATION , calculateApiTimeTaken(startTime)); - removeFields(params , JsonKey.START_TIME); - params.put(JsonKey.STATUS, String.valueOf(exception.getResponseCode())); - params.put(JsonKey.LOG_LEVEL, "error"); - params.put(JsonKey.STACKTRACE, generateStackTrace(exception.getStackTrace())); - reqForTelemetry.setRequest(generateTelemetryRequestForController(TelemetryEvents.LOG.getName(), params, - (Map) requestInfo.get(JsonKey.CONTEXT))); - lmaxWriter.submitMessage(reqForTelemetry); - - // cleaning request info ... - return Results.status(exception.getResponseCode(), - Json.toJson(BaseController.createResponseOnException(req, exception))); - } - - private long calculateApiTimeTaken(Long startTime) { - - Long timeConsumed=null; - if(null != startTime ){ - timeConsumed= System.currentTimeMillis() - startTime; - } - return timeConsumed; - } - - /** - * This method will make a call to Akka actor and return promise. - * - * @param actorRef - * ActorSelection - * @param request - * Request - * @param timeout - * Timeout - * @param responseKey - * String - * @param httpReq - * play.mvc.Http.Request - * @return Promise - */ - public Promise actorResponseHandler(Object actorRef, org.sunbird.common.request.Request request, - Timeout timeout, String responseKey, Request httpReq) { - // set header to request object , setting actor type and channel headers value - // ... - setChannelAndActorInfo(ctx(), request); - - if (actorRef instanceof ActorRef) { - return Promise.wrap(Patterns.ask((ActorRef) actorRef, request, timeout)) - .map(new Function() { - public Result apply(Object result) { - if (result instanceof Response) { - Response response = (Response) result; - return createCommonResponse(response, responseKey, httpReq); - } else if (result instanceof ProjectCommonException) { - return createCommonExceptionResponse((ProjectCommonException) result, request()); - } else { - ProjectLogger.log("Unsupported Actor Response format", LoggerEnum.INFO.name()); - return createCommonExceptionResponse(new Exception(), httpReq); - } - } - }); - } else { - return Promise.wrap(Patterns.ask((ActorSelection) actorRef, request, timeout)) - .map(new Function() { - public Result apply(Object result) { - if (result instanceof Response) { - Response response = (Response) result; - return createCommonResponse(response, responseKey, httpReq); - } else if (result instanceof ProjectCommonException) { - return createCommonExceptionResponse((ProjectCommonException) result, request()); - } else { - ProjectLogger.log("Unsupported Actor Response format", LoggerEnum.INFO.name()); - return createCommonExceptionResponse(new Exception(), httpReq); - } - } - }); - } - } - - /** - * This method will provide environment id. - * - * @return int - */ - public int getEnvironment() { - - if (Global.env != null) { - return Global.env.getValue(); - } - return ProjectUtil.Environment.dev.getValue(); - } - - /** - * Method to get UserId by AuthToken - * - * @param token - * @return String - */ - public String getUserIdByAuthToken(String token) { - - return AuthenticationHelper.verifyUserAccesToken(token); - } - - /** - * Method to get API response Id - * - * @param request - * play.mvc.Http.Request - * @return String - */ - private static String getApiResponseId(Request request) { - - String val = ""; - if (request != null) { - String path = request.path(); - if (request.method().equalsIgnoreCase(ProjectUtil.Method.GET.name())) { - val = Global.getResponseId(path); - if (StringUtils.isBlank(val)) { - String[] splitedpath = path.split("[/]"); - path = removeLastValue(splitedpath); - val = Global.getResponseId(path); - } - } else { - val = Global.getResponseId(path); - } - if (StringUtils.isBlank(val)) { - val = Global.getResponseId(path); - if (StringUtils.isBlank(val)) { - String[] splitedpath = path.split("[/]"); - path = removeLastValue(splitedpath); - val = Global.getResponseId(path); - } - } - } - return val; - } - - /** - * Method to get API response Id - * - * @param path - * String - * @param method - * String - * @return String - */ - private static String getApiResponseId(String path, String method) { - String val = ""; - if (ProjectUtil.Method.GET.name().equalsIgnoreCase(method)) { - val = Global.getResponseId(path); - if (StringUtils.isBlank(val)) { - String[] splitedpath = path.split("[/]"); - String tempPath = removeLastValue(splitedpath); - val = Global.getResponseId(tempPath); - } - } else { - val = Global.getResponseId(path); - } - return val; - } - - /** - * Method to remove last value - * - * @param splited - * String [] - * @return String - */ - private static String removeLastValue(String splited[]) { - - StringBuilder builder = new StringBuilder(); - if (splited != null && splited.length > 0) { - for (int i = 1; i < splited.length - 1; i++) { - builder.append("/" + splited[i]); - } - } - return builder.toString(); - } - - public static void setActorRef(Object obj) { - actorRef = obj; - } - - private static Map genarateTelemetryInfoForError() { - - Map map = new HashMap<>(); - Map requestInfo = Global.requestInfo.get(ctx().flash().get(JsonKey.REQUEST_ID)); - Map contextInfo = (Map) requestInfo.get(JsonKey.CONTEXT); - Map params = new HashMap<>(); - params.put(JsonKey.ERR_TYPE, JsonKey.API_ACCESS); - - map.put(JsonKey.CONTEXT, contextInfo); - map.put(JsonKey.PARAMS, params); - return map; - } - - public void setChannelAndActorInfo(Context ctx, org.sunbird.common.request.Request reqObj) { - - reqObj.getContext().put(JsonKey.CHANNEL, ctx().flash().get(JsonKey.CHANNEL)); - reqObj.getContext().put(JsonKey.ACTOR_ID, ctx().flash().get(JsonKey.ACTOR_ID)); - reqObj.getContext().put(JsonKey.ACTOR_TYPE, ctx().flash().get(JsonKey.ACTOR_TYPE)); - - } - - /** - * This method will set extra param to request body which is required for actor - * layer. - * - * @param request - * Request - * @param requestId - * String - * @param actorOpName - * String - * @param requestedUserId - * String - * @param env - * int - * @return Request - */ - public org.sunbird.common.request.Request setExtraParam(org.sunbird.common.request.Request request, - String requestId, String actorOpName, String requestedUserId, int env) { - request.setRequestId(requestId); - request.setOperation(actorOpName); - request.getRequest().put(JsonKey.CREATED_BY, requestedUserId); - request.setEnv(env); - return request; - } + public static final int AKKA_WAIT_TIME = 10; + private static Object actorRef = null; + private TelemetryLmaxWriter lmaxWriter = TelemetryLmaxWriter.getInstance(); + protected Timeout timeout = new Timeout(AKKA_WAIT_TIME, TimeUnit.SECONDS); + + static { + try { + actorRef = SunbirdMWService.getRequestRouter(); + } catch (Exception ex) { + ProjectLogger.log("Exception occured while getting actor ref in base controller " + ex); + } + } + + /** + * Helper method for creating and initialising a request for given operation and request body. + * + * @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}) + * instance. + */ + protected org.sunbird.common.request.Request createAndInitRequest( + String operation, JsonNode requestBodyJson) { + org.sunbird.common.request.Request request; + + if (requestBodyJson != null) { + request = + (org.sunbird.common.request.Request) + mapper.RequestMapper.mapRequest( + requestBodyJson, org.sunbird.common.request.Request.class); + } else { + request = new org.sunbird.common.request.Request(); + } + + request.setOperation(operation); + request.setRequestId(ExecutionContext.getRequestId()); + request.setEnv(getEnvironment()); + + return request; + } + + /** + * 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}) + * instance. + */ + protected org.sunbird.common.request.Request createAndInitRequest(String operation) { + return createAndInitRequest(operation, null); + } + + /** + * This method will provide remote Actor selection + * + * @return Object + */ + public Object getActorRef() { + + return actorRef; + } + + /** + * This method will create failure response + * + * @param request Request + * @param code ResponseCode + * @param headerCode ResponseCode + * @return Response + */ + public static Response createFailureResponse( + Request request, ResponseCode code, ResponseCode headerCode) { + + Response response = new Response(); + response.setVer(getApiVersion(request.path())); + response.setId(getApiResponseId(request)); + response.setTs(ProjectUtil.getFormattedDate()); + response.setResponseCode(headerCode); + response.setParams(createResponseParamObj(code)); + return response; + } + + /** + * This method will create response parameter + * + * @param code ResponseCode + * @return ResponseParams + */ + public static ResponseParams createResponseParamObj(ResponseCode code) { + ResponseParams params = new ResponseParams(); + if (code.getResponseCode() != 200) { + params.setErr(code.getErrorCode()); + params.setErrmsg(code.getErrorMessage()); + } + params.setMsgid(ExecutionContext.getRequestId()); + params.setStatus(ResponseCode.getHeaderResponseCode(code.getResponseCode()).name()); + return params; + } + + /** + * This method will create data for success response. + * + * @param request play.mvc.Http.Request + * @param response Response + * @return Response + */ + public static Response createSuccessResponse(Request request, Response response) { + + if (request != null) { + response.setVer(getApiVersion(request.path())); + } else { + response.setVer(""); + } + response.setId(getApiResponseId(request)); + response.setTs(ProjectUtil.getFormattedDate()); + ResponseCode code = ResponseCode.getResponse(ResponseCode.success.getErrorCode()); + code.setResponseCode(ResponseCode.OK.getResponseCode()); + response.setParams(createResponseParamObj(code)); + return response; + } + + /** + * This method will provide api version. + * + * @param request String + * @return String + */ + public static String getApiVersion(String request) { + + return request.split("[/]")[1]; + } + + /** + * This method will handle response in case of exception + * + * @param request play.mvc.Http.Request + * @param exception ProjectCommonException + * @return Response + */ + public static Response createResponseOnException( + Request request, ProjectCommonException exception) { + ProjectLogger.log( + exception != null ? exception.getMessage() : "Message is not coming", + exception, + genarateTelemetryInfoForError()); + Response response = new Response(); + response.setVer(""); + if (request != null) { + response.setVer(getApiVersion(request.path())); + } + response.setId(getApiResponseId(request)); + response.setTs(ProjectUtil.getFormattedDate()); + response.setResponseCode(ResponseCode.getHeaderResponseCode(exception.getResponseCode())); + ResponseCode code = ResponseCode.getResponse(exception.getCode()); + if (code == null) { + code = ResponseCode.SERVER_ERROR; + } + response.setParams(createResponseParamObj(code)); + if (response.getParams() != null) { + response.getParams().setStatus(response.getParams().getStatus()); + if (exception.getCode() != null) { + response.getParams().setStatus(exception.getCode()); + } + if (!StringUtils.isBlank(response.getParams().getErrmsg()) + && response.getParams().getErrmsg().contains("{0}")) { + response.getParams().setErrmsg(exception.getMessage()); + } + } + Global.requestInfo.remove(ctx().flash().get(JsonKey.REQUEST_ID)); + return response; + } + + /** + * @param path String + * @param method String + * @param exception ProjectCommonException + * @return Response + */ + public static Response createResponseOnException( + String path, String method, ProjectCommonException exception) { + + Response response = new Response(); + response.setVer(getApiVersion(path)); + response.setId(getApiResponseId(path, method)); + response.setTs(ProjectUtil.getFormattedDate()); + response.setResponseCode(ResponseCode.getHeaderResponseCode(exception.getResponseCode())); + ResponseCode code = ResponseCode.getResponse(exception.getCode()); + response.setParams(createResponseParamObj(code)); + return response; + } + + /** + * This method will create common response for all controller method + * + * @param response Object + * @param key String + * @param request play.mvc.Http.Request + * @return Result + */ + public Result createCommonResponse(Object response, String key, Request request) { + + Map requestInfo = Global.requestInfo.get(ctx().flash().get(JsonKey.REQUEST_ID)); + org.sunbird.common.request.Request req = new org.sunbird.common.request.Request(); + + Map params = (Map) requestInfo.get(JsonKey.ADDITIONAL_INFO); + + params.put(JsonKey.LOG_TYPE, JsonKey.API_ACCESS); + params.put(JsonKey.MESSAGE, ""); + params.put(JsonKey.METHOD, request.method()); + // calculate the total time consume + long startTime = (Long) params.get(JsonKey.START_TIME); + params.put(JsonKey.DURATION, calculateApiTimeTaken(startTime)); + removeFields(params, JsonKey.START_TIME); + params.put( + JsonKey.STATUS, String.valueOf(((Response) response).getResponseCode().getResponseCode())); + params.put(JsonKey.LOG_LEVEL, JsonKey.INFO); + req.setRequest( + generateTelemetryRequestForController( + TelemetryEvents.LOG.getName(), + params, + (Map) requestInfo.get(JsonKey.CONTEXT))); + // if any request is coming form /v1/telemetry/save then don't generate the telemetry log + // for it. + lmaxWriter.submitMessage(req); + + Response courseResponse = (Response) response; + if (!StringUtils.isBlank(key)) { + Object value = courseResponse.getResult().get(JsonKey.RESPONSE); + courseResponse.getResult().remove(JsonKey.RESPONSE); + courseResponse.getResult().put(key, value); + } + + // remove request info from map + Global.requestInfo.remove(ctx().flash().get(JsonKey.REQUEST_ID)); + return Results.ok( + Json.toJson(BaseController.createSuccessResponse(request, (Response) courseResponse))); + // } + /* + * else { + * + * ProjectCommonException exception = (ProjectCommonException) response; return + * Results.status(exception.getResponseCode(), + * Json.toJson(BaseController.createResponseOnException(request, exception))); } + */ + } + + private void removeFields(Map params, String... properties) { + for (String property : properties) { + params.remove(property); + } + } + + private String generateStackTrace(StackTraceElement[] elements) { + StringBuilder builder = new StringBuilder(""); + for (StackTraceElement element : elements) { + + builder.append(element.toString()); + builder.append("\n"); + } + return builder.toString(); + } + + private Map generateTelemetryRequestForController( + String eventType, Map params, Map context) { + + Map map = new HashMap<>(); + map.put(JsonKey.TELEMETRY_EVENT_TYPE, eventType); + map.put(JsonKey.CONTEXT, context); + map.put(JsonKey.PARAMS, params); + return map; + } + + /** + * Common exception response handler method. + * + * @param e Exception + * @param request play.mvc.Http.Request + * @return Result + */ + public Result createCommonExceptionResponse(Exception e, Request request) { + Request req = request; + ProjectLogger.log(e.getMessage(), e, genarateTelemetryInfoForError()); + if (req == null) { + req = request(); + } + ProjectCommonException exception = null; + if (e instanceof ProjectCommonException) { + exception = (ProjectCommonException) e; + } else { + exception = + new ProjectCommonException( + ResponseCode.internalError.getErrorCode(), + ResponseCode.internalError.getErrorMessage(), + ResponseCode.SERVER_ERROR.getResponseCode()); + } + + Map requestInfo = Global.requestInfo.get(ctx().flash().get(JsonKey.REQUEST_ID)); + org.sunbird.common.request.Request reqForTelemetry = new org.sunbird.common.request.Request(); + Map params = (Map) requestInfo.get(JsonKey.ADDITIONAL_INFO); + params.put(JsonKey.LOG_TYPE, JsonKey.API_ACCESS); + params.put(JsonKey.MESSAGE, ""); + params.put(JsonKey.METHOD, request.method()); + // calculate the total time consume + long startTime = (Long) params.get(JsonKey.START_TIME); + params.put(JsonKey.DURATION, calculateApiTimeTaken(startTime)); + removeFields(params, JsonKey.START_TIME); + params.put(JsonKey.STATUS, String.valueOf(exception.getResponseCode())); + params.put(JsonKey.LOG_LEVEL, "error"); + params.put(JsonKey.STACKTRACE, generateStackTrace(exception.getStackTrace())); + reqForTelemetry.setRequest( + generateTelemetryRequestForController( + TelemetryEvents.LOG.getName(), + params, + (Map) requestInfo.get(JsonKey.CONTEXT))); + lmaxWriter.submitMessage(reqForTelemetry); + + // cleaning request info ... + return Results.status( + exception.getResponseCode(), + Json.toJson(BaseController.createResponseOnException(req, exception))); + } + + private long calculateApiTimeTaken(Long startTime) { + + Long timeConsumed = null; + if (null != startTime) { + timeConsumed = System.currentTimeMillis() - startTime; + } + return timeConsumed; + } + + /** + * This method will make a call to Akka actor and return promise. + * + * @param actorRef ActorSelection + * @param request Request + * @param timeout Timeout + * @param responseKey String + * @param httpReq play.mvc.Http.Request + * @return Promise + */ + public Promise actorResponseHandler( + Object actorRef, + org.sunbird.common.request.Request request, + Timeout timeout, + String responseKey, + Request httpReq) { + // set header to request object , setting actor type and channel headers value + // ... + setChannelAndActorInfo(ctx(), request); + + if (actorRef instanceof ActorRef) { + return Promise.wrap(Patterns.ask((ActorRef) actorRef, request, timeout)) + .map( + new Function() { + public Result apply(Object result) { + if (result instanceof Response) { + Response response = (Response) result; + return createCommonResponse(response, responseKey, httpReq); + } else if (result instanceof ProjectCommonException) { + return createCommonExceptionResponse( + (ProjectCommonException) result, request()); + } else { + ProjectLogger.log("Unsupported Actor Response format", LoggerEnum.INFO.name()); + return createCommonExceptionResponse(new Exception(), httpReq); + } + } + }); + } else { + return Promise.wrap(Patterns.ask((ActorSelection) actorRef, request, timeout)) + .map( + new Function() { + public Result apply(Object result) { + if (result instanceof Response) { + Response response = (Response) result; + return createCommonResponse(response, responseKey, httpReq); + } else if (result instanceof ProjectCommonException) { + return createCommonExceptionResponse( + (ProjectCommonException) result, request()); + } else { + ProjectLogger.log("Unsupported Actor Response format", LoggerEnum.INFO.name()); + return createCommonExceptionResponse(new Exception(), httpReq); + } + } + }); + } + } + + /** + * This method will provide environment id. + * + * @return int + */ + public int getEnvironment() { + + if (Global.env != null) { + return Global.env.getValue(); + } + return ProjectUtil.Environment.dev.getValue(); + } + + /** + * Method to get UserId by AuthToken + * + * @param token + * @return String + */ + public String getUserIdByAuthToken(String token) { + + return AuthenticationHelper.verifyUserAccesToken(token); + } + + /** + * Method to get API response Id + * + * @param request play.mvc.Http.Request + * @return String + */ + private static String getApiResponseId(Request request) { + + String val = ""; + if (request != null) { + String path = request.path(); + if (request.method().equalsIgnoreCase(ProjectUtil.Method.GET.name())) { + val = Global.getResponseId(path); + if (StringUtils.isBlank(val)) { + String[] splitedpath = path.split("[/]"); + path = removeLastValue(splitedpath); + val = Global.getResponseId(path); + } + } else { + val = Global.getResponseId(path); + } + if (StringUtils.isBlank(val)) { + val = Global.getResponseId(path); + if (StringUtils.isBlank(val)) { + String[] splitedpath = path.split("[/]"); + path = removeLastValue(splitedpath); + val = Global.getResponseId(path); + } + } + } + return val; + } + + /** + * Method to get API response Id + * + * @param path String + * @param method String + * @return String + */ + private static String getApiResponseId(String path, String method) { + String val = ""; + if (ProjectUtil.Method.GET.name().equalsIgnoreCase(method)) { + val = Global.getResponseId(path); + if (StringUtils.isBlank(val)) { + String[] splitedpath = path.split("[/]"); + String tempPath = removeLastValue(splitedpath); + val = Global.getResponseId(tempPath); + } + } else { + val = Global.getResponseId(path); + } + return val; + } + + /** + * Method to remove last value + * + * @param splited String [] + * @return String + */ + private static String removeLastValue(String splited[]) { + + StringBuilder builder = new StringBuilder(); + if (splited != null && splited.length > 0) { + for (int i = 1; i < splited.length - 1; i++) { + builder.append("/" + splited[i]); + } + } + return builder.toString(); + } + + public static void setActorRef(Object obj) { + actorRef = obj; + } + + private static Map genarateTelemetryInfoForError() { + + Map map = new HashMap<>(); + Map requestInfo = Global.requestInfo.get(ctx().flash().get(JsonKey.REQUEST_ID)); + Map contextInfo = (Map) requestInfo.get(JsonKey.CONTEXT); + Map params = new HashMap<>(); + params.put(JsonKey.ERR_TYPE, JsonKey.API_ACCESS); + + map.put(JsonKey.CONTEXT, contextInfo); + map.put(JsonKey.PARAMS, params); + return map; + } + + public void setChannelAndActorInfo(Context ctx, org.sunbird.common.request.Request reqObj) { + + reqObj.getContext().put(JsonKey.CHANNEL, ctx().flash().get(JsonKey.CHANNEL)); + reqObj.getContext().put(JsonKey.ACTOR_ID, ctx().flash().get(JsonKey.ACTOR_ID)); + reqObj.getContext().put(JsonKey.ACTOR_TYPE, ctx().flash().get(JsonKey.ACTOR_TYPE)); + } + + /** + * This method will set extra param to request body which is required for actor layer. + * + * @param request Request + * @param requestId String + * @param actorOpName String + * @param requestedUserId String + * @param env int + * @return Request + */ + public org.sunbird.common.request.Request setExtraParam( + org.sunbird.common.request.Request request, + String requestId, + String actorOpName, + String requestedUserId, + int env) { + request.setRequestId(requestId); + request.setOperation(actorOpName); + request.getRequest().put(JsonKey.CREATED_BY, requestedUserId); + request.setEnv(env); + return request; + } } diff --git a/service/app/controllers/LearnerController.java b/service/app/controllers/LearnerController.java index 4ed0706600..ae5e8335f2 100644 --- a/service/app/controllers/LearnerController.java +++ b/service/app/controllers/LearnerController.java @@ -1,14 +1,12 @@ -/** - * - */ +/** */ package controllers; +import com.fasterxml.jackson.databind.JsonNode; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; - import org.sunbird.common.exception.ProjectCommonException; import org.sunbird.common.models.util.ActorOperations; import org.sunbird.common.models.util.JsonKey; @@ -18,23 +16,20 @@ import org.sunbird.common.request.Request; import org.sunbird.common.request.RequestValidator; import org.sunbird.common.responsecode.ResponseCode; - -import com.fasterxml.jackson.databind.JsonNode; - import play.libs.F.Promise; import play.mvc.Result; import play.mvc.Results; /** * This controller will handler all the request related to learner state. - * + * * @author Manzarul */ public class LearnerController extends BaseController { /** * This method will provide list of enrolled courses for a user. User courses are stored in * Cassandra db. - * + * * @param uid user id for whom we need to collect all the courses. * @return Result */ @@ -49,7 +44,7 @@ public Promise getEnrolledCourses(String uid) { request.setOperation(ActorOperations.GET_COURSE.getValue()); request.setRequest(map); request.setRequestId(ExecutionContext.getRequestId()); - return actorResponseHandler(getActorRef(), request, timeout, JsonKey.COURSES, request()); + return actorResponseHandler(getActorRef(), request, timeout, JsonKey.COURSES, request()); } catch (Exception e) { return Promise.pure(createCommonExceptionResponse(e, request())); } @@ -57,7 +52,7 @@ public Promise getEnrolledCourses(String uid) { /** * This method will be called when user will enroll for a new course. - * + * * @return Result */ public Promise enrollCourse() { @@ -71,17 +66,16 @@ public Promise enrollCourse() { reqObj.setEnv(getEnvironment()); HashMap innerMap = new HashMap<>(); innerMap.put(JsonKey.COURSE, reqObj.getRequest()); - innerMap.put(JsonKey.REQUESTED_BY,ctx().flash().get(JsonKey.USER_ID)); + innerMap.put(JsonKey.REQUESTED_BY, ctx().flash().get(JsonKey.USER_ID)); innerMap.put(JsonKey.HEADER, getAllRequestHeaders(request())); reqObj.setRequest(innerMap); - return actorResponseHandler(getActorRef(), reqObj, timeout, null, request()); + return actorResponseHandler(getActorRef(), reqObj, timeout, null, request()); } catch (Exception e) { return Promise.pure(createCommonExceptionResponse(e, request())); } } /** - * * @param request * @return Map */ @@ -96,11 +90,10 @@ private Map getAllRequestHeaders(play.mvc.Http.Request request) return map; } - /** * This method will provide list of user content state. Content refer user activity {started,half * completed ,completed} against TOC (table of content). - * + * * @return Result */ public Promise getContentState() { @@ -117,14 +110,13 @@ public Promise getContentState() { } catch (Exception e) { return Promise.pure(createCommonExceptionResponse(e, request())); } - } @SuppressWarnings("unchecked") private Map createRequest(Request reqObj) { HashMap innerMap = new HashMap<>(); - innerMap.put(JsonKey.REQUESTED_BY,ctx().flash().get(JsonKey.USER_ID)); + innerMap.put(JsonKey.REQUESTED_BY, ctx().flash().get(JsonKey.USER_ID)); innerMap.put(JsonKey.USER_ID, reqObj.getRequest().get(JsonKey.USER_ID)); if ((null != reqObj.getRequest().get(JsonKey.CONTENT_IDS)) @@ -140,13 +132,14 @@ private Map createRequest(Request reqObj) { if ((((List) reqObj.getRequest().get(JsonKey.COURSE_IDS)).size() == 1) && ((List) reqObj.getRequest().get(JsonKey.CONTENT_IDS)).size() >= 0) { Map map = new HashMap(); - map.put(JsonKey.COURSE_ID, - ((List) reqObj.getRequest().get(JsonKey.COURSE_IDS)).get(0)); + map.put( + JsonKey.COURSE_ID, ((List) reqObj.getRequest().get(JsonKey.COURSE_IDS)).get(0)); map.put(JsonKey.CONTENT_IDS, (reqObj.getRequest().get(JsonKey.CONTENT_IDS))); innerMap.put(JsonKey.COURSE, map); return innerMap; } else { - throw new ProjectCommonException(ResponseCode.invalidRequestData.getErrorCode(), + throw new ProjectCommonException( + ResponseCode.invalidRequestData.getErrorCode(), ResponseCode.invalidRequestData.getErrorMessage(), ResponseCode.invalidRequestData.getResponseCode()); } @@ -156,7 +149,7 @@ private Map createRequest(Request reqObj) { /** * This method will update learner current state with last store state. - * + * * @return Result */ public Promise updateContentState() { @@ -170,7 +163,7 @@ public Promise updateContentState() { reqObj.setEnv(getEnvironment()); HashMap innerMap = new HashMap<>(); innerMap.put(JsonKey.CONTENTS, reqObj.getRequest().get(JsonKey.CONTENTS)); - innerMap.put(JsonKey.REQUESTED_BY,ctx().flash().get(JsonKey.USER_ID)); + innerMap.put(JsonKey.REQUESTED_BY, ctx().flash().get(JsonKey.USER_ID)); innerMap.put(JsonKey.USER_ID, reqObj.getRequest().get(JsonKey.USER_ID)); reqObj.setRequest(innerMap); return actorResponseHandler(getActorRef(), reqObj, timeout, null, request()); @@ -184,7 +177,6 @@ public Result getHealth() { } /** - * * @param all * @return */ @@ -192,9 +184,10 @@ public Result preflight(String all) { response().setHeader("Access-Control-Allow-Origin", "*"); response().setHeader("Allow", "*"); response().setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, DELETE, OPTIONS"); - response().setHeader("Access-Control-Allow-Headers", - "Origin, X-Requested-With, Content-Type, Accept, Referer, User-Agent,X-Consumer-ID,cid,ts,X-Device-ID,X-Authenticated-Userid,X-msgid,id,X-Access-TokenId"); + response() + .setHeader( + "Access-Control-Allow-Headers", + "Origin, X-Requested-With, Content-Type, Accept, Referer, User-Agent,X-Consumer-ID,cid,ts,X-Device-ID,X-Authenticated-Userid,X-msgid,id,X-Access-TokenId"); return ok(); } - } diff --git a/service/app/controllers/assessment/AssessmentController.java b/service/app/controllers/assessment/AssessmentController.java index 6a0a19f979..b98607465e 100644 --- a/service/app/controllers/assessment/AssessmentController.java +++ b/service/app/controllers/assessment/AssessmentController.java @@ -1,10 +1,9 @@ -/** - * - */ +/** */ package controllers.assessment; +import com.fasterxml.jackson.databind.JsonNode; +import controllers.BaseController; import java.util.HashMap; - import org.sunbird.common.models.util.ActorOperations; import org.sunbird.common.models.util.JsonKey; import org.sunbird.common.models.util.LoggerEnum; @@ -12,24 +11,19 @@ import org.sunbird.common.request.ExecutionContext; import org.sunbird.common.request.Request; import org.sunbird.common.request.RequestValidator; - -import com.fasterxml.jackson.databind.JsonNode; - -import controllers.BaseController; import play.libs.F.Promise; import play.mvc.Result; /** * This controller will handle all the API related to Assessment - * + * * @author Manzarul */ public class AssessmentController extends BaseController { - /** * This method will add assessment entry into cassandra DB. - * + * * @return Promise */ public Promise saveAssessment() { @@ -44,7 +38,7 @@ public Promise saveAssessment() { reqObj.setEnv(getEnvironment()); HashMap innerMap = new HashMap<>(); innerMap.put(JsonKey.ASSESSMENT, reqObj.getRequest()); - innerMap.put(JsonKey.REQUESTED_BY,ctx().flash().get(JsonKey.USER_ID)); + innerMap.put(JsonKey.REQUESTED_BY, ctx().flash().get(JsonKey.USER_ID)); reqObj.setRequest(innerMap); return actorResponseHandler(getActorRef(), reqObj, timeout, null, request()); } catch (Exception e) { @@ -56,7 +50,7 @@ public Promise saveAssessment() { * This method will provide user assessment details based on userid and course id. if only course * id is coming then it will provide all the user assessment for that course. if course id and * user id's both coming then it will provide only those users assessment for that course. - * + * * @return Promise */ public Promise getAssessment() { @@ -71,13 +65,11 @@ public Promise getAssessment() { reqObj.setEnv(getEnvironment()); HashMap innerMap = new HashMap<>(); innerMap.put(JsonKey.ASSESSMENT, reqObj.getRequest()); - innerMap.put(JsonKey.REQUESTED_BY,ctx().flash().get(JsonKey.USER_ID)); + innerMap.put(JsonKey.REQUESTED_BY, ctx().flash().get(JsonKey.USER_ID)); reqObj.setRequest(innerMap); return actorResponseHandler(getActorRef(), reqObj, timeout, null, request()); } catch (Exception e) { return Promise.pure(createCommonExceptionResponse(e, request())); } } - - } diff --git a/service/app/controllers/audit/AuditLogController.java b/service/app/controllers/audit/AuditLogController.java index eaf5299739..a847941349 100644 --- a/service/app/controllers/audit/AuditLogController.java +++ b/service/app/controllers/audit/AuditLogController.java @@ -1,29 +1,23 @@ package controllers.audit; +import com.fasterxml.jackson.databind.JsonNode; +import controllers.BaseController; import java.util.HashMap; - 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.ExecutionContext; import org.sunbird.common.request.Request; - -import com.fasterxml.jackson.databind.JsonNode; - -import controllers.BaseController; import play.libs.F.Promise; import play.mvc.Result; -/** - * Controller class to provide APIs for searching Audit Logs - * - */ +/** Controller class to provide APIs for searching Audit Logs */ public class AuditLogController extends BaseController { /** * Method to search audit history logs - * + * * @return */ public Promise searchAuditHistory() { @@ -43,5 +37,4 @@ public Promise searchAuditHistory() { return Promise.pure(createCommonExceptionResponse(e, request())); } } - } diff --git a/service/app/controllers/badges/BadgesController.java b/service/app/controllers/badges/BadgesController.java index f8f032cbd7..0035921528 100644 --- a/service/app/controllers/badges/BadgesController.java +++ b/service/app/controllers/badges/BadgesController.java @@ -1,8 +1,8 @@ -/** - * - */ +/** */ package controllers.badges; +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.models.util.LoggerEnum; @@ -10,31 +10,28 @@ import org.sunbird.common.request.ExecutionContext; import org.sunbird.common.request.Request; import org.sunbird.common.request.RequestValidator; - -import com.fasterxml.jackson.databind.JsonNode; - -import controllers.BaseController; import play.libs.F.Promise; import play.mvc.Result; /** * This controller will handle all api related to badges. - * @author Manzarul * + * @author Manzarul */ -public class BadgesController extends BaseController{ +public class BadgesController extends BaseController { /** * This method will provide all badges master data. + * * @return Promise */ public Promise getBadges() { try { - ProjectLogger.log("Call to get badges master data." , LoggerEnum.DEBUG.name()); + ProjectLogger.log("Call to get badges master data.", LoggerEnum.DEBUG.name()); Request reqObj = new Request(); reqObj.setOperation(ActorOperations.GET_ALL_BADGE.getValue()); reqObj.setRequestId(ExecutionContext.getRequestId()); - reqObj.getRequest().put(JsonKey.CREATED_BY,ctx().flash().get(JsonKey.USER_ID)); + reqObj.getRequest().put(JsonKey.CREATED_BY, ctx().flash().get(JsonKey.USER_ID)); reqObj.setEnv(getEnvironment()); return actorResponseHandler(getActorRef(), reqObj, timeout, null, request()); } catch (Exception e) { @@ -44,6 +41,7 @@ public Promise getBadges() { /** * This method will add badges to user profile. + * * @return Promise */ public Promise addUserBadges() { @@ -54,7 +52,7 @@ public Promise addUserBadges() { RequestValidator.validateAddUserBadge(reqObj); reqObj.setOperation(ActorOperations.ADD_USER_BADGE.getValue()); reqObj.setRequestId(ExecutionContext.getRequestId()); - reqObj.getRequest().put(JsonKey.CREATED_BY,ctx().flash().get(JsonKey.USER_ID)); + reqObj.getRequest().put(JsonKey.CREATED_BY, ctx().flash().get(JsonKey.USER_ID)); reqObj.setEnv(getEnvironment()); return actorResponseHandler(getActorRef(), reqObj, timeout, null, request()); } catch (Exception e) { diff --git a/service/app/controllers/badging/BadgeAssertionController.java b/service/app/controllers/badging/BadgeAssertionController.java index 5c55f7a40f..ad405a0227 100644 --- a/service/app/controllers/badging/BadgeAssertionController.java +++ b/service/app/controllers/badging/BadgeAssertionController.java @@ -1,8 +1,9 @@ -/** - * - */ +/** */ package controllers.badging; +import com.fasterxml.jackson.databind.JsonNode; +import controllers.BaseController; +import controllers.badging.validator.BadgeAssertionValidator; import org.sunbird.common.models.util.BadgingActorOperations; import org.sunbird.common.models.util.BadgingJsonKey; import org.sunbird.common.models.util.JsonKey; @@ -10,110 +11,120 @@ import org.sunbird.common.models.util.ProjectLogger; import org.sunbird.common.request.ExecutionContext; import org.sunbird.common.request.Request; - -import com.fasterxml.jackson.databind.JsonNode; - -import controllers.BaseController; -import controllers.badging.validator.BadgeAssertionValidator; import play.libs.F.Promise; import play.mvc.BodyParser; import play.mvc.Result; /** - * This controller will handle all api related to badge assertions. - * issue badge, revoke badge,get badge instance etc. - * @author Manzarul + * This controller will handle all api related to badge assertions. issue badge, revoke badge,get + * badge instance etc. * + * @author Manzarul */ public class BadgeAssertionController extends BaseController { - /** - * This method will be called to issue a badge either on content or user. - * Request Param {"issuerSlug":"unique String","badgeSlug" : "unique string", - * "recipientEmail":"email","evidence":"url , basically it is badge class public - * url" ,"notify":boolean} - * - * @return Promise - */ - public Promise issueBadge() { - try { - JsonNode requestData = request().body().asJson(); - ProjectLogger.log(" Issue badge method called = " + requestData, LoggerEnum.DEBUG.name()); - Request reqObj = (Request) mapper.RequestMapper.mapRequest(requestData, Request.class); - BadgeAssertionValidator.validateBadgeAssertion(reqObj); - reqObj = setExtraParam(reqObj, ExecutionContext.getRequestId(), - BadgingActorOperations.CREATE_BADGE_ASSERTION.getValue(), ctx().flash().get(JsonKey.USER_ID), - getEnvironment()); - return actorResponseHandler(getActorRef(), reqObj, timeout, null, request()); - } catch (Exception e) { - return Promise.pure(createCommonExceptionResponse(e, request())); - } - } + /** + * This method will be called to issue a badge either on content or user. Request Param + * {"issuerSlug":"unique String","badgeSlug" : "unique string", + * "recipientEmail":"email","evidence":"url , basically it is badge class public url" + * ,"notify":boolean} + * + * @return Promise + */ + public Promise issueBadge() { + try { + JsonNode requestData = request().body().asJson(); + ProjectLogger.log(" Issue badge method called = " + requestData, LoggerEnum.DEBUG.name()); + Request reqObj = (Request) mapper.RequestMapper.mapRequest(requestData, Request.class); + BadgeAssertionValidator.validateBadgeAssertion(reqObj); + reqObj = + setExtraParam( + reqObj, + ExecutionContext.getRequestId(), + BadgingActorOperations.CREATE_BADGE_ASSERTION.getValue(), + ctx().flash().get(JsonKey.USER_ID), + getEnvironment()); + return actorResponseHandler(getActorRef(), reqObj, timeout, null, request()); + } catch (Exception e) { + return Promise.pure(createCommonExceptionResponse(e, request())); + } + } - /** - * This controller will provide assertion details.based on - * assertionSlug. - * @param badgeSlug - * String - * @param assertionSlug - * @return Promise - */ - public Promise getAssertionDetails(String assertionId) { - try { - ProjectLogger.log(" get badge assertion details api called = " + assertionId, LoggerEnum.DEBUG.name()); - Request reqObj = new Request(); - reqObj.getRequest().put(BadgingJsonKey.ASSERTION_ID, assertionId); - BadgeAssertionValidator.validategetBadgeAssertion(reqObj); - reqObj = setExtraParam(reqObj, ExecutionContext.getRequestId(), - BadgingActorOperations.GET_BADGE_ASSERTION.getValue(), ctx().flash().get(JsonKey.USER_ID), - getEnvironment()); - return actorResponseHandler(getActorRef(), reqObj, timeout, null, request()); - } catch (Exception e) { - return Promise.pure(createCommonExceptionResponse(e, request())); - } - } + /** + * This controller will provide assertion details.based on assertionSlug. + * + * @param badgeSlug String + * @param assertionSlug + * @return Promise + */ + public Promise getAssertionDetails(String assertionId) { + try { + ProjectLogger.log( + " get badge assertion details api called = " + assertionId, LoggerEnum.DEBUG.name()); + Request reqObj = new Request(); + reqObj.getRequest().put(BadgingJsonKey.ASSERTION_ID, assertionId); + BadgeAssertionValidator.validategetBadgeAssertion(reqObj); + reqObj = + setExtraParam( + reqObj, + ExecutionContext.getRequestId(), + BadgingActorOperations.GET_BADGE_ASSERTION.getValue(), + ctx().flash().get(JsonKey.USER_ID), + getEnvironment()); + return actorResponseHandler(getActorRef(), reqObj, timeout, null, request()); + } catch (Exception e) { + return Promise.pure(createCommonExceptionResponse(e, request())); + } + } - /** - * This controller will provide list of assertions based on issuerSlug,badgeSlug and - * assertionSlug - * @return Promise - */ - public Promise getAssertionList() { - try { - JsonNode requestData = request().body().asJson(); - ProjectLogger.log(" get assertion list api called = " + requestData, LoggerEnum.DEBUG.name()); - Request reqObj = (Request) mapper.RequestMapper.mapRequest(requestData, Request.class); - BadgeAssertionValidator.validateGetAssertionList(reqObj); - reqObj = setExtraParam(reqObj, ExecutionContext.getRequestId(), - BadgingActorOperations.GET_BADGE_ASSERTION_LIST.getValue(), ctx().flash().get(JsonKey.USER_ID), - getEnvironment()); - return actorResponseHandler(getActorRef(), reqObj, timeout, null, request()); - } catch (Exception e) { - return Promise.pure(createCommonExceptionResponse(e, request())); - } - } + /** + * This controller will provide list of assertions based on issuerSlug,badgeSlug and assertionSlug + * + * @return Promise + */ + public Promise getAssertionList() { + try { + JsonNode requestData = request().body().asJson(); + ProjectLogger.log(" get assertion list api called = " + requestData, LoggerEnum.DEBUG.name()); + Request reqObj = (Request) mapper.RequestMapper.mapRequest(requestData, Request.class); + BadgeAssertionValidator.validateGetAssertionList(reqObj); + reqObj = + setExtraParam( + reqObj, + ExecutionContext.getRequestId(), + BadgingActorOperations.GET_BADGE_ASSERTION_LIST.getValue(), + ctx().flash().get(JsonKey.USER_ID), + getEnvironment()); + return actorResponseHandler(getActorRef(), reqObj, timeout, null, request()); + } catch (Exception e) { + return Promise.pure(createCommonExceptionResponse(e, request())); + } + } - /** - * This controller will revoke user assertion based on issuerSlug, - * badgeSlug and assertionSlug - * @param badgeSlug - * String - * @param assertionSlug - * @return Promise - */ - @BodyParser.Of(BodyParser.Json.class) - public Promise revokeAssertion() { - try { - JsonNode requestData = request().body().asJson(); - ProjectLogger.log(" Revoke badge method called = " + requestData, LoggerEnum.DEBUG.name()); - Request reqObj = (Request) mapper.RequestMapper.mapRequest(requestData, Request.class); - BadgeAssertionValidator.validateRevokeAssertion(reqObj); - reqObj = setExtraParam(reqObj, ExecutionContext.getRequestId(), - BadgingActorOperations.REVOKE_BADGE.getValue(), ctx().flash().get(JsonKey.USER_ID), - getEnvironment()); - return actorResponseHandler(getActorRef(), reqObj, timeout, null, request()); - } catch (Exception e) { - return Promise.pure(createCommonExceptionResponse(e, request())); - } - } + /** + * This controller will revoke user assertion based on issuerSlug, badgeSlug and assertionSlug + * + * @param badgeSlug String + * @param assertionSlug + * @return Promise + */ + @BodyParser.Of(BodyParser.Json.class) + public Promise revokeAssertion() { + try { + JsonNode requestData = request().body().asJson(); + ProjectLogger.log(" Revoke badge method called = " + requestData, LoggerEnum.DEBUG.name()); + Request reqObj = (Request) mapper.RequestMapper.mapRequest(requestData, Request.class); + BadgeAssertionValidator.validateRevokeAssertion(reqObj); + reqObj = + setExtraParam( + reqObj, + ExecutionContext.getRequestId(), + BadgingActorOperations.REVOKE_BADGE.getValue(), + ctx().flash().get(JsonKey.USER_ID), + getEnvironment()); + return actorResponseHandler(getActorRef(), reqObj, timeout, null, request()); + } catch (Exception e) { + return Promise.pure(createCommonExceptionResponse(e, request())); + } + } } diff --git a/service/app/controllers/badging/BadgeClassController.java b/service/app/controllers/badging/BadgeClassController.java index 6ac9609302..8a5bfeea98 100644 --- a/service/app/controllers/badging/BadgeClassController.java +++ b/service/app/controllers/badging/BadgeClassController.java @@ -1,11 +1,13 @@ package controllers.badging; +import com.fasterxml.jackson.databind.JsonNode; +import controllers.BaseController; +import controllers.badging.validator.BadgeClassValidator; import java.io.FileInputStream; import java.io.InputStream; import java.util.HashMap; import java.util.List; import java.util.Map; - import org.apache.commons.io.IOUtils; import org.sunbird.common.models.util.BadgingActorOperations; import org.sunbird.common.models.util.BadgingJsonKey; @@ -13,11 +15,6 @@ import org.sunbird.common.models.util.LoggerEnum; import org.sunbird.common.models.util.ProjectLogger; import org.sunbird.common.request.Request; - -import com.fasterxml.jackson.databind.JsonNode; - -import controllers.BaseController; -import controllers.badging.validator.BadgeClassValidator; import play.libs.F; import play.mvc.Http; import play.mvc.Result; @@ -28,132 +25,126 @@ * @author B Vinaya Kumar */ public class BadgeClassController extends BaseController { - /** - * Create a new badge class for a particular issuer. - * - * Request body contains following parameters: - * issuerId: The ID of the Issuer to be owner of the new Badge Class - * name: The name of the Badge Class - * description: A short description of the new Badge Class. - * image: An image to represent the Badge Class. - * criteria: Either a text string or a URL of a remotely hosted page describing the criteria - * rootOrgId: Root organisation ID - * type: Badge class type (user / content) - * subtype: Badge class subtype (e.g. award) - * roles: JSON array of roles (e.g. [ "OFFICIAL_TEXTBOOK_BADGE_ISSUER" ]) - * - * @return Return a promise for create badge class API result. - */ - public F.Promise createBadgeClass() { - ProjectLogger.log("createBadgeClass called", LoggerEnum.DEBUG.name()); - - try { - Request request = createAndInitRequest(BadgingActorOperations.CREATE_BADGE_CLASS.getValue()); - - HashMap map = new HashMap<>(); - - Http.MultipartFormData multipartBody = request().body().asMultipartFormData(); - - if (multipartBody != null) { - Map data = multipartBody.asFormUrlEncoded(); - for (Map.Entry entry : data.entrySet()) { - map.put(entry.getKey(), entry.getValue()[0]); - } - - List imageFilePart = multipartBody.getFiles(); - if (imageFilePart.size() > 0) { - InputStream inputStream = new FileInputStream(imageFilePart.get(0).getFile()); - byte[] imageByteArray = IOUtils.toByteArray(inputStream); - map.put(JsonKey.IMAGE, imageByteArray); - } - } - - request.setRequest(map); - - new BadgeClassValidator().validateCreateBadgeClass(request, request().headers()); - - return actorResponseHandler(getActorRef(), request, timeout, null, request()); - } catch (Exception e) { - ProjectLogger.log("createBadgeClass: exception = ", e); - - return F.Promise.pure(createCommonExceptionResponse(e, request())); + /** + * Create a new badge class for a particular issuer. + * + *

Request body contains following parameters: issuerId: The ID of the Issuer to be owner of + * the new Badge Class name: The name of the Badge Class description: A short description of the + * new Badge Class. image: An image to represent the Badge Class. criteria: Either a text string + * or a URL of a remotely hosted page describing the criteria rootOrgId: Root organisation ID + * type: Badge class type (user / content) subtype: Badge class subtype (e.g. award) roles: JSON + * array of roles (e.g. [ "OFFICIAL_TEXTBOOK_BADGE_ISSUER" ]) + * + * @return Return a promise for create badge class API result. + */ + public F.Promise createBadgeClass() { + ProjectLogger.log("createBadgeClass called", LoggerEnum.DEBUG.name()); + + try { + Request request = createAndInitRequest(BadgingActorOperations.CREATE_BADGE_CLASS.getValue()); + + HashMap map = new HashMap<>(); + + Http.MultipartFormData multipartBody = request().body().asMultipartFormData(); + + if (multipartBody != null) { + Map data = multipartBody.asFormUrlEncoded(); + for (Map.Entry entry : data.entrySet()) { + map.put(entry.getKey(), entry.getValue()[0]); } - } - /** - * Get details of requsted badge class. - * - * @param badgeId The ID of the Badge Class whose details to view - * @return Return a promise for get badge class API result. - */ - public F.Promise getBadgeClass(String badgeId) { - ProjectLogger.log("getBadgeClass called.", LoggerEnum.DEBUG.name()); + List imageFilePart = multipartBody.getFiles(); + if (imageFilePart.size() > 0) { + InputStream inputStream = new FileInputStream(imageFilePart.get(0).getFile()); + byte[] imageByteArray = IOUtils.toByteArray(inputStream); + map.put(JsonKey.IMAGE, imageByteArray); + } + } - try { - Request request = createAndInitRequest(BadgingActorOperations.GET_BADGE_CLASS.getValue()); - request.put(BadgingJsonKey.BADGE_ID, badgeId); + request.setRequest(map); - new BadgeClassValidator().validateGetBadgeClass(request); + new BadgeClassValidator().validateCreateBadgeClass(request, request().headers()); - return actorResponseHandler(getActorRef(), request, timeout, null, request()); - } catch (Exception e) { - ProjectLogger.log("getBadgeClass: exception = ", e); + return actorResponseHandler(getActorRef(), request, timeout, null, request()); + } catch (Exception e) { + ProjectLogger.log("createBadgeClass: exception = ", e); - return F.Promise.pure(createCommonExceptionResponse(e, request())); - } + return F.Promise.pure(createCommonExceptionResponse(e, request())); } + } - /** - * Get list of badge classes for given issuer(s) and matching given context. - * - * Request containing following filters: - * issuerList: List of Issuer IDs whose badge classes are to be listed - * badgeList: List of badge IDs whose badge classes are to be listed - * rootOrgId: Root organisation ID - * type: Badge class type (user / content) - * subtype: Badge class subtype (e.g. award) - * roles: JSON array of roles (e.g. [ "OFFICIAL_TEXTBOOK_BADGE_ISSUER" ]) - * - * @return Return a promise for search badge class API result. - */ - public F.Promise searchBadgeClass() { - ProjectLogger.log("searchBadgeClass called.", LoggerEnum.DEBUG.name()); - - try { - JsonNode bodyJson = request().body().asJson(); - - Request request = createAndInitRequest(BadgingActorOperations.SEARCH_BADGE_CLASS.getValue(), bodyJson); - - new BadgeClassValidator().validateSearchBadgeClass(request); - - return actorResponseHandler(getActorRef(), request, timeout, null, request()); - } catch (Exception e) { - ProjectLogger.log("searchBadgeClass: exception = ", e); - - return F.Promise.pure(createCommonExceptionResponse(e, request())); - } + /** + * Get details of requsted badge class. + * + * @param badgeId The ID of the Badge Class whose details to view + * @return Return a promise for get badge class API result. + */ + public F.Promise getBadgeClass(String badgeId) { + ProjectLogger.log("getBadgeClass called.", LoggerEnum.DEBUG.name()); + + try { + Request request = createAndInitRequest(BadgingActorOperations.GET_BADGE_CLASS.getValue()); + request.put(BadgingJsonKey.BADGE_ID, badgeId); + + new BadgeClassValidator().validateGetBadgeClass(request); + + return actorResponseHandler(getActorRef(), request, timeout, null, request()); + } catch (Exception e) { + ProjectLogger.log("getBadgeClass: exception = ", e); + + return F.Promise.pure(createCommonExceptionResponse(e, request())); } + } + + /** + * Get list of badge classes for given issuer(s) and matching given context. + * + *

Request containing following filters: issuerList: List of Issuer IDs whose badge classes are + * to be listed badgeList: List of badge IDs whose badge classes are to be listed rootOrgId: Root + * organisation ID type: Badge class type (user / content) subtype: Badge class subtype (e.g. + * award) roles: JSON array of roles (e.g. [ "OFFICIAL_TEXTBOOK_BADGE_ISSUER" ]) + * + * @return Return a promise for search badge class API result. + */ + public F.Promise searchBadgeClass() { + ProjectLogger.log("searchBadgeClass called.", LoggerEnum.DEBUG.name()); + + try { + JsonNode bodyJson = request().body().asJson(); + + Request request = + createAndInitRequest(BadgingActorOperations.SEARCH_BADGE_CLASS.getValue(), bodyJson); + + new BadgeClassValidator().validateSearchBadgeClass(request); + + return actorResponseHandler(getActorRef(), request, timeout, null, request()); + } catch (Exception e) { + ProjectLogger.log("searchBadgeClass: exception = ", e); + + return F.Promise.pure(createCommonExceptionResponse(e, request())); + } + } - /** - * Delete a badge class that has never been issued. - * - * @param badgeId The ID of the Badge Class to delete - * @return Return a promise for delete badge class API result. - */ - public F.Promise deleteBadgeClass(String badgeId) { - ProjectLogger.log("deleteBadgeClass called.", LoggerEnum.DEBUG.name()); + /** + * Delete a badge class that has never been issued. + * + * @param badgeId The ID of the Badge Class to delete + * @return Return a promise for delete badge class API result. + */ + public F.Promise deleteBadgeClass(String badgeId) { + ProjectLogger.log("deleteBadgeClass called.", LoggerEnum.DEBUG.name()); - try { - Request request = createAndInitRequest(BadgingActorOperations.DELETE_BADGE_CLASS.getValue()); - request.put(BadgingJsonKey.BADGE_ID, badgeId); + try { + Request request = createAndInitRequest(BadgingActorOperations.DELETE_BADGE_CLASS.getValue()); + request.put(BadgingJsonKey.BADGE_ID, badgeId); - new BadgeClassValidator().validateDeleteBadgeClass(request); + new BadgeClassValidator().validateDeleteBadgeClass(request); - return actorResponseHandler(getActorRef(), request, timeout, null, request()); - } catch (Exception e) { - ProjectLogger.log("deleteBadgeClass: exception = ", e); + return actorResponseHandler(getActorRef(), request, timeout, null, request()); + } catch (Exception e) { + ProjectLogger.log("deleteBadgeClass: exception = ", e); - return F.Promise.pure(createCommonExceptionResponse(e, request())); - } + return F.Promise.pure(createCommonExceptionResponse(e, request())); } + } } diff --git a/service/app/controllers/badging/BadgeIssuerController.java b/service/app/controllers/badging/BadgeIssuerController.java index 19697bc76f..abaf2eed15 100644 --- a/service/app/controllers/badging/BadgeIssuerController.java +++ b/service/app/controllers/badging/BadgeIssuerController.java @@ -1,5 +1,8 @@ package controllers.badging; +import com.fasterxml.jackson.databind.JsonNode; +import controllers.BaseController; +import controllers.badging.validator.BadgeIssuerRequestValidator; import java.io.File; import java.io.FileInputStream; import java.io.IOException; @@ -8,7 +11,6 @@ import java.util.List; import java.util.Map; import java.util.Map.Entry; - import org.apache.commons.io.IOUtils; import org.sunbird.badge.BadgeOperations; import org.sunbird.common.exception.ProjectCommonException; @@ -18,24 +20,17 @@ import org.sunbird.common.request.ExecutionContext; import org.sunbird.common.request.Request; import org.sunbird.common.responsecode.ResponseCode; - -import com.fasterxml.jackson.databind.JsonNode; - -import controllers.BaseController; -import controllers.badging.validator.BadgeIssuerRequestValidator; import play.libs.F.Promise; import play.mvc.Http.MultipartFormData; import play.mvc.Http.MultipartFormData.FilePart; import play.mvc.Result; -/** - * Created by arvind on 2/3/18. - * This controller is for handling the badge issuer apis. - */ +/** Created by arvind on 2/3/18. This controller is for handling the badge issuer apis. */ public class BadgeIssuerController extends BaseController { /** * This method will add badges to user profile. + * * @return Promise */ public Promise createBadgeIssuer() { @@ -46,21 +41,28 @@ public Promise createBadgeIssuer() { JsonNode requestData = request().body().asJson(); ProjectLogger.log("call to create badge issuer api." + requestData, LoggerEnum.DEBUG.name()); if (body != null) { - map = readFormData(body, map); - }else if (null != requestData) { + map = readFormData(body, map); + } else if (null != requestData) { reqObj = (Request) mapper.RequestMapper.mapRequest(request().body().asJson(), Request.class); map.putAll(reqObj.getRequest()); } else { - ProjectCommonException e = new ProjectCommonException( - ResponseCode.invalidData.getErrorCode(), ResponseCode.invalidData.getErrorMessage(), - ResponseCode.CLIENT_ERROR.getResponseCode()); + ProjectCommonException e = + new ProjectCommonException( + ResponseCode.invalidData.getErrorCode(), + ResponseCode.invalidData.getErrorMessage(), + ResponseCode.CLIENT_ERROR.getResponseCode()); return Promise.pure(createCommonExceptionResponse(e, request())); } reqObj.getRequest().putAll(map); BadgeIssuerRequestValidator.validateCreateBadgeIssuer(reqObj); - reqObj = setExtraParam(reqObj, ExecutionContext.getRequestId(), BadgeOperations.createBadgeIssuer.name(), - ctx().flash().get(JsonKey.USER_ID), getEnvironment()); + reqObj = + setExtraParam( + reqObj, + ExecutionContext.getRequestId(), + BadgeOperations.createBadgeIssuer.name(), + ctx().flash().get(JsonKey.USER_ID), + getEnvironment()); return actorResponseHandler(getActorRef(), reqObj, timeout, null, request()); } catch (Exception e) { return Promise.pure(createCommonExceptionResponse(e, request())); @@ -69,30 +71,42 @@ public Promise createBadgeIssuer() { /** * This method will add badges to user profile. + * * @return Promise */ - public Promise getBadgeIssuer(String issuerId) { - try { - Request reqObj = new Request(); - reqObj = setExtraParam(reqObj, ExecutionContext.getRequestId(), BadgeOperations.getBadgeIssuer.name(), - ctx().flash().get(JsonKey.USER_ID), getEnvironment()); - reqObj.getRequest().put(JsonKey.SLUG, issuerId); - BadgeIssuerRequestValidator.validateGetBadgeIssuerDetail(reqObj); - return actorResponseHandler(getActorRef(), reqObj, timeout, null, request()); - } catch (Exception e) { - return Promise.pure(createCommonExceptionResponse(e, request())); - } - } + public Promise getBadgeIssuer(String issuerId) { + try { + Request reqObj = new Request(); + reqObj = + setExtraParam( + reqObj, + ExecutionContext.getRequestId(), + BadgeOperations.getBadgeIssuer.name(), + ctx().flash().get(JsonKey.USER_ID), + getEnvironment()); + reqObj.getRequest().put(JsonKey.SLUG, issuerId); + BadgeIssuerRequestValidator.validateGetBadgeIssuerDetail(reqObj); + return actorResponseHandler(getActorRef(), reqObj, timeout, null, request()); + } catch (Exception e) { + return Promise.pure(createCommonExceptionResponse(e, request())); + } + } /** * This method will add badges to user profile. + * * @return Promise */ public Promise getAllIssuer() { try { Request reqObj = new Request(); - reqObj = setExtraParam(reqObj, ExecutionContext.getRequestId(), BadgeOperations.getAllIssuer.name(), - ctx().flash().get(JsonKey.USER_ID), getEnvironment()); + reqObj = + setExtraParam( + reqObj, + ExecutionContext.getRequestId(), + BadgeOperations.getAllIssuer.name(), + ctx().flash().get(JsonKey.USER_ID), + getEnvironment()); return actorResponseHandler(getActorRef(), reqObj, timeout, null, request()); } catch (Exception e) { return Promise.pure(createCommonExceptionResponse(e, request())); @@ -101,14 +115,20 @@ public Promise getAllIssuer() { /** * This method will add badges to user profile. + * * @return Promise */ public Promise deleteBadgeIssuer(String issuerId) { try { Request reqObj = new Request(); - reqObj = setExtraParam(reqObj, ExecutionContext.getRequestId(), BadgeOperations.deleteIssuer.name(), - ctx().flash().get(JsonKey.USER_ID), getEnvironment()); - reqObj.getRequest().put(JsonKey.SLUG , issuerId); + reqObj = + setExtraParam( + reqObj, + ExecutionContext.getRequestId(), + BadgeOperations.deleteIssuer.name(), + ctx().flash().get(JsonKey.USER_ID), + getEnvironment()); + reqObj.getRequest().put(JsonKey.SLUG, issuerId); BadgeIssuerRequestValidator.validateGetBadgeIssuerDetail(reqObj); return actorResponseHandler(getActorRef(), reqObj, timeout, null, request()); } catch (Exception e) { @@ -117,27 +137,27 @@ public Promise deleteBadgeIssuer(String issuerId) { } /** - * This method will read from input data and put all the - * requested key and value inside a map. + * This method will read from input data and put all the requested key and value inside a map. + * * @param body MultipartFormData * @param map Map * @return Map * @throws IOException */ - private Map readFormData (MultipartFormData body , Map map) throws IOException{ - Map data = body.asFormUrlEncoded(); - for (Entry entry : data.entrySet()) { - map.put(entry.getKey(), entry.getValue()[0]); - } - List filePart = body.getFiles(); - if(filePart != null && !filePart.isEmpty()){ - File f = filePart.get(0).getFile(); - InputStream is = new FileInputStream(f); - byte[] byteArray = IOUtils.toByteArray(is); - map.put(JsonKey.FILE_NAME , filePart.get(0).getFilename()); - map.put(JsonKey.IMAGE, byteArray); - } - return map; + private Map readFormData(MultipartFormData body, Map map) + throws IOException { + Map data = body.asFormUrlEncoded(); + for (Entry entry : data.entrySet()) { + map.put(entry.getKey(), entry.getValue()[0]); + } + List filePart = body.getFiles(); + if (filePart != null && !filePart.isEmpty()) { + File f = filePart.get(0).getFile(); + InputStream is = new FileInputStream(f); + byte[] byteArray = IOUtils.toByteArray(is); + map.put(JsonKey.FILE_NAME, filePart.get(0).getFilename()); + map.put(JsonKey.IMAGE, byteArray); + } + return map; } - } diff --git a/service/app/controllers/badging/validator/BadgeAssertionValidator.java b/service/app/controllers/badging/validator/BadgeAssertionValidator.java index ff9be1670d..6bda1df669 100644 --- a/service/app/controllers/badging/validator/BadgeAssertionValidator.java +++ b/service/app/controllers/badging/validator/BadgeAssertionValidator.java @@ -3,7 +3,6 @@ import java.text.MessageFormat; import java.util.List; import java.util.Map; - import org.apache.commons.lang3.StringUtils; import org.sunbird.common.exception.ProjectCommonException; import org.sunbird.common.models.util.BadgingJsonKey; @@ -15,143 +14,166 @@ /** * This class will do the request validation for Badge assertion. - * @author Manzarul * + * @author Manzarul */ public class BadgeAssertionValidator { - private static final int ERROR_CODE = ResponseCode.CLIENT_ERROR.getResponseCode(); + private static final int ERROR_CODE = ResponseCode.CLIENT_ERROR.getResponseCode(); + + /* + * Default private constructor + */ + private BadgeAssertionValidator() {} + + /** + * This method will do the basic validation of badge assertion request. + * + * @param request Request + */ + public static void validateBadgeAssertion(Request request) { - /* - * Default private constructor - */ - private BadgeAssertionValidator() { - } - - /** - * This method will do the basic validation of badge assertion - * request. - * @param request Request - */ - public static void validateBadgeAssertion(Request request) { + if (StringUtils.isBlank((String) request.getRequest().get(BadgingJsonKey.ISSUER_ID))) { + throw new ProjectCommonException( + ResponseCode.issuerIdRequired.getErrorCode(), + ResponseCode.issuerIdRequired.getErrorMessage(), + ERROR_CODE); + } + if (StringUtils.isBlank((String) request.getRequest().get(BadgingJsonKey.BADGE_ID))) { + throw new ProjectCommonException( + ResponseCode.badgeIdRequired.getErrorCode(), + ResponseCode.badgeIdRequired.getErrorMessage(), + ERROR_CODE); + } + if (!StringUtils.isBlank((String) request.getRequest().get(BadgingJsonKey.EVIDENCE))) { + boolean response = + ProjectUtil.isUrlvalid((String) request.getRequest().get(BadgingJsonKey.EVIDENCE)); + if (!response) { + throw new ProjectCommonException( + ResponseCode.evidenceRequired.getErrorCode(), + ResponseCode.evidenceRequired.getErrorMessage(), + ERROR_CODE); + } + } + if (StringUtils.isBlank((String) request.getRequest().get(BadgingJsonKey.RECIPIENT_ID))) { + throw new ProjectCommonException( + ResponseCode.recipientIdRequired.getErrorCode(), + ResponseCode.recipientIdRequired.getErrorMessage(), + ERROR_CODE); + } + if (StringUtils.isBlank((String) request.getRequest().get(BadgingJsonKey.RECIPIENT_TYPE))) { + throw new ProjectCommonException( + ResponseCode.recipientTypeRequired.getErrorCode(), + ResponseCode.recipientTypeRequired.getErrorMessage(), + ERROR_CODE); + } + if (!matchRecipientType((String) request.getRequest().get(BadgingJsonKey.RECIPIENT_TYPE))) { + throw new ProjectCommonException( + ResponseCode.invalidRecipientType.getErrorCode(), + ResponseCode.invalidRecipientType.getErrorMessage(), + ERROR_CODE); + } + } - if (StringUtils.isBlank((String) request.getRequest().get(BadgingJsonKey.ISSUER_ID))) { - throw new ProjectCommonException(ResponseCode.issuerIdRequired.getErrorCode(), - ResponseCode.issuerIdRequired.getErrorMessage(), ERROR_CODE); - } - if (StringUtils.isBlank((String) request.getRequest().get(BadgingJsonKey.BADGE_ID))) { - throw new ProjectCommonException(ResponseCode.badgeIdRequired.getErrorCode(), - ResponseCode.badgeIdRequired.getErrorMessage(), ERROR_CODE); + /** + * This method will verify null and empty check for requested param. if any param is null or empty + * then it will throw exception + * + * @param request Request + */ + public static void validategetBadgeAssertion(Request request) { + if (StringUtils.isBlank((String) request.getRequest().get(BadgingJsonKey.ASSERTION_ID))) { + throw new ProjectCommonException( + ResponseCode.assertionIdRequired.getErrorCode(), + ResponseCode.assertionIdRequired.getErrorMessage(), + ERROR_CODE); + } + } - } - if (!StringUtils.isBlank((String) request.getRequest().get(BadgingJsonKey.EVIDENCE))) { - boolean response = ProjectUtil.isUrlvalid((String) request.getRequest().get(BadgingJsonKey.EVIDENCE)); - if (!response) { - throw new ProjectCommonException(ResponseCode.evidenceRequired.getErrorCode(), - ResponseCode.evidenceRequired.getErrorMessage(), ERROR_CODE); - } - } - if (StringUtils.isBlank((String) request.getRequest().get(BadgingJsonKey.RECIPIENT_ID))) { - throw new ProjectCommonException(ResponseCode.recipientIdRequired.getErrorCode(), - ResponseCode.recipientIdRequired.getErrorMessage(), ERROR_CODE); - } - if (StringUtils.isBlank((String) request.getRequest().get(BadgingJsonKey.RECIPIENT_TYPE))) { - throw new ProjectCommonException(ResponseCode.recipientTypeRequired.getErrorCode(), - ResponseCode.recipientTypeRequired.getErrorMessage(), ERROR_CODE); - } - if (!matchRecipientType((String) request.getRequest().get(BadgingJsonKey.RECIPIENT_TYPE))) { - throw new ProjectCommonException(ResponseCode.invalidRecipientType.getErrorCode(), - ResponseCode.invalidRecipientType.getErrorMessage(), ERROR_CODE); - } + /** + * This method will validate get assertion list requested data. expected data "assertions": [{ + * "issuerId": "oracle-university", "badgeId": "java-se-8-programmer", "assertionId": + * "1ebceaf1-b63b-4edb-97c0-bfc6e3235408" }] + * + * @param request + */ + public static void validateGetAssertionList(Request request) { + Map filtesMap = (Map) request.getRequest().get(JsonKey.FILTERS); + if (filtesMap == null) { + throw new ProjectCommonException( + ResponseCode.invalidRequestData.getErrorCode(), + ResponseCode.invalidRequestData.getErrorMessage(), + ERROR_CODE); + } + Object obj = filtesMap.get(BadgingJsonKey.ASSERTIONS); + if (obj == null || !(obj instanceof List)) { + throw new ProjectCommonException( + ResponseCode.invalidRequestData.getErrorCode(), + ResponseCode.invalidRequestData.getErrorMessage(), + ERROR_CODE); + } + List assertionData = (List) obj; + int size = + Integer.parseInt( + PropertiesCache.getInstance().getProperty(BadgingJsonKey.BADGING_ASSERTION_LIST_SIZE)); + if (assertionData.size() > size) { + throw new ProjectCommonException( + ResponseCode.sizeLimitExceed.getErrorCode(), + MessageFormat.format(ResponseCode.sizeLimitExceed.getErrorMessage(), size), + ERROR_CODE); + } - } - - /** - * This method will verify null and empty check for requested param. - * if any param is null or empty then it will throw exception - * @param request Request - */ - public static void validategetBadgeAssertion(Request request) { - if (StringUtils.isBlank((String)request.getRequest().get(BadgingJsonKey.ASSERTION_ID))) { - throw new ProjectCommonException(ResponseCode.assertionIdRequired.getErrorCode(), - ResponseCode.assertionIdRequired.getErrorMessage(), ERROR_CODE); + for (String assertionId : assertionData) { + Request temp = new Request(); + temp.getRequest().put(BadgingJsonKey.ASSERTION_ID, assertionId); + validategetBadgeAssertion(temp); + } + } - } - } - - /** - * This method will validate get assertion list requested data. - * expected data - * "assertions": [{ - * "issuerId": "oracle-university", - * "badgeId": "java-se-8-programmer", - * "assertionId": "1ebceaf1-b63b-4edb-97c0-bfc6e3235408" - * }] - * @param request - */ - public static void validateGetAssertionList(Request request) { - Map filtesMap = (Map) request.getRequest().get(JsonKey.FILTERS); - if (filtesMap == null) { - throw new ProjectCommonException(ResponseCode.invalidRequestData.getErrorCode(), - ResponseCode.invalidRequestData.getErrorMessage(), ERROR_CODE); - } - Object obj = filtesMap.get(BadgingJsonKey.ASSERTIONS); - if (obj == null || !(obj instanceof List)) { - throw new ProjectCommonException(ResponseCode.invalidRequestData.getErrorCode(), - ResponseCode.invalidRequestData.getErrorMessage(), ERROR_CODE); - } - List assertionData = (List) obj; - int size = Integer - .parseInt(PropertiesCache.getInstance().getProperty(BadgingJsonKey.BADGING_ASSERTION_LIST_SIZE)); - if (assertionData.size() > size) { - throw new ProjectCommonException(ResponseCode.sizeLimitExceed.getErrorCode(), - MessageFormat.format(ResponseCode.sizeLimitExceed.getErrorMessage(), size), ERROR_CODE); - } + /** + * This method will validate revoke assertion request data. + * + * @param request Request + */ + public static void validateRevokeAssertion(Request request) { + validategetBadgeAssertion(request); + if (StringUtils.isBlank((String) request.getRequest().get(BadgingJsonKey.REVOCATION_REASON))) { + throw new ProjectCommonException( + ResponseCode.revocationReasonRequired.getErrorCode(), + ResponseCode.revocationReasonRequired.getErrorMessage(), + ERROR_CODE); + } + if (StringUtils.isBlank((String) request.getRequest().get(BadgingJsonKey.RECIPIENT_ID))) { + throw new ProjectCommonException( + ResponseCode.recipientIdRequired.getErrorCode(), + ResponseCode.recipientIdRequired.getErrorMessage(), + ERROR_CODE); + } + if (StringUtils.isBlank((String) request.getRequest().get(BadgingJsonKey.RECIPIENT_TYPE))) { + throw new ProjectCommonException( + ResponseCode.recipientTypeRequired.getErrorCode(), + ResponseCode.recipientTypeRequired.getErrorMessage(), + ERROR_CODE); + } + if (!matchRecipientType((String) request.getRequest().get(BadgingJsonKey.RECIPIENT_TYPE))) { + throw new ProjectCommonException( + ResponseCode.invalidRecipientType.getErrorCode(), + ResponseCode.invalidRecipientType.getErrorMessage(), + ERROR_CODE); + } + } - for (String assertionId : assertionData) { - Request temp = new Request(); - temp.getRequest().put(BadgingJsonKey.ASSERTION_ID, assertionId); - validategetBadgeAssertion(temp); - } - } - - - /** - * This method will validate revoke assertion request data. - * @param request Request - */ - public static void validateRevokeAssertion(Request request) { - validategetBadgeAssertion(request); - if (StringUtils.isBlank((String) request.getRequest().get(BadgingJsonKey.REVOCATION_REASON))) { - throw new ProjectCommonException(ResponseCode.revocationReasonRequired.getErrorCode(), - ResponseCode.revocationReasonRequired.getErrorMessage(), ERROR_CODE); - } - if (StringUtils.isBlank((String) request.getRequest().get(BadgingJsonKey.RECIPIENT_ID))) { - throw new ProjectCommonException(ResponseCode.recipientIdRequired.getErrorCode(), - ResponseCode.recipientIdRequired.getErrorMessage(), ERROR_CODE); - } - if (StringUtils.isBlank((String) request.getRequest().get(BadgingJsonKey.RECIPIENT_TYPE))) { - throw new ProjectCommonException(ResponseCode.recipientTypeRequired.getErrorCode(), - ResponseCode.recipientTypeRequired.getErrorMessage(), ERROR_CODE); - } - if (!matchRecipientType((String) request.getRequest().get(BadgingJsonKey.RECIPIENT_TYPE))) { - throw new ProjectCommonException(ResponseCode.invalidRecipientType.getErrorCode(), - ResponseCode.invalidRecipientType.getErrorMessage(), ERROR_CODE); - } - } - - /** - * This method will check valid recipient type. - * @param recipientType String - * @return boolean - */ - private static boolean matchRecipientType(String recipientType) { - if (BadgingJsonKey.BADGE_TYPE_USER.equalsIgnoreCase(recipientType) - || BadgingJsonKey.BADGE_TYPE_CONTENT.equalsIgnoreCase(recipientType)) { - return true; - } - return false; - } - - + /** + * This method will check valid recipient type. + * + * @param recipientType String + * @return boolean + */ + private static boolean matchRecipientType(String recipientType) { + if (BadgingJsonKey.BADGE_TYPE_USER.equalsIgnoreCase(recipientType) + || BadgingJsonKey.BADGE_TYPE_CONTENT.equalsIgnoreCase(recipientType)) { + return true; + } + return false; + } } diff --git a/service/app/controllers/badging/validator/BadgeClassValidator.java b/service/app/controllers/badging/validator/BadgeClassValidator.java index edcbed95f0..2c1ec628db 100644 --- a/service/app/controllers/badging/validator/BadgeClassValidator.java +++ b/service/app/controllers/badging/validator/BadgeClassValidator.java @@ -1,9 +1,9 @@ package controllers.badging.validator; +import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import java.util.HashMap; import java.util.Map; - import org.apache.commons.lang.StringUtils; import org.sunbird.common.exception.ProjectCommonException; import org.sunbird.common.models.response.HttpUtilResponse; @@ -18,214 +18,234 @@ import org.sunbird.common.request.Request; import org.sunbird.common.responsecode.ResponseCode; -import com.fasterxml.jackson.databind.ObjectMapper; - /** * Validates BadgeClass API requests. * * @author B Vinaya Kumar */ public class BadgeClassValidator extends BaseRequestValidator { - private static final int ERROR_CODE = ResponseCode.CLIENT_ERROR.getResponseCode(); - private static PropertiesCache propertiesCache = PropertiesCache.getInstance(); - - /** - * Helper method for validating given role ID against list of predefined valid badge issuer roles. - * - * @param role Role ID. - * @param error Error to be thrown in case of validation error. - */ - private void validateRole(String role, ResponseCode error) { - String validRoles = System.getenv(BadgingJsonKey.VALID_BADGE_ROLES); - if (StringUtils.isBlank(validRoles)) { - validRoles = propertiesCache.getProperty(BadgingJsonKey.VALID_BADGE_ROLES); - } - - String[] validRolesList = validRoles.split("\\,"); - for (String validRole : validRolesList) { - if (role.equalsIgnoreCase(validRole)) return; - } - - throw new ProjectCommonException(error.getErrorCode(), error.getErrorMessage(), ResponseCode.CLIENT_ERROR.getResponseCode()); + private static final int ERROR_CODE = ResponseCode.CLIENT_ERROR.getResponseCode(); + private static PropertiesCache propertiesCache = PropertiesCache.getInstance(); + + /** + * Helper method for validating given role ID against list of predefined valid badge issuer roles. + * + * @param role Role ID. + * @param error Error to be thrown in case of validation error. + */ + private void validateRole(String role, ResponseCode error) { + String validRoles = System.getenv(BadgingJsonKey.VALID_BADGE_ROLES); + if (StringUtils.isBlank(validRoles)) { + validRoles = propertiesCache.getProperty(BadgingJsonKey.VALID_BADGE_ROLES); } - /** - * Helper method for validating given list of role IDs. - * - * @param roles Single (string) or multiple (JSON array) role IDs. - * @param error Error to be thrown in case of validation error. - */ - private void validateRoles(String roles, ResponseCode error) { - if (StringUtils.isEmpty(roles)) { - throw new ProjectCommonException(error.getErrorCode(), error.getErrorMessage(), ResponseCode.CLIENT_ERROR.getResponseCode()); - } + String[] validRolesList = validRoles.split("\\,"); + for (String validRole : validRolesList) { + if (role.equalsIgnoreCase(validRole)) return; } - /** - * Helper method for validating if given org ID is a valid root org ID. - * - * @param rootOrgId Organisation ID. - * @param httpRequestHeaders Map containing headers received in incoming request. - */ - private void validateRootOrgId(String rootOrgId, Map httpRequestHeaders) { - validateParam(rootOrgId, ResponseCode.rootOrgIdRequired); - - try { - String baseUrl = ProjectUtil.getConfigValue(LearnerServiceUrls.BASE_URL); - String prefix = LearnerServiceUrls.PREFIX_ORG_SERVICE; - LearnerServiceUrls.Path path = LearnerServiceUrls.Path.API_GW_PATH_READ_ORG; - String requestUrl = LearnerServiceUrls.getRequestUrl(baseUrl, prefix, path); - - Map headersMap = LearnerServiceUrls.getRequestHeaders(httpRequestHeaders); - - Map requestMap = new HashMap<>(); - requestMap.put(JsonKey.ORGANISATION_ID, rootOrgId); - - Map bodyMap = new HashMap<>(); - bodyMap.put(JsonKey.REQUEST, requestMap); - - ObjectMapper objectMapper = new ObjectMapper(); - String bodyJson = objectMapper.writeValueAsString(bodyMap); - - HttpUtilResponse response = HttpUtil.doPostRequest(requestUrl, bodyJson, headersMap); - if (response.getStatusCode() == ResponseCode.OK.getResponseCode()) { - String responseStr = response.getBody(); - if (responseStr != null) { - Map responseMap = objectMapper.readValue(responseStr, HashMap.class); - Map resultMap = (Map) responseMap.get(JsonKey.RESULT); - Map resultResponseMap = (Map) resultMap.get(JsonKey.RESPONSE); - boolean isRootOrg = resultResponseMap.get(JsonKey.IS_ROOT_ORG) != null ? (boolean) resultResponseMap.get(JsonKey.IS_ROOT_ORG) : false; - if (isRootOrg) return; - } - } - } catch (IOException | NullPointerException e) { - ProjectLogger.log("validateRootOrgId: exception = ", e); - } - - ResponseCode error = ResponseCode.invalidRootOrganisationId; - throw new ProjectCommonException(error.getErrorCode(), error.getErrorMessage(), ResponseCode.CLIENT_ERROR.getResponseCode()); + throw new ProjectCommonException( + error.getErrorCode(), error.getErrorMessage(), ResponseCode.CLIENT_ERROR.getResponseCode()); + } + + /** + * Helper method for validating given list of role IDs. + * + * @param roles Single (string) or multiple (JSON array) role IDs. + * @param error Error to be thrown in case of validation error. + */ + private void validateRoles(String roles, ResponseCode error) { + if (StringUtils.isEmpty(roles)) { + throw new ProjectCommonException( + error.getErrorCode(), + error.getErrorMessage(), + ResponseCode.CLIENT_ERROR.getResponseCode()); } - - /** - * Helper method to validate given type against supported badge types (user / content). - * - * @param type Badge type. - */ - private void validateType(String type) { - ResponseCode error = ResponseCode.badgeTypeRequired; - - if (StringUtils.isBlank(type)) { - throw new ProjectCommonException(error.getErrorCode(), error.getErrorMessage(), ResponseCode.CLIENT_ERROR.getResponseCode()); - } - - error = ResponseCode.invalidBadgeType; - if (! (type.equalsIgnoreCase(BadgingJsonKey.BADGE_TYPE_USER) || type.equalsIgnoreCase(BadgingJsonKey.BADGE_TYPE_CONTENT))) { - throw new ProjectCommonException(error.getErrorCode(), error.getErrorMessage(), ResponseCode.CLIENT_ERROR.getResponseCode()); + } + + /** + * Helper method for validating if given org ID is a valid root org ID. + * + * @param rootOrgId Organisation ID. + * @param httpRequestHeaders Map containing headers received in incoming request. + */ + private void validateRootOrgId(String rootOrgId, Map httpRequestHeaders) { + validateParam(rootOrgId, ResponseCode.rootOrgIdRequired); + + try { + String baseUrl = ProjectUtil.getConfigValue(LearnerServiceUrls.BASE_URL); + String prefix = LearnerServiceUrls.PREFIX_ORG_SERVICE; + LearnerServiceUrls.Path path = LearnerServiceUrls.Path.API_GW_PATH_READ_ORG; + String requestUrl = LearnerServiceUrls.getRequestUrl(baseUrl, prefix, path); + + Map headersMap = LearnerServiceUrls.getRequestHeaders(httpRequestHeaders); + + Map requestMap = new HashMap<>(); + requestMap.put(JsonKey.ORGANISATION_ID, rootOrgId); + + Map bodyMap = new HashMap<>(); + bodyMap.put(JsonKey.REQUEST, requestMap); + + ObjectMapper objectMapper = new ObjectMapper(); + String bodyJson = objectMapper.writeValueAsString(bodyMap); + + HttpUtilResponse response = HttpUtil.doPostRequest(requestUrl, bodyJson, headersMap); + if (response.getStatusCode() == ResponseCode.OK.getResponseCode()) { + String responseStr = response.getBody(); + if (responseStr != null) { + Map responseMap = objectMapper.readValue(responseStr, HashMap.class); + Map resultMap = (Map) responseMap.get(JsonKey.RESULT); + Map resultResponseMap = + (Map) resultMap.get(JsonKey.RESPONSE); + boolean isRootOrg = + resultResponseMap.get(JsonKey.IS_ROOT_ORG) != null + ? (boolean) resultResponseMap.get(JsonKey.IS_ROOT_ORG) + : false; + if (isRootOrg) return; } + } + } catch (IOException | NullPointerException e) { + ProjectLogger.log("validateRootOrgId: exception = ", e); } - /** - * Helper method to validate given subtype against configured badge subtypes (e.g. award). - * - * @param subtype Badge subtype. - */ - private void validateSubtype(String subtype) { - if (subtype != null) { - String validSubtypes = System.getenv(BadgingJsonKey.VALID_BADGE_SUBTYPES); - if (StringUtils.isBlank(validSubtypes)) { - validSubtypes = propertiesCache.getProperty(BadgingJsonKey.VALID_BADGE_SUBTYPES); - } - - String[] validSubtypesList = validSubtypes.split("\\,"); - for (String validSubtype : validSubtypesList) { - if (validSubtype.equalsIgnoreCase(subtype)) return; - } - - ResponseCode error = ResponseCode.invalidBadgeSubtype; - throw new ProjectCommonException(error.getErrorCode(), error.getErrorMessage(), ResponseCode.CLIENT_ERROR.getResponseCode()); - } + ResponseCode error = ResponseCode.invalidRootOrganisationId; + throw new ProjectCommonException( + error.getErrorCode(), error.getErrorMessage(), ResponseCode.CLIENT_ERROR.getResponseCode()); + } + + /** + * Helper method to validate given type against supported badge types (user / content). + * + * @param type Badge type. + */ + private void validateType(String type) { + ResponseCode error = ResponseCode.badgeTypeRequired; + + if (StringUtils.isBlank(type)) { + throw new ProjectCommonException( + error.getErrorCode(), + error.getErrorMessage(), + ResponseCode.CLIENT_ERROR.getResponseCode()); } - - /** - * Validates request of create badge class API. - * - * @param request Request containing following parameters: - * issuerId: The ID of the Issuer to be owner of the new Badge Class. - * name: The name of the Badge Class. - * description: A short description of the new Badge Class. - * image: An image to represent the Badge Class. - * criteria: Either a text string or a URL of a remotely hosted page describing the criteria. - * rootOrgId: Root organisation ID. - * type: Badge class type (user / content). - * subtype: Badge class subtype (e.g. award). - * roles: JSON array of roles (e.g. [ "OFFICIAL_TEXTBOOK_BADGE_ISSUER" ]). - * @param httpRequestHeaders Map of headers in the received HTTP request. - */ - public void validateCreateBadgeClass(Request request, Map httpRequestHeaders) { - Map requestMap = request.getRequest(); - - if (requestMap == null) { - throw new ProjectCommonException(ResponseCode.invalidRequestData.getErrorCode(), - ResponseCode.invalidRequestData.getErrorMessage(), ERROR_CODE); - } - - validateParam((String) requestMap.get(BadgingJsonKey.ISSUER_ID), ResponseCode.issuerIdRequired); - validateParam((String) requestMap.get(BadgingJsonKey.BADGE_CRITERIA), ResponseCode.badgeCriteriaRequired); - validateParam((String) requestMap.get(JsonKey.NAME), ResponseCode.badgeNameRequired); - validateParam((String) requestMap.get(JsonKey.DESCRIPTION), ResponseCode.badgeDescriptionRequired); - - validateRootOrgId((String) requestMap.get(JsonKey.ROOT_ORG_ID), httpRequestHeaders); - validateType((String) requestMap.get(JsonKey.TYPE)); - validateSubtype((String) requestMap.get(JsonKey.SUBTYPE)); - validateRoles((String) requestMap.get(JsonKey.ROLES), ResponseCode.badgeRolesRequired); - - Object image = request.getRequest().get(JsonKey.IMAGE); - - if (image == null) { - throw new ProjectCommonException(ResponseCode.badgeImageRequired.getErrorCode(), - ResponseCode.badgeImageRequired.getErrorMessage(), ERROR_CODE); - } + error = ResponseCode.invalidBadgeType; + if (!(type.equalsIgnoreCase(BadgingJsonKey.BADGE_TYPE_USER) + || type.equalsIgnoreCase(BadgingJsonKey.BADGE_TYPE_CONTENT))) { + throw new ProjectCommonException( + error.getErrorCode(), + error.getErrorMessage(), + ResponseCode.CLIENT_ERROR.getResponseCode()); } - - /** - * Validates request of get badge class API. - * - * @param request Request containing following parameters: - * badgeId: The ID of the Badge Class whose details to view. - */ - public void validateGetBadgeClass(Request request) { - String badgeId = (String) request.getRequest().get(BadgingJsonKey.BADGE_ID); - validateParam(badgeId, ResponseCode.badgeIdRequired); + } + + /** + * Helper method to validate given subtype against configured badge subtypes (e.g. award). + * + * @param subtype Badge subtype. + */ + private void validateSubtype(String subtype) { + if (subtype != null) { + String validSubtypes = System.getenv(BadgingJsonKey.VALID_BADGE_SUBTYPES); + if (StringUtils.isBlank(validSubtypes)) { + validSubtypes = propertiesCache.getProperty(BadgingJsonKey.VALID_BADGE_SUBTYPES); + } + + String[] validSubtypesList = validSubtypes.split("\\,"); + for (String validSubtype : validSubtypesList) { + if (validSubtype.equalsIgnoreCase(subtype)) return; + } + + ResponseCode error = ResponseCode.invalidBadgeSubtype; + throw new ProjectCommonException( + error.getErrorCode(), + error.getErrorMessage(), + ResponseCode.CLIENT_ERROR.getResponseCode()); } - - /** - * Validates request of search badge class API. - * - * @param request Request containing following filters: - * issuerList: List of Issuer IDs whose badge classes are to be listed. - * badgeList: List of badge IDs whose badge classes are to be listed - * rootOrgId: Root organisation ID. - * type: Badge class type (user / content). - * subtype: Badge class subtype (e.g. award). - * roles: JSON array of roles (e.g. [ "OFFICIAL_TEXTBOOK_BADGE_ISSUER" ]). - */ - public void validateSearchBadgeClass(Request request) { - Map filtersMap = (Map) request.getRequest().get(JsonKey.FILTERS); - - if (filtersMap == null) { - throw new ProjectCommonException(ResponseCode.invalidRequestData.getErrorCode(), ResponseCode.invalidRequestData.getErrorMessage(), ResponseCode.CLIENT_ERROR.getResponseCode()); - } + } + + /** + * Validates request of create badge class API. + * + * @param request Request containing following parameters: issuerId: The ID of the Issuer to be + * owner of the new Badge Class. name: The name of the Badge Class. description: A short + * description of the new Badge Class. image: An image to represent the Badge Class. criteria: + * Either a text string or a URL of a remotely hosted page describing the criteria. rootOrgId: + * Root organisation ID. type: Badge class type (user / content). subtype: Badge class subtype + * (e.g. award). roles: JSON array of roles (e.g. [ "OFFICIAL_TEXTBOOK_BADGE_ISSUER" ]). + * @param httpRequestHeaders Map of headers in the received HTTP request. + */ + public void validateCreateBadgeClass(Request request, Map httpRequestHeaders) { + Map requestMap = request.getRequest(); + + if (requestMap == null) { + throw new ProjectCommonException( + ResponseCode.invalidRequestData.getErrorCode(), + ResponseCode.invalidRequestData.getErrorMessage(), + ERROR_CODE); } - /** - * Validates request of delete badge class API. - * - * @param request Request containing following parameters: - * badgeId: The ID of the Badge Class to delete. - */ - public void validateDeleteBadgeClass(Request request) { - String badgeId = (String) request.getRequest().get(BadgingJsonKey.BADGE_ID); - validateParam(badgeId, ResponseCode.badgeIdRequired); + validateParam((String) requestMap.get(BadgingJsonKey.ISSUER_ID), ResponseCode.issuerIdRequired); + validateParam( + (String) requestMap.get(BadgingJsonKey.BADGE_CRITERIA), ResponseCode.badgeCriteriaRequired); + validateParam((String) requestMap.get(JsonKey.NAME), ResponseCode.badgeNameRequired); + validateParam( + (String) requestMap.get(JsonKey.DESCRIPTION), ResponseCode.badgeDescriptionRequired); + + validateRootOrgId((String) requestMap.get(JsonKey.ROOT_ORG_ID), httpRequestHeaders); + validateType((String) requestMap.get(JsonKey.TYPE)); + validateSubtype((String) requestMap.get(JsonKey.SUBTYPE)); + validateRoles((String) requestMap.get(JsonKey.ROLES), ResponseCode.badgeRolesRequired); + + Object image = request.getRequest().get(JsonKey.IMAGE); + + if (image == null) { + throw new ProjectCommonException( + ResponseCode.badgeImageRequired.getErrorCode(), + ResponseCode.badgeImageRequired.getErrorMessage(), + ERROR_CODE); + } + } + + /** + * Validates request of get badge class API. + * + * @param request Request containing following parameters: badgeId: The ID of the Badge Class + * whose details to view. + */ + public void validateGetBadgeClass(Request request) { + String badgeId = (String) request.getRequest().get(BadgingJsonKey.BADGE_ID); + validateParam(badgeId, ResponseCode.badgeIdRequired); + } + + /** + * Validates request of search badge class API. + * + * @param request Request containing following filters: issuerList: List of Issuer IDs whose badge + * classes are to be listed. badgeList: List of badge IDs whose badge classes are to be listed + * rootOrgId: Root organisation ID. type: Badge class type (user / content). subtype: Badge + * class subtype (e.g. award). roles: JSON array of roles (e.g. [ + * "OFFICIAL_TEXTBOOK_BADGE_ISSUER" ]). + */ + public void validateSearchBadgeClass(Request request) { + Map filtersMap = + (Map) request.getRequest().get(JsonKey.FILTERS); + + if (filtersMap == null) { + throw new ProjectCommonException( + ResponseCode.invalidRequestData.getErrorCode(), + ResponseCode.invalidRequestData.getErrorMessage(), + ResponseCode.CLIENT_ERROR.getResponseCode()); } + } + + /** + * Validates request of delete badge class API. + * + * @param request Request containing following parameters: badgeId: The ID of the Badge Class to + * delete. + */ + public void validateDeleteBadgeClass(Request request) { + String badgeId = (String) request.getRequest().get(BadgingJsonKey.BADGE_ID); + validateParam(badgeId, ResponseCode.badgeIdRequired); + } } diff --git a/service/app/controllers/badging/validator/BadgeIssuerRequestValidator.java b/service/app/controllers/badging/validator/BadgeIssuerRequestValidator.java index 90fa882c83..c2afe3354d 100644 --- a/service/app/controllers/badging/validator/BadgeIssuerRequestValidator.java +++ b/service/app/controllers/badging/validator/BadgeIssuerRequestValidator.java @@ -7,60 +7,56 @@ import org.sunbird.common.request.Request; import org.sunbird.common.responsecode.ResponseCode; -/** - * Created by arvind on 2/3/18. - */ +/** Created by arvind on 2/3/18. */ public class BadgeIssuerRequestValidator { - private BadgeIssuerRequestValidator() {} + private BadgeIssuerRequestValidator() {} - private static final int ERROR_CODE = ResponseCode.CLIENT_ERROR.getResponseCode(); + private static final int ERROR_CODE = ResponseCode.CLIENT_ERROR.getResponseCode(); - /** - * Method to validate noteId - * - * @param request - */ - public static void validateCreateBadgeIssuer(Request request) { - if (StringUtils.isBlank((String) request.getRequest().get(JsonKey.NAME))) { - throw createExceptionInstance( - ResponseCode.invalidDataForCreateBadgeIssuer.getErrorCode(), - "name is required."); - } - if (ProjectUtil - .isStringNullOREmpty((String) request.getRequest().get(JsonKey.DESCRIPTION))) { - throw createExceptionInstance( - ResponseCode.invalidDataForCreateBadgeIssuer.getErrorCode(), - "Description is required."); - } - if (StringUtils.isBlank((String) request.getRequest().get(JsonKey.URL))) { - throw createExceptionInstance( - ResponseCode.invalidDataForCreateBadgeIssuer.getErrorCode(), - "url is required."); - } - if (StringUtils.isBlank((String) request.getRequest().get(JsonKey.EMAIL))) { - throw createExceptionInstance( - ResponseCode.invalidDataForCreateBadgeIssuer.getErrorCode(), - "email is required."); - } - - if (!ProjectUtil.isEmailvalid((String) request.getRequest().get(JsonKey.EMAIL))) { - throw createExceptionInstance( - ResponseCode.invalidDataForCreateBadgeIssuer.getErrorCode(), - "email is invalid."); - } + /** + * Method to validate noteId + * + * @param request + */ + public static void validateCreateBadgeIssuer(Request request) { + if (StringUtils.isBlank((String) request.getRequest().get(JsonKey.NAME))) { + throw createExceptionInstance( + ResponseCode.invalidDataForCreateBadgeIssuer.getErrorCode(), "name is required."); } - - public static void validateGetBadgeIssuerDetail(Request request) { - if (StringUtils.isBlank((String) request.getRequest().get(JsonKey.SLUG))) { - throw new ProjectCommonException(ResponseCode.slugRequired.getErrorCode(), - ResponseCode.slugRequired.getErrorMessage(), ERROR_CODE); - } + if (ProjectUtil.isStringNullOREmpty((String) request.getRequest().get(JsonKey.DESCRIPTION))) { + throw createExceptionInstance( + ResponseCode.invalidDataForCreateBadgeIssuer.getErrorCode(), "Description is required."); } - - private static ProjectCommonException createExceptionInstance(String errorCode, String errMsg) { - return new ProjectCommonException(ResponseCode.getResponse(errorCode).getErrorCode(), - ResponseCode.getResponse(errorCode).getErrorMessage(), ERROR_CODE, errMsg); + if (StringUtils.isBlank((String) request.getRequest().get(JsonKey.URL))) { + throw createExceptionInstance( + ResponseCode.invalidDataForCreateBadgeIssuer.getErrorCode(), "url is required."); + } + if (StringUtils.isBlank((String) request.getRequest().get(JsonKey.EMAIL))) { + throw createExceptionInstance( + ResponseCode.invalidDataForCreateBadgeIssuer.getErrorCode(), "email is required."); } + if (!ProjectUtil.isEmailvalid((String) request.getRequest().get(JsonKey.EMAIL))) { + throw createExceptionInstance( + ResponseCode.invalidDataForCreateBadgeIssuer.getErrorCode(), "email is invalid."); + } + } + + public static void validateGetBadgeIssuerDetail(Request request) { + if (StringUtils.isBlank((String) request.getRequest().get(JsonKey.SLUG))) { + throw new ProjectCommonException( + ResponseCode.slugRequired.getErrorCode(), + ResponseCode.slugRequired.getErrorMessage(), + ERROR_CODE); + } + } + + private static ProjectCommonException createExceptionInstance(String errorCode, String errMsg) { + return new ProjectCommonException( + ResponseCode.getResponse(errorCode).getErrorCode(), + ResponseCode.getResponse(errorCode).getErrorMessage(), + ERROR_CODE, + errMsg); + } } diff --git a/service/app/controllers/bulkapimanagement/BulkUploadController.java b/service/app/controllers/bulkapimanagement/BulkUploadController.java index a6281cd174..dc02928738 100644 --- a/service/app/controllers/bulkapimanagement/BulkUploadController.java +++ b/service/app/controllers/bulkapimanagement/BulkUploadController.java @@ -1,5 +1,7 @@ package controllers.bulkapimanagement; +import com.fasterxml.jackson.databind.JsonNode; +import controllers.BaseController; import java.io.ByteArrayInputStream; import java.io.FileInputStream; import java.io.InputStream; @@ -8,7 +10,6 @@ import java.util.List; import java.util.Map; import java.util.Map.Entry; - import org.apache.commons.io.IOUtils; import org.sunbird.common.exception.ProjectCommonException; import org.sunbird.common.models.util.ActorOperations; @@ -19,10 +20,6 @@ import org.sunbird.common.request.Request; import org.sunbird.common.request.RequestValidator; import org.sunbird.common.responsecode.ResponseCode; - -import com.fasterxml.jackson.databind.JsonNode; - -import controllers.BaseController; import play.libs.F.Promise; import play.mvc.Http.MultipartFormData; import play.mvc.Http.MultipartFormData.FilePart; @@ -30,14 +27,14 @@ /** * This controller will handle all the request related to bulk api's for user management. - * + * * @author Amit Kumar */ public class BulkUploadController extends BaseController { /** * This method will allow to upload bulk user. - * + * * @return Promise */ public Promise uploadUser() { @@ -64,22 +61,26 @@ public Promise uploadUser() { for (Entry entry : formUrlEncodeddata.entrySet()) { map.put(entry.getKey(), entry.getValue()[0]); } - InputStream is = new ByteArrayInputStream( - ((String) map.get(JsonKey.DATA)).getBytes(StandardCharsets.UTF_8)); + InputStream is = + new ByteArrayInputStream( + ((String) map.get(JsonKey.DATA)).getBytes(StandardCharsets.UTF_8)); byteArray = IOUtils.toByteArray(is); reqObj.getRequest().putAll(map); } else if (null != requestData) { reqObj = (Request) mapper.RequestMapper.mapRequest(request().body().asJson(), Request.class); - InputStream is = new ByteArrayInputStream( - ((String) reqObj.getRequest().get(JsonKey.DATA)).getBytes(StandardCharsets.UTF_8)); + InputStream is = + new ByteArrayInputStream( + ((String) reqObj.getRequest().get(JsonKey.DATA)).getBytes(StandardCharsets.UTF_8)); byteArray = IOUtils.toByteArray(is); reqObj.getRequest().putAll(map); map.putAll(reqObj.getRequest()); } else { - ProjectCommonException e = new ProjectCommonException( - ResponseCode.invalidData.getErrorCode(), ResponseCode.invalidData.getErrorMessage(), - ResponseCode.CLIENT_ERROR.getResponseCode()); + ProjectCommonException e = + new ProjectCommonException( + ResponseCode.invalidData.getErrorCode(), + ResponseCode.invalidData.getErrorMessage(), + ResponseCode.CLIENT_ERROR.getResponseCode()); return Promise.pure(createCommonExceptionResponse(e, request())); } RequestValidator.validateUploadUser(reqObj); @@ -93,7 +94,6 @@ public Promise uploadUser() { reqObj.setRequest(innerMap); map.put(JsonKey.FILE, byteArray); - return actorResponseHandler(getActorRef(), reqObj, timeout, null, request()); } catch (Exception e) { return Promise.pure(createCommonExceptionResponse(e, request())); @@ -102,7 +102,7 @@ public Promise uploadUser() { /** * This method will provide the status of bulk operation by their processId. - * + * * @param processId Stirng * @return Promise */ @@ -151,22 +151,26 @@ public Promise uploadOrg() { for (Entry entry : formUrlEncodeddata.entrySet()) { map.put(entry.getKey(), entry.getValue()[0]); } - InputStream is = new ByteArrayInputStream( - ((String) map.get(JsonKey.DATA)).getBytes(StandardCharsets.UTF_8)); + InputStream is = + new ByteArrayInputStream( + ((String) map.get(JsonKey.DATA)).getBytes(StandardCharsets.UTF_8)); byteArray = IOUtils.toByteArray(is); reqObj.getRequest().putAll(map); } else if (null != requestData) { reqObj = (Request) mapper.RequestMapper.mapRequest(request().body().asJson(), Request.class); - InputStream is = new ByteArrayInputStream( - ((String) reqObj.getRequest().get(JsonKey.DATA)).getBytes(StandardCharsets.UTF_8)); + InputStream is = + new ByteArrayInputStream( + ((String) reqObj.getRequest().get(JsonKey.DATA)).getBytes(StandardCharsets.UTF_8)); byteArray = IOUtils.toByteArray(is); reqObj.getRequest().putAll(map); map.putAll(reqObj.getRequest()); } else { - ProjectCommonException e = new ProjectCommonException( - ResponseCode.invalidData.getErrorCode(), ResponseCode.invalidData.getErrorMessage(), - ResponseCode.CLIENT_ERROR.getResponseCode()); + ProjectCommonException e = + new ProjectCommonException( + ResponseCode.invalidData.getErrorCode(), + ResponseCode.invalidData.getErrorMessage(), + ResponseCode.CLIENT_ERROR.getResponseCode()); return Promise.pure(createCommonExceptionResponse(e, request())); } reqObj.getRequest().putAll(map); @@ -187,7 +191,7 @@ public Promise uploadOrg() { /** * This method will allow to upload bulk user. - * + * * @return Promise */ public Promise bulkBatchEnrollment() { @@ -214,22 +218,26 @@ public Promise bulkBatchEnrollment() { for (Entry entry : formUrlEncodeddata.entrySet()) { map.put(entry.getKey(), entry.getValue()[0]); } - InputStream is = new ByteArrayInputStream( - ((String) map.get(JsonKey.DATA)).getBytes(StandardCharsets.UTF_8)); + InputStream is = + new ByteArrayInputStream( + ((String) map.get(JsonKey.DATA)).getBytes(StandardCharsets.UTF_8)); byteArray = IOUtils.toByteArray(is); reqObj.getRequest().putAll(map); } else if (null != requestData) { reqObj = (Request) mapper.RequestMapper.mapRequest(request().body().asJson(), Request.class); - InputStream is = new ByteArrayInputStream( - ((String) reqObj.getRequest().get(JsonKey.DATA)).getBytes(StandardCharsets.UTF_8)); + InputStream is = + new ByteArrayInputStream( + ((String) reqObj.getRequest().get(JsonKey.DATA)).getBytes(StandardCharsets.UTF_8)); byteArray = IOUtils.toByteArray(is); reqObj.getRequest().putAll(map); map.putAll(reqObj.getRequest()); } else { - ProjectCommonException e = new ProjectCommonException( - ResponseCode.invalidData.getErrorCode(), ResponseCode.invalidData.getErrorMessage(), - ResponseCode.CLIENT_ERROR.getResponseCode()); + ProjectCommonException e = + new ProjectCommonException( + ResponseCode.invalidData.getErrorCode(), + ResponseCode.invalidData.getErrorMessage(), + ResponseCode.CLIENT_ERROR.getResponseCode()); return Promise.pure(createCommonExceptionResponse(e, request())); } @@ -274,5 +282,4 @@ public Promise userDataDecryption() { return Promise.pure(createCommonExceptionResponse(e, request())); } } - } diff --git a/service/app/controllers/clientmanagement/ClientController.java b/service/app/controllers/clientmanagement/ClientController.java index c1809c1c0e..e8ae88dd14 100644 --- a/service/app/controllers/clientmanagement/ClientController.java +++ b/service/app/controllers/clientmanagement/ClientController.java @@ -1,7 +1,8 @@ package controllers.clientmanagement; +import com.fasterxml.jackson.databind.JsonNode; +import controllers.BaseController; import java.util.HashMap; - import org.sunbird.common.models.util.ActorOperations; import org.sunbird.common.models.util.JsonKey; import org.sunbird.common.models.util.LoggerEnum; @@ -10,10 +11,6 @@ import org.sunbird.common.request.HeaderParam; import org.sunbird.common.request.Request; import org.sunbird.common.request.RequestValidator; - -import com.fasterxml.jackson.databind.JsonNode; - -import controllers.BaseController; import play.libs.F.Promise; import play.mvc.Result; @@ -25,7 +22,7 @@ public class ClientController extends BaseController { /** * Method to register the client and generate master key for the client - * + * * @return Response object on success else Error object */ public Promise registerClient() { @@ -46,6 +43,7 @@ public Promise registerClient() { /** * Method to update the client key for the given clientId in the header + * * @return Response object on success else Error object */ public Promise updateClientKey() { @@ -53,7 +51,7 @@ public Promise updateClientKey() { JsonNode requestData = request().body().asJson(); ProjectLogger.log("Update client key: " + requestData, LoggerEnum.INFO.name()); String masterKey = request().getHeader(HeaderParam.X_Authenticated_Client_Token.getName()); - String clientId = request().getHeader(HeaderParam.X_Authenticated_Client_Id.getName()); + String clientId = request().getHeader(HeaderParam.X_Authenticated_Client_Id.getName()); Request reqObj = (Request) mapper.RequestMapper.mapRequest(requestData, Request.class); RequestValidator.validateUpdateClientKey(clientId, masterKey); reqObj.setOperation(ActorOperations.UPDATE_CLIENT_KEY.getValue()); @@ -71,7 +69,8 @@ public Promise updateClientKey() { } /** - * Method to get client data such as Master Key based on given clientId + * Method to get client data such as Master Key based on given clientId + * * @param clientId * @return Response object on success else Error object */ @@ -79,14 +78,14 @@ public Promise getClientKey(String clientId) { try { ProjectLogger.log("Get client key: " + clientId, LoggerEnum.INFO.name()); String type = request().getQueryString(JsonKey.TYPE); - RequestValidator.validateGetClientKey(clientId , type); + RequestValidator.validateGetClientKey(clientId, type); Request reqObj = new Request(); reqObj.setOperation(ActorOperations.GET_CLIENT_KEY.getValue()); reqObj.setRequestId(ExecutionContext.getRequestId()); reqObj.setEnv(getEnvironment()); HashMap innerMap = new HashMap<>(); innerMap.put(JsonKey.CLIENT_ID, clientId); - innerMap.put(JsonKey.TYPE,type); + innerMap.put(JsonKey.TYPE, type); reqObj.setRequest(innerMap); return actorResponseHandler(getActorRef(), reqObj, timeout, null, request()); } catch (Exception e) { @@ -94,5 +93,4 @@ public Promise getClientKey(String clientId) { return Promise.pure(createCommonExceptionResponse(e, request())); } } - } diff --git a/service/app/controllers/config/ApplicationConfigController.java b/service/app/controllers/config/ApplicationConfigController.java index 8347401b1d..4654dbbacb 100644 --- a/service/app/controllers/config/ApplicationConfigController.java +++ b/service/app/controllers/config/ApplicationConfigController.java @@ -1,7 +1,8 @@ package controllers.config; +import com.fasterxml.jackson.databind.JsonNode; +import controllers.BaseController; import java.util.HashMap; - import org.sunbird.common.models.util.ActorOperations; import org.sunbird.common.models.util.JsonKey; import org.sunbird.common.models.util.LoggerEnum; @@ -9,25 +10,21 @@ import org.sunbird.common.request.ExecutionContext; import org.sunbird.common.request.Request; import org.sunbird.common.request.RequestValidator; - -import com.fasterxml.jackson.databind.JsonNode; - -import controllers.BaseController; import play.libs.F.Promise; import play.mvc.Result; public class ApplicationConfigController extends BaseController { - /** * This method will update system settings. - * + * * @return Promise */ public Promise updateSystemSettings() { try { JsonNode requestData = request().body().asJson(); - ProjectLogger.log("making a call to update system settings api = " + requestData, LoggerEnum.INFO.name()); + ProjectLogger.log( + "making a call to update system settings api = " + requestData, LoggerEnum.INFO.name()); Request reqObj = (Request) mapper.RequestMapper.mapRequest(requestData, Request.class); RequestValidator.validateUpdateSystemSettingsRequest(reqObj); reqObj.setOperation(ActorOperations.UPDATE_SYSTEM_SETTINGS.getValue()); diff --git a/service/app/controllers/coursemanagement/CourseBatchController.java b/service/app/controllers/coursemanagement/CourseBatchController.java index 3862fcd502..38146e53e8 100644 --- a/service/app/controllers/coursemanagement/CourseBatchController.java +++ b/service/app/controllers/coursemanagement/CourseBatchController.java @@ -1,15 +1,14 @@ -/** - * - */ +/** */ package controllers.coursemanagement; +import com.fasterxml.jackson.databind.JsonNode; +import controllers.BaseController; 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.ActorOperations; import org.sunbird.common.models.util.JsonKey; @@ -19,24 +18,20 @@ import org.sunbird.common.request.ExecutionContext; import org.sunbird.common.request.Request; import org.sunbird.common.request.RequestValidator; - -import com.fasterxml.jackson.databind.JsonNode; - -import controllers.BaseController; import play.libs.F.Promise; import play.mvc.Result; /** * This controller will handle all the API related to course batches , add batch,update batch,join * member to batch, remove member from batch, get particular batch details. - * + * * @author Manzarul */ public class CourseBatchController extends BaseController { /** * This method will add a new batch for a particular course. - * + * * @return Promise */ public Promise createBatch() { @@ -66,7 +61,7 @@ public Promise createBatch() { /** * This method will update existing batch details. - * + * * @return Promise */ public Promise updateBatch() { @@ -88,10 +83,9 @@ public Promise updateBatch() { } } - /** * This method will do soft delete to the batch. - * + * * @return Promise */ public Promise deleteBatch() { @@ -113,11 +107,9 @@ public Promise deleteBatch() { } } - - /** * This method will do the user batch enrollment - * + * * @return Promise */ public Promise addUserToBatch(String batchId) { @@ -140,10 +132,9 @@ public Promise addUserToBatch(String batchId) { } } - /** * This method will remove user batch enrollment. - * + * * @return Promise */ public Promise removeUsersFromBatch() { @@ -165,10 +156,9 @@ public Promise removeUsersFromBatch() { } } - /** * This method will fetch batch details from ES. - * + * * @return Promise */ public Promise getBatch(String batchId) { @@ -189,9 +179,7 @@ public Promise getBatch(String batchId) { } } - /** - * * @param request * @return Map */ @@ -206,7 +194,6 @@ private Map getAllRequestHeaders(play.mvc.Http.Request request) return map; } - /** * This method will do the user search for Elastic search. this will internally call composite * search api. diff --git a/service/app/controllers/coursemanagement/CourseController.java b/service/app/controllers/coursemanagement/CourseController.java index a367ec7022..c99601e4e3 100644 --- a/service/app/controllers/coursemanagement/CourseController.java +++ b/service/app/controllers/coursemanagement/CourseController.java @@ -1,13 +1,12 @@ -/** - * - */ +/** */ package controllers.coursemanagement; +import com.fasterxml.jackson.databind.JsonNode; +import controllers.BaseController; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; - import org.sunbird.common.models.util.ActorOperations; import org.sunbird.common.models.util.JsonKey; import org.sunbird.common.models.util.LoggerEnum; @@ -15,17 +14,13 @@ import org.sunbird.common.request.ExecutionContext; import org.sunbird.common.request.Request; import org.sunbird.common.request.RequestValidator; - -import com.fasterxml.jackson.databind.JsonNode; - -import controllers.BaseController; import play.libs.F.Promise; import play.mvc.Result; /** * This controller will handle all the API related to course, add course, published course, update * course, search course. - * + * * @author Manzarul * @author Amit Kumar */ @@ -33,7 +28,7 @@ public class CourseController extends BaseController { /** * This method will add a new course entry into cassandra DB. - * + * * @return Promise */ public Promise createCourse() { @@ -61,7 +56,7 @@ public Promise createCourse() { * published, once course is published we can only update the status to Retired other filed can't * be updated. if course status is not live then update on other fields are valid. if user is * making course status as Retired then we need to updated inside cassandra as well as ES. - * + * * @return Promise */ public Promise updateCourse() { @@ -83,11 +78,10 @@ public Promise updateCourse() { } } - /** * This method will publish the course. when ever course will be published , internally we need to * make EkStep api call to collect all the content related to this course and put into ES. - * + * * @return Promise */ public Promise publishCourse() { @@ -113,7 +107,7 @@ public Promise publishCourse() { /** * This method will do the course search. Based on front end search query we need to make * ElasticSearch search api call to get the data. In ES we will only search for Live course. - * + * * @return Promise */ public Promise searchCourse() { @@ -136,7 +130,7 @@ public Promise searchCourse() { /** * This method will make the course as retired in Cassandra and ES both - * + * * @return Promise */ public Promise deleteCourse() { @@ -157,10 +151,9 @@ public Promise deleteCourse() { } } - /** * This method will do the course search based on course id. search will happen under ES. - * + * * @param courseId Stirng * @return Promise */ @@ -184,7 +177,7 @@ public Promise getCourseById(String courseId) { /** * This method will provide the recommended courses for particular user. search will happen under * ES. - * + * * @return Promise */ public Promise recommendedCourses() { @@ -204,7 +197,6 @@ public Promise recommendedCourses() { } /** - * * @param request * @return Map */ @@ -218,5 +210,4 @@ private Map getAllRequestHeaders(play.mvc.Http.Request request) } return map; } - } diff --git a/service/app/controllers/datapersistence/DbOperationController.java b/service/app/controllers/datapersistence/DbOperationController.java index d8ed5cc034..b779bd5119 100644 --- a/service/app/controllers/datapersistence/DbOperationController.java +++ b/service/app/controllers/datapersistence/DbOperationController.java @@ -1,15 +1,13 @@ package controllers.datapersistence; +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.models.util.LoggerEnum; import org.sunbird.common.models.util.ProjectLogger; import org.sunbird.common.request.ExecutionContext; import org.sunbird.common.request.Request; - -import com.fasterxml.jackson.databind.JsonNode; - -import controllers.BaseController; import play.libs.F.Promise; import play.mvc.Result; @@ -17,7 +15,7 @@ public class DbOperationController extends BaseController { /** * This method will allow create Data in DB. - * + * * @return Promise */ public Promise create() { @@ -37,7 +35,7 @@ public Promise create() { /** * This method will allow update Data in DB. - * + * * @return Promise */ public Promise update() { @@ -57,7 +55,7 @@ public Promise update() { /** * This method will allow to delete Data in DB. - * + * * @return Promise */ public Promise delete() { @@ -75,10 +73,9 @@ public Promise delete() { } } - /** * This method will allow to read Data from DB/ES. - * + * * @return Promise */ public Promise read() { @@ -96,10 +93,9 @@ public Promise read() { } } - /** * This method will allow to read all Data from DB/ES. - * + * * @return Promise */ public Promise readAll() { @@ -117,10 +113,9 @@ public Promise readAll() { } } - /** * This method will allow to search Data from ES. - * + * * @return Promise */ public Promise search() { @@ -140,7 +135,7 @@ public Promise search() { /** * Method to get data from ElasticSearch based on query - * + * * @return ES Response */ public Promise getMetrics() { diff --git a/service/app/controllers/geolocation/GeoLocationController.java b/service/app/controllers/geolocation/GeoLocationController.java index c78c45a135..cc3dd5cf72 100644 --- a/service/app/controllers/geolocation/GeoLocationController.java +++ b/service/app/controllers/geolocation/GeoLocationController.java @@ -1,8 +1,9 @@ package controllers.geolocation; +import com.fasterxml.jackson.databind.JsonNode; +import controllers.BaseController; import java.util.HashMap; import java.util.Map; - import org.sunbird.common.models.util.ActorOperations; import org.sunbird.common.models.util.JsonKey; import org.sunbird.common.models.util.LoggerEnum; @@ -10,19 +11,12 @@ import org.sunbird.common.request.ExecutionContext; import org.sunbird.common.request.Request; import org.sunbird.common.request.RequestValidator; - -import com.fasterxml.jackson.databind.JsonNode; - -import controllers.BaseController; import play.libs.F.Promise; import play.mvc.Result; -/** - * Created by arvind on 31/10/17. - */ +/** Created by arvind on 31/10/17. */ public class GeoLocationController extends BaseController { - public Promise createGeoLocation() { try { JsonNode requestData = request().body().asJson(); @@ -42,7 +36,7 @@ public Promise createGeoLocation() { public Promise getGeoLocation(String id) { try { - ProjectLogger.log("get geo location by id " ); + ProjectLogger.log("get geo location by id "); String type = request().getQueryString(JsonKey.TYPE); Request reqObj = new Request(); reqObj.setOperation(ActorOperations.GET_GEO_LOCATION.getValue()); @@ -50,8 +44,8 @@ public Promise getGeoLocation(String id) { reqObj.setEnv(getEnvironment()); Map innerMap = reqObj.getRequest(); innerMap.put(JsonKey.REQUESTED_BY, ctx().flash().get(JsonKey.USER_ID)); - innerMap.put(JsonKey.TYPE , type); - innerMap.put(JsonKey.ID , id); + innerMap.put(JsonKey.TYPE, type); + innerMap.put(JsonKey.ID, id); reqObj.setRequest(innerMap); return actorResponseHandler(getActorRef(), reqObj, timeout, null, request()); } catch (Exception e) { @@ -69,7 +63,7 @@ public Promise updateGeoLocation(String locationId) { reqObj.setEnv(getEnvironment()); Map innerMap = reqObj.getRequest(); innerMap.put(JsonKey.REQUESTED_BY, ctx().flash().get(JsonKey.USER_ID)); - innerMap.put(JsonKey.LOCATION_ID , locationId); + innerMap.put(JsonKey.LOCATION_ID, locationId); reqObj.setRequest(innerMap); return actorResponseHandler(getActorRef(), reqObj, timeout, null, request()); } catch (Exception e) { @@ -111,7 +105,7 @@ public Promise sendNotification() { return Promise.pure(createCommonExceptionResponse(e, request())); } } - + public Promise getUserCount() { try { JsonNode requestData = request().body().asJson(); @@ -129,5 +123,4 @@ public Promise getUserCount() { return Promise.pure(createCommonExceptionResponse(e, request())); } } - } diff --git a/service/app/controllers/healthmanager/HealthController.java b/service/app/controllers/healthmanager/HealthController.java index 2e4c00ecaf..7f0068016a 100644 --- a/service/app/controllers/healthmanager/HealthController.java +++ b/service/app/controllers/healthmanager/HealthController.java @@ -1,13 +1,11 @@ -/** - * - */ +/** */ package controllers.healthmanager; +import controllers.BaseController; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; - import org.apache.commons.lang3.StringUtils; import org.sunbird.common.models.response.Response; import org.sunbird.common.models.util.ActorOperations; @@ -19,14 +17,10 @@ import org.sunbird.common.models.util.PropertiesCache; import org.sunbird.common.request.ExecutionContext; import org.sunbird.common.request.Request; - -import controllers.BaseController; import play.libs.F.Promise; import play.mvc.Result; -/** - * @author Manzarul - */ +/** @author Manzarul */ public class HealthController extends BaseController { private static List list = new ArrayList<>(); @@ -40,7 +34,7 @@ public class HealthController extends BaseController { /** * This method will do the complete health check - * + * * @return Promise */ public Promise getHealth() { @@ -48,7 +42,7 @@ public Promise getHealth() { Request reqObj = new Request(); reqObj.setOperation(ActorOperations.HEALTH_CHECK.getValue()); reqObj.setRequestId(ExecutionContext.getRequestId()); - reqObj.getRequest().put(JsonKey.CREATED_BY,ctx().flash().get(JsonKey.USER_ID)); + reqObj.getRequest().put(JsonKey.CREATED_BY, ctx().flash().get(JsonKey.USER_ID)); reqObj.setEnv(getEnvironment()); return actorResponseHandler(getActorRef(), reqObj, timeout, null, request()); } catch (Exception e) { @@ -56,10 +50,9 @@ public Promise getHealth() { } } - /** * This method will do the health check for play service. - * + * * @return Promise */ public Promise getLearnerServiceHealth(String val) { @@ -95,7 +88,6 @@ public Promise getLearnerServiceHealth(String val) { } } - public Promise getEkStepHealtCheck(play.mvc.Http.Request request) { Map finalResponseMap = new HashMap<>(); List> responseList = new ArrayList<>(); @@ -105,7 +97,8 @@ public Promise getEkStepHealtCheck(play.mvc.Http.Request request) { Map headers = new HashMap<>(); headers.put(JsonKey.AUTHORIZATION, JsonKey.BEARER + System.getenv(JsonKey.AUTHORIZATION)); if (StringUtils.isBlank((String) headers.get(JsonKey.AUTHORIZATION))) { - headers.put(JsonKey.AUTHORIZATION, + headers.put( + JsonKey.AUTHORIZATION, PropertiesCache.getInstance().getProperty(JsonKey.EKSTEP_AUTHORIZATION)); } headers.put("Content-Type", "application/json"); @@ -113,10 +106,12 @@ public Promise getEkStepHealtCheck(play.mvc.Http.Request request) { if (StringUtils.isBlank(ekStepBaseUrl)) { ekStepBaseUrl = PropertiesCache.getInstance().getProperty(JsonKey.EKSTEP_BASE_URL); } - String response = HttpUtil.sendPostRequest( - ekStepBaseUrl - + PropertiesCache.getInstance().getProperty(JsonKey.EKSTEP_CONTENT_SEARCH_URL), - body, headers); + String response = + HttpUtil.sendPostRequest( + ekStepBaseUrl + + PropertiesCache.getInstance().getProperty(JsonKey.EKSTEP_CONTENT_SEARCH_URL), + body, + headers); if (response.contains("OK")) { responseList.add(ProjectUtil.createCheckResponse(JsonKey.EKSTEP_SERVICE, false, null)); finalResponseMap.put(JsonKey.Healthy, true); @@ -137,5 +132,4 @@ public Promise getEkStepHealtCheck(play.mvc.Http.Request request) { response.setTs(ExecutionContext.getRequestId()); return Promise.pure(ok(play.libs.Json.toJson(response))); } - } diff --git a/service/app/controllers/metrics/CourseMetricsController.java b/service/app/controllers/metrics/CourseMetricsController.java index 7bddf69058..50649c469b 100644 --- a/service/app/controllers/metrics/CourseMetricsController.java +++ b/service/app/controllers/metrics/CourseMetricsController.java @@ -1,14 +1,12 @@ package controllers.metrics; +import controllers.BaseController; import java.util.HashMap; import java.util.Map; - import org.sunbird.common.models.util.ActorOperations; import org.sunbird.common.models.util.JsonKey; import org.sunbird.common.request.ExecutionContext; import org.sunbird.common.request.Request; - -import controllers.BaseController; import play.libs.F.Promise; import play.mvc.Result; @@ -22,7 +20,7 @@ public Promise courseProgress(String batchId) { request.setEnv(getEnvironment()); map.put(JsonKey.BATCH_ID, batchId); map.put(JsonKey.PERIOD, periodStr); - map.put(JsonKey.REQUESTED_BY,ctx().flash().get(JsonKey.USER_ID)); + map.put(JsonKey.REQUESTED_BY, ctx().flash().get(JsonKey.USER_ID)); request.setRequest(map); request.setOperation(ActorOperations.COURSE_PROGRESS_METRICS.getValue()); request.setRequest(map); @@ -42,7 +40,7 @@ public Promise courseCreation(String courseId) { request.setOperation(ActorOperations.COURSE_CREATION_METRICS.getValue()); map.put(JsonKey.COURSE_ID, courseId); map.put(JsonKey.PERIOD, periodStr); - map.put(JsonKey.REQUESTED_BY,ctx().flash().get(JsonKey.USER_ID)); + map.put(JsonKey.REQUESTED_BY, ctx().flash().get(JsonKey.USER_ID)); request.setRequest(map); request.setRequestId(ExecutionContext.getRequestId()); return actorResponseHandler(getActorRef(), request, timeout, null, request()); @@ -60,8 +58,8 @@ public Promise courseProgressReport(String batchId) { request.setEnv(getEnvironment()); map.put(JsonKey.BATCH_ID, batchId); map.put(JsonKey.PERIOD, periodStr); - map.put(JsonKey.FORMAT , reportType); - map.put(JsonKey.REQUESTED_BY,ctx().flash().get(JsonKey.USER_ID)); + map.put(JsonKey.FORMAT, reportType); + map.put(JsonKey.REQUESTED_BY, ctx().flash().get(JsonKey.USER_ID)); request.setRequest(map); request.setOperation(ActorOperations.COURSE_PROGRESS_METRICS_REPORT.getValue()); request.setRequest(map); @@ -88,7 +86,4 @@ public Promise courseCreationReport(String courseId) { return Promise.pure(createCommonExceptionResponse(e, request())); } } - - - } diff --git a/service/app/controllers/metrics/OrganisationMetricsController.java b/service/app/controllers/metrics/OrganisationMetricsController.java index d85c306258..f1a634addc 100644 --- a/service/app/controllers/metrics/OrganisationMetricsController.java +++ b/service/app/controllers/metrics/OrganisationMetricsController.java @@ -1,15 +1,13 @@ package controllers.metrics; +import controllers.BaseController; import java.util.HashMap; import java.util.Map; - 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.request.ExecutionContext; import org.sunbird.common.request.Request; - -import controllers.BaseController; import play.libs.F.Promise; import play.mvc.Result; @@ -18,7 +16,7 @@ public class OrganisationMetricsController extends BaseController { public Promise orgCreation(String orgId) { ProjectLogger.log("Start Org Metrics Creation Contoller"); try { - String periodStr = request().getQueryString(JsonKey.PERIOD); + String periodStr = request().getQueryString(JsonKey.PERIOD); Map map = new HashMap<>(); map.put(JsonKey.ORG_ID, orgId); map.put(JsonKey.PERIOD, periodStr); @@ -34,11 +32,11 @@ public Promise orgCreation(String orgId) { return Promise.pure(createCommonExceptionResponse(e, request())); } } - + public Promise orgConsumption(String orgId) { ProjectLogger.log("Start Org Metrics Consumption Contoller"); try { - String periodStr = request().getQueryString(JsonKey.PERIOD); + String periodStr = request().getQueryString(JsonKey.PERIOD); Map map = new HashMap<>(); map.put(JsonKey.ORG_ID, orgId); map.put(JsonKey.PERIOD, periodStr); @@ -64,14 +62,14 @@ public Promise orgCreationReport(String orgId) { map.put(JsonKey.ORG_ID, orgId); map.put(JsonKey.PERIOD, periodStr); map.put(JsonKey.FORMAT, format); - map.put(JsonKey.REQUESTED_BY,ctx().flash().get(JsonKey.USER_ID)); + map.put(JsonKey.REQUESTED_BY, ctx().flash().get(JsonKey.USER_ID)); Request request = new Request(); request.setEnv(getEnvironment()); request.setOperation(ActorOperations.ORG_CREATION_METRICS_REPORT.getValue()); request.setRequest(map); request.setRequestId(ExecutionContext.getRequestId()); ProjectLogger.log("Return from Org Creation Report Contoller"); - return actorResponseHandler(getActorRef(), request, timeout, null, request()); + return actorResponseHandler(getActorRef(), request, timeout, null, request()); } catch (Exception e) { return Promise.pure(createCommonExceptionResponse(e, request())); } @@ -86,7 +84,7 @@ public Promise orgConsumptionReport(String orgId) { map.put(JsonKey.ORG_ID, orgId); map.put(JsonKey.PERIOD, periodStr); map.put(JsonKey.FORMAT, format); - map.put(JsonKey.REQUESTED_BY,ctx().flash().get(JsonKey.USER_ID)); + map.put(JsonKey.REQUESTED_BY, ctx().flash().get(JsonKey.USER_ID)); Request request = new Request(); request.setEnv(getEnvironment()); request.setOperation(ActorOperations.ORG_CONSUMPTION_METRICS_REPORT.getValue()); @@ -98,5 +96,4 @@ public Promise orgConsumptionReport(String orgId) { return Promise.pure(createCommonExceptionResponse(e, request())); } } - } diff --git a/service/app/controllers/metrics/UserMetricsController.java b/service/app/controllers/metrics/UserMetricsController.java index 1bedcf513f..810f37d653 100644 --- a/service/app/controllers/metrics/UserMetricsController.java +++ b/service/app/controllers/metrics/UserMetricsController.java @@ -1,18 +1,16 @@ package controllers.metrics; +import controllers.BaseController; import java.util.HashMap; import java.util.Map; - import org.sunbird.common.models.util.ActorOperations; import org.sunbird.common.request.ExecutionContext; import org.sunbird.common.request.Request; - -import controllers.BaseController; import play.libs.F.Promise; import play.mvc.Result; public class UserMetricsController extends BaseController { - + public Promise userCreation(String userId) { try { Map map = new HashMap<>(); @@ -27,7 +25,7 @@ public Promise userCreation(String userId) { return Promise.pure(createCommonExceptionResponse(e, request())); } } - + public Promise userConsumption(String userId) { try { Map map = new HashMap<>(); @@ -42,5 +40,4 @@ public Promise userConsumption(String userId) { return Promise.pure(createCommonExceptionResponse(e, request())); } } - } diff --git a/service/app/controllers/notesmanagement/NotesController.java b/service/app/controllers/notesmanagement/NotesController.java index 82e2dcee43..07a9010f0b 100644 --- a/service/app/controllers/notesmanagement/NotesController.java +++ b/service/app/controllers/notesmanagement/NotesController.java @@ -1,7 +1,8 @@ package controllers.notesmanagement; +import com.fasterxml.jackson.databind.JsonNode; +import controllers.BaseController; import java.util.HashMap; - import org.apache.commons.lang3.StringUtils; import org.sunbird.common.exception.ProjectCommonException; import org.sunbird.common.models.util.ActorOperations; @@ -12,22 +13,18 @@ import org.sunbird.common.request.Request; import org.sunbird.common.request.RequestValidator; import org.sunbird.common.responsecode.ResponseCode; - -import com.fasterxml.jackson.databind.JsonNode; - -import controllers.BaseController; import play.libs.F.Promise; import play.mvc.Result; /** - * Controller class to handle Notes related operation such as - * create, read/get, search, update and delete - * + * Controller class to handle Notes related operation such as create, read/get, search, update and + * delete */ public class NotesController extends BaseController { - + /** * Method to create Note + * * @return Promise */ public Promise createNote() { @@ -35,10 +32,15 @@ public Promise createNote() { JsonNode requestData = request().body().asJson(); ProjectLogger.log("Create note request: " + requestData, LoggerEnum.INFO.name()); Request reqObj = (Request) mapper.RequestMapper.mapRequest(requestData, Request.class); - if(null != ctx().flash().get(JsonKey.IS_AUTH_REQ) && Boolean.parseBoolean(ctx().flash().get(JsonKey.IS_AUTH_REQ))){ + if (null != ctx().flash().get(JsonKey.IS_AUTH_REQ) + && Boolean.parseBoolean(ctx().flash().get(JsonKey.IS_AUTH_REQ))) { String userId = (String) reqObj.get(JsonKey.USER_ID); - if((!StringUtils.isBlank(userId)) && (!userId.equals(ctx().flash().get(JsonKey.USER_ID)))){ - throw new ProjectCommonException(ResponseCode.unAuthorised.getErrorCode(), ResponseCode.unAuthorised.getErrorMessage(), ResponseCode.UNAUTHORIZED.getResponseCode()); + if ((!StringUtils.isBlank(userId)) + && (!userId.equals(ctx().flash().get(JsonKey.USER_ID)))) { + throw new ProjectCommonException( + ResponseCode.unAuthorised.getErrorCode(), + ResponseCode.unAuthorised.getErrorMessage(), + ResponseCode.UNAUTHORIZED.getResponseCode()); } } RequestValidator.validateNote(reqObj); @@ -47,7 +49,7 @@ public Promise createNote() { reqObj.setEnv(getEnvironment()); HashMap innerMap = new HashMap<>(); innerMap.put(JsonKey.NOTE, reqObj.getRequest()); - innerMap.put(JsonKey.REQUESTED_BY,ctx().flash().get(JsonKey.USER_ID)); + innerMap.put(JsonKey.REQUESTED_BY, ctx().flash().get(JsonKey.USER_ID)); reqObj.setRequest(innerMap); return actorResponseHandler(getActorRef(), reqObj, timeout, null, request()); } catch (Exception e) { @@ -58,6 +60,7 @@ public Promise createNote() { /** * Method to update the note + * * @param noteId * @return Promise */ @@ -73,7 +76,7 @@ public Promise updateNote(String noteId) { HashMap innerMap = new HashMap<>(); innerMap.put(JsonKey.NOTE_ID, noteId); innerMap.put(JsonKey.NOTE, reqObj.getRequest()); - innerMap.put(JsonKey.REQUESTED_BY,ctx().flash().get(JsonKey.USER_ID)); + innerMap.put(JsonKey.REQUESTED_BY, ctx().flash().get(JsonKey.USER_ID)); reqObj.setRequest(innerMap); return actorResponseHandler(getActorRef(), reqObj, timeout, null, request()); } catch (Exception e) { @@ -81,9 +84,10 @@ public Promise updateNote(String noteId) { return Promise.pure(createCommonExceptionResponse(e, request())); } } - + /** * Method to get the note details + * * @param noteId * @return Promise */ @@ -96,7 +100,7 @@ public Promise getNote(String noteId) { reqObj.setRequestId(ExecutionContext.getRequestId()); reqObj.setEnv(getEnvironment()); HashMap innerMap = new HashMap<>(); - innerMap.put(JsonKey.REQUESTED_BY,ctx().flash().get(JsonKey.USER_ID)); + innerMap.put(JsonKey.REQUESTED_BY, ctx().flash().get(JsonKey.USER_ID)); innerMap.put(JsonKey.NOTE_ID, noteId); reqObj.setRequest(innerMap); return actorResponseHandler(getActorRef(), reqObj, timeout, null, request()); @@ -108,6 +112,7 @@ public Promise getNote(String noteId) { /** * Method to search note + * * @return */ public Promise searchNote() { @@ -119,7 +124,7 @@ public Promise searchNote() { reqObj.setRequestId(ExecutionContext.getRequestId()); reqObj.setEnv(getEnvironment()); HashMap innerMap = new HashMap<>(); - innerMap.put(JsonKey.REQUESTED_BY,ctx().flash().get(JsonKey.USER_ID)); + innerMap.put(JsonKey.REQUESTED_BY, ctx().flash().get(JsonKey.USER_ID)); innerMap.putAll(reqObj.getRequest()); reqObj.setRequest(innerMap); return actorResponseHandler(getActorRef(), reqObj, timeout, null, request()); @@ -131,6 +136,7 @@ public Promise searchNote() { /** * Method to delete the note + * * @param noteId * @return Promise */ @@ -144,7 +150,7 @@ public Promise deleteNote(String noteId) { reqObj.setEnv(getEnvironment()); HashMap innerMap = new HashMap<>(); innerMap.put(JsonKey.NOTE_ID, noteId); - innerMap.put(JsonKey.REQUESTED_BY,ctx().flash().get(JsonKey.USER_ID)); + innerMap.put(JsonKey.REQUESTED_BY, ctx().flash().get(JsonKey.USER_ID)); reqObj.setRequest(innerMap); return actorResponseHandler(getActorRef(), reqObj, timeout, null, request()); } catch (Exception e) { @@ -152,4 +158,4 @@ public Promise deleteNote(String noteId) { return Promise.pure(createCommonExceptionResponse(e, request())); } } -} \ No newline at end of file +} diff --git a/service/app/controllers/notificationservice/EmailServiceController.java b/service/app/controllers/notificationservice/EmailServiceController.java index 400118a1bb..0bac0d2715 100644 --- a/service/app/controllers/notificationservice/EmailServiceController.java +++ b/service/app/controllers/notificationservice/EmailServiceController.java @@ -1,7 +1,8 @@ package controllers.notificationservice; +import com.fasterxml.jackson.databind.JsonNode; +import controllers.BaseController; import java.util.HashMap; - import org.sunbird.common.models.util.ActorOperations; import org.sunbird.common.models.util.JsonKey; import org.sunbird.common.models.util.LoggerEnum; @@ -9,10 +10,6 @@ import org.sunbird.common.request.ExecutionContext; import org.sunbird.common.request.Request; import org.sunbird.common.request.RequestValidator; - -import com.fasterxml.jackson.databind.JsonNode; - -import controllers.BaseController; import play.libs.F.Promise; import play.mvc.Result; @@ -20,7 +17,7 @@ public class EmailServiceController extends BaseController { /** * This method will add a new course entry into cassandra DB. - * + * * @return Promise */ public Promise sendMail() { @@ -35,13 +32,12 @@ public Promise sendMail() { reqObj.setEnv(getEnvironment()); HashMap innerMap = new HashMap<>(); innerMap.put(JsonKey.EMAIL_REQUEST, reqObj.getRequest()); - innerMap.put(JsonKey.REQUESTED_BY,ctx().flash().get(JsonKey.USER_ID)); + innerMap.put(JsonKey.REQUESTED_BY, ctx().flash().get(JsonKey.USER_ID)); reqObj.setRequest(innerMap); - - return actorResponseHandler(getActorRef(), reqObj, timeout, null, request()); + + return actorResponseHandler(getActorRef(), reqObj, timeout, null, request()); } catch (Exception e) { return Promise.pure(createCommonExceptionResponse(e, request())); } } - } diff --git a/service/app/controllers/organisationmanagement/OrganisationController.java b/service/app/controllers/organisationmanagement/OrganisationController.java index 2613ad22d7..9bc955eb3c 100644 --- a/service/app/controllers/organisationmanagement/OrganisationController.java +++ b/service/app/controllers/organisationmanagement/OrganisationController.java @@ -1,6 +1,4 @@ -/** - * - */ +/** */ package controllers.organisationmanagement; import com.fasterxml.jackson.databind.JsonNode; @@ -24,430 +22,412 @@ /** * This controller will handle all the API related to course, add course , published course, update * course, search course. - * + * * @author Amit Kumar */ public class OrganisationController extends BaseController { - - - /** - * This method will do the registration process. Registered organization data will be store - * inside cassandra DB. - * - * @return Promise - */ - @SuppressWarnings("unchecked") - public Promise createOrg() { - - try { - JsonNode requestData = request().body().asJson(); - ProjectLogger.log("Create organisation request: " + requestData, - LoggerEnum.INFO.name()); - Request reqObj = (Request) mapper.RequestMapper.mapRequest(requestData, Request.class); - ProjectUtil.updateMapSomeValueTOLowerCase(reqObj); - RequestValidator.validateCreateOrg(reqObj); - reqObj.setOperation(ActorOperations.CREATE_ORG.getValue()); - reqObj.setRequestId(ExecutionContext.getRequestId()); - reqObj.setEnv(getEnvironment()); - HashMap innerMap = new HashMap<>(); - Map address = - (Map) reqObj.getRequest().get(JsonKey.ADDRESS); - Map orgData = reqObj.getRequest(); - if (null != address && address.size() > 0 && orgData.containsKey(JsonKey.ADDRESS)) { - innerMap.put(JsonKey.ADDRESS, address); - orgData.remove(JsonKey.ADDRESS); - } - if (orgData.containsKey(JsonKey.PROVIDER)) { - orgData.put(JsonKey.PROVIDER, - ((String) orgData.get(JsonKey.PROVIDER)).toLowerCase()); - } - if (orgData.containsKey(JsonKey.EXTERNAL_ID)) { - orgData.put(JsonKey.EXTERNAL_ID, - ((String) orgData.get(JsonKey.EXTERNAL_ID)).toLowerCase()); - } - innerMap.put(JsonKey.ORGANISATION, orgData); - innerMap.put(JsonKey.REQUESTED_BY, ctx().flash().get(JsonKey.USER_ID)); - reqObj.setRequest(innerMap); - return actorResponseHandler(getActorRef(), reqObj, timeout, null, request()); - } catch (Exception e) { - return Promise.pure(createCommonExceptionResponse(e, request())); - } + /** + * This method will do the registration process. Registered organization data will be store inside + * cassandra DB. + * + * @return Promise + */ + @SuppressWarnings("unchecked") + public Promise createOrg() { + + try { + JsonNode requestData = request().body().asJson(); + ProjectLogger.log("Create organisation request: " + requestData, LoggerEnum.INFO.name()); + Request reqObj = (Request) mapper.RequestMapper.mapRequest(requestData, Request.class); + ProjectUtil.updateMapSomeValueTOLowerCase(reqObj); + RequestValidator.validateCreateOrg(reqObj); + reqObj.setOperation(ActorOperations.CREATE_ORG.getValue()); + reqObj.setRequestId(ExecutionContext.getRequestId()); + reqObj.setEnv(getEnvironment()); + HashMap innerMap = new HashMap<>(); + Map address = (Map) reqObj.getRequest().get(JsonKey.ADDRESS); + Map orgData = reqObj.getRequest(); + if (null != address && address.size() > 0 && orgData.containsKey(JsonKey.ADDRESS)) { + innerMap.put(JsonKey.ADDRESS, address); + orgData.remove(JsonKey.ADDRESS); + } + if (orgData.containsKey(JsonKey.PROVIDER)) { + orgData.put(JsonKey.PROVIDER, ((String) orgData.get(JsonKey.PROVIDER)).toLowerCase()); + } + if (orgData.containsKey(JsonKey.EXTERNAL_ID)) { + orgData.put(JsonKey.EXTERNAL_ID, ((String) orgData.get(JsonKey.EXTERNAL_ID)).toLowerCase()); + } + innerMap.put(JsonKey.ORGANISATION, orgData); + innerMap.put(JsonKey.REQUESTED_BY, ctx().flash().get(JsonKey.USER_ID)); + reqObj.setRequest(innerMap); + return actorResponseHandler(getActorRef(), reqObj, timeout, null, request()); + } catch (Exception e) { + return Promise.pure(createCommonExceptionResponse(e, request())); } - - /** - * Method to approve an organization - * - * @return Promise - */ - public Promise approveOrg() { - - try { - JsonNode requestData = request().body().asJson(); - ProjectLogger.log("Approve organisation request: " + requestData, - LoggerEnum.INFO.name()); - Request reqObj = (Request) mapper.RequestMapper.mapRequest(requestData, Request.class); - ProjectUtil.updateMapSomeValueTOLowerCase(reqObj); - RequestValidator.validateOrg(reqObj); - reqObj.setOperation(ActorOperations.APPROVE_ORG.getValue()); - reqObj.setRequestId(ExecutionContext.getRequestId()); - reqObj.setEnv(getEnvironment()); - HashMap innerMap = new HashMap<>(); - innerMap.put(JsonKey.ORGANISATION, reqObj.getRequest()); - innerMap.put(JsonKey.REQUESTED_BY, ctx().flash().get(JsonKey.USER_ID)); - reqObj.setRequest(innerMap); - return actorResponseHandler(getActorRef(), reqObj, timeout, null, request()); - } catch (Exception e) { - return Promise.pure(createCommonExceptionResponse(e, request())); - } + } + + /** + * Method to approve an organization + * + * @return Promise + */ + public Promise approveOrg() { + + try { + JsonNode requestData = request().body().asJson(); + ProjectLogger.log("Approve organisation request: " + requestData, LoggerEnum.INFO.name()); + Request reqObj = (Request) mapper.RequestMapper.mapRequest(requestData, Request.class); + ProjectUtil.updateMapSomeValueTOLowerCase(reqObj); + RequestValidator.validateOrg(reqObj); + reqObj.setOperation(ActorOperations.APPROVE_ORG.getValue()); + reqObj.setRequestId(ExecutionContext.getRequestId()); + reqObj.setEnv(getEnvironment()); + HashMap innerMap = new HashMap<>(); + innerMap.put(JsonKey.ORGANISATION, reqObj.getRequest()); + innerMap.put(JsonKey.REQUESTED_BY, ctx().flash().get(JsonKey.USER_ID)); + reqObj.setRequest(innerMap); + return actorResponseHandler(getActorRef(), reqObj, timeout, null, request()); + } catch (Exception e) { + return Promise.pure(createCommonExceptionResponse(e, request())); } - - /** - * This method will update organization data. - * - * @return Promise - */ - @SuppressWarnings("unchecked") - public Promise updateOrg() { - - try { - JsonNode requestData = request().body().asJson(); - ProjectLogger.log("Update organisation request: " + requestData, - LoggerEnum.INFO.name()); - Request reqObj = (Request) mapper.RequestMapper.mapRequest(requestData, Request.class); - ProjectUtil.updateMapSomeValueTOLowerCase(reqObj); - RequestValidator.validateUpdateOrg(reqObj); - reqObj.setOperation(ActorOperations.UPDATE_ORG.getValue()); - reqObj.setRequestId(ExecutionContext.getRequestId()); - reqObj.setEnv(getEnvironment()); - HashMap innerMap = new HashMap<>(); - Map address = - (Map) reqObj.getRequest().get(JsonKey.ADDRESS); - Map orgData = reqObj.getRequest(); - if (null != address && address.size() > 0 && orgData.containsKey(JsonKey.ADDRESS)) { - innerMap.put(JsonKey.ADDRESS, address); - orgData.remove(JsonKey.ADDRESS); - } - innerMap.put(JsonKey.ORGANISATION, orgData); - innerMap.put(JsonKey.REQUESTED_BY, ctx().flash().get(JsonKey.USER_ID)); - reqObj.setRequest(innerMap); - return actorResponseHandler(getActorRef(), reqObj, timeout, null, request()); - } catch (Exception e) { - return Promise.pure(createCommonExceptionResponse(e, request())); - } + } + + /** + * This method will update organization data. + * + * @return Promise + */ + @SuppressWarnings("unchecked") + public Promise updateOrg() { + + try { + JsonNode requestData = request().body().asJson(); + ProjectLogger.log("Update organisation request: " + requestData, LoggerEnum.INFO.name()); + Request reqObj = (Request) mapper.RequestMapper.mapRequest(requestData, Request.class); + ProjectUtil.updateMapSomeValueTOLowerCase(reqObj); + RequestValidator.validateUpdateOrg(reqObj); + reqObj.setOperation(ActorOperations.UPDATE_ORG.getValue()); + reqObj.setRequestId(ExecutionContext.getRequestId()); + reqObj.setEnv(getEnvironment()); + HashMap innerMap = new HashMap<>(); + Map address = (Map) reqObj.getRequest().get(JsonKey.ADDRESS); + Map orgData = reqObj.getRequest(); + if (null != address && address.size() > 0 && orgData.containsKey(JsonKey.ADDRESS)) { + innerMap.put(JsonKey.ADDRESS, address); + orgData.remove(JsonKey.ADDRESS); + } + innerMap.put(JsonKey.ORGANISATION, orgData); + innerMap.put(JsonKey.REQUESTED_BY, ctx().flash().get(JsonKey.USER_ID)); + reqObj.setRequest(innerMap); + return actorResponseHandler(getActorRef(), reqObj, timeout, null, request()); + } catch (Exception e) { + return Promise.pure(createCommonExceptionResponse(e, request())); } - - /** - * Method to update the status of the organization - * - * @return Promise - */ - public Promise updateOrgStatus() { - - try { - JsonNode requestData = request().body().asJson(); - ProjectLogger.log("Update organisation request: " + requestData, - LoggerEnum.INFO.name()); - Request reqObj = (Request) mapper.RequestMapper.mapRequest(requestData, Request.class); - ProjectUtil.updateMapSomeValueTOLowerCase(reqObj); - RequestValidator.validateUpdateOrgStatus(reqObj); - reqObj.setOperation(ActorOperations.UPDATE_ORG_STATUS.getValue()); - reqObj.setRequestId(ExecutionContext.getRequestId()); - reqObj.setEnv(getEnvironment()); - HashMap innerMap = new HashMap<>(); - innerMap.put(JsonKey.ORGANISATION, reqObj.getRequest()); - innerMap.put(JsonKey.REQUESTED_BY, ctx().flash().get(JsonKey.USER_ID)); - reqObj.setRequest(innerMap); - return actorResponseHandler(getActorRef(), reqObj, timeout, null, request()); - } catch (Exception e) { - return Promise.pure(createCommonExceptionResponse(e, null)); - } + } + + /** + * Method to update the status of the organization + * + * @return Promise + */ + public Promise updateOrgStatus() { + + try { + JsonNode requestData = request().body().asJson(); + ProjectLogger.log("Update organisation request: " + requestData, LoggerEnum.INFO.name()); + Request reqObj = (Request) mapper.RequestMapper.mapRequest(requestData, Request.class); + ProjectUtil.updateMapSomeValueTOLowerCase(reqObj); + RequestValidator.validateUpdateOrgStatus(reqObj); + reqObj.setOperation(ActorOperations.UPDATE_ORG_STATUS.getValue()); + reqObj.setRequestId(ExecutionContext.getRequestId()); + reqObj.setEnv(getEnvironment()); + HashMap innerMap = new HashMap<>(); + innerMap.put(JsonKey.ORGANISATION, reqObj.getRequest()); + innerMap.put(JsonKey.REQUESTED_BY, ctx().flash().get(JsonKey.USER_ID)); + reqObj.setRequest(innerMap); + return actorResponseHandler(getActorRef(), reqObj, timeout, null, request()); + } catch (Exception e) { + return Promise.pure(createCommonExceptionResponse(e, null)); } - - /** - * This method will provide user profile details based on requested userId. - * - * @return Promise - */ - public Promise getOrgDetails() { - - try { - JsonNode requestData = request().body().asJson(); - ProjectLogger.log("Get Organisation details request: " + requestData, - LoggerEnum.INFO.name()); - Request reqObj = (Request) mapper.RequestMapper.mapRequest(requestData, Request.class); - ProjectUtil.updateMapSomeValueTOLowerCase(reqObj); - RequestValidator.validateOrg(reqObj); - reqObj.setOperation(ActorOperations.GET_ORG_DETAILS.getValue()); - reqObj.setRequestId(ExecutionContext.getRequestId()); - reqObj.setEnv(getEnvironment()); - HashMap innerMap = new HashMap<>(); - innerMap.put(JsonKey.ORGANISATION, reqObj.getRequest()); - innerMap.put(JsonKey.REQUESTED_BY, ctx().flash().get(JsonKey.USER_ID)); - reqObj.setRequest(innerMap); - return actorResponseHandler(getActorRef(), reqObj, timeout, null, request()); - } catch (Exception e) { - return Promise.pure(createCommonExceptionResponse(e, request())); - } + } + + /** + * This method will provide user profile details based on requested userId. + * + * @return Promise + */ + public Promise getOrgDetails() { + + try { + JsonNode requestData = request().body().asJson(); + ProjectLogger.log("Get Organisation details request: " + requestData, LoggerEnum.INFO.name()); + Request reqObj = (Request) mapper.RequestMapper.mapRequest(requestData, Request.class); + ProjectUtil.updateMapSomeValueTOLowerCase(reqObj); + RequestValidator.validateOrg(reqObj); + reqObj.setOperation(ActorOperations.GET_ORG_DETAILS.getValue()); + reqObj.setRequestId(ExecutionContext.getRequestId()); + reqObj.setEnv(getEnvironment()); + HashMap innerMap = new HashMap<>(); + innerMap.put(JsonKey.ORGANISATION, reqObj.getRequest()); + innerMap.put(JsonKey.REQUESTED_BY, ctx().flash().get(JsonKey.USER_ID)); + reqObj.setRequest(innerMap); + return actorResponseHandler(getActorRef(), reqObj, timeout, null, request()); + } catch (Exception e) { + return Promise.pure(createCommonExceptionResponse(e, request())); } - - /** - * Method to add an user to the organization - * - * @return Promise - */ - public Promise addMemberToOrganisation() { - - try { - JsonNode requestData = request().body().asJson(); - ProjectLogger.log(" add member to organisation = " + requestData, - LoggerEnum.INFO.name()); - Request reqObj = (Request) mapper.RequestMapper.mapRequest(requestData, Request.class); - ProjectUtil.updateMapSomeValueTOLowerCase(reqObj); - RequestValidator.validateAddMember(reqObj); - reqObj.setOperation(ActorOperations.ADD_MEMBER_ORGANISATION.getValue()); - reqObj.setRequestId(ExecutionContext.getRequestId()); - reqObj.setEnv(getEnvironment()); - HashMap innerMap = new HashMap<>(); - innerMap.put(JsonKey.USER_ORG, reqObj.getRequest()); - innerMap.put(JsonKey.REQUESTED_BY, ctx().flash().get(JsonKey.USER_ID)); - reqObj.setRequest(innerMap); - return actorResponseHandler(getActorRef(), reqObj, timeout, null, request()); - } catch (Exception e) { - return Promise.pure(createCommonExceptionResponse(e, request())); - } + } + + /** + * Method to add an user to the organization + * + * @return Promise + */ + public Promise addMemberToOrganisation() { + + try { + JsonNode requestData = request().body().asJson(); + ProjectLogger.log(" add member to organisation = " + requestData, LoggerEnum.INFO.name()); + Request reqObj = (Request) mapper.RequestMapper.mapRequest(requestData, Request.class); + ProjectUtil.updateMapSomeValueTOLowerCase(reqObj); + RequestValidator.validateAddMember(reqObj); + reqObj.setOperation(ActorOperations.ADD_MEMBER_ORGANISATION.getValue()); + reqObj.setRequestId(ExecutionContext.getRequestId()); + reqObj.setEnv(getEnvironment()); + HashMap innerMap = new HashMap<>(); + innerMap.put(JsonKey.USER_ORG, reqObj.getRequest()); + innerMap.put(JsonKey.REQUESTED_BY, ctx().flash().get(JsonKey.USER_ID)); + reqObj.setRequest(innerMap); + return actorResponseHandler(getActorRef(), reqObj, timeout, null, request()); + } catch (Exception e) { + return Promise.pure(createCommonExceptionResponse(e, request())); } - - /** - * Method to remove an user to the organization - * - * @return Promise - */ - public Promise removeMemberFromOrganisation() { - - try { - JsonNode requestData = request().body().asJson(); - ProjectLogger.log(" remove member from organisation = " + requestData, - LoggerEnum.INFO.name()); - Request reqObj = (Request) mapper.RequestMapper.mapRequest(requestData, Request.class); - ProjectUtil.updateMapSomeValueTOLowerCase(reqObj); - RequestValidator.validateUserOrg(reqObj); - reqObj.setOperation(ActorOperations.REMOVE_MEMBER_ORGANISATION.getValue()); - reqObj.setRequestId(ExecutionContext.getRequestId()); - reqObj.setEnv(getEnvironment()); - HashMap innerMap = new HashMap<>(); - innerMap.put(JsonKey.USER_ORG, reqObj.getRequest()); - innerMap.put(JsonKey.REQUESTED_BY, ctx().flash().get(JsonKey.USER_ID)); - reqObj.setRequest(innerMap); - return actorResponseHandler(getActorRef(), reqObj, timeout, null, request()); - } catch (Exception e) { - return Promise.pure(createCommonExceptionResponse(e, request())); - } + } + + /** + * Method to remove an user to the organization + * + * @return Promise + */ + public Promise removeMemberFromOrganisation() { + + try { + JsonNode requestData = request().body().asJson(); + ProjectLogger.log( + " remove member from organisation = " + requestData, LoggerEnum.INFO.name()); + Request reqObj = (Request) mapper.RequestMapper.mapRequest(requestData, Request.class); + ProjectUtil.updateMapSomeValueTOLowerCase(reqObj); + RequestValidator.validateUserOrg(reqObj); + reqObj.setOperation(ActorOperations.REMOVE_MEMBER_ORGANISATION.getValue()); + reqObj.setRequestId(ExecutionContext.getRequestId()); + reqObj.setEnv(getEnvironment()); + HashMap innerMap = new HashMap<>(); + innerMap.put(JsonKey.USER_ORG, reqObj.getRequest()); + innerMap.put(JsonKey.REQUESTED_BY, ctx().flash().get(JsonKey.USER_ID)); + reqObj.setRequest(innerMap); + return actorResponseHandler(getActorRef(), reqObj, timeout, null, request()); + } catch (Exception e) { + return Promise.pure(createCommonExceptionResponse(e, request())); } - - /** - * Method to perform the user join organization operation . - * - * @return Promise - */ - public Promise joinUserOrganisation() { - - try { - JsonNode requestData = request().body().asJson(); - ProjectLogger.log(" join user organisation = " + requestData, LoggerEnum.INFO.name()); - Request reqObj = (Request) mapper.RequestMapper.mapRequest(requestData, Request.class); - ProjectUtil.updateMapSomeValueTOLowerCase(reqObj); - RequestValidator.validateUserOrg(reqObj); - reqObj.setOperation(ActorOperations.JOIN_USER_ORGANISATION.getValue()); - reqObj.setRequestId(ExecutionContext.getRequestId()); - reqObj.setEnv(getEnvironment()); - HashMap innerMap = new HashMap<>(); - innerMap.put(JsonKey.USER_ORG, reqObj.getRequest()); - innerMap.put(JsonKey.REQUESTED_BY, ctx().flash().get(JsonKey.USER_ID)); - reqObj.setRequest(innerMap); - return actorResponseHandler(getActorRef(), reqObj, timeout, null, request()); - } catch (Exception e) { - return Promise.pure(createCommonExceptionResponse(e, request())); - } + } + + /** + * Method to perform the user join organization operation . + * + * @return Promise + */ + public Promise joinUserOrganisation() { + + try { + JsonNode requestData = request().body().asJson(); + ProjectLogger.log(" join user organisation = " + requestData, LoggerEnum.INFO.name()); + Request reqObj = (Request) mapper.RequestMapper.mapRequest(requestData, Request.class); + ProjectUtil.updateMapSomeValueTOLowerCase(reqObj); + RequestValidator.validateUserOrg(reqObj); + reqObj.setOperation(ActorOperations.JOIN_USER_ORGANISATION.getValue()); + reqObj.setRequestId(ExecutionContext.getRequestId()); + reqObj.setEnv(getEnvironment()); + HashMap innerMap = new HashMap<>(); + innerMap.put(JsonKey.USER_ORG, reqObj.getRequest()); + innerMap.put(JsonKey.REQUESTED_BY, ctx().flash().get(JsonKey.USER_ID)); + reqObj.setRequest(innerMap); + return actorResponseHandler(getActorRef(), reqObj, timeout, null, request()); + } catch (Exception e) { + return Promise.pure(createCommonExceptionResponse(e, request())); } - - /** - * Method to approve the user joined organization . - * - * @return Promise - */ - public Promise approveUserOrganisation() { - - try { - JsonNode requestData = request().body().asJson(); - ProjectLogger.log(" approve user organisation = " + requestData, - LoggerEnum.INFO.name()); - Request reqObj = (Request) mapper.RequestMapper.mapRequest(requestData, Request.class); - ProjectUtil.updateMapSomeValueTOLowerCase(reqObj); - RequestValidator.validateUserOrg(reqObj); - reqObj.setOperation(ActorOperations.APPROVE_USER_ORGANISATION.getValue()); - reqObj.setRequestId(ExecutionContext.getRequestId()); - reqObj.setEnv(getEnvironment()); - HashMap innerMap = new HashMap<>(); - innerMap.put(JsonKey.USER_ORG, reqObj.getRequest()); - innerMap.put(JsonKey.REQUESTED_BY, ctx().flash().get(JsonKey.USER_ID)); - reqObj.setRequest(innerMap); - return actorResponseHandler(getActorRef(), reqObj, timeout, null, request()); - } catch (Exception e) { - return Promise.pure(createCommonExceptionResponse(e, request())); - } + } + + /** + * Method to approve the user joined organization . + * + * @return Promise + */ + public Promise approveUserOrganisation() { + + try { + JsonNode requestData = request().body().asJson(); + ProjectLogger.log(" approve user organisation = " + requestData, LoggerEnum.INFO.name()); + Request reqObj = (Request) mapper.RequestMapper.mapRequest(requestData, Request.class); + ProjectUtil.updateMapSomeValueTOLowerCase(reqObj); + RequestValidator.validateUserOrg(reqObj); + reqObj.setOperation(ActorOperations.APPROVE_USER_ORGANISATION.getValue()); + reqObj.setRequestId(ExecutionContext.getRequestId()); + reqObj.setEnv(getEnvironment()); + HashMap innerMap = new HashMap<>(); + innerMap.put(JsonKey.USER_ORG, reqObj.getRequest()); + innerMap.put(JsonKey.REQUESTED_BY, ctx().flash().get(JsonKey.USER_ID)); + reqObj.setRequest(innerMap); + return actorResponseHandler(getActorRef(), reqObj, timeout, null, request()); + } catch (Exception e) { + return Promise.pure(createCommonExceptionResponse(e, request())); } - - /** - * Method to reject the user organization . - * - * @return Promise - */ - public Promise rejectUserOrganisation() { - - try { - JsonNode requestData = request().body().asJson(); - ProjectLogger.log(" approve user organisation = " + requestData, - LoggerEnum.INFO.name()); - Request reqObj = (Request) mapper.RequestMapper.mapRequest(requestData, Request.class); - ProjectUtil.updateMapSomeValueTOLowerCase(reqObj); - RequestValidator.validateUserOrg(reqObj); - reqObj.setOperation(ActorOperations.REJECT_USER_ORGANISATION.getValue()); - reqObj.setRequestId(ExecutionContext.getRequestId()); - reqObj.setEnv(getEnvironment()); - HashMap innerMap = new HashMap<>(); - innerMap.put(JsonKey.USER_ORG, reqObj.getRequest()); - innerMap.put(JsonKey.REQUESTED_BY, ctx().flash().get(JsonKey.USER_ID)); - reqObj.setRequest(innerMap); - return actorResponseHandler(getActorRef(), reqObj, timeout, null, request()); - } catch (Exception e) { - return Promise.pure(createCommonExceptionResponse(e, request())); - } + } + + /** + * Method to reject the user organization . + * + * @return Promise + */ + public Promise rejectUserOrganisation() { + + try { + JsonNode requestData = request().body().asJson(); + ProjectLogger.log(" approve user organisation = " + requestData, LoggerEnum.INFO.name()); + Request reqObj = (Request) mapper.RequestMapper.mapRequest(requestData, Request.class); + ProjectUtil.updateMapSomeValueTOLowerCase(reqObj); + RequestValidator.validateUserOrg(reqObj); + reqObj.setOperation(ActorOperations.REJECT_USER_ORGANISATION.getValue()); + reqObj.setRequestId(ExecutionContext.getRequestId()); + reqObj.setEnv(getEnvironment()); + HashMap innerMap = new HashMap<>(); + innerMap.put(JsonKey.USER_ORG, reqObj.getRequest()); + innerMap.put(JsonKey.REQUESTED_BY, ctx().flash().get(JsonKey.USER_ID)); + reqObj.setRequest(innerMap); + return actorResponseHandler(getActorRef(), reqObj, timeout, null, request()); + } catch (Exception e) { + return Promise.pure(createCommonExceptionResponse(e, request())); } - - /** - * This method will download organization details. - * - * @return Promise - */ - public Promise downloadOrgs() { - try { - JsonNode requestData = request().body().asJson(); - ProjectLogger.log(" Downlaod org data request =" + requestData, LoggerEnum.INFO.name()); - Request reqObj = (Request) mapper.RequestMapper.mapRequest(requestData, Request.class); - reqObj.setOperation(ActorOperations.DOWNLOAD_ORGS.getValue()); - reqObj.setRequestId(ExecutionContext.getRequestId()); - reqObj.setEnv(getEnvironment()); - HashMap innerMap = new HashMap<>(); - ProjectUtil.updateMapSomeValueTOLowerCase(reqObj); - innerMap.put(JsonKey.REQUESTED_BY, ctx().flash().get(JsonKey.USER_ID)); - reqObj.setRequest(innerMap); - return actorResponseHandler(getActorRef(), reqObj, timeout, null, request()); - } catch (Exception e) { - return Promise.pure(createCommonExceptionResponse(e, request())); - } + } + + /** + * This method will download organization details. + * + * @return Promise + */ + public Promise downloadOrgs() { + try { + JsonNode requestData = request().body().asJson(); + ProjectLogger.log(" Downlaod org data request =" + requestData, LoggerEnum.INFO.name()); + Request reqObj = (Request) mapper.RequestMapper.mapRequest(requestData, Request.class); + reqObj.setOperation(ActorOperations.DOWNLOAD_ORGS.getValue()); + reqObj.setRequestId(ExecutionContext.getRequestId()); + reqObj.setEnv(getEnvironment()); + HashMap innerMap = new HashMap<>(); + ProjectUtil.updateMapSomeValueTOLowerCase(reqObj); + innerMap.put(JsonKey.REQUESTED_BY, ctx().flash().get(JsonKey.USER_ID)); + reqObj.setRequest(innerMap); + return actorResponseHandler(getActorRef(), reqObj, timeout, null, request()); + } catch (Exception e) { + return Promise.pure(createCommonExceptionResponse(e, request())); } - - - /** - * This method will do the organisation search for Elastic search. this will internally call - * composite search api. - * - * @return Promise - */ - @SuppressWarnings({"unchecked", "rawtypes"}) - public Promise search() { - try { - JsonNode requestData = request().body().asJson(); - ProjectLogger.log("Organisation search api call =" + requestData, - LoggerEnum.INFO.name()); - Request reqObj = (Request) mapper.RequestMapper.mapRequest(requestData, Request.class); - ProjectUtil.updateMapSomeValueTOLowerCase(reqObj); - reqObj.setOperation(ActorOperations.COMPOSITE_SEARCH.getValue()); - reqObj.setRequestId(ExecutionContext.getRequestId()); - reqObj.setEnv(getEnvironment()); - reqObj.put(JsonKey.REQUESTED_BY, ctx().flash().get(JsonKey.USER_ID)); - List esObjectType = new ArrayList<>(); - esObjectType.add(EsType.organisation.getTypeName()); - - if (reqObj.getRequest().containsKey(JsonKey.FILTERS) - && reqObj.getRequest().get(JsonKey.FILTERS) != null - && reqObj.getRequest().get(JsonKey.FILTERS) instanceof Map) { - ((Map) (reqObj.getRequest().get(JsonKey.FILTERS))).put(JsonKey.OBJECT_TYPE, - esObjectType); - } else { - Map filtermap = new HashMap<>(); - Map dataMap = new HashMap<>(); - dataMap.put(JsonKey.OBJECT_TYPE, esObjectType); - filtermap.put(JsonKey.FILTERS, dataMap); - } - return actorResponseHandler(getActorRef(), reqObj, timeout, null, request()); - } catch (Exception e) { - return Promise.pure(createCommonExceptionResponse(e, request())); - } + } + + /** + * This method will do the organisation search for Elastic search. this will internally call + * composite search api. + * + * @return Promise + */ + @SuppressWarnings({"unchecked", "rawtypes"}) + public Promise search() { + try { + JsonNode requestData = request().body().asJson(); + ProjectLogger.log("Organisation search api call =" + requestData, LoggerEnum.INFO.name()); + Request reqObj = (Request) mapper.RequestMapper.mapRequest(requestData, Request.class); + ProjectUtil.updateMapSomeValueTOLowerCase(reqObj); + reqObj.setOperation(ActorOperations.COMPOSITE_SEARCH.getValue()); + reqObj.setRequestId(ExecutionContext.getRequestId()); + reqObj.setEnv(getEnvironment()); + reqObj.put(JsonKey.REQUESTED_BY, ctx().flash().get(JsonKey.USER_ID)); + List esObjectType = new ArrayList<>(); + esObjectType.add(EsType.organisation.getTypeName()); + + if (reqObj.getRequest().containsKey(JsonKey.FILTERS) + && reqObj.getRequest().get(JsonKey.FILTERS) != null + && reqObj.getRequest().get(JsonKey.FILTERS) instanceof Map) { + ((Map) (reqObj.getRequest().get(JsonKey.FILTERS))).put(JsonKey.OBJECT_TYPE, esObjectType); + } else { + Map filtermap = new HashMap<>(); + Map dataMap = new HashMap<>(); + dataMap.put(JsonKey.OBJECT_TYPE, esObjectType); + filtermap.put(JsonKey.FILTERS, dataMap); + } + return actorResponseHandler(getActorRef(), reqObj, timeout, null, request()); + } catch (Exception e) { + return Promise.pure(createCommonExceptionResponse(e, request())); } - - /** - * This method will fetch list of OrgType. - * - * @return Promise - */ - public Promise getOrgTypeList() { - try { - ProjectLogger.log("Organisation getOrgTypeList method call", LoggerEnum.INFO.name()); - Request reqObj = new Request(); - reqObj.setOperation(ActorOperations.GET_ORG_TYPE_LIST.getValue()); - reqObj.setRequestId(ExecutionContext.getRequestId()); - reqObj.setEnv(getEnvironment()); - reqObj.put(JsonKey.REQUESTED_BY, ctx().flash().get(JsonKey.USER_ID)); - return actorResponseHandler(getActorRef(), reqObj, timeout, null, request()); - } catch (Exception e) { - return Promise.pure(createCommonExceptionResponse(e, request())); - } + } + + /** + * This method will fetch list of OrgType. + * + * @return Promise + */ + public Promise getOrgTypeList() { + try { + ProjectLogger.log("Organisation getOrgTypeList method call", LoggerEnum.INFO.name()); + Request reqObj = new Request(); + reqObj.setOperation(ActorOperations.GET_ORG_TYPE_LIST.getValue()); + reqObj.setRequestId(ExecutionContext.getRequestId()); + reqObj.setEnv(getEnvironment()); + reqObj.put(JsonKey.REQUESTED_BY, ctx().flash().get(JsonKey.USER_ID)); + return actorResponseHandler(getActorRef(), reqObj, timeout, null, request()); + } catch (Exception e) { + return Promise.pure(createCommonExceptionResponse(e, request())); } - - /** - * This method will create OrgType. - * - * @return Promise - */ - public Promise createOrgType() { - try { - JsonNode requestData = request().body().asJson(); - ProjectLogger.log("Organisation CreateOrgType method call =" + requestData, - LoggerEnum.INFO.name()); - Request reqObj = (Request) mapper.RequestMapper.mapRequest(requestData, Request.class); - RequestValidator.validateCreateOrgType(reqObj); - reqObj.setOperation(ActorOperations.CREATE_ORG_TYPE.getValue()); - reqObj.setRequestId(ExecutionContext.getRequestId()); - reqObj.setEnv(getEnvironment()); - reqObj.getRequest().put(JsonKey.CREATED_BY, ctx().flash().get(JsonKey.USER_ID)); - return actorResponseHandler(getActorRef(), reqObj, timeout, null, request()); - } catch (Exception e) { - return Promise.pure(createCommonExceptionResponse(e, request())); - } + } + + /** + * This method will create OrgType. + * + * @return Promise + */ + public Promise createOrgType() { + try { + JsonNode requestData = request().body().asJson(); + ProjectLogger.log( + "Organisation CreateOrgType method call =" + requestData, LoggerEnum.INFO.name()); + Request reqObj = (Request) mapper.RequestMapper.mapRequest(requestData, Request.class); + RequestValidator.validateCreateOrgType(reqObj); + reqObj.setOperation(ActorOperations.CREATE_ORG_TYPE.getValue()); + reqObj.setRequestId(ExecutionContext.getRequestId()); + reqObj.setEnv(getEnvironment()); + reqObj.getRequest().put(JsonKey.CREATED_BY, ctx().flash().get(JsonKey.USER_ID)); + return actorResponseHandler(getActorRef(), reqObj, timeout, null, request()); + } catch (Exception e) { + return Promise.pure(createCommonExceptionResponse(e, request())); } - - /** - * This method will update OrgType. - * - * @return Promise - */ - public Promise updateOrgType() { - try { - JsonNode requestData = request().body().asJson(); - ProjectLogger.log("Organisation UpdateOrgType method call =" + requestData, - LoggerEnum.INFO.name()); - Request reqObj = (Request) mapper.RequestMapper.mapRequest(requestData, Request.class); - RequestValidator.validateUpdateOrgType(reqObj); - reqObj.setOperation(ActorOperations.UPDATE_ORG_TYPE.getValue()); - reqObj.setRequestId(ExecutionContext.getRequestId()); - reqObj.setEnv(getEnvironment()); - reqObj.getRequest().put(JsonKey.UPDATED_BY, ctx().flash().get(JsonKey.USER_ID)); - return actorResponseHandler(getActorRef(), reqObj, timeout, null, request()); - } catch (Exception e) { - return Promise.pure(createCommonExceptionResponse(e, request())); - } + } + + /** + * This method will update OrgType. + * + * @return Promise + */ + public Promise updateOrgType() { + try { + JsonNode requestData = request().body().asJson(); + ProjectLogger.log( + "Organisation UpdateOrgType method call =" + requestData, LoggerEnum.INFO.name()); + Request reqObj = (Request) mapper.RequestMapper.mapRequest(requestData, Request.class); + RequestValidator.validateUpdateOrgType(reqObj); + reqObj.setOperation(ActorOperations.UPDATE_ORG_TYPE.getValue()); + reqObj.setRequestId(ExecutionContext.getRequestId()); + reqObj.setEnv(getEnvironment()); + reqObj.getRequest().put(JsonKey.UPDATED_BY, ctx().flash().get(JsonKey.USER_ID)); + return actorResponseHandler(getActorRef(), reqObj, timeout, null, request()); + } catch (Exception e) { + return Promise.pure(createCommonExceptionResponse(e, request())); } - + } } diff --git a/service/app/controllers/pagemanagement/PageController.java b/service/app/controllers/pagemanagement/PageController.java index 75f8a9dbfa..09bdb03631 100644 --- a/service/app/controllers/pagemanagement/PageController.java +++ b/service/app/controllers/pagemanagement/PageController.java @@ -1,13 +1,12 @@ -/** - * - */ +/** */ package controllers.pagemanagement; +import com.fasterxml.jackson.databind.JsonNode; +import controllers.BaseController; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; - import org.sunbird.common.models.util.ActorOperations; import org.sunbird.common.models.util.JsonKey; import org.sunbird.common.models.util.LoggerEnum; @@ -15,32 +14,27 @@ import org.sunbird.common.request.ExecutionContext; import org.sunbird.common.request.Request; import org.sunbird.common.request.RequestValidator; - -import com.fasterxml.jackson.databind.JsonNode; - -import controllers.BaseController; import play.libs.F.Promise; import play.mvc.Result; /** * This controller will handle all the request related to page api's. - * + * * @author Amit Kumar */ - public class PageController extends BaseController { /** * This method will allow admin to create a page for view. - * + * * @return Promise */ public Promise createPage() { try { JsonNode requestData = request().body().asJson(); - ProjectLogger.log("getting create page data request = " + requestData, - LoggerEnum.INFO.name()); + ProjectLogger.log( + "getting create page data request = " + requestData, LoggerEnum.INFO.name()); Request reqObj = (Request) mapper.RequestMapper.mapRequest(requestData, Request.class); RequestValidator.validateCreatePage(reqObj); reqObj.setOperation(ActorOperations.CREATE_PAGE.getValue()); @@ -56,18 +50,17 @@ public Promise createPage() { } } - /** * This method will allow admin to update already created page data. - * + * * @return Promise */ public Promise updatePage() { try { JsonNode requestData = request().body().asJson(); - ProjectLogger.log("getting update page data request = " + requestData, - LoggerEnum.INFO.name()); + ProjectLogger.log( + "getting update page data request = " + requestData, LoggerEnum.INFO.name()); Request reqObj = (Request) mapper.RequestMapper.mapRequest(requestData, Request.class); RequestValidator.validateUpdatepage(reqObj); reqObj.setOperation(ActorOperations.UPDATE_PAGE.getValue()); @@ -85,15 +78,15 @@ public Promise updatePage() { /** * This method will provide particular page setting data. - * + * * @param pageId String * @return Promise */ public Promise getPageSetting(String pageId) { try { - ProjectLogger.log("getting data for particular page settings = " + pageId, - LoggerEnum.INFO.name()); + ProjectLogger.log( + "getting data for particular page settings = " + pageId, LoggerEnum.INFO.name()); Request reqObj = new Request(); reqObj.setOperation(ActorOperations.GET_PAGE_SETTING.getValue()); reqObj.setRequestId(ExecutionContext.getRequestId()); @@ -105,10 +98,9 @@ public Promise getPageSetting(String pageId) { } } - /** * This method will provide completed data for all pages which is saved in cassandra DAC. - * + * * @return Promise */ public Promise getPageSettings() { @@ -127,7 +119,7 @@ public Promise getPageSettings() { /** * This method will provide completed data for a particular page. - * + * * @return Promise */ public Promise getPageData() { @@ -153,7 +145,7 @@ public Promise getPageData() { /** * Method to get all request headers - * + * * @param request play.mvc.Http.Request * @return Map */ @@ -169,18 +161,17 @@ private Map getAllRequestHeaders(play.mvc.Http.Request request) return map; } - /** * This method will allow admin to create sections for page view - * + * * @return Promise */ public Promise createPageSection() { try { JsonNode requestData = request().body().asJson(); - ProjectLogger.log("getting create page section data request=" + requestData, - LoggerEnum.INFO.name()); + ProjectLogger.log( + "getting create page section data request=" + requestData, LoggerEnum.INFO.name()); Request reqObj = (Request) mapper.RequestMapper.mapRequest(requestData, Request.class); RequestValidator.validateCreateSection(reqObj); reqObj.setOperation(ActorOperations.CREATE_SECTION.getValue()); @@ -196,18 +187,17 @@ public Promise createPageSection() { } } - /** * This method will allow admin to update already created page sections - * + * * @return Promise */ public Promise updatePageSection() { try { JsonNode requestData = request().body().asJson(); - ProjectLogger.log("getting update page section data request=" + requestData, - LoggerEnum.INFO.name()); + ProjectLogger.log( + "getting update page section data request=" + requestData, LoggerEnum.INFO.name()); Request reqObj = (Request) mapper.RequestMapper.mapRequest(requestData, Request.class); RequestValidator.validateUpdateSection(reqObj); reqObj.setOperation(ActorOperations.UPDATE_SECTION.getValue()); @@ -225,15 +215,15 @@ public Promise updatePageSection() { /** * This method will provide particular page section data. - * + * * @param sectionId String * @return Promise */ public Promise getSection(String sectionId) { try { - ProjectLogger.log("getting data for particular page section =" + sectionId, - LoggerEnum.INFO.name()); + ProjectLogger.log( + "getting data for particular page section =" + sectionId, LoggerEnum.INFO.name()); Request reqObj = new Request(); reqObj.setOperation(ActorOperations.GET_SECTION.getValue()); reqObj.setRequestId(ExecutionContext.getRequestId()); @@ -245,10 +235,9 @@ public Promise getSection(String sectionId) { } } - /** * This method will provide completed data for all sections stored in cassandra DAC. - * + * * @return Promise */ public Promise getSections() { @@ -264,5 +253,4 @@ public Promise getSections() { return Promise.pure(createCommonExceptionResponse(e, request())); } } - } diff --git a/service/app/controllers/search/SearchController.java b/service/app/controllers/search/SearchController.java index 1f808c9f15..63c2631a32 100644 --- a/service/app/controllers/search/SearchController.java +++ b/service/app/controllers/search/SearchController.java @@ -1,10 +1,9 @@ -/** - * - */ +/** */ package controllers.search; +import com.fasterxml.jackson.databind.JsonNode; +import controllers.BaseController; import java.util.HashMap; - import org.sunbird.common.models.util.ActorOperations; import org.sunbird.common.models.util.JsonKey; import org.sunbird.common.models.util.LoggerEnum; @@ -12,16 +11,12 @@ import org.sunbird.common.request.ExecutionContext; import org.sunbird.common.request.Request; import org.sunbird.common.request.RequestValidator; - -import com.fasterxml.jackson.databind.JsonNode; - -import controllers.BaseController; import play.libs.F.Promise; import play.mvc.Result; /** * This controller will handle all the request related user and organization search. - * + * * @author Manzarul */ public class SearchController extends BaseController { @@ -30,7 +25,7 @@ public class SearchController extends BaseController { * This method will do data search for user and organization. Search type will be decide based on * request object type coming with filter if objectType key is not coming then we need to do the * search for all the types. - * + * * @return Promise */ public Promise compositeSearch() { @@ -50,7 +45,7 @@ public Promise compositeSearch() { /** * This method will do data Sync form Cassandra db to Elasticsearch. - * + * * @return Promise */ public Promise sync() { @@ -60,7 +55,7 @@ public Promise sync() { Request reqObj = (Request) mapper.RequestMapper.mapRequest(requestData, Request.class); RequestValidator.validateSyncRequest(reqObj); String operation = (String) reqObj.getRequest().get(JsonKey.OPERATION_FOR); - if("keycloak".equalsIgnoreCase(operation)){ + if ("keycloak".equalsIgnoreCase(operation)) { reqObj.setOperation(ActorOperations.SYNC_KEYCLOAK.getValue()); reqObj.setRequestId(ExecutionContext.getRequestId()); reqObj.getRequest().put(JsonKey.CREATED_BY, ctx().flash().get(JsonKey.USER_ID)); @@ -69,7 +64,7 @@ public Promise sync() { map.put(JsonKey.DATA, reqObj.getRequest()); reqObj.setRequest(map); return actorResponseHandler(getActorRef(), reqObj, timeout, null, request()); - }else{ + } else { reqObj.setOperation(ActorOperations.SYNC.getValue()); reqObj.setRequestId(ExecutionContext.getRequestId()); reqObj.getRequest().put(JsonKey.CREATED_BY, ctx().flash().get(JsonKey.USER_ID)); @@ -79,10 +74,9 @@ public Promise sync() { reqObj.setRequest(map); return actorResponseHandler(getActorRef(), reqObj, timeout, null, request()); } - + } catch (Exception e) { return Promise.pure(createCommonExceptionResponse(e, request())); } } - } diff --git a/service/app/controllers/skills/SkillController.java b/service/app/controllers/skills/SkillController.java index 0e4fad8777..01b915f84e 100644 --- a/service/app/controllers/skills/SkillController.java +++ b/service/app/controllers/skills/SkillController.java @@ -1,23 +1,18 @@ package controllers.skills; +import com.fasterxml.jackson.databind.JsonNode; +import controllers.BaseController; import java.util.Map; - 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.ExecutionContext; import org.sunbird.common.request.Request; - -import com.fasterxml.jackson.databind.JsonNode; - -import controllers.BaseController; import play.libs.F.Promise; import play.mvc.Result; -/** - * Created by arvind on 23/10/17. - */ +/** Created by arvind on 23/10/17. */ public class SkillController extends BaseController { public Promise addSkill() { @@ -69,5 +64,4 @@ public Promise getSkillsList() { return Promise.pure(createCommonExceptionResponse(e, request())); } } - } diff --git a/service/app/controllers/storage/FileStorageController.java b/service/app/controllers/storage/FileStorageController.java index 88900b1658..89f0dac6ff 100644 --- a/service/app/controllers/storage/FileStorageController.java +++ b/service/app/controllers/storage/FileStorageController.java @@ -1,5 +1,7 @@ package controllers.storage; +import com.fasterxml.jackson.databind.JsonNode; +import controllers.BaseController; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; @@ -9,7 +11,6 @@ import java.util.List; import java.util.Map; import java.util.Map.Entry; - import org.apache.commons.io.IOUtils; import org.sunbird.common.exception.ProjectCommonException; import org.sunbird.common.models.util.ActorOperations; @@ -17,37 +18,32 @@ import org.sunbird.common.request.ExecutionContext; import org.sunbird.common.request.Request; import org.sunbird.common.responsecode.ResponseCode; - -import com.fasterxml.jackson.databind.JsonNode; - -import controllers.BaseController; import play.libs.F.Promise; import play.mvc.Http.MultipartFormData; import play.mvc.Http.MultipartFormData.FilePart; import play.mvc.Result; -/** - * Created by arvind on 28/8/17. - */ +/** Created by arvind on 28/8/17. */ public class FileStorageController extends BaseController { /** - * This method to upload the files on cloud storage . - * @return Promise + * This method to upload the files on cloud storage . + * + * @return Promise */ public Promise uploadFileService() { try { Request reqObj = new Request(); - Map map = new HashMap<>(); + Map map = new HashMap<>(); byte[] byteArray = null; MultipartFormData body = request().body().asMultipartFormData(); - Map formUrlEncodeddata = request().body().asFormUrlEncoded(); + Map formUrlEncodeddata = request().body().asFormUrlEncoded(); JsonNode requestData = request().body().asJson(); if (body != null) { - Map data = body.asFormUrlEncoded(); - for(Entry entry : data.entrySet()){ + Map data = body.asFormUrlEncoded(); + for (Entry entry : data.entrySet()) { map.put(entry.getKey(), entry.getValue()[0]); } List filePart = body.getFiles(); @@ -56,27 +52,32 @@ public Promise uploadFileService() { InputStream is = new FileInputStream(f); byteArray = IOUtils.toByteArray(is); reqObj.getRequest().putAll(map); - map.put(JsonKey.FILE_NAME , filePart.get(0).getFilename()); - } else if(null != formUrlEncodeddata){ - //read data as string from request - for(Entry entry : formUrlEncodeddata.entrySet()){ + map.put(JsonKey.FILE_NAME, filePart.get(0).getFilename()); + } else if (null != formUrlEncodeddata) { + // read data as string from request + for (Entry entry : formUrlEncodeddata.entrySet()) { map.put(entry.getKey(), entry.getValue()[0]); } - InputStream is = new ByteArrayInputStream(((String)map.get(JsonKey.DATA)).getBytes( - StandardCharsets.UTF_8)); + InputStream is = + new ByteArrayInputStream( + ((String) map.get(JsonKey.DATA)).getBytes(StandardCharsets.UTF_8)); byteArray = IOUtils.toByteArray(is); reqObj.getRequest().putAll(map); - } else if(null != requestData){ - reqObj = (Request) mapper.RequestMapper.mapRequest(request().body().asJson(), Request.class); - InputStream is = new ByteArrayInputStream(((String)reqObj.getRequest().get(JsonKey.DATA)).getBytes(StandardCharsets.UTF_8)); + } else if (null != requestData) { + reqObj = + (Request) mapper.RequestMapper.mapRequest(request().body().asJson(), Request.class); + InputStream is = + new ByteArrayInputStream( + ((String) reqObj.getRequest().get(JsonKey.DATA)).getBytes(StandardCharsets.UTF_8)); byteArray = IOUtils.toByteArray(is); reqObj.getRequest().putAll(map); map.putAll(reqObj.getRequest()); - } else{ - ProjectCommonException e = new ProjectCommonException( - ResponseCode.invalidData.getErrorCode(), - ResponseCode.invalidData.getErrorMessage(), - ResponseCode.CLIENT_ERROR.getResponseCode()); + } else { + ProjectCommonException e = + new ProjectCommonException( + ResponseCode.invalidData.getErrorCode(), + ResponseCode.invalidData.getErrorMessage(), + ResponseCode.CLIENT_ERROR.getResponseCode()); return Promise.pure(createCommonExceptionResponse(e, request())); } reqObj.setOperation(ActorOperations.FILE_STORAGE_SERVICE.getValue()); @@ -84,7 +85,7 @@ public Promise uploadFileService() { reqObj.setEnv(getEnvironment()); HashMap innerMap = new HashMap<>(); innerMap.put(JsonKey.DATA, map); - map.put(JsonKey.CREATED_BY,ctx().flash().get(JsonKey.USER_ID)); + map.put(JsonKey.CREATED_BY, ctx().flash().get(JsonKey.USER_ID)); reqObj.setRequest(innerMap); map.put(JsonKey.FILE, byteArray); @@ -93,5 +94,4 @@ public Promise uploadFileService() { return Promise.pure(createCommonExceptionResponse(e, request())); } } - } diff --git a/service/app/controllers/telemetry/TelemetryController.java b/service/app/controllers/telemetry/TelemetryController.java index 31d8d4b21a..fdf0a4c60a 100644 --- a/service/app/controllers/telemetry/TelemetryController.java +++ b/service/app/controllers/telemetry/TelemetryController.java @@ -1,6 +1,4 @@ -/** - * - */ +/** */ package controllers.telemetry; import com.fasterxml.jackson.databind.JsonNode; @@ -20,60 +18,61 @@ /** * This controller will handle all sunbird telemetry request data. - * - * @author Manzarul * + * @author Manzarul */ public class TelemetryController extends BaseController { - /** - * This method will receive the telemetry data and send it to EKStep to process it. - * - * @return Promise - */ - public Promise save() { + /** + * This method will receive the telemetry data and send it to EKStep to process it. + * + * @return Promise + */ + public Promise save() { - try { - Request request = null; - if (isGzipRequest(request().headers())) { - ProjectLogger.log("Receiving telemetry in gzip format.", LoggerEnum.DEBUG.name()); - request = new Request(); - byte[] byteArray = getBytes(request().body()); - Map map = new HashMap<>(); - map.put(JsonKey.FILE, byteArray); - request.getRequest().putAll(map); - } else { - JsonNode requestData = request().body().asJson(); - ProjectLogger.log("Receiving telemetry in json format.", requestData, - LoggerEnum.DEBUG.name()); - request = (Request) RequestMapper.mapRequest(requestData, Request.class); - } - request = setExtraParam(request, ExecutionContext.getRequestId(), - ActorOperations.SAVE_TELEMETRY.getValue(), ctx().flash().get(JsonKey.USER_ID), - getEnvironment()); - return actorResponseHandler(getActorRef(), request, timeout, null, request()); - } catch (Exception e) { - return Promise.pure(createCommonExceptionResponse(e, request())); - } + try { + Request request = null; + if (isGzipRequest(request().headers())) { + ProjectLogger.log("Receiving telemetry in gzip format.", LoggerEnum.DEBUG.name()); + request = new Request(); + byte[] byteArray = getBytes(request().body()); + Map map = new HashMap<>(); + map.put(JsonKey.FILE, byteArray); + request.getRequest().putAll(map); + } else { + JsonNode requestData = request().body().asJson(); + ProjectLogger.log( + "Receiving telemetry in json format.", requestData, LoggerEnum.DEBUG.name()); + request = (Request) RequestMapper.mapRequest(requestData, Request.class); + } + request = + setExtraParam( + request, + ExecutionContext.getRequestId(), + ActorOperations.SAVE_TELEMETRY.getValue(), + ctx().flash().get(JsonKey.USER_ID), + getEnvironment()); + return actorResponseHandler(getActorRef(), request, timeout, null, request()); + } catch (Exception e) { + return Promise.pure(createCommonExceptionResponse(e, request())); } + } - private boolean isGzipRequest(Map headers) { - boolean isGzip = false; - if (headers.containsKey("accept-encoding")) { - for (String encoding : headers.get("accept-encoding")) { - if (encoding.contains("gzip")) { - isGzip = true; - break; - } - } + private boolean isGzipRequest(Map headers) { + boolean isGzip = false; + if (headers.containsKey("accept-encoding")) { + for (String encoding : headers.get("accept-encoding")) { + if (encoding.contains("gzip")) { + isGzip = true; + break; } - return isGzip; - } - - private byte[] getBytes(RequestBody requestBody) throws Exception { - byte[] byteArray = requestBody.asRaw().asBytes(); - return byteArray; - + } } + return isGzip; + } + private byte[] getBytes(RequestBody requestBody) throws Exception { + byte[] byteArray = requestBody.asRaw().asBytes(); + return byteArray; + } } diff --git a/service/app/controllers/tenantpreference/TenantPreferenceController.java b/service/app/controllers/tenantpreference/TenantPreferenceController.java index 512662fcbd..1a3311a2fc 100644 --- a/service/app/controllers/tenantpreference/TenantPreferenceController.java +++ b/service/app/controllers/tenantpreference/TenantPreferenceController.java @@ -1,23 +1,18 @@ package controllers.tenantpreference; +import com.fasterxml.jackson.databind.JsonNode; +import controllers.BaseController; import java.util.Map; - 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.ExecutionContext; import org.sunbird.common.request.Request; - -import com.fasterxml.jackson.databind.JsonNode; - -import controllers.BaseController; import play.libs.F.Promise; import play.mvc.Result; -/** - * Created by arvind on 27/10/17. - */ +/** Created by arvind on 27/10/17. */ public class TenantPreferenceController extends BaseController { public Promise createTenantPreference() { @@ -87,5 +82,4 @@ public Promise updateTCStatusOfUser() { return Promise.pure(createCommonExceptionResponse(e, request())); } } - } diff --git a/service/app/controllers/usermanagement/UserController.java b/service/app/controllers/usermanagement/UserController.java index d6aa40ad72..f07b7dd27e 100644 --- a/service/app/controllers/usermanagement/UserController.java +++ b/service/app/controllers/usermanagement/UserController.java @@ -1,16 +1,15 @@ -/** - * - */ +/** */ package controllers.usermanagement; import static org.sunbird.learner.util.Util.isNotNull; import static org.sunbird.learner.util.Util.isNull; +import com.fasterxml.jackson.databind.JsonNode; +import controllers.BaseController; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; - import org.apache.commons.lang3.StringUtils; import org.sunbird.common.exception.ProjectCommonException; import org.sunbird.common.models.util.ActorOperations; @@ -24,10 +23,6 @@ import org.sunbird.common.request.Request; import org.sunbird.common.request.UserRequestValidator; import org.sunbird.common.responsecode.ResponseCode; - -import com.fasterxml.jackson.databind.JsonNode; - -import controllers.BaseController; import play.libs.F.Promise; import play.mvc.Result; import util.AuthenticationHelper; @@ -48,8 +43,8 @@ public class UserController extends BaseController { public Promise createUser() { try { JsonNode requestData = request().body().asJson(); - ProjectLogger.log(" get user registration request data = " + requestData, - LoggerEnum.INFO.name()); + ProjectLogger.log( + " get user registration request data = " + requestData, LoggerEnum.INFO.name()); Request reqObj = (Request) mapper.RequestMapper.mapRequest(requestData, Request.class); UserRequestValidator.validateCreateUser(reqObj); @@ -78,14 +73,13 @@ public Promise createUser() { */ public Promise updateUserProfile() { - try { + try { JsonNode requestData = request().body().asJson(); ProjectLogger.log(" get user update profile data = " + requestData, LoggerEnum.INFO.name()); Request reqObj = (Request) mapper.RequestMapper.mapRequest(requestData, Request.class); if (null != ctx().flash().get(JsonKey.IS_AUTH_REQ) && Boolean.parseBoolean(ctx().flash().get(JsonKey.IS_AUTH_REQ))) { validateAuthenticity(reqObj); - } UserRequestValidator.validateUpdateUser(reqObj); reqObj.setOperation(ActorOperations.UPDATE_USER.getValue()); @@ -114,16 +108,15 @@ private void validateAuthenticity(Request reqObj) { } else { validateWithUserId(reqObj); } - } private void validateWithClient(Request reqObj) { String clientId = ctx().flash().get(JsonKey.USER_ID); - String userId ; + String userId; if (null != reqObj.getRequest().get(JsonKey.USER_ID)) { - userId = (String)reqObj.getRequest().get(JsonKey.USER_ID); + userId = (String) reqObj.getRequest().get(JsonKey.USER_ID); } else { - userId = (String)reqObj.getRequest().get(JsonKey.ID); + userId = (String) reqObj.getRequest().get(JsonKey.ID); } Map clientDetail = AuthenticationHelper.getClientAccessTokenDetail(clientId); @@ -131,14 +124,16 @@ private void validateWithClient(Request reqObj) { Map userDetail = AuthenticationHelper.getUserDetail(userId); // check whether both exist or not ... if (clientDetail == null || userDetail == null) { - throw new ProjectCommonException(ResponseCode.unAuthorised.getErrorCode(), + throw new ProjectCommonException( + ResponseCode.unAuthorised.getErrorCode(), ResponseCode.unAuthorised.getErrorMessage(), ResponseCode.UNAUTHORIZED.getResponseCode()); } String userRootOrgId = (String) userDetail.get(JsonKey.ROOT_ORG_ID); if (StringUtils.isBlank(userRootOrgId)) { - throw new ProjectCommonException(ResponseCode.unAuthorised.getErrorCode(), + throw new ProjectCommonException( + ResponseCode.unAuthorised.getErrorCode(), ResponseCode.unAuthorised.getErrorMessage(), ResponseCode.UNAUTHORIZED.getResponseCode()); } @@ -146,12 +141,13 @@ private void validateWithClient(Request reqObj) { Map orgDetail = AuthenticationHelper.getOrgDetail(userRootOrgId); String userChannel = (String) orgDetail.get(JsonKey.CHANNEL); String clientChannel = (String) clientDetail.get(JsonKey.CHANNEL); - ProjectLogger.log("User channel : "+userChannel); - ProjectLogger.log("Client channel : "+clientChannel); + ProjectLogger.log("User channel : " + userChannel); + ProjectLogger.log("Client channel : " + clientChannel); // check whether both belongs to the same channel or not ... if (!compareStrings(userChannel, clientChannel)) { - throw new ProjectCommonException(ResponseCode.unAuthorised.getErrorCode(), + throw new ProjectCommonException( + ResponseCode.unAuthorised.getErrorCode(), ResponseCode.unAuthorised.getErrorMessage(), ResponseCode.UNAUTHORIZED.getResponseCode()); } @@ -159,15 +155,14 @@ private void validateWithClient(Request reqObj) { private void validateWithUserId(Request reqObj) { String userId = (String) reqObj.getRequest().get(JsonKey.USER_ID); - if ((!StringUtils.isBlank(userId)) - && (!userId.equals(ctx().flash().get(JsonKey.USER_ID)))) { - throw new ProjectCommonException(ResponseCode.unAuthorised.getErrorCode(), + if ((!StringUtils.isBlank(userId)) && (!userId.equals(ctx().flash().get(JsonKey.USER_ID)))) { + throw new ProjectCommonException( + ResponseCode.unAuthorised.getErrorCode(), ResponseCode.unAuthorised.getErrorMessage(), ResponseCode.UNAUTHORIZED.getResponseCode()); } } - /** * This method will do the user authentication based on login type key. login can be done with * following ways (simple login , Google plus login , Facebook login , Aadhaar login) @@ -210,8 +205,7 @@ public Promise logout() { HashMap innerMap = new HashMap<>(); innerMap.put(JsonKey.USER, reqObj.getRequest()); innerMap.put(JsonKey.REQUESTED_BY, ctx().flash().get(JsonKey.USER_ID)); - innerMap.put(JsonKey.AUTH_TOKEN, - request().getHeader(HeaderParam.X_Access_TokenId.getName())); + innerMap.put(JsonKey.AUTH_TOKEN, request().getHeader(HeaderParam.X_Access_TokenId.getName())); reqObj.setRequest(innerMap); return actorResponseHandler(getActorRef(), reqObj, timeout, null, request()); } catch (Exception e) { @@ -291,7 +285,6 @@ public Promise getRoles() { } } - /** * Method to verify user existence in our DB. * @@ -301,8 +294,8 @@ public Promise getUserDetailsByLoginId() { try { JsonNode requestData = request().body().asJson(); - ProjectLogger.log(" verify user details by loginId data =" + requestData, - LoggerEnum.INFO.name()); + ProjectLogger.log( + " verify user details by loginId data =" + requestData, LoggerEnum.INFO.name()); Request reqObj = (Request) mapper.RequestMapper.mapRequest(requestData, Request.class); UserRequestValidator.validateVerifyUser(reqObj); reqObj.setOperation(ActorOperations.GET_USER_DETAILS_BY_LOGINID.getValue()); @@ -343,7 +336,6 @@ public Promise downloadUsers() { } } - /** * This method will provide user profile details based on requested userId. * @@ -370,7 +362,7 @@ public Promise blockUser() { /** * This method will assign either user role directly or user org role. - * + * * @return Promise */ public Promise assignRoles() { @@ -450,7 +442,7 @@ public Promise search() { /** * This method will update user current login time to keyCloack. - * + * * @return promise */ public Promise updateLoginTime() { @@ -474,33 +466,33 @@ public Promise updateLoginTime() { } } - /** * Get all the social media types supported - * + * * @return */ public Promise getMediaTypes() { - try { - ProjectLogger.log(" get media Types ", LoggerEnum.INFO.name()); - Request reqObj = new Request(); - reqObj.setOperation(ActorOperations.GET_MEDIA_TYPES.getValue()); - reqObj.setRequestId(ExecutionContext.getRequestId()); - reqObj.setEnv(getEnvironment()); - HashMap innerMap = new HashMap<>(); - innerMap.put(JsonKey.REQUESTED_BY, - getUserIdByAuthToken(request().getHeader(HeaderParam.X_Authenticated_Userid.getName()))); - reqObj.setRequest(innerMap); - return actorResponseHandler(getActorRef(), reqObj, timeout, null, request()); - } catch (Exception e) { - return Promise.pure(createCommonExceptionResponse(e, request())); - } - } - + try { + ProjectLogger.log(" get media Types ", LoggerEnum.INFO.name()); + Request reqObj = new Request(); + reqObj.setOperation(ActorOperations.GET_MEDIA_TYPES.getValue()); + reqObj.setRequestId(ExecutionContext.getRequestId()); + reqObj.setEnv(getEnvironment()); + HashMap innerMap = new HashMap<>(); + innerMap.put( + JsonKey.REQUESTED_BY, + getUserIdByAuthToken(request().getHeader(HeaderParam.X_Authenticated_Userid.getName()))); + reqObj.setRequest(innerMap); + return actorResponseHandler(getActorRef(), reqObj, timeout, null, request()); + } catch (Exception e) { + return Promise.pure(createCommonExceptionResponse(e, request())); + } + } + /** - * This method will send user temporary password on his/her - * registered email.in Request it will take either user loginid - * or email. + * This method will send user temporary password on his/her registered email.in Request it will + * take either user loginid or email. + * * @return Promise */ public Promise forgotpassword() { @@ -514,34 +506,36 @@ public Promise forgotpassword() { reqObj.setEnv(getEnvironment()); HashMap innerMap = new HashMap<>(); innerMap.put(JsonKey.USER, reqObj.getRequest()); - reqObj.getRequest().put(JsonKey.USER_ID,ctx().flash().get(JsonKey.USER_ID)); - innerMap.put(JsonKey.REQUESTED_BY,ctx().flash().get(JsonKey.USER_ID)); + reqObj.getRequest().put(JsonKey.USER_ID, ctx().flash().get(JsonKey.USER_ID)); + innerMap.put(JsonKey.REQUESTED_BY, ctx().flash().get(JsonKey.USER_ID)); reqObj.setRequest(innerMap); return actorResponseHandler(getActorRef(), reqObj, timeout, null, request()); } catch (Exception e) { return Promise.pure(createCommonExceptionResponse(e, request())); } } - + /** - * This method will add or update user profile visibility - * control. User can make all field as private except name. - * any private filed of user is not search-able. + * This method will add or update user profile visibility control. User can make all field as + * private except name. any private filed of user is not search-able. + * * @return Promise */ public Promise profileVisibility() { try { JsonNode requestData = request().body().asJson(); - ProjectLogger.log(" Profile visibility control request= " + requestData, LoggerEnum.INFO.name()); + ProjectLogger.log( + " Profile visibility control request= " + requestData, LoggerEnum.INFO.name()); Request reqObj = (Request) mapper.RequestMapper.mapRequest(requestData, Request.class); UserRequestValidator.validateProfileVisibility(reqObj); if (null != ctx().flash().get(JsonKey.IS_AUTH_REQ) && Boolean.parseBoolean(ctx().flash().get(JsonKey.IS_AUTH_REQ))) { - String userId = (String) reqObj.getRequest().get(JsonKey.USER_ID); - if (!userId.equals(ctx().flash().get(JsonKey.USER_ID))) { - throw new ProjectCommonException(ResponseCode.unAuthorised.getErrorCode(), - ResponseCode.unAuthorised.getErrorMessage(), - ResponseCode.UNAUTHORIZED.getResponseCode()); + String userId = (String) reqObj.getRequest().get(JsonKey.USER_ID); + if (!userId.equals(ctx().flash().get(JsonKey.USER_ID))) { + throw new ProjectCommonException( + ResponseCode.unAuthorised.getErrorCode(), + ResponseCode.unAuthorised.getErrorMessage(), + ResponseCode.UNAUTHORIZED.getResponseCode()); } } reqObj.setOperation(ActorOperations.PROFILE_VISIBILITY.getValue()); @@ -549,7 +543,7 @@ public Promise profileVisibility() { reqObj.setEnv(getEnvironment()); HashMap innerMap = new HashMap<>(); innerMap.put(JsonKey.USER, reqObj.getRequest()); - innerMap.put(JsonKey.REQUESTED_BY,ctx().flash().get(JsonKey.USER_ID)); + innerMap.put(JsonKey.REQUESTED_BY, ctx().flash().get(JsonKey.USER_ID)); reqObj.setRequest(innerMap); return actorResponseHandler(getActorRef(), reqObj, timeout, null, request()); } catch (Exception e) { @@ -567,5 +561,4 @@ private boolean compareStrings(String first, String second) { } return first.equalsIgnoreCase(second); } - } diff --git a/service/app/mapper/RequestMapper.java b/service/app/mapper/RequestMapper.java index de1bf31014..184ee107a3 100644 --- a/service/app/mapper/RequestMapper.java +++ b/service/app/mapper/RequestMapper.java @@ -1,28 +1,23 @@ -/** - * - */ +/** */ package mapper; +import com.fasterxml.jackson.databind.JsonNode; import org.sunbird.common.exception.ProjectCommonException; import org.sunbird.common.models.util.LoggerEnum; import org.sunbird.common.models.util.ProjectLogger; import org.sunbird.common.responsecode.ResponseCode; - -import com.fasterxml.jackson.databind.JsonNode; - import play.libs.Json; /** * This class will map the requested json data into custom class. - * - * @author Manzarul * + * @author Manzarul */ public class RequestMapper { /** * Method to map request - * + * * @param requestData JsonNode * @param obj Class * @exception RuntimeException @@ -34,12 +29,11 @@ public static Object mapRequest(JsonNode requestData, Class obj) throws R return Json.fromJson(requestData, obj); } catch (Exception e) { ProjectLogger.log("ControllerRequestMapper error : " + e.getMessage(), e); - ProjectLogger.log("Request Data" + requestData.toString(), - LoggerEnum.INFO.name()); - throw new ProjectCommonException(ResponseCode.invalidData.getErrorCode(), + ProjectLogger.log("Request Data" + requestData.toString(), LoggerEnum.INFO.name()); + throw new ProjectCommonException( + ResponseCode.invalidData.getErrorCode(), ResponseCode.invalidData.getErrorMessage(), ResponseCode.CLIENT_ERROR.getResponseCode()); } } - } diff --git a/service/app/util/AuthenticationHelper.java b/service/app/util/AuthenticationHelper.java index d7605e473f..2796b310c4 100644 --- a/service/app/util/AuthenticationHelper.java +++ b/service/app/util/AuthenticationHelper.java @@ -1,12 +1,9 @@ -/** - * - */ +/** */ package util; import java.util.HashMap; import java.util.List; import java.util.Map; - import org.sunbird.cassandra.CassandraOperation; import org.sunbird.common.models.response.Response; import org.sunbird.common.models.util.JsonKey; @@ -19,140 +16,153 @@ import org.sunbird.services.sso.SSOManager; import org.sunbird.services.sso.SSOServiceFactory; - /** - * * This class will handle all the method related to authentication. For example verifying user * access token, creating access token after success login. - * - * @author Manzarul * + * @author Manzarul */ public class AuthenticationHelper { - static{ - Application.checkCassandraConnection(); + static { + Application.checkCassandraConnection(); } + private static CassandraOperation cassandraOperation = ServiceFactory.getInstance(); private static DbInfo userAuth = Util.dbInfoMap.get(JsonKey.USER_AUTH_DB); /** * This method will verify the incoming user access token against store data base /cache. If token * is valid then it would be associated with some user id. In case of token matched it will * provide user id. else will provide empty string. + * * @param token String * @return String */ @SuppressWarnings("unchecked") public static String verifyUserAccesToken(String token) { SSOManager ssoManager = SSOServiceFactory.getInstance(); - String userId = ""; - try { - boolean response = Boolean.parseBoolean(PropertiesCache.getInstance().getProperty(JsonKey.IS_SSO_ENABLED)); + String userId = ""; + try { + boolean response = + Boolean.parseBoolean(PropertiesCache.getInstance().getProperty(JsonKey.IS_SSO_ENABLED)); if (response) { - userId = ssoManager.verifyToken(token); + userId = ssoManager.verifyToken(token); } else { - Response authResponse = cassandraOperation.getRecordById(userAuth.getKeySpace(), userAuth.getTableName(), token); - if(authResponse != null && authResponse.get(JsonKey.RESPONSE) != null) { - List> authList = - (List>) authResponse.get(JsonKey.RESPONSE); + Response authResponse = + cassandraOperation.getRecordById( + userAuth.getKeySpace(), userAuth.getTableName(), token); + if (authResponse != null && authResponse.get(JsonKey.RESPONSE) != null) { + List> authList = + (List>) authResponse.get(JsonKey.RESPONSE); if (authList != null && !authList.isEmpty()) { - Map authMap = authList.get(0); - userId = (String) authMap.get(JsonKey.USER_ID); + Map authMap = authList.get(0); + userId = (String) authMap.get(JsonKey.USER_ID); } - } + } } } catch (Exception e) { ProjectLogger.log("invalid auth token =" + token, e); } return userId; } - - + @SuppressWarnings("unchecked") - public static String verifyClientAccessToken(String clientId, String clientToken){ + public static String verifyClientAccessToken(String clientId, String clientToken) { Util.DbInfo clientDbInfo = Util.dbInfoMap.get(JsonKey.CLIENT_INFO_DB); Map propertyMap = new HashMap<>(); propertyMap.put(JsonKey.ID, clientId); propertyMap.put(JsonKey.MASTER_KEY, clientToken); String validClientId = ""; try { - Response clientResponse = cassandraOperation.getRecordsByProperties(clientDbInfo.getKeySpace(), clientDbInfo.getTableName(), propertyMap); - if(null != clientResponse && !clientResponse.getResult().isEmpty()){ - List> dataList = (List>) clientResponse.getResult().get(JsonKey.RESPONSE); + Response clientResponse = + cassandraOperation.getRecordsByProperties( + clientDbInfo.getKeySpace(), clientDbInfo.getTableName(), propertyMap); + if (null != clientResponse && !clientResponse.getResult().isEmpty()) { + List> dataList = + (List>) clientResponse.getResult().get(JsonKey.RESPONSE); validClientId = (String) dataList.get(0).get(JsonKey.ID); - } - }catch (Exception e) { + } + } catch (Exception e) { ProjectLogger.log("Validating client token failed due to : ", e); } return validClientId; } - public static Map getClientAccessTokenDetail(String clientId){ + public static Map getClientAccessTokenDetail(String clientId) { Util.DbInfo clientDbInfo = Util.dbInfoMap.get(JsonKey.CLIENT_INFO_DB); - Map response = null; + Map response = null; Map propertyMap = new HashMap<>(); propertyMap.put(JsonKey.ID, clientId); try { - Response clientResponse = cassandraOperation.getRecordById(clientDbInfo.getKeySpace(), clientDbInfo.getTableName(), clientId); - if(null != clientResponse && !clientResponse.getResult().isEmpty()){ - List> dataList = (List>) clientResponse.getResult().get(JsonKey.RESPONSE); + Response clientResponse = + cassandraOperation.getRecordById( + clientDbInfo.getKeySpace(), clientDbInfo.getTableName(), clientId); + if (null != clientResponse && !clientResponse.getResult().isEmpty()) { + List> dataList = + (List>) clientResponse.getResult().get(JsonKey.RESPONSE); response = dataList.get(0); } - }catch (Exception e) { + } catch (Exception e) { ProjectLogger.log("Validating client token failed due to : ", e); } return response; } - public static Map getUserDetail(String userId){ + public static Map getUserDetail(String userId) { Util.DbInfo userDbInfo = Util.dbInfoMap.get(JsonKey.USER_DB); - Map response = null; + Map response = null; try { - Response userResponse = cassandraOperation.getRecordById(userDbInfo.getKeySpace(), userDbInfo.getTableName(), userId); - if(null != userResponse && !userResponse.getResult().isEmpty()){ - List> dataList = (List>) userResponse.getResult().get(JsonKey.RESPONSE); + Response userResponse = + cassandraOperation.getRecordById( + userDbInfo.getKeySpace(), userDbInfo.getTableName(), userId); + if (null != userResponse && !userResponse.getResult().isEmpty()) { + List> dataList = + (List>) userResponse.getResult().get(JsonKey.RESPONSE); response = dataList.get(0); } - }catch (Exception e) { - ProjectLogger.log("fetching user for id "+ userId+" failed due to : ", e); + } catch (Exception e) { + ProjectLogger.log("fetching user for id " + userId + " failed due to : ", e); } return response; } - public static Map getOrgDetail(String orgId){ + public static Map getOrgDetail(String orgId) { Util.DbInfo userDbInfo = Util.dbInfoMap.get(JsonKey.ORG_DB); - Map response = null; + Map response = null; try { - Response userResponse = cassandraOperation.getRecordById(userDbInfo.getKeySpace(), userDbInfo.getTableName(), orgId); - if(null != userResponse && !userResponse.getResult().isEmpty()){ - List> dataList = (List>) userResponse.getResult().get(JsonKey.RESPONSE); + Response userResponse = + cassandraOperation.getRecordById( + userDbInfo.getKeySpace(), userDbInfo.getTableName(), orgId); + if (null != userResponse && !userResponse.getResult().isEmpty()) { + List> dataList = + (List>) userResponse.getResult().get(JsonKey.RESPONSE); response = dataList.get(0); } - }catch (Exception e) { - ProjectLogger.log("fetching user for id "+ orgId+" failed due to : ", e); + } catch (Exception e) { + ProjectLogger.log("fetching user for id " + orgId + " failed due to : ", e); } return response; } /** * This method will save the user access token in side data base. - * + * * @param token String * @param userId String * @return boolean */ public static boolean saveUserAccessToken(String token, String userId) { - + return false; } /** * This method will invalidate the user access token. - * + * * @param token String * @return boolean */ public static boolean invalidateToken(String token) { - + return false; } } diff --git a/service/app/util/Global.java b/service/app/util/Global.java index dfb11908ab..edb51e8445 100644 --- a/service/app/util/Global.java +++ b/service/app/util/Global.java @@ -1,14 +1,11 @@ - -/** - * - */ +/** */ package util; +import controllers.BaseController; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; import java.util.UUID; - import org.apache.commons.lang3.StringUtils; import org.sunbird.actor.service.SunbirdMWService; import org.sunbird.common.exception.ProjectCommonException; @@ -23,9 +20,6 @@ import org.sunbird.common.request.HeaderParam; import org.sunbird.common.responsecode.ResponseCode; import org.sunbird.telemetry.util.TelemetryUtil; - - -import controllers.BaseController; import play.Application; import play.GlobalSettings; import play.libs.F.Promise; @@ -39,278 +33,283 @@ /** * This class will work as a filter. - * - * @author Manzarul * + * @author Manzarul */ public class Global extends GlobalSettings { - public static ProjectUtil.Environment env; - - public static Map> requestInfo = new HashMap<>(); + public static ProjectUtil.Environment env; - public static String ssoPublicKey = ""; - private static final String version = "v1"; + public static Map> requestInfo = new HashMap<>(); - private class ActionWrapper extends Action.Simple { - public ActionWrapper(Action action) { - this.delegate = action; - } + public static String ssoPublicKey = ""; + private static final String version = "v1"; - @Override - public Promise call(Http.Context ctx) throws java.lang.Throwable { - ctx.request().headers(); - long startTime = System.currentTimeMillis(); - Promise result = null; - Http.Response response = ctx.response(); - response.setHeader("Access-Control-Allow-Origin", "*"); - String message = RequestInterceptor.verifyRequestData(ctx); - // call method to set all the required params for the telemetry event(log)... - intializeRequestInfo(ctx, message.replace("{userId}", "")); - if (message.contains("{userId}")) { - ctx.flash().put(JsonKey.USER_ID, message.replace("{userId}", "")); - ctx.flash().put(JsonKey.IS_AUTH_REQ, "false"); - for (String uri : RequestInterceptor.restrictedUriList) { - if (ctx.request().path().contains(uri)) { - ctx.flash().put(JsonKey.IS_AUTH_REQ, "true"); - break; - } - } - result = delegate.call(ctx); - } else if (!StringUtils.isBlank(message)) { - result = onDataValidationError(ctx.request(), message, ResponseCode.UNAUTHORIZED.getResponseCode()); - } else { - result = delegate.call(ctx); - } -// ProjectLogger.log("Learning Service Call Ended for api ==" + ctx.request().path() + " Time taken " -// + (System.currentTimeMillis() - startTime), LoggerEnum.PERF_LOG); - return result; - } - } + private class ActionWrapper extends Action.Simple { + public ActionWrapper(Action action) { + this.delegate = action; + } - /** - * - * @author Manzarul - * - */ - public enum RequestMethod { - GET, POST, PUT, DELETE, PATCH; - } + @Override + public Promise call(Http.Context ctx) throws java.lang.Throwable { + ctx.request().headers(); + long startTime = System.currentTimeMillis(); + Promise result = null; + Http.Response response = ctx.response(); + response.setHeader("Access-Control-Allow-Origin", "*"); + String message = RequestInterceptor.verifyRequestData(ctx); + // call method to set all the required params for the telemetry event(log)... + intializeRequestInfo(ctx, message.replace("{userId}", "")); + if (message.contains("{userId}")) { + ctx.flash().put(JsonKey.USER_ID, message.replace("{userId}", "")); + ctx.flash().put(JsonKey.IS_AUTH_REQ, "false"); + for (String uri : RequestInterceptor.restrictedUriList) { + if (ctx.request().path().contains(uri)) { + ctx.flash().put(JsonKey.IS_AUTH_REQ, "true"); + break; + } + } + result = delegate.call(ctx); + } else if (!StringUtils.isBlank(message)) { + result = + onDataValidationError( + ctx.request(), message, ResponseCode.UNAUTHORIZED.getResponseCode()); + } else { + result = delegate.call(ctx); + } + // ProjectLogger.log("Learning Service Call Ended for api ==" + ctx.request().path() + " + // Time taken " + // + (System.currentTimeMillis() - startTime), LoggerEnum.PERF_LOG); + return result; + } + } - /** - * This method will be called on application start up. it will be called only - * time in it's life cycle. - * - * @param app - * Application - */ - public void onStart(Application app) { - setEnvironment(); - ssoPublicKey = System.getenv(JsonKey.SSO_PUBLIC_KEY); - ProjectLogger.log("Server started.. with environment: " + env.name(), LoggerEnum.INFO.name()); - SunbirdMWService.init(); - } + /** @author Manzarul */ + public enum RequestMethod { + GET, + POST, + PUT, + DELETE, + PATCH; + } - /** - * This method will be called on each request. - * - * @param request - * Request - * @param actionMethod - * Method - * @return Action - */ - @SuppressWarnings("rawtypes") - public Action onRequest(Request request, Method actionMethod) { + /** + * This method will be called on application start up. it will be called only time in it's life + * cycle. + * + * @param app Application + */ + public void onStart(Application app) { + setEnvironment(); + ssoPublicKey = System.getenv(JsonKey.SSO_PUBLIC_KEY); + ProjectLogger.log("Server started.. with environment: " + env.name(), LoggerEnum.INFO.name()); + SunbirdMWService.init(); + } - String messageId = request.getHeader(JsonKey.MESSAGE_ID); - if (StringUtils.isBlank(messageId)) { - UUID uuid = UUID.randomUUID(); - messageId = uuid.toString(); - } - ExecutionContext.setRequestId(messageId); - return new ActionWrapper(super.onRequest(request, actionMethod)); - } + /** + * This method will be called on each request. + * + * @param request Request + * @param actionMethod Method + * @return Action + */ + @SuppressWarnings("rawtypes") + public Action onRequest(Request request, Method actionMethod) { - private void intializeRequestInfo(Context ctx, String userId) { - // TODO: need to re-factor entire code. - if (StringUtils.isBlank(userId)) { - userId = "anonymous"; - } - Request request = ctx.request(); - String actionMethod = ctx.request().method(); - String messageId = ExecutionContext.getRequestId();// request.getHeader(JsonKey.MESSAGE_ID); - String url = request.uri(); - String methodName = actionMethod; - long startTime = System.currentTimeMillis(); + String messageId = request.getHeader(JsonKey.MESSAGE_ID); + if (StringUtils.isBlank(messageId)) { + UUID uuid = UUID.randomUUID(); + messageId = uuid.toString(); + } + ExecutionContext.setRequestId(messageId); + return new ActionWrapper(super.onRequest(request, actionMethod)); + } - ExecutionContext context = ExecutionContext.getCurrent(); - Map reqContext = new HashMap<>(); - // set env and channel to the - String channel = request.getHeader(JsonKey.CHANNEL_ID); - if (StringUtils.isBlank(channel)) { - channel = JsonKey.DEFAULT_ROOT_ORG_ID; - } - reqContext.put(JsonKey.CHANNEL, channel); - ctx.flash().put(JsonKey.CHANNEL, channel); - reqContext.put(JsonKey.ENV, getEnv(request)); // context done we can pass it directly to the LMAX Disruptor ... - reqContext.put(JsonKey.REQUEST_ID, ExecutionContext.getRequestId()); + private void intializeRequestInfo(Context ctx, String userId) { + // TODO: need to re-factor entire code. + if (StringUtils.isBlank(userId)) { + userId = "anonymous"; + } + Request request = ctx.request(); + String actionMethod = ctx.request().method(); + String messageId = ExecutionContext.getRequestId(); // request.getHeader(JsonKey.MESSAGE_ID); + String url = request.uri(); + String methodName = actionMethod; + long startTime = System.currentTimeMillis(); - String userToken = request.getHeader(HeaderParam.X_Access_TokenId.getName()); - if (null != userToken) { - reqContext.put(JsonKey.ACTOR_ID, userId); - reqContext.put(JsonKey.ACTOR_TYPE, JsonKey.USER); - ctx.flash().put(JsonKey.ACTOR_ID, userId); - ctx.flash().put(JsonKey.ACTOR_TYPE, JsonKey.USER); + ExecutionContext context = ExecutionContext.getCurrent(); + Map reqContext = new HashMap<>(); + // set env and channel to the + String channel = request.getHeader(JsonKey.CHANNEL_ID); + if (StringUtils.isBlank(channel)) { + channel = JsonKey.DEFAULT_ROOT_ORG_ID; + } + reqContext.put(JsonKey.CHANNEL, channel); + ctx.flash().put(JsonKey.CHANNEL, channel); + reqContext.put( + JsonKey.ENV, + getEnv(request)); // context done we can pass it directly to the LMAX Disruptor ... + reqContext.put(JsonKey.REQUEST_ID, ExecutionContext.getRequestId()); - } else { - // write logic to check consumer id and set trype as consumer ... - String consumerId = request.getHeader(HeaderParam.X_Consumer_ID.getName()); - if (StringUtils.isBlank(consumerId)) { - consumerId = JsonKey.DEFAULT_CONSUMER_ID; - } - reqContext.put(JsonKey.ACTOR_ID, consumerId); - reqContext.put(JsonKey.ACTOR_TYPE, JsonKey.CONSUMER); - ctx.flash().put(JsonKey.ACTOR_ID, consumerId); - ctx.flash().put(JsonKey.ACTOR_TYPE, JsonKey.CONSUMER); + String userToken = request.getHeader(HeaderParam.X_Access_TokenId.getName()); + if (null != userToken) { + reqContext.put(JsonKey.ACTOR_ID, userId); + reqContext.put(JsonKey.ACTOR_TYPE, JsonKey.USER); + ctx.flash().put(JsonKey.ACTOR_ID, userId); + ctx.flash().put(JsonKey.ACTOR_TYPE, JsonKey.USER); - } + } else { + // write logic to check consumer id and set trype as consumer ... + String consumerId = request.getHeader(HeaderParam.X_Consumer_ID.getName()); + if (StringUtils.isBlank(consumerId)) { + consumerId = JsonKey.DEFAULT_CONSUMER_ID; + } + reqContext.put(JsonKey.ACTOR_ID, consumerId); + reqContext.put(JsonKey.ACTOR_TYPE, JsonKey.CONSUMER); + ctx.flash().put(JsonKey.ACTOR_ID, consumerId); + ctx.flash().put(JsonKey.ACTOR_TYPE, JsonKey.CONSUMER); + } - context.setRequestContext(reqContext); - Map map = new HashMap<>(); - map.put(JsonKey.CONTEXT, TelemetryUtil.getTelemetryContext()); - Map additionalInfo = new HashMap<>(); - additionalInfo.put(JsonKey.URL, url); - additionalInfo.put(JsonKey.METHOD, methodName); - additionalInfo.put(JsonKey.START_TIME, startTime); + context.setRequestContext(reqContext); + Map map = new HashMap<>(); + map.put(JsonKey.CONTEXT, TelemetryUtil.getTelemetryContext()); + Map additionalInfo = new HashMap<>(); + additionalInfo.put(JsonKey.URL, url); + additionalInfo.put(JsonKey.METHOD, methodName); + additionalInfo.put(JsonKey.START_TIME, startTime); - // additional info contains info other than context info ... - map.put(JsonKey.ADDITIONAL_INFO, additionalInfo); - if (StringUtils.isBlank(messageId)) { - messageId = JsonKey.DEFAULT_CONSUMER_ID; - } - ctx.flash().put(JsonKey.REQUEST_ID, messageId); - requestInfo.put(messageId, map); - } + // additional info contains info other than context info ... + map.put(JsonKey.ADDITIONAL_INFO, additionalInfo); + if (StringUtils.isBlank(messageId)) { + messageId = JsonKey.DEFAULT_CONSUMER_ID; + } + ctx.flash().put(JsonKey.REQUEST_ID, messageId); + requestInfo.put(messageId, map); + } - private String getEnv(Request request) { + private String getEnv(Request request) { - String uri = request.uri(); - String env; - if (uri.startsWith("/v1/user")) { - env = JsonKey.USER; - } else if (uri.startsWith("/v1/org")) { - env = JsonKey.ORGANISATION; - } else if (uri.startsWith("/v1/object")) { - env = JsonKey.ANNOUNCEMENT; - } else if (uri.startsWith("/v1/page")) { - env = JsonKey.PAGE; - } else if (uri.startsWith("/v1/course/batch")) { - env = JsonKey.BATCH; - } else if (uri.startsWith("/v1/notification")) { - env = JsonKey.NOTIFICATION; - } else if (uri.startsWith("/v1/dashboard")) { - env = JsonKey.DASHBOARD; - } else if (uri.startsWith("/v1/badges")) { - env = JsonKey.BADGES; - } else if (uri.startsWith("/v1/issuer")) { - env = BadgingJsonKey.BADGES; - } else { - env = "miscellaneous"; - } - return env; - } + String uri = request.uri(); + String env; + if (uri.startsWith("/v1/user")) { + env = JsonKey.USER; + } else if (uri.startsWith("/v1/org")) { + env = JsonKey.ORGANISATION; + } else if (uri.startsWith("/v1/object")) { + env = JsonKey.ANNOUNCEMENT; + } else if (uri.startsWith("/v1/page")) { + env = JsonKey.PAGE; + } else if (uri.startsWith("/v1/course/batch")) { + env = JsonKey.BATCH; + } else if (uri.startsWith("/v1/notification")) { + env = JsonKey.NOTIFICATION; + } else if (uri.startsWith("/v1/dashboard")) { + env = JsonKey.DASHBOARD; + } else if (uri.startsWith("/v1/badges")) { + env = JsonKey.BADGES; + } else if (uri.startsWith("/v1/issuer")) { + env = BadgingJsonKey.BADGES; + } else { + env = "miscellaneous"; + } + return env; + } - /** - * This method will do request data validation for GET method only. As a GET - * request user must send some key in header. - * - * @param request - * Request - * @param errorMessage - * String - * @return Promise - */ - public Promise onDataValidationError(Request request, String errorMessage, int responseCode) { - ProjectLogger.log("Data error found--" + errorMessage); - ResponseCode code = ResponseCode.getResponse(errorMessage); - ResponseCode headerCode = ResponseCode.CLIENT_ERROR; - Response resp = BaseController.createFailureResponse(request, code, headerCode); - return Promise.pure(Results.status(responseCode, Json.toJson(resp))); - } + /** + * This method will do request data validation for GET method only. As a GET request user must + * send some key in header. + * + * @param request Request + * @param errorMessage String + * @return Promise + */ + public Promise onDataValidationError( + Request request, String errorMessage, int responseCode) { + ProjectLogger.log("Data error found--" + errorMessage); + ResponseCode code = ResponseCode.getResponse(errorMessage); + ResponseCode headerCode = ResponseCode.CLIENT_ERROR; + Response resp = BaseController.createFailureResponse(request, code, headerCode); + return Promise.pure(Results.status(responseCode, Json.toJson(resp))); + } - /** - * This method will be used to send the request header missing error message. - * - * @param request - * Http.RequestHeader - * @param t - * Throwable - * @return Promise - */ - @Override - public Promise onError(Http.RequestHeader request, Throwable t) { + /** + * This method will be used to send the request header missing error message. + * + * @param request Http.RequestHeader + * @param t Throwable + * @return Promise + */ + @Override + public Promise onError(Http.RequestHeader request, Throwable t) { - Response response = null; - ProjectCommonException commonException = null; - if (t instanceof ProjectCommonException) { - commonException = (ProjectCommonException) t; - response = BaseController.createResponseOnException(request.path(), request.method(), - (ProjectCommonException) t); - } else if (t instanceof akka.pattern.AskTimeoutException) { - commonException = new ProjectCommonException(ResponseCode.actorConnectionError.getErrorCode(), - ResponseCode.actorConnectionError.getErrorMessage(), ResponseCode.SERVER_ERROR.getResponseCode()); - } else { - commonException = new ProjectCommonException(ResponseCode.internalError.getErrorCode(), - ResponseCode.internalError.getErrorMessage(), ResponseCode.SERVER_ERROR.getResponseCode()); - } - response = BaseController.createResponseOnException(request.path(), request.method(), commonException); - return Promise.pure(Results.internalServerError(Json.toJson(response))); - } + Response response = null; + ProjectCommonException commonException = null; + if (t instanceof ProjectCommonException) { + commonException = (ProjectCommonException) t; + response = + BaseController.createResponseOnException( + request.path(), request.method(), (ProjectCommonException) t); + } else if (t instanceof akka.pattern.AskTimeoutException) { + commonException = + new ProjectCommonException( + ResponseCode.actorConnectionError.getErrorCode(), + ResponseCode.actorConnectionError.getErrorMessage(), + ResponseCode.SERVER_ERROR.getResponseCode()); + } else { + commonException = + new ProjectCommonException( + ResponseCode.internalError.getErrorCode(), + ResponseCode.internalError.getErrorMessage(), + ResponseCode.SERVER_ERROR.getResponseCode()); + } + response = + BaseController.createResponseOnException(request.path(), request.method(), commonException); + return Promise.pure(Results.internalServerError(Json.toJson(response))); + } - /** - * This method will identify the environment and update with enum. - * - * @return Environment - */ - public Environment setEnvironment() { + /** + * This method will identify the environment and update with enum. + * + * @return Environment + */ + public Environment setEnvironment() { - if (play.Play.isDev()) { - return env = Environment.dev; - } else if (play.Play.isTest()) { - return env = Environment.qa; - } else { - return env = Environment.prod; - } - } + if (play.Play.isDev()) { + return env = Environment.dev; + } else if (play.Play.isTest()) { + return env = Environment.qa; + } else { + return env = Environment.prod; + } + } - /** - * Method to get the response id on basis of request path. - * - * @param requestPath - * @return - */ - public static String getResponseId(String requestPath) { + /** + * Method to get the response id on basis of request path. + * + * @param requestPath + * @return + */ + public static String getResponseId(String requestPath) { - String path = requestPath; - final String ver = "/" + version; - path = path.trim(); - StringBuilder builder = new StringBuilder(""); - if (path.startsWith(ver)) { - String requestUrl = (path.split("\\?"))[0]; - requestUrl = requestUrl.replaceFirst(ver, "api"); - String[] list = requestUrl.split("/"); - for (String str : list) { - if (str.matches("[A-Za-z]+")) { - builder.append(str).append("."); - } - } - builder.deleteCharAt(builder.length() - 1); - } else { - if ("/health".equalsIgnoreCase(path)) { - builder.append("api.all.health"); - } - } - return builder.toString(); - } + String path = requestPath; + final String ver = "/" + version; + path = path.trim(); + StringBuilder builder = new StringBuilder(""); + if (path.startsWith(ver)) { + String requestUrl = (path.split("\\?"))[0]; + requestUrl = requestUrl.replaceFirst(ver, "api"); + String[] list = requestUrl.split("/"); + for (String str : list) { + if (str.matches("[A-Za-z]+")) { + builder.append(str).append("."); + } + } + builder.deleteCharAt(builder.length() - 1); + } else { + if ("/health".equalsIgnoreCase(path)) { + builder.append("api.all.health"); + } + } + return builder.toString(); + } } diff --git a/service/app/util/RBACUtil.java b/service/app/util/RBACUtil.java index 91a8b19ec4..8ebe79925d 100644 --- a/service/app/util/RBACUtil.java +++ b/service/app/util/RBACUtil.java @@ -1,18 +1,16 @@ -/** - * - */ +/** */ package util; /** * This is role based access control class. This class will handle user role based access control. - * + * * @author Manzarul */ public class RBACUtil { /** * Based on incoming user id and API, this method will decide user has access to this API or not. - * + * * @param uid String * @param api String * @return boolean @@ -21,5 +19,4 @@ public boolean hasAccess(String uid, String api) { return true; } - } diff --git a/service/app/util/RequestInterceptor.java b/service/app/util/RequestInterceptor.java index 145ed72615..4257929b8a 100644 --- a/service/app/util/RequestInterceptor.java +++ b/service/app/util/RequestInterceptor.java @@ -3,7 +3,6 @@ import java.util.ArrayList; import java.util.List; import java.util.concurrent.ConcurrentHashMap; - import org.apache.commons.lang3.StringUtils; import org.sunbird.common.models.util.JsonKey; import org.sunbird.common.models.util.LoggerEnum; @@ -11,21 +10,21 @@ import org.sunbird.common.models.util.PropertiesCache; import org.sunbird.common.request.HeaderParam; import org.sunbird.common.responsecode.ResponseCode; - import play.mvc.Http; import play.mvc.Http.Request; /** * This class will do the request header validation - * - * @author Amit Kumar * + * @author Amit Kumar */ public class RequestInterceptor { protected static List restrictedUriList = null; private static ConcurrentHashMap apiHeaderIgnoreMap = new ConcurrentHashMap<>(); + private RequestInterceptor() {} + static { restrictedUriList = new ArrayList<>(); restrictedUriList.add("/v1/user/update"); @@ -35,8 +34,8 @@ private RequestInterceptor() {} restrictedUriList.add("/v1/note/read"); restrictedUriList.add("/v1/note/delete"); restrictedUriList.add("/v1/content/state/update"); - - //--------------------------- + + // --------------------------- short var = 1; apiHeaderIgnoreMap.put("/v1/user/create", var); apiHeaderIgnoreMap.put("/v1/org/search", var); @@ -58,7 +57,7 @@ private RequestInterceptor() {} apiHeaderIgnoreMap.put("/v1/object/delete", var); apiHeaderIgnoreMap.put("/v1/object/search", var); apiHeaderIgnoreMap.put("/v1/object/metrics", var); - apiHeaderIgnoreMap.put("/v1/client/register",var); + apiHeaderIgnoreMap.put("/v1/client/register", var); apiHeaderIgnoreMap.put("/v1/client/key/read", var); apiHeaderIgnoreMap.put("/v1/notification/send", var); apiHeaderIgnoreMap.put("/v1/user/getuser", var); @@ -66,69 +65,74 @@ private RequestInterceptor() {} apiHeaderIgnoreMap.put("/v1/org/preferences/read", var); apiHeaderIgnoreMap.put("/v1/org/preferences/create", var); apiHeaderIgnoreMap.put("/v1/org/preferences/update", var); - apiHeaderIgnoreMap.put("/v1/telemetry", var); - //making badging api's as public access - apiHeaderIgnoreMap.put("/v1/issuer/create", var); - apiHeaderIgnoreMap.put("/v1/issuer/read", var); - apiHeaderIgnoreMap.put("/v1/issuer/list", var); - apiHeaderIgnoreMap.put("/v1/issuer/delete", var); - apiHeaderIgnoreMap.put("/v1/issuer/badge/create", var); - apiHeaderIgnoreMap.put("/v1/issuer/badge/read", var); - apiHeaderIgnoreMap.put("/v1/issuer/badge/search", var); - apiHeaderIgnoreMap.put("/v1/issuer/badge/delete", var); - apiHeaderIgnoreMap.put("/v1/issuer/badge/assertion/create", var); - apiHeaderIgnoreMap.put("/v1/issuer/badge/assertion/read", var); - apiHeaderIgnoreMap.put("/v1/issuer/badge/assertion/search", var); - apiHeaderIgnoreMap.put("/v1/issuer/badge/assertion/delete", var); - //making org read as public access - apiHeaderIgnoreMap.put("/v1/org/read", var); + apiHeaderIgnoreMap.put("/v1/telemetry", var); + // making badging api's as public access + apiHeaderIgnoreMap.put("/v1/issuer/create", var); + apiHeaderIgnoreMap.put("/v1/issuer/read", var); + apiHeaderIgnoreMap.put("/v1/issuer/list", var); + apiHeaderIgnoreMap.put("/v1/issuer/delete", var); + apiHeaderIgnoreMap.put("/v1/issuer/badge/create", var); + apiHeaderIgnoreMap.put("/v1/issuer/badge/read", var); + apiHeaderIgnoreMap.put("/v1/issuer/badge/search", var); + apiHeaderIgnoreMap.put("/v1/issuer/badge/delete", var); + apiHeaderIgnoreMap.put("/v1/issuer/badge/assertion/create", var); + apiHeaderIgnoreMap.put("/v1/issuer/badge/assertion/read", var); + apiHeaderIgnoreMap.put("/v1/issuer/badge/assertion/search", var); + apiHeaderIgnoreMap.put("/v1/issuer/badge/assertion/delete", var); + // making org read as public access + apiHeaderIgnoreMap.put("/v1/org/read", var); } /** * This Method will do the request header validation. - * + * * @param request Request * @return String */ public static String verifyRequestData(Http.Context ctx) { - Request request = ctx.request(); - String response = "{userId}"; - if (!isRequestInExcludeList(request.path())) { - String accessToken = request.getHeader(HeaderParam.X_Access_TokenId.getName()); - String authClientToken = request.getHeader(HeaderParam.X_Authenticated_Client_Token.getName()); - String authClientId = request.getHeader(HeaderParam.X_Authenticated_Client_Id.getName()); - if (StringUtils.isBlank(accessToken) && StringUtils.isBlank(authClientToken) - && StringUtils.isBlank(authClientId)) { - return ResponseCode.unAuthorised.getErrorCode(); - } - if (StringUtils.isBlank(System.getenv(JsonKey.SSO_PUBLIC_KEY)) - && Boolean.parseBoolean(PropertiesCache.getInstance().getProperty(JsonKey.IS_SSO_ENABLED))) { - ProjectLogger.log("SSO public key is not set by environment variable==", LoggerEnum.INFO.name()); - response = "{userId}" + JsonKey.NOT_AVAILABLE; - } else if (!StringUtils.isBlank(authClientToken) && !StringUtils.isBlank(authClientId)) { - String clientId = AuthenticationHelper.verifyClientAccessToken(authClientId, authClientToken); - if (StringUtils.isBlank(clientId)) { - return ResponseCode.unAuthorised.getErrorCode(); - } - response = "{userId}" + clientId; - ctx.flash().put(JsonKey.AUTH_WITH_MASTER_KEY, Boolean.toString(true)); - } else { - String userId = AuthenticationHelper.verifyUserAccesToken(accessToken); - if (StringUtils.isBlank(userId)) { - return ResponseCode.unAuthorised.getErrorCode(); - } - response = "{userId}" + userId; - } - } else { - AuthenticationHelper.invalidateToken(""); - } - return response; - } - + Request request = ctx.request(); + String response = "{userId}"; + if (!isRequestInExcludeList(request.path())) { + String accessToken = request.getHeader(HeaderParam.X_Access_TokenId.getName()); + String authClientToken = + request.getHeader(HeaderParam.X_Authenticated_Client_Token.getName()); + String authClientId = request.getHeader(HeaderParam.X_Authenticated_Client_Id.getName()); + if (StringUtils.isBlank(accessToken) + && StringUtils.isBlank(authClientToken) + && StringUtils.isBlank(authClientId)) { + return ResponseCode.unAuthorised.getErrorCode(); + } + if (StringUtils.isBlank(System.getenv(JsonKey.SSO_PUBLIC_KEY)) + && Boolean.parseBoolean( + PropertiesCache.getInstance().getProperty(JsonKey.IS_SSO_ENABLED))) { + ProjectLogger.log( + "SSO public key is not set by environment variable==", LoggerEnum.INFO.name()); + response = "{userId}" + JsonKey.NOT_AVAILABLE; + } else if (!StringUtils.isBlank(authClientToken) && !StringUtils.isBlank(authClientId)) { + String clientId = + AuthenticationHelper.verifyClientAccessToken(authClientId, authClientToken); + if (StringUtils.isBlank(clientId)) { + return ResponseCode.unAuthorised.getErrorCode(); + } + response = "{userId}" + clientId; + ctx.flash().put(JsonKey.AUTH_WITH_MASTER_KEY, Boolean.toString(true)); + } else { + String userId = AuthenticationHelper.verifyUserAccesToken(accessToken); + if (StringUtils.isBlank(userId)) { + return ResponseCode.unAuthorised.getErrorCode(); + } + response = "{userId}" + userId; + } + } else { + AuthenticationHelper.invalidateToken(""); + } + return response; + } + /** * this method will check incoming request required validation or not. if this method return true * it means no need of validation other wise validation is required. - * + * * @param request Stirng URI * @return boolean */ @@ -147,10 +151,10 @@ public static boolean isRequestInExcludeList(String request) { } return resp; } - + /** * Method to remove last value - * + * * @param splited String [] * @return String */ @@ -164,5 +168,4 @@ private static String removeLastValue(String splited[]) { } return builder.toString(); } - } diff --git a/service/test/controllers/ApplicationTest.java b/service/test/controllers/ApplicationTest.java index 08e2bcff86..1c6899bb65 100644 --- a/service/test/controllers/ApplicationTest.java +++ b/service/test/controllers/ApplicationTest.java @@ -7,64 +7,60 @@ import org.sunbird.common.models.response.Response; import org.sunbird.common.models.response.ResponseParams; import org.sunbird.common.responsecode.ResponseCode; - import play.mvc.Result; - /** - * - * Simple (JUnit) tests that can call all parts of a play app. - * If you are interested in mocking a whole application, see the wiki for more details. - *extends WithApplication + * Simple (JUnit) tests that can call all parts of a play app. If you are interested in mocking a + * whole application, see the wiki for more details. extends WithApplication */ - public class ApplicationTest { - @Test - public void checkGetApiVersion() { - String apiPath = "/v1/learner/getenrolledcoures"; - String version = BaseController.getApiVersion(apiPath); - assertEquals("v1", version); - } + @Test + public void checkGetApiVersion() { + String apiPath = "/v1/learner/getenrolledcoures"; + String version = BaseController.getApiVersion(apiPath); + assertEquals("v1", version); + } + + @Test + public void checkCreateRequestParam() { + ResponseCode code = ResponseCode.getResponse(ResponseCode.success.getErrorCode()); + code.setResponseCode(ResponseCode.OK.getResponseCode()); + ResponseParams params = BaseController.createResponseParamObj(code); + assertEquals(ResponseCode.success.name(), params.getStatus()); + } - @Test - public void checkCreateRequestParam() { - ResponseCode code = ResponseCode.getResponse(ResponseCode.success.getErrorCode()); - code.setResponseCode(ResponseCode.OK.getResponseCode()); - ResponseParams params = BaseController.createResponseParamObj(code); - assertEquals(ResponseCode.success.name(), params.getStatus()); - } + // @Test + public void checkExceptionResponse() { + ProjectCommonException exception = + new ProjectCommonException( + ResponseCode.courseIdRequiredError.getErrorCode(), + ResponseCode.courseIdRequiredError.getErrorMessage(), + ResponseCode.CLIENT_ERROR.getResponseCode()); + Response response = BaseController.createResponseOnException(null, exception); + assertEquals(ResponseCode.courseIdRequiredError.getErrorCode(), response.getParams().getErr()); + } - //@Test - public void checkExceptionResponse() { - ProjectCommonException exception = new ProjectCommonException(ResponseCode.courseIdRequiredError.getErrorCode(), - ResponseCode.courseIdRequiredError.getErrorMessage(), ResponseCode.CLIENT_ERROR.getResponseCode()); - Response response = BaseController.createResponseOnException(null, exception); - assertEquals(ResponseCode.courseIdRequiredError.getErrorCode(), response.getParams().getErr()); - } + // @Test + public void testSuccessResponse() { + Response response = new Response(); + response = BaseController.createSuccessResponse(null, response); + assertEquals(ResponseCode.OK, response.getResponseCode()); + } - //@Test - public void testSuccessResponse() { - Response response = new Response(); - response = BaseController.createSuccessResponse(null, response); - assertEquals(ResponseCode.OK, response.getResponseCode()); - } - - @Test - public void checkFailureResponse() { - ResponseCode code = ResponseCode.getResponse(ResponseCode.authTokenRequired.getErrorCode()); - code.setResponseCode(ResponseCode.CLIENT_ERROR.getResponseCode()); - ResponseParams params = BaseController.createResponseParamObj(code); - assertEquals(ResponseCode.authTokenRequired.name(), params.getStatus()); - } - - - @Test(expected= RuntimeException.class) - public void testcreateCommonExceptionResponse() { - ResponseCode code = ResponseCode.getResponse(ResponseCode.authTokenRequired.getErrorCode()); - code.setResponseCode(ResponseCode.CLIENT_ERROR.getResponseCode()); - Result result = new BaseController().createCommonExceptionResponse(new Exception(),null); - assertEquals(ResponseCode.OK.getResponseCode(), result.status()); - } + @Test + public void checkFailureResponse() { + ResponseCode code = ResponseCode.getResponse(ResponseCode.authTokenRequired.getErrorCode()); + code.setResponseCode(ResponseCode.CLIENT_ERROR.getResponseCode()); + ResponseParams params = BaseController.createResponseParamObj(code); + assertEquals(ResponseCode.authTokenRequired.name(), params.getStatus()); + } + @Test(expected = RuntimeException.class) + public void testcreateCommonExceptionResponse() { + ResponseCode code = ResponseCode.getResponse(ResponseCode.authTokenRequired.getErrorCode()); + code.setResponseCode(ResponseCode.CLIENT_ERROR.getResponseCode()); + Result result = new BaseController().createCommonExceptionResponse(new Exception(), null); + assertEquals(ResponseCode.OK.getResponseCode(), result.status()); + } } diff --git a/service/test/controllers/DummyActor.java b/service/test/controllers/DummyActor.java index 80d865ee1b..5f0d7f3166 100644 --- a/service/test/controllers/DummyActor.java +++ b/service/test/controllers/DummyActor.java @@ -1,18 +1,15 @@ package controllers; -import org.sunbird.common.models.response.Response; - import akka.actor.ActorRef; import akka.actor.UntypedAbstractActor; +import org.sunbird.common.models.response.Response; -/** - * Created by arvind on 30/11/17. - */ +/** Created by arvind on 30/11/17. */ public class DummyActor extends UntypedAbstractActor { @Override public void onReceive(Object message) throws Throwable { Response response = new Response(); - sender().tell(response , ActorRef.noSender()); + sender().tell(response, ActorRef.noSender()); } } diff --git a/service/test/controllers/LearnerControllerTest.java b/service/test/controllers/LearnerControllerTest.java index 49890c33a9..4c87b31ece 100644 --- a/service/test/controllers/LearnerControllerTest.java +++ b/service/test/controllers/LearnerControllerTest.java @@ -4,12 +4,16 @@ import static org.powermock.api.mockito.PowerMockito.when; import static play.test.Helpers.route; +import akka.actor.ActorRef; +import akka.actor.ActorSystem; +import akka.actor.Props; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; - import org.junit.BeforeClass; import org.junit.FixMethodOrder; import org.junit.Test; @@ -23,13 +27,6 @@ import org.sunbird.common.models.util.JsonKey; import org.sunbird.common.models.util.ProjectLogger; import org.sunbird.common.request.HeaderParam; - -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - -import akka.actor.ActorRef; -import akka.actor.ActorSystem; -import akka.actor.Props; import play.libs.Json; import play.mvc.Http.RequestBuilder; import play.mvc.Result; @@ -37,9 +34,7 @@ import play.test.Helpers; import util.RequestInterceptor; -/** - * Created by arvind on 6/12/17. - */ +/** Created by arvind on 6/12/17. */ @FixMethodOrder(MethodSorters.NAME_ASCENDING) @RunWith(PowerMockRunner.class) @PrepareForTest(RequestInterceptor.class) @@ -47,7 +42,7 @@ public class LearnerControllerTest { private static FakeApplication app; - private static Map headerMap; + private static Map headerMap; private static ActorSystem system; private static final Props props = Props.create(controllers.DummyActor.class); @@ -56,10 +51,11 @@ public static void startApp() { app = Helpers.fakeApplication(); Helpers.start(app); headerMap = new HashMap(); - headerMap.put(HeaderParam.X_Consumer_ID.getName(), new String[]{"Service test consumer"}); - headerMap.put(HeaderParam.X_Device_ID.getName(), new String[]{"Some Device Id"}); - headerMap.put(HeaderParam.X_Authenticated_Userid.getName(), new String[]{"Authenticated user id"}); - headerMap.put(JsonKey.MESSAGE_ID, new String[]{"Unique Message id"}); + headerMap.put(HeaderParam.X_Consumer_ID.getName(), new String[] {"Service test consumer"}); + headerMap.put(HeaderParam.X_Device_ID.getName(), new String[] {"Some Device Id"}); + headerMap.put( + HeaderParam.X_Authenticated_Userid.getName(), new String[] {"Authenticated user id"}); + headerMap.put(JsonKey.MESSAGE_ID, new String[] {"Unique Message id"}); system = ActorSystem.create("system"); ActorRef subject = system.actorOf(props); @@ -69,15 +65,17 @@ public static void startApp() { @Test public void testenrollCourse() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - innerMap.put("courseId" , "course-123"); - requestMap.put(JsonKey.REQUEST , innerMap); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + innerMap.put("courseId", "course-123"); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); System.out.println(data); JsonNode json = Json.parse(data); - RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/user/courses/enroll").method("POST"); + RequestBuilder req = + new RequestBuilder().bodyJson(json).uri("/v1/user/courses/enroll").method("POST"); req.headers(headerMap); Result result = route(req); assertEquals(200, result.status()); @@ -86,15 +84,17 @@ public void testenrollCourse() { @Test public void testenrollCourseWithInvalidData() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - innerMap.put("courseId" , null); - requestMap.put(JsonKey.REQUEST , innerMap); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + innerMap.put("courseId", null); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); System.out.println(data); JsonNode json = Json.parse(data); - RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/user/courses/enroll").method("POST"); + RequestBuilder req = + new RequestBuilder().bodyJson(json).uri("/v1/user/courses/enroll").method("POST"); req.headers(headerMap); Result result = route(req); assertEquals(400, result.status()); @@ -103,7 +103,8 @@ public void testenrollCourseWithInvalidData() { @Test public void testgetEnrolledCourses() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); RequestBuilder req = new RequestBuilder().uri("/v1/user/courses/userid").method("GET"); req.headers(headerMap); Result result = route(req); @@ -113,22 +114,24 @@ public void testgetEnrolledCourses() { @Test public void testupdateContentState() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); List list = new ArrayList(); Map map = new HashMap(); - map.put(JsonKey.CONTENT_ID ,"6778"); - map.put(JsonKey.STATUS , "Active"); + map.put(JsonKey.CONTENT_ID, "6778"); + map.put(JsonKey.STATUS, "Active"); map.put(JsonKey.LAST_UPDATED_TIME, "2017-12-18 10:47:30:707+0530"); list.add(map); - innerMap.put("contents" , list); - innerMap.put("courseId" , "course-123"); - requestMap.put(JsonKey.REQUEST , innerMap); + innerMap.put("contents", list); + innerMap.put("courseId", "course-123"); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); - RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/content/state/update").method("PATCH"); + RequestBuilder req = + new RequestBuilder().bodyJson(json).uri("/v1/content/state/update").method("PATCH"); req.headers(headerMap); Result result = route(req); assertEquals(200, result.status()); @@ -137,30 +140,31 @@ public void testupdateContentState() { @Test public void testgetContentState() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - innerMap.put("courseId" , "course-123"); - requestMap.put(JsonKey.REQUEST , innerMap); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + innerMap.put("courseId", "course-123"); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); - RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/content/state/read").method("POST"); + RequestBuilder req = + new RequestBuilder().bodyJson(json).uri("/v1/content/state/read").method("POST"); req.headers(headerMap); Result result = route(req); assertEquals(200, result.status()); } - private static String mapToJson(Map map){ + private static String mapToJson(Map map) { ObjectMapper mapperObj = new ObjectMapper(); String jsonResp = ""; try { jsonResp = mapperObj.writeValueAsString(map); } catch (IOException e) { - ProjectLogger.log(e.getMessage(),e); + ProjectLogger.log(e.getMessage(), e); } return jsonResp; } - } diff --git a/service/test/controllers/assessment/AssessmentControllerTest.java b/service/test/controllers/assessment/AssessmentControllerTest.java index 113ccbfc9c..bccdf15c77 100644 --- a/service/test/controllers/assessment/AssessmentControllerTest.java +++ b/service/test/controllers/assessment/AssessmentControllerTest.java @@ -4,10 +4,16 @@ import static org.powermock.api.mockito.PowerMockito.when; import static play.test.Helpers.route; +import akka.actor.ActorRef; +import akka.actor.ActorSystem; +import akka.actor.Props; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import controllers.BaseController; +import controllers.DummyActor; import java.io.IOException; import java.util.HashMap; import java.util.Map; - import org.junit.BeforeClass; import org.junit.FixMethodOrder; import org.junit.Test; @@ -21,15 +27,6 @@ import org.sunbird.common.models.util.JsonKey; import org.sunbird.common.models.util.ProjectLogger; import org.sunbird.common.request.HeaderParam; - -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - -import akka.actor.ActorRef; -import akka.actor.ActorSystem; -import akka.actor.Props; -import controllers.BaseController; -import controllers.DummyActor; import play.libs.Json; import play.mvc.Http.RequestBuilder; import play.mvc.Result; @@ -37,9 +34,7 @@ import play.test.Helpers; import util.RequestInterceptor; -/** - * Created by arvind on 6/12/17. - */ +/** Created by arvind on 6/12/17. */ @FixMethodOrder(MethodSorters.NAME_ASCENDING) @RunWith(PowerMockRunner.class) @PrepareForTest(RequestInterceptor.class) @@ -47,20 +42,20 @@ public class AssessmentControllerTest { private static FakeApplication app; - private static Map headerMap; + private static Map headerMap; private static ActorSystem system; private static final Props props = Props.create(DummyActor.class); - @BeforeClass public static void startApp() { app = Helpers.fakeApplication(); Helpers.start(app); headerMap = new HashMap(); - headerMap.put(HeaderParam.X_Consumer_ID.getName(), new String[]{"Service test consumer"}); - headerMap.put(HeaderParam.X_Device_ID.getName(), new String[]{"Some Device Id"}); - headerMap.put(HeaderParam.X_Authenticated_Userid.getName(), new String[]{"Authenticated user id"}); - headerMap.put(JsonKey.MESSAGE_ID, new String[]{"Unique Message id"}); + headerMap.put(HeaderParam.X_Consumer_ID.getName(), new String[] {"Service test consumer"}); + headerMap.put(HeaderParam.X_Device_ID.getName(), new String[] {"Some Device Id"}); + headerMap.put( + HeaderParam.X_Authenticated_Userid.getName(), new String[] {"Authenticated user id"}); + headerMap.put(JsonKey.MESSAGE_ID, new String[] {"Unique Message id"}); system = ActorSystem.create("system"); ActorRef subject = system.actorOf(props); @@ -70,17 +65,19 @@ public static void startApp() { @Test public void testsaveAssessment() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - innerMap.put("courseId" , "course-123"); - innerMap.put("contentId" , "content01"); - innerMap.put("attemptId" , "2"); - requestMap.put(JsonKey.REQUEST , innerMap); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + innerMap.put("courseId", "course-123"); + innerMap.put("contentId", "content01"); + innerMap.put("attemptId", "2"); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); - RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/assessment/update").method("POST"); + RequestBuilder req = + new RequestBuilder().bodyJson(json).uri("/v1/assessment/update").method("POST"); req.headers(headerMap); Result result = route(req); assertEquals(200, result.status()); @@ -89,30 +86,30 @@ public void testsaveAssessment() { @Test public void testgetAssessment() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - innerMap.put("courseId" , "course-123"); - requestMap.put(JsonKey.REQUEST , innerMap); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + innerMap.put("courseId", "course-123"); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); - RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/assessment/result/read").method("POST"); + RequestBuilder req = + new RequestBuilder().bodyJson(json).uri("/v1/assessment/result/read").method("POST"); req.headers(headerMap); Result result = route(req); assertEquals(200, result.status()); } - - private static String mapToJson(Map map){ + private static String mapToJson(Map map) { ObjectMapper mapperObj = new ObjectMapper(); String jsonResp = ""; try { jsonResp = mapperObj.writeValueAsString(map); } catch (IOException e) { - ProjectLogger.log(e.getMessage(),e); + ProjectLogger.log(e.getMessage(), e); } return jsonResp; } - } diff --git a/service/test/controllers/audit/AuditLogControllerTest.java b/service/test/controllers/audit/AuditLogControllerTest.java index 0a0db79c21..0711d45899 100644 --- a/service/test/controllers/audit/AuditLogControllerTest.java +++ b/service/test/controllers/audit/AuditLogControllerTest.java @@ -4,10 +4,16 @@ import static org.powermock.api.mockito.PowerMockito.when; import static play.test.Helpers.route; +import akka.actor.ActorRef; +import akka.actor.ActorSystem; +import akka.actor.Props; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import controllers.BaseController; +import controllers.DummyActor; import java.io.IOException; import java.util.HashMap; import java.util.Map; - import org.junit.BeforeClass; import org.junit.FixMethodOrder; import org.junit.Test; @@ -21,15 +27,6 @@ import org.sunbird.common.models.util.JsonKey; import org.sunbird.common.models.util.ProjectLogger; import org.sunbird.common.request.HeaderParam; - -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - -import akka.actor.ActorRef; -import akka.actor.ActorSystem; -import akka.actor.Props; -import controllers.BaseController; -import controllers.DummyActor; import play.libs.Json; import play.mvc.Http.RequestBuilder; import play.mvc.Result; @@ -37,9 +34,7 @@ import play.test.Helpers; import util.RequestInterceptor; -/** - * Created by arvind on 6/12/17. - */ +/** Created by arvind on 6/12/17. */ @FixMethodOrder(MethodSorters.NAME_ASCENDING) @RunWith(PowerMockRunner.class) @PrepareForTest(RequestInterceptor.class) @@ -47,7 +42,7 @@ public class AuditLogControllerTest { private static FakeApplication app; - private static Map headerMap; + private static Map headerMap; private static ActorSystem system; private static final Props props = Props.create(DummyActor.class); @@ -56,10 +51,11 @@ public static void startApp() { app = Helpers.fakeApplication(); Helpers.start(app); headerMap = new HashMap(); - headerMap.put(HeaderParam.X_Consumer_ID.getName(), new String[]{"Service test consumer"}); - headerMap.put(HeaderParam.X_Device_ID.getName(), new String[]{"Some Device Id"}); - headerMap.put(HeaderParam.X_Authenticated_Userid.getName(), new String[]{"Authenticated user id"}); - headerMap.put(JsonKey.MESSAGE_ID, new String[]{"Unique Message id"}); + headerMap.put(HeaderParam.X_Consumer_ID.getName(), new String[] {"Service test consumer"}); + headerMap.put(HeaderParam.X_Device_ID.getName(), new String[] {"Some Device Id"}); + headerMap.put( + HeaderParam.X_Authenticated_Userid.getName(), new String[] {"Authenticated user id"}); + headerMap.put(JsonKey.MESSAGE_ID, new String[] {"Unique Message id"}); system = ActorSystem.create("system"); ActorRef subject = system.actorOf(props); @@ -69,28 +65,29 @@ public static void startApp() { @Test public void testsearchAuditHistory() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - requestMap.put(JsonKey.REQUEST , innerMap); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); - RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/audit/history").method("POST"); + RequestBuilder req = + new RequestBuilder().bodyJson(json).uri("/v1/audit/history").method("POST"); req.headers(headerMap); Result result = route(req); assertEquals(200, result.status()); } - private static String mapToJson(Map map){ + private static String mapToJson(Map map) { ObjectMapper mapperObj = new ObjectMapper(); String jsonResp = ""; try { jsonResp = mapperObj.writeValueAsString(map); } catch (IOException e) { - ProjectLogger.log(e.getMessage(),e); + ProjectLogger.log(e.getMessage(), e); } return jsonResp; } - } diff --git a/service/test/controllers/badges/BadgesControllerTest.java b/service/test/controllers/badges/BadgesControllerTest.java index 4cf51058eb..68a5cd2fc9 100644 --- a/service/test/controllers/badges/BadgesControllerTest.java +++ b/service/test/controllers/badges/BadgesControllerTest.java @@ -4,10 +4,16 @@ import static org.powermock.api.mockito.PowerMockito.when; import static play.test.Helpers.route; +import akka.actor.ActorRef; +import akka.actor.ActorSystem; +import akka.actor.Props; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import controllers.BaseController; +import controllers.DummyActor; import java.io.IOException; import java.util.HashMap; import java.util.Map; - import org.junit.BeforeClass; import org.junit.FixMethodOrder; import org.junit.Test; @@ -21,15 +27,6 @@ import org.sunbird.common.models.util.JsonKey; import org.sunbird.common.models.util.ProjectLogger; import org.sunbird.common.request.HeaderParam; - -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - -import akka.actor.ActorRef; -import akka.actor.ActorSystem; -import akka.actor.Props; -import controllers.BaseController; -import controllers.DummyActor; import play.libs.Json; import play.mvc.Http.RequestBuilder; import play.mvc.Result; @@ -37,9 +34,7 @@ import play.test.Helpers; import util.RequestInterceptor; -/** - * Created by arvind on 6/12/17. - */ +/** Created by arvind on 6/12/17. */ @FixMethodOrder(MethodSorters.NAME_ASCENDING) @RunWith(PowerMockRunner.class) @PrepareForTest(RequestInterceptor.class) @@ -47,7 +42,7 @@ public class BadgesControllerTest { private static FakeApplication app; - private static Map headerMap; + private static Map headerMap; private static ActorSystem system; private static final Props props = Props.create(DummyActor.class); @@ -56,10 +51,11 @@ public static void startApp() { app = Helpers.fakeApplication(); Helpers.start(app); headerMap = new HashMap(); - headerMap.put(HeaderParam.X_Consumer_ID.getName(), new String[]{"Service test consumer"}); - headerMap.put(HeaderParam.X_Device_ID.getName(), new String[]{"Some Device Id"}); - headerMap.put(HeaderParam.X_Authenticated_Userid.getName(), new String[]{"Authenticated user id"}); - headerMap.put(JsonKey.MESSAGE_ID, new String[]{"Unique Message id"}); + headerMap.put(HeaderParam.X_Consumer_ID.getName(), new String[] {"Service test consumer"}); + headerMap.put(HeaderParam.X_Device_ID.getName(), new String[] {"Some Device Id"}); + headerMap.put( + HeaderParam.X_Authenticated_Userid.getName(), new String[] {"Authenticated user id"}); + headerMap.put(JsonKey.MESSAGE_ID, new String[] {"Unique Message id"}); system = ActorSystem.create("system"); ActorRef subject = system.actorOf(props); @@ -69,16 +65,18 @@ public static void startApp() { @Test public void testaddUserBadges() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - innerMap.put("badgeTypeId" , "org123"); - innerMap.put("receiverId" , "user01"); - requestMap.put(JsonKey.REQUEST , innerMap); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + innerMap.put("badgeTypeId", "org123"); + innerMap.put("receiverId", "user01"); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); - RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/user/badges/add").method("POST"); + RequestBuilder req = + new RequestBuilder().bodyJson(json).uri("/v1/user/badges/add").method("POST"); req.headers(headerMap); Result result = route(req); assertEquals(200, result.status()); @@ -87,22 +85,22 @@ public void testaddUserBadges() { @Test public void testgetBadges() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); RequestBuilder req = new RequestBuilder().uri("/v1/badges/list").method("GET"); req.headers(headerMap); Result result = route(req); assertEquals(200, result.status()); } - private static String mapToJson(Map map){ + private static String mapToJson(Map map) { ObjectMapper mapperObj = new ObjectMapper(); String jsonResp = ""; try { jsonResp = mapperObj.writeValueAsString(map); } catch (IOException e) { - ProjectLogger.log(e.getMessage(),e); + ProjectLogger.log(e.getMessage(), e); } return jsonResp; } - } diff --git a/service/test/controllers/badging/BadgeAssertionControllerTest.java b/service/test/controllers/badging/BadgeAssertionControllerTest.java index c701b4bb6b..100460734b 100644 --- a/service/test/controllers/badging/BadgeAssertionControllerTest.java +++ b/service/test/controllers/badging/BadgeAssertionControllerTest.java @@ -4,12 +4,18 @@ import static org.powermock.api.mockito.PowerMockito.when; import static play.test.Helpers.route; +import akka.actor.ActorRef; +import akka.actor.ActorSystem; +import akka.actor.Props; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import controllers.BaseController; +import controllers.DummyActor; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; - import org.junit.BeforeClass; import org.junit.FixMethodOrder; import org.junit.Test; @@ -24,15 +30,6 @@ import org.sunbird.common.models.util.JsonKey; import org.sunbird.common.models.util.ProjectLogger; import org.sunbird.common.request.HeaderParam; - -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - -import akka.actor.ActorRef; -import akka.actor.ActorSystem; -import akka.actor.Props; -import controllers.BaseController; -import controllers.DummyActor; import play.libs.Json; import play.mvc.Http.RequestBuilder; import play.mvc.Result; @@ -40,9 +37,7 @@ import play.test.Helpers; import util.RequestInterceptor; -/** - * Created by arvind on 5/3/18. - */ +/** Created by arvind on 5/3/18. */ @FixMethodOrder(MethodSorters.NAME_ASCENDING) @RunWith(PowerMockRunner.class) @PrepareForTest(RequestInterceptor.class) @@ -50,7 +45,7 @@ public class BadgeAssertionControllerTest { private static FakeApplication app; - private static Map headerMap; + private static Map headerMap; private static ActorSystem system; private static final Props props = Props.create(DummyActor.class); @@ -59,10 +54,11 @@ public static void startApp() { app = Helpers.fakeApplication(); Helpers.start(app); headerMap = new HashMap(); - headerMap.put(HeaderParam.X_Consumer_ID.getName(), new String[]{"Service test consumer"}); - headerMap.put(HeaderParam.X_Device_ID.getName(), new String[]{"Some Device Id"}); - headerMap.put(HeaderParam.X_Authenticated_Userid.getName(), new String[]{"Authenticated user id"}); - headerMap.put(JsonKey.MESSAGE_ID, new String[]{"Unique Message id"}); + headerMap.put(HeaderParam.X_Consumer_ID.getName(), new String[] {"Service test consumer"}); + headerMap.put(HeaderParam.X_Device_ID.getName(), new String[] {"Some Device Id"}); + headerMap.put( + HeaderParam.X_Authenticated_Userid.getName(), new String[] {"Authenticated user id"}); + headerMap.put(JsonKey.MESSAGE_ID, new String[] {"Unique Message id"}); system = ActorSystem.create("system"); ActorRef subject = system.actorOf(props); @@ -72,19 +68,21 @@ public static void startApp() { @Test public void testAssertionCreate() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - innerMap.put(BadgingJsonKey.ISSUER_ID , "issuerId"); - innerMap.put(BadgingJsonKey.BADGE_CLASS_ID , "badgeid"); - innerMap.put(BadgingJsonKey.RECIPIENT_EMAIL , "abc@gmail.com"); - innerMap.put(BadgingJsonKey.RECIPIENT_ID , "userIdorcontentId"); - innerMap.put(BadgingJsonKey.RECIPIENT_TYPE , "user"); - requestMap.put(JsonKey.REQUEST , innerMap); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + innerMap.put(BadgingJsonKey.ISSUER_ID, "issuerId"); + innerMap.put(BadgingJsonKey.BADGE_CLASS_ID, "badgeid"); + innerMap.put(BadgingJsonKey.RECIPIENT_EMAIL, "abc@gmail.com"); + innerMap.put(BadgingJsonKey.RECIPIENT_ID, "userIdorcontentId"); + innerMap.put(BadgingJsonKey.RECIPIENT_TYPE, "user"); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); - RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/issuer/badge/assertion/create").method("POST"); + RequestBuilder req = + new RequestBuilder().bodyJson(json).uri("/v1/issuer/badge/assertion/create").method("POST"); req.headers(headerMap); Result result = route(req); assertEquals(200, result.status()); @@ -93,161 +91,177 @@ public void testAssertionCreate() { @Test public void createAssertionWithInvalidData() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - innerMap.put(BadgingJsonKey.BADGE_CLASS_ID , "badgeid"); - innerMap.put(BadgingJsonKey.RECIPIENT_EMAIL , "abc@gmail.com"); - innerMap.put(BadgingJsonKey.RECIPIENT_ID , "userIdorcontentId"); - innerMap.put(BadgingJsonKey.RECIPIENT_TYPE , "user"); - requestMap.put(JsonKey.REQUEST , innerMap); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + innerMap.put(BadgingJsonKey.BADGE_CLASS_ID, "badgeid"); + innerMap.put(BadgingJsonKey.RECIPIENT_EMAIL, "abc@gmail.com"); + innerMap.put(BadgingJsonKey.RECIPIENT_ID, "userIdorcontentId"); + innerMap.put(BadgingJsonKey.RECIPIENT_TYPE, "user"); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); - RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/issuer/badge/assertion/create").method("POST"); + RequestBuilder req = + new RequestBuilder().bodyJson(json).uri("/v1/issuer/badge/assertion/create").method("POST"); req.headers(headerMap); Result result = route(req); assertEquals(400, result.status()); } - + @Test public void assertionWithInvalidRecipent() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - innerMap.put(BadgingJsonKey.BADGE_CLASS_ID , "badgeid"); - innerMap.put(BadgingJsonKey.RECIPIENT_EMAIL , "abc@gmail.com"); - innerMap.put(BadgingJsonKey.RECIPIENT_ID , "userIdorcontentId"); - innerMap.put(BadgingJsonKey.RECIPIENT_TYPE , "textbook"); - requestMap.put(JsonKey.REQUEST , innerMap); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + innerMap.put(BadgingJsonKey.BADGE_CLASS_ID, "badgeid"); + innerMap.put(BadgingJsonKey.RECIPIENT_EMAIL, "abc@gmail.com"); + innerMap.put(BadgingJsonKey.RECIPIENT_ID, "userIdorcontentId"); + innerMap.put(BadgingJsonKey.RECIPIENT_TYPE, "textbook"); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); - RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/issuer/badge/assertion/create").method("POST"); + RequestBuilder req = + new RequestBuilder().bodyJson(json).uri("/v1/issuer/badge/assertion/create").method("POST"); req.headers(headerMap); Result result = route(req); assertEquals(400, result.status()); } - - + @Test public void getAssertionTest() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - RequestBuilder req = new RequestBuilder().uri("/v1/issuer/badge/assertion/read/assertionId").method("GET"); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + RequestBuilder req = + new RequestBuilder().uri("/v1/issuer/badge/assertion/read/assertionId").method("GET"); req.headers(headerMap); Result result = route(req); assertEquals(200, result.status()); } - + @Test public void getAssertionWithInvalidTest() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - innerMap.put(BadgingJsonKey.BADGE_CLASS_ID , "badgeid"); - innerMap.put(BadgingJsonKey.ASSERTION_ID , "assertionId"); - requestMap.put(JsonKey.REQUEST , innerMap); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + innerMap.put(BadgingJsonKey.BADGE_CLASS_ID, "badgeid"); + innerMap.put(BadgingJsonKey.ASSERTION_ID, "assertionId"); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); - RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/issuer/badge/assertion/read").method("POST"); + RequestBuilder req = + new RequestBuilder().bodyJson(json).uri("/v1/issuer/badge/assertion/read").method("POST"); req.headers(headerMap); Result result = route(req); assertEquals(400, result.status()); } - - @Test public void getAssertionListTest() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); List assertionList = new ArrayList(); assertionList.add("assertionId"); - innerMap.put(JsonKey.FILTERS , assertionList); - Map dataMap = new HashMap<>(); - requestMap.put(JsonKey.REQUEST , innerMap); + innerMap.put(JsonKey.FILTERS, assertionList); + Map dataMap = new HashMap<>(); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); - RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/issuer/badge/assertion/search").method("POST"); + RequestBuilder req = + new RequestBuilder().bodyJson(json).uri("/v1/issuer/badge/assertion/search").method("POST"); req.headers(headerMap); Result result = route(req); assertEquals(200, result.status()); } - + @Test public void getAssertionListWithInvalidTYpe() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - innerMap.put(BadgingJsonKey.ASSERTION_ID , "assertionId"); - List> list = new ArrayList<>(); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + innerMap.put(BadgingJsonKey.ASSERTION_ID, "assertionId"); + List> list = new ArrayList<>(); list.add(innerMap); - Map dataMap = new HashMap<>(); + Map dataMap = new HashMap<>(); dataMap.put(BadgingJsonKey.BADGE_ASSERTIONS, list); - requestMap.put(JsonKey.REQUEST , dataMap); + requestMap.put(JsonKey.REQUEST, dataMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); - RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/issuer/badge/assertion/search").method("POST"); + RequestBuilder req = + new RequestBuilder().bodyJson(json).uri("/v1/issuer/badge/assertion/search").method("POST"); req.headers(headerMap); Result result = route(req); assertEquals(400, result.status()); } - - + @Test public void revokeAssertionTest() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - innerMap.put(BadgingJsonKey.ASSERTION_ID , "assertionId"); - innerMap.put(BadgingJsonKey.RECIPIENT_ID , "userIdorcontentId"); - innerMap.put(BadgingJsonKey.RECIPIENT_TYPE , "user"); - innerMap.put(BadgingJsonKey.REVOCATION_REASON , "some reason"); - requestMap.put(JsonKey.REQUEST , innerMap); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + innerMap.put(BadgingJsonKey.ASSERTION_ID, "assertionId"); + innerMap.put(BadgingJsonKey.RECIPIENT_ID, "userIdorcontentId"); + innerMap.put(BadgingJsonKey.RECIPIENT_TYPE, "user"); + innerMap.put(BadgingJsonKey.REVOCATION_REASON, "some reason"); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); - RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/issuer/badge/assertion/delete").method("DELETE"); + RequestBuilder req = + new RequestBuilder() + .bodyJson(json) + .uri("/v1/issuer/badge/assertion/delete") + .method("DELETE"); req.headers(headerMap); Result result = route(req); assertEquals(200, result.status()); } - + @Test public void revokeAssertionFailureTest() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - innerMap.put(BadgingJsonKey.ASSERTION_ID , "assertionId"); - innerMap.put(BadgingJsonKey.RECIPIENT_ID , "userIdorcontentId"); - innerMap.put(BadgingJsonKey.RECIPIENT_TYPE , "user"); - requestMap.put(JsonKey.REQUEST , innerMap); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + innerMap.put(BadgingJsonKey.ASSERTION_ID, "assertionId"); + innerMap.put(BadgingJsonKey.RECIPIENT_ID, "userIdorcontentId"); + innerMap.put(BadgingJsonKey.RECIPIENT_TYPE, "user"); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); - RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/issuer/badge/assertion/delete").method("DELETE"); + RequestBuilder req = + new RequestBuilder() + .bodyJson(json) + .uri("/v1/issuer/badge/assertion/delete") + .method("DELETE"); req.headers(headerMap); Result result = route(req); assertEquals(400, result.status()); } - - - private static String mapToJson(Map map){ + + private static String mapToJson(Map map) { ObjectMapper mapperObj = new ObjectMapper(); String jsonResp = ""; try { jsonResp = mapperObj.writeValueAsString(map); } catch (IOException e) { - ProjectLogger.log(e.getMessage(),e); + ProjectLogger.log(e.getMessage(), e); } return jsonResp; } - } diff --git a/service/test/controllers/badging/BadgeIssuerControllerTest.java b/service/test/controllers/badging/BadgeIssuerControllerTest.java index cda6da4052..98da0110ab 100644 --- a/service/test/controllers/badging/BadgeIssuerControllerTest.java +++ b/service/test/controllers/badging/BadgeIssuerControllerTest.java @@ -4,10 +4,16 @@ import static org.powermock.api.mockito.PowerMockito.when; import static play.test.Helpers.route; +import akka.actor.ActorRef; +import akka.actor.ActorSystem; +import akka.actor.Props; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import controllers.BaseController; +import controllers.DummyActor; import java.io.IOException; import java.util.HashMap; import java.util.Map; - import org.junit.BeforeClass; import org.junit.FixMethodOrder; import org.junit.Test; @@ -21,15 +27,6 @@ import org.sunbird.common.models.util.JsonKey; import org.sunbird.common.models.util.ProjectLogger; import org.sunbird.common.request.HeaderParam; - -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - -import akka.actor.ActorRef; -import akka.actor.ActorSystem; -import akka.actor.Props; -import controllers.BaseController; -import controllers.DummyActor; import play.libs.Json; import play.mvc.Http.RequestBuilder; import play.mvc.Result; @@ -37,9 +34,7 @@ import play.test.Helpers; import util.RequestInterceptor; -/** - * Created by arvind on 5/3/18. - */ +/** Created by arvind on 5/3/18. */ @FixMethodOrder(MethodSorters.NAME_ASCENDING) @RunWith(PowerMockRunner.class) @PrepareForTest(RequestInterceptor.class) @@ -47,7 +42,7 @@ public class BadgeIssuerControllerTest { private static FakeApplication app; - private static Map headerMap; + private static Map headerMap; private static ActorSystem system; private static final Props props = Props.create(DummyActor.class); @@ -56,10 +51,11 @@ public static void startApp() { app = Helpers.fakeApplication(); Helpers.start(app); headerMap = new HashMap(); - headerMap.put(HeaderParam.X_Consumer_ID.getName(), new String[]{"Service test consumer"}); - headerMap.put(HeaderParam.X_Device_ID.getName(), new String[]{"Some Device Id"}); - headerMap.put(HeaderParam.X_Authenticated_Userid.getName(), new String[]{"Authenticated user id"}); - headerMap.put(JsonKey.MESSAGE_ID, new String[]{"Unique Message id"}); + headerMap.put(HeaderParam.X_Consumer_ID.getName(), new String[] {"Service test consumer"}); + headerMap.put(HeaderParam.X_Device_ID.getName(), new String[] {"Some Device Id"}); + headerMap.put( + HeaderParam.X_Authenticated_Userid.getName(), new String[] {"Authenticated user id"}); + headerMap.put(JsonKey.MESSAGE_ID, new String[] {"Unique Message id"}); system = ActorSystem.create("system"); ActorRef subject = system.actorOf(props); @@ -69,18 +65,20 @@ public static void startApp() { @Test public void testCreateBadgeIssuer() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - innerMap.put(JsonKey.NAME , "goldBadge"); - innerMap.put(JsonKey.DESCRIPTION , "golden award"); - innerMap.put(JsonKey.EMAIL , "abc@gmail.com"); - innerMap.put(JsonKey.URL , "dummy/url"); - requestMap.put(JsonKey.REQUEST , innerMap); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + innerMap.put(JsonKey.NAME, "goldBadge"); + innerMap.put(JsonKey.DESCRIPTION, "golden award"); + innerMap.put(JsonKey.EMAIL, "abc@gmail.com"); + innerMap.put(JsonKey.URL, "dummy/url"); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); - RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/issuer/create").method("POST"); + RequestBuilder req = + new RequestBuilder().bodyJson(json).uri("/v1/issuer/create").method("POST"); req.headers(headerMap); Result result = route(req); assertEquals(200, result.status()); @@ -89,17 +87,19 @@ public void testCreateBadgeIssuer() { @Test public void testCreateBadgeIssuerInvalidRequestData() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - innerMap.put(JsonKey.NAME , "goldBadge"); - innerMap.put(JsonKey.DESCRIPTION , "golden award"); - innerMap.put(JsonKey.EMAIL , "abc@gmail.com"); - requestMap.put(JsonKey.REQUEST , innerMap); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + innerMap.put(JsonKey.NAME, "goldBadge"); + innerMap.put(JsonKey.DESCRIPTION, "golden award"); + innerMap.put(JsonKey.EMAIL, "abc@gmail.com"); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); - RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/issuer/create").method("POST"); + RequestBuilder req = + new RequestBuilder().bodyJson(json).uri("/v1/issuer/create").method("POST"); req.headers(headerMap); Result result = route(req); assertEquals(400, result.status()); @@ -108,7 +108,8 @@ public void testCreateBadgeIssuerInvalidRequestData() { @Test public void testGetBadgeIssuer() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); RequestBuilder req = new RequestBuilder().uri("/v1/issuer/read/123").method("GET"); req.headers(headerMap); @@ -119,7 +120,8 @@ public void testGetBadgeIssuer() { @Test public void testGetAllIssuer() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); RequestBuilder req = new RequestBuilder().uri("/v1/issuer/list").method("GET"); req.headers(headerMap); @@ -130,7 +132,8 @@ public void testGetAllIssuer() { @Test public void testDeleteBadgeIssuer() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); RequestBuilder req = new RequestBuilder().uri("/v1/issuer/delete/123").method("DELETE"); req.headers(headerMap); @@ -138,15 +141,14 @@ public void testDeleteBadgeIssuer() { assertEquals(200, result.status()); } - private static String mapToJson(Map map){ + private static String mapToJson(Map map) { ObjectMapper mapperObj = new ObjectMapper(); String jsonResp = ""; try { jsonResp = mapperObj.writeValueAsString(map); } catch (IOException e) { - ProjectLogger.log(e.getMessage(),e); + ProjectLogger.log(e.getMessage(), e); } return jsonResp; } - } diff --git a/service/test/controllers/badging/validator/BadgeAssertionTest.java b/service/test/controllers/badging/validator/BadgeAssertionTest.java index a77b51e632..dc7aa96887 100644 --- a/service/test/controllers/badging/validator/BadgeAssertionTest.java +++ b/service/test/controllers/badging/validator/BadgeAssertionTest.java @@ -4,7 +4,6 @@ import java.util.HashMap; import java.util.Map; - import org.junit.Assert; import org.junit.Test; import org.powermock.core.classloader.annotations.PowerMockIgnore; @@ -15,176 +14,173 @@ /** * Test class for Badge assertion request data. - * @author Manzarul * + * @author Manzarul */ @PowerMockIgnore({"javax.management.*", "javax.net.ssl.*", "javax.security.*"}) public class BadgeAssertionTest { - - - @Test - public void validateAssertionSuccess () { - Request request = new Request(); - boolean response = false; - Map requestObj = new HashMap<>(); - requestObj.put(BadgingJsonKey.ISSUER_ID, "slug12"); - requestObj.put(BadgingJsonKey.BADGE_CLASS_ID, "classslug"); - requestObj.put(BadgingJsonKey.RECIPIENT_ID, "UserId or contnet id"); - requestObj.put(BadgingJsonKey.RECIPIENT_TYPE, "user"); - requestObj.put(BadgingJsonKey.EVIDENCE, "http://127.0.0.1:8000/public/badges/db-design-expert"); - requestObj.put(BadgingJsonKey.NOTIFY, false); - request.setRequest(requestObj); - try { - BadgeAssertionValidator.validateBadgeAssertion(request); - response = true; - } catch (ProjectCommonException e) { - Assert.assertNull(e); - } - assertEquals(true, response); - } - @Test - public void validateAssertionWithEmptyIssuer () { - Request request = new Request(); - boolean response = false; - Map requestObj = new HashMap<>(); - requestObj.put(BadgingJsonKey.ISSUER_ID, ""); - requestObj.put(BadgingJsonKey.BADGE_CLASS_ID, "classslug"); - requestObj.put(BadgingJsonKey.EVIDENCE, "http://localhost:8000/public/badges/db-design-expert"); - requestObj.put(BadgingJsonKey.NOTIFY, false); - request.setRequest(requestObj); - try { - BadgeAssertionValidator.validateBadgeAssertion(request); - response = true; - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.issuerIdRequired.getErrorCode(), e.getCode()); - } - assertEquals(false, response); - } - - @Test - public void validateAssertionWithOutIssuer () { - Request request = new Request(); - boolean response = false; - Map requestObj = new HashMap<>(); - requestObj.put(BadgingJsonKey.BADGE_CLASS_ID, "classslug"); - requestObj.put(BadgingJsonKey.RECIPIENT_ID, "userId"); - requestObj.put(BadgingJsonKey.EVIDENCE, "http://localhost:8000/public/badges/db-design-expert"); - requestObj.put(BadgingJsonKey.NOTIFY, false); - request.setRequest(requestObj); - try { - BadgeAssertionValidator.validateBadgeAssertion(request); - response = true; - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.issuerIdRequired.getErrorCode(), e.getCode()); - } - assertEquals(false, response); - } - - @Test - public void validateAssertionWithEmptyBadgeSlug () { - Request request = new Request(); - boolean response = false; - Map requestObj = new HashMap<>(); - requestObj.put(BadgingJsonKey.ISSUER_ID, "issuerSlug"); - requestObj.put(BadgingJsonKey.BADGE_CLASS_ID, ""); - requestObj.put(BadgingJsonKey.RECIPIENT_ID, "contentId"); - requestObj.put(BadgingJsonKey.EVIDENCE, "http://localhost:8000/public/badges/db-design-expert"); - requestObj.put(BadgingJsonKey.NOTIFY, false); - request.setRequest(requestObj); - try { - BadgeAssertionValidator.validateBadgeAssertion(request); - response = true; - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.badgeIdRequired.getErrorCode(), e.getCode()); - } - assertEquals(false, response); - } - - @Test - public void validateAssertionWithOutBadgeSlug () { - Request request = new Request(); - boolean response = false; - Map requestObj = new HashMap<>(); - requestObj.put(BadgingJsonKey.ISSUER_ID, "issuerSlug"); - requestObj.put(BadgingJsonKey.RECIPIENT_ID, "userId"); - requestObj.put(BadgingJsonKey.EVIDENCE, "http://localhost:8000/public/badges/db-design-expert"); - requestObj.put(BadgingJsonKey.NOTIFY, false); - request.setRequest(requestObj); - try { - BadgeAssertionValidator.validateBadgeAssertion(request); - response = true; - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.badgeIdRequired.getErrorCode(), e.getCode()); - } - assertEquals(false, response); - } - - @Test - public void validateAssertionWithEmptyRecipient () { - Request request = new Request(); - boolean response = false; - Map requestObj = new HashMap<>(); - requestObj.put(BadgingJsonKey.ISSUER_ID, "issuerSlug"); - requestObj.put(BadgingJsonKey.BADGE_CLASS_ID, "classslug"); - requestObj.put(BadgingJsonKey.RECIPIENT_ID, ""); - requestObj.put(BadgingJsonKey.EVIDENCE, "http://dev.open-sunbird.org"); - requestObj.put(BadgingJsonKey.NOTIFY, false); - request.setRequest(requestObj); - try { - BadgeAssertionValidator.validateBadgeAssertion(request); - response = true; - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.recipientIdRequired.getErrorCode(), e.getCode()); - } - assertEquals(false, response); - } - - - @Test - public void assertionWithOutRecipientId() { - Request request = new Request(); - boolean response = false; - Map requestObj = new HashMap<>(); - requestObj.put(BadgingJsonKey.ISSUER_ID, "issuerSlug"); - requestObj.put(BadgingJsonKey.BADGE_CLASS_ID, "classslug"); - requestObj.put(BadgingJsonKey.NOTIFY, false); - request.setRequest(requestObj); - try { - BadgeAssertionValidator.validateBadgeAssertion(request); - response = true; - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.recipientIdRequired.getErrorCode(), e.getCode()); - } - assertEquals(false, response); - } - - @Test - public void assertionWithEmptyEvidence() { - Request request = new Request(); - boolean response = false; - Map requestObj = new HashMap<>(); - requestObj.put(BadgingJsonKey.ISSUER_ID, "issuerSlug"); - requestObj.put(BadgingJsonKey.BADGE_CLASS_ID, "classslug"); - requestObj.put(BadgingJsonKey.RECIPIENT_ID, "UserId or contnet id"); - requestObj.put(BadgingJsonKey.RECIPIENT_TYPE, "content"); - requestObj.put(BadgingJsonKey.EVIDENCE, "some data"); - requestObj.put(BadgingJsonKey.NOTIFY, false); - request.setRequest(requestObj); - try { - BadgeAssertionValidator.validateBadgeAssertion(request); - response = true; - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.evidenceRequired.getErrorCode(), e.getCode()); - } - assertEquals(false, response); - } - + @Test + public void validateAssertionSuccess() { + Request request = new Request(); + boolean response = false; + Map requestObj = new HashMap<>(); + requestObj.put(BadgingJsonKey.ISSUER_ID, "slug12"); + requestObj.put(BadgingJsonKey.BADGE_CLASS_ID, "classslug"); + requestObj.put(BadgingJsonKey.RECIPIENT_ID, "UserId or contnet id"); + requestObj.put(BadgingJsonKey.RECIPIENT_TYPE, "user"); + requestObj.put(BadgingJsonKey.EVIDENCE, "http://127.0.0.1:8000/public/badges/db-design-expert"); + requestObj.put(BadgingJsonKey.NOTIFY, false); + request.setRequest(requestObj); + try { + BadgeAssertionValidator.validateBadgeAssertion(request); + response = true; + } catch (ProjectCommonException e) { + Assert.assertNull(e); + } + assertEquals(true, response); + } + + @Test + public void validateAssertionWithEmptyIssuer() { + Request request = new Request(); + boolean response = false; + Map requestObj = new HashMap<>(); + requestObj.put(BadgingJsonKey.ISSUER_ID, ""); + requestObj.put(BadgingJsonKey.BADGE_CLASS_ID, "classslug"); + requestObj.put(BadgingJsonKey.EVIDENCE, "http://localhost:8000/public/badges/db-design-expert"); + requestObj.put(BadgingJsonKey.NOTIFY, false); + request.setRequest(requestObj); + try { + BadgeAssertionValidator.validateBadgeAssertion(request); + response = true; + } catch (ProjectCommonException e) { + assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); + assertEquals(ResponseCode.issuerIdRequired.getErrorCode(), e.getCode()); + } + assertEquals(false, response); + } + + @Test + public void validateAssertionWithOutIssuer() { + Request request = new Request(); + boolean response = false; + Map requestObj = new HashMap<>(); + requestObj.put(BadgingJsonKey.BADGE_CLASS_ID, "classslug"); + requestObj.put(BadgingJsonKey.RECIPIENT_ID, "userId"); + requestObj.put(BadgingJsonKey.EVIDENCE, "http://localhost:8000/public/badges/db-design-expert"); + requestObj.put(BadgingJsonKey.NOTIFY, false); + request.setRequest(requestObj); + try { + BadgeAssertionValidator.validateBadgeAssertion(request); + response = true; + } catch (ProjectCommonException e) { + assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); + assertEquals(ResponseCode.issuerIdRequired.getErrorCode(), e.getCode()); + } + assertEquals(false, response); + } + + @Test + public void validateAssertionWithEmptyBadgeSlug() { + Request request = new Request(); + boolean response = false; + Map requestObj = new HashMap<>(); + requestObj.put(BadgingJsonKey.ISSUER_ID, "issuerSlug"); + requestObj.put(BadgingJsonKey.BADGE_CLASS_ID, ""); + requestObj.put(BadgingJsonKey.RECIPIENT_ID, "contentId"); + requestObj.put(BadgingJsonKey.EVIDENCE, "http://localhost:8000/public/badges/db-design-expert"); + requestObj.put(BadgingJsonKey.NOTIFY, false); + request.setRequest(requestObj); + try { + BadgeAssertionValidator.validateBadgeAssertion(request); + response = true; + } catch (ProjectCommonException e) { + assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); + assertEquals(ResponseCode.badgeIdRequired.getErrorCode(), e.getCode()); + } + assertEquals(false, response); + } + + @Test + public void validateAssertionWithOutBadgeSlug() { + Request request = new Request(); + boolean response = false; + Map requestObj = new HashMap<>(); + requestObj.put(BadgingJsonKey.ISSUER_ID, "issuerSlug"); + requestObj.put(BadgingJsonKey.RECIPIENT_ID, "userId"); + requestObj.put(BadgingJsonKey.EVIDENCE, "http://localhost:8000/public/badges/db-design-expert"); + requestObj.put(BadgingJsonKey.NOTIFY, false); + request.setRequest(requestObj); + try { + BadgeAssertionValidator.validateBadgeAssertion(request); + response = true; + } catch (ProjectCommonException e) { + assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); + assertEquals(ResponseCode.badgeIdRequired.getErrorCode(), e.getCode()); + } + assertEquals(false, response); + } + + @Test + public void validateAssertionWithEmptyRecipient() { + Request request = new Request(); + boolean response = false; + Map requestObj = new HashMap<>(); + requestObj.put(BadgingJsonKey.ISSUER_ID, "issuerSlug"); + requestObj.put(BadgingJsonKey.BADGE_CLASS_ID, "classslug"); + requestObj.put(BadgingJsonKey.RECIPIENT_ID, ""); + requestObj.put(BadgingJsonKey.EVIDENCE, "http://dev.open-sunbird.org"); + requestObj.put(BadgingJsonKey.NOTIFY, false); + request.setRequest(requestObj); + try { + BadgeAssertionValidator.validateBadgeAssertion(request); + response = true; + } catch (ProjectCommonException e) { + assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); + assertEquals(ResponseCode.recipientIdRequired.getErrorCode(), e.getCode()); + } + assertEquals(false, response); + } + + @Test + public void assertionWithOutRecipientId() { + Request request = new Request(); + boolean response = false; + Map requestObj = new HashMap<>(); + requestObj.put(BadgingJsonKey.ISSUER_ID, "issuerSlug"); + requestObj.put(BadgingJsonKey.BADGE_CLASS_ID, "classslug"); + requestObj.put(BadgingJsonKey.NOTIFY, false); + request.setRequest(requestObj); + try { + BadgeAssertionValidator.validateBadgeAssertion(request); + response = true; + } catch (ProjectCommonException e) { + assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); + assertEquals(ResponseCode.recipientIdRequired.getErrorCode(), e.getCode()); + } + assertEquals(false, response); + } + + @Test + public void assertionWithEmptyEvidence() { + Request request = new Request(); + boolean response = false; + Map requestObj = new HashMap<>(); + requestObj.put(BadgingJsonKey.ISSUER_ID, "issuerSlug"); + requestObj.put(BadgingJsonKey.BADGE_CLASS_ID, "classslug"); + requestObj.put(BadgingJsonKey.RECIPIENT_ID, "UserId or contnet id"); + requestObj.put(BadgingJsonKey.RECIPIENT_TYPE, "content"); + requestObj.put(BadgingJsonKey.EVIDENCE, "some data"); + requestObj.put(BadgingJsonKey.NOTIFY, false); + request.setRequest(requestObj); + try { + BadgeAssertionValidator.validateBadgeAssertion(request); + response = true; + } catch (ProjectCommonException e) { + assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); + assertEquals(ResponseCode.evidenceRequired.getErrorCode(), e.getCode()); + } + assertEquals(false, response); + } } diff --git a/service/test/controllers/badging/validator/BadgeClassValidatorTest.java b/service/test/controllers/badging/validator/BadgeClassValidatorTest.java index a77d3e93f4..8538be0beb 100644 --- a/service/test/controllers/badging/validator/BadgeClassValidatorTest.java +++ b/service/test/controllers/badging/validator/BadgeClassValidatorTest.java @@ -6,7 +6,6 @@ import java.io.IOException; import java.util.HashMap; import java.util.Map; - import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -32,392 +31,428 @@ @PrepareForTest({HttpUtil.class}) @PowerMockIgnore({"javax.management.*", "javax.net.ssl.*", "javax.security.*"}) public class BadgeClassValidatorTest { - private static final String READ_ROOT_ORG_TRUE_RESPONSE = "{\"id\":\"api.org.read\",\"ver\":\"v1\",\"ts\":\"2018-03-22 13:38:07:948+0000\",\"params\":{\"resmsgid\":null,\"msgid\":\"78070b77-a82d-4670-882e-1ed83af890bd\",\"err\":null,\"status\":\"success\",\"errmsg\":null},\"responseCode\":\"OK\",\"result\":{\"response\":{\"dateTime\":null,\"preferredLanguage\":\"English\",\"approvedBy\":null,\"channel\":\"ROOT_ORG\",\"description\":\"Sunbird\",\"updatedDate\":\"2017-08-24 06:02:10:846+0000\",\"addressId\":null,\"orgType\":null,\"provider\":null,\"orgCode\":\"sunbird\",\"theme\":null,\"id\":\"ORG_001\",\"communityId\":null,\"isApproved\":null,\"slug\":\"sunbird\",\"identifier\":\"ORG_001\",\"thumbnail\":null,\"orgName\":\"Sunbird\",\"updatedBy\":\"user1\",\"externalId\":null,\"isRootOrg\":true,\"rootOrgId\":null,\"approvedDate\":null,\"imgUrl\":null,\"homeUrl\":null,\"isDefault\":null,\"contactDetail\":\"[{\\\"phone\\\":\\\"213124234234\\\",\\\"email\\\":\\\"test@test.com\\\"},{\\\"phone\\\":\\\"+91213124234234\\\",\\\"email\\\":\\\"test1@test.com\\\"}]\",\"createdDate\":null,\"createdBy\":null,\"parentOrgId\":null,\"hashTagId\":\"b00bc992ef25f1a9a8d63291e20efc8d\",\"noOfMembers\":1,\"status\":null}}}"; - private static final String READ_ROOT_ORG_FALSE_RESPONSE = "{\"id\":\"api.org.read\",\"ver\":\"v1\",\"ts\":\"2018-03-22 13:38:07:948+0000\",\"params\":{\"resmsgid\":null,\"msgid\":\"78070b77-a82d-4670-882e-1ed83af890bd\",\"err\":null,\"status\":\"success\",\"errmsg\":null},\"responseCode\":\"OK\",\"result\":{\"response\":{\"dateTime\":null,\"preferredLanguage\":\"English\",\"approvedBy\":null,\"channel\":\"ROOT_ORG\",\"description\":\"Sunbird\",\"updatedDate\":\"2017-08-24 06:02:10:846+0000\",\"addressId\":null,\"orgType\":null,\"provider\":null,\"orgCode\":\"sunbird\",\"theme\":null,\"id\":\"ORG_001\",\"communityId\":null,\"isApproved\":null,\"slug\":\"sunbird\",\"identifier\":\"ORG_001\",\"thumbnail\":null,\"orgName\":\"Sunbird\",\"updatedBy\":\"user1\",\"externalId\":null,\"isRootOrg\":false,\"rootOrgId\":null,\"approvedDate\":null,\"imgUrl\":null,\"homeUrl\":null,\"isDefault\":null,\"contactDetail\":\"[{\\\"phone\\\":\\\"213124234234\\\",\\\"email\\\":\\\"test@test.com\\\"},{\\\"phone\\\":\\\"+91213124234234\\\",\\\"email\\\":\\\"test1@test.com\\\"}]\",\"createdDate\":null,\"createdBy\":null,\"parentOrgId\":null,\"hashTagId\":\"b00bc992ef25f1a9a8d63291e20efc8d\",\"noOfMembers\":1,\"status\":null}}}"; - private static final String READ_ROOT_ORG_EMTPY_RESPONSE = "{\"id\":\"api.org.read\",\"ver\":\"v1\",\"ts\":\"2018-03-22 13:38:07:948+0000\",\"params\":{\"resmsgid\":null,\"msgid\":\"78070b77-a82d-4670-882e-1ed83af890bd\",\"err\":null,\"status\":\"success\",\"errmsg\":null},\"responseCode\":\"OK\",\"result\":{}}"; - - @Before - public void setUp() throws IOException { - PowerMockito.mockStatic(HttpUtil.class); - PowerMockito.when(HttpUtil.doPostRequest(Mockito.anyString(), Mockito.anyString(), Mockito.anyMap())) - .thenReturn(new HttpUtilResponse(READ_ROOT_ORG_TRUE_RESPONSE, ResponseCode.OK.getResponseCode())); - } - - @Test - public void testValidateCreateBadgeClassIssuerIdRequired() { - Request request = new Request(); - Map requestMap = new HashMap<>(); - request.setRequest(requestMap); - - try { - new BadgeClassValidator().validateCreateBadgeClass(request, new HashMap<>()); - } catch (ProjectCommonException e) { - assertEquals(e.getCode(), ResponseCode.issuerIdRequired.getErrorCode()); - } + private static final String READ_ROOT_ORG_TRUE_RESPONSE = + "{\"id\":\"api.org.read\",\"ver\":\"v1\",\"ts\":\"2018-03-22 13:38:07:948+0000\",\"params\":{\"resmsgid\":null,\"msgid\":\"78070b77-a82d-4670-882e-1ed83af890bd\",\"err\":null,\"status\":\"success\",\"errmsg\":null},\"responseCode\":\"OK\",\"result\":{\"response\":{\"dateTime\":null,\"preferredLanguage\":\"English\",\"approvedBy\":null,\"channel\":\"ROOT_ORG\",\"description\":\"Sunbird\",\"updatedDate\":\"2017-08-24 06:02:10:846+0000\",\"addressId\":null,\"orgType\":null,\"provider\":null,\"orgCode\":\"sunbird\",\"theme\":null,\"id\":\"ORG_001\",\"communityId\":null,\"isApproved\":null,\"slug\":\"sunbird\",\"identifier\":\"ORG_001\",\"thumbnail\":null,\"orgName\":\"Sunbird\",\"updatedBy\":\"user1\",\"externalId\":null,\"isRootOrg\":true,\"rootOrgId\":null,\"approvedDate\":null,\"imgUrl\":null,\"homeUrl\":null,\"isDefault\":null,\"contactDetail\":\"[{\\\"phone\\\":\\\"213124234234\\\",\\\"email\\\":\\\"test@test.com\\\"},{\\\"phone\\\":\\\"+91213124234234\\\",\\\"email\\\":\\\"test1@test.com\\\"}]\",\"createdDate\":null,\"createdBy\":null,\"parentOrgId\":null,\"hashTagId\":\"b00bc992ef25f1a9a8d63291e20efc8d\",\"noOfMembers\":1,\"status\":null}}}"; + private static final String READ_ROOT_ORG_FALSE_RESPONSE = + "{\"id\":\"api.org.read\",\"ver\":\"v1\",\"ts\":\"2018-03-22 13:38:07:948+0000\",\"params\":{\"resmsgid\":null,\"msgid\":\"78070b77-a82d-4670-882e-1ed83af890bd\",\"err\":null,\"status\":\"success\",\"errmsg\":null},\"responseCode\":\"OK\",\"result\":{\"response\":{\"dateTime\":null,\"preferredLanguage\":\"English\",\"approvedBy\":null,\"channel\":\"ROOT_ORG\",\"description\":\"Sunbird\",\"updatedDate\":\"2017-08-24 06:02:10:846+0000\",\"addressId\":null,\"orgType\":null,\"provider\":null,\"orgCode\":\"sunbird\",\"theme\":null,\"id\":\"ORG_001\",\"communityId\":null,\"isApproved\":null,\"slug\":\"sunbird\",\"identifier\":\"ORG_001\",\"thumbnail\":null,\"orgName\":\"Sunbird\",\"updatedBy\":\"user1\",\"externalId\":null,\"isRootOrg\":false,\"rootOrgId\":null,\"approvedDate\":null,\"imgUrl\":null,\"homeUrl\":null,\"isDefault\":null,\"contactDetail\":\"[{\\\"phone\\\":\\\"213124234234\\\",\\\"email\\\":\\\"test@test.com\\\"},{\\\"phone\\\":\\\"+91213124234234\\\",\\\"email\\\":\\\"test1@test.com\\\"}]\",\"createdDate\":null,\"createdBy\":null,\"parentOrgId\":null,\"hashTagId\":\"b00bc992ef25f1a9a8d63291e20efc8d\",\"noOfMembers\":1,\"status\":null}}}"; + private static final String READ_ROOT_ORG_EMTPY_RESPONSE = + "{\"id\":\"api.org.read\",\"ver\":\"v1\",\"ts\":\"2018-03-22 13:38:07:948+0000\",\"params\":{\"resmsgid\":null,\"msgid\":\"78070b77-a82d-4670-882e-1ed83af890bd\",\"err\":null,\"status\":\"success\",\"errmsg\":null},\"responseCode\":\"OK\",\"result\":{}}"; + + @Before + public void setUp() throws IOException { + PowerMockito.mockStatic(HttpUtil.class); + PowerMockito.when( + HttpUtil.doPostRequest(Mockito.anyString(), Mockito.anyString(), Mockito.anyMap())) + .thenReturn( + new HttpUtilResponse(READ_ROOT_ORG_TRUE_RESPONSE, ResponseCode.OK.getResponseCode())); + } + + @Test + public void testValidateCreateBadgeClassIssuerIdRequired() { + Request request = new Request(); + Map requestMap = new HashMap<>(); + request.setRequest(requestMap); + + try { + new BadgeClassValidator().validateCreateBadgeClass(request, new HashMap<>()); + } catch (ProjectCommonException e) { + assertEquals(e.getCode(), ResponseCode.issuerIdRequired.getErrorCode()); } + } - @Test - public void testValidateCreateBadgeClassCriteriaRequired() { - Request request = new Request(); + @Test + public void testValidateCreateBadgeClassCriteriaRequired() { + Request request = new Request(); - Map requestMap = new HashMap<>(); - requestMap.put(BadgingJsonKey.ISSUER_ID, "oracle-university"); + Map requestMap = new HashMap<>(); + requestMap.put(BadgingJsonKey.ISSUER_ID, "oracle-university"); - request.setRequest(requestMap); + request.setRequest(requestMap); - try { - new BadgeClassValidator().validateCreateBadgeClass(request, new HashMap<>()); - } catch (ProjectCommonException e) { - assertEquals(e.getCode(), ResponseCode.badgeCriteriaRequired.getErrorCode()); - } + try { + new BadgeClassValidator().validateCreateBadgeClass(request, new HashMap<>()); + } catch (ProjectCommonException e) { + assertEquals(e.getCode(), ResponseCode.badgeCriteriaRequired.getErrorCode()); } + } - @Test - public void testValidateCreateBadgeClassNameRequired() { - Request request = new Request(); + @Test + public void testValidateCreateBadgeClassNameRequired() { + Request request = new Request(); - Map requestMap = new HashMap<>(); - requestMap.put(BadgingJsonKey.ISSUER_ID, "oracle-university"); - requestMap.put(BadgingJsonKey.BADGE_CRITERIA, "https://education.oracle.com/pls/web_prod-plq-dad/db_pages.getpage?page_id=5001&get_params=p_exam_id:1Z0-808"); + Map requestMap = new HashMap<>(); + requestMap.put(BadgingJsonKey.ISSUER_ID, "oracle-university"); + requestMap.put( + BadgingJsonKey.BADGE_CRITERIA, + "https://education.oracle.com/pls/web_prod-plq-dad/db_pages.getpage?page_id=5001&get_params=p_exam_id:1Z0-808"); - request.setRequest(requestMap); + request.setRequest(requestMap); - try { - new BadgeClassValidator().validateCreateBadgeClass(request, new HashMap<>()); - } catch (ProjectCommonException e) { - assertEquals(e.getCode(), ResponseCode.badgeNameRequired.getErrorCode()); - } + try { + new BadgeClassValidator().validateCreateBadgeClass(request, new HashMap<>()); + } catch (ProjectCommonException e) { + assertEquals(e.getCode(), ResponseCode.badgeNameRequired.getErrorCode()); } + } - @Test - public void testValidateCreateBadgeClassDescriptionRequired() { - Request request = new Request(); + @Test + public void testValidateCreateBadgeClassDescriptionRequired() { + Request request = new Request(); - Map requestMap = new HashMap<>(); - requestMap.put(BadgingJsonKey.ISSUER_ID, "oracle-university"); - requestMap.put(BadgingJsonKey.BADGE_CRITERIA, "https://education.oracle.com/pls/web_prod-plq-dad/db_pages.getpage?page_id=5001&get_params=p_exam_id:1Z0-808"); - requestMap.put(JsonKey.NAME, "Java SE 8 Programmer"); + Map requestMap = new HashMap<>(); + requestMap.put(BadgingJsonKey.ISSUER_ID, "oracle-university"); + requestMap.put( + BadgingJsonKey.BADGE_CRITERIA, + "https://education.oracle.com/pls/web_prod-plq-dad/db_pages.getpage?page_id=5001&get_params=p_exam_id:1Z0-808"); + requestMap.put(JsonKey.NAME, "Java SE 8 Programmer"); - request.setRequest(requestMap); + request.setRequest(requestMap); - try { - new BadgeClassValidator().validateCreateBadgeClass(request, new HashMap<>()); - } catch (ProjectCommonException e) { - assertEquals(e.getCode(), ResponseCode.badgeDescriptionRequired.getErrorCode()); - } + try { + new BadgeClassValidator().validateCreateBadgeClass(request, new HashMap<>()); + } catch (ProjectCommonException e) { + assertEquals(e.getCode(), ResponseCode.badgeDescriptionRequired.getErrorCode()); } - - @Test - public void testValidateCreateBadgeClassRootOrgIdRequired() { - Request request = new Request(); - - Map requestMap = new HashMap<>(); - requestMap.put(BadgingJsonKey.ISSUER_ID, "oracle-university"); - requestMap.put(BadgingJsonKey.BADGE_CRITERIA, "https://education.oracle.com/pls/web_prod-plq-dad/db_pages.getpage?page_id=5001&get_params=p_exam_id:1Z0-808"); - requestMap.put(JsonKey.NAME, "Java SE 8 Programmer"); - requestMap.put(JsonKey.DESCRIPTION, "A basic Java SE 8 certification."); - - request.setRequest(requestMap); - - try { - new BadgeClassValidator().validateCreateBadgeClass(request, new HashMap<>()); - } catch (ProjectCommonException e) { - assertEquals(e.getCode(), ResponseCode.rootOrgIdRequired.getErrorCode()); - } + } + + @Test + public void testValidateCreateBadgeClassRootOrgIdRequired() { + Request request = new Request(); + + Map requestMap = new HashMap<>(); + requestMap.put(BadgingJsonKey.ISSUER_ID, "oracle-university"); + requestMap.put( + BadgingJsonKey.BADGE_CRITERIA, + "https://education.oracle.com/pls/web_prod-plq-dad/db_pages.getpage?page_id=5001&get_params=p_exam_id:1Z0-808"); + requestMap.put(JsonKey.NAME, "Java SE 8 Programmer"); + requestMap.put(JsonKey.DESCRIPTION, "A basic Java SE 8 certification."); + + request.setRequest(requestMap); + + try { + new BadgeClassValidator().validateCreateBadgeClass(request, new HashMap<>()); + } catch (ProjectCommonException e) { + assertEquals(e.getCode(), ResponseCode.rootOrgIdRequired.getErrorCode()); } + } - private void performValidateCreateBadgeClassInvalidRootOrgId(Request request) { - try { - new BadgeClassValidator().validateCreateBadgeClass(request, new HashMap<>()); - } catch (ProjectCommonException e) { - assertEquals(e.getCode(), ResponseCode.rootOrgIdRequired.getErrorCode()); - } - } - - @Test - public void testValidateCreateBadgeClassInvalidRootOrgId() throws IOException { - PowerMockito.when(HttpUtil.doPostRequest(Mockito.anyString(), Mockito.anyString(), Mockito.anyMap())) - .thenReturn(new HttpUtilResponse("", ResponseCode.RESOURCE_NOT_FOUND.getResponseCode())); - - Request request = new Request(); - - Map requestMap = new HashMap<>(); - requestMap.put(BadgingJsonKey.ISSUER_ID, "oracle-university"); - requestMap.put(BadgingJsonKey.BADGE_CRITERIA, "https://education.oracle.com/pls/web_prod-plq-dad/db_pages.getpage?page_id=5001&get_params=p_exam_id:1Z0-808"); - requestMap.put(JsonKey.NAME, "Java SE 8 Programmer"); - requestMap.put(JsonKey.DESCRIPTION, "A basic Java SE 8 certification."); - - request.setRequest(requestMap); - - PowerMockito.when(HttpUtil.doPostRequest(Mockito.anyString(), Mockito.anyString(), Mockito.anyMap())) - .thenReturn(new HttpUtilResponse("", ResponseCode.RESOURCE_NOT_FOUND.getResponseCode())); - performValidateCreateBadgeClassInvalidRootOrgId(request); - - PowerMockito.when(HttpUtil.doPostRequest(Mockito.anyString(), Mockito.anyString(), Mockito.anyMap())) - .thenReturn(new HttpUtilResponse(READ_ROOT_ORG_FALSE_RESPONSE, ResponseCode.OK.getResponseCode())); - performValidateCreateBadgeClassInvalidRootOrgId(request); - - PowerMockito.when(HttpUtil.doPostRequest(Mockito.anyString(), Mockito.anyString(), Mockito.anyMap())) - .thenReturn(new HttpUtilResponse(READ_ROOT_ORG_EMTPY_RESPONSE, ResponseCode.OK.getResponseCode())); - performValidateCreateBadgeClassInvalidRootOrgId(request); + private void performValidateCreateBadgeClassInvalidRootOrgId(Request request) { + try { + new BadgeClassValidator().validateCreateBadgeClass(request, new HashMap<>()); + } catch (ProjectCommonException e) { + assertEquals(e.getCode(), ResponseCode.rootOrgIdRequired.getErrorCode()); } - - @Test - public void testValidateCreateBadgeClassTypeRequired() { - Request request = new Request(); - - Map requestMap = new HashMap<>(); - requestMap.put(BadgingJsonKey.ISSUER_ID, "oracle-university"); - requestMap.put(BadgingJsonKey.BADGE_CRITERIA, "https://education.oracle.com/pls/web_prod-plq-dad/db_pages.getpage?page_id=5001&get_params=p_exam_id:1Z0-808"); - requestMap.put(JsonKey.NAME, "Java SE 8 Programmer"); - requestMap.put(JsonKey.DESCRIPTION, "A basic Java SE 8 certification."); - requestMap.put(JsonKey.ROOT_ORG_ID, "AP"); - - request.setRequest(requestMap); - - try { - new BadgeClassValidator().validateCreateBadgeClass(request, new HashMap<>()); - } catch (ProjectCommonException e) { - assertEquals(e.getCode(), ResponseCode.badgeTypeRequired.getErrorCode()); - } + } + + @Test + public void testValidateCreateBadgeClassInvalidRootOrgId() throws IOException { + PowerMockito.when( + HttpUtil.doPostRequest(Mockito.anyString(), Mockito.anyString(), Mockito.anyMap())) + .thenReturn(new HttpUtilResponse("", ResponseCode.RESOURCE_NOT_FOUND.getResponseCode())); + + Request request = new Request(); + + Map requestMap = new HashMap<>(); + requestMap.put(BadgingJsonKey.ISSUER_ID, "oracle-university"); + requestMap.put( + BadgingJsonKey.BADGE_CRITERIA, + "https://education.oracle.com/pls/web_prod-plq-dad/db_pages.getpage?page_id=5001&get_params=p_exam_id:1Z0-808"); + requestMap.put(JsonKey.NAME, "Java SE 8 Programmer"); + requestMap.put(JsonKey.DESCRIPTION, "A basic Java SE 8 certification."); + + request.setRequest(requestMap); + + PowerMockito.when( + HttpUtil.doPostRequest(Mockito.anyString(), Mockito.anyString(), Mockito.anyMap())) + .thenReturn(new HttpUtilResponse("", ResponseCode.RESOURCE_NOT_FOUND.getResponseCode())); + performValidateCreateBadgeClassInvalidRootOrgId(request); + + PowerMockito.when( + HttpUtil.doPostRequest(Mockito.anyString(), Mockito.anyString(), Mockito.anyMap())) + .thenReturn( + new HttpUtilResponse(READ_ROOT_ORG_FALSE_RESPONSE, ResponseCode.OK.getResponseCode())); + performValidateCreateBadgeClassInvalidRootOrgId(request); + + PowerMockito.when( + HttpUtil.doPostRequest(Mockito.anyString(), Mockito.anyString(), Mockito.anyMap())) + .thenReturn( + new HttpUtilResponse(READ_ROOT_ORG_EMTPY_RESPONSE, ResponseCode.OK.getResponseCode())); + performValidateCreateBadgeClassInvalidRootOrgId(request); + } + + @Test + public void testValidateCreateBadgeClassTypeRequired() { + Request request = new Request(); + + Map requestMap = new HashMap<>(); + requestMap.put(BadgingJsonKey.ISSUER_ID, "oracle-university"); + requestMap.put( + BadgingJsonKey.BADGE_CRITERIA, + "https://education.oracle.com/pls/web_prod-plq-dad/db_pages.getpage?page_id=5001&get_params=p_exam_id:1Z0-808"); + requestMap.put(JsonKey.NAME, "Java SE 8 Programmer"); + requestMap.put(JsonKey.DESCRIPTION, "A basic Java SE 8 certification."); + requestMap.put(JsonKey.ROOT_ORG_ID, "AP"); + + request.setRequest(requestMap); + + try { + new BadgeClassValidator().validateCreateBadgeClass(request, new HashMap<>()); + } catch (ProjectCommonException e) { + assertEquals(e.getCode(), ResponseCode.badgeTypeRequired.getErrorCode()); } - - @Test - public void testValidateCreateBadgeClassInvalidType() { - Request request = new Request(); - - Map requestMap = new HashMap<>(); - requestMap.put(BadgingJsonKey.ISSUER_ID, "oracle-university"); - requestMap.put(BadgingJsonKey.BADGE_CRITERIA, "https://education.oracle.com/pls/web_prod-plq-dad/db_pages.getpage?page_id=5001&get_params=p_exam_id:1Z0-808"); - requestMap.put(JsonKey.NAME, "Java SE 8 Programmer"); - requestMap.put(JsonKey.DESCRIPTION, "A basic Java SE 8 certification."); - requestMap.put(JsonKey.ROOT_ORG_ID, "AP"); - requestMap.put(JsonKey.TYPE, "invalid"); - - request.setRequest(requestMap); - - try { - new BadgeClassValidator().validateCreateBadgeClass(request, new HashMap<>()); - } catch (ProjectCommonException e) { - assertEquals(e.getCode(), ResponseCode.invalidBadgeType.getErrorCode()); - } + } + + @Test + public void testValidateCreateBadgeClassInvalidType() { + Request request = new Request(); + + Map requestMap = new HashMap<>(); + requestMap.put(BadgingJsonKey.ISSUER_ID, "oracle-university"); + requestMap.put( + BadgingJsonKey.BADGE_CRITERIA, + "https://education.oracle.com/pls/web_prod-plq-dad/db_pages.getpage?page_id=5001&get_params=p_exam_id:1Z0-808"); + requestMap.put(JsonKey.NAME, "Java SE 8 Programmer"); + requestMap.put(JsonKey.DESCRIPTION, "A basic Java SE 8 certification."); + requestMap.put(JsonKey.ROOT_ORG_ID, "AP"); + requestMap.put(JsonKey.TYPE, "invalid"); + + request.setRequest(requestMap); + + try { + new BadgeClassValidator().validateCreateBadgeClass(request, new HashMap<>()); + } catch (ProjectCommonException e) { + assertEquals(e.getCode(), ResponseCode.invalidBadgeType.getErrorCode()); } - - @Test - public void testValidateCreateBadgeClassInvalidSubtype() { - Request request = new Request(); - - Map requestMap = new HashMap<>(); - requestMap.put(BadgingJsonKey.ISSUER_ID, "oracle-university"); - requestMap.put(BadgingJsonKey.BADGE_CRITERIA, "https://education.oracle.com/pls/web_prod-plq-dad/db_pages.getpage?page_id=5001&get_params=p_exam_id:1Z0-808"); - requestMap.put(JsonKey.NAME, "Java SE 8 Programmer"); - requestMap.put(JsonKey.DESCRIPTION, "A basic Java SE 8 certification."); - requestMap.put(JsonKey.ROOT_ORG_ID, "AP"); - requestMap.put(JsonKey.TYPE, "user"); - requestMap.put(JsonKey.SUBTYPE, "invalid"); - - request.setRequest(requestMap); - - try { - new BadgeClassValidator().validateCreateBadgeClass(request, new HashMap<>()); - } catch (ProjectCommonException e) { - assertEquals(e.getCode(), ResponseCode.invalidBadgeSubtype.getErrorCode()); - } + } + + @Test + public void testValidateCreateBadgeClassInvalidSubtype() { + Request request = new Request(); + + Map requestMap = new HashMap<>(); + requestMap.put(BadgingJsonKey.ISSUER_ID, "oracle-university"); + requestMap.put( + BadgingJsonKey.BADGE_CRITERIA, + "https://education.oracle.com/pls/web_prod-plq-dad/db_pages.getpage?page_id=5001&get_params=p_exam_id:1Z0-808"); + requestMap.put(JsonKey.NAME, "Java SE 8 Programmer"); + requestMap.put(JsonKey.DESCRIPTION, "A basic Java SE 8 certification."); + requestMap.put(JsonKey.ROOT_ORG_ID, "AP"); + requestMap.put(JsonKey.TYPE, "user"); + requestMap.put(JsonKey.SUBTYPE, "invalid"); + + request.setRequest(requestMap); + + try { + new BadgeClassValidator().validateCreateBadgeClass(request, new HashMap<>()); + } catch (ProjectCommonException e) { + assertEquals(e.getCode(), ResponseCode.invalidBadgeSubtype.getErrorCode()); } - - @Test - public void testValidateCreateBadgeClassRolesRequiredNull() { - Request request = new Request(); - - Map requestMap = new HashMap<>(); - requestMap.put(BadgingJsonKey.ISSUER_ID, "oracle-university"); - requestMap.put(BadgingJsonKey.BADGE_CRITERIA, "https://education.oracle.com/pls/web_prod-plq-dad/db_pages.getpage?page_id=5001&get_params=p_exam_id:1Z0-808"); - requestMap.put(JsonKey.NAME, "Java SE 8 Programmer"); - requestMap.put(JsonKey.DESCRIPTION, "A basic Java SE 8 certification."); - requestMap.put(JsonKey.ROOT_ORG_ID, "AP"); - requestMap.put(JsonKey.TYPE, "user"); - requestMap.put(JsonKey.SUBTYPE, "award"); - - request.setRequest(requestMap); - - try { - new BadgeClassValidator().validateCreateBadgeClass(request, new HashMap<>()); - } catch (ProjectCommonException e) { - assertEquals(e.getCode(), ResponseCode.badgeRolesRequired.getErrorCode()); - } + } + + @Test + public void testValidateCreateBadgeClassRolesRequiredNull() { + Request request = new Request(); + + Map requestMap = new HashMap<>(); + requestMap.put(BadgingJsonKey.ISSUER_ID, "oracle-university"); + requestMap.put( + BadgingJsonKey.BADGE_CRITERIA, + "https://education.oracle.com/pls/web_prod-plq-dad/db_pages.getpage?page_id=5001&get_params=p_exam_id:1Z0-808"); + requestMap.put(JsonKey.NAME, "Java SE 8 Programmer"); + requestMap.put(JsonKey.DESCRIPTION, "A basic Java SE 8 certification."); + requestMap.put(JsonKey.ROOT_ORG_ID, "AP"); + requestMap.put(JsonKey.TYPE, "user"); + requestMap.put(JsonKey.SUBTYPE, "award"); + + request.setRequest(requestMap); + + try { + new BadgeClassValidator().validateCreateBadgeClass(request, new HashMap<>()); + } catch (ProjectCommonException e) { + assertEquals(e.getCode(), ResponseCode.badgeRolesRequired.getErrorCode()); } - - @Test - public void testValidateCreateBadgeClassRolesRequiredEmpty() { - Request request = new Request(); - - Map requestMap = new HashMap<>(); - requestMap.put(BadgingJsonKey.ISSUER_ID, "oracle-university"); - requestMap.put(BadgingJsonKey.BADGE_CRITERIA, "https://education.oracle.com/pls/web_prod-plq-dad/db_pages.getpage?page_id=5001&get_params=p_exam_id:1Z0-808"); - requestMap.put(JsonKey.NAME, "Java SE 8 Programmer"); - requestMap.put(JsonKey.DESCRIPTION, "A basic Java SE 8 certification."); - requestMap.put(JsonKey.ROOT_ORG_ID, "AP"); - requestMap.put(JsonKey.TYPE, "user"); - requestMap.put(JsonKey.SUBTYPE, "award"); - requestMap.put(JsonKey.ROLES, "[]"); - - request.setRequest(requestMap); - - try { - new BadgeClassValidator().validateCreateBadgeClass(request, new HashMap<>()); - } catch (ProjectCommonException e) { - assertEquals(e.getCode(), ResponseCode.badgeRolesRequired.getErrorCode()); - } + } + + @Test + public void testValidateCreateBadgeClassRolesRequiredEmpty() { + Request request = new Request(); + + Map requestMap = new HashMap<>(); + requestMap.put(BadgingJsonKey.ISSUER_ID, "oracle-university"); + requestMap.put( + BadgingJsonKey.BADGE_CRITERIA, + "https://education.oracle.com/pls/web_prod-plq-dad/db_pages.getpage?page_id=5001&get_params=p_exam_id:1Z0-808"); + requestMap.put(JsonKey.NAME, "Java SE 8 Programmer"); + requestMap.put(JsonKey.DESCRIPTION, "A basic Java SE 8 certification."); + requestMap.put(JsonKey.ROOT_ORG_ID, "AP"); + requestMap.put(JsonKey.TYPE, "user"); + requestMap.put(JsonKey.SUBTYPE, "award"); + requestMap.put(JsonKey.ROLES, "[]"); + + request.setRequest(requestMap); + + try { + new BadgeClassValidator().validateCreateBadgeClass(request, new HashMap<>()); + } catch (ProjectCommonException e) { + assertEquals(e.getCode(), ResponseCode.badgeRolesRequired.getErrorCode()); } - - @Test - public void testValidateCreateBadgeClassSingleRoleImageRequired() { - Request request = new Request(); - - Map requestMap = new HashMap<>(); - requestMap.put(BadgingJsonKey.ISSUER_ID, "oracle-university"); - requestMap.put(BadgingJsonKey.BADGE_CRITERIA, "https://education.oracle.com/pls/web_prod-plq-dad/db_pages.getpage?page_id=5001&get_params=p_exam_id:1Z0-808"); - requestMap.put(JsonKey.NAME, "Java SE 8 Programmer"); - requestMap.put(JsonKey.DESCRIPTION, "A basic Java SE 8 certification."); - requestMap.put(JsonKey.ROOT_ORG_ID, "AP"); - requestMap.put(JsonKey.TYPE, "user"); - requestMap.put(JsonKey.SUBTYPE, "award"); - requestMap.put(JsonKey.ROLES, "OFFICIAL_TEXTBOOK_BADGE_ISSUER"); - - request.setRequest(requestMap); - - try { - new BadgeClassValidator().validateCreateBadgeClass(request, new HashMap<>()); - } catch (ProjectCommonException e) { - assertEquals(e.getCode(), ResponseCode.badgeImageRequired.getErrorCode()); - } + } + + @Test + public void testValidateCreateBadgeClassSingleRoleImageRequired() { + Request request = new Request(); + + Map requestMap = new HashMap<>(); + requestMap.put(BadgingJsonKey.ISSUER_ID, "oracle-university"); + requestMap.put( + BadgingJsonKey.BADGE_CRITERIA, + "https://education.oracle.com/pls/web_prod-plq-dad/db_pages.getpage?page_id=5001&get_params=p_exam_id:1Z0-808"); + requestMap.put(JsonKey.NAME, "Java SE 8 Programmer"); + requestMap.put(JsonKey.DESCRIPTION, "A basic Java SE 8 certification."); + requestMap.put(JsonKey.ROOT_ORG_ID, "AP"); + requestMap.put(JsonKey.TYPE, "user"); + requestMap.put(JsonKey.SUBTYPE, "award"); + requestMap.put(JsonKey.ROLES, "OFFICIAL_TEXTBOOK_BADGE_ISSUER"); + + request.setRequest(requestMap); + + try { + new BadgeClassValidator().validateCreateBadgeClass(request, new HashMap<>()); + } catch (ProjectCommonException e) { + assertEquals(e.getCode(), ResponseCode.badgeImageRequired.getErrorCode()); } - - @Test - public void testValidateCreateBadgeClassMultipleRolesImageRequired() { - Request request = new Request(); - - Map requestMap = new HashMap<>(); - requestMap.put(BadgingJsonKey.ISSUER_ID, "oracle-university"); - requestMap.put(BadgingJsonKey.BADGE_CRITERIA, "https://education.oracle.com/pls/web_prod-plq-dad/db_pages.getpage?page_id=5001&get_params=p_exam_id:1Z0-808"); - requestMap.put(JsonKey.NAME, "Java SE 8 Programmer"); - requestMap.put(JsonKey.DESCRIPTION, "A basic Java SE 8 certification."); - requestMap.put(JsonKey.ROOT_ORG_ID, "AP"); - requestMap.put(JsonKey.TYPE, "user"); - requestMap.put(JsonKey.SUBTYPE, "award"); - requestMap.put(JsonKey.ROLES, "[ \"OFFICIAL_TEXTBOOK_BADGE_ISSUER\", \"TEACHER_BADGE_ISSUER\" ]"); - - request.setRequest(requestMap); - - try { - new BadgeClassValidator().validateCreateBadgeClass(request, new HashMap<>()); - } catch (ProjectCommonException e) { - assertEquals(e.getCode(), ResponseCode.badgeImageRequired.getErrorCode()); - } + } + + @Test + public void testValidateCreateBadgeClassMultipleRolesImageRequired() { + Request request = new Request(); + + Map requestMap = new HashMap<>(); + requestMap.put(BadgingJsonKey.ISSUER_ID, "oracle-university"); + requestMap.put( + BadgingJsonKey.BADGE_CRITERIA, + "https://education.oracle.com/pls/web_prod-plq-dad/db_pages.getpage?page_id=5001&get_params=p_exam_id:1Z0-808"); + requestMap.put(JsonKey.NAME, "Java SE 8 Programmer"); + requestMap.put(JsonKey.DESCRIPTION, "A basic Java SE 8 certification."); + requestMap.put(JsonKey.ROOT_ORG_ID, "AP"); + requestMap.put(JsonKey.TYPE, "user"); + requestMap.put(JsonKey.SUBTYPE, "award"); + requestMap.put( + JsonKey.ROLES, "[ \"OFFICIAL_TEXTBOOK_BADGE_ISSUER\", \"TEACHER_BADGE_ISSUER\" ]"); + + request.setRequest(requestMap); + + try { + new BadgeClassValidator().validateCreateBadgeClass(request, new HashMap<>()); + } catch (ProjectCommonException e) { + assertEquals(e.getCode(), ResponseCode.badgeImageRequired.getErrorCode()); } - - @Test - public void testValidateCreateBadgeClassSuccess() { - Request request = new Request(); - - Map requestMap = new HashMap<>(); - requestMap.put(BadgingJsonKey.ISSUER_ID, "oracle-university"); - requestMap.put(BadgingJsonKey.BADGE_CRITERIA, "https://education.oracle.com/pls/web_prod-plq-dad/db_pages.getpage?page_id=5001&get_params=p_exam_id:1Z0-808"); - requestMap.put(JsonKey.NAME, "Java SE 8 Programmer"); - requestMap.put(JsonKey.DESCRIPTION, "A basic Java SE 8 certification."); - requestMap.put(JsonKey.ROOT_ORG_ID, "AP"); - requestMap.put(JsonKey.TYPE, "user"); - requestMap.put(JsonKey.SUBTYPE, "award"); - requestMap.put(JsonKey.ROLES, "[ \"OFFICIAL_TEXTBOOK_BADGE_ISSUER\" ]"); - requestMap.put(JsonKey.IMAGE, "something"); - - request.setRequest(requestMap); - - try { - new BadgeClassValidator().validateCreateBadgeClass(request, new HashMap<>()); - } catch (ProjectCommonException e) { - fail(); - } + } + + @Test + public void testValidateCreateBadgeClassSuccess() { + Request request = new Request(); + + Map requestMap = new HashMap<>(); + requestMap.put(BadgingJsonKey.ISSUER_ID, "oracle-university"); + requestMap.put( + BadgingJsonKey.BADGE_CRITERIA, + "https://education.oracle.com/pls/web_prod-plq-dad/db_pages.getpage?page_id=5001&get_params=p_exam_id:1Z0-808"); + requestMap.put(JsonKey.NAME, "Java SE 8 Programmer"); + requestMap.put(JsonKey.DESCRIPTION, "A basic Java SE 8 certification."); + requestMap.put(JsonKey.ROOT_ORG_ID, "AP"); + requestMap.put(JsonKey.TYPE, "user"); + requestMap.put(JsonKey.SUBTYPE, "award"); + requestMap.put(JsonKey.ROLES, "[ \"OFFICIAL_TEXTBOOK_BADGE_ISSUER\" ]"); + requestMap.put(JsonKey.IMAGE, "something"); + + request.setRequest(requestMap); + + try { + new BadgeClassValidator().validateCreateBadgeClass(request, new HashMap<>()); + } catch (ProjectCommonException e) { + fail(); } + } - @Test - public void testValidateGetBadgeBadgeIdRequired() { - Request request = new Request(); + @Test + public void testValidateGetBadgeBadgeIdRequired() { + Request request = new Request(); - Map requestMap = new HashMap<>(); - requestMap.put(BadgingJsonKey.ISSUER_ID, "oracle-university"); + Map requestMap = new HashMap<>(); + requestMap.put(BadgingJsonKey.ISSUER_ID, "oracle-university"); - request.setRequest(requestMap); + request.setRequest(requestMap); - try { - new BadgeClassValidator().validateGetBadgeClass(request); - } catch (ProjectCommonException e) { - assertEquals(e.getCode(), ResponseCode.badgeIdRequired.getErrorCode()); - } + try { + new BadgeClassValidator().validateGetBadgeClass(request); + } catch (ProjectCommonException e) { + assertEquals(e.getCode(), ResponseCode.badgeIdRequired.getErrorCode()); } + } - @Test - public void testValidateGetBadgeClassSuccess() { - Request request = new Request(); + @Test + public void testValidateGetBadgeClassSuccess() { + Request request = new Request(); - Map requestMap = new HashMap<>(); - requestMap.put(BadgingJsonKey.ISSUER_ID, "oracle-university"); - requestMap.put(BadgingJsonKey.BADGE_ID, "java-se-8-programmer"); + Map requestMap = new HashMap<>(); + requestMap.put(BadgingJsonKey.ISSUER_ID, "oracle-university"); + requestMap.put(BadgingJsonKey.BADGE_ID, "java-se-8-programmer"); - request.setRequest(requestMap); + request.setRequest(requestMap); - try { - new BadgeClassValidator().validateGetBadgeClass(request); - } catch (ProjectCommonException e) { - fail(); - } + try { + new BadgeClassValidator().validateGetBadgeClass(request); + } catch (ProjectCommonException e) { + fail(); } + } - @Test - public void testValidateSearchBadgeInvalidRequest() { - Request request = new Request(); + @Test + public void testValidateSearchBadgeInvalidRequest() { + Request request = new Request(); - Map requestMap = new HashMap<>(); + Map requestMap = new HashMap<>(); - request.setRequest(requestMap); + request.setRequest(requestMap); - try { - new BadgeClassValidator().validateSearchBadgeClass(request); - } catch (ProjectCommonException e) { - assertEquals(e.getCode(), ResponseCode.invalidRequestData.getErrorCode()); - } + try { + new BadgeClassValidator().validateSearchBadgeClass(request); + } catch (ProjectCommonException e) { + assertEquals(e.getCode(), ResponseCode.invalidRequestData.getErrorCode()); } + } - @Test - public void testValidateDeleteBadgeBadgeIdRequired() { - Request request = new Request(); + @Test + public void testValidateDeleteBadgeBadgeIdRequired() { + Request request = new Request(); - Map requestMap = new HashMap<>(); - requestMap.put(BadgingJsonKey.ISSUER_ID, "oracle-university"); + Map requestMap = new HashMap<>(); + requestMap.put(BadgingJsonKey.ISSUER_ID, "oracle-university"); - request.setRequest(requestMap); + request.setRequest(requestMap); - try { - new BadgeClassValidator().validateDeleteBadgeClass(request); - } catch (ProjectCommonException e) { - assertEquals(e.getCode(), ResponseCode.badgeIdRequired.getErrorCode()); - } + try { + new BadgeClassValidator().validateDeleteBadgeClass(request); + } catch (ProjectCommonException e) { + assertEquals(e.getCode(), ResponseCode.badgeIdRequired.getErrorCode()); } + } - @Test - public void testValidateDeleteBadgeClassSuccess() { - Request request = new Request(); + @Test + public void testValidateDeleteBadgeClassSuccess() { + Request request = new Request(); - Map requestMap = new HashMap<>(); - requestMap.put(BadgingJsonKey.ISSUER_ID, "oracle-university"); - requestMap.put(BadgingJsonKey.BADGE_ID, "java-se-8-programmer"); + Map requestMap = new HashMap<>(); + requestMap.put(BadgingJsonKey.ISSUER_ID, "oracle-university"); + requestMap.put(BadgingJsonKey.BADGE_ID, "java-se-8-programmer"); - request.setRequest(requestMap); + request.setRequest(requestMap); - try { - new BadgeClassValidator().validateDeleteBadgeClass(request); - } catch (ProjectCommonException e) { - fail(); - } + try { + new BadgeClassValidator().validateDeleteBadgeClass(request); + } catch (ProjectCommonException e) { + fail(); } + } } diff --git a/service/test/controllers/badging/validator/GetAssertionTest.java b/service/test/controllers/badging/validator/GetAssertionTest.java index 5edb9baba7..d15a8b4bec 100644 --- a/service/test/controllers/badging/validator/GetAssertionTest.java +++ b/service/test/controllers/badging/validator/GetAssertionTest.java @@ -7,7 +7,6 @@ import java.util.HashMap; import java.util.List; import java.util.Map; - import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; @@ -21,187 +20,185 @@ /** * Test class for Badge assertion get request data. - * @author Manzarul * + * @author Manzarul */ @RunWith(PowerMockRunner.class) @PowerMockIgnore("javax.management.*") public class GetAssertionTest { - @Test - public void getAssertion() { - Request request = new Request(); - boolean response = false; - Map requestObj = new HashMap<>(); - requestObj.put(BadgingJsonKey.ISSUER_ID, "issuerSlug"); - requestObj.put(BadgingJsonKey.BADGE_CLASS_ID, "classslug"); - requestObj.put(BadgingJsonKey.ASSERTION_ID, "someAssertionId"); - request.setRequest(requestObj); - try { - BadgeAssertionValidator.validategetBadgeAssertion(request); - response = true; - } catch (ProjectCommonException e) { - Assert.assertNull(e); - } - assertEquals(true, response); - } - - @Test - public void getAssertionWithOutIssuerId() { - Request request = new Request(); - boolean response = false; - Map requestObj = new HashMap<>(); - requestObj.put(BadgingJsonKey.ASSERTION_ID, "someAssertionId"); - request.setRequest(requestObj); - try { - BadgeAssertionValidator.validategetBadgeAssertion(request); - response = true; - } catch (ProjectCommonException e) { - Assert.assertNull(e); - } - assertEquals(true, response); - } - - @Test - public void getAssertionWithEmptyIssuerId() { - Request request = new Request(); - boolean response = false; - List list = new ArrayList<>(); - Map> filterMap = new HashMap<>(); - filterMap.put(BadgingJsonKey.ASSERTIONS, list); - - request.getRequest().put(JsonKey.FILTERS, filterMap); - try { - BadgeAssertionValidator.validategetBadgeAssertion(request); - response = true; - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.assertionIdRequired.getErrorCode(), e.getCode()); - } - assertEquals(false, response); - } - - @Test - public void getAssertionWithEmptyBadgeId() { - Request request = new Request(); - boolean response = false; - Map requestObj = new HashMap<>(); - requestObj.put(BadgingJsonKey.ISSUER_ID, "issuerId"); - requestObj.put(BadgingJsonKey.BADGE_CLASS_ID, null); - requestObj.put(BadgingJsonKey.ASSERTION_ID, "someAssertionId"); - request.setRequest(requestObj); - try { - BadgeAssertionValidator.validategetBadgeAssertion(request); - response = true; - } catch (ProjectCommonException e) { - Assert.assertNull(e); - } - assertEquals(true, response); - } - - @Test - public void getAssertionWithEmptyAssertionId() { - Request request = new Request(); - boolean response = false; - Map requestObj = new HashMap<>(); - requestObj.put(BadgingJsonKey.ISSUER_ID, "issuerId"); - requestObj.put(BadgingJsonKey.BADGE_CLASS_ID, "badgeId"); - requestObj.put(BadgingJsonKey.ASSERTION_ID, ""); - request.setRequest(requestObj); - try { - BadgeAssertionValidator.validategetBadgeAssertion(request); - response = true; - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.assertionIdRequired.getErrorCode(), e.getCode()); - } - assertEquals(false, response); - } - - - @Test - public void getAssertionList() { - Request request = new Request(); - boolean response = false; - List list = new ArrayList<>(); - for (int i = 0 ; i< 2 ;i++) { - list.add("assertionId-"+i); - } - Map> filterMap = new HashMap<>(); - filterMap.put(BadgingJsonKey.ASSERTIONS, list); - - request.getRequest().put(JsonKey.FILTERS, filterMap); - try { - BadgeAssertionValidator.validateGetAssertionList(request); - response = true; - } catch (ProjectCommonException e) { - Assert.assertNull(e); - } - assertEquals(true, response); - } - - @Test - public void getAssertionListWithWrongKey() { - Request request = new Request(); - boolean response = false; - Map requestObj = new HashMap<>(); - requestObj.put(BadgingJsonKey.ISSUER_ID, "issuerSlug"); - requestObj.put(BadgingJsonKey.BADGE_CLASS_ID, "classslug"); - requestObj.put(BadgingJsonKey.ASSERTION_ID, "someAssertionId"); - List> list = new ArrayList<>(); - list.add(requestObj); - request.getRequest().put("list", list); - try { - BadgeAssertionValidator.validateGetAssertionList(request); - response = true; - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.invalidRequestData.getErrorCode(), e.getCode()); - } - assertEquals(false, response); - } - - - @Test - public void getAssertionListWithExceedSize() { - Request request = new Request(); - boolean response = false; - List list = new ArrayList<>(); - for (int i = 0 ; i< 50 ;i++) { - list.add("assertionId-"+i); - } - Map> filterMap = new HashMap<>(); - filterMap.put(BadgingJsonKey.ASSERTIONS, list); - - request.getRequest().put(JsonKey.FILTERS, filterMap); - try { - BadgeAssertionValidator.validateGetAssertionList(request); - response = true; - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.sizeLimitExceed.getErrorCode(), e.getCode()); - } - assertEquals(false, response); - } - - @Test - public void getAssertionListWithMaxSize() { - Request request = new Request(); - boolean response = false; - List list = new ArrayList<>(); - for (int i = 0 ; i< 5 ;i++) { - list.add("assertionId-"+i); - } - Map> filterMap = new HashMap<>(); - filterMap.put(BadgingJsonKey.ASSERTIONS, list); - - request.getRequest().put(JsonKey.FILTERS, filterMap); - try { - BadgeAssertionValidator.validateGetAssertionList(request); - response = true; - } catch (ProjectCommonException e) { - assertNotNull(e); - } - assertEquals(true, response); - } + @Test + public void getAssertion() { + Request request = new Request(); + boolean response = false; + Map requestObj = new HashMap<>(); + requestObj.put(BadgingJsonKey.ISSUER_ID, "issuerSlug"); + requestObj.put(BadgingJsonKey.BADGE_CLASS_ID, "classslug"); + requestObj.put(BadgingJsonKey.ASSERTION_ID, "someAssertionId"); + request.setRequest(requestObj); + try { + BadgeAssertionValidator.validategetBadgeAssertion(request); + response = true; + } catch (ProjectCommonException e) { + Assert.assertNull(e); + } + assertEquals(true, response); + } + + @Test + public void getAssertionWithOutIssuerId() { + Request request = new Request(); + boolean response = false; + Map requestObj = new HashMap<>(); + requestObj.put(BadgingJsonKey.ASSERTION_ID, "someAssertionId"); + request.setRequest(requestObj); + try { + BadgeAssertionValidator.validategetBadgeAssertion(request); + response = true; + } catch (ProjectCommonException e) { + Assert.assertNull(e); + } + assertEquals(true, response); + } + + @Test + public void getAssertionWithEmptyIssuerId() { + Request request = new Request(); + boolean response = false; + List list = new ArrayList<>(); + Map> filterMap = new HashMap<>(); + filterMap.put(BadgingJsonKey.ASSERTIONS, list); + + request.getRequest().put(JsonKey.FILTERS, filterMap); + try { + BadgeAssertionValidator.validategetBadgeAssertion(request); + response = true; + } catch (ProjectCommonException e) { + assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); + assertEquals(ResponseCode.assertionIdRequired.getErrorCode(), e.getCode()); + } + assertEquals(false, response); + } + + @Test + public void getAssertionWithEmptyBadgeId() { + Request request = new Request(); + boolean response = false; + Map requestObj = new HashMap<>(); + requestObj.put(BadgingJsonKey.ISSUER_ID, "issuerId"); + requestObj.put(BadgingJsonKey.BADGE_CLASS_ID, null); + requestObj.put(BadgingJsonKey.ASSERTION_ID, "someAssertionId"); + request.setRequest(requestObj); + try { + BadgeAssertionValidator.validategetBadgeAssertion(request); + response = true; + } catch (ProjectCommonException e) { + Assert.assertNull(e); + } + assertEquals(true, response); + } + + @Test + public void getAssertionWithEmptyAssertionId() { + Request request = new Request(); + boolean response = false; + Map requestObj = new HashMap<>(); + requestObj.put(BadgingJsonKey.ISSUER_ID, "issuerId"); + requestObj.put(BadgingJsonKey.BADGE_CLASS_ID, "badgeId"); + requestObj.put(BadgingJsonKey.ASSERTION_ID, ""); + request.setRequest(requestObj); + try { + BadgeAssertionValidator.validategetBadgeAssertion(request); + response = true; + } catch (ProjectCommonException e) { + assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); + assertEquals(ResponseCode.assertionIdRequired.getErrorCode(), e.getCode()); + } + assertEquals(false, response); + } + + @Test + public void getAssertionList() { + Request request = new Request(); + boolean response = false; + List list = new ArrayList<>(); + for (int i = 0; i < 2; i++) { + list.add("assertionId-" + i); + } + Map> filterMap = new HashMap<>(); + filterMap.put(BadgingJsonKey.ASSERTIONS, list); + + request.getRequest().put(JsonKey.FILTERS, filterMap); + try { + BadgeAssertionValidator.validateGetAssertionList(request); + response = true; + } catch (ProjectCommonException e) { + Assert.assertNull(e); + } + assertEquals(true, response); + } + + @Test + public void getAssertionListWithWrongKey() { + Request request = new Request(); + boolean response = false; + Map requestObj = new HashMap<>(); + requestObj.put(BadgingJsonKey.ISSUER_ID, "issuerSlug"); + requestObj.put(BadgingJsonKey.BADGE_CLASS_ID, "classslug"); + requestObj.put(BadgingJsonKey.ASSERTION_ID, "someAssertionId"); + List> list = new ArrayList<>(); + list.add(requestObj); + request.getRequest().put("list", list); + try { + BadgeAssertionValidator.validateGetAssertionList(request); + response = true; + } catch (ProjectCommonException e) { + assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); + assertEquals(ResponseCode.invalidRequestData.getErrorCode(), e.getCode()); + } + assertEquals(false, response); + } + + @Test + public void getAssertionListWithExceedSize() { + Request request = new Request(); + boolean response = false; + List list = new ArrayList<>(); + for (int i = 0; i < 50; i++) { + list.add("assertionId-" + i); + } + Map> filterMap = new HashMap<>(); + filterMap.put(BadgingJsonKey.ASSERTIONS, list); + + request.getRequest().put(JsonKey.FILTERS, filterMap); + try { + BadgeAssertionValidator.validateGetAssertionList(request); + response = true; + } catch (ProjectCommonException e) { + assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); + assertEquals(ResponseCode.sizeLimitExceed.getErrorCode(), e.getCode()); + } + assertEquals(false, response); + } + + @Test + public void getAssertionListWithMaxSize() { + Request request = new Request(); + boolean response = false; + List list = new ArrayList<>(); + for (int i = 0; i < 5; i++) { + list.add("assertionId-" + i); + } + Map> filterMap = new HashMap<>(); + filterMap.put(BadgingJsonKey.ASSERTIONS, list); + + request.getRequest().put(JsonKey.FILTERS, filterMap); + try { + BadgeAssertionValidator.validateGetAssertionList(request); + response = true; + } catch (ProjectCommonException e) { + assertNotNull(e); + } + assertEquals(true, response); + } } diff --git a/service/test/controllers/badging/validator/RevokeAssertionTest.java b/service/test/controllers/badging/validator/RevokeAssertionTest.java index 241828fa53..231ee965bb 100644 --- a/service/test/controllers/badging/validator/RevokeAssertionTest.java +++ b/service/test/controllers/badging/validator/RevokeAssertionTest.java @@ -4,7 +4,6 @@ import java.util.HashMap; import java.util.Map; - import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; @@ -14,119 +13,119 @@ import org.sunbird.common.models.util.BadgingJsonKey; import org.sunbird.common.request.Request; import org.sunbird.common.responsecode.ResponseCode; + /** * Test class for Badge assertion revoke request data. - * @author Manzarul * + * @author Manzarul */ @RunWith(PowerMockRunner.class) @PowerMockIgnore({"javax.management.*", "javax.net.ssl.*", "javax.security.*"}) public class RevokeAssertionTest { - @Test - public void revokeAssertion() { - Request request = new Request(); - boolean response = false; - Map requestObj = new HashMap<>(); - requestObj.put(BadgingJsonKey.ISSUER_ID, "issuerSlug"); - requestObj.put(BadgingJsonKey.BADGE_CLASS_ID, "classslug"); - requestObj.put(BadgingJsonKey.ASSERTION_ID, "someAssertionId"); - requestObj.put(BadgingJsonKey.REVOCATION_REASON, "some reason"); - requestObj.put(BadgingJsonKey.RECIPIENT_ID, "userIdorContentId"); - requestObj.put(BadgingJsonKey.RECIPIENT_TYPE, "user"); - request.setRequest(requestObj); - try { - BadgeAssertionValidator.validateRevokeAssertion(request); - response = true; - } catch (ProjectCommonException e) { - Assert.assertNull(e); - } - assertEquals(true, response); - } + @Test + public void revokeAssertion() { + Request request = new Request(); + boolean response = false; + Map requestObj = new HashMap<>(); + requestObj.put(BadgingJsonKey.ISSUER_ID, "issuerSlug"); + requestObj.put(BadgingJsonKey.BADGE_CLASS_ID, "classslug"); + requestObj.put(BadgingJsonKey.ASSERTION_ID, "someAssertionId"); + requestObj.put(BadgingJsonKey.REVOCATION_REASON, "some reason"); + requestObj.put(BadgingJsonKey.RECIPIENT_ID, "userIdorContentId"); + requestObj.put(BadgingJsonKey.RECIPIENT_TYPE, "user"); + request.setRequest(requestObj); + try { + BadgeAssertionValidator.validateRevokeAssertion(request); + response = true; + } catch (ProjectCommonException e) { + Assert.assertNull(e); + } + assertEquals(true, response); + } + + @Test + public void revoeWithemptyReason() { + Request request = new Request(); + boolean response = false; + Map requestObj = new HashMap<>(); + requestObj.put(BadgingJsonKey.ISSUER_ID, "issuerSlug"); + requestObj.put(BadgingJsonKey.BADGE_CLASS_ID, "classslug"); + requestObj.put(BadgingJsonKey.ASSERTION_ID, "someAssertionId"); + requestObj.put(BadgingJsonKey.REVOCATION_REASON, " "); + requestObj.put(BadgingJsonKey.RECIPIENT_ID, "userIdorContentId"); + requestObj.put(BadgingJsonKey.RECIPIENT_TYPE, "user"); + request.setRequest(requestObj); + try { + BadgeAssertionValidator.validateRevokeAssertion(request); + response = true; + } catch (ProjectCommonException e) { + assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); + assertEquals(ResponseCode.revocationReasonRequired.getErrorCode(), e.getCode()); + } + assertEquals(false, response); + } + + @Test + public void revokeWithEmptyBadgeId() { + Request request = new Request(); + boolean response = false; + Map requestObj = new HashMap<>(); + requestObj.put(BadgingJsonKey.ISSUER_ID, "issuerSlug"); + requestObj.put(BadgingJsonKey.BADGE_CLASS_ID, ""); + requestObj.put(BadgingJsonKey.ASSERTION_ID, "someAssertionId"); + requestObj.put(BadgingJsonKey.REVOCATION_REASON, "some reason"); + requestObj.put(BadgingJsonKey.RECIPIENT_ID, "userIdorContentId"); + requestObj.put(BadgingJsonKey.RECIPIENT_TYPE, "user"); + request.setRequest(requestObj); + try { + BadgeAssertionValidator.validateRevokeAssertion(request); + response = true; + } catch (ProjectCommonException e) { + Assert.assertNull(e); + } + assertEquals(true, response); + } + + @Test + public void revokeWithOutIssuer() { + Request request = new Request(); + boolean response = false; + Map requestObj = new HashMap<>(); + requestObj.put(BadgingJsonKey.BADGE_CLASS_ID, "classslug"); + requestObj.put(BadgingJsonKey.ASSERTION_ID, "someAssertionId"); + requestObj.put(BadgingJsonKey.REVOCATION_REASON, "some reason"); + requestObj.put(BadgingJsonKey.RECIPIENT_ID, "userIdorContentId"); + requestObj.put(BadgingJsonKey.RECIPIENT_TYPE, "user"); + request.setRequest(requestObj); + try { + BadgeAssertionValidator.validateRevokeAssertion(request); + response = true; + } catch (ProjectCommonException e) { + Assert.assertNull(e); + } + assertEquals(true, response); + } - @Test - public void revoeWithemptyReason() { - Request request = new Request(); - boolean response = false; - Map requestObj = new HashMap<>(); - requestObj.put(BadgingJsonKey.ISSUER_ID, "issuerSlug"); - requestObj.put(BadgingJsonKey.BADGE_CLASS_ID, "classslug"); - requestObj.put(BadgingJsonKey.ASSERTION_ID, "someAssertionId"); - requestObj.put(BadgingJsonKey.REVOCATION_REASON, " "); - requestObj.put(BadgingJsonKey.RECIPIENT_ID, "userIdorContentId"); - requestObj.put(BadgingJsonKey.RECIPIENT_TYPE, "user"); - request.setRequest(requestObj); - try { - BadgeAssertionValidator.validateRevokeAssertion(request); - response = true; - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.revocationReasonRequired.getErrorCode(), e.getCode()); - } - assertEquals(false, response); - } - - @Test - public void revokeWithEmptyBadgeId() { - Request request = new Request(); - boolean response = false; - Map requestObj = new HashMap<>(); - requestObj.put(BadgingJsonKey.ISSUER_ID, "issuerSlug"); - requestObj.put(BadgingJsonKey.BADGE_CLASS_ID, ""); - requestObj.put(BadgingJsonKey.ASSERTION_ID, "someAssertionId"); - requestObj.put(BadgingJsonKey.REVOCATION_REASON, "some reason"); - requestObj.put(BadgingJsonKey.RECIPIENT_ID, "userIdorContentId"); - requestObj.put(BadgingJsonKey.RECIPIENT_TYPE, "user"); - request.setRequest(requestObj); - try { - BadgeAssertionValidator.validateRevokeAssertion(request); - response = true; - } catch (ProjectCommonException e) { - Assert.assertNull(e); - } - assertEquals(true, response); - } - - @Test - public void revokeWithOutIssuer() { - Request request = new Request(); - boolean response = false; - Map requestObj = new HashMap<>(); - requestObj.put(BadgingJsonKey.BADGE_CLASS_ID, "classslug"); - requestObj.put(BadgingJsonKey.ASSERTION_ID, "someAssertionId"); - requestObj.put(BadgingJsonKey.REVOCATION_REASON, "some reason"); - requestObj.put(BadgingJsonKey.RECIPIENT_ID, "userIdorContentId"); - requestObj.put(BadgingJsonKey.RECIPIENT_TYPE, "user"); - request.setRequest(requestObj); - try { - BadgeAssertionValidator.validateRevokeAssertion(request); - response = true; - } catch (ProjectCommonException e) { - Assert.assertNull(e); - } - assertEquals(true, response); - } - - @Test - public void revokeWithInvalidRecipient() { - Request request = new Request(); - boolean response = false; - Map requestObj = new HashMap<>(); - requestObj.put(BadgingJsonKey.ISSUER_ID, "issuerSlug"); - requestObj.put(BadgingJsonKey.BADGE_CLASS_ID, "badgeId"); - requestObj.put(BadgingJsonKey.ASSERTION_ID, "someAssertionId"); - requestObj.put(BadgingJsonKey.REVOCATION_REASON, "some reason"); - requestObj.put(BadgingJsonKey.RECIPIENT_ID, "userIdorContentId"); - requestObj.put(BadgingJsonKey.RECIPIENT_TYPE, "user-1"); - request.setRequest(requestObj); - try { - BadgeAssertionValidator.validateRevokeAssertion(request); - response = true; - } catch (ProjectCommonException e) { - assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); - assertEquals(ResponseCode.invalidRecipientType.getErrorCode(), e.getCode()); - } - assertEquals(false, response); - } - + @Test + public void revokeWithInvalidRecipient() { + Request request = new Request(); + boolean response = false; + Map requestObj = new HashMap<>(); + requestObj.put(BadgingJsonKey.ISSUER_ID, "issuerSlug"); + requestObj.put(BadgingJsonKey.BADGE_CLASS_ID, "badgeId"); + requestObj.put(BadgingJsonKey.ASSERTION_ID, "someAssertionId"); + requestObj.put(BadgingJsonKey.REVOCATION_REASON, "some reason"); + requestObj.put(BadgingJsonKey.RECIPIENT_ID, "userIdorContentId"); + requestObj.put(BadgingJsonKey.RECIPIENT_TYPE, "user-1"); + request.setRequest(requestObj); + try { + BadgeAssertionValidator.validateRevokeAssertion(request); + response = true; + } catch (ProjectCommonException e) { + assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); + assertEquals(ResponseCode.invalidRecipientType.getErrorCode(), e.getCode()); + } + assertEquals(false, response); + } } diff --git a/service/test/controllers/bulkapimanagement/BulkUploadControllerTest.java b/service/test/controllers/bulkapimanagement/BulkUploadControllerTest.java index 64a4290541..ec2f36ccc6 100644 --- a/service/test/controllers/bulkapimanagement/BulkUploadControllerTest.java +++ b/service/test/controllers/bulkapimanagement/BulkUploadControllerTest.java @@ -4,11 +4,17 @@ import static org.powermock.api.mockito.PowerMockito.when; import static play.test.Helpers.route; +import akka.actor.ActorRef; +import akka.actor.ActorSystem; +import akka.actor.Props; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import controllers.BaseController; +import controllers.DummyActor; import java.io.IOException; import java.nio.charset.Charset; import java.util.HashMap; import java.util.Map; - import org.junit.BeforeClass; import org.junit.FixMethodOrder; import org.junit.Test; @@ -22,15 +28,6 @@ import org.sunbird.common.models.util.JsonKey; import org.sunbird.common.models.util.ProjectLogger; import org.sunbird.common.request.HeaderParam; - -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - -import akka.actor.ActorRef; -import akka.actor.ActorSystem; -import akka.actor.Props; -import controllers.BaseController; -import controllers.DummyActor; import play.libs.Json; import play.mvc.Http.RequestBuilder; import play.mvc.Result; @@ -38,9 +35,7 @@ import play.test.Helpers; import util.RequestInterceptor; -/** - * Created by arvind on 4/12/17. - */ +/** Created by arvind on 4/12/17. */ @FixMethodOrder(MethodSorters.NAME_ASCENDING) @RunWith(PowerMockRunner.class) @PrepareForTest(RequestInterceptor.class) @@ -48,7 +43,7 @@ public class BulkUploadControllerTest { private static FakeApplication app; - private static Map headerMap; + private static Map headerMap; private static ActorSystem system; private static final Props props = Props.create(DummyActor.class); @@ -57,10 +52,11 @@ public static void startApp() { app = Helpers.fakeApplication(); Helpers.start(app); headerMap = new HashMap(); - headerMap.put(HeaderParam.X_Consumer_ID.getName(), new String[]{"Service test consumer"}); - headerMap.put(HeaderParam.X_Device_ID.getName(), new String[]{"Some Device Id"}); - headerMap.put(HeaderParam.X_Authenticated_Userid.getName(), new String[]{"Authenticated user id"}); - headerMap.put(JsonKey.MESSAGE_ID, new String[]{"Unique Message id"}); + headerMap.put(HeaderParam.X_Consumer_ID.getName(), new String[] {"Service test consumer"}); + headerMap.put(HeaderParam.X_Device_ID.getName(), new String[] {"Some Device Id"}); + headerMap.put( + HeaderParam.X_Authenticated_Userid.getName(), new String[] {"Authenticated user id"}); + headerMap.put(JsonKey.MESSAGE_ID, new String[] {"Unique Message id"}); system = ActorSystem.create("system"); ActorRef subject = system.actorOf(props); @@ -70,12 +66,13 @@ public static void startApp() { @Test public void testuploadUser() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - innerMap.put(JsonKey.DATA , "sampleStream".getBytes(Charset.defaultCharset())); - innerMap.put(JsonKey.ORGANISATION_ID , "org123"); - requestMap.put(JsonKey.REQUEST , innerMap); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + innerMap.put(JsonKey.DATA, "sampleStream".getBytes(Charset.defaultCharset())); + innerMap.put(JsonKey.ORGANISATION_ID, "org123"); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); @@ -88,12 +85,13 @@ public void testuploadUser() { @Test public void testuploadOrg() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - innerMap.put(JsonKey.DATA , "sampleStream".getBytes(Charset.defaultCharset())); - //innerMap.put(JsonKey.ORGANISATION_ID , "org123"); - requestMap.put(JsonKey.REQUEST , innerMap); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + innerMap.put(JsonKey.DATA, "sampleStream".getBytes(Charset.defaultCharset())); + // innerMap.put(JsonKey.ORGANISATION_ID , "org123"); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); @@ -106,7 +104,8 @@ public void testuploadOrg() { @Test public void testgetUploadStatus() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); RequestBuilder req = new RequestBuilder().uri("/v1/upload/status/pid").method("GET"); req.headers(headerMap); Result result = route(req); @@ -116,16 +115,18 @@ public void testgetUploadStatus() { @Test public void testbulkBatchEnrollment() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject())).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - innerMap.put(JsonKey.DATA , "sampleStream".getBytes(Charset.defaultCharset())); - //innerMap.put(JsonKey.ORGANISATION_ID , "org123"); - requestMap.put(JsonKey.REQUEST , innerMap); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + innerMap.put(JsonKey.DATA, "sampleStream".getBytes(Charset.defaultCharset())); + // innerMap.put(JsonKey.ORGANISATION_ID , "org123"); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); - RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/batch/bulk/enrollment").method("POST"); + RequestBuilder req = + new RequestBuilder().bodyJson(json).uri("/v1/batch/bulk/enrollment").method("POST"); req.headers(headerMap); Result result = route(req); assertEquals(200, result.status()); @@ -134,7 +135,8 @@ public void testbulkBatchEnrollment() { @Test public void testuserDataEncryption() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); RequestBuilder req = new RequestBuilder().uri("/v1/user/data/encrypt").method("GET"); req.headers(headerMap); Result result = route(req); @@ -144,22 +146,22 @@ public void testuserDataEncryption() { @Test public void testuserDataDecryption() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); RequestBuilder req = new RequestBuilder().uri("/v1/user/data/decrypt").method("GET"); req.headers(headerMap); Result result = route(req); assertEquals(200, result.status()); } - private static String mapToJson(Map map){ + private static String mapToJson(Map map) { ObjectMapper mapperObj = new ObjectMapper(); String jsonResp = ""; try { jsonResp = mapperObj.writeValueAsString(map); } catch (IOException e) { - ProjectLogger.log(e.getMessage(),e); + ProjectLogger.log(e.getMessage(), e); } return jsonResp; } - } diff --git a/service/test/controllers/clientmanagement/ClientControllerTest.java b/service/test/controllers/clientmanagement/ClientControllerTest.java index 16a3d34040..d70ba7ecdc 100644 --- a/service/test/controllers/clientmanagement/ClientControllerTest.java +++ b/service/test/controllers/clientmanagement/ClientControllerTest.java @@ -4,10 +4,16 @@ import static org.powermock.api.mockito.PowerMockito.when; import static play.test.Helpers.route; +import akka.actor.ActorRef; +import akka.actor.ActorSystem; +import akka.actor.Props; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import controllers.BaseController; +import controllers.DummyActor; import java.io.IOException; import java.util.HashMap; import java.util.Map; - import org.junit.BeforeClass; import org.junit.FixMethodOrder; import org.junit.Test; @@ -21,15 +27,6 @@ import org.sunbird.common.models.util.JsonKey; import org.sunbird.common.models.util.ProjectLogger; import org.sunbird.common.request.HeaderParam; - -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - -import akka.actor.ActorRef; -import akka.actor.ActorSystem; -import akka.actor.Props; -import controllers.BaseController; -import controllers.DummyActor; import play.libs.Json; import play.mvc.Http.RequestBuilder; import play.mvc.Result; @@ -37,9 +34,7 @@ import play.test.Helpers; import util.RequestInterceptor; -/** - * Created by arvind on 6/12/17. - */ +/** Created by arvind on 6/12/17. */ @FixMethodOrder(MethodSorters.NAME_ASCENDING) @RunWith(PowerMockRunner.class) @PrepareForTest(RequestInterceptor.class) @@ -47,7 +42,7 @@ public class ClientControllerTest { private static FakeApplication app; - private static Map headerMap; + private static Map headerMap; private static ActorSystem system; private static final Props props = Props.create(DummyActor.class); @@ -56,10 +51,11 @@ public static void startApp() { app = Helpers.fakeApplication(); Helpers.start(app); headerMap = new HashMap(); - headerMap.put(HeaderParam.X_Consumer_ID.getName(), new String[]{"Service test consumer"}); - headerMap.put(HeaderParam.X_Device_ID.getName(), new String[]{"Some Device Id"}); - headerMap.put(HeaderParam.X_Authenticated_Userid.getName(), new String[]{"Authenticated user id"}); - headerMap.put(JsonKey.MESSAGE_ID, new String[]{"Unique Message id"}); + headerMap.put(HeaderParam.X_Consumer_ID.getName(), new String[] {"Service test consumer"}); + headerMap.put(HeaderParam.X_Device_ID.getName(), new String[] {"Some Device Id"}); + headerMap.put( + HeaderParam.X_Authenticated_Userid.getName(), new String[] {"Authenticated user id"}); + headerMap.put(JsonKey.MESSAGE_ID, new String[] {"Unique Message id"}); system = ActorSystem.create("system"); ActorRef subject = system.actorOf(props); @@ -69,15 +65,17 @@ public static void startApp() { @Test public void testregisterClient() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - innerMap.put("clientName" , "ap"); - requestMap.put(JsonKey.REQUEST , innerMap); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + innerMap.put("clientName", "ap"); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); - RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/client/register").method("POST"); + RequestBuilder req = + new RequestBuilder().bodyJson(json).uri("/v1/client/register").method("POST"); req.headers(headerMap); Result result = route(req); assertEquals(200, result.status()); @@ -86,18 +84,20 @@ public void testregisterClient() { @Test public void testupdateClientKey() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - innerMap.put("x-authenticated-client-token" , "ap"); - innerMap.put("x-authenticated-client-id","123"); - requestMap.put(JsonKey.REQUEST , innerMap); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + innerMap.put("x-authenticated-client-token", "ap"); + innerMap.put("x-authenticated-client-id", "123"); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); - RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/client/key/update").method("PATCH"); - headerMap.put("x-authenticated-client-token" , new String[]{"ap"}); - headerMap.put("x-authenticated-client-id",new String[]{"123"}); + RequestBuilder req = + new RequestBuilder().bodyJson(json).uri("/v1/client/key/update").method("PATCH"); + headerMap.put("x-authenticated-client-token", new String[] {"ap"}); + headerMap.put("x-authenticated-client-id", new String[] {"123"}); req.headers(headerMap); Result result = route(req); assertEquals(200, result.status()); @@ -106,22 +106,23 @@ public void testupdateClientKey() { @Test public void testgetClientKey() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - RequestBuilder req = new RequestBuilder().uri("/v1/client/key/read/clientId?type=channel").method("GET"); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + RequestBuilder req = + new RequestBuilder().uri("/v1/client/key/read/clientId?type=channel").method("GET"); req.headers(headerMap); Result result = route(req); assertEquals(200, result.status()); } - private static String mapToJson(Map map){ + private static String mapToJson(Map map) { ObjectMapper mapperObj = new ObjectMapper(); String jsonResp = ""; try { jsonResp = mapperObj.writeValueAsString(map); } catch (IOException e) { - ProjectLogger.log(e.getMessage(),e); + ProjectLogger.log(e.getMessage(), e); } return jsonResp; } - } diff --git a/service/test/controllers/config/ApplicationConfigControllerTest.java b/service/test/controllers/config/ApplicationConfigControllerTest.java index 8afebedd03..40c22b5eac 100644 --- a/service/test/controllers/config/ApplicationConfigControllerTest.java +++ b/service/test/controllers/config/ApplicationConfigControllerTest.java @@ -4,13 +4,19 @@ import static org.powermock.api.mockito.PowerMockito.when; import static play.test.Helpers.route; +import akka.actor.ActorRef; +import akka.actor.ActorSystem; +import akka.actor.Props; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import controllers.BaseController; +import controllers.DummyActor; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; - import org.junit.BeforeClass; import org.junit.FixMethodOrder; import org.junit.Test; @@ -25,15 +31,6 @@ import org.sunbird.common.models.util.ProjectLogger; import org.sunbird.common.models.util.PropertiesCache; import org.sunbird.common.request.HeaderParam; - -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - -import akka.actor.ActorRef; -import akka.actor.ActorSystem; -import akka.actor.Props; -import controllers.BaseController; -import controllers.DummyActor; import play.libs.Json; import play.mvc.Http.RequestBuilder; import play.mvc.Result; @@ -41,9 +38,7 @@ import play.test.Helpers; import util.RequestInterceptor; -/** - * Created by arvind on 6/12/17. - */ +/** Created by arvind on 6/12/17. */ @FixMethodOrder(MethodSorters.NAME_ASCENDING) @RunWith(PowerMockRunner.class) @PrepareForTest(RequestInterceptor.class) @@ -51,7 +46,7 @@ public class ApplicationConfigControllerTest { private static FakeApplication app; - private static Map headerMap; + private static Map headerMap; private static ActorSystem system; private static final Props props = Props.create(DummyActor.class); @@ -60,10 +55,11 @@ public static void startApp() { app = Helpers.fakeApplication(); Helpers.start(app); headerMap = new HashMap(); - headerMap.put(HeaderParam.X_Consumer_ID.getName(), new String[]{"Service test consumer"}); - headerMap.put(HeaderParam.X_Device_ID.getName(), new String[]{"Some Device Id"}); - headerMap.put(HeaderParam.X_Authenticated_Userid.getName(), new String[]{"Authenticated user id"}); - headerMap.put(JsonKey.MESSAGE_ID, new String[]{"Unique Message id"}); + headerMap.put(HeaderParam.X_Consumer_ID.getName(), new String[] {"Service test consumer"}); + headerMap.put(HeaderParam.X_Device_ID.getName(), new String[] {"Some Device Id"}); + headerMap.put( + HeaderParam.X_Authenticated_Userid.getName(), new String[] {"Authenticated user id"}); + headerMap.put(JsonKey.MESSAGE_ID, new String[] {"Unique Message id"}); system = ActorSystem.create("system"); ActorRef subject = system.actorOf(props); @@ -73,34 +69,39 @@ public static void startApp() { @Test public void testupdateSystemSettings() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - List list = new ArrayList(Arrays.asList(PropertiesCache.getInstance().getProperty("system_settings_properties").split(","))); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + List list = + new ArrayList( + Arrays.asList( + PropertiesCache.getInstance() + .getProperty("system_settings_properties") + .split(","))); - if(list.size()>0){ - innerMap.put(list.get(0),list.get(0)); - requestMap.put(JsonKey.REQUEST , innerMap); + if (list.size() > 0) { + innerMap.put(list.get(0), list.get(0)); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); - RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/system/settings").method("POST"); + RequestBuilder req = + new RequestBuilder().bodyJson(json).uri("/v1/system/settings").method("POST"); req.headers(headerMap); Result result = route(req); assertEquals(200, result.status()); } - } - private static String mapToJson(Map map){ + private static String mapToJson(Map map) { ObjectMapper mapperObj = new ObjectMapper(); String jsonResp = ""; try { jsonResp = mapperObj.writeValueAsString(map); } catch (IOException e) { - ProjectLogger.log(e.getMessage(),e); + ProjectLogger.log(e.getMessage(), e); } return jsonResp; } - } diff --git a/service/test/controllers/coursemanagement/CourseBatchControllerTest.java b/service/test/controllers/coursemanagement/CourseBatchControllerTest.java index 0924d24fd4..368c09318e 100644 --- a/service/test/controllers/coursemanagement/CourseBatchControllerTest.java +++ b/service/test/controllers/coursemanagement/CourseBatchControllerTest.java @@ -4,13 +4,19 @@ import static org.powermock.api.mockito.PowerMockito.when; import static play.test.Helpers.route; +import akka.actor.ActorRef; +import akka.actor.ActorSystem; +import akka.actor.Props; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import controllers.BaseController; +import controllers.DummyActor; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.Map; - import org.junit.BeforeClass; import org.junit.FixMethodOrder; import org.junit.Test; @@ -24,15 +30,6 @@ import org.sunbird.common.models.util.JsonKey; import org.sunbird.common.models.util.ProjectLogger; import org.sunbird.common.request.HeaderParam; - -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - -import akka.actor.ActorRef; -import akka.actor.ActorSystem; -import akka.actor.Props; -import controllers.BaseController; -import controllers.DummyActor; import play.libs.Json; import play.mvc.Http.RequestBuilder; import play.mvc.Result; @@ -40,9 +37,7 @@ import play.test.Helpers; import util.RequestInterceptor; -/** - * Created by arvind on 1/12/17. - */ +/** Created by arvind on 1/12/17. */ @FixMethodOrder(MethodSorters.NAME_ASCENDING) @RunWith(PowerMockRunner.class) @PrepareForTest(RequestInterceptor.class) @@ -50,7 +45,7 @@ public class CourseBatchControllerTest { private static FakeApplication app; - private static Map headerMap; + private static Map headerMap; private static ActorSystem system; private static final Props props = Props.create(DummyActor.class); @@ -59,10 +54,11 @@ public static void startApp() { app = Helpers.fakeApplication(); Helpers.start(app); headerMap = new HashMap(); - headerMap.put(HeaderParam.X_Consumer_ID.getName(), new String[]{"Service test consumer"}); - headerMap.put(HeaderParam.X_Device_ID.getName(), new String[]{"Some Device Id"}); - headerMap.put(HeaderParam.X_Authenticated_Userid.getName(), new String[]{"Authenticated user id"}); - headerMap.put(JsonKey.MESSAGE_ID, new String[]{"Unique Message id"}); + headerMap.put(HeaderParam.X_Consumer_ID.getName(), new String[] {"Service test consumer"}); + headerMap.put(HeaderParam.X_Device_ID.getName(), new String[] {"Some Device Id"}); + headerMap.put( + HeaderParam.X_Authenticated_Userid.getName(), new String[] {"Authenticated user id"}); + headerMap.put(JsonKey.MESSAGE_ID, new String[] {"Unique Message id"}); system = ActorSystem.create("system"); ActorRef subject = system.actorOf(props); @@ -72,24 +68,26 @@ public static void startApp() { @Test public void testcreateBatch() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - innerMap.put(JsonKey.COURSE_ID , "org123"); - innerMap.put(JsonKey.NAME ,"IT BATCH"); - innerMap.put(JsonKey.ENROLLMENT_TYPE , JsonKey.INVITE_ONLY); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + innerMap.put(JsonKey.COURSE_ID, "org123"); + innerMap.put(JsonKey.NAME, "IT BATCH"); + innerMap.put(JsonKey.ENROLLMENT_TYPE, JsonKey.INVITE_ONLY); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); Date currentdate = new Date(); Calendar calendar = Calendar.getInstance(); - calendar.add(Calendar.DAY_OF_MONTH , 2); + calendar.add(Calendar.DAY_OF_MONTH, 2); Date futureDate = calendar.getTime(); - innerMap.put(JsonKey.START_DATE , format.format(currentdate)); - innerMap.put(JsonKey.END_DATE , format.format(futureDate)); - requestMap.put(JsonKey.REQUEST , innerMap); + innerMap.put(JsonKey.START_DATE, format.format(currentdate)); + innerMap.put(JsonKey.END_DATE, format.format(futureDate)); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); - RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/course/batch/create").method("POST"); + RequestBuilder req = + new RequestBuilder().bodyJson(json).uri("/v1/course/batch/create").method("POST"); req.headers(headerMap); Result result = route(req); assertEquals(200, result.status()); @@ -98,24 +96,26 @@ public void testcreateBatch() { @Test public void testcreateBatchWithInvalidEnrollmentType() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - innerMap.put(JsonKey.COURSE_ID , "org123"); - innerMap.put(JsonKey.NAME ,"IT BATCH"); - innerMap.put(JsonKey.ENROLLMENT_TYPE , "inlaid_invite_type"); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + innerMap.put(JsonKey.COURSE_ID, "org123"); + innerMap.put(JsonKey.NAME, "IT BATCH"); + innerMap.put(JsonKey.ENROLLMENT_TYPE, "inlaid_invite_type"); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); Date currentdate = new Date(); Calendar calendar = Calendar.getInstance(); - calendar.add(Calendar.DAY_OF_MONTH , 2); + calendar.add(Calendar.DAY_OF_MONTH, 2); Date futureDate = calendar.getTime(); - innerMap.put(JsonKey.START_DATE , format.format(currentdate)); - innerMap.put(JsonKey.END_DATE , format.format(futureDate)); - requestMap.put(JsonKey.REQUEST , innerMap); + innerMap.put(JsonKey.START_DATE, format.format(currentdate)); + innerMap.put(JsonKey.END_DATE, format.format(futureDate)); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); - RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/course/batch/create").method("POST"); + RequestBuilder req = + new RequestBuilder().bodyJson(json).uri("/v1/course/batch/create").method("POST"); req.headers(headerMap); Result result = route(req); assertEquals(400, result.status()); @@ -124,24 +124,26 @@ public void testcreateBatchWithInvalidEnrollmentType() { @Test public void testupdateBatch() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - innerMap.put(JsonKey.COURSE_ID , "org123"); - innerMap.put(JsonKey.NAME ,"IT BATCH UPDATED"); - innerMap.put(JsonKey.ENROLLMENT_TYPE , JsonKey.INVITE_ONLY); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + innerMap.put(JsonKey.COURSE_ID, "org123"); + innerMap.put(JsonKey.NAME, "IT BATCH UPDATED"); + innerMap.put(JsonKey.ENROLLMENT_TYPE, JsonKey.INVITE_ONLY); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); Date currentdate = new Date(); Calendar calendar = Calendar.getInstance(); - calendar.add(Calendar.DAY_OF_MONTH , 2); + calendar.add(Calendar.DAY_OF_MONTH, 2); Date futureDate = calendar.getTime(); - innerMap.put(JsonKey.START_DATE , format.format(currentdate)); - innerMap.put(JsonKey.END_DATE , format.format(futureDate)); - requestMap.put(JsonKey.REQUEST , innerMap); + innerMap.put(JsonKey.START_DATE, format.format(currentdate)); + innerMap.put(JsonKey.END_DATE, format.format(futureDate)); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); - RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/course/batch/update").method("PATCH"); + RequestBuilder req = + new RequestBuilder().bodyJson(json).uri("/v1/course/batch/update").method("PATCH"); req.headers(headerMap); Result result = route(req); assertEquals(200, result.status()); @@ -150,16 +152,21 @@ public void testupdateBatch() { @Test public void testaddUserToBatch() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - innerMap.put(JsonKey.BATCH_ID , "batch123"); - innerMap.put(JsonKey.USER_IDs ,"LIST OF USER IDs"); - requestMap.put(JsonKey.REQUEST , innerMap); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + innerMap.put(JsonKey.BATCH_ID, "batch123"); + innerMap.put(JsonKey.USER_IDs, "LIST OF USER IDs"); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); - RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/course/batch/users/add/batchid").method("POST"); + RequestBuilder req = + new RequestBuilder() + .bodyJson(json) + .uri("/v1/course/batch/users/add/batchid") + .method("POST"); req.headers(headerMap); Result result = route(req); assertEquals(200, result.status()); @@ -168,16 +175,21 @@ public void testaddUserToBatch() { @Test public void testaddUserToBatchWithUserIdsNull() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - innerMap.put(JsonKey.BATCH_ID , "batch123"); - innerMap.put(JsonKey.USER_IDs ,null); - requestMap.put(JsonKey.REQUEST , innerMap); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + innerMap.put(JsonKey.BATCH_ID, "batch123"); + innerMap.put(JsonKey.USER_IDs, null); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); - RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/course/batch/users/add/batchid").method("POST"); + RequestBuilder req = + new RequestBuilder() + .bodyJson(json) + .uri("/v1/course/batch/users/add/batchid") + .method("POST"); req.headers(headerMap); Result result = route(req); assertEquals(400, result.status()); @@ -186,16 +198,18 @@ public void testaddUserToBatchWithUserIdsNull() { @Test public void testremoveUsersFromBatch() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - innerMap.put(JsonKey.BATCH_ID , "batch123"); - innerMap.put(JsonKey.USER_IDs ,"LIST OF USER IDs"); - requestMap.put(JsonKey.REQUEST , innerMap); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + innerMap.put(JsonKey.BATCH_ID, "batch123"); + innerMap.put(JsonKey.USER_IDs, "LIST OF USER IDs"); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); - RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/course/batch/users/remove").method("POST"); + RequestBuilder req = + new RequestBuilder().bodyJson(json).uri("/v1/course/batch/users/remove").method("POST"); req.headers(headerMap); Result result = route(req); assertEquals(200, result.status()); @@ -204,7 +218,8 @@ public void testremoveUsersFromBatch() { @Test public void testgetBatch() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); RequestBuilder req = new RequestBuilder().uri("/v1/course/batch/read/batchId").method("GET"); req.headers(headerMap); Result result = route(req); @@ -214,29 +229,30 @@ public void testgetBatch() { @Test public void testsearchBatch() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - innerMap.put(JsonKey.FILTERS , "batch123"); - requestMap.put(JsonKey.REQUEST , innerMap); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + innerMap.put(JsonKey.FILTERS, "batch123"); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); - RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/course/batch/search").method("POST"); + RequestBuilder req = + new RequestBuilder().bodyJson(json).uri("/v1/course/batch/search").method("POST"); req.headers(headerMap); Result result = route(req); assertEquals(200, result.status()); } - private static String mapToJson(Map map){ + private static String mapToJson(Map map) { ObjectMapper mapperObj = new ObjectMapper(); String jsonResp = ""; try { jsonResp = mapperObj.writeValueAsString(map); } catch (IOException e) { - ProjectLogger.log(e.getMessage(),e); + ProjectLogger.log(e.getMessage(), e); } return jsonResp; } - } diff --git a/service/test/controllers/coursemanagement/CourseControllerTest.java b/service/test/controllers/coursemanagement/CourseControllerTest.java index 56d2ecab54..dd2eac1826 100644 --- a/service/test/controllers/coursemanagement/CourseControllerTest.java +++ b/service/test/controllers/coursemanagement/CourseControllerTest.java @@ -4,12 +4,18 @@ import static org.powermock.api.mockito.PowerMockito.when; import static play.test.Helpers.route; +import akka.actor.ActorRef; +import akka.actor.ActorSystem; +import akka.actor.Props; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import controllers.BaseController; +import controllers.DummyActor; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; - import org.junit.BeforeClass; import org.junit.FixMethodOrder; import org.junit.Test; @@ -23,15 +29,6 @@ import org.sunbird.common.models.util.JsonKey; import org.sunbird.common.models.util.ProjectLogger; import org.sunbird.common.request.HeaderParam; - -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - -import akka.actor.ActorRef; -import akka.actor.ActorSystem; -import akka.actor.Props; -import controllers.BaseController; -import controllers.DummyActor; import play.libs.Json; import play.mvc.Http.RequestBuilder; import play.mvc.Result; @@ -39,9 +36,7 @@ import play.test.Helpers; import util.RequestInterceptor; -/** - * Created by arvind on 19/12/17. - */ +/** Created by arvind on 19/12/17. */ @FixMethodOrder(MethodSorters.NAME_ASCENDING) @RunWith(PowerMockRunner.class) @PrepareForTest(RequestInterceptor.class) @@ -49,7 +44,7 @@ public class CourseControllerTest { private static FakeApplication app; - private static Map headerMap; + private static Map headerMap; private static ActorSystem system; private static final Props props = Props.create(DummyActor.class); @@ -58,10 +53,11 @@ public static void startApp() { app = Helpers.fakeApplication(); Helpers.start(app); headerMap = new HashMap(); - headerMap.put(HeaderParam.X_Consumer_ID.getName(), new String[]{"Service test consumer"}); - headerMap.put(HeaderParam.X_Device_ID.getName(), new String[]{"Some Device Id"}); - headerMap.put(HeaderParam.X_Authenticated_Userid.getName(), new String[]{"Authenticated user id"}); - headerMap.put(JsonKey.MESSAGE_ID, new String[]{"Unique Message id"}); + headerMap.put(HeaderParam.X_Consumer_ID.getName(), new String[] {"Service test consumer"}); + headerMap.put(HeaderParam.X_Device_ID.getName(), new String[] {"Some Device Id"}); + headerMap.put( + HeaderParam.X_Authenticated_Userid.getName(), new String[] {"Authenticated user id"}); + headerMap.put(JsonKey.MESSAGE_ID, new String[] {"Unique Message id"}); system = ActorSystem.create("system"); ActorRef subject = system.actorOf(props); @@ -71,18 +67,20 @@ public static void startApp() { @Test public void testcreateCourse() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - innerMap.put(JsonKey.BATCH_ID , "batch123"); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + innerMap.put(JsonKey.BATCH_ID, "batch123"); List userIds = new ArrayList(); userIds.add("123"); - innerMap.put(JsonKey.USER_IDs ,userIds); - requestMap.put(JsonKey.REQUEST , innerMap); + innerMap.put(JsonKey.USER_IDs, userIds); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); - RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/course/create").method("POST"); + RequestBuilder req = + new RequestBuilder().bodyJson(json).uri("/v1/course/create").method("POST"); req.headers(headerMap); Result result = route(req); assertEquals(200, result.status()); @@ -91,15 +89,17 @@ public void testcreateCourse() { @Test public void testcreateCourseWithInvalidData() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - innerMap.put(JsonKey.BATCH_ID , "batch123"); - requestMap.put(JsonKey.REQUEST , innerMap); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + innerMap.put(JsonKey.BATCH_ID, "batch123"); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); - RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/course/create").method("POST"); + RequestBuilder req = + new RequestBuilder().bodyJson(json).uri("/v1/course/create").method("POST"); req.headers(headerMap); Result result = route(req); assertEquals(400, result.status()); @@ -108,15 +108,17 @@ public void testcreateCourseWithInvalidData() { @Test public void testupdateCourse() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - innerMap.put(JsonKey.COURSE_ID , "course001"); - requestMap.put(JsonKey.REQUEST , innerMap); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + innerMap.put(JsonKey.COURSE_ID, "course001"); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); - RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/course/update").method("PATCH"); + RequestBuilder req = + new RequestBuilder().bodyJson(json).uri("/v1/course/update").method("PATCH"); req.headers(headerMap); Result result = route(req); assertEquals(200, result.status()); @@ -125,14 +127,16 @@ public void testupdateCourse() { @Test public void testupdateCourseWithInvalidData() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - requestMap.put(JsonKey.REQUEST , innerMap); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); - RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/course/update").method("PATCH"); + RequestBuilder req = + new RequestBuilder().bodyJson(json).uri("/v1/course/update").method("PATCH"); req.headers(headerMap); Result result = route(req); assertEquals(400, result.status()); @@ -141,15 +145,17 @@ public void testupdateCourseWithInvalidData() { @Test public void testpublishCourse() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - innerMap.put(JsonKey.COURSE_ID , "course001"); - requestMap.put(JsonKey.REQUEST , innerMap); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + innerMap.put(JsonKey.COURSE_ID, "course001"); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); - RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/course/publish").method("POST"); + RequestBuilder req = + new RequestBuilder().bodyJson(json).uri("/v1/course/publish").method("POST"); req.headers(headerMap); Result result = route(req); assertEquals(200, result.status()); @@ -158,14 +164,16 @@ public void testpublishCourse() { @Test public void testpublishCourseWithoutCourseId() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - requestMap.put(JsonKey.REQUEST , innerMap); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); - RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/course/publish").method("POST"); + RequestBuilder req = + new RequestBuilder().bodyJson(json).uri("/v1/course/publish").method("POST"); req.headers(headerMap); Result result = route(req); assertEquals(400, result.status()); @@ -174,15 +182,17 @@ public void testpublishCourseWithoutCourseId() { @Test public void testsearchCourse() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - innerMap.put(JsonKey.COURSE_ID , "course001"); - requestMap.put(JsonKey.REQUEST , innerMap); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + innerMap.put(JsonKey.COURSE_ID, "course001"); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); - RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/course/search").method("POST"); + RequestBuilder req = + new RequestBuilder().bodyJson(json).uri("/v1/course/search").method("POST"); req.headers(headerMap); Result result = route(req); assertEquals(200, result.status()); @@ -191,15 +201,17 @@ public void testsearchCourse() { @Test public void testdeleteCourse() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - innerMap.put(JsonKey.COURSE_ID , "course001"); - requestMap.put(JsonKey.REQUEST , innerMap); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + innerMap.put(JsonKey.COURSE_ID, "course001"); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); - RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/course/delete").method("POST"); + RequestBuilder req = + new RequestBuilder().bodyJson(json).uri("/v1/course/delete").method("POST"); req.headers(headerMap); Result result = route(req); assertEquals(200, result.status()); @@ -208,7 +220,8 @@ public void testdeleteCourse() { @Test public void testgetCourseById() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); RequestBuilder req = new RequestBuilder().uri("/v1/course/courseId").method("GET"); req.headers(headerMap); Result result = route(req); @@ -218,22 +231,22 @@ public void testgetCourseById() { @Test public void testrecommendedCourses() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); RequestBuilder req = new RequestBuilder().uri("/v1/recommended/courses").method("GET"); req.headers(headerMap); Result result = route(req); assertEquals(200, result.status()); } - private static String mapToJson(Map map){ + private static String mapToJson(Map map) { ObjectMapper mapperObj = new ObjectMapper(); String jsonResp = ""; try { jsonResp = mapperObj.writeValueAsString(map); } catch (IOException e) { - ProjectLogger.log(e.getMessage(),e); + ProjectLogger.log(e.getMessage(), e); } return jsonResp; } - } diff --git a/service/test/controllers/datapersistence/DbOperationControllerTest.java b/service/test/controllers/datapersistence/DbOperationControllerTest.java index 1e5d38abf9..a6636704ed 100644 --- a/service/test/controllers/datapersistence/DbOperationControllerTest.java +++ b/service/test/controllers/datapersistence/DbOperationControllerTest.java @@ -4,12 +4,18 @@ import static org.powermock.api.mockito.PowerMockito.when; import static play.test.Helpers.route; +import akka.actor.ActorRef; +import akka.actor.ActorSystem; +import akka.actor.Props; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import controllers.BaseController; +import controllers.DummyActor; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; - import org.junit.BeforeClass; import org.junit.FixMethodOrder; import org.junit.Test; @@ -24,15 +30,6 @@ import org.sunbird.common.models.util.ProjectLogger; import org.sunbird.common.request.HeaderParam; import org.sunbird.learner.util.Util; - -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - -import akka.actor.ActorRef; -import akka.actor.ActorSystem; -import akka.actor.Props; -import controllers.BaseController; -import controllers.DummyActor; import play.libs.Json; import play.mvc.Http.RequestBuilder; import play.mvc.Result; @@ -40,9 +37,7 @@ import play.test.Helpers; import util.RequestInterceptor; -/** - * Created by arvind on 5/12/17. - */ +/** Created by arvind on 5/12/17. */ @FixMethodOrder(MethodSorters.NAME_ASCENDING) @RunWith(PowerMockRunner.class) @PrepareForTest(RequestInterceptor.class) @@ -50,10 +45,10 @@ public class DbOperationControllerTest { private static FakeApplication app; - private static Map headerMap; + private static Map headerMap; private static ActorSystem system; private static final Props props = Props.create(DummyActor.class); - /* private static List tableList = null; + /* private static List tableList = null; private static CassandraConnectionManager manager = CassandraConnectionMngrFactory .getObject(PropertiesCache.getInstance().getProperty(JsonKey.SUNBIRD_CASSANDRA_MODE));*/ private static String entityName = null; @@ -64,16 +59,17 @@ public class DbOperationControllerTest { @BeforeClass public static void startApp() { - //createtableList(); + // createtableList(); Util.checkCassandraDbConnections(JsonKey.SUNBIRD_PLUGIN); entityName = "announcement"; app = Helpers.fakeApplication(); Helpers.start(app); headerMap = new HashMap(); - headerMap.put(HeaderParam.X_Consumer_ID.getName(), new String[]{"Service test consumer"}); - headerMap.put(HeaderParam.X_Device_ID.getName(), new String[]{"Some Device Id"}); - headerMap.put(HeaderParam.X_Authenticated_Userid.getName(), new String[]{"Authenticated user id"}); - headerMap.put(JsonKey.MESSAGE_ID, new String[]{"Unique Message id"}); + headerMap.put(HeaderParam.X_Consumer_ID.getName(), new String[] {"Service test consumer"}); + headerMap.put(HeaderParam.X_Device_ID.getName(), new String[] {"Some Device Id"}); + headerMap.put( + HeaderParam.X_Authenticated_Userid.getName(), new String[] {"Authenticated user id"}); + headerMap.put(JsonKey.MESSAGE_ID, new String[] {"Unique Message id"}); system = ActorSystem.create("system"); ActorRef subject = system.actorOf(props); @@ -89,7 +85,7 @@ public static void startApp() { }*/ @Test - public void testAll(){ + public void testAll() { testCreate(); testCreateWithWrongEntityName(); testupdate(); @@ -97,137 +93,148 @@ public void testAll(){ testreadAll(); testsearch(); testdelete(); - + PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - innerMap.put(ENTITY_NAME , entityName); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + innerMap.put(ENTITY_NAME, entityName); List requiredFields = new ArrayList<>(); requiredFields.add("userid"); - innerMap.put(REQUIRED_FIELDS , requiredFields); + innerMap.put(REQUIRED_FIELDS, requiredFields); Map filters = new HashMap<>(); - filters.put(JsonKey.USER_ID ,"usergt78y4ry85464" ); - innerMap.put(JsonKey.FILTERS , filters); - innerMap.put(JsonKey.ID , "ggudy8d8ydyy8ddy9"); - requestMap.put(JsonKey.REQUEST , innerMap); + filters.put(JsonKey.USER_ID, "usergt78y4ry85464"); + innerMap.put(JsonKey.FILTERS, filters); + innerMap.put(JsonKey.ID, "ggudy8d8ydyy8ddy9"); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); - RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/object/search").method("POST"); + RequestBuilder req = + new RequestBuilder().bodyJson(json).uri("/v1/object/search").method("POST"); req.headers(headerMap); Result result = route(req); assertEquals(200, result.status()); } - //@Test + // @Test public void testCreate() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - innerMap.put(ENTITY_NAME , entityName); - innerMap.put(INDEXED , true); - Map payLoad = new HashMap<>(); - payLoad.put(JsonKey.USER_ID , "usergt78y4ry8"); - payLoad.put(JsonKey.ID , "ggudy8d8ydyy8ddy9"); - innerMap.put(PAYLOAD , payLoad); - requestMap.put(JsonKey.REQUEST , innerMap); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + innerMap.put(ENTITY_NAME, entityName); + innerMap.put(INDEXED, true); + Map payLoad = new HashMap<>(); + payLoad.put(JsonKey.USER_ID, "usergt78y4ry8"); + payLoad.put(JsonKey.ID, "ggudy8d8ydyy8ddy9"); + innerMap.put(PAYLOAD, payLoad); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); - RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/object/create").method("POST"); + RequestBuilder req = + new RequestBuilder().bodyJson(json).uri("/v1/object/create").method("POST"); req.headers(headerMap); Result result = route(req); assertEquals(200, result.status()); try { Thread.sleep(4000); } catch (InterruptedException e) { - ProjectLogger.log(e.getMessage(),e); + ProjectLogger.log(e.getMessage(), e); } } public void testCreateWithWrongEntityName() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - innerMap.put(ENTITY_NAME , entityName+"-wrong"); - innerMap.put(INDEXED , true); - Map payLoad = new HashMap<>(); - payLoad.put(JsonKey.USER_ID , "usergt78y4ry8"); - payLoad.put(JsonKey.ID , "ggudy8d8ydyy8ddy9"); - innerMap.put(PAYLOAD , payLoad); - requestMap.put(JsonKey.REQUEST , innerMap); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + innerMap.put(ENTITY_NAME, entityName + "-wrong"); + innerMap.put(INDEXED, true); + Map payLoad = new HashMap<>(); + payLoad.put(JsonKey.USER_ID, "usergt78y4ry8"); + payLoad.put(JsonKey.ID, "ggudy8d8ydyy8ddy9"); + innerMap.put(PAYLOAD, payLoad); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); - RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/object/create").method("POST"); + RequestBuilder req = + new RequestBuilder().bodyJson(json).uri("/v1/object/create").method("POST"); req.headers(headerMap); Result result = route(req); assertEquals(200, result.status()); } - //@Test + // @Test public void testupdate() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - innerMap.put(ENTITY_NAME , entityName); - innerMap.put(INDEXED , true); - Map payLoad = new HashMap<>(); - payLoad.put(JsonKey.USER_ID , "usergt78y4ry85464"); - payLoad.put(JsonKey.ID , "ggudy8d8ydyy8ddy9"); - innerMap.put(PAYLOAD , payLoad); - requestMap.put(JsonKey.REQUEST , innerMap); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + innerMap.put(ENTITY_NAME, entityName); + innerMap.put(INDEXED, true); + Map payLoad = new HashMap<>(); + payLoad.put(JsonKey.USER_ID, "usergt78y4ry85464"); + payLoad.put(JsonKey.ID, "ggudy8d8ydyy8ddy9"); + innerMap.put(PAYLOAD, payLoad); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); - RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/object/update").method("POST"); + RequestBuilder req = + new RequestBuilder().bodyJson(json).uri("/v1/object/update").method("POST"); req.headers(headerMap); Result result = route(req); assertEquals(200, result.status()); } - //@Test + // @Test public void testdelete() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - innerMap.put(ENTITY_NAME , entityName); - innerMap.put(INDEXED , true); - innerMap.put(JsonKey.ID , "ggudy8d8ydyy8ddy9"); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + innerMap.put(ENTITY_NAME, entityName); + innerMap.put(INDEXED, true); + innerMap.put(JsonKey.ID, "ggudy8d8ydyy8ddy9"); /*Map payLoad = new HashMap<>(); payLoad.put(JsonKey.USER_ID , "usergt78y4ry8"); payLoad.put(JsonKey.ID , "ggudy8d8ydyy8ddy9"); innerMap.put(PAYLOAD , payLoad);*/ - requestMap.put(JsonKey.REQUEST , innerMap); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); - RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/object/delete").method("POST"); + RequestBuilder req = + new RequestBuilder().bodyJson(json).uri("/v1/object/delete").method("POST"); req.headers(headerMap); Result result = route(req); assertEquals(200, result.status()); } - //@Test + // @Test public void testread() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - innerMap.put(ENTITY_NAME , entityName); - //innerMap.put(INDEXED , true); - //innerMap.put(JsonKey.USER_ID , "usergt78y4ry8"); - innerMap.put(JsonKey.ID , "ggudy8d8ydyy8ddy9"); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + innerMap.put(ENTITY_NAME, entityName); + // innerMap.put(INDEXED , true); + // innerMap.put(JsonKey.USER_ID , "usergt78y4ry8"); + innerMap.put(JsonKey.ID, "ggudy8d8ydyy8ddy9"); /*Map payLoad = new HashMap<>(); payLoad.put(JsonKey.USER_ID , "usergt78y4ry8"); payLoad.put(JsonKey.ID , "ggudy8d8ydyy8ddy9"); innerMap.put(PAYLOAD , payLoad);*/ - requestMap.put(JsonKey.REQUEST , innerMap); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); @@ -237,48 +244,51 @@ public void testread() { assertEquals(200, result.status()); } - //@Test + // @Test public void testreadAll() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - innerMap.put(ENTITY_NAME , entityName); - innerMap.put(INDEXED , true); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + innerMap.put(ENTITY_NAME, entityName); + innerMap.put(INDEXED, true); /*Map payLoad = new HashMap<>(); payLoad.put(JsonKey.USER_ID , "usergt78y4ry8"); payLoad.put(JsonKey.ID , "ggudy8d8ydyy8ddy9"); innerMap.put(PAYLOAD , payLoad);*/ - requestMap.put(JsonKey.REQUEST , innerMap); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); - RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/object/read/list").method("POST"); + RequestBuilder req = + new RequestBuilder().bodyJson(json).uri("/v1/object/read/list").method("POST"); req.headers(headerMap); Result result = route(req); assertEquals(200, result.status()); } - public void testsearch() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - innerMap.put(ENTITY_NAME , entityName); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + innerMap.put(ENTITY_NAME, entityName); List requiredFields = new ArrayList<>(); requiredFields.add("userid"); - innerMap.put(REQUIRED_FIELDS , requiredFields); + innerMap.put(REQUIRED_FIELDS, requiredFields); Map filters = new HashMap<>(); - filters.put(JsonKey.USER_ID ,"usergt78y4ry85464" ); - innerMap.put(JsonKey.FILTERS , filters); - innerMap.put(JsonKey.ID , "ggudy8d8ydyy8ddy9"); - requestMap.put(JsonKey.REQUEST , innerMap); + filters.put(JsonKey.USER_ID, "usergt78y4ry85464"); + innerMap.put(JsonKey.FILTERS, filters); + innerMap.put(JsonKey.ID, "ggudy8d8ydyy8ddy9"); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); - RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/object/search").method("POST"); + RequestBuilder req = + new RequestBuilder().bodyJson(json).uri("/v1/object/search").method("POST"); req.headers(headerMap); Result result = route(req); assertEquals(200, result.status()); @@ -286,36 +296,37 @@ public void testsearch() { public void testgetMetrics() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - innerMap.put(ENTITY_NAME , entityName); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + innerMap.put(ENTITY_NAME, entityName); List requiredFields = new ArrayList<>(); requiredFields.add("userid"); - innerMap.put(REQUIRED_FIELDS , requiredFields); + innerMap.put(REQUIRED_FIELDS, requiredFields); Map filters = new HashMap<>(); - filters.put(JsonKey.USER_ID ,"usergt78y4ry85464" ); - innerMap.put(JsonKey.FILTERS , filters); - innerMap.put(JsonKey.ID , "ggudy8d8ydyy8ddy9"); - requestMap.put(JsonKey.REQUEST , innerMap); + filters.put(JsonKey.USER_ID, "usergt78y4ry85464"); + innerMap.put(JsonKey.FILTERS, filters); + innerMap.put(JsonKey.ID, "ggudy8d8ydyy8ddy9"); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); - RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/object/metrics").method("POST"); + RequestBuilder req = + new RequestBuilder().bodyJson(json).uri("/v1/object/metrics").method("POST"); req.headers(headerMap); Result result = route(req); assertEquals(200, result.status()); } - private static String mapToJson(Map map){ + private static String mapToJson(Map map) { ObjectMapper mapperObj = new ObjectMapper(); String jsonResp = ""; try { jsonResp = mapperObj.writeValueAsString(map); } catch (IOException e) { - ProjectLogger.log(e.getMessage(),e); + ProjectLogger.log(e.getMessage(), e); } return jsonResp; } - } diff --git a/service/test/controllers/geolocation/GeoLocationControllerTest.java b/service/test/controllers/geolocation/GeoLocationControllerTest.java index 411cb81182..1d8fed4713 100644 --- a/service/test/controllers/geolocation/GeoLocationControllerTest.java +++ b/service/test/controllers/geolocation/GeoLocationControllerTest.java @@ -4,10 +4,16 @@ import static org.powermock.api.mockito.PowerMockito.when; import static play.test.Helpers.route; +import akka.actor.ActorRef; +import akka.actor.ActorSystem; +import akka.actor.Props; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import controllers.BaseController; +import controllers.DummyActor; import java.io.IOException; import java.util.HashMap; import java.util.Map; - import org.junit.BeforeClass; import org.junit.FixMethodOrder; import org.junit.Test; @@ -21,15 +27,6 @@ import org.sunbird.common.models.util.JsonKey; import org.sunbird.common.models.util.ProjectLogger; import org.sunbird.common.request.HeaderParam; - -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - -import akka.actor.ActorRef; -import akka.actor.ActorSystem; -import akka.actor.Props; -import controllers.BaseController; -import controllers.DummyActor; import play.libs.Json; import play.mvc.Http.RequestBuilder; import play.mvc.Result; @@ -37,9 +34,7 @@ import play.test.Helpers; import util.RequestInterceptor; -/** - * Created by arvind on 1/12/17. - */ +/** Created by arvind on 1/12/17. */ @FixMethodOrder(MethodSorters.NAME_ASCENDING) @RunWith(PowerMockRunner.class) @PrepareForTest(RequestInterceptor.class) @@ -47,7 +42,7 @@ public class GeoLocationControllerTest { private static FakeApplication app; - private static Map headerMap; + private static Map headerMap; private static ActorSystem system; private static final Props props = Props.create(DummyActor.class); @@ -56,10 +51,11 @@ public static void startApp() { app = Helpers.fakeApplication(); Helpers.start(app); headerMap = new HashMap(); - headerMap.put(HeaderParam.X_Consumer_ID.getName(), new String[]{"Service test consumer"}); - headerMap.put(HeaderParam.X_Device_ID.getName(), new String[]{"Some Device Id"}); - headerMap.put(HeaderParam.X_Authenticated_Userid.getName(), new String[]{"Authenticated user id"}); - headerMap.put(JsonKey.MESSAGE_ID, new String[]{"Unique Message id"}); + headerMap.put(HeaderParam.X_Consumer_ID.getName(), new String[] {"Service test consumer"}); + headerMap.put(HeaderParam.X_Device_ID.getName(), new String[] {"Some Device Id"}); + headerMap.put( + HeaderParam.X_Authenticated_Userid.getName(), new String[] {"Authenticated user id"}); + headerMap.put(JsonKey.MESSAGE_ID, new String[] {"Unique Message id"}); system = ActorSystem.create("system"); ActorRef subject = system.actorOf(props); @@ -69,15 +65,17 @@ public static void startApp() { @Test public void testcreateGeoLocation() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - innerMap.put(JsonKey.ROOT_ORG_ID , "org123"); - requestMap.put(JsonKey.REQUEST , innerMap); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + innerMap.put(JsonKey.ROOT_ORG_ID, "org123"); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); - RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/location/create").method("POST"); + RequestBuilder req = + new RequestBuilder().bodyJson(json).uri("/v1/location/create").method("POST"); req.headers(headerMap); Result result = route(req); assertEquals(200, result.status()); @@ -86,7 +84,8 @@ public void testcreateGeoLocation() { @Test public void testgetGeoLocation() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); RequestBuilder req = new RequestBuilder().uri("/v1/location/read/123").method("GET"); req.headers(headerMap); @@ -97,15 +96,17 @@ public void testgetGeoLocation() { @Test public void testupdateGeoLocation() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - innerMap.put(JsonKey.ROOT_ORG_ID , "org123"); - requestMap.put(JsonKey.REQUEST , innerMap); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + innerMap.put(JsonKey.ROOT_ORG_ID, "org123"); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); - RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/location/update/123").method("PATCH"); + RequestBuilder req = + new RequestBuilder().bodyJson(json).uri("/v1/location/update/123").method("PATCH"); req.headers(headerMap); Result result = route(req); assertEquals(200, result.status()); @@ -114,15 +115,17 @@ public void testupdateGeoLocation() { @Test public void testdeleteGeoLocation() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - innerMap.put(JsonKey.ROOT_ORG_ID , "org123"); - requestMap.put(JsonKey.REQUEST , innerMap); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + innerMap.put(JsonKey.ROOT_ORG_ID, "org123"); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); - RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/location/delete/123").method("DELETE"); + RequestBuilder req = + new RequestBuilder().bodyJson(json).uri("/v1/location/delete/123").method("DELETE"); req.headers(headerMap); Result result = route(req); assertEquals(200, result.status()); @@ -131,34 +134,35 @@ public void testdeleteGeoLocation() { @Test public void testsendNotification() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - innerMap.put(JsonKey.ROOT_ORG_ID , "org123"); - innerMap.put(JsonKey.TO,"c93"); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + innerMap.put(JsonKey.ROOT_ORG_ID, "org123"); + innerMap.put(JsonKey.TO, "c93"); Map map = new HashMap(); - map.put(JsonKey.FROM_EMAIL , "fromEmail"); - innerMap.put(JsonKey.DATA , map); - innerMap.put(JsonKey.TYPE , "fcm"); - requestMap.put(JsonKey.REQUEST , innerMap); + map.put(JsonKey.FROM_EMAIL, "fromEmail"); + innerMap.put(JsonKey.DATA, map); + innerMap.put(JsonKey.TYPE, "fcm"); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); - RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/notification/send").method("POST"); + RequestBuilder req = + new RequestBuilder().bodyJson(json).uri("/v1/notification/send").method("POST"); req.headers(headerMap); Result result = route(req); assertEquals(200, result.status()); } - private static String mapToJson(Map map){ + private static String mapToJson(Map map) { ObjectMapper mapperObj = new ObjectMapper(); String jsonResp = ""; try { jsonResp = mapperObj.writeValueAsString(map); } catch (IOException e) { - ProjectLogger.log(e.getMessage(),e); + ProjectLogger.log(e.getMessage(), e); } return jsonResp; } - } diff --git a/service/test/controllers/healthmanager/HealthControllerTest.java b/service/test/controllers/healthmanager/HealthControllerTest.java index 041d423e02..08eb11843f 100644 --- a/service/test/controllers/healthmanager/HealthControllerTest.java +++ b/service/test/controllers/healthmanager/HealthControllerTest.java @@ -4,9 +4,13 @@ import static org.powermock.api.mockito.PowerMockito.when; import static play.test.Helpers.route; +import akka.actor.ActorRef; +import akka.actor.ActorSystem; +import akka.actor.Props; +import controllers.BaseController; +import controllers.DummyActor; import java.util.HashMap; import java.util.Map; - import org.junit.BeforeClass; import org.junit.FixMethodOrder; import org.junit.Test; @@ -19,21 +23,13 @@ import org.powermock.modules.junit4.PowerMockRunner; import org.sunbird.common.models.util.JsonKey; import org.sunbird.common.request.HeaderParam; - -import akka.actor.ActorRef; -import akka.actor.ActorSystem; -import akka.actor.Props; -import controllers.BaseController; -import controllers.DummyActor; import play.mvc.Http.RequestBuilder; import play.mvc.Result; import play.test.FakeApplication; import play.test.Helpers; import util.RequestInterceptor; -/** - * Created by arvind on 5/12/17. - */ +/** Created by arvind on 5/12/17. */ @FixMethodOrder(MethodSorters.NAME_ASCENDING) @RunWith(PowerMockRunner.class) @PrepareForTest(RequestInterceptor.class) @@ -41,7 +37,7 @@ public class HealthControllerTest { private static FakeApplication app; - private static Map headerMap; + private static Map headerMap; private static ActorSystem system; private static final Props props = Props.create(DummyActor.class); @@ -50,10 +46,11 @@ public static void startApp() { app = Helpers.fakeApplication(); Helpers.start(app); headerMap = new HashMap(); - headerMap.put(HeaderParam.X_Consumer_ID.getName(), new String[]{"Service test consumer"}); - headerMap.put(HeaderParam.X_Device_ID.getName(), new String[]{"Some Device Id"}); - headerMap.put(HeaderParam.X_Authenticated_Userid.getName(), new String[]{"Authenticated user id"}); - headerMap.put(JsonKey.MESSAGE_ID, new String[]{"Unique Message id"}); + headerMap.put(HeaderParam.X_Consumer_ID.getName(), new String[] {"Service test consumer"}); + headerMap.put(HeaderParam.X_Device_ID.getName(), new String[] {"Some Device Id"}); + headerMap.put( + HeaderParam.X_Authenticated_Userid.getName(), new String[] {"Authenticated user id"}); + headerMap.put(JsonKey.MESSAGE_ID, new String[] {"Unique Message id"}); system = ActorSystem.create("system"); ActorRef subject = system.actorOf(props); @@ -63,7 +60,8 @@ public static void startApp() { @Test public void testgetHealth() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); RequestBuilder req = new RequestBuilder().uri("/v1/health").method("GET"); req.headers(headerMap); Result result = route(req); @@ -73,7 +71,8 @@ public void testgetHealth() { @Test public void testgetLearnerServiceHealth() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); RequestBuilder req = new RequestBuilder().uri("/v1/ekstep/health").method("GET"); req.headers(headerMap); Result result = route(req); @@ -83,7 +82,8 @@ public void testgetLearnerServiceHealth() { @Test public void testgetLearnerServiceHealth01() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); RequestBuilder req = new RequestBuilder().uri("/v1/learner/health").method("GET"); req.headers(headerMap); Result result = route(req); @@ -93,11 +93,11 @@ public void testgetLearnerServiceHealth01() { @Test public void testgetLearnerServiceHealth02() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); RequestBuilder req = new RequestBuilder().uri("/v1/actor/health").method("GET"); req.headers(headerMap); Result result = route(req); assertEquals(200, result.status()); } - } diff --git a/service/test/controllers/metrics/CourseMetricsControllerTest.java b/service/test/controllers/metrics/CourseMetricsControllerTest.java index 021f511522..33ca071bbc 100644 --- a/service/test/controllers/metrics/CourseMetricsControllerTest.java +++ b/service/test/controllers/metrics/CourseMetricsControllerTest.java @@ -4,9 +4,13 @@ import static org.powermock.api.mockito.PowerMockito.when; import static play.test.Helpers.route; +import akka.actor.ActorRef; +import akka.actor.ActorSystem; +import akka.actor.Props; +import controllers.BaseController; +import controllers.DummyActor; import java.util.HashMap; import java.util.Map; - import org.junit.BeforeClass; import org.junit.FixMethodOrder; import org.junit.Test; @@ -19,21 +23,13 @@ import org.powermock.modules.junit4.PowerMockRunner; import org.sunbird.common.models.util.JsonKey; import org.sunbird.common.request.HeaderParam; - -import akka.actor.ActorRef; -import akka.actor.ActorSystem; -import akka.actor.Props; -import controllers.BaseController; -import controllers.DummyActor; import play.mvc.Http.RequestBuilder; import play.mvc.Result; import play.test.FakeApplication; import play.test.Helpers; import util.RequestInterceptor; -/** - * Created by arvind on 1/12/17. - */ +/** Created by arvind on 1/12/17. */ @FixMethodOrder(MethodSorters.NAME_ASCENDING) @RunWith(PowerMockRunner.class) @PrepareForTest(RequestInterceptor.class) @@ -41,7 +37,7 @@ public class CourseMetricsControllerTest { private static FakeApplication app; - private static Map headerMap; + private static Map headerMap; private static ActorSystem system; private static final Props props = Props.create(DummyActor.class); @@ -50,10 +46,11 @@ public static void startApp() { app = Helpers.fakeApplication(); Helpers.start(app); headerMap = new HashMap(); - headerMap.put(HeaderParam.X_Consumer_ID.getName(), new String[]{"Service test consumer"}); - headerMap.put(HeaderParam.X_Device_ID.getName(), new String[]{"Some Device Id"}); - headerMap.put(HeaderParam.X_Authenticated_Userid.getName(), new String[]{"Authenticated user id"}); - headerMap.put(JsonKey.MESSAGE_ID, new String[]{"Unique Message id"}); + headerMap.put(HeaderParam.X_Consumer_ID.getName(), new String[] {"Service test consumer"}); + headerMap.put(HeaderParam.X_Device_ID.getName(), new String[] {"Some Device Id"}); + headerMap.put( + HeaderParam.X_Authenticated_Userid.getName(), new String[] {"Authenticated user id"}); + headerMap.put(JsonKey.MESSAGE_ID, new String[] {"Unique Message id"}); system = ActorSystem.create("system"); ActorRef subject = system.actorOf(props); @@ -63,8 +60,10 @@ public static void startApp() { @Test public void testcourseProgress() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - RequestBuilder req = new RequestBuilder().uri("/v1/dashboard/progress/course/batchId?period=7d").method("GET"); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + RequestBuilder req = + new RequestBuilder().uri("/v1/dashboard/progress/course/batchId?period=7d").method("GET"); req.headers(headerMap); Result result = route(req); assertEquals(200, result.status()); @@ -73,8 +72,12 @@ public void testcourseProgress() { @Test public void testcourseCreation() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - RequestBuilder req = new RequestBuilder().uri("/v1/dashboard/consumption/course/courseId?period=7d").method("GET"); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + RequestBuilder req = + new RequestBuilder() + .uri("/v1/dashboard/consumption/course/courseId?period=7d") + .method("GET"); req.headers(headerMap); Result result = route(req); assertEquals(200, result.status()); @@ -83,8 +86,12 @@ public void testcourseCreation() { @Test public void testcourseProgressReport() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - RequestBuilder req = new RequestBuilder().uri("/v1/dashboard/progress/course/courseId/export?period=7d&format=excel").method("GET"); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + RequestBuilder req = + new RequestBuilder() + .uri("/v1/dashboard/progress/course/courseId/export?period=7d&format=excel") + .method("GET"); req.headers(headerMap); Result result = route(req); assertEquals(200, result.status()); @@ -93,12 +100,14 @@ public void testcourseProgressReport() { @Test public void testcourseCreationReport() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - RequestBuilder req = new RequestBuilder().uri("/v1/dashboard/progress/course/courseId/export?period=7d&format=excel").method("GET"); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + RequestBuilder req = + new RequestBuilder() + .uri("/v1/dashboard/progress/course/courseId/export?period=7d&format=excel") + .method("GET"); req.headers(headerMap); Result result = route(req); assertEquals(200, result.status()); } - - -} \ No newline at end of file +} diff --git a/service/test/controllers/metrics/OrganisationMetricsControllerTest.java b/service/test/controllers/metrics/OrganisationMetricsControllerTest.java index 315420d268..152f5cebb9 100644 --- a/service/test/controllers/metrics/OrganisationMetricsControllerTest.java +++ b/service/test/controllers/metrics/OrganisationMetricsControllerTest.java @@ -4,9 +4,13 @@ import static org.powermock.api.mockito.PowerMockito.when; import static play.test.Helpers.route; +import akka.actor.ActorRef; +import akka.actor.ActorSystem; +import akka.actor.Props; +import controllers.BaseController; +import controllers.DummyActor; import java.util.HashMap; import java.util.Map; - import org.junit.BeforeClass; import org.junit.FixMethodOrder; import org.junit.Test; @@ -19,43 +23,34 @@ import org.powermock.modules.junit4.PowerMockRunner; import org.sunbird.common.models.util.JsonKey; import org.sunbird.common.request.HeaderParam; - -import akka.actor.ActorRef; -import akka.actor.ActorSystem; -import akka.actor.Props; -import controllers.BaseController; -import controllers.DummyActor; import play.mvc.Http.RequestBuilder; import play.mvc.Result; import play.test.FakeApplication; import play.test.Helpers; import util.RequestInterceptor; -/** - * Created by arvind on 4/12/17. - */ +/** Created by arvind on 4/12/17. */ @FixMethodOrder(MethodSorters.NAME_ASCENDING) @RunWith(PowerMockRunner.class) @PrepareForTest(RequestInterceptor.class) @PowerMockIgnore("javax.management.*") public class OrganisationMetricsControllerTest { - private static FakeApplication app; - private static Map headerMap; + private static Map headerMap; private static ActorSystem system; private static final Props props = Props.create(DummyActor.class); - @BeforeClass public static void startApp() { app = Helpers.fakeApplication(); Helpers.start(app); headerMap = new HashMap(); - headerMap.put(HeaderParam.X_Consumer_ID.getName(), new String[]{"Service test consumer"}); - headerMap.put(HeaderParam.X_Device_ID.getName(), new String[]{"Some Device Id"}); - headerMap.put(HeaderParam.X_Authenticated_Userid.getName(), new String[]{"Authenticated user id"}); - headerMap.put(JsonKey.MESSAGE_ID, new String[]{"Unique Message id"}); + headerMap.put(HeaderParam.X_Consumer_ID.getName(), new String[] {"Service test consumer"}); + headerMap.put(HeaderParam.X_Device_ID.getName(), new String[] {"Some Device Id"}); + headerMap.put( + HeaderParam.X_Authenticated_Userid.getName(), new String[] {"Authenticated user id"}); + headerMap.put(JsonKey.MESSAGE_ID, new String[] {"Unique Message id"}); system = ActorSystem.create("system"); ActorRef subject = system.actorOf(props); @@ -65,8 +60,10 @@ public static void startApp() { @Test public void testcourseProgress() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - RequestBuilder req = new RequestBuilder().uri("/v1/dashboard/creation/org/orgId?period=7d").method("GET"); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + RequestBuilder req = + new RequestBuilder().uri("/v1/dashboard/creation/org/orgId?period=7d").method("GET"); req.headers(headerMap); Result result = route(req); assertEquals(200, result.status()); @@ -75,8 +72,10 @@ public void testcourseProgress() { @Test public void testorgConsumption() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - RequestBuilder req = new RequestBuilder().uri("/v1/dashboard/consumption/org/orgId?period=7d").method("GET"); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + RequestBuilder req = + new RequestBuilder().uri("/v1/dashboard/consumption/org/orgId?period=7d").method("GET"); req.headers(headerMap); Result result = route(req); assertEquals(200, result.status()); @@ -85,8 +84,10 @@ public void testorgConsumption() { @Test public void testorgCreationReport() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - RequestBuilder req = new RequestBuilder().uri("/v1/dashboard/creation/org/orgId/export?period=7d").method("GET"); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + RequestBuilder req = + new RequestBuilder().uri("/v1/dashboard/creation/org/orgId/export?period=7d").method("GET"); req.headers(headerMap); Result result = route(req); assertEquals(200, result.status()); @@ -95,11 +96,14 @@ public void testorgCreationReport() { @Test public void testorgConsumptionReport() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - RequestBuilder req = new RequestBuilder().uri("/v1/dashboard/consumption/org/orgId/export?period=7d").method("GET"); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + RequestBuilder req = + new RequestBuilder() + .uri("/v1/dashboard/consumption/org/orgId/export?period=7d") + .method("GET"); req.headers(headerMap); Result result = route(req); assertEquals(200, result.status()); } - } diff --git a/service/test/controllers/metrics/UserMetricsControllerTest.java b/service/test/controllers/metrics/UserMetricsControllerTest.java index 254b1025ae..4aa094457b 100644 --- a/service/test/controllers/metrics/UserMetricsControllerTest.java +++ b/service/test/controllers/metrics/UserMetricsControllerTest.java @@ -4,9 +4,13 @@ import static org.powermock.api.mockito.PowerMockito.when; import static play.test.Helpers.route; +import akka.actor.ActorRef; +import akka.actor.ActorSystem; +import akka.actor.Props; +import controllers.BaseController; +import controllers.DummyActor; import java.util.HashMap; import java.util.Map; - import org.junit.BeforeClass; import org.junit.FixMethodOrder; import org.junit.Test; @@ -19,21 +23,13 @@ import org.powermock.modules.junit4.PowerMockRunner; import org.sunbird.common.models.util.JsonKey; import org.sunbird.common.request.HeaderParam; - -import akka.actor.ActorRef; -import akka.actor.ActorSystem; -import akka.actor.Props; -import controllers.BaseController; -import controllers.DummyActor; import play.mvc.Http.RequestBuilder; import play.mvc.Result; import play.test.FakeApplication; import play.test.Helpers; import util.RequestInterceptor; -/** - * Created by arvind on 4/12/17. - */ +/** Created by arvind on 4/12/17. */ @FixMethodOrder(MethodSorters.NAME_ASCENDING) @RunWith(PowerMockRunner.class) @PrepareForTest(RequestInterceptor.class) @@ -41,7 +37,7 @@ public class UserMetricsControllerTest { private static FakeApplication app; - private static Map headerMap; + private static Map headerMap; private static ActorSystem system; private static final Props props = Props.create(DummyActor.class); @@ -50,10 +46,11 @@ public static void startApp() { app = Helpers.fakeApplication(); Helpers.start(app); headerMap = new HashMap(); - headerMap.put(HeaderParam.X_Consumer_ID.getName(), new String[]{"Service test consumer"}); - headerMap.put(HeaderParam.X_Device_ID.getName(), new String[]{"Some Device Id"}); - headerMap.put(HeaderParam.X_Authenticated_Userid.getName(), new String[]{"Authenticated user id"}); - headerMap.put(JsonKey.MESSAGE_ID, new String[]{"Unique Message id"}); + headerMap.put(HeaderParam.X_Consumer_ID.getName(), new String[] {"Service test consumer"}); + headerMap.put(HeaderParam.X_Device_ID.getName(), new String[] {"Some Device Id"}); + headerMap.put( + HeaderParam.X_Authenticated_Userid.getName(), new String[] {"Authenticated user id"}); + headerMap.put(JsonKey.MESSAGE_ID, new String[] {"Unique Message id"}); system = ActorSystem.create("system"); ActorRef subject = system.actorOf(props); @@ -63,8 +60,10 @@ public static void startApp() { @Test public void testuserCreation() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - RequestBuilder req = new RequestBuilder().uri("/v1/dashboard/creation/user/userId").method("GET"); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + RequestBuilder req = + new RequestBuilder().uri("/v1/dashboard/creation/user/userId").method("GET"); req.headers(headerMap); Result result = route(req); assertEquals(200, result.status()); @@ -73,11 +72,12 @@ public void testuserCreation() { @Test public void testuserConsumption() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - RequestBuilder req = new RequestBuilder().uri("/v1/dashboard/consumption/user/userId").method("GET"); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + RequestBuilder req = + new RequestBuilder().uri("/v1/dashboard/consumption/user/userId").method("GET"); req.headers(headerMap); Result result = route(req); assertEquals(200, result.status()); } - } diff --git a/service/test/controllers/notesmanagement/NotesControllerTest.java b/service/test/controllers/notesmanagement/NotesControllerTest.java index 0fae48fc87..222643cebe 100644 --- a/service/test/controllers/notesmanagement/NotesControllerTest.java +++ b/service/test/controllers/notesmanagement/NotesControllerTest.java @@ -4,10 +4,16 @@ import static org.powermock.api.mockito.PowerMockito.when; import static play.test.Helpers.route; +import akka.actor.ActorRef; +import akka.actor.ActorSystem; +import akka.actor.Props; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import controllers.BaseController; +import controllers.DummyActor; import java.io.IOException; import java.util.HashMap; import java.util.Map; - import org.junit.BeforeClass; import org.junit.FixMethodOrder; import org.junit.Test; @@ -21,15 +27,6 @@ import org.sunbird.common.models.util.JsonKey; import org.sunbird.common.models.util.ProjectLogger; import org.sunbird.common.request.HeaderParam; - -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - -import akka.actor.ActorRef; -import akka.actor.ActorSystem; -import akka.actor.Props; -import controllers.BaseController; -import controllers.DummyActor; import play.libs.Json; import play.mvc.Http.RequestBuilder; import play.mvc.Result; @@ -37,9 +34,7 @@ import play.test.Helpers; import util.RequestInterceptor; -/** - * Created by arvind on 4/12/17. - */ +/** Created by arvind on 4/12/17. */ @FixMethodOrder(MethodSorters.NAME_ASCENDING) @RunWith(PowerMockRunner.class) @PrepareForTest(RequestInterceptor.class) @@ -47,7 +42,7 @@ public class NotesControllerTest { private static FakeApplication app; - private static Map headerMap; + private static Map headerMap; private static ActorSystem system; private static final Props props = Props.create(DummyActor.class); @@ -56,10 +51,11 @@ public static void startApp() { app = Helpers.fakeApplication(); Helpers.start(app); headerMap = new HashMap(); - headerMap.put(HeaderParam.X_Consumer_ID.getName(), new String[]{"Service test consumer"}); - headerMap.put(HeaderParam.X_Device_ID.getName(), new String[]{"Some Device Id"}); - headerMap.put(HeaderParam.X_Authenticated_Userid.getName(), new String[]{"Authenticated user id"}); - headerMap.put(JsonKey.MESSAGE_ID, new String[]{"Unique Message id"}); + headerMap.put(HeaderParam.X_Consumer_ID.getName(), new String[] {"Service test consumer"}); + headerMap.put(HeaderParam.X_Device_ID.getName(), new String[] {"Some Device Id"}); + headerMap.put( + HeaderParam.X_Authenticated_Userid.getName(), new String[] {"Authenticated user id"}); + headerMap.put(JsonKey.MESSAGE_ID, new String[] {"Unique Message id"}); system = ActorSystem.create("system"); ActorRef subject = system.actorOf(props); @@ -69,15 +65,16 @@ public static void startApp() { @Test public void testCreateNote() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId}uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - innerMap.put(JsonKey.USER_ID , "uuiuhcf784508 8y8c79-fhh"); - innerMap.put(JsonKey.COURSE_ID , "crs123"); - innerMap.put(JsonKey.CONTENT_ID , "content123"); - innerMap.put(JsonKey.NOTE , "note"); - innerMap.put(JsonKey.TITLE , "learn"); - requestMap.put(JsonKey.REQUEST , innerMap); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId}uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + innerMap.put(JsonKey.USER_ID, "uuiuhcf784508 8y8c79-fhh"); + innerMap.put(JsonKey.COURSE_ID, "crs123"); + innerMap.put(JsonKey.CONTENT_ID, "content123"); + innerMap.put(JsonKey.NOTE, "note"); + innerMap.put(JsonKey.TITLE, "learn"); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); @@ -90,14 +87,15 @@ public void testCreateNote() { @Test public void testCreateNoteWithInvalidRequestData() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - innerMap.put(JsonKey.USER_ID , ""); - innerMap.put(JsonKey.COURSE_ID , "org123"); - innerMap.put(JsonKey.NOTE , ""); - innerMap.put(JsonKey.TITLE , "org123"); - requestMap.put(JsonKey.REQUEST , innerMap); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + innerMap.put(JsonKey.USER_ID, ""); + innerMap.put(JsonKey.COURSE_ID, "org123"); + innerMap.put(JsonKey.NOTE, ""); + innerMap.put(JsonKey.TITLE, "org123"); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); @@ -110,7 +108,8 @@ public void testCreateNoteWithInvalidRequestData() { @Test public void testGetNote() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); RequestBuilder req = new RequestBuilder().uri("/v1/note/read/123").method("GET"); req.headers(headerMap); @@ -121,16 +120,18 @@ public void testGetNote() { @Test public void testUpdateNote() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - innerMap.put(JsonKey.ID , "123"); - innerMap.put(JsonKey.TAGS , "123"); - requestMap.put(JsonKey.REQUEST , innerMap); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + innerMap.put(JsonKey.ID, "123"); + innerMap.put(JsonKey.TAGS, "123"); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); - RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/note/update/123").method("PATCH"); + RequestBuilder req = + new RequestBuilder().bodyJson(json).uri("/v1/note/update/123").method("PATCH"); req.headers(headerMap); Result result = route(req); assertEquals(200, result.status()); @@ -139,15 +140,17 @@ public void testUpdateNote() { @Test public void testDeleteNote() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - innerMap.put(JsonKey.ID , "123"); - requestMap.put(JsonKey.REQUEST , innerMap); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + innerMap.put(JsonKey.ID, "123"); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); - RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/note/delete/123").method("DELETE"); + RequestBuilder req = + new RequestBuilder().bodyJson(json).uri("/v1/note/delete/123").method("DELETE"); req.headers(headerMap); Result result = route(req); assertEquals(200, result.status()); @@ -156,13 +159,14 @@ public void testDeleteNote() { @Test public void testsearchNote() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - Map filterMap = new HashMap<>(); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + Map filterMap = new HashMap<>(); filterMap.put(JsonKey.ID, "123"); innerMap.put(JsonKey.FILTERS, filterMap); - requestMap.put(JsonKey.REQUEST , innerMap); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); @@ -172,16 +176,14 @@ public void testsearchNote() { assertEquals(200, result.status()); } - private static String mapToJson(Map map){ + private static String mapToJson(Map map) { ObjectMapper mapperObj = new ObjectMapper(); String jsonResp = ""; try { jsonResp = mapperObj.writeValueAsString(map); } catch (IOException e) { - ProjectLogger.log(e.getMessage(),e); + ProjectLogger.log(e.getMessage(), e); } return jsonResp; } - } - diff --git a/service/test/controllers/notificationservice/EmailServiceControllerTest.java b/service/test/controllers/notificationservice/EmailServiceControllerTest.java index 9ed4548dbb..c30a9a83c4 100644 --- a/service/test/controllers/notificationservice/EmailServiceControllerTest.java +++ b/service/test/controllers/notificationservice/EmailServiceControllerTest.java @@ -4,12 +4,18 @@ import static org.powermock.api.mockito.PowerMockito.when; import static play.test.Helpers.route; +import akka.actor.ActorRef; +import akka.actor.ActorSystem; +import akka.actor.Props; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import controllers.BaseController; +import controllers.DummyActor; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; - import org.junit.BeforeClass; import org.junit.FixMethodOrder; import org.junit.Test; @@ -23,15 +29,6 @@ import org.sunbird.common.models.util.JsonKey; import org.sunbird.common.models.util.ProjectLogger; import org.sunbird.common.request.HeaderParam; - -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - -import akka.actor.ActorRef; -import akka.actor.ActorSystem; -import akka.actor.Props; -import controllers.BaseController; -import controllers.DummyActor; import play.libs.Json; import play.mvc.Http.RequestBuilder; import play.mvc.Result; @@ -39,9 +36,7 @@ import play.test.Helpers; import util.RequestInterceptor; -/** - * Created by arvind on 4/12/17. - */ +/** Created by arvind on 4/12/17. */ @FixMethodOrder(MethodSorters.NAME_ASCENDING) @RunWith(PowerMockRunner.class) @PrepareForTest(RequestInterceptor.class) @@ -49,20 +44,20 @@ public class EmailServiceControllerTest { private static FakeApplication app; - private static Map headerMap; + private static Map headerMap; private static ActorSystem system; private static final Props props = Props.create(DummyActor.class); - @BeforeClass public static void startApp() { app = Helpers.fakeApplication(); Helpers.start(app); headerMap = new HashMap(); - headerMap.put(HeaderParam.X_Consumer_ID.getName(), new String[]{"Service test consumer"}); - headerMap.put(HeaderParam.X_Device_ID.getName(), new String[]{"Some Device Id"}); - headerMap.put(HeaderParam.X_Authenticated_Userid.getName(), new String[]{"Authenticated user id"}); - headerMap.put(JsonKey.MESSAGE_ID, new String[]{"Unique Message id"}); + headerMap.put(HeaderParam.X_Consumer_ID.getName(), new String[] {"Service test consumer"}); + headerMap.put(HeaderParam.X_Device_ID.getName(), new String[] {"Some Device Id"}); + headerMap.put( + HeaderParam.X_Authenticated_Userid.getName(), new String[] {"Authenticated user id"}); + headerMap.put(JsonKey.MESSAGE_ID, new String[] {"Unique Message id"}); system = ActorSystem.create("system"); ActorRef subject = system.actorOf(props); @@ -72,23 +67,25 @@ public static void startApp() { @Test public void testsendMail() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - innerMap.put(JsonKey.ORG_NAME , "org123"); - innerMap.put(JsonKey.SUBJECT , "subject"); - innerMap.put(JsonKey.BODY , "body"); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + innerMap.put(JsonKey.ORG_NAME, "org123"); + innerMap.put(JsonKey.SUBJECT, "subject"); + innerMap.put(JsonKey.BODY, "body"); List recepeintsEmails = new ArrayList<>(); recepeintsEmails.add("abc"); List receipeintUserIds = new ArrayList<>(); receipeintUserIds.add("user001"); - innerMap.put("recipientEmails" , recepeintsEmails); - innerMap.put("recipientUserIds" , receipeintUserIds); - requestMap.put(JsonKey.REQUEST , innerMap); + innerMap.put("recipientEmails", recepeintsEmails); + innerMap.put("recipientUserIds", receipeintUserIds); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); - RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/notification/email").method("POST"); + RequestBuilder req = + new RequestBuilder().bodyJson(json).uri("/v1/notification/email").method("POST"); req.headers(headerMap); Result result = route(req); assertEquals(200, result.status()); @@ -97,37 +94,38 @@ public void testsendMail() { @Test public void testsendMailWithInvalidRequestData() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - innerMap.put(JsonKey.ORG_NAME , "org123"); - innerMap.put(JsonKey.SUBJECT , ""); - innerMap.put(JsonKey.BODY , ""); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + innerMap.put(JsonKey.ORG_NAME, "org123"); + innerMap.put(JsonKey.SUBJECT, ""); + innerMap.put(JsonKey.BODY, ""); List recepeintsEmails = new ArrayList<>(); recepeintsEmails.add("abc"); List receipeintUserIds = new ArrayList<>(); receipeintUserIds.add("user001"); - innerMap.put("recipientEmails" , recepeintsEmails); - innerMap.put("recipientUserIds" , receipeintUserIds); - requestMap.put(JsonKey.REQUEST , innerMap); + innerMap.put("recipientEmails", recepeintsEmails); + innerMap.put("recipientUserIds", receipeintUserIds); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); - RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/notification/email").method("POST"); + RequestBuilder req = + new RequestBuilder().bodyJson(json).uri("/v1/notification/email").method("POST"); req.headers(headerMap); Result result = route(req); assertEquals(400, result.status()); } - private static String mapToJson(Map map){ + private static String mapToJson(Map map) { ObjectMapper mapperObj = new ObjectMapper(); String jsonResp = ""; try { jsonResp = mapperObj.writeValueAsString(map); } catch (IOException e) { - ProjectLogger.log(e.getMessage(),e); + ProjectLogger.log(e.getMessage(), e); } return jsonResp; } - } diff --git a/service/test/controllers/organisationmanagement/OrganisationControllerTest.java b/service/test/controllers/organisationmanagement/OrganisationControllerTest.java index ca930255de..5fb7551195 100644 --- a/service/test/controllers/organisationmanagement/OrganisationControllerTest.java +++ b/service/test/controllers/organisationmanagement/OrganisationControllerTest.java @@ -4,11 +4,17 @@ import static org.powermock.api.mockito.PowerMockito.when; import static play.test.Helpers.route; +import akka.actor.ActorRef; +import akka.actor.ActorSystem; +import akka.actor.Props; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import controllers.BaseController; +import controllers.DummyActor; import java.io.IOException; import java.math.BigInteger; import java.util.HashMap; import java.util.Map; - import org.junit.BeforeClass; import org.junit.FixMethodOrder; import org.junit.Test; @@ -22,15 +28,6 @@ import org.sunbird.common.models.util.JsonKey; import org.sunbird.common.models.util.ProjectLogger; import org.sunbird.common.request.HeaderParam; - -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - -import akka.actor.ActorRef; -import akka.actor.ActorSystem; -import akka.actor.Props; -import controllers.BaseController; -import controllers.DummyActor; import play.libs.Json; import play.mvc.Http.RequestBuilder; import play.mvc.Result; @@ -38,9 +35,7 @@ import play.test.Helpers; import util.RequestInterceptor; -/** - * Created by arvind on 1/12/17. - */ +/** Created by arvind on 1/12/17. */ @FixMethodOrder(MethodSorters.NAME_ASCENDING) @RunWith(PowerMockRunner.class) @PrepareForTest(RequestInterceptor.class) @@ -48,7 +43,7 @@ public class OrganisationControllerTest { private static FakeApplication app; - private static Map headerMap; + private static Map headerMap; private static ActorSystem system; private static final Props props = Props.create(DummyActor.class); @@ -57,10 +52,11 @@ public static void startApp() { app = Helpers.fakeApplication(); Helpers.start(app); headerMap = new HashMap(); - headerMap.put(HeaderParam.X_Consumer_ID.getName(), new String[]{"Service test consumer"}); - headerMap.put(HeaderParam.X_Device_ID.getName(), new String[]{"Some Device Id"}); - headerMap.put(HeaderParam.X_Authenticated_Userid.getName(), new String[]{"Authenticated user id"}); - headerMap.put(JsonKey.MESSAGE_ID, new String[]{"Unique Message id"}); + headerMap.put(HeaderParam.X_Consumer_ID.getName(), new String[] {"Service test consumer"}); + headerMap.put(HeaderParam.X_Device_ID.getName(), new String[] {"Some Device Id"}); + headerMap.put( + HeaderParam.X_Authenticated_Userid.getName(), new String[] {"Authenticated user id"}); + headerMap.put(JsonKey.MESSAGE_ID, new String[] {"Unique Message id"}); system = ActorSystem.create("system"); ActorRef subject = system.actorOf(props); @@ -70,11 +66,12 @@ public static void startApp() { @Test public void testCreateOrg() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - innerMap.put(JsonKey.ORG_NAME , "org123"); - requestMap.put(JsonKey.REQUEST , innerMap); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + innerMap.put(JsonKey.ORG_NAME, "org123"); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); @@ -87,11 +84,12 @@ public void testCreateOrg() { @Test public void testCreateOrgInvalidRequestData() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - innerMap.put(JsonKey.ORG_NAME , null); - requestMap.put(JsonKey.REQUEST , innerMap); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + innerMap.put(JsonKey.ORG_NAME, null); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); @@ -104,16 +102,16 @@ public void testCreateOrgInvalidRequestData() { @Test public void testApproveOrg() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - innerMap.put(JsonKey.ORGANISATION_ID , "org123"); - requestMap.put(JsonKey.REQUEST , innerMap); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + innerMap.put(JsonKey.ORGANISATION_ID, "org123"); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); - JsonNode json = Json.parse(data); RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/org/approve").method("POST"); req.headers(headerMap); @@ -124,16 +122,16 @@ public void testApproveOrg() { @Test public void testApproveOrgInvalidRequestData() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - innerMap.put(JsonKey.ORGANISATION_ID , null); - requestMap.put(JsonKey.REQUEST , innerMap); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + innerMap.put(JsonKey.ORGANISATION_ID, null); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); - JsonNode json = Json.parse(data); RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/org/approve").method("POST"); req.headers(headerMap); @@ -144,17 +142,17 @@ public void testApproveOrgInvalidRequestData() { @Test public void testUpdateOrg() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - innerMap.put(JsonKey.ORGANISATION_ID , "org123"); - innerMap.put(JsonKey.ROOT_ORG_ID , "rootorg12"); - requestMap.put(JsonKey.REQUEST , innerMap); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + innerMap.put(JsonKey.ORGANISATION_ID, "org123"); + innerMap.put(JsonKey.ROOT_ORG_ID, "rootorg12"); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); - JsonNode json = Json.parse(data); RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/org/update").method("PATCH"); req.headers(headerMap); @@ -165,16 +163,18 @@ public void testUpdateOrg() { @Test public void testupdateOrgStatus() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - innerMap.put(JsonKey.ORGANISATION_ID , "org123"); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + innerMap.put(JsonKey.ORGANISATION_ID, "org123"); innerMap.put(JsonKey.STATUS, new BigInteger("1")); - requestMap.put(JsonKey.REQUEST , innerMap); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); - RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/org/status/update").method("POST"); + RequestBuilder req = + new RequestBuilder().bodyJson(json).uri("/v1/org/status/update").method("POST"); req.headers(headerMap); Result result = route(req); assertEquals(404, result.status()); @@ -183,12 +183,13 @@ public void testupdateOrgStatus() { @Test public void testgetOrgDetails() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - innerMap.put(JsonKey.ORGANISATION_ID , "org123"); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + innerMap.put(JsonKey.ORGANISATION_ID, "org123"); innerMap.put(JsonKey.STATUS, new BigInteger("1")); - requestMap.put(JsonKey.REQUEST , innerMap); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); @@ -201,16 +202,18 @@ public void testgetOrgDetails() { @Test public void testaddMemberToOrganisation() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - innerMap.put(JsonKey.ORGANISATION_ID , "org123"); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + innerMap.put(JsonKey.ORGANISATION_ID, "org123"); innerMap.put(JsonKey.USER_ID, "userId"); - requestMap.put(JsonKey.REQUEST , innerMap); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); - RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/org/member/add").method("POST"); + RequestBuilder req = + new RequestBuilder().bodyJson(json).uri("/v1/org/member/add").method("POST"); req.headers(headerMap); Result result = route(req); assertEquals(200, result.status()); @@ -219,16 +222,18 @@ public void testaddMemberToOrganisation() { @Test public void testremoveMemberFromOrganisation() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - innerMap.put(JsonKey.ORGANISATION_ID , "org123"); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + innerMap.put(JsonKey.ORGANISATION_ID, "org123"); innerMap.put(JsonKey.USER_ID, "userId"); - requestMap.put(JsonKey.REQUEST , innerMap); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); - RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/org/member/remove").method("POST"); + RequestBuilder req = + new RequestBuilder().bodyJson(json).uri("/v1/org/member/remove").method("POST"); req.headers(headerMap); Result result = route(req); assertEquals(200, result.status()); @@ -237,16 +242,18 @@ public void testremoveMemberFromOrganisation() { @Test public void testjoinUserOrganisation() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - innerMap.put(JsonKey.ORGANISATION_ID , "org123"); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + innerMap.put(JsonKey.ORGANISATION_ID, "org123"); innerMap.put(JsonKey.USER_ID, "userId"); - requestMap.put(JsonKey.REQUEST , innerMap); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); - RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/org/member/join").method("POST"); + RequestBuilder req = + new RequestBuilder().bodyJson(json).uri("/v1/org/member/join").method("POST"); req.headers(headerMap); Result result = route(req); assertEquals(200, result.status()); @@ -255,16 +262,18 @@ public void testjoinUserOrganisation() { @Test public void testapproveUserOrganisation() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - innerMap.put(JsonKey.ORGANISATION_ID , "org123"); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + innerMap.put(JsonKey.ORGANISATION_ID, "org123"); innerMap.put(JsonKey.USER_ID, "userId"); - requestMap.put(JsonKey.REQUEST , innerMap); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); - RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/org/member/approve").method("POST"); + RequestBuilder req = + new RequestBuilder().bodyJson(json).uri("/v1/org/member/approve").method("POST"); req.headers(headerMap); Result result = route(req); assertEquals(200, result.status()); @@ -273,16 +282,18 @@ public void testapproveUserOrganisation() { @Test public void testrejectUserOrganisation() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - innerMap.put(JsonKey.ORGANISATION_ID , "org123"); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + innerMap.put(JsonKey.ORGANISATION_ID, "org123"); innerMap.put(JsonKey.USER_ID, "userId"); - requestMap.put(JsonKey.REQUEST , innerMap); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); - RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/org/member/approve").method("POST"); + RequestBuilder req = + new RequestBuilder().bodyJson(json).uri("/v1/org/member/approve").method("POST"); req.headers(headerMap); Result result = route(req); assertEquals(200, result.status()); @@ -291,12 +302,13 @@ public void testrejectUserOrganisation() { @Test public void testdownloadOrgs() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - innerMap.put(JsonKey.ORGANISATION_ID , "org123"); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + innerMap.put(JsonKey.ORGANISATION_ID, "org123"); innerMap.put(JsonKey.STATUS, new BigInteger("1")); - requestMap.put(JsonKey.REQUEST , innerMap); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); @@ -309,12 +321,13 @@ public void testdownloadOrgs() { @Test public void testsearchOrgs() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - innerMap.put(JsonKey.ORGANISATION_ID , "org123"); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + innerMap.put(JsonKey.ORGANISATION_ID, "org123"); innerMap.put(JsonKey.STATUS, new BigInteger("1")); - requestMap.put(JsonKey.REQUEST , innerMap); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); @@ -327,7 +340,8 @@ public void testsearchOrgs() { @Test public void testgetOrgTypeList() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); RequestBuilder req = new RequestBuilder().uri("/v1/org/type/list").method("GET"); req.headers(headerMap); @@ -338,16 +352,18 @@ public void testgetOrgTypeList() { @Test public void testcreateOrgType() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - innerMap.put(JsonKey.NAME , "org123"); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + innerMap.put(JsonKey.NAME, "org123"); innerMap.put(JsonKey.STATUS, new BigInteger("1")); - requestMap.put(JsonKey.REQUEST , innerMap); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); - RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/org/type/create").method("POST"); + RequestBuilder req = + new RequestBuilder().bodyJson(json).uri("/v1/org/type/create").method("POST"); req.headers(headerMap); Result result = route(req); assertEquals(200, result.status()); @@ -356,30 +372,31 @@ public void testcreateOrgType() { @Test public void testupdateOrgType() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - innerMap.put(JsonKey.NAME , "org123"); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + innerMap.put(JsonKey.NAME, "org123"); innerMap.put(JsonKey.ID, "1"); - requestMap.put(JsonKey.REQUEST , innerMap); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); - RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/org/type/update").method("PATCH"); + RequestBuilder req = + new RequestBuilder().bodyJson(json).uri("/v1/org/type/update").method("PATCH"); req.headers(headerMap); Result result = route(req); assertEquals(200, result.status()); } - private static String mapToJson(Map map){ + private static String mapToJson(Map map) { ObjectMapper mapperObj = new ObjectMapper(); String jsonResp = ""; try { jsonResp = mapperObj.writeValueAsString(map); } catch (IOException e) { - ProjectLogger.log(e.getMessage(),e); + ProjectLogger.log(e.getMessage(), e); } return jsonResp; } - } diff --git a/service/test/controllers/pagemanagement/PageControllerTest.java b/service/test/controllers/pagemanagement/PageControllerTest.java index b67398f52c..d1c35485d8 100644 --- a/service/test/controllers/pagemanagement/PageControllerTest.java +++ b/service/test/controllers/pagemanagement/PageControllerTest.java @@ -4,10 +4,16 @@ import static org.powermock.api.mockito.PowerMockito.when; import static play.test.Helpers.route; +import akka.actor.ActorRef; +import akka.actor.ActorSystem; +import akka.actor.Props; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import controllers.BaseController; +import controllers.DummyActor; import java.io.IOException; import java.util.HashMap; import java.util.Map; - import org.junit.BeforeClass; import org.junit.FixMethodOrder; import org.junit.Test; @@ -21,15 +27,6 @@ import org.sunbird.common.models.util.JsonKey; import org.sunbird.common.models.util.ProjectLogger; import org.sunbird.common.request.HeaderParam; - -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - -import akka.actor.ActorRef; -import akka.actor.ActorSystem; -import akka.actor.Props; -import controllers.BaseController; -import controllers.DummyActor; import play.libs.Json; import play.mvc.Http.RequestBuilder; import play.mvc.Result; @@ -37,9 +34,7 @@ import play.test.Helpers; import util.RequestInterceptor; -/** - * Created by arvind on 4/12/17. - */ +/** Created by arvind on 4/12/17. */ @FixMethodOrder(MethodSorters.NAME_ASCENDING) @RunWith(PowerMockRunner.class) @PrepareForTest(RequestInterceptor.class) @@ -47,7 +42,7 @@ public class PageControllerTest { private static FakeApplication app; - private static Map headerMap; + private static Map headerMap; private static ActorSystem system; private static final Props props = Props.create(DummyActor.class); @@ -56,10 +51,11 @@ public static void startApp() { app = Helpers.fakeApplication(); Helpers.start(app); headerMap = new HashMap(); - headerMap.put(HeaderParam.X_Consumer_ID.getName(), new String[]{"Service test consumer"}); - headerMap.put(HeaderParam.X_Device_ID.getName(), new String[]{"Some Device Id"}); - headerMap.put(HeaderParam.X_Authenticated_Userid.getName(), new String[]{"Authenticated user id"}); - headerMap.put(JsonKey.MESSAGE_ID, new String[]{"Unique Message id"}); + headerMap.put(HeaderParam.X_Consumer_ID.getName(), new String[] {"Service test consumer"}); + headerMap.put(HeaderParam.X_Device_ID.getName(), new String[] {"Some Device Id"}); + headerMap.put( + HeaderParam.X_Authenticated_Userid.getName(), new String[] {"Authenticated user id"}); + headerMap.put(JsonKey.MESSAGE_ID, new String[] {"Unique Message id"}); system = ActorSystem.create("system"); ActorRef subject = system.actorOf(props); @@ -69,11 +65,12 @@ public static void startApp() { @Test public void testcreatePage() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - innerMap.put("name" , "page1"); - requestMap.put(JsonKey.REQUEST , innerMap); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + innerMap.put("name", "page1"); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); @@ -86,12 +83,13 @@ public void testcreatePage() { @Test public void testupdatePage() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - innerMap.put("name" , "page1"); - innerMap.put(JsonKey.ID , "page1"); - requestMap.put(JsonKey.REQUEST , innerMap); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + innerMap.put("name", "page1"); + innerMap.put(JsonKey.ID, "page1"); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); @@ -104,7 +102,8 @@ public void testupdatePage() { @Test public void testgetPageSetting() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); RequestBuilder req = new RequestBuilder().uri("/v1/page/read/pageId").method("GET"); req.headers(headerMap); Result result = route(req); @@ -114,7 +113,8 @@ public void testgetPageSetting() { @Test public void testgetPageSettings() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); RequestBuilder req = new RequestBuilder().uri("/v1/page/all/settings").method("GET"); req.headers(headerMap); Result result = route(req); @@ -124,16 +124,18 @@ public void testgetPageSettings() { @Test public void testgetPageData() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - innerMap.put("name" , "page1"); - innerMap.put(JsonKey.SOURCE , "src"); - requestMap.put(JsonKey.REQUEST , innerMap); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + innerMap.put("name", "page1"); + innerMap.put(JsonKey.SOURCE, "src"); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); - RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/page/assemble").method("POST"); + RequestBuilder req = + new RequestBuilder().bodyJson(json).uri("/v1/page/assemble").method("POST"); req.headers(headerMap); Result result = route(req); assertEquals(200, result.status()); @@ -142,16 +144,18 @@ public void testgetPageData() { @Test public void testcreatePageSection() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - innerMap.put("name" , "page1"); - innerMap.put("sectionDataType" , "section01"); - requestMap.put(JsonKey.REQUEST , innerMap); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + innerMap.put("name", "page1"); + innerMap.put("sectionDataType", "section01"); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); - RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/page/section/create").method("POST"); + RequestBuilder req = + new RequestBuilder().bodyJson(json).uri("/v1/page/section/create").method("POST"); req.headers(headerMap); Result result = route(req); assertEquals(200, result.status()); @@ -160,17 +164,19 @@ public void testcreatePageSection() { @Test public void testupdatePageSection() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - innerMap.put("name" , "page1"); - innerMap.put("sectionDataType" , "section01"); - innerMap.put(JsonKey.ID , "001"); - requestMap.put(JsonKey.REQUEST , innerMap); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + innerMap.put("name", "page1"); + innerMap.put("sectionDataType", "section01"); + innerMap.put(JsonKey.ID, "001"); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); - RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/page/section/update").method("PATCH"); + RequestBuilder req = + new RequestBuilder().bodyJson(json).uri("/v1/page/section/update").method("PATCH"); req.headers(headerMap); Result result = route(req); assertEquals(200, result.status()); @@ -179,7 +185,8 @@ public void testupdatePageSection() { @Test public void testgetSection() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); RequestBuilder req = new RequestBuilder().uri("/v1/page/section/read/sectionId").method("GET"); req.headers(headerMap); Result result = route(req); @@ -189,22 +196,22 @@ public void testgetSection() { @Test public void testgetSections() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); RequestBuilder req = new RequestBuilder().uri("/v1/page/section/list").method("GET"); req.headers(headerMap); Result result = route(req); assertEquals(200, result.status()); } - private static String mapToJson(Map map){ + private static String mapToJson(Map map) { ObjectMapper mapperObj = new ObjectMapper(); String jsonResp = ""; try { jsonResp = mapperObj.writeValueAsString(map); } catch (IOException e) { - ProjectLogger.log(e.getMessage(),e); + ProjectLogger.log(e.getMessage(), e); } return jsonResp; } - } diff --git a/service/test/controllers/search/SearchControllerTest.java b/service/test/controllers/search/SearchControllerTest.java index c893c65b07..3b32757d99 100644 --- a/service/test/controllers/search/SearchControllerTest.java +++ b/service/test/controllers/search/SearchControllerTest.java @@ -4,10 +4,16 @@ import static org.powermock.api.mockito.PowerMockito.when; import static play.test.Helpers.route; +import akka.actor.ActorRef; +import akka.actor.ActorSystem; +import akka.actor.Props; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import controllers.BaseController; +import controllers.DummyActor; import java.io.IOException; import java.util.HashMap; import java.util.Map; - import org.junit.BeforeClass; import org.junit.FixMethodOrder; import org.junit.Test; @@ -21,15 +27,6 @@ import org.sunbird.common.models.util.JsonKey; import org.sunbird.common.models.util.ProjectLogger; import org.sunbird.common.request.HeaderParam; - -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - -import akka.actor.ActorRef; -import akka.actor.ActorSystem; -import akka.actor.Props; -import controllers.BaseController; -import controllers.DummyActor; import play.libs.Json; import play.mvc.Http.RequestBuilder; import play.mvc.Result; @@ -37,9 +34,7 @@ import play.test.Helpers; import util.RequestInterceptor; -/** - * Created by arvind on 6/12/17. - */ +/** Created by arvind on 6/12/17. */ @FixMethodOrder(MethodSorters.NAME_ASCENDING) @RunWith(PowerMockRunner.class) @PrepareForTest(RequestInterceptor.class) @@ -47,7 +42,7 @@ public class SearchControllerTest { private static FakeApplication app; - private static Map headerMap; + private static Map headerMap; private static ActorSystem system; private static final Props props = Props.create(DummyActor.class); @@ -56,10 +51,11 @@ public static void startApp() { app = Helpers.fakeApplication(); Helpers.start(app); headerMap = new HashMap(); - headerMap.put(HeaderParam.X_Consumer_ID.getName(), new String[]{"Service test consumer"}); - headerMap.put(HeaderParam.X_Device_ID.getName(), new String[]{"Some Device Id"}); - headerMap.put(HeaderParam.X_Authenticated_Userid.getName(), new String[]{"Authenticated user id"}); - headerMap.put(JsonKey.MESSAGE_ID, new String[]{"Unique Message id"}); + headerMap.put(HeaderParam.X_Consumer_ID.getName(), new String[] {"Service test consumer"}); + headerMap.put(HeaderParam.X_Device_ID.getName(), new String[] {"Some Device Id"}); + headerMap.put( + HeaderParam.X_Authenticated_Userid.getName(), new String[] {"Authenticated user id"}); + headerMap.put(JsonKey.MESSAGE_ID, new String[] {"Unique Message id"}); system = ActorSystem.create("system"); ActorRef subject = system.actorOf(props); @@ -69,16 +65,18 @@ public static void startApp() { @Test public void testcompositeSearch() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - innerMap.put(JsonKey.ORG_NAME , "org123"); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + innerMap.put(JsonKey.ORG_NAME, "org123"); innerMap.put(JsonKey.OBJECT_TYPE, JsonKey.ORGANISATION); - requestMap.put(JsonKey.REQUEST , innerMap); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); - RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/search/compositesearch").method("POST"); + RequestBuilder req = + new RequestBuilder().bodyJson(json).uri("/v1/search/compositesearch").method("POST"); req.headers(headerMap); Result result = route(req); assertEquals(200, result.status()); @@ -87,12 +85,13 @@ public void testcompositeSearch() { @Test public void testsync() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); innerMap.put(JsonKey.OBJECT_TYPE, JsonKey.ORGANISATION); - innerMap.put(JsonKey.OPERATION_FOR , "learner"); - requestMap.put(JsonKey.REQUEST , innerMap); + innerMap.put(JsonKey.OPERATION_FOR, "learner"); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); @@ -102,15 +101,14 @@ public void testsync() { assertEquals(200, result.status()); } - private static String mapToJson(Map map){ + private static String mapToJson(Map map) { ObjectMapper mapperObj = new ObjectMapper(); String jsonResp = ""; try { jsonResp = mapperObj.writeValueAsString(map); } catch (IOException e) { - ProjectLogger.log(e.getMessage(),e); + ProjectLogger.log(e.getMessage(), e); } return jsonResp; } - } diff --git a/service/test/controllers/skills/SkillControllerTest.java b/service/test/controllers/skills/SkillControllerTest.java index 9da297c80e..b6c82d8656 100644 --- a/service/test/controllers/skills/SkillControllerTest.java +++ b/service/test/controllers/skills/SkillControllerTest.java @@ -4,10 +4,16 @@ import static org.powermock.api.mockito.PowerMockito.when; import static play.test.Helpers.route; +import akka.actor.ActorRef; +import akka.actor.ActorSystem; +import akka.actor.Props; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import controllers.BaseController; +import controllers.DummyActor; import java.io.IOException; import java.util.HashMap; import java.util.Map; - import org.junit.BeforeClass; import org.junit.FixMethodOrder; import org.junit.Test; @@ -21,15 +27,6 @@ import org.sunbird.common.models.util.JsonKey; import org.sunbird.common.models.util.ProjectLogger; import org.sunbird.common.request.HeaderParam; - -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - -import akka.actor.ActorRef; -import akka.actor.ActorSystem; -import akka.actor.Props; -import controllers.BaseController; -import controllers.DummyActor; import play.libs.Json; import play.mvc.Http.RequestBuilder; import play.mvc.Result; @@ -37,9 +34,7 @@ import play.test.Helpers; import util.RequestInterceptor; -/** - * Created by arvind on 30/11/17. - */ +/** Created by arvind on 30/11/17. */ @FixMethodOrder(MethodSorters.NAME_ASCENDING) @RunWith(PowerMockRunner.class) @PrepareForTest(RequestInterceptor.class) @@ -47,7 +42,7 @@ public class SkillControllerTest { private static FakeApplication app; - private static Map headerMap; + private static Map headerMap; private static ActorSystem system; private static final Props props = Props.create(DummyActor.class); @@ -56,10 +51,11 @@ public static void startApp() { app = Helpers.fakeApplication(); Helpers.start(app); headerMap = new HashMap(); - headerMap.put(HeaderParam.X_Consumer_ID.getName(), new String[]{"Service test consumer"}); - headerMap.put(HeaderParam.X_Device_ID.getName(), new String[]{"Some Device Id"}); - headerMap.put(HeaderParam.X_Authenticated_Userid.getName(), new String[]{"Authenticated user id"}); - headerMap.put(JsonKey.MESSAGE_ID, new String[]{"Unique Message id"}); + headerMap.put(HeaderParam.X_Consumer_ID.getName(), new String[] {"Service test consumer"}); + headerMap.put(HeaderParam.X_Device_ID.getName(), new String[] {"Some Device Id"}); + headerMap.put( + HeaderParam.X_Authenticated_Userid.getName(), new String[] {"Authenticated user id"}); + headerMap.put(JsonKey.MESSAGE_ID, new String[] {"Unique Message id"}); system = ActorSystem.create("system"); ActorRef subject = system.actorOf(props); @@ -69,17 +65,18 @@ public static void startApp() { @Test public void testAddSkill() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - innerMap.put(JsonKey.ORGANISATION_ID , "7687584"); - requestMap.put(JsonKey.REQUEST , innerMap); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + innerMap.put(JsonKey.ORGANISATION_ID, "7687584"); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); - JsonNode json = Json.parse(data); - RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/user/skill/add").method("POST"); + RequestBuilder req = + new RequestBuilder().bodyJson(json).uri("/v1/user/skill/add").method("POST"); req.headers(headerMap); Result result = route(req); assertEquals(200, result.status()); @@ -88,17 +85,18 @@ public void testAddSkill() { @Test public void testGetUserSkill() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - innerMap.put(JsonKey.USER_ID , "7687584"); - requestMap.put(JsonKey.REQUEST , innerMap); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + innerMap.put(JsonKey.USER_ID, "7687584"); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); - JsonNode json = Json.parse(data); - RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/user/skill/read").method("POST"); + RequestBuilder req = + new RequestBuilder().bodyJson(json).uri("/v1/user/skill/read").method("POST"); req.headers(headerMap); Result result = route(req); assertEquals(200, result.status()); @@ -107,8 +105,8 @@ public void testGetUserSkill() { @Test public void testGetSkills() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); RequestBuilder req = new RequestBuilder().uri("/v1/skills").method("GET"); req.headers(headerMap); @@ -116,14 +114,13 @@ public void testGetSkills() { assertEquals(200, result.status()); } - - private static String mapToJson(Map map){ + private static String mapToJson(Map map) { ObjectMapper mapperObj = new ObjectMapper(); String jsonResp = ""; try { jsonResp = mapperObj.writeValueAsString(map); } catch (IOException e) { - ProjectLogger.log(e.getMessage(),e); + ProjectLogger.log(e.getMessage(), e); } return jsonResp; } diff --git a/service/test/controllers/storage/FileStorageControllerTest.java b/service/test/controllers/storage/FileStorageControllerTest.java index d760ffb279..96d4d159ec 100644 --- a/service/test/controllers/storage/FileStorageControllerTest.java +++ b/service/test/controllers/storage/FileStorageControllerTest.java @@ -1,14 +1,19 @@ - package controllers.storage; import static org.junit.Assert.assertEquals; import static org.powermock.api.mockito.PowerMockito.when; import static play.test.Helpers.route; +import akka.actor.ActorRef; +import akka.actor.ActorSystem; +import akka.actor.Props; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import controllers.BaseController; +import controllers.DummyActor; import java.io.IOException; import java.util.HashMap; import java.util.Map; - import org.junit.BeforeClass; import org.junit.FixMethodOrder; import org.junit.Test; @@ -22,15 +27,6 @@ import org.sunbird.common.models.util.JsonKey; import org.sunbird.common.models.util.ProjectLogger; import org.sunbird.common.request.HeaderParam; - -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - -import akka.actor.ActorRef; -import akka.actor.ActorSystem; -import akka.actor.Props; -import controllers.BaseController; -import controllers.DummyActor; import play.libs.Json; import play.mvc.Http.RequestBuilder; import play.mvc.Result; @@ -38,9 +34,7 @@ import play.test.Helpers; import util.RequestInterceptor; -/** - * Created by arvind on 6/12/17. - */ +/** Created by arvind on 6/12/17. */ @FixMethodOrder(MethodSorters.NAME_ASCENDING) @RunWith(PowerMockRunner.class) @PrepareForTest(RequestInterceptor.class) @@ -48,7 +42,7 @@ public class FileStorageControllerTest { private static FakeApplication app; - private static Map headerMap; + private static Map headerMap; private static ActorSystem system; private static final Props props = Props.create(DummyActor.class); @@ -57,10 +51,11 @@ public static void startApp() { app = Helpers.fakeApplication(); Helpers.start(app); headerMap = new HashMap(); - headerMap.put(HeaderParam.X_Consumer_ID.getName(), new String[]{"Service test consumer"}); - headerMap.put(HeaderParam.X_Device_ID.getName(), new String[]{"Some Device Id"}); - headerMap.put(HeaderParam.X_Authenticated_Userid.getName(), new String[]{"Authenticated user id"}); - headerMap.put(JsonKey.MESSAGE_ID, new String[]{"Unique Message id"}); + headerMap.put(HeaderParam.X_Consumer_ID.getName(), new String[] {"Service test consumer"}); + headerMap.put(HeaderParam.X_Device_ID.getName(), new String[] {"Some Device Id"}); + headerMap.put( + HeaderParam.X_Authenticated_Userid.getName(), new String[] {"Authenticated user id"}); + headerMap.put(JsonKey.MESSAGE_ID, new String[] {"Unique Message id"}); system = ActorSystem.create("system"); ActorRef subject = system.actorOf(props); @@ -70,11 +65,12 @@ public static void startApp() { @Test public void testuploadFileService() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - innerMap.put(JsonKey.DATA , "uploadFILEData".getBytes()); - requestMap.put(JsonKey.REQUEST , innerMap); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + innerMap.put(JsonKey.DATA, "uploadFILEData".getBytes()); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); @@ -84,15 +80,14 @@ public void testuploadFileService() { assertEquals(200, result.status()); } - private static String mapToJson(Map map){ + private static String mapToJson(Map map) { ObjectMapper mapperObj = new ObjectMapper(); String jsonResp = ""; try { jsonResp = mapperObj.writeValueAsString(map); } catch (IOException e) { - ProjectLogger.log(e.getMessage(),e); + ProjectLogger.log(e.getMessage(), e); } return jsonResp; } - } diff --git a/service/test/controllers/tenantpreference/TenantPreferenceControllerTest.java b/service/test/controllers/tenantpreference/TenantPreferenceControllerTest.java index 4f7b772bc8..788d616b4b 100644 --- a/service/test/controllers/tenantpreference/TenantPreferenceControllerTest.java +++ b/service/test/controllers/tenantpreference/TenantPreferenceControllerTest.java @@ -4,10 +4,16 @@ import static org.powermock.api.mockito.PowerMockito.when; import static play.test.Helpers.route; +import akka.actor.ActorRef; +import akka.actor.ActorSystem; +import akka.actor.Props; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import controllers.BaseController; +import controllers.DummyActor; import java.io.IOException; import java.util.HashMap; import java.util.Map; - import org.junit.BeforeClass; import org.junit.FixMethodOrder; import org.junit.Test; @@ -21,15 +27,6 @@ import org.sunbird.common.models.util.JsonKey; import org.sunbird.common.models.util.ProjectLogger; import org.sunbird.common.request.HeaderParam; - -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - -import akka.actor.ActorRef; -import akka.actor.ActorSystem; -import akka.actor.Props; -import controllers.BaseController; -import controllers.DummyActor; import play.libs.Json; import play.mvc.Http.RequestBuilder; import play.mvc.Result; @@ -37,9 +34,7 @@ import play.test.Helpers; import util.RequestInterceptor; -/** - * Created by arvind on 6/12/17. - */ +/** Created by arvind on 6/12/17. */ @FixMethodOrder(MethodSorters.NAME_ASCENDING) @RunWith(PowerMockRunner.class) @PrepareForTest(RequestInterceptor.class) @@ -47,7 +42,7 @@ public class TenantPreferenceControllerTest { private static FakeApplication app; - private static Map headerMap; + private static Map headerMap; private static ActorSystem system; private static final Props props = Props.create(DummyActor.class); @@ -56,10 +51,11 @@ public static void startApp() { app = Helpers.fakeApplication(); Helpers.start(app); headerMap = new HashMap(); - headerMap.put(HeaderParam.X_Consumer_ID.getName(), new String[]{"Service test consumer"}); - headerMap.put(HeaderParam.X_Device_ID.getName(), new String[]{"Some Device Id"}); - headerMap.put(HeaderParam.X_Authenticated_Userid.getName(), new String[]{"Authenticated user id"}); - headerMap.put(JsonKey.MESSAGE_ID, new String[]{"Unique Message id"}); + headerMap.put(HeaderParam.X_Consumer_ID.getName(), new String[] {"Service test consumer"}); + headerMap.put(HeaderParam.X_Device_ID.getName(), new String[] {"Some Device Id"}); + headerMap.put( + HeaderParam.X_Authenticated_Userid.getName(), new String[] {"Authenticated user id"}); + headerMap.put(JsonKey.MESSAGE_ID, new String[] {"Unique Message id"}); system = ActorSystem.create("system"); ActorRef subject = system.actorOf(props); @@ -69,17 +65,19 @@ public static void startApp() { @Test public void testcreateTanentPreference() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - innerMap.put(JsonKey.ROLE , "admin"); - innerMap.put(JsonKey.DATA , "displayPage"); - innerMap.put(JsonKey.ROOT_ORG_ID , "rootOrg001"); - requestMap.put(JsonKey.REQUEST , innerMap); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + innerMap.put(JsonKey.ROLE, "admin"); + innerMap.put(JsonKey.DATA, "displayPage"); + innerMap.put(JsonKey.ROOT_ORG_ID, "rootOrg001"); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); - RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/org/tc/create").method("POST"); + RequestBuilder req = + new RequestBuilder().bodyJson(json).uri("/v1/org/tc/create").method("POST"); req.headers(headerMap); Result result = route(req); assertEquals(200, result.status()); @@ -88,16 +86,18 @@ public void testcreateTanentPreference() { @Test public void testupdateTanentPreference() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - innerMap.put(JsonKey.ROLE , "admin"); - innerMap.put(JsonKey.DATA , "displayPage"); - requestMap.put(JsonKey.REQUEST , innerMap); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + innerMap.put(JsonKey.ROLE, "admin"); + innerMap.put(JsonKey.DATA, "displayPage"); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); - RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/org/tc/update").method("POST"); + RequestBuilder req = + new RequestBuilder().bodyJson(json).uri("/v1/org/tc/update").method("POST"); req.headers(headerMap); Result result = route(req); assertEquals(200, result.status()); @@ -106,7 +106,8 @@ public void testupdateTanentPreference() { @Test public void testGetTanentPreference() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); RequestBuilder req = new RequestBuilder().uri("/v1/org/tc/read/orgId").method("GET"); req.headers(headerMap); Result result = route(req); @@ -116,30 +117,31 @@ public void testGetTanentPreference() { @Test public void testupdateTCStatusOfUser() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - innerMap.put(JsonKey.USER_ID , "user123"); - innerMap.put(JsonKey.TERM_AND_CONDITION_STATUS , "accepted"); - requestMap.put(JsonKey.REQUEST , innerMap); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + innerMap.put(JsonKey.USER_ID, "user123"); + innerMap.put(JsonKey.TERM_AND_CONDITION_STATUS, "accepted"); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); - RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/user/tc/update").method("POST"); + RequestBuilder req = + new RequestBuilder().bodyJson(json).uri("/v1/user/tc/update").method("POST"); req.headers(headerMap); Result result = route(req); assertEquals(200, result.status()); } - private static String mapToJson(Map map){ + private static String mapToJson(Map map) { ObjectMapper mapperObj = new ObjectMapper(); String jsonResp = ""; try { jsonResp = mapperObj.writeValueAsString(map); } catch (IOException e) { - ProjectLogger.log(e.getMessage(),e); + ProjectLogger.log(e.getMessage(), e); } return jsonResp; } - } diff --git a/service/test/controllers/usermanagement/UserControllerTest.java b/service/test/controllers/usermanagement/UserControllerTest.java index efd05c3d7f..ba3ee01699 100644 --- a/service/test/controllers/usermanagement/UserControllerTest.java +++ b/service/test/controllers/usermanagement/UserControllerTest.java @@ -4,12 +4,18 @@ import static org.powermock.api.mockito.PowerMockito.when; import static play.test.Helpers.route; +import akka.actor.ActorRef; +import akka.actor.ActorSystem; +import akka.actor.Props; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import controllers.BaseController; +import controllers.DummyActor; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; - import org.junit.BeforeClass; import org.junit.FixMethodOrder; import org.junit.Test; @@ -23,15 +29,6 @@ import org.sunbird.common.models.util.JsonKey; import org.sunbird.common.models.util.ProjectLogger; import org.sunbird.common.request.HeaderParam; - -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - -import akka.actor.ActorRef; -import akka.actor.ActorSystem; -import akka.actor.Props; -import controllers.BaseController; -import controllers.DummyActor; import play.libs.Json; import play.mvc.Http.RequestBuilder; import play.mvc.Result; @@ -39,9 +36,7 @@ import play.test.Helpers; import util.RequestInterceptor; -/** - * Created by arvind on 6/12/17. - */ +/** Created by arvind on 6/12/17. */ @FixMethodOrder(MethodSorters.NAME_ASCENDING) @RunWith(PowerMockRunner.class) @PrepareForTest(RequestInterceptor.class) @@ -49,7 +44,7 @@ public class UserControllerTest { private static FakeApplication app; - private static Map headerMap; + private static Map headerMap; private static ActorSystem system; private static final Props props = Props.create(DummyActor.class); @@ -58,10 +53,11 @@ public static void startApp() { app = Helpers.fakeApplication(); Helpers.start(app); headerMap = new HashMap(); - headerMap.put(HeaderParam.X_Consumer_ID.getName(), new String[]{"Service test consumer"}); - headerMap.put(HeaderParam.X_Device_ID.getName(), new String[]{"Some Device Id"}); - headerMap.put(HeaderParam.X_Authenticated_Userid.getName(), new String[]{"Authenticated user id"}); - headerMap.put(JsonKey.MESSAGE_ID, new String[]{"Unique Message id"}); + headerMap.put(HeaderParam.X_Consumer_ID.getName(), new String[] {"Service test consumer"}); + headerMap.put(HeaderParam.X_Device_ID.getName(), new String[] {"Some Device Id"}); + headerMap.put( + HeaderParam.X_Authenticated_Userid.getName(), new String[] {"Authenticated user id"}); + headerMap.put(JsonKey.MESSAGE_ID, new String[] {"Unique Message id"}); system = ActorSystem.create("system"); ActorRef subject = system.actorOf(props); @@ -71,24 +67,25 @@ public static void startApp() { @Test public void testcreateUser() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - innerMap.put(JsonKey.PHONE , "8800088000"); - innerMap.put(JsonKey.COUNTRY_CODE,"+91"); - innerMap.put(JsonKey.EMAIL , "abbc@gmail.com"); - innerMap.put(JsonKey.USERNAME , "userName"); - innerMap.put(JsonKey.FIRST_NAME , "john"); - innerMap.put(JsonKey.LAST_NAME , "rambo"); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + innerMap.put(JsonKey.PHONE, "8800088000"); + innerMap.put(JsonKey.COUNTRY_CODE, "+91"); + innerMap.put(JsonKey.EMAIL, "abbc@gmail.com"); + innerMap.put(JsonKey.USERNAME, "userName"); + innerMap.put(JsonKey.FIRST_NAME, "john"); + innerMap.put(JsonKey.LAST_NAME, "rambo"); List roles = new ArrayList<>(); roles.add("user"); List languages = new ArrayList<>(); languages.add("hindi"); - innerMap.put(JsonKey.ROLES , roles); - innerMap.put(JsonKey.LANGUAGE , languages); + innerMap.put(JsonKey.ROLES, roles); + innerMap.put(JsonKey.LANGUAGE, languages); - requestMap.put(JsonKey.REQUEST , innerMap); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); @@ -101,24 +98,25 @@ public void testcreateUser() { @Test public void testcreateUserWithInvalidPhone() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - innerMap.put(JsonKey.PHONE , "00088000"); - innerMap.put(JsonKey.COUNTRY_CODE,"+91"); - innerMap.put(JsonKey.EMAIL , "abbc@gmail.com"); - innerMap.put(JsonKey.USERNAME , "userName"); - innerMap.put(JsonKey.FIRST_NAME , "john"); - innerMap.put(JsonKey.LAST_NAME , "rambo"); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + innerMap.put(JsonKey.PHONE, "00088000"); + innerMap.put(JsonKey.COUNTRY_CODE, "+91"); + innerMap.put(JsonKey.EMAIL, "abbc@gmail.com"); + innerMap.put(JsonKey.USERNAME, "userName"); + innerMap.put(JsonKey.FIRST_NAME, "john"); + innerMap.put(JsonKey.LAST_NAME, "rambo"); List roles = new ArrayList<>(); roles.add("user"); List languages = new ArrayList<>(); languages.add("hindi"); - innerMap.put(JsonKey.ROLES , roles); - innerMap.put(JsonKey.LANGUAGE , languages); + innerMap.put(JsonKey.ROLES, roles); + innerMap.put(JsonKey.LANGUAGE, languages); - requestMap.put(JsonKey.REQUEST , innerMap); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); @@ -131,24 +129,25 @@ public void testcreateUserWithInvalidPhone() { @Test public void testupdateUserProfile() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - innerMap.put(JsonKey.PHONE , "8800088000"); - innerMap.put(JsonKey.COUNTRY_CODE,"+91"); - innerMap.put(JsonKey.EMAIL , "abbc@gmail.com"); - //innerMap.put(JsonKey.USERNAME , "userName"); - innerMap.put(JsonKey.FIRST_NAME , "john"); - innerMap.put(JsonKey.LAST_NAME , "rambo"); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + innerMap.put(JsonKey.PHONE, "8800088000"); + innerMap.put(JsonKey.COUNTRY_CODE, "+91"); + innerMap.put(JsonKey.EMAIL, "abbc@gmail.com"); + // innerMap.put(JsonKey.USERNAME , "userName"); + innerMap.put(JsonKey.FIRST_NAME, "john"); + innerMap.put(JsonKey.LAST_NAME, "rambo"); List roles = new ArrayList<>(); roles.add("user"); List languages = new ArrayList<>(); languages.add("hindi"); - innerMap.put(JsonKey.ROLES , roles); - innerMap.put(JsonKey.LANGUAGE , languages); + innerMap.put(JsonKey.ROLES, roles); + innerMap.put(JsonKey.LANGUAGE, languages); - requestMap.put(JsonKey.REQUEST , innerMap); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); @@ -161,14 +160,15 @@ public void testupdateUserProfile() { @Test public void testlogin() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - innerMap.put(JsonKey.USERNAME , "userName"); - innerMap.put(JsonKey.PASSWORD , "john"); - innerMap.put(JsonKey.SOURCE , "src"); - - requestMap.put(JsonKey.REQUEST , innerMap); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + innerMap.put(JsonKey.USERNAME, "userName"); + innerMap.put(JsonKey.PASSWORD, "john"); + innerMap.put(JsonKey.SOURCE, "src"); + + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); @@ -181,12 +181,13 @@ public void testlogin() { @Test public void testlogout() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - innerMap.put(JsonKey.USERNAME , "userName"); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + innerMap.put(JsonKey.USERNAME, "userName"); - requestMap.put(JsonKey.REQUEST , innerMap); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); @@ -199,18 +200,20 @@ public void testlogout() { @Test public void testchangePassword() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); - innerMap.put(JsonKey.PASSWORD , "password"); - innerMap.put(JsonKey.NEW_PASSWORD , "newpssword"); + innerMap.put(JsonKey.PASSWORD, "password"); + innerMap.put(JsonKey.NEW_PASSWORD, "newpssword"); - requestMap.put(JsonKey.REQUEST , innerMap); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); - RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/user/changepassword").method("POST"); + RequestBuilder req = + new RequestBuilder().bodyJson(json).uri("/v1/user/changepassword").method("POST"); req.headers(headerMap); Result result = route(req); assertEquals(200, result.status()); @@ -219,7 +222,8 @@ public void testchangePassword() { @Test public void testgetUserProfile() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); RequestBuilder req = new RequestBuilder().uri("/v1/user/getprofile/userId").method("GET"); req.headers(headerMap); Result result = route(req); @@ -229,7 +233,8 @@ public void testgetUserProfile() { @Test public void testgetRoles() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); RequestBuilder req = new RequestBuilder().uri("/v1/role/read").method("GET"); req.headers(headerMap); Result result = route(req); @@ -239,13 +244,14 @@ public void testgetRoles() { @Test public void testgetUserDetailsByLoginId() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); - innerMap.put(JsonKey.LOGIN_ID , "loginid"); + innerMap.put(JsonKey.LOGIN_ID, "loginid"); - requestMap.put(JsonKey.REQUEST , innerMap); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); @@ -258,14 +264,16 @@ public void testgetUserDetailsByLoginId() { @Test public void testdownloadUsers() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - requestMap.put(JsonKey.REQUEST , innerMap); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); - RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/user/download").method("POST"); + RequestBuilder req = + new RequestBuilder().bodyJson(json).uri("/v1/user/download").method("POST"); req.headers(headerMap); Result result = route(req); assertEquals(200, result.status()); @@ -274,10 +282,11 @@ public void testdownloadUsers() { @Test public void testblockUser() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - requestMap.put(JsonKey.REQUEST , innerMap); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); @@ -290,18 +299,20 @@ public void testblockUser() { @Test public void testassignRoles() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - innerMap.put(JsonKey.USER_ID , "user123"); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + innerMap.put(JsonKey.USER_ID, "user123"); List roles = new ArrayList<>(); roles.add("user"); - innerMap.put(JsonKey.ROLES , roles); - requestMap.put(JsonKey.REQUEST , innerMap); + innerMap.put(JsonKey.ROLES, roles); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); - RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/user/assign/role").method("POST"); + RequestBuilder req = + new RequestBuilder().bodyJson(json).uri("/v1/user/assign/role").method("POST"); req.headers(headerMap); Result result = route(req); assertEquals(200, result.status()); @@ -310,10 +321,11 @@ public void testassignRoles() { @Test public void testunBlockUser() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - requestMap.put(JsonKey.REQUEST , innerMap); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); @@ -326,10 +338,11 @@ public void testunBlockUser() { @Test public void testsearch() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - requestMap.put(JsonKey.REQUEST , innerMap); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); @@ -342,14 +355,16 @@ public void testsearch() { @Test public void testupdateLoginTime() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - requestMap.put(JsonKey.REQUEST , innerMap); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); - RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/user/update/logintime").method("PATCH"); + RequestBuilder req = + new RequestBuilder().bodyJson(json).uri("/v1/user/update/logintime").method("PATCH"); req.headers(headerMap); Result result = route(req); assertEquals(200, result.status()); @@ -358,7 +373,8 @@ public void testupdateLoginTime() { @Test public void testgetMediaTypes() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); RequestBuilder req = new RequestBuilder().uri("/v1/user/mediatype/list").method("GET"); req.headers(headerMap); Result result = route(req); @@ -368,15 +384,17 @@ public void testgetMediaTypes() { @Test public void testforgotpassword() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - innerMap.put(JsonKey.USERNAME , "user01"); - requestMap.put(JsonKey.REQUEST , innerMap); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + innerMap.put(JsonKey.USERNAME, "user01"); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); - RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/user/forgotpassword").method("POST"); + RequestBuilder req = + new RequestBuilder().bodyJson(json).uri("/v1/user/forgotpassword").method("POST"); req.headers(headerMap); Result result = route(req); assertEquals(200, result.status()); @@ -385,36 +403,37 @@ public void testforgotpassword() { @Test public void testprofileVisibility() { PowerMockito.mockStatic(RequestInterceptor.class); - when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); - Map requestMap = new HashMap<>(); - Map innerMap = new HashMap<>(); - innerMap.put(JsonKey.USER_ID , "user01"); + when(RequestInterceptor.verifyRequestData(Mockito.anyObject())) + .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh"); + Map requestMap = new HashMap<>(); + Map innerMap = new HashMap<>(); + innerMap.put(JsonKey.USER_ID, "user01"); List privateFields = new ArrayList<>(); privateFields.add(JsonKey.PHONE); List publicFields = new ArrayList<>(); publicFields.add(JsonKey.EMAIL); - innerMap.put(JsonKey.PRIVATE , privateFields); - innerMap.put(JsonKey.PUBLIC , publicFields); - requestMap.put(JsonKey.REQUEST , innerMap); + innerMap.put(JsonKey.PRIVATE, privateFields); + innerMap.put(JsonKey.PUBLIC, publicFields); + requestMap.put(JsonKey.REQUEST, innerMap); String data = mapToJson(requestMap); JsonNode json = Json.parse(data); - RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/user/profile/visibility").method("POST"); + RequestBuilder req = + new RequestBuilder().bodyJson(json).uri("/v1/user/profile/visibility").method("POST"); req.headers(headerMap); Result result = route(req); assertEquals(200, result.status()); } - private static String mapToJson(Map map){ + private static String mapToJson(Map map) { ObjectMapper mapperObj = new ObjectMapper(); String jsonResp = ""; try { jsonResp = mapperObj.writeValueAsString(map); } catch (IOException e) { - ProjectLogger.log(e.getMessage(),e); + ProjectLogger.log(e.getMessage(), e); } return jsonResp; } - } diff --git a/tools/java-format/google-java-format-1.5-all-deps.jar b/tools/java-format/google-java-format-1.5-all-deps.jar new file mode 100644 index 0000000000..ada76955da Binary files /dev/null and b/tools/java-format/google-java-format-1.5-all-deps.jar differ