Fix minor code smells
[aai/search-data-service.git] / src / main / java / org / onap / aai / sa / rest / IndexApi.java
index 3371fcd..7d58fb3 100644 (file)
@@ -1,4 +1,4 @@
-/**
+/**
  * ============LICENSE_START=======================================================
  * org.onap.aai
  * ================================================================================
@@ -37,13 +37,16 @@ import org.springframework.http.HttpStatus;
 import org.springframework.http.MediaType;
 import org.springframework.http.ResponseEntity;
 
-
 /**
  * This class encapsulates the REST end points associated with manipulating indexes in the document store.
  */
 public class IndexApi {
 
 
+    private static final String UNKNOWN_LOG_FIELD_STR = "Unknown";
+    private static final String MSG_UNEXPECTED_AUTHENTICATION_FAILURE_CAUSE =
+            "Unexpected authentication failure - cause: ";
+    private static final String MSG_AUTHENTICATION_FAILURE = "Authentication failure.";
     private static final String HEADER_VALIDATION_SUCCESS = "SUCCESS";
     protected SearchServiceApi searchService = null;
 
@@ -89,26 +92,22 @@ public class IndexApi {
             HttpHeaders headers, String index, DocumentStoreInterface documentStore) {
 
         int resultCode = 500;
-        String resultString = "Unexpected error";
 
         // Initialize the MDC Context for logging purposes.
         ApiUtils.initMdcContext(request, headers);
 
-        // Validate that the request is correctly authenticated before going
-        // any further.
+        // Validate that the request is correctly authenticated before going any further.
         try {
-
             if (!searchService.validateRequest(headers, request, ApiUtils.Action.POST,
                     ApiUtils.SEARCH_AUTH_POLICY_NAME)) {
-                logger.warn(SearchDbMsgs.INDEX_CREATE_FAILURE, index, "Authentication failure.");
-                return errorResponse(HttpStatus.FORBIDDEN, "Authentication failure.", request);
+                logger.warn(SearchDbMsgs.INDEX_CREATE_FAILURE, index, MSG_AUTHENTICATION_FAILURE);
+                return errorResponse(HttpStatus.FORBIDDEN, MSG_AUTHENTICATION_FAILURE, request);
             }
 
         } catch (Exception e) {
-
             logger.warn(SearchDbMsgs.INDEX_CREATE_FAILURE, index,
-                    "Unexpected authentication failure - cause: " + e.getMessage());
-            return errorResponse(HttpStatus.FORBIDDEN, "Authentication failure.", request);
+                    MSG_UNEXPECTED_AUTHENTICATION_FAILURE_CAUSE + e.getMessage());
+            return errorResponse(HttpStatus.FORBIDDEN, MSG_AUTHENTICATION_FAILURE, request);
         }
 
 
@@ -119,8 +118,9 @@ public class IndexApi {
             return errorResponse(HttpStatus.valueOf(resultCode), "Missing payload", request);
         }
 
-        try {
+        String resultString;
 
+        try {
             // Marshal the supplied json string into a document schema object.
             ObjectMapper mapper = new ObjectMapper();
             DocumentSchema schema = mapper.readValue(documentSchema, DocumentSchema.class);
@@ -155,9 +155,7 @@ public class IndexApi {
         ResponseEntity<String> response =
                 ResponseEntity.status(resultCode).contentType(MediaType.APPLICATION_JSON).body(resultString);
 
-
-        // Log the result.
-        if ((response.getStatusCodeValue() >= 200) && (response.getStatusCodeValue() < 300)) {
+        if (ApiUtils.isSuccessStatusCode(response.getStatusCodeValue())) {
             logger.info(SearchDbMsgs.CREATED_INDEX, index);
         } else {
             logger.warn(SearchDbMsgs.INDEX_CREATE_FAILURE, index, resultString);
@@ -167,9 +165,9 @@ public class IndexApi {
         auditLogger.info(SearchDbMsgs.PROCESS_REST_REQUEST,
                 new LogFields().setField(LogLine.DefinedFields.RESPONSE_CODE, resultCode).setField(
                         LogLine.DefinedFields.RESPONSE_DESCRIPTION, HttpStatus.valueOf(resultCode).toString()),
-                (request != null) ? request.getMethod().toString() : "Unknown",
-                (request != null) ? request.getRequestURL().toString() : "Unknown",
-                (request != null) ? request.getRemoteHost() : "Unknown",
+                (request != null) ? request.getMethod() : UNKNOWN_LOG_FIELD_STR,
+                (request != null) ? request.getRequestURL().toString() : UNKNOWN_LOG_FIELD_STR,
+                (request != null) ? request.getRemoteHost() : UNKNOWN_LOG_FIELD_STR,
                 Integer.toString(response.getStatusCodeValue()));
 
 
@@ -229,54 +227,46 @@ public class IndexApi {
         // Initialize the MDC Context for logging purposes.
         ApiUtils.initMdcContext(request, headers);
 
-        // Set a default response in case something unexpected goes wrong.
-        ResponseEntity<String> response = ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Unknown");
+        ResponseEntity<String> response;
 
         // Validate that the request is correctly authenticated before going
         // any further.
         try {
-
             if (!searchService.validateRequest(headers, request, ApiUtils.Action.POST,
                     ApiUtils.SEARCH_AUTH_POLICY_NAME)) {
-                logger.warn(SearchDbMsgs.INDEX_CREATE_FAILURE, index, "Authentication failure.");
-                return errorResponse(HttpStatus.FORBIDDEN, "Authentication failure.", request);
+                logger.warn(SearchDbMsgs.INDEX_CREATE_FAILURE, index, MSG_AUTHENTICATION_FAILURE);
+                return errorResponse(HttpStatus.FORBIDDEN, MSG_AUTHENTICATION_FAILURE, request);
             }
 
         } catch (Exception e) {
-
             logger.warn(SearchDbMsgs.INDEX_CREATE_FAILURE, index,
-                    "Unexpected authentication failure - cause: " + e.getMessage());
-            return errorResponse(HttpStatus.FORBIDDEN, "Authentication failure.", request);
+                    MSG_UNEXPECTED_AUTHENTICATION_FAILURE_CAUSE + e.getMessage());
+            return errorResponse(HttpStatus.FORBIDDEN, MSG_AUTHENTICATION_FAILURE, request);
         }
 
-
         try {
             // Send the request to the document store.
             response = responseFromOperationResult(documentStore.deleteIndex(index));
-
         } catch (DocumentStoreOperationException e) {
             response = ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).contentType(MediaType.APPLICATION_JSON)
                     .body(e.getMessage());
         }
 
-        // Log the result.
-        if ((response.getStatusCodeValue() >= 200) && (response.getStatusCodeValue() < 300)) {
+        if (ApiUtils.isSuccessStatusCode(response.getStatusCodeValue())) {
             logger.info(SearchDbMsgs.DELETED_INDEX, index);
         } else {
             logger.warn(SearchDbMsgs.INDEX_DELETE_FAILURE, index, response.getBody());
         }
 
-        // Generate our audit log.
         auditLogger.info(SearchDbMsgs.PROCESS_REST_REQUEST,
                 new LogFields().setField(LogLine.DefinedFields.RESPONSE_CODE, response.getStatusCodeValue()).setField(
                         LogLine.DefinedFields.RESPONSE_DESCRIPTION, response.getStatusCode().getReasonPhrase()),
-                (request != null) ? request.getMethod().toString() : "Unknown",
-                (request != null) ? request.getRequestURL().toString() : "Unknown",
-                (request != null) ? request.getRemoteHost() : "Unknown",
+                (request != null) ? request.getMethod() : UNKNOWN_LOG_FIELD_STR,
+                (request != null) ? request.getRequestURL().toString() : UNKNOWN_LOG_FIELD_STR,
+                (request != null) ? request.getRemoteHost() : UNKNOWN_LOG_FIELD_STR,
                 Integer.toString(response.getStatusCodeValue()));
 
-        // Clear the MDC context so that no other transaction inadvertently
-        // uses our transaction id.
+        // Clear the MDC context so that no other transaction inadvertently uses our transaction id.
         ApiUtils.clearMdcContext();
 
         return response;
@@ -293,8 +283,7 @@ public class IndexApi {
      * @throws com.fasterxml.jackson.databind.JsonMappingException
      * @throws IOException
      */
-    public String generateDocumentMappings(String documentSchema) throws com.fasterxml.jackson.core.JsonParseException,
-            com.fasterxml.jackson.databind.JsonMappingException, IOException {
+    public String generateDocumentMappings(String documentSchema) throws IOException {
 
         // Unmarshal the json content into a document schema object.
         ObjectMapper mapper = new ObjectMapper();
@@ -356,7 +345,7 @@ public class IndexApi {
      */
     public ResponseEntity<String> responseFromOperationResult(OperationResult result) {
 
-        if ((result.getResultCode() >= 200) && (result.getResultCode() < 300)) {
+        if (ApiUtils.isSuccessStatusCode(result.getResultCode())) {
             return ResponseEntity.status(result.getResultCode()).contentType(MediaType.APPLICATION_JSON)
                     .body(result.getResult());
         } else {
@@ -376,9 +365,9 @@ public class IndexApi {
         auditLogger.info(SearchDbMsgs.PROCESS_REST_REQUEST,
                 new LogFields().setField(LogLine.DefinedFields.RESPONSE_CODE, status.value())
                         .setField(LogLine.DefinedFields.RESPONSE_DESCRIPTION, status.getReasonPhrase()),
-                (request != null) ? request.getMethod().toString() : "Unknown",
-                (request != null) ? request.getRequestURL().toString() : "Unknown",
-                (request != null) ? request.getRemoteHost() : "Unknown", Integer.toString(status.value()));
+                (request != null) ? request.getMethod() : UNKNOWN_LOG_FIELD_STR,
+                (request != null) ? request.getRequestURL().toString() : UNKNOWN_LOG_FIELD_STR,
+                (request != null) ? request.getRemoteHost() : UNKNOWN_LOG_FIELD_STR, Integer.toString(status.value()));
 
         // Clear the MDC context so that no other transaction inadvertently
         // uses our transaction id.
@@ -402,12 +391,12 @@ public class IndexApi {
         try {
             if (!searchService.validateRequest(headers, request, ApiUtils.Action.POST,
                     ApiUtils.SEARCH_AUTH_POLICY_NAME)) {
-                logger.warn(failureMsgEnum, index, "Authentication failure.");
-                return errorResponse(HttpStatus.FORBIDDEN, "Authentication failure.", request);
+                logger.warn(failureMsgEnum, index, MSG_AUTHENTICATION_FAILURE);
+                return errorResponse(HttpStatus.FORBIDDEN, MSG_AUTHENTICATION_FAILURE, request);
             }
         } catch (Exception e) {
-            logger.warn(failureMsgEnum, index, "Unexpected authentication failure - cause: " + e.getMessage());
-            return errorResponse(HttpStatus.FORBIDDEN, "Authentication failure.", request);
+            logger.warn(failureMsgEnum, index, MSG_UNEXPECTED_AUTHENTICATION_FAILURE_CAUSE + e.getMessage());
+            return errorResponse(HttpStatus.FORBIDDEN, MSG_AUTHENTICATION_FAILURE, request);
         }
         return ResponseEntity.status(HttpStatus.OK).body(HEADER_VALIDATION_SUCCESS);
     }