diff options
author | mark.j.leonard <mark.j.leonard@gmail.com> | 2018-09-21 17:14:05 +0100 |
---|---|---|
committer | mark.j.leonard <mark.j.leonard@gmail.com> | 2018-09-21 17:14:05 +0100 |
commit | f637a36c9df966c341727910e30241b63cc49c06 (patch) | |
tree | 3e2eed7c0b4b25a67b602399a75eee09b726c07d /src/main | |
parent | 15af66b115f3e8046b2d0f2634fb77b3d835f730 (diff) |
Fix simple Sonar Lint issues
Address all the trivial Sonar issues (ignoring some duplicated strings)
Change-Id: I5a15d42e6ae316f4c5b1dea5f42f604cec8c82a8
Issue-ID: AAI-1650
Signed-off-by: mark.j.leonard <mark.j.leonard@gmail.com>
Diffstat (limited to 'src/main')
17 files changed, 479 insertions, 574 deletions
diff --git a/src/main/java/org/onap/aai/sa/Application.java b/src/main/java/org/onap/aai/sa/Application.java index 4fe2202..620dbee 100644 --- a/src/main/java/org/onap/aai/sa/Application.java +++ b/src/main/java/org/onap/aai/sa/Application.java @@ -29,9 +29,7 @@ import org.springframework.boot.web.support.SpringBootServletInitializer; @SpringBootApplication
public class Application extends SpringBootServletInitializer {
-
public static void main(String[] args) {
-
String keyStorePassword = System.getProperty("KEY_STORE_PASSWORD");
if (keyStorePassword == null || keyStorePassword.isEmpty()) {
throw new RuntimeException("Env property KEY_STORE_PASSWORD not set");
diff --git a/src/main/java/org/onap/aai/sa/auth/SearchDbServiceAuthCore.java b/src/main/java/org/onap/aai/sa/auth/SearchDbServiceAuthCore.java index 48743b6..95c48c3 100644 --- a/src/main/java/org/onap/aai/sa/auth/SearchDbServiceAuthCore.java +++ b/src/main/java/org/onap/aai/sa/auth/SearchDbServiceAuthCore.java @@ -1,4 +1,4 @@ -/** +/** * ============LICENSE_START======================================================= * org.onap.aai * ================================================================================ @@ -42,7 +42,7 @@ public class SearchDbServiceAuthCore { private static Logger logger = LoggerFactory.getInstance().getLogger(SearchDbServiceAuthCore.class.getName()); - private static String GlobalAuthFileName = SearchDbConstants.SDB_AUTH_CONFIG_FILENAME; + private static String authFileName = SearchDbConstants.SDB_AUTH_CONFIG_FILENAME; private enum HTTP_METHODS { POST, @@ -56,39 +56,26 @@ public class SearchDbServiceAuthCore { private static boolean usersInitialized = false; private static HashMap<String, SearchDbAuthUser> users; - private static boolean timerSet = false; private static Timer timer = null; - public synchronized static void init() { - - - SearchDbServiceAuthCore.getConfigFile(); + public static synchronized void init() { + if (SearchDbServiceAuthCore.authFileName == null) { + SearchDbServiceAuthCore.authFileName = "/home/aaiadmin/etc/aaipolicy.json"; + } SearchDbServiceAuthCore.reloadUsers(); - } public static void cleanup() { timer.cancel(); } - public static String getConfigFile() { - if (GlobalAuthFileName == null) { - String nc = GlobalAuthFileName; - if (nc == null) { - nc = "/home/aaiadmin/etc/aaipolicy.json"; - } - GlobalAuthFileName = nc; - } - return GlobalAuthFileName; - } - - public synchronized static void reloadUsers() { + public static synchronized void reloadUsers() { users = new HashMap<>(); ObjectMapper mapper = new ObjectMapper(); // can reuse, share globally JSONParser parser = new JSONParser(); try { - parser.parse(new FileReader(GlobalAuthFileName)); - JsonNode rootNode = mapper.readTree(new File(GlobalAuthFileName)); + parser.parse(new FileReader(authFileName)); + JsonNode rootNode = mapper.readTree(new File(authFileName)); JsonNode rolesNode = rootNode.path("roles"); for (JsonNode roleNode : rolesNode) { @@ -109,18 +96,16 @@ public class SearchDbServiceAuthCore { authRole.addAllowedFunction(thisFunction); } - if (hasMethods == false) { + if (!hasMethods) { // iterate the list from HTTP_METHODS for (HTTP_METHODS meth : HTTP_METHODS.values()) { String thisFunction = meth.toString() + ":" + function; - authRole.addAllowedFunction(thisFunction); } } } for (JsonNode userNode : usersNode) { - // make the user lower case String username = userNode.path("username").asText().toLowerCase(); SearchDbAuthUser authUser = null; if (users.containsKey(username)) { @@ -129,7 +114,6 @@ public class SearchDbServiceAuthCore { authUser = new SearchDbAuthUser(); } - authUser.setUser(username); authUser.addRole(roleName, authRole); users.put(username, authUser); @@ -164,7 +148,7 @@ public class SearchDbServiceAuthCore { return this.username; } - public HashMap<String, TabularAuthRole> getRoles() { + public Map<String, TabularAuthRole> getRoles() { return this.roles; } @@ -208,15 +192,11 @@ public class SearchDbServiceAuthCore { } public boolean hasAllowedFunction(String afunc) { - if (this.allowedFunctions.contains(afunc)) { - return true; - } else { - return false; - } + return this.allowedFunctions.contains(afunc); } } - public static HashMap<String, SearchDbAuthUser> getUsers(String key) { + public static Map<String, SearchDbAuthUser> getUsers() { if (!usersInitialized || (users == null)) { reloadUsers(); } @@ -224,21 +204,12 @@ public class SearchDbServiceAuthCore { } public static boolean authorize(String username, String authFunction) { - if (!usersInitialized || (users == null)) { init(); } if (users.containsKey(username)) { - if (users.get(username).checkAllowed(authFunction) == true) { - - return true; - } else { - - - return false; - } + return users.get(username).checkAllowed(authFunction); } else { - return false; } } diff --git a/src/main/java/org/onap/aai/sa/rest/AnalyzerApi.java b/src/main/java/org/onap/aai/sa/rest/AnalyzerApi.java index 59b526f..664124d 100644 --- a/src/main/java/org/onap/aai/sa/rest/AnalyzerApi.java +++ b/src/main/java/org/onap/aai/sa/rest/AnalyzerApi.java @@ -1,4 +1,4 @@ -/** +/** * ============LICENSE_START======================================================= * org.onap.aai * ================================================================================ @@ -46,116 +46,113 @@ import org.springframework.web.bind.annotation.RestController; @RequestMapping("/services/search-data-service/v1/analyzers/search") public class AnalyzerApi { - private SearchServiceApi searchService = null; + private SearchServiceApi searchService = null; - // Set up the loggers. - private static Logger logger = LoggerFactory.getInstance().getLogger(IndexApi.class.getName()); + // Set up the loggers. + private static Logger logger = LoggerFactory.getInstance().getLogger(IndexApi.class.getName()); private static Logger auditLogger = LoggerFactory.getInstance().getAuditLogger(IndexApi.class.getName()); - public AnalyzerApi(@Qualifier("searchServiceApi") SearchServiceApi searchService) { - this.searchService = searchService; - } + public AnalyzerApi( @Qualifier("searchServiceApi") SearchServiceApi searchService) { + this.searchService = searchService; + } @RequestMapping(method = RequestMethod.GET, consumes = {"application/json"}, produces = {"application/json"}) public ResponseEntity<String> processGet(HttpServletRequest request, @RequestHeader HttpHeaders headers, - ApiUtils apiUtils) { + ApiUtils apiUtils) { - HttpStatus responseCode = HttpStatus.INTERNAL_SERVER_ERROR; - String responseString = "Undefined error"; + HttpStatus responseCode = HttpStatus.INTERNAL_SERVER_ERROR; + String responseString; - // Initialize the MDC Context for logging purposes. - ApiUtils.initMdcContext(request, headers); + // Initialize the MDC Context for logging purposes. + ApiUtils.initMdcContext(request, headers); - // Validate that the request is correctly authenticated before going - // any further. - try { + // Validate that the request is correctly authenticated before going + // any further. + try { if (!searchService.validateRequest(headers, request, ApiUtils.Action.GET, ApiUtils.SEARCH_AUTH_POLICY_NAME)) { - logger.warn(SearchDbMsgs.GET_ANALYZERS_FAILURE, "Authentication failure."); + logger.warn(SearchDbMsgs.GET_ANALYZERS_FAILURE, "Authentication failure."); return ResponseEntity.status(HttpStatus.FORBIDDEN).contentType(MediaType.APPLICATION_JSON) .body("Authentication failure."); - } + } - } catch (Exception e) { + } catch (Exception e) { - logger.warn(SearchDbMsgs.GET_ANALYZERS_FAILURE, - "Unexpected authentication failure - cause: " + e.getMessage()); + logger.warn(SearchDbMsgs.GET_ANALYZERS_FAILURE, + "Unexpected authentication failure - cause: " + e.getMessage()); return ResponseEntity.status(HttpStatus.FORBIDDEN).contentType(MediaType.APPLICATION_JSON) .body("Authentication failure."); - } + } - // Now, build the list of analyzers. - try { + // Now, build the list of analyzers. + try { responseString = buildAnalyzerList(ElasticSearchHttpController.getInstance().getAnalysisConfig()); - responseCode = HttpStatus.OK; - - } catch (Exception e) { - - logger.warn(SearchDbMsgs.GET_ANALYZERS_FAILURE, - "Unexpected failure retrieving analysis configuration - cause: " + e.getMessage()); - responseString = "Failed to retrieve analysis configuration. Cause: " + e.getMessage(); - } + responseCode = HttpStatus.OK; + } catch (Exception e) { + logger.warn(SearchDbMsgs.GET_ANALYZERS_FAILURE, + "Unexpected failure retrieving analysis configuration - cause: " + e.getMessage()); + responseString = "Failed to retrieve analysis configuration. Cause: " + e.getMessage(); + } - // Build the HTTP response. - ResponseEntity response = + // Build the HTTP response. + ResponseEntity<String> response = ResponseEntity.status(responseCode).contentType(MediaType.APPLICATION_JSON).body(responseString); - // Generate our audit log. - auditLogger.info(SearchDbMsgs.PROCESS_REST_REQUEST, + // Generate our audit log. + auditLogger.info(SearchDbMsgs.PROCESS_REST_REQUEST, new LogFields().setField(LogLine.DefinedFields.RESPONSE_CODE, responseCode.value()) - .setField(LogLine.DefinedFields.RESPONSE_DESCRIPTION, responseCode.value()), - (request != null) ? request.getMethod() : "Unknown", - (request != null) ? request.getRequestURL().toString() : "Unknown", - (request != null) ? request.getRemoteHost() : "Unknown", - Integer.toString(response.getStatusCodeValue())); - - // Clear the MDC context so that no other transaction inadvertently - // uses our transaction id. - ApiUtils.clearMdcContext(); + .setField(LogLine.DefinedFields.RESPONSE_DESCRIPTION, responseCode.value()), + (request != null) ? request.getMethod() : "Unknown", + (request != null) ? request.getRequestURL ().toString () : "Unknown", + (request != null) ? request.getRemoteHost () : "Unknown", + Integer.toString(response.getStatusCodeValue ())); - return response; - } + // Clear the MDC context so that no other transaction inadvertently + // uses our transaction id. + ApiUtils.clearMdcContext(); + return response; + } - /** + /** * This method takes a list of analyzer objects and generates a simple json structure to enumerate them. - * + * * <p> * Note, this includes only the aspects of the analyzer object that we want to make public to an external client. - * + * * @param analysisConfig - The analysis configuration object to extract the analyzers from. - * @return - A json string enumerating the defined analyzers. - */ - private String buildAnalyzerList(AnalysisConfiguration analysisConfig) { - - StringBuilder sb = new StringBuilder(); - - sb.append("{"); - AtomicBoolean firstAnalyzer = new AtomicBoolean(true); - for (AnalyzerSchema analyzer : analysisConfig.getAnalyzers()) { - - if (!firstAnalyzer.compareAndSet(true, false)) { - sb.append(", "); - } - - sb.append("{"); - sb.append("\"name\": \"").append(analyzer.getName()).append("\", "); - sb.append("\"description\": \"").append(analyzer.getDescription()).append("\", "); - sb.append("\"behaviours\": ["); - AtomicBoolean firstBehaviour = new AtomicBoolean(true); - for (String behaviour : analyzer.getBehaviours()) { - if (!firstBehaviour.compareAndSet(true, false)) { - sb.append(", "); - } - sb.append("\"").append(behaviour).append("\""); - } - sb.append("]"); - sb.append("}"); + * @return - A json string enumerating the defined analyzers. + */ + private String buildAnalyzerList(AnalysisConfiguration analysisConfig) { + + StringBuilder sb = new StringBuilder(); + + sb.append("{"); + AtomicBoolean firstAnalyzer = new AtomicBoolean(true); + for (AnalyzerSchema analyzer : analysisConfig.getAnalyzers()) { + + if (!firstAnalyzer.compareAndSet(true, false)) { + sb.append(", "); + } + + sb.append("{"); + sb.append("\"name\": \"").append(analyzer.getName()).append("\", "); + sb.append("\"description\": \"").append(analyzer.getDescription()).append("\", "); + sb.append("\"behaviours\": ["); + AtomicBoolean firstBehaviour = new AtomicBoolean(true); + for (String behaviour : analyzer.getBehaviours()) { + if (!firstBehaviour.compareAndSet(true, false)) { + sb.append(", "); } - sb.append("}"); - - return sb.toString(); + sb.append("\"").append(behaviour).append("\""); + } + sb.append("]"); + sb.append("}"); } + sb.append("}"); + + return sb.toString(); + } } diff --git a/src/main/java/org/onap/aai/sa/rest/ApiUtils.java b/src/main/java/org/onap/aai/sa/rest/ApiUtils.java index bbbc02b..fee8621 100644 --- a/src/main/java/org/onap/aai/sa/rest/ApiUtils.java +++ b/src/main/java/org/onap/aai/sa/rest/ApiUtils.java @@ -1,4 +1,4 @@ -/** +/** * ============LICENSE_START======================================================= * org.onap.aai * ================================================================================ @@ -28,8 +28,10 @@ import org.slf4j.MDC; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; -// Spring Imports - +/** + * Spring Imports. + * + */ public class ApiUtils { public static final String SEARCH_AUTH_POLICY_NAME = "search"; @@ -40,7 +42,7 @@ public class ApiUtils { GET, PUT, DELETE - }; + } /** * This method uses the contents of the supplied HTTP headers and request structures to populate the MDC Context @@ -50,7 +52,6 @@ public class ApiUtils { * @param headers - HTTP headers */ protected static void initMdcContext(HttpServletRequest httpReq, HttpHeaders headers) { - // Auto generate a transaction if we were not provided one. String transId = null; if (headers != null) { @@ -61,7 +62,6 @@ public class ApiUtils { } } - String fromIp = (httpReq != null) ? httpReq.getRemoteHost() : ""; String fromApp = (headers != null) ? headers.getFirst("X-FromAppId") : ""; @@ -95,8 +95,6 @@ public class ApiUtils { } public static boolean validateDocumentUri(String uri, boolean requireId) { - - // If the URI starts with a leading '/' character, remove it. uri = uri.startsWith("/") ? uri.substring(1) : uri; // Now, tokenize the URI string. @@ -111,19 +109,14 @@ public class ApiUtils { } public static String extractIndexFromUri(String uri) { - - // If the URI starts with a leading '/' character, remove it. uri = uri.startsWith("/") ? uri.substring(1) : uri; - // Now, tokenize the URI string. String[] tokens = uri.split("/"); int i = 0; for (String token : tokens) { - if (token.equals("indexes")) { - if (i + 1 < tokens.length) { - return tokens[i + 1]; - } + if (token.equals("indexes") && i + 1 < tokens.length) { + return tokens[i + 1]; } i++; } @@ -132,19 +125,14 @@ public class ApiUtils { } public static String extractIdFromUri(String uri) { - - // If the URI starts with a leading '/' character, remove it. uri = uri.startsWith("/") ? uri.substring(1) : uri; - // Now, tokenize the URI string. String[] tokens = uri.split("/"); int i = 0; for (String token : tokens) { - if (token.equals("documents")) { - if (i + 1 < tokens.length) { - return tokens[i + 1]; - } + if (token.equals("documents") && i + 1 < tokens.length) { + return tokens[i + 1]; } i++; } @@ -153,29 +141,14 @@ public class ApiUtils { } public static String getHttpStatusString(int httpStatusCode) { - // Some of the status codes we use are still in draft state in the standards, and are not - // recognized in the javax library. We need to manually translate these to human-readable - // strings. - String statusString = "Unknown"; - HttpStatus status = null; - try { - status = HttpStatus.valueOf(httpStatusCode); + return HttpStatus.valueOf(httpStatusCode).getReasonPhrase(); } catch (IllegalArgumentException e) { - } - - - if (status == null) { - switch (httpStatusCode) { - case 207: - statusString = "Multi Status"; - break; - default: + if (httpStatusCode == 207) { + return "Multi-Status"; + } else { + return "Unknown"; } - } else { - statusString = status.getReasonPhrase(); } - - return statusString; } } diff --git a/src/main/java/org/onap/aai/sa/rest/BulkApi.java b/src/main/java/org/onap/aai/sa/rest/BulkApi.java index bf8f187..84f4953 100644 --- a/src/main/java/org/onap/aai/sa/rest/BulkApi.java +++ b/src/main/java/org/onap/aai/sa/rest/BulkApi.java @@ -1,4 +1,4 @@ -/** +/** * ============LICENSE_START======================================================= * org.onap.aai * ================================================================================ @@ -88,33 +88,28 @@ public class BulkApi { * @return - A standard REST response structure. */ public ResponseEntity<String> processPost(String operations, HttpServletRequest request, HttpHeaders headers, - DocumentStoreInterface documentStore, ApiUtils apiUtils) { - - + DocumentStoreInterface documentStore) { // Initialize the MDC Context for logging purposes. ApiUtils.initMdcContext(request, headers); // Set a default result code and entity string for the request. int resultCode = 500; - String resultString = "Unexpected error"; + String resultString; if (logger.isDebugEnabled()) { logger.debug("SEARCH: Process Bulk Request - operations = [" + operations.replaceAll("\n", "") + " ]"); } try { - // Validate that the request is correctly authenticated before going // any further. if (!searchService.validateRequest(headers, request, ApiUtils.Action.POST, ApiUtils.SEARCH_AUTH_POLICY_NAME)) { logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE, "Authentication failure."); - return buildResponse(HttpStatus.FORBIDDEN.value(), "Authentication failure.", request, apiUtils); + return buildResponse(HttpStatus.FORBIDDEN.value(), "Authentication failure.", request); } - } catch (Exception e) { - // This is a catch all for any unexpected failure trying to perform // the authentication. logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE, @@ -124,35 +119,30 @@ public class BulkApi { } return buildResponse(HttpStatus.FORBIDDEN.value(), "Authentication failure - cause " + e.getMessage(), - request, apiUtils); + request); } // We expect a payload containing a JSON structure enumerating the // operations to be performed. if (operations == null) { logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE, "Missing operations list payload"); - - return buildResponse(resultCode, "Missing payload", request, apiUtils); + return buildResponse(resultCode, "Missing payload", request); } - // Marshal the supplied json string into a Java object. ObjectMapper mapper = new ObjectMapper(); BulkRequest[] requests = null; try { requests = mapper.readValue(operations, BulkRequest[].class); - } catch (IOException e) { - logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE, "Failed to marshal operations list: " + e.getMessage()); if (logger.isDebugEnabled()) { logger.debug("Stack Trace:\n" + e.getStackTrace()); } - // Populate the result code and entity string for our HTTP response // and return the response to the client.. return buildResponse(HttpStatus.BAD_REQUEST.value(), "Unable to marshal operations: " + e.getMessage(), - request, apiUtils); + request); } // Verify that our parsed operations list actually contains some valid @@ -163,8 +153,7 @@ public class BulkApi { // Populate the result code and entity string for our HTTP response // and return the response to the client.. - return buildResponse(HttpStatus.BAD_REQUEST.value(), "Empty operations list in bulk request", request, - apiUtils); + return buildResponse(HttpStatus.BAD_REQUEST.value(), "Empty operations list in bulk request", request); } try { @@ -189,18 +178,18 @@ public class BulkApi { } // Build our HTTP response. - ResponseEntity response = + ResponseEntity<String> response = ResponseEntity.status(resultCode).contentType(MediaType.APPLICATION_JSON).body(resultString); // Log the result. if ((response.getStatusCodeValue() >= 200) && (response.getStatusCodeValue() < 300)) { logger.info(SearchDbMsgs.PROCESSED_BULK_OPERATIONS); } else { - logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE, (String) response.getBody()); + logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE, response.getBody()); } // Finally, return the HTTP response to the client. - return buildResponse(resultCode, resultString, request, apiUtils); + return buildResponse(resultCode, resultString, request); } @@ -212,9 +201,7 @@ public class BulkApi { * @param request - The HTTP request to extract data from for the audit log. * @return - An HTTP response object. */ - private ResponseEntity<String> buildResponse(int resultCode, String resultString, HttpServletRequest request, - ApiUtils apiUtils) { - + private ResponseEntity<String> buildResponse(int resultCode, String resultString, HttpServletRequest request) { ResponseEntity<String> response = ResponseEntity.status(resultCode).contentType(MediaType.APPLICATION_JSON).body(resultString); @@ -222,7 +209,7 @@ public class BulkApi { auditLogger.info(SearchDbMsgs.PROCESS_REST_REQUEST, new LogFields().setField(LogLine.DefinedFields.RESPONSE_CODE, resultCode) .setField(LogLine.DefinedFields.RESPONSE_DESCRIPTION, ApiUtils.getHttpStatusString(resultCode)), - (request != null) ? request.getMethod().toString() : "Unknown", + (request != null) ? request.getMethod() : "Unknown", (request != null) ? request.getRequestURL().toString() : "Unknown", (request != null) ? request.getRemoteHost() : "Unknown", Integer.toString(response.getStatusCodeValue())); diff --git a/src/main/java/org/onap/aai/sa/rest/DocumentApi.java b/src/main/java/org/onap/aai/sa/rest/DocumentApi.java index 2d9eb1f..af650a7 100644 --- a/src/main/java/org/onap/aai/sa/rest/DocumentApi.java +++ b/src/main/java/org/onap/aai/sa/rest/DocumentApi.java @@ -1,4 +1,4 @@ -/** +/** * ============LICENSE_START======================================================= * org.onap.aai * ================================================================================ @@ -99,7 +99,7 @@ public class DocumentApi { if (httpResponse != null) { httpResponse.setHeader(RESPONSE_HEADER_RESOURCE_VERSION, result.getResultVersion()); } - ResponseEntity response = + ResponseEntity<String> response = ResponseEntity.status(result.getResultCode()).contentType(MediaType.APPLICATION_JSON).body(output); logResult(request, HttpStatus.valueOf(response.getStatusCodeValue())); logResult(request, HttpStatus.valueOf(response.getStatusCodeValue())); @@ -165,7 +165,7 @@ public class DocumentApi { if (httpResponse != null) { httpResponse.setHeader(RESPONSE_HEADER_RESOURCE_VERSION, result.getResultVersion()); } - ResponseEntity response = + ResponseEntity<String> response = ResponseEntity.status(result.getResultCode()).contentType(MediaType.APPLICATION_JSON).body(output); logResult(request, HttpStatus.valueOf(response.getStatusCodeValue())); @@ -221,7 +221,7 @@ public class DocumentApi { if (httpResponse != null) { httpResponse.setHeader(RESPONSE_HEADER_RESOURCE_VERSION, result.getResultVersion()); } - ResponseEntity response; + ResponseEntity<String> response; if (output == null) { response = ResponseEntity.status(result.getResultCode()).build(); } else { @@ -281,7 +281,7 @@ public class DocumentApi { if (httpResponse != null) { httpResponse.setHeader(RESPONSE_HEADER_RESOURCE_VERSION, result.getResultVersion()); } - ResponseEntity response = + ResponseEntity<String> response = ResponseEntity.status(result.getResultCode()).contentType(MediaType.APPLICATION_JSON).body(output); logResult(request, HttpStatus.valueOf(response.getStatusCodeValue())); @@ -327,7 +327,7 @@ public class DocumentApi { ? mapper.writerWithDefaultPrettyPrinter().writeValueAsString(result.getError()) : result.getFailureCause(); } - ResponseEntity response = + ResponseEntity<String> response = ResponseEntity.status(result.getResultCode()).contentType(MediaType.APPLICATION_JSON).body(output); // Clear the MDC context so that no other transaction inadvertently @@ -395,8 +395,8 @@ public class DocumentApi { * @param headers - The HTTP headers. * @return - A standard HTTP response. */ - private ResponseEntity processQuery(String index, String content, HttpServletRequest request, HttpHeaders headers, - DocumentStoreInterface documentStore) { + private ResponseEntity<String> processQuery(String index, String content, HttpServletRequest request, + HttpHeaders headers, DocumentStoreInterface documentStore) { try { ObjectMapper mapper = new ObjectMapper(); @@ -444,7 +444,7 @@ public class DocumentApi { ? mapper.writerWithDefaultPrettyPrinter().writeValueAsString(result.getError()) : result.getFailureCause(); } - ResponseEntity response = + ResponseEntity<String> response = ResponseEntity.status(result.getResultCode()).contentType(MediaType.APPLICATION_JSON).body(output); // Clear the MDC context so that no other transaction inadvertently @@ -581,26 +581,25 @@ public class DocumentApi { return output.toString(); } - private ResponseEntity handleError(HttpServletRequest request, String message, HttpStatus status) { + private ResponseEntity<String> handleError(HttpServletRequest request, String message, HttpStatus status) { logResult(request, status); return ResponseEntity.status(status).contentType(MediaType.APPLICATION_JSON).body(message); } void logResult(HttpServletRequest request, HttpStatus status) { - logger.info(SearchDbMsgs.PROCESS_REST_REQUEST, (request != null) ? request.getMethod().toString() : "", + logger.info(SearchDbMsgs.PROCESS_REST_REQUEST, (request != null) ? request.getMethod() : "", (request != null) ? request.getRequestURL().toString() : "", (request != null) ? request.getRemoteHost() : "", Integer.toString(status.value())); 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() : "", + (request != null) ? request.getMethod() : "", (request != null) ? request.getRequestURL().toString() : "", (request != null) ? request.getRemoteHost() : "", Integer.toString(status.value())); - // 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(); } } diff --git a/src/main/java/org/onap/aai/sa/rest/IndexApi.java b/src/main/java/org/onap/aai/sa/rest/IndexApi.java index 3371fcd..4add62c 100644 --- a/src/main/java/org/onap/aai/sa/rest/IndexApi.java +++ b/src/main/java/org/onap/aai/sa/rest/IndexApi.java @@ -1,4 +1,4 @@ -/** +/** * ============LICENSE_START======================================================= * org.onap.aai * ================================================================================ @@ -37,378 +37,371 @@ 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 HEADER_VALIDATION_SUCCESS = "SUCCESS"; - protected SearchServiceApi searchService = null; + private static final String HEADER_VALIDATION_SUCCESS = "SUCCESS"; + protected SearchServiceApi searchService = null; - /** - * Configuration for the custom analyzers that will be used for indexing. - */ - protected AnalysisConfiguration analysisConfig; + /** + * Configuration for the custom analyzers that will be used for indexing. + */ + protected AnalysisConfiguration analysisConfig; - // Set up the loggers. + // Set up the loggers. private static Logger logger = LoggerFactory.getInstance().getLogger(IndexApi.class.getName()); private static Logger auditLogger = LoggerFactory.getInstance().getAuditLogger(IndexApi.class.getName()); - public IndexApi(SearchServiceApi searchService) { - this.searchService = searchService; - init(); - } + public IndexApi(SearchServiceApi searchService) { + this.searchService = searchService; + init(); + } - /** - * Initializes the end point. - * - * @throws FileNotFoundException - * @throws IOException - * @throws DocumentStoreOperationException - */ - public void init() { + /** + * Initializes the end point. + * + * @throws FileNotFoundException + * @throws IOException + * @throws DocumentStoreOperationException + */ + public void init() { - // Instantiate our analysis configuration object. - analysisConfig = new AnalysisConfiguration(); - } + // Instantiate our analysis configuration object. + analysisConfig = new AnalysisConfiguration(); + } - /** + /** * Processes client requests to create a new index and document type in the document store. - * + * * @param documentSchema - The contents of the request body which is expected to be a JSON structure which * corresponds to the schema defined in document.schema.json - * @param index - The name of the index to create. - * @return - A Standard REST response - */ + * @param index - The name of the index to create. + * @return - A Standard REST response + */ public ResponseEntity<String> processCreateIndex(String documentSchema, HttpServletRequest request, HttpHeaders headers, String index, DocumentStoreInterface documentStore) { - int resultCode = 500; - String resultString = "Unexpected error"; + int resultCode = 500; + + // Initialize the MDC Context for logging purposes. + ApiUtils.initMdcContext(request, headers); - // Initialize the MDC Context for logging purposes. - ApiUtils.initMdcContext(request, headers); - - // Validate that the request is correctly authenticated before going - // any further. - try { + // 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, "Authentication failure."); + return errorResponse(HttpStatus.FORBIDDEN, "Authentication failure.", request); + } - } catch (Exception e) { + } catch (Exception e) { - logger.warn(SearchDbMsgs.INDEX_CREATE_FAILURE, index, - "Unexpected authentication failure - cause: " + e.getMessage()); - return errorResponse(HttpStatus.FORBIDDEN, "Authentication failure.", request); - } + logger.warn(SearchDbMsgs.INDEX_CREATE_FAILURE, index, + "Unexpected authentication failure - cause: " + e.getMessage()); + return errorResponse(HttpStatus.FORBIDDEN, "Authentication failure.", request); + } - // We expect a payload containing the document schema. Make sure - // it is present. - if (documentSchema == null) { - logger.warn(SearchDbMsgs.INDEX_CREATE_FAILURE, index, "Missing document schema payload"); - return errorResponse(HttpStatus.valueOf(resultCode), "Missing payload", request); - } + // We expect a payload containing the document schema. Make sure + // it is present. + if (documentSchema == null) { + logger.warn(SearchDbMsgs.INDEX_CREATE_FAILURE, index, "Missing document schema payload"); + return errorResponse(HttpStatus.valueOf(resultCode), "Missing payload", request); + } - try { + String resultString; - // Marshal the supplied json string into a document schema object. - ObjectMapper mapper = new ObjectMapper(); - DocumentSchema schema = mapper.readValue(documentSchema, DocumentSchema.class); + try { + // Marshal the supplied json string into a document schema object. + ObjectMapper mapper = new ObjectMapper(); + DocumentSchema schema = mapper.readValue(documentSchema, DocumentSchema.class); - // Now, ask the DAO to create the index. - OperationResult result = documentStore.createIndex(index, schema); + // Now, ask the DAO to create the index. + OperationResult result = documentStore.createIndex(index, schema); - // Extract the result code and string from the OperationResult - // object so that we can use them to generate a standard REST - // response. - // Note that we want to return a 201 result code on a successful - // create, so if we get back a 200 from the document store, - // translate that int a 201. - resultCode = (result.getResultCode() == 200) ? 201 : result.getResultCode(); + // Extract the result code and string from the OperationResult + // object so that we can use them to generate a standard REST + // response. + // Note that we want to return a 201 result code on a successful + // create, so if we get back a 200 from the document store, + // translate that int a 201. + resultCode = (result.getResultCode() == 200) ? 201 : result.getResultCode(); resultString = (result.getFailureCause() == null) ? result.getResult() : result.getFailureCause(); - } catch (com.fasterxml.jackson.core.JsonParseException - | com.fasterxml.jackson.databind.JsonMappingException e) { + } catch (com.fasterxml.jackson.core.JsonParseException + | com.fasterxml.jackson.databind.JsonMappingException e) { - // We were unable to marshal the supplied json string into a valid - // document schema, so return an appropriate error response. - resultCode = HttpStatus.BAD_REQUEST.value(); - resultString = "Malformed schema: " + e.getMessage(); + // We were unable to marshal the supplied json string into a valid + // document schema, so return an appropriate error response. + resultCode = HttpStatus.BAD_REQUEST.value(); + resultString = "Malformed schema: " + e.getMessage(); - } catch (IOException e) { + } catch (IOException e) { - // We'll treat this is a general internal error. - resultCode = HttpStatus.INTERNAL_SERVER_ERROR.value(); - resultString = "IO Failure: " + e.getMessage(); - } + // We'll treat this is a general internal error. + resultCode = HttpStatus.INTERNAL_SERVER_ERROR.value(); + resultString = "IO Failure: " + e.getMessage(); + } ResponseEntity<String> response = ResponseEntity.status(resultCode).contentType(MediaType.APPLICATION_JSON).body(resultString); - // Log the result. - if ((response.getStatusCodeValue() >= 200) && (response.getStatusCodeValue() < 300)) { - logger.info(SearchDbMsgs.CREATED_INDEX, index); - } else { - logger.warn(SearchDbMsgs.INDEX_CREATE_FAILURE, index, resultString); - } + // Log the result. + if ((response.getStatusCodeValue() >= 200) && (response.getStatusCodeValue() < 300)) { + logger.info(SearchDbMsgs.CREATED_INDEX, index); + } else { + logger.warn(SearchDbMsgs.INDEX_CREATE_FAILURE, index, resultString); + } - // Generate our audit log. - auditLogger.info(SearchDbMsgs.PROCESS_REST_REQUEST, + // Generate our audit log. + 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", - Integer.toString(response.getStatusCodeValue())); + (request != null) ? request.getMethod() : "Unknown", + (request != null) ? request.getRequestURL ().toString () : "Unknown", + (request != null) ? request.getRemoteHost () : "Unknown", + Integer.toString(response.getStatusCodeValue ())); - // Clear the MDC context so that no other transaction inadvertently - // uses our transaction id. - ApiUtils.clearMdcContext(); + // Clear the MDC context so that no other transaction inadvertently + // uses our transaction id. + ApiUtils.clearMdcContext(); - // Finally, return the response. - return response; - } + // Finally, return the response. + return response; + } - /** + /** * This function accepts any JSON and will "blindly" write it to the document store. - * + * * Note, eventually this "dynamic" flow should follow the same JSON-Schema validation procedure as the normal create * index flow. - * - * @param dynamicSchema - The JSON string that will be sent to the document store. - * @param index - The name of the index to be created. - * @param documentStore - The document store specific interface. - * @return The result of the document store interface's operation. - */ - public ResponseEntity<String> processCreateDynamicIndex(String dynamicSchema, HttpServletRequest request, - HttpHeaders headers, String index, DocumentStoreInterface documentStore) { + * + * @param dynamicSchema - The JSON string that will be sent to the document store. + * @param index - The name of the index to be created. + * @param documentStore - The document store specific interface. + * @return The result of the document store interface's operation. + */ + public ResponseEntity<String> processCreateDynamicIndex(String dynamicSchema, HttpServletRequest request, + HttpHeaders headers, String index, DocumentStoreInterface documentStore) { - ResponseEntity<String> response = null; + ResponseEntity<String> response = null; ResponseEntity<String> validationResponse = validateRequest(request, headers, index, SearchDbMsgs.INDEX_CREATE_FAILURE); - if (validationResponse.getStatusCodeValue() != HttpStatus.OK.value()) { - response = validationResponse; - } else { - OperationResult result = documentStore.createDynamicIndex(index, dynamicSchema); - - int resultCode = (result.getResultCode() == 200) ? 201 : result.getResultCode(); - String resultString = (result.getFailureCause() == null) ? result.getResult() : result.getFailureCause(); + if (validationResponse.getStatusCodeValue () != HttpStatus.OK.value ()) { + response = validationResponse; + } else { + OperationResult result = documentStore.createDynamicIndex(index, dynamicSchema); - response = ResponseEntity.status(resultCode).body(resultString); - } + int resultCode = (result.getResultCode() == 200) ? 201 : result.getResultCode(); + String resultString = (result.getFailureCause() == null) ? result.getResult() : result.getFailureCause(); - return response; + response = ResponseEntity.status(resultCode).body(resultString); } - /** + return response; + } + + /** * Processes a client request to remove an index from the document store. Note that this implicitly deletes all * documents contained within that index. - * - * @param index - The index to be deleted. - * @return - A standard REST response. - */ + * + * @param index - The index to be deleted. + * @return - A standard REST response. + */ public ResponseEntity<String> processDelete(String index, HttpServletRequest request, HttpHeaders headers, - DocumentStoreInterface documentStore) { - - // 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"); - - // 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); - } - - } catch (Exception e) { - - logger.warn(SearchDbMsgs.INDEX_CREATE_FAILURE, index, - "Unexpected authentication failure - cause: " + e.getMessage()); - return errorResponse(HttpStatus.FORBIDDEN, "Authentication failure.", request); - } - - - try { - // Send the request to the document store. - response = responseFromOperationResult(documentStore.deleteIndex(index)); + DocumentStoreInterface documentStore) { + + // Initialize the MDC Context for logging purposes. + ApiUtils.initMdcContext(request, headers); + + 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); + } + + } catch (Exception e) { + logger.warn(SearchDbMsgs.INDEX_CREATE_FAILURE, index, + "Unexpected authentication failure - cause: " + e.getMessage()); + return errorResponse(HttpStatus.FORBIDDEN, "Authentication failure.", request); + } - } catch (DocumentStoreOperationException e) { + 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)) { - logger.info(SearchDbMsgs.DELETED_INDEX, index); - } else { + // Log the result. + if ((response.getStatusCodeValue() >= 200) && (response.getStatusCodeValue() < 300)) { + 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, + // 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", - Integer.toString(response.getStatusCodeValue())); + (request != null) ? request.getMethod() : "Unknown", + (request != null) ? request.getRequestURL ().toString () : "Unknown", + (request != null) ? request.getRemoteHost () : "Unknown", + Integer.toString(response.getStatusCodeValue())); - // Clear the MDC context so that no other transaction inadvertently - // uses our transaction id. - ApiUtils.clearMdcContext(); + // Clear the MDC context so that no other transaction inadvertently + // uses our transaction id. + ApiUtils.clearMdcContext(); - return response; - } + return response; + } - /** + /** * This method takes a JSON format document schema and produces a set of field mappings in the form that Elastic * Search expects. - * - * @param documentSchema - A document schema expressed as a JSON string. - * @return - A JSON string expressing an Elastic Search mapping configuration. - * @throws com.fasterxml.jackson.core.JsonParseException - * @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 { - - // Unmarshal the json content into a document schema object. - ObjectMapper mapper = new ObjectMapper(); - DocumentSchema schema = mapper.readValue(documentSchema, DocumentSchema.class); - - // Now, generate the Elastic Search mapping json and return it. - StringBuilder sb = new StringBuilder(); - sb.append("{"); - sb.append("\"properties\": {"); - - boolean first = true; - for (DocumentFieldSchema field : schema.getFields()) { - - if (!first) { - sb.append(","); - } else { - first = false; - } - - sb.append("\"").append(field.getName()).append("\": {"); - - // The field type is mandatory. - sb.append("\"type\": \"").append(field.getDataType()).append("\""); - - // If the index field was specified, then append it. - if (field.getSearchable() != null) { + * + * @param documentSchema - A document schema expressed as a JSON string. + * @return - A JSON string expressing an Elastic Search mapping configuration. + * @throws com.fasterxml.jackson.core.JsonParseException + * @throws com.fasterxml.jackson.databind.JsonMappingException + * @throws IOException + */ + public String generateDocumentMappings(String documentSchema) throws IOException { + + // Unmarshal the json content into a document schema object. + ObjectMapper mapper = new ObjectMapper(); + DocumentSchema schema = mapper.readValue(documentSchema, DocumentSchema.class); + + // Now, generate the Elastic Search mapping json and return it. + StringBuilder sb = new StringBuilder(); + sb.append("{"); + sb.append("\"properties\": {"); + + boolean first = true; + for (DocumentFieldSchema field : schema.getFields()) { + + if (!first) { + sb.append(","); + } else { + first = false; + } + + sb.append("\"").append(field.getName()).append("\": {"); + + // The field type is mandatory. + sb.append("\"type\": \"").append(field.getDataType()).append("\""); + + // If the index field was specified, then append it. + if (field.getSearchable() != null) { sb.append(", \"index\": \"").append(field.getSearchable() ? "analyzed" : "not_analyzed").append("\""); - } + } - // If a search analyzer was specified, then append it. - if (field.getSearchAnalyzer() != null) { - sb.append(", \"search_analyzer\": \"").append(field.getSearchAnalyzer()).append("\""); - } + // If a search analyzer was specified, then append it. + if (field.getSearchAnalyzer() != null) { + sb.append(", \"search_analyzer\": \"").append(field.getSearchAnalyzer()).append("\""); + } - // If an indexing analyzer was specified, then append it. - if (field.getIndexAnalyzer() != null) { - sb.append(", \"analyzer\": \"").append(field.getIndexAnalyzer()).append("\""); - } else { - sb.append(", \"analyzer\": \"").append("whitespace").append("\""); - } + // If an indexing analyzer was specified, then append it. + if (field.getIndexAnalyzer() != null) { + sb.append(", \"analyzer\": \"").append(field.getIndexAnalyzer()).append("\""); + } else { + sb.append(", \"analyzer\": \"").append("whitespace").append("\""); + } - sb.append("}"); - } + sb.append("}"); + } - sb.append("}"); - sb.append("}"); + sb.append("}"); + sb.append("}"); - logger.debug("Generated document mappings: " + sb.toString()); + logger.debug("Generated document mappings: " + sb.toString()); - return sb.toString(); - } + return sb.toString(); + } - /** + /** * Converts an {@link OperationResult} to a standard REST {@link ResponseEntity} object. - * - * @param result - The {@link OperationResult} to be converted. - * @return - The equivalent {@link ResponseEntity} object. - */ - public ResponseEntity<String> responseFromOperationResult(OperationResult result) { + * + * @param result - The {@link OperationResult} to be converted. + * @return - The equivalent {@link ResponseEntity} object. + */ + public ResponseEntity<String> responseFromOperationResult(OperationResult result) { - if ((result.getResultCode() >= 200) && (result.getResultCode() < 300)) { + if ((result.getResultCode() >= 200) && (result.getResultCode() < 300)) { return ResponseEntity.status(result.getResultCode()).contentType(MediaType.APPLICATION_JSON) .body(result.getResult()); - } else { - if (result.getFailureCause() != null) { + } else { + if (result.getFailureCause() != null) { return ResponseEntity.status(result.getResultCode()).contentType(MediaType.APPLICATION_JSON) .body(result.getFailureCause()); - } else { + } else { return ResponseEntity.status(result.getResultCode()).contentType(MediaType.APPLICATION_JSON) .body(result.getResult()); - } - } + } } + } - public ResponseEntity<String> errorResponse(HttpStatus status, String msg, HttpServletRequest request) { + public ResponseEntity<String> errorResponse(HttpStatus status, String msg, HttpServletRequest request) { - // Generate our audit log. - auditLogger.info(SearchDbMsgs.PROCESS_REST_REQUEST, + // Generate our audit log. + 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", + .setField(LogLine.DefinedFields.RESPONSE_DESCRIPTION, status.getReasonPhrase()), + (request != null) ? request.getMethod() : "Unknown", + (request != null) ? request.getRequestURL ().toString () : "Unknown", (request != null) ? request.getRemoteHost() : "Unknown", Integer.toString(status.value())); - // Clear the MDC context so that no other transaction inadvertently - // uses our transaction id. - ApiUtils.clearMdcContext(); + // Clear the MDC context so that no other transaction inadvertently + // uses our transaction id. + ApiUtils.clearMdcContext(); - return ResponseEntity.status(status).contentType(MediaType.APPLICATION_JSON).body(msg); - } + return ResponseEntity.status(status).contentType ( MediaType.APPLICATION_JSON ).body(msg); + } - /** - * A helper method used for validating/authenticating an incoming request. - * - * @param request - The http request that will be validated. - * @param headers - The http headers that will be validated. - * @param index - The name of the index that the document store request is being made against. - * @param failureMsgEnum - The logging message to be used upon validation failure. - * @return A success or failure response - */ + /** + * A helper method used for validating/authenticating an incoming request. + * + * @param request - The http request that will be validated. + * @param headers - The http headers that will be validated. + * @param index - The name of the index that the document store request is being made against. + * @param failureMsgEnum - The logging message to be used upon validation failure. + * @return A success or failure response + */ private ResponseEntity<String> validateRequest(HttpServletRequest request, HttpHeaders headers, String index, SearchDbMsgs failureMsgEnum) { - try { + 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); - } - } catch (Exception e) { - logger.warn(failureMsgEnum, index, "Unexpected authentication failure - cause: " + e.getMessage()); - return errorResponse(HttpStatus.FORBIDDEN, "Authentication failure.", request); - } - return ResponseEntity.status(HttpStatus.OK).body(HEADER_VALIDATION_SUCCESS); + logger.warn(failureMsgEnum, index, "Authentication failure."); + return errorResponse(HttpStatus.FORBIDDEN, "Authentication failure.", request); + } + } catch (Exception e) { + logger.warn(failureMsgEnum, index, "Unexpected authentication failure - cause: " + e.getMessage()); + return errorResponse(HttpStatus.FORBIDDEN, "Authentication failure.", request); } + return ResponseEntity.status(HttpStatus.OK).body(HEADER_VALIDATION_SUCCESS); + } } diff --git a/src/main/java/org/onap/aai/sa/rest/SearchServiceApi.java b/src/main/java/org/onap/aai/sa/rest/SearchServiceApi.java index d807996..776e72b 100644 --- a/src/main/java/org/onap/aai/sa/rest/SearchServiceApi.java +++ b/src/main/java/org/onap/aai/sa/rest/SearchServiceApi.java @@ -1,4 +1,4 @@ -/** +/** * ============LICENSE_START======================================================= * org.onap.aai * ================================================================================ @@ -65,11 +65,8 @@ public class SearchServiceApi { * Performs all one-time initialization required for the end point. */ public void init() { - // Instantiate our Document Store DAO. documentStore = ElasticSearchHttpController.getInstance(); - - apiUtils = new ApiUtils(); } @RequestMapping(value = "/indexes/{index}", method = RequestMethod.PUT, produces = {"application/json"}) @@ -183,13 +180,11 @@ public class SearchServiceApi { // Forward the request to our document API to delete the document. BulkApi bulkApi = new BulkApi(this); - ResponseEntity<String> dbugResp = bulkApi.processPost(requestBody, request, headers, documentStore, apiUtils); - return dbugResp; + return bulkApi.processPost(requestBody, request, headers, documentStore); } protected boolean validateRequest(HttpHeaders headers, HttpServletRequest req, Action action, - String authPolicyFunctionName) throws Exception { - + String authPolicyFunctionName) { SearchDbServiceAuth serviceAuth = new SearchDbServiceAuth(); String cipherSuite = (String) req.getAttribute("javax.servlet.request.cipher_suite"); @@ -210,10 +205,6 @@ public class SearchServiceApi { String status = serviceAuth.authUser(headers, authUser.toLowerCase(), action.toString() + ":" + authPolicyFunctionName); - if (!status.equals("OK")) { - return false; - } - - return true; + return status.equals("OK"); } } diff --git a/src/main/java/org/onap/aai/sa/searchdbabstraction/RestEchoService.java b/src/main/java/org/onap/aai/sa/searchdbabstraction/RestEchoService.java index d92a1da..96929c7 100644 --- a/src/main/java/org/onap/aai/sa/searchdbabstraction/RestEchoService.java +++ b/src/main/java/org/onap/aai/sa/searchdbabstraction/RestEchoService.java @@ -18,16 +18,14 @@ * limitations under the License. * ============LICENSE_END========================================================= */ -package org.onap.aai.sa.searchdbabstraction; - +package org.onap.aai.sa.searchdbabstraction; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; - /** * Exposes REST endpoints for a simple echo service. */ diff --git a/src/main/java/org/onap/aai/sa/searchdbabstraction/entity/ErrorResult.java b/src/main/java/org/onap/aai/sa/searchdbabstraction/entity/ErrorResult.java index 06c788a..aa7e720 100644 --- a/src/main/java/org/onap/aai/sa/searchdbabstraction/entity/ErrorResult.java +++ b/src/main/java/org/onap/aai/sa/searchdbabstraction/entity/ErrorResult.java @@ -25,7 +25,6 @@ public class ErrorResult { private String type; private String reason; - public ErrorResult(String type, String reason) { super(); this.type = type; diff --git a/src/main/java/org/onap/aai/sa/searchdbabstraction/searchapi/AbstractAggregation.java b/src/main/java/org/onap/aai/sa/searchdbabstraction/searchapi/AbstractAggregation.java index 80b4704..46d6fa1 100644 --- a/src/main/java/org/onap/aai/sa/searchdbabstraction/searchapi/AbstractAggregation.java +++ b/src/main/java/org/onap/aai/sa/searchdbabstraction/searchapi/AbstractAggregation.java @@ -1,4 +1,4 @@ -/** +/** * ============LICENSE_START======================================================= * org.onap.aai * ================================================================================ @@ -29,49 +29,48 @@ import com.fasterxml.jackson.annotation.JsonProperty; */ public abstract class AbstractAggregation { - /** - * The name of the field to apply the aggregation against. - */ - protected String field; + /** + * The name of the field to apply the aggregation against. + */ + protected String field; - /** + /** * Optionally allows the number of buckets for the aggregation to be specified. - */ - protected Integer size; + */ + protected Integer size; - /** + /** * Optionally sets the minimum number of matches that must occur before a particular bucket is included in the * aggregation result. - */ - @JsonProperty("min-threshold") - protected Integer minThreshold; + */ + @JsonProperty("min-threshold") + protected Integer minThreshold; - public String getField() { - return field; - } + public String getField() { + return field; + } - public void setField(String field) { - this.field = field; - } + public void setField(String field) { + this.field = field; + } - public Integer getSize() { - return size; - } + public Integer getSize() { + return size; + } - public void setSize(Integer size) { - this.size = size; - } + public void setSize(Integer size) { + this.size = size; + } - public Integer getMinThreshold() { - return minThreshold; - } + public Integer getMinThreshold() { + return minThreshold; + } - public void setMinThreshold(Integer minThreshold) { - this.minThreshold = minThreshold; - } + public void setMinThreshold(Integer minThreshold) { + this.minThreshold = minThreshold; + } - public abstract String toElasticSearch(); + public abstract String toElasticSearch(); - public abstract String toString(); } diff --git a/src/main/java/org/onap/aai/sa/searchdbabstraction/searchapi/DateRange.java b/src/main/java/org/onap/aai/sa/searchdbabstraction/searchapi/DateRange.java index 78f707a..cd49ee7 100644 --- a/src/main/java/org/onap/aai/sa/searchdbabstraction/searchapi/DateRange.java +++ b/src/main/java/org/onap/aai/sa/searchdbabstraction/searchapi/DateRange.java @@ -27,7 +27,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; * <p> * The expected JSON structure for a ranges is as follows: * <p> - * + * * <pre> * { * "from": <from-date> @@ -36,7 +36,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; * <p> * or * <p> - * + * * <pre> * { * "to": <to-date> @@ -45,7 +45,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; * <p> * or * <p> - * + * * <pre> * { * "from": <from-date>, @@ -86,18 +86,18 @@ public class DateRange { if (fromDate != null) { sb.append("\"from\": \""); - sb.append(fromDate.toString()); + sb.append(fromDate); sb.append("\""); } if (toDate != null) { if (fromDate != null) { sb.append(", \"to\": \""); - sb.append(toDate.toString()); + sb.append(toDate); sb.append("\""); } else { sb.append("\"to\": \""); - sb.append(toDate.toString()); + sb.append(toDate); sb.append("\""); } } @@ -107,6 +107,7 @@ public class DateRange { return sb.toString(); } + @Override public String toString() { return "{from: " + fromDate + ", to: " + toDate + "}"; } diff --git a/src/main/java/org/onap/aai/sa/searchdbabstraction/service/SearchService.java b/src/main/java/org/onap/aai/sa/searchdbabstraction/service/SearchService.java index 350ddf0..46536ab 100644 --- a/src/main/java/org/onap/aai/sa/searchdbabstraction/service/SearchService.java +++ b/src/main/java/org/onap/aai/sa/searchdbabstraction/service/SearchService.java @@ -1,4 +1,4 @@ -/** +/** * ============LICENSE_START======================================================= * org.onap.aai * ================================================================================ @@ -30,27 +30,24 @@ import org.onap.aai.sa.searchdbabstraction.logging.SearchDbMsgs; import org.onap.aai.sa.searchdbabstraction.util.SearchDbConstants; import org.springframework.beans.factory.annotation.Autowired; - public class SearchService { - private ElasticSearchHttpController esController = null; - - static Logger logger = LoggerFactory.getInstance().getLogger(SearchService.class.getName()); + static Logger logger = LoggerFactory.getInstance().getLogger(SearchService.class.getName()); - @Autowired - private ElasticSearchConfig esConfig; + @Autowired + private ElasticSearchConfig esConfig; - public SearchService() { - try { - start(); - } catch (Exception e) { - logger.error(SearchDbMsgs.STARTUP_EXCEPTION, e.getLocalizedMessage()); - } + public SearchService() { + try { + start(); + } catch (Exception e) { + logger.error(SearchDbMsgs.STARTUP_EXCEPTION, e.getLocalizedMessage()); } + } - protected void start() throws Exception { - Properties configProperties = new Properties(); - configProperties.load(new FileInputStream(SearchDbConstants.ES_CONFIG_FILE)); - esController = new ElasticSearchHttpController(esConfig); - logger.info(SearchDbMsgs.SERVICE_STARTED); - } + protected void start() throws Exception { + Properties configProperties = new Properties(); + configProperties.load(new FileInputStream(SearchDbConstants.ES_CONFIG_FILE)); + new ElasticSearchHttpController(esConfig); + logger.info(SearchDbMsgs.SERVICE_STARTED); + } } diff --git a/src/main/java/org/onap/aai/sa/searchdbabstraction/util/AggregationParsingUtil.java b/src/main/java/org/onap/aai/sa/searchdbabstraction/util/AggregationParsingUtil.java index def3f04..20fd027 100644 --- a/src/main/java/org/onap/aai/sa/searchdbabstraction/util/AggregationParsingUtil.java +++ b/src/main/java/org/onap/aai/sa/searchdbabstraction/util/AggregationParsingUtil.java @@ -1,4 +1,4 @@ -/** +/** * ============LICENSE_START======================================================= * org.onap.aai * ================================================================================ @@ -29,14 +29,18 @@ import org.onap.aai.sa.searchdbabstraction.entity.AggregationBucket; import org.onap.aai.sa.searchdbabstraction.entity.AggregationResult; public class AggregationParsingUtil { + + private AggregationParsingUtil() { // Do not instantiate + } + public static AggregationResult[] parseAggregationResults(JSONObject aggregations) throws JsonProcessingException { // Obtain the set of aggregation names - Set keySet = aggregations.keySet(); + Set<?> keySet = aggregations.keySet(); AggregationResult[] aggResults = new AggregationResult[keySet.size()]; int index = 0; - for (Iterator it = keySet.iterator(); it.hasNext();) { + for (Iterator<?> it = keySet.iterator(); it.hasNext();) { String key = (String) it.next(); AggregationResult aggResult = new AggregationResult(); aggResult.setName(key); diff --git a/src/main/java/org/onap/aai/sa/searchdbabstraction/util/DocumentSchemaUtil.java b/src/main/java/org/onap/aai/sa/searchdbabstraction/util/DocumentSchemaUtil.java index 09ef76b..df91cca 100644 --- a/src/main/java/org/onap/aai/sa/searchdbabstraction/util/DocumentSchemaUtil.java +++ b/src/main/java/org/onap/aai/sa/searchdbabstraction/util/DocumentSchemaUtil.java @@ -1,4 +1,4 @@ -/** +/** * ============LICENSE_START======================================================= * org.onap.aai * ================================================================================ @@ -20,8 +20,6 @@ */ package org.onap.aai.sa.searchdbabstraction.util; -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.File; import java.io.FileInputStream; @@ -34,12 +32,14 @@ import org.onap.aai.sa.rest.DocumentSchema; public class DocumentSchemaUtil { + private DocumentSchemaUtil() { // Do not instantiate + } + private static String dynamicCustomMapping = null; private static final String DYNAMIC_CUSTOM_TEMPALTE_FILE = System.getProperty("CONFIG_HOME") + File.separator + "dynamic-custom-template.json"; - public static String generateDocumentMappings(String documentSchema) - throws JsonParseException, JsonMappingException, IOException { + public static String generateDocumentMappings(String documentSchema) throws IOException { // Unmarshal the json content into a document schema object. ObjectMapper mapper = new ObjectMapper(); @@ -103,10 +103,8 @@ public class DocumentSchemaUtil { sb.append("\"type\": \"").append(fieldSchema.getDataType()).append("\""); // For date type fields we may optionally supply a format specifier. - if (fieldSchema.getDataType().equals("date")) { - if (fieldSchema.getFormat() != null) { - sb.append(", \"format\": \"").append(fieldSchema.getFormat()).append("\""); - } + if (fieldSchema.getDataType().equals("date") && fieldSchema.getFormat() != null) { + sb.append(", \"format\": \"").append(fieldSchema.getFormat()).append("\""); } // If the index field was specified, then append it. diff --git a/src/main/java/org/onap/aai/sa/searchdbabstraction/util/ElasticSearchPayloadTranslator.java b/src/main/java/org/onap/aai/sa/searchdbabstraction/util/ElasticSearchPayloadTranslator.java index 79b145d..d3dd3e1 100644 --- a/src/main/java/org/onap/aai/sa/searchdbabstraction/util/ElasticSearchPayloadTranslator.java +++ b/src/main/java/org/onap/aai/sa/searchdbabstraction/util/ElasticSearchPayloadTranslator.java @@ -39,12 +39,12 @@ import org.onap.aai.sa.searchdbabstraction.logging.SearchDbMsgs; /** * This class as the name suggests is to translate the payload of PUT & POST requests to ElasticSearch (ES) to its * compatible syntax, specially compatible with ES v6 or above. - * + * * For example, data type such as "string" is now replaced by "text" or "keyword". - * + * * So this class will make those translations reading off from a json configuration file, therefore the configuration * can be updated with new translations as and when required without touching the code. - * + * * @author EDWINL * */ @@ -55,21 +55,23 @@ public class ElasticSearchPayloadTranslator { private static final String CONFIG_DIRECTORY = System.getProperty("CONFIG_HOME"); private static final String ES_PAYLOAD_TRANSLATION_FILE = "es-payload-translation.json"; + private ElasticSearchPayloadTranslator() { // Do not instantiate + } /** * Using JSON Path query to filter objects to translate the payload to ES compatible version The filter queries and * the replacement attributes are configured in the es-payload-translation.json file. - * + * * @param source * @return translated payload in String * @throws IOException */ public static String translateESPayload(String source) throws IOException { - logger.info(SearchDbMsgs.PROCESS_PAYLOAD_QUERY, "translateESPayload, method-params[ source=" + source + "]"); + logger.info(SearchDbMsgs.PROCESS_PAYLOAD_QUERY, "translateESPayload, method-params[ source=" + source + "]", + "(unknown)"); String pathToTranslationFile = CONFIG_DIRECTORY + File.separator + ES_PAYLOAD_TRANSLATION_FILE; try { - JSONObject translationConfigPayload = new JSONObject(IOUtils.toString(new FileInputStream(new File(pathToTranslationFile)), "UTF-8")); JSONArray attrTranslations = translationConfigPayload.getJSONArray("attr-translations"); @@ -88,13 +90,12 @@ public class ElasticSearchPayloadTranslator { logger.info(SearchDbMsgs.PROCESS_PAYLOAD_QUERY, "Payload after translation: " + payloadToTranslate.jsonString()); return payloadToTranslate.jsonString(); - - } catch (JSONException | IOException e) { - logger.error(SearchDbMsgs.FILTERS_CONFIG_FAILURE, e, ES_PAYLOAD_TRANSLATION_FILE, e.getMessage()); - if (e instanceof JSONException) { - throw new IOException("Payload translation configuration looks corrupted. Please correct!", e); - } - throw new IOException("Error in configuring payload translation file. Please check if it exists.", e); + } catch (JSONException ex) { + logger.error(SearchDbMsgs.FILTERS_CONFIG_FAILURE, ex, ES_PAYLOAD_TRANSLATION_FILE, ex.getMessage()); + throw new IOException("Payload translation configuration looks corrupted. Please correct!", ex); + } catch (IOException ex) { + logger.error(SearchDbMsgs.FILTERS_CONFIG_FAILURE, ex, ES_PAYLOAD_TRANSLATION_FILE, ex.getMessage()); + throw new IOException("Error in configuring payload translation file. Please check if it exists.", ex); } } } diff --git a/src/main/java/org/onap/aai/sa/searchdbabstraction/util/SearchDbConstants.java b/src/main/java/org/onap/aai/sa/searchdbabstraction/util/SearchDbConstants.java index 1171895..0819d38 100644 --- a/src/main/java/org/onap/aai/sa/searchdbabstraction/util/SearchDbConstants.java +++ b/src/main/java/org/onap/aai/sa/searchdbabstraction/util/SearchDbConstants.java @@ -1,4 +1,4 @@ -/** +/** * ============LICENSE_START======================================================= * org.onap.aai * ================================================================================ @@ -21,15 +21,19 @@ package org.onap.aai.sa.searchdbabstraction.util; public class SearchDbConstants { + + private SearchDbConstants() { // Do not instantiate + } + public static final String SDB_FILESEP = (System.getProperty("file.separator") == null) ? "/" : System.getProperty("file.separator"); public static final String SDB_BUNDLECONFIG_NAME = (System.getProperty("BUNDLECONFIG_DIR") == null) ? "bundleconfig" : System.getProperty("BUNDLECONFIG_DIR"); - // + public static final String SDB_HOME_BUNDLECONFIG = (System.getProperty("AJSC_HOME") == null) ? SDB_FILESEP + "opt" + SDB_FILESEP + "app" + SDB_FILESEP + "searchdb" + SDB_FILESEP + SDB_BUNDLECONFIG_NAME : System.getProperty("AJSC_HOME") + SDB_FILESEP + SDB_BUNDLECONFIG_NAME; - // + public static final String SDB_HOME_ETC = SDB_HOME_BUNDLECONFIG + SDB_FILESEP + "etc" + SDB_FILESEP; public static final String SDB_CONFIG_APP_LOCATION = SDB_HOME_ETC + "appprops" + SDB_FILESEP; @@ -42,11 +46,6 @@ public class SearchDbConstants { public static final String SDB_FILTER_CONFIG_FILE = SDB_SPECIFIC_CONFIG + "filter-config.json"; public static final String SDB_ANALYSIS_CONFIG_FILE = SDB_SPECIFIC_CONFIG + "analysis-config.json"; - // public static final String SDB_HOME_SEARCHCONFIG = (System.getProperty("app.config") == null) - // ? System.getProperty("user.dir") + SDB_FILESEP + "config" + SDB_FILESEP + "searchdb" - // + SDB_FILESEP + "elastic-search.properties" - // : System.getProperty("app.config") + SDB_FILESEP + "searchdb" + SDB_FILESEP + "elastic-search.properties"; - // Logging related public static final String SDB_SERVICE_NAME = "SearchDataService"; } |