Skip to content

Commit

Permalink
Offensive Data Report APIs (#175)
Browse files Browse the repository at this point in the history
* APIs for Offensive Data Flags
  • Loading branch information
juhiagl8 authored Feb 20, 2023
1 parent 6b5b503 commit 0b4f145
Show file tree
Hide file tree
Showing 6 changed files with 247 additions and 5 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package org.sunbird.assessment.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.sunbird.assessment.service.OffensiveDataFlagService;
import org.sunbird.common.model.SBApiResponse;
import org.sunbird.common.util.Constants;

import javax.validation.Valid;
import java.util.Map;

@RestController
public class OffensiveDataReportController {

@Autowired
OffensiveDataFlagService offensiveDataFlagService;

@PostMapping("/v1/offensive/data/flag")
public ResponseEntity<SBApiResponse> createFlag(
@Valid @RequestBody Map<String, Object> requestBody, @RequestHeader(Constants.X_AUTH_TOKEN) String token) throws Exception {
SBApiResponse readResponse = offensiveDataFlagService.createFlag(requestBody, token);
return new ResponseEntity<>(readResponse, readResponse.getResponseCode());
}

@PatchMapping("/v1/offensive/data/flag")
public ResponseEntity<SBApiResponse> updateFlag(@RequestHeader(Constants.X_AUTH_TOKEN) String token,
@Valid @RequestBody Map<String, Object> request) {
SBApiResponse response = offensiveDataFlagService.updateFlag(token, request);
return new ResponseEntity<>(response, response.getResponseCode());
}

@GetMapping("/v1/offensive/data/flag/getFlaggedData")
public ResponseEntity<SBApiResponse> getFlaggedData(@RequestHeader(Constants.X_AUTH_TOKEN) String token) throws Exception {
SBApiResponse readResponse = offensiveDataFlagService.getFlaggedData(token);
return new ResponseEntity<>(readResponse, readResponse.getResponseCode());
}


}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package org.sunbird.assessment.service;

import org.sunbird.common.model.SBApiResponse;

import java.util.Map;

public interface OffensiveDataFlagService {
public SBApiResponse createFlag(Map<String, Object> requestBody, String token);

public SBApiResponse getFlaggedData(String token);

SBApiResponse updateFlag(String token, Map<String, Object> request);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,165 @@
package org.sunbird.assessment.service;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.sunbird.cassandra.utils.CassandraOperation;
import org.sunbird.common.model.SBApiResponse;
import org.sunbird.common.util.Constants;
import org.sunbird.common.util.ProjectUtil;
import org.sunbird.common.util.RequestInterceptor;

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

@Service
@SuppressWarnings("unchecked")
public class OffensiveDataFlagServiceImpl implements OffensiveDataFlagService {

private final Logger logger = LoggerFactory.getLogger(OffensiveDataFlagServiceImpl.class);

@Autowired
CassandraOperation cassandraOperation;

@Override
public SBApiResponse createFlag(Map<String, Object> requestBody, String token) {
String errMsg = "";
String userId = RequestInterceptor.fetchUserIdFromAccessToken(token);
errMsg = validateRequest(requestBody, userId, Constants.ADD);
SBApiResponse response = ProjectUtil.createDefaultResponse(Constants.ADD_OFFENSIVE_DATA_FLAG);
if (StringUtils.isEmpty(errMsg)) {
Map<String, Object> request = (Map<String, Object>) requestBody.get(Constants.REQUEST);
request.put(Constants.USER_ID, userId);
request.put(Constants.CONTEXT_STATUS, Constants.DRAFT);
request.put(Constants.CREATED_BY, userId);
request.put(Constants.CREATED_DATE, new Timestamp(new java.util.Date().getTime()));
SBApiResponse resp = cassandraOperation.insertRecord(Constants.KEYSPACE_SUNBIRD,
Constants.TABLE_OFFENSIVE_DATA_FLAGS, request);
if (!resp.get(Constants.RESPONSE).equals(Constants.SUCCESS)) {
errMsg = "Failed to add records into DB";
} else {
response.getResult().put(Constants.STATUS, Constants.CREATED);
}
}
if (StringUtils.isNotBlank(errMsg)) {
response.getParams().setStatus(Constants.FAILED);
response.getParams().setErrmsg(errMsg);
response.setResponseCode(HttpStatus.BAD_REQUEST);
return response;
}
return response;
}

@Override
public SBApiResponse updateFlag(String token, Map<String, Object> requestBody) {
String errMsg = "";
SBApiResponse response = ProjectUtil.createDefaultResponse(Constants.UPDATE_OFFENSIVE_DATA_FLAG);
String userId = RequestInterceptor.fetchUserIdFromAccessToken(token);
errMsg = validateRequest(requestBody, userId, Constants.UPDATE);
if (StringUtils.isEmpty(errMsg)) {
try {
Map<String, Object> request = (Map<String, Object>) requestBody.get(Constants.REQUEST);
Map<String, Object> compositeKeys = new HashMap<>();
compositeKeys.put(Constants.USER_ID, userId);
compositeKeys.put(Constants.CONTEXT_TYPE, request.get(Constants.CONTEXT_TYPE));
compositeKeys.put(Constants.CONTEXT_TYPE_ID, request.get(Constants.CONTEXT_TYPE_ID));
Map<String, Object> fieldsToBeUpdated = new HashMap<>();
fieldsToBeUpdated.put(Constants.CONTEXT_STATUS, request.get(Constants.CONTEXT_STATUS));
if(!ObjectUtils.isEmpty(request.get(Constants.ADDITIONAL_PARAMS))) {
fieldsToBeUpdated.put(Constants.ADDITIONAL_PARAMS, request.get(Constants.ADDITIONAL_PARAMS));
}
fieldsToBeUpdated.put(Constants.UPDATED_BY, userId);
fieldsToBeUpdated.put(Constants.UPDATED_DATE, new Timestamp(new java.util.Date().getTime()));
Map<String, Object> resp = cassandraOperation.updateRecord(Constants.KEYSPACE_SUNBIRD, Constants.TABLE_OFFENSIVE_DATA_FLAGS,
fieldsToBeUpdated, compositeKeys);
if (!resp.get(Constants.RESPONSE).equals(Constants.SUCCESS)) {
errMsg = (String) resp.get(Constants.ERROR_MESSAGE);
} else {
response.getResult().put(Constants.STATUS, Constants.UPDATED);
}
} catch (Exception e) {
errMsg = String.format("Failed to update an offensive flag with the details. Exception: ", e.getMessage());
logger.error(errMsg, e);
}
}
if (StringUtils.isNotBlank(errMsg)) {
response.getParams().setStatus(Constants.FAILED);
response.getParams().setErrmsg(errMsg);
response.setResponseCode(HttpStatus.BAD_REQUEST);
return response;
}
return response;
}

@Override
public SBApiResponse getFlaggedData(String token) {
String userId = RequestInterceptor.fetchUserIdFromAccessToken(token);
String errMsg = "";
SBApiResponse response = ProjectUtil.createDefaultResponse(Constants.GET_OFFENSIVE_DATA_FLAG);
if (userId != null) {
Map<String, Object> request = new HashMap<>();
request.put(Constants.USER_ID, userId);
List<Map<String, Object>> existingDataList = cassandraOperation.getRecordsByProperties(
Constants.KEYSPACE_SUNBIRD, Constants.TABLE_OFFENSIVE_DATA_FLAGS, request, null);
response.getResult().put("Content", existingDataList);
response.getResult().put("Count", existingDataList.size());
} else {
errMsg = "Invalid User Id";
}
if (StringUtils.isNotBlank(errMsg)) {
response.getParams().setStatus(Constants.FAILED);
response.getParams().setErrmsg(errMsg);
response.setResponseCode(HttpStatus.BAD_REQUEST);
return response;
}
return response;
}

private String validateRequest(Map<String, Object> requestBody, String userId, String type) {
if (StringUtils.isEmpty(userId)) {
return "Invalid User Id";
}
Map<String, Object> request = (Map<String, Object>) requestBody.get(Constants.REQUEST);
if (ObjectUtils.isEmpty(request)) {
return "Invalid Request.";
}

StringBuilder errMsg = new StringBuilder();
List<String> missingAttributes = new ArrayList<>();
List<String> errList = new ArrayList<>();

String contextType = (String) request.get(Constants.CONTEXT_TYPE);
if (StringUtils.isBlank(contextType)) {
missingAttributes.add(Constants.CONTEXT_TYPE);
}

String contextTypeId = (String) request.get(Constants.CONTEXT_TYPE_ID);
if (StringUtils.isBlank(contextTypeId)) {
missingAttributes.add(Constants.CONTEXT_TYPE_ID);
}

if(type.equalsIgnoreCase(Constants.UPDATE)) {
String contextStatus = (String) request.get(Constants.CONTEXT_STATUS);
if (StringUtils.isBlank(contextStatus)) {
missingAttributes.add(Constants.CONTEXT_STATUS);
}
}

if (!missingAttributes.isEmpty()) {
errMsg.append("Request doesn't have mandatory parameters - [").append(missingAttributes)
.append("]. ");
}

if (!errList.isEmpty()) {
errMsg.append(errList.toString());
}
return errMsg.toString();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,10 @@ public SBApiResponse insertRecord(String keyspaceName, String tableName, Map<Str
connectionManager.getSession(keyspaceName).execute(boundStatement.bind(array));
response.put(Constants.RESPONSE, Constants.SUCCESS);
} catch (Exception e) {
logger.error(
String.format("Exception occurred while inserting record to %s %s", tableName, e.getMessage()));
String errMsg = String.format("Exception occurred while inserting record to %s %s", tableName, e.getMessage());
logger.error(errMsg);
response.put(Constants.RESPONSE, Constants.FAILED);
response.put(Constants.ERROR_MESSAGE, errMsg);
}
return response;
}
Expand Down Expand Up @@ -225,7 +227,10 @@ public Map<String, Object> updateRecord(String keyspaceName, String tableName, M
session.execute(updateQuery);
response.put(Constants.RESPONSE, Constants.SUCCESS);
} catch (Exception e) {
logger.error(e.getMessage());
String errMsg = String.format("Exception occurred while updating record to %s %s", tableName, e.getMessage());
logger.error(errMsg);
response.put(Constants.RESPONSE, Constants.FAILED);
response.put(Constants.ERROR_MESSAGE, errMsg);
throw e;
}
return response;
Expand Down
15 changes: 14 additions & 1 deletion src/main/java/org/sunbird/common/util/Constants.java
Original file line number Diff line number Diff line change
Expand Up @@ -618,8 +618,21 @@ public class Constants {
COURSE_ORG_NAME);

public static final List<String> USER_ENROLMENT_COMMON_FIELDS = Arrays.asList(STATUS, COMPLETION_PERCENTAGE);

public static final String CONTEXT_TYPE = "contextType";
public static final String CONTEXT_TYPE_ID = "contextTypeId";
public static final String ADDITIONAL_PARAMS = "additionalParams";
public static final String CONTEXT_STATUS = "contextStatus";
public static final String TABLE_OFFENSIVE_DATA_FLAGS = "offensive_data_flags";
public static final String ADD_OFFENSIVE_DATA_FLAG = "api.add.offensive.data.flag";
public static final String UPDATE_OFFENSIVE_DATA_FLAG = "api.update.offensive.data.flag";
public static final String GET_OFFENSIVE_DATA_FLAG = "api.get.offensive.data.flag";
public static final String DRAFT = "DRAFT";
public static final Object CREATED = "Created";
public static final Object UPDATED = "Updated";

private Constants() {
throw new IllegalStateException("Utility class");
}

}
}
8 changes: 7 additions & 1 deletion src/main/resources/cassandratablecolumn.properties
Original file line number Diff line number Diff line change
Expand Up @@ -43,4 +43,10 @@ filename=fileName
rootorgid=rootOrgId
filepath=filePath
mapid=mapId
sborgid=sbOrgId
sborgid=sbOrgId
contexttype=contextType
contexttypeid=contextTypeId
acquiredchannel=acquiredChannel
additionalparams=additionalParams
requestedby=requestedBy
contextstatus=contextStatus

0 comments on commit 0b4f145

Please sign in to comment.