Skip to content

Commit

Permalink
Changes from previous releases
Browse files Browse the repository at this point in the history
  • Loading branch information
karthik-tarento committed Jan 20, 2022
1 parent 85948a3 commit c0fec6f
Show file tree
Hide file tree
Showing 29 changed files with 1,184 additions and 17 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package org.sunbird.common;

import org.sunbird.common.models.util.JsonKey;
import org.sunbird.common.request.Request;

import java.util.Map;
import java.util.HashMap;
import java.util.List;

public class Common {
public static Map<String, String[]> getRequestHeadersInArray(Map<String, List<String>> requestHeaders) {
Map<String, String[]> requestHeadersArray = new HashMap();
requestHeaders.entrySet().forEach(entry -> requestHeadersArray.put(entry.getKey(), entry.getValue().toArray(new String[0])));
return requestHeadersArray;
}

public static void handleFixedBatchIdRequest(Request request) {
String courseIdKey = request.getRequest().containsKey(JsonKey.COURSE_ID)
? JsonKey.COURSE_ID
: (request.getRequest().containsKey(JsonKey.ENROLLABLE_ITEM_ID)
? JsonKey.ENROLLABLE_ITEM_ID
: JsonKey.COLLECTION_ID);
String courseId = request.getRequest().getOrDefault(courseIdKey, "").toString();
request.getRequest().put(JsonKey.COURSE_ID, courseId);
//Till we add a type, we will use fixed batch identifier to prefix to course to get the batchId
String fixedBatchId = request.getRequest().getOrDefault(JsonKey.FIXED_BATCH_ID, "").toString();
String batchId = request.getRequest().getOrDefault(JsonKey.BATCH_ID, "").toString();
if (!fixedBatchId.isEmpty()) {
batchId = formBatchIdForFixedBatchId(courseId, fixedBatchId);
}
request.getRequest().put(JsonKey.BATCH_ID, batchId);
}

public static String formBatchIdForFixedBatchId(String courseId, String fixedBatchId) {
return fixedBatchId + "-" + courseId;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,9 @@ public final class SunbirdKey {
public static final String ACTIVITY_TYPE = "activity_type";
public static final String USER_ID = "user_id";
public static final String RESPONSE = "response";

public static final String COLLECTION = "collection";
public static final String EVENT_SET = "eventSet";
public static final String OBJECT_TYPE = "objectType";

private SunbirdKey() {}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
package org.sunbird.learner.actors.event;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import org.sunbird.common.models.response.Response;
import org.sunbird.common.models.util.JsonKey;
import org.sunbird.common.request.Request;
import org.sunbird.common.responsecode.ResponseCode;
import org.sunbird.keys.SunbirdKey;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.sunbird.common.models.util.JsonKey.EKSTEP_BASE_URL;
import static org.sunbird.common.models.util.ProjectUtil.getConfigValue;

public class EventContentUtil {

private static final ObjectMapper mapper = new ObjectMapper();

public static List<String> getChildEventIds(Request request, String eventSetId) throws JsonProcessingException, UnirestException {
Response response = getContent(request, JsonKey.IDENTIFIER, eventSetId, new HashMap<>(), "/eventset/v4/hierarchy/{identifier}");
if (response != null && response.getResponseCode().getResponseCode() == ResponseCode.OK.getResponseCode()) {
Map<String, Object> result = (Map<String, Object>) response.getResult().getOrDefault(SunbirdKey.EVENT_SET, new HashMap<String, Object>());
return (List<String>) result.getOrDefault("childNodes", new ArrayList<String>());
}
else
return new ArrayList<>();
}

private static Response getContent(Request request, String pathId, String pathValue, Map<String, Object> queryMap, String uri) throws UnirestException, JsonProcessingException {
String requestUrl = getConfigValue(EKSTEP_BASE_URL) + uri;
Map<String, String> headers = new HashMap<>();
headers.put(SunbirdKey.CONTENT_TYPE_HEADER, SunbirdKey.APPLICATION_JSON);
headers.put(SunbirdKey.X_CHANNEL_ID, request.getContext().getOrDefault(SunbirdKey.CHANNEL, "").toString());
HttpResponse<String> httpResponse = Unirest.get(requestUrl).headers(headers).routeParam(pathId, pathValue).queryString(queryMap).asString();
Response response = null;
if (null != httpResponse) {
response = mapper.readValue(httpResponse.getBody(), Response.class);
}
return response;
}

public static Response postContent(Request request, String contentKey, String uri, Map<String, Object> contentMap, String pathId, String pathVal) throws UnirestException, JsonProcessingException {
String requestUrl = getConfigValue(EKSTEP_BASE_URL) + uri;
Map<String, String> headers = new HashMap<String, String>() {{
put(SunbirdKey.CONTENT_TYPE_HEADER, SunbirdKey.APPLICATION_JSON);
put(SunbirdKey.X_CHANNEL_ID, (String) request.getContext().get(SunbirdKey.CHANNEL));
}};
Map<String, Object> requestMap = new HashMap<String, Object>() {{
put(SunbirdKey.REQUEST, new HashMap<String, Object>() {{
put(contentKey, contentMap);
}});
}};

HttpResponse<String> updateResponse =
Unirest.patch(requestUrl)
.headers(headers)
.routeParam(pathId, pathVal)
.body(mapper.writeValueAsString(requestMap))
.asString();

Response response = null;
if (null != updateResponse) response = mapper.readValue(updateResponse.getBody(), Response.class);
return response;
}

public static Response deleteContent(Request request, String uri, String pathId, String pathVal) throws UnirestException, JsonProcessingException {
String requestUrl = getConfigValue(EKSTEP_BASE_URL) + uri;
Map<String, String> headers = new HashMap<String, String>() {{
put(SunbirdKey.CONTENT_TYPE_HEADER, SunbirdKey.APPLICATION_JSON);
put(SunbirdKey.X_CHANNEL_ID, (String) request.getContext().get(SunbirdKey.CHANNEL));
}};

HttpResponse<String> updateResponse =
Unirest.delete(requestUrl)
.headers(headers)
.routeParam(pathId, pathVal)
.asString();

Response response = null;
if (null != updateResponse) response = mapper.readValue(updateResponse.getBody(), Response.class);
return response;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
package org.sunbird.learner.actors.event;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.sunbird.actor.base.BaseActor;
import org.sunbird.common.Common;
import org.sunbird.common.exception.ProjectCommonException;
import org.sunbird.common.models.response.Response;
import org.sunbird.common.models.util.JsonKey;
import org.sunbird.common.request.Request;
import org.sunbird.common.responsecode.ResponseCode;
import org.sunbird.keys.SunbirdKey;
import org.sunbird.learner.actors.coursebatch.service.UserCoursesService;

import java.text.MessageFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

public class EventManagementActor extends BaseActor {

private final UserCoursesService userCoursesService = new UserCoursesService();

@Override
public void onReceive(Request request) throws Throwable {
String requestedOperation = request.getOperation();
switch (requestedOperation) {
case "discardEvent":
discardEvent(request);
break;
default:
onReceiveUnsupportedOperation(requestedOperation);
break;
}
}

private void discardEvent(Request request) throws Exception {
validateNoEnrollments(request);
String pathId = JsonKey.IDENTIFIER;
String pathVal = request.getRequest().getOrDefault(JsonKey.IDENTIFIER, "").toString();
Response response = EventContentUtil.deleteContent(request, "/private/event/v4/discard/{identifier}", pathId, pathVal);
try {
if (response != null && response.getResponseCode().getResponseCode() == ResponseCode.OK.getResponseCode()) {
sender().tell(response, self());
} else if (response != null) {
Map<String, Object> resultMap =
Optional.ofNullable(response.getResult()).orElse(new HashMap<>());
String message = "Event discard failed ";
if (MapUtils.isNotEmpty(resultMap)) {
Object obj = Optional.ofNullable(resultMap.get(SunbirdKey.TB_MESSAGES)).orElse("");
if (obj instanceof List) {
message += ((List<String>) obj).stream().collect(Collectors.joining(";"));
} else if (StringUtils.isNotEmpty(response.getParams().getErrmsg())) {
message += response.getParams().getErrmsg();
} else {
message += String.valueOf(obj);
}
}
ProjectCommonException.throwClientErrorException(
ResponseCode.customServerError,
MessageFormat.format(
ResponseCode.customServerError.getErrorMessage(), message));
} else {
ProjectCommonException.throwClientErrorException(ResponseCode.CLIENT_ERROR);
}
} catch (Exception ex) {
logger.error(request.getRequestContext(), "EventManagementActor:discardEvent : discard error ", ex);
if (ex instanceof ProjectCommonException) {
throw ex;
} else {
throw new ProjectCommonException(
ResponseCode.SERVER_ERROR.getErrorCode(),
ResponseCode.SERVER_ERROR.getErrorMessage(),
ResponseCode.SERVER_ERROR.getResponseCode());
}
}
}

private void validateNoEnrollments(Request request) {
String identifier = request.get(SunbirdKey.IDENTIFIER).toString();
String fixedBatchId = request.get(JsonKey.FIXED_BATCH_ID).toString();
String batchId = Common.formBatchIdForFixedBatchId(identifier, fixedBatchId);
List<String> participants = userCoursesService.getParticipantsList(batchId, true, request.getRequestContext());
if (!participants.isEmpty()) {
ProjectCommonException.throwClientErrorException(
ResponseCode.cannotUpdateEventSetHavingEnrollments,
ResponseCode.cannotUpdateEventSetHavingEnrollments.getErrorMessage());
}
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
package org.sunbird.learner.actors.event;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.mashape.unirest.http.exceptions.UnirestException;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.sunbird.actor.base.BaseActor;
import org.sunbird.common.Common;
import org.sunbird.common.exception.ProjectCommonException;
import org.sunbird.common.models.response.Response;
import org.sunbird.common.models.util.JsonKey;
import org.sunbird.common.request.Request;
import org.sunbird.common.responsecode.ResponseCode;
import org.sunbird.keys.SunbirdKey;
import org.sunbird.learner.actors.coursebatch.service.UserCoursesService;

import java.text.MessageFormat;
import java.util.*;
import java.util.stream.Collectors;

public class EventSetManagementActor extends BaseActor {
private final UserCoursesService userCoursesService = new UserCoursesService();

@Override
public void onReceive(Request request) throws Throwable {
String requestedOperation = request.getOperation();
switch (requestedOperation) {
case "updateEventSet":
updateEventSet(request);
break;
case "discardEventSet":
discardEventSet(request);
break;
default:
onReceiveUnsupportedOperation(requestedOperation);
break;
}
}

private void updateEventSet(Request request) throws Exception {
validateNoEventEnrollments(request);
try {
Map<String, Object> contentMap = new HashMap<>((Map<String, Object>) request.get(SunbirdKey.EVENT_SET));
String pathId = JsonKey.IDENTIFIER;
String pathVal = request.getRequest().getOrDefault(JsonKey.IDENTIFIER, "").toString();
Response response = EventContentUtil.postContent(request, SunbirdKey.EVENT_SET, "/private/eventset/v4/update/{identifier}", contentMap, pathId, pathVal);
if (null != response) {
if (response.getResponseCode().getResponseCode() == ResponseCode.OK.getResponseCode()) {
sender().tell(response, self());
} else {
String message = formErrorDetailsMessage(response, "EventSet updation failed ");
ProjectCommonException.throwClientErrorException(
ResponseCode.customServerError,
MessageFormat.format(
ResponseCode.customServerError.getErrorMessage(), message));
}
} else {
ProjectCommonException.throwClientErrorException(ResponseCode.CLIENT_ERROR);
}
} catch (Exception ex) {
logger.error(request.getRequestContext(), "EventSetManagementActor:updateEventSet : update error ", ex);
if (ex instanceof ProjectCommonException) {
throw ex;
} else {
throw new ProjectCommonException(
ResponseCode.SERVER_ERROR.getErrorCode(),
ResponseCode.SERVER_ERROR.getErrorMessage(),
ResponseCode.SERVER_ERROR.getResponseCode());
}
}
}

private String formErrorDetailsMessage(Response response, String message) {
Map<String, Object> resultMap =
Optional.ofNullable(response.getResult()).orElse(new HashMap<>());
if (MapUtils.isNotEmpty(resultMap)) {
Object obj = Optional.ofNullable(resultMap.get(SunbirdKey.TB_MESSAGES)).orElse("");
if (obj instanceof List) {
message += ((List<String>) obj).stream().collect(Collectors.joining(";"));
} else if (StringUtils.isNotEmpty(response.getParams().getErrmsg())) {
message += response.getParams().getErrmsg();
} else {
message += String.valueOf(obj);
}
}
return message;
}

private void discardEventSet(Request request) throws Exception {
validateNoEventEnrollments(request);
try {
String pathId = JsonKey.IDENTIFIER;
String pathVal = request.getRequest().getOrDefault(JsonKey.IDENTIFIER, "").toString();
Response response = EventContentUtil.deleteContent(request, "/private/eventset/v4/discard/{identifier}", pathId, pathVal);
if (null != response) {
if (response.getResponseCode().getResponseCode() == ResponseCode.OK.getResponseCode()) {
sender().tell(response, self());
} else {
String message = formErrorDetailsMessage(response, "EventSet discard failed ");
ProjectCommonException.throwClientErrorException(
ResponseCode.customServerError,
MessageFormat.format(
ResponseCode.customServerError.getErrorMessage(), message));
}
} else {
ProjectCommonException.throwClientErrorException(ResponseCode.CLIENT_ERROR);
}
} catch (Exception ex) {
logger.error(request.getRequestContext(), "EventSetManagementActor:discardEventSet : discard error ", ex);
if (ex instanceof ProjectCommonException) {
throw ex;
} else {
throw new ProjectCommonException(
ResponseCode.SERVER_ERROR.getErrorCode(),
ResponseCode.SERVER_ERROR.getErrorMessage(),
ResponseCode.SERVER_ERROR.getResponseCode());
}
}
}

private void validateNoEventEnrollments(Request request) {
String identifier = request.get(SunbirdKey.IDENTIFIER).toString();
String fixedBatchId = request.get(JsonKey.FIXED_BATCH_ID).toString();
List<String> participants = new ArrayList<>();
try {
List<String> eventsIds = EventContentUtil.getChildEventIds(request, identifier);
participants = eventsIds.stream().map(childId -> {
String childBatchId = Common.formBatchIdForFixedBatchId(childId, fixedBatchId);
return userCoursesService.getParticipantsList(childBatchId, true, request.getRequestContext());
})
.filter(Objects::nonNull)
.flatMap(List::stream)
.collect(Collectors.toList());
} catch (UnirestException | JsonProcessingException e) {
ProjectCommonException.throwServerErrorException(
ResponseCode.SERVER_ERROR,
e.getMessage());
}
if (!participants.isEmpty()) {
ProjectCommonException.throwClientErrorException(
ResponseCode.cannotUpdateEventSetHavingEnrollments,
ResponseCode.cannotUpdateEventSetHavingEnrollments.getErrorMessage());
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ private static void initializeDBProperty() {
JsonKey.LEARNER_CONTENT_DB, getDbInfoObject(COURSE_KEY_SPACE_NAME, "user_content_consumption"));
dbInfoMap.put(
JsonKey.COURSE_MANAGEMENT_DB, getDbInfoObject(KEY_SPACE_NAME, "course_management"));
dbInfoMap.put(JsonKey.COURSE_USER_ENROLMENTS_DB, getDbInfoObject(COURSE_KEY_SPACE_NAME, "user_enrolments"));
dbInfoMap.put(JsonKey.PAGE_MGMT_DB, getDbInfoObject(KEY_SPACE_NAME, "page_management"));
dbInfoMap.put(JsonKey.PAGE_SECTION_DB, getDbInfoObject(KEY_SPACE_NAME, "page_section"));
dbInfoMap.put(JsonKey.SECTION_MGMT_DB, getDbInfoObject(KEY_SPACE_NAME, "page_section"));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ public class CourseBatchNotificationActor extends BaseActor {
.getProperty(JsonKey.SUNBIRD_COURSE_BATCH_NOTIFICATION_SIGNATURE);
private static String baseUrl =
PropertiesCache.getInstance().getProperty(JsonKey.SUNBIRD_WEB_URL);
private static String courseBatchPath =
PropertiesCache.getInstance().getProperty(JsonKey.COURSE_BATCH_PATH);
private UserOrgService userOrgService = UserOrgServiceImpl.getInstance();

@Override
Expand Down
Loading

0 comments on commit c0fec6f

Please sign in to comment.