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 | |
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')
28 files changed, 848 insertions, 968 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"; } diff --git a/src/test/java/org/onap/aai/sa/rest/ApiUtilsTest.java b/src/test/java/org/onap/aai/sa/rest/ApiUtilsTest.java index 593ec92..f205fa8 100644 --- a/src/test/java/org/onap/aai/sa/rest/ApiUtilsTest.java +++ b/src/test/java/org/onap/aai/sa/rest/ApiUtilsTest.java @@ -1,4 +1,4 @@ -/** +/** * ============LICENSE_START======================================================= * org.onap.aai * ================================================================================ @@ -20,23 +20,18 @@ */ package org.onap.aai.sa.rest; -import static org.junit.Assert.assertEquals; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; import org.junit.Test; - public class ApiUtilsTest { @Test public void testHTTPStatusConversion() { - String statusString; - statusString = ApiUtils.getHttpStatusString(201); - assertEquals(0, statusString.compareToIgnoreCase("Created")); - - statusString = ApiUtils.getHttpStatusString(207); - assertEquals(0, statusString.compareToIgnoreCase("Multi-Status")); - - statusString = ApiUtils.getHttpStatusString(9999); - assertEquals(0, statusString.compareToIgnoreCase("Unknown")); + assertThat(ApiUtils.getHttpStatusString(201), is(equalTo("Created"))); + assertThat(ApiUtils.getHttpStatusString(207), is(equalTo("Multi-Status"))); + assertThat(ApiUtils.getHttpStatusString(9999), is(equalTo("Unknown"))); } } diff --git a/src/test/java/org/onap/aai/sa/rest/BulkApiTest.java b/src/test/java/org/onap/aai/sa/rest/BulkApiTest.java index eff4efc..23071eb 100644 --- a/src/test/java/org/onap/aai/sa/rest/BulkApiTest.java +++ b/src/test/java/org/onap/aai/sa/rest/BulkApiTest.java @@ -1,4 +1,4 @@ -/** +/** * ============LICENSE_START======================================================= * org.onap.aai * ================================================================================ @@ -34,7 +34,6 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.ResultActions; /** @@ -78,13 +77,11 @@ public class BulkApiTest { this.mockMvc.perform(post(TOP_URI).contentType(MediaType.APPLICATION_JSON).content(validPayloadStr)) .andExpect(status().isOk()); - // Post a request to the bulk operations endpoint with an invalid // operations list payload. File inValidBulkOpsFile = new File("src/test/resources/json/bulk-ops-invalid.json"); String inValidPayloadStr = TestUtils.readFileToString(inValidBulkOpsFile); - ResultActions invalid = - this.mockMvc.perform(post(TOP_URI).contentType(MediaType.APPLICATION_JSON).content(inValidPayloadStr)) - .andExpect(status().isBadRequest()); + this.mockMvc.perform(post(TOP_URI).contentType(MediaType.APPLICATION_JSON).content(inValidPayloadStr)) + .andExpect(status().isBadRequest()); } } diff --git a/src/test/java/org/onap/aai/sa/rest/DocumentApiTest.java b/src/test/java/org/onap/aai/sa/rest/DocumentApiTest.java index 4276f3d..dd1ad2f 100644 --- a/src/test/java/org/onap/aai/sa/rest/DocumentApiTest.java +++ b/src/test/java/org/onap/aai/sa/rest/DocumentApiTest.java @@ -1,4 +1,4 @@ -/** +/** * ============LICENSE_START======================================================= * org.onap.aai * ================================================================================ @@ -27,8 +27,6 @@ import static org.springframework.test.web.servlet.request.MockMvcRequestBuilder import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; import java.io.IOException; -//import org.glassfish.jersey.server.ResourceConfig; -//import org.glassfish.jersey.test.JerseyTest; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; @@ -168,37 +166,25 @@ public class DocumentApiTest { } - // - // /** - // * This test validates the behaviour of the 'Search Documents' GET request - // * endpoint. - // * - // * @throws IOException - // * @throws ParseException - // */ + + /** + * This test validates the behaviour of the 'Search Documents' GET request endpoint. + * + * @throws Exception + */ @Ignore - @Test public void searchDocumentTest1() throws Exception { - // String result = target(INDEXES_URI + INDEX_NAME + "/" + SEARCH_URI + - // SIMPLE_QUERY).request().get(String.class); - MvcResult result = this.mockMvc .perform(get(INDEXES_URI + INDEX_NAME + "/" + SEARCH_URI + SIMPLE_QUERY) .contentType(MediaType.APPLICATION_JSON).header("If-Match", "1").content(CREATE_JSON_CONTENT)) .andReturn(); - // Our stub document store DAO returns the parameters that it was - // passed as the result string, so now we can validate that our - // endpoint invoked it with the correct parameters. JSONParser parser = new JSONParser(); JSONObject json = (JSONObject) parser.parse(result.getResponse().getContentAsString()); assertTrue("Unexpected Result ", json.get("totalHits").toString().equals("1")); - - } - // /** * This test validates the behaviour of the 'Search Documents' GET request endpoint. * @@ -207,21 +193,14 @@ public class DocumentApiTest { */ @Test public void searchDocumentTest2() throws Exception { - // String result = target(INDEXES_URI + INDEX_NAME + "/" + - // SEARCH_URI).request().post(Entity.json(COMPLEX_QUERY), String.class); - MvcResult result = this.mockMvc.perform(get(INDEXES_URI + INDEX_NAME + "/" + SEARCH_URI) .contentType(MediaType.APPLICATION_JSON).content(COMPLEX_QUERY)).andReturn(); - // Our stub document store DAO returns the parameters that it was - // passed as the result string, so now we can validate that our - // endpoint invoked it with the correct parameters. JSONParser parser = new JSONParser(); JSONObject json = (JSONObject) parser.parse(result.getResponse().getContentAsString()); JSONObject resultJson = (JSONObject) json.get("searchResult"); assertTrue("Unexpected Result ", resultJson.get("totalHits").toString().equals("1")); - } } diff --git a/src/test/java/org/onap/aai/sa/rest/DocumentSchemaTest.java b/src/test/java/org/onap/aai/sa/rest/DocumentSchemaTest.java index b18928d..c2d5021 100644 --- a/src/test/java/org/onap/aai/sa/rest/DocumentSchemaTest.java +++ b/src/test/java/org/onap/aai/sa/rest/DocumentSchemaTest.java @@ -29,7 +29,6 @@ import java.io.File; import java.io.IOException; import org.junit.Test; - public class DocumentSchemaTest { private final String SIMPLE_DOC_SCHEMA_JSON = "src/test/resources/json/simpleDocument.json"; diff --git a/src/test/java/org/onap/aai/sa/rest/DocumentTest.java b/src/test/java/org/onap/aai/sa/rest/DocumentTest.java index 9fa5fe1..d16fe87 100644 --- a/src/test/java/org/onap/aai/sa/rest/DocumentTest.java +++ b/src/test/java/org/onap/aai/sa/rest/DocumentTest.java @@ -103,6 +103,7 @@ public class DocumentTest { Assert.assertTrue(HttpStatus.BAD_REQUEST.value() == response.getStatusCodeValue());
}
+ @SuppressWarnings("unchecked")
@Test
public void testProcessPost_NotNullContent() throws Exception {
String transactionId = "transactionId-1";
@@ -117,7 +118,7 @@ public class DocumentTest { Mockito.when(searchServiceApi.validateRequest(Mockito.any(HttpHeaders.class),
Mockito.any(HttpServletRequest.class), Mockito.any(ApiUtils.Action.class), Mockito.anyString()))
.thenThrow(IllegalArgumentException.class);
- ResponseEntity response =
+ ResponseEntity<?> response =
documentApi.processPost(content, request, headers, httpResponse, "index", documentStore);
Assert.assertNotNull(response);
Assert.assertTrue(HttpStatus.FORBIDDEN.value() == response.getStatusCodeValue());
@@ -179,7 +180,7 @@ public class DocumentTest { }
- //
+ @SuppressWarnings("unchecked")
@Test
public void testProcessSearchWithGet_ValidateThrowsException() throws Exception {
String transactionId = "transactionId-1";
@@ -207,7 +208,6 @@ public class DocumentTest { }
- //
@Test
public void testProcessSearchWithGet_ValidateIsFalse() throws Exception {
String transactionId = "transactionId-1";
@@ -279,6 +279,7 @@ public class DocumentTest { Assert.assertTrue(HttpStatus.BAD_REQUEST.value() == response.getStatusCodeValue());
}
+ @SuppressWarnings("unchecked")
@Test
public void testProcessPut_RequestThrowsException() throws Exception {
String transactionId = "transactionId-1";
@@ -319,7 +320,6 @@ public class DocumentTest { Assert.assertTrue(HttpStatus.FORBIDDEN.value() == response.getStatusCodeValue());
}
- @Ignore
@Test
public void testProcessPut_ResultInvalid() throws Exception {
String transactionId = "transactionId-1";
@@ -338,7 +338,7 @@ public class DocumentTest { Mockito.when(searchServiceApi.validateRequest(Mockito.any(HttpHeaders.class),
Mockito.any(HttpServletRequest.class), Mockito.any(ApiUtils.Action.class), Mockito.anyString()))
.thenReturn(true);
- Mockito.when(documentStore.updateDocument(Mockito.anyString(), Mockito.any(DocumentStoreDataEntity.class),
+ Mockito.when(documentStore.createDocument(Mockito.anyString(), Mockito.any(DocumentStoreDataEntity.class),
Mockito.anyBoolean())).thenReturn(result);
ResponseEntity<String> response =
documentApi.processPut(content, request, headers, httpResponse, "index", "id-1", documentStore);
@@ -346,6 +346,7 @@ public class DocumentTest { Assert.assertTrue(HttpStatus.FOUND.value() == response.getStatusCodeValue());
}
+ @SuppressWarnings("unchecked")
@Test
public void testProcessDelete_RequestThrowsException() throws Exception {
String transactionId = "transactionId-1";
@@ -413,6 +414,7 @@ public class DocumentTest { Assert.assertTrue(HttpStatus.FOUND.value() == response.getStatusCodeValue());
}
+ @SuppressWarnings("unchecked")
@Test
public void testProcessGet_RequestThrowsException() throws Exception {
String transactionId = "transactionId-1";
@@ -496,6 +498,7 @@ public class DocumentTest { Assert.assertTrue(HttpStatus.BAD_REQUEST.value() == response.getStatusCodeValue());
}
+ @SuppressWarnings("unchecked")
@Test
public void testQueryWithGetWithPayload_RequestThrowsException() throws Exception {
String transactionId = "transactionId-1";
@@ -555,6 +558,7 @@ public class DocumentTest { Assert.assertTrue(HttpStatus.FORBIDDEN.value() == response.getStatusCodeValue());
}
+ @SuppressWarnings("unchecked")
@Test
public void testCreateProcessIndex_IndexApi_RequestThrowsException() throws Exception {
String transactionId = "transactionId-1";
@@ -612,6 +616,7 @@ public class DocumentTest { Assert.assertTrue(HttpStatus.FORBIDDEN.value() == response.getStatusCodeValue());
}
+ @SuppressWarnings("unchecked")
@Test
public void testProcessDelete_IndexApi_RequestThrowsException() throws Exception {
String transactionId = "transactionId-1";
@@ -630,6 +635,7 @@ public class DocumentTest { Assert.assertTrue(HttpStatus.FORBIDDEN.value() == response.getStatusCodeValue());
}
+ @SuppressWarnings("unchecked")
@Test
public void testProcessDelete_IndexApi_DeleteIndexException() throws Exception {
String transactionId = "transactionId-1";
diff --git a/src/test/java/org/onap/aai/sa/rest/IndexApiTest.java b/src/test/java/org/onap/aai/sa/rest/IndexApiTest.java index cd33edd..ed84a7a 100644 --- a/src/test/java/org/onap/aai/sa/rest/IndexApiTest.java +++ b/src/test/java/org/onap/aai/sa/rest/IndexApiTest.java @@ -135,7 +135,7 @@ public class IndexApiTest { successResult.setResult(SUCCESS_RESULT_STRING); // Convert our success OperationResult to a standard REST Response... - ResponseEntity successResponse = indexApi.responseFromOperationResult(successResult); + ResponseEntity<?> successResponse = indexApi.responseFromOperationResult(successResult); // ...and validate that the Response is correctly populated. assertEquals("Unexpected result code", SUCCESS_RESULT_CODE, successResponse.getStatusCodeValue()); @@ -148,7 +148,7 @@ public class IndexApiTest { failureResult.setFailureCause(FAILURE_CAUSE_STRING); // Convert our failure OperationResult to a standard REST Response... - ResponseEntity failureResponse = indexApi.responseFromOperationResult(failureResult); + ResponseEntity<?> failureResponse = indexApi.responseFromOperationResult(failureResult); // ...and validate that the Response is correctly populated. assertEquals("Unexpected result code", FAILURE_RESULT_CODE, failureResponse.getStatusCodeValue()); diff --git a/src/test/java/org/onap/aai/sa/rest/SearchServiceApiHarness.java b/src/test/java/org/onap/aai/sa/rest/SearchServiceApiHarness.java index 072b090..93e1d49 100644 --- a/src/test/java/org/onap/aai/sa/rest/SearchServiceApiHarness.java +++ b/src/test/java/org/onap/aai/sa/rest/SearchServiceApiHarness.java @@ -158,8 +158,7 @@ public class SearchServiceApiHarness extends SearchServiceApi { @Override protected boolean validateRequest(HttpHeaders headers, HttpServletRequest req, ApiUtils.Action action, - String authPolicyFunctionName) throws Exception { - + String authPolicyFunctionName) { return authenticationShouldSucceed; } } diff --git a/src/test/java/org/onap/aai/sa/rest/StubEsController.java b/src/test/java/org/onap/aai/sa/rest/StubEsController.java index 14a7534..cb4edbc 100644 --- a/src/test/java/org/onap/aai/sa/rest/StubEsController.java +++ b/src/test/java/org/onap/aai/sa/rest/StubEsController.java @@ -111,10 +111,6 @@ public class StubEsController implements DocumentStoreInterface { opResult.setResultCode(404); } else { opResult.setResultCode(200); - String id = "dummy"; - if (document.getId() != null) { - id = document.getId(); - } opResult.setResultVersion("1"); } @@ -253,7 +249,7 @@ public class StubEsController implements DocumentStoreInterface { SearchHit searchHit = new SearchHit(); Document doc = new Document(); doc.setEtag("etag1"); - Map<String, Object> content = new HashMap<String, Object>(); + Map<String, Object> content = new HashMap<>(); content.put("key1", "value1"); doc.setContent(new JSONObject()); searchHit.setDocument(doc); diff --git a/src/test/java/org/onap/aai/sa/searchdbabstraction/searchapi/QueryTest.java b/src/test/java/org/onap/aai/sa/searchdbabstraction/searchapi/QueryTest.java index 2f22605..e229348 100644 --- a/src/test/java/org/onap/aai/sa/searchdbabstraction/searchapi/QueryTest.java +++ b/src/test/java/org/onap/aai/sa/searchdbabstraction/searchapi/QueryTest.java @@ -1,4 +1,4 @@ -/** +/** * ============LICENSE_START======================================================= * org.onap.aai * ================================================================================ @@ -32,182 +32,182 @@ import org.junit.Test; public class QueryTest { - /** + /** * This test validates that we are able to marshal json structures representing term queries into POJOs and that we * can then unmarshal those POJOs into ElasticSearch syntax. - * - * @throws JsonParseException - * @throws JsonMappingException - * @throws IOException - */ - @Test - public void termQueryTest() throws JsonParseException, JsonMappingException, IOException { + * + * @throws JsonParseException + * @throws JsonMappingException + * @throws IOException + */ + @Test + public void termQueryTest() throws JsonParseException, JsonMappingException, IOException { - Integer intValue = 1; - String field = "searchTags"; - String termQueryWithIntegerValueJson = "{\"field\": \"" + field + "\", \"value\": " + intValue + "}"; - String termQueryWithIntegerValueExpectedES = "{\"term\": {\"" + field + "\" : " + intValue + "}}"; + Integer intValue = 1; + String field = "searchTags"; + String termQueryWithIntegerValueJson = "{\"field\": \"" + field + "\", \"value\": " + intValue + "}"; + String termQueryWithIntegerValueExpectedES = "{\"term\": {\"" + field + "\" : " + intValue + "}}"; - Double doubleValue = 5.7; - String termQueryWithDoubleValueJson = "{\"field\": \"" + field + "\", \"value\": " + doubleValue + "}"; - String termQueryWithDoubleValueExpectedES = "{\"term\": {\"" + field + "\" : " + doubleValue + "}}"; + Double doubleValue = 5.7; + String termQueryWithDoubleValueJson = "{\"field\": \"" + field + "\", \"value\": " + doubleValue + "}"; + String termQueryWithDoubleValueExpectedES = "{\"term\": {\"" + field + "\" : " + doubleValue + "}}"; - String stringValue = "theValue"; - String termQueryWithStringValueJson = "{\"field\": \"" + field + "\", \"value\": \"" + stringValue + "\"}"; - String termQueryWithStringValueExpectedES = "{\"term\": {\"" + field + "\" : \"" + stringValue + "\"}}"; + String stringValue = "theValue"; + String termQueryWithStringValueJson = "{\"field\": \"" + field + "\", \"value\": \"" + stringValue + "\"}"; + String termQueryWithStringValueExpectedES = "{\"term\": {\"" + field + "\" : \"" + stringValue + "\"}}"; - ObjectMapper mapper = new ObjectMapper(); + ObjectMapper mapper = new ObjectMapper(); - // Validate that we can marshal a term query where the supplied value - // is an Integer. - TermQuery integerTermQuery = mapper.readValue(termQueryWithIntegerValueJson, TermQuery.class); + // Validate that we can marshal a term query where the supplied value + // is an Integer. + TermQuery integerTermQuery = mapper.readValue(termQueryWithIntegerValueJson, TermQuery.class); assertTrue( "Expected value to be of type Integer, but was type " + integerTermQuery.getValue().getClass().getName(), - integerTermQuery.getValue() instanceof Integer); - assertEquals(intValue, integerTermQuery.getValue()); + integerTermQuery.getValue() instanceof Integer); + assertEquals(intValue, integerTermQuery.getValue()); - assertTrue("ElasticSearch term query translation does not match the expected result", - termQueryWithIntegerValueExpectedES.equals(integerTermQuery.toElasticSearch())); + assertTrue("ElasticSearch term query translation does not match the expected result", + termQueryWithIntegerValueExpectedES.equals(integerTermQuery.toElasticSearch())); - // Validate that we can marshal a term query where the supplied value - // is a Double. - TermQuery doubleTermQuery = mapper.readValue(termQueryWithDoubleValueJson, TermQuery.class); + // Validate that we can marshal a term query where the supplied value + // is a Double. + TermQuery doubleTermQuery = mapper.readValue(termQueryWithDoubleValueJson, TermQuery.class); assertTrue( "Expected value to be of type Double, but was type " + doubleTermQuery.getValue().getClass().getName(), - doubleTermQuery.getValue() instanceof Double); - assertEquals(doubleValue, doubleTermQuery.getValue()); - assertTrue("ElasticSearch term query translation does not match the expected result", - termQueryWithDoubleValueExpectedES.equals(doubleTermQuery.toElasticSearch())); - - // Validate that we can marshal a term query where the supplied value - // is a String literal. - TermQuery stringTermQuery = mapper.readValue(termQueryWithStringValueJson, TermQuery.class); + doubleTermQuery.getValue() instanceof Double); + assertEquals(doubleValue, doubleTermQuery.getValue()); + assertTrue("ElasticSearch term query translation does not match the expected result", + termQueryWithDoubleValueExpectedES.equals(doubleTermQuery.toElasticSearch())); + + // Validate that we can marshal a term query where the supplied value + // is a String literal. + TermQuery stringTermQuery = mapper.readValue(termQueryWithStringValueJson, TermQuery.class); assertTrue( "Expected value to be of type String, but was type " + stringTermQuery.getValue().getClass().getName(), - stringTermQuery.getValue() instanceof String); - assertEquals(stringValue, stringTermQuery.getValue()); - assertTrue("ElasticSearch term query translation does not match the expected result", - termQueryWithStringValueExpectedES.equals(stringTermQuery.toElasticSearch())); + stringTermQuery.getValue() instanceof String); + assertEquals(stringValue, stringTermQuery.getValue()); + assertTrue("ElasticSearch term query translation does not match the expected result", + termQueryWithStringValueExpectedES.equals(stringTermQuery.toElasticSearch())); - } + } - /** + /** * This test validates that we are able to marshal json structures representing parsed queries into POJOs and that * we can then unmarshal those POJOs into ElasticSearch syntax. - * - * @throws JsonParseException - * @throws JsonMappingException - * @throws IOException - */ - @Test - public void parsedQueryTest() throws JsonParseException, JsonMappingException, IOException { - - String field = "fieldname"; - String queryString = "The query string"; - - String queryJson = "{\"field\": \"" + field + "\", \"query-string\": \"" + queryString + "\"}"; + * + * @throws JsonParseException + * @throws JsonMappingException + * @throws IOException + */ + @Test + public void parsedQueryTest() throws JsonParseException, JsonMappingException, IOException { + + String field = "fieldname"; + String queryString = "The query string"; + + String queryJson = "{\"field\": \"" + field + "\", \"query-string\": \"" + queryString + "\"}"; String queryExpectedES = "{\"query_string\": {\"default_field\": \"" + field + "\", \"query\": \"" + queryString + "\"}}"; - ObjectMapper mapper = new ObjectMapper(); - ParsedQuery pq = mapper.readValue(queryJson, ParsedQuery.class); + ObjectMapper mapper = new ObjectMapper(); + ParsedQuery pq = mapper.readValue(queryJson, ParsedQuery.class); - assertTrue("Unexpected marshalled value for 'field' - expected: " + field + " actual: " + pq.getField(), - field.equals(pq.getField())); + assertTrue("Unexpected marshalled value for 'field' - expected: " + field + " actual: " + pq.getField(), + field.equals(pq.getField())); assertTrue("Unexpected marshalled value for 'query-string' - expected: " + queryString + " actual: " + pq.getQueryString(), queryString.equals(pq.getQueryString())); assertTrue( "Unexpected ElasticSearch syntax. Expected: " + queryExpectedES + " Actual: " + pq.toElasticSearch(), - queryExpectedES.equals(pq.toElasticSearch())); - } + queryExpectedES.equals(pq.toElasticSearch())); + } - /** + /** * This test validates that a ranged query cannot be parsed with values for both the 'gte' and 'gt' fields or the * 'lte' and 'lt' fields, and that we do not allow mixing of numeric and date types in the same query. - * - * @throws JsonParseException - * @throws IOException - */ - @Test - public void rangeQueryConflictingBoundsTest() throws JsonParseException, IOException { + * + * @throws JsonParseException + * @throws IOException + */ + @Test + public void rangeQueryConflictingBoundsTest() throws JsonParseException, IOException { String invalidGTAndGTE = "{ \"field\": \"timestamp\", \"gte\": \"2016-10-06T00:00:00.558+03:00\", \"gt\": \"2016-10-06T23:59:59.558+03:00\"}"; String invalidLTAndLTE = "{ \"field\": \"timestamp\", \"lte\": \"2016-10-06T00:00:00.558+03:00\", \"lt\": \"2016-10-06T23:59:59.558+03:00\"}"; - String invalidTypes = "{ \"field\": \"timestamp\", \"lte\": 5, \"gte\": \"2016-10-06T23:59:59.558+03:00\"}"; - - ObjectMapper mapper = new ObjectMapper(); - - // Attempt to parse a query where we are setting values for both the - // 'greater than' and 'greater than and equal to' operators. - boolean gotExpectedException = false; - try { - RangeQuery badRangeQuery = mapper.readValue(invalidGTAndGTE, RangeQuery.class); - } catch (JsonMappingException e) { - gotExpectedException = true; - } - assertTrue("Attempting to set both a 'gt' and 'gte' value on the same query should not have been allowed", - gotExpectedException); - - // Attempt to parse a query where we are setting values for both the - // 'less than' and 'less than and equal to' operators. - gotExpectedException = false; - try { - RangeQuery badRangeQuery = mapper.readValue(invalidLTAndLTE, RangeQuery.class); - } catch (JsonMappingException e) { - gotExpectedException = true; - } - assertTrue("Attempting to set both a 'lt' and 'lte' value on the same query should not have been allowed", - gotExpectedException); - - // Attempt to parse a query where we are mixing numeric and date values - // in the same query. - gotExpectedException = false; - try { - RangeQuery badRangeQuery = mapper.readValue(invalidTypes, RangeQuery.class); - } catch (JsonMappingException e) { - gotExpectedException = true; - } - assertTrue("Attempting to mix numeric and date values in the same query should not have been allowed", - gotExpectedException); + String invalidTypes = "{ \"field\": \"timestamp\", \"lte\": 5, \"gte\": \"2016-10-06T23:59:59.558+03:00\"}"; + ObjectMapper mapper = new ObjectMapper(); + // Attempt to parse a query where we are setting values for both the + // 'greater than' and 'greater than and equal to' operators. + boolean gotExpectedException = false; + try { + mapper.readValue(invalidGTAndGTE, RangeQuery.class); + } catch (JsonMappingException e) { + gotExpectedException = true; + } + assertTrue("Attempting to set both a 'gt' and 'gte' value on the same query should not have been allowed", + gotExpectedException); + + // Attempt to parse a query where we are setting values for both the + // 'less than' and 'less than and equal to' operators. + gotExpectedException = false; + try { + mapper.readValue(invalidLTAndLTE, RangeQuery.class); + } catch (JsonMappingException e) { + gotExpectedException = true; + } + assertTrue("Attempting to set both a 'lt' and 'lte' value on the same query should not have been allowed", + gotExpectedException); + + // Attempt to parse a query where we are mixing numeric and date values + // in the same query. + gotExpectedException = false; + try { + mapper.readValue(invalidTypes, RangeQuery.class); + } catch (JsonMappingException e) { + gotExpectedException = true; } + assertTrue("Attempting to mix numeric and date values in the same query should not have been allowed", + gotExpectedException); - /** + } + + + /** * This test validates that date range queries can be marshalled to a Java POJO and unmarshalled to ElasticSearch * syntax. - * - * @throws JsonParseException - * @throws JsonMappingException - * @throws IOException - */ - @Test - public void dateRangeQueryTest() throws JsonParseException, JsonMappingException, IOException { - - String field = "timestamp"; - String greaterThanDate = "2016-10-06T00:00:00.558+03:00"; - String lessThanDate = "2016-10-06T23:59:59.558+03:00"; - - ObjectMapper mapper = new ObjectMapper(); - - // Generate a date range query using 'greater than or equal' and 'less - // than or equal' operations. + * + * @throws JsonParseException + * @throws JsonMappingException + * @throws IOException + */ + @Test + public void dateRangeQueryTest() throws JsonParseException, JsonMappingException, IOException { + + String field = "timestamp"; + String greaterThanDate = "2016-10-06T00:00:00.558+03:00"; + String lessThanDate = "2016-10-06T23:59:59.558+03:00"; + + ObjectMapper mapper = new ObjectMapper(); + + // Generate a date range query using 'greater than or equal' and 'less + // than or equal' operations. String dateRangeJson = "{ \"field\": \"" + field + "\", \"gte\": \"" + greaterThanDate + "\", \"lte\": \"" + lessThanDate + "\"}"; - String dateRangeExpectedES = - "{\"range\": {\"timestamp\": {\"gte\": \"2016-10-06T00:00:00.558+03:00\", \"lte\": \"2016-10-06T23:59:59.558+03:00\"}}}"; + String dateRangeExpectedES = + "{\"range\": {\"timestamp\": {\"gte\": \"2016-10-06T00:00:00.558+03:00\", \"lte\": \"2016-10-06T23:59:59.558+03:00\"}}}"; - // Validate that the query is marshalled correctly to the POJO and that - // the generated ElasticSearch syntax looks as expected. - RangeQuery dateRangeQuery = mapper.readValue(dateRangeJson, RangeQuery.class); + // Validate that the query is marshalled correctly to the POJO and that + // the generated ElasticSearch syntax looks as expected. + RangeQuery dateRangeQuery = mapper.readValue(dateRangeJson, RangeQuery.class); assertTrue("Unexpected marshalled value for 'field'. Expected: " + field + " Actual: " + dateRangeQuery.getField(), field.equals(dateRangeQuery.getField())); @@ -222,19 +222,19 @@ public class QueryTest { assertTrue( "Unexpected ElasticSearch syntax. Expected: " + dateRangeExpectedES + " Actual: " + dateRangeQuery.toElasticSearch(), - dateRangeExpectedES.equals(dateRangeQuery.toElasticSearch())); + dateRangeExpectedES.equals(dateRangeQuery.toElasticSearch())); - // Generate a date range query using 'greater than' and 'less than or - // equal' operations. + // Generate a date range query using 'greater than' and 'less than or + // equal' operations. dateRangeJson = "{ \"field\": \"" + field + "\", \"gt\": \"" + greaterThanDate + "\", \"lte\": \"" + lessThanDate + "\"}"; - dateRangeExpectedES = - "{\"range\": {\"timestamp\": {\"gt\": \"2016-10-06T00:00:00.558+03:00\", \"lte\": \"2016-10-06T23:59:59.558+03:00\"}}}"; + dateRangeExpectedES = + "{\"range\": {\"timestamp\": {\"gt\": \"2016-10-06T00:00:00.558+03:00\", \"lte\": \"2016-10-06T23:59:59.558+03:00\"}}}"; - // Validate that the query is marshalled correctly to the POJO and that - // the generated ElasticSearch syntax looks as expected. - dateRangeQuery = mapper.readValue(dateRangeJson, RangeQuery.class); + // Validate that the query is marshalled correctly to the POJO and that + // the generated ElasticSearch syntax looks as expected. + dateRangeQuery = mapper.readValue(dateRangeJson, RangeQuery.class); assertTrue("Unexpected marshalled value for 'field'. Expected: " + field + " Actual: " + dateRangeQuery.getField(), field.equals(dateRangeQuery.getField())); @@ -254,16 +254,16 @@ public class QueryTest { assertTrue( "Unexpected ElasticSearch syntax. Expected: " + dateRangeExpectedES + " Actual: " + dateRangeQuery.toElasticSearch(), - dateRangeExpectedES.equals(dateRangeQuery.toElasticSearch())); + dateRangeExpectedES.equals(dateRangeQuery.toElasticSearch())); - // Generate a date range query using only a 'greater than' operation. + // Generate a date range query using only a 'greater than' operation. dateRangeJson = "{ \"field\": \"" + field + "\", \"gt\": \"" + greaterThanDate + "\"}"; dateRangeExpectedES = "{\"range\": {\"timestamp\": {\"gt\": \"2016-10-06T00:00:00.558+03:00\"}}}"; - // Validate that the query is marshalled correctly to the POJO and that - // the generated ElasticSearch syntax looks as expected. - dateRangeQuery = mapper.readValue(dateRangeJson, RangeQuery.class); + // Validate that the query is marshalled correctly to the POJO and that + // the generated ElasticSearch syntax looks as expected. + dateRangeQuery = mapper.readValue(dateRangeJson, RangeQuery.class); assertTrue("Unexpected marshalled value for 'field'. Expected: " + field + " Actual: " + dateRangeQuery.getField(), field.equals(dateRangeQuery.getField())); @@ -277,48 +277,48 @@ public class QueryTest { assertTrue( "Unexpected ElasticSearch syntax. Expected: " + dateRangeExpectedES + " Actual: " + dateRangeQuery.toElasticSearch(), - dateRangeExpectedES.equals(dateRangeQuery.toElasticSearch())); + dateRangeExpectedES.equals(dateRangeQuery.toElasticSearch())); - } + } - /** + /** * This test validates that numeric range queries can be marshalled to a Java POJO and unmarshalled to ElasticSearch * syntax. - * - * @throws JsonParseException - * @throws JsonMappingException - * @throws IOException - */ - @Test - public void numericRangeQueryTest() throws JsonParseException, JsonMappingException, IOException { - - String field = "version"; - Integer greaterThanInt = 5; - Integer lessThanInt = 100; - - ObjectMapper mapper = new ObjectMapper(); - - // Generate a numeric range query using 'greater than or equal' and 'less - // than or equal' operations. - String numericRangeJson = - "{ \"field\": \"" + field + "\", \"gte\": " + greaterThanInt + ", \"lte\": " + lessThanInt + "}"; - String numericRangeExpectedES = - "{\"range\": {\"" + field + "\": {\"gte\": " + greaterThanInt + ", \"lte\": " + lessThanInt + "}}}"; - - // Validate that the query is marshalled correctly to the POJO and that - // the generated ElasticSearch syntax looks as expected. - RangeQuery numericRangeQuery = mapper.readValue(numericRangeJson, RangeQuery.class); + * + * @throws JsonParseException + * @throws JsonMappingException + * @throws IOException + */ + @Test + public void numericRangeQueryTest() throws JsonParseException, JsonMappingException, IOException { + + String field = "version"; + Integer greaterThanInt = 5; + Integer lessThanInt = 100; + + ObjectMapper mapper = new ObjectMapper(); + + // Generate a numeric range query using 'greater than or equal' and 'less + // than or equal' operations. + String numericRangeJson = + "{ \"field\": \"" + field + "\", \"gte\": " + greaterThanInt + ", \"lte\": " + lessThanInt + "}"; + String numericRangeExpectedES = + "{\"range\": {\"" + field + "\": {\"gte\": " + greaterThanInt + ", \"lte\": " + lessThanInt + "}}}"; + + // Validate that the query is marshalled correctly to the POJO and that + // the generated ElasticSearch syntax looks as expected. + RangeQuery numericRangeQuery = mapper.readValue(numericRangeJson, RangeQuery.class); assertTrue("Unexpected marshalled value for 'field'. Expected: " + field + " Actual: " + numericRangeQuery.getField(), field.equals(numericRangeQuery.getField())); assertTrue( "Unexpected type for 'gte' value. Expected: Integer Actual: " + numericRangeQuery.getGte().getClass().getName(), - numericRangeQuery.getGte() instanceof Integer); + numericRangeQuery.getGte() instanceof Integer); assertTrue( "Unexpected type for 'lte' value. Expected: Integer Actual: " + numericRangeQuery.getLte().getClass().getName(), - numericRangeQuery.getLte() instanceof Integer); + numericRangeQuery.getLte() instanceof Integer); assertEquals("Unexpected marshalled value for 'gte'. Expected: " + greaterThanInt + " Actual: " + numericRangeQuery.getGte(), greaterThanInt, numericRangeQuery.getGte()); assertEquals("Unexpected marshalled value for 'lte'. Expected: " + lessThanInt + " Actual: " @@ -326,22 +326,22 @@ public class QueryTest { assertTrue( "Unexpected ElasticSearch syntax. Expected: " + numericRangeExpectedES + " Actual: " + numericRangeQuery.toElasticSearch(), - numericRangeExpectedES.equals(numericRangeQuery.toElasticSearch())); + numericRangeExpectedES.equals(numericRangeQuery.toElasticSearch())); - Double greaterThanDouble = 5.0; - Double lessThanDouble = 100.0; + Double greaterThanDouble = 5.0; + Double lessThanDouble = 100.0; - // Generate a date range query using 'greater than' and 'less than or - // equal' operations. - numericRangeJson = - "{ \"field\": \"" + field + "\", \"gt\": " + greaterThanDouble + ", \"lte\": " + lessThanDouble + "}"; + // Generate a date range query using 'greater than' and 'less than or + // equal' operations. + numericRangeJson = + "{ \"field\": \"" + field + "\", \"gt\": " + greaterThanDouble + ", \"lte\": " + lessThanDouble + "}"; numericRangeExpectedES = "{\"range\": {\"" + field + "\": {\"gt\": " + greaterThanDouble + ", \"lte\": " + lessThanDouble + "}}}"; - // Validate that the query is marshalled correctly to the POJO and that - // the generated ElasticSearch syntax looks as expected. - numericRangeQuery = mapper.readValue(numericRangeJson, RangeQuery.class); + // Validate that the query is marshalled correctly to the POJO and that + // the generated ElasticSearch syntax looks as expected. + numericRangeQuery = mapper.readValue(numericRangeJson, RangeQuery.class); assertTrue("Unexpected marshalled value for 'field'. Expected: " + field + " Actual: " + numericRangeQuery.getField(), field.equals(numericRangeQuery.getField())); @@ -352,7 +352,7 @@ public class QueryTest { assertTrue( "Unexpected type for 'lte' value. Expected: Double Actual: " + numericRangeQuery.getLte().getClass().getName(), - numericRangeQuery.getLte() instanceof Double); + numericRangeQuery.getLte() instanceof Double); assertEquals("Unexpected marshalled value for 'gt'. Expected: " + greaterThanDouble + " Actual: " + numericRangeQuery.getGt(), greaterThanDouble, numericRangeQuery.getGt()); @@ -363,7 +363,7 @@ public class QueryTest { assertTrue( "Unexpected ElasticSearch syntax. Expected: " + numericRangeExpectedES + " Actual: " + numericRangeQuery.toElasticSearch(), - numericRangeExpectedES.equals(numericRangeQuery.toElasticSearch())); - } + numericRangeExpectedES.equals(numericRangeQuery.toElasticSearch())); + } } diff --git a/src/test/java/org/onap/aai/sa/searchdbabstraction/searchapi/RangeQueryTest.java b/src/test/java/org/onap/aai/sa/searchdbabstraction/searchapi/RangeQueryTest.java index e8ca844..f048cee 100644 --- a/src/test/java/org/onap/aai/sa/searchdbabstraction/searchapi/RangeQueryTest.java +++ b/src/test/java/org/onap/aai/sa/searchdbabstraction/searchapi/RangeQueryTest.java @@ -1,149 +1,155 @@ -/**
- * ============LICENSE_START=======================================================
- * org.onap.aai
- * ================================================================================
- * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
- * Copyright © 2017-2018 Amdocs
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-package org.onap.aai.sa.searchdbabstraction.searchapi;
-
-import com.fasterxml.jackson.databind.ObjectMapper;
-import java.io.File;
-import java.io.IOException;
-import org.junit.Assert;
-import org.junit.Test;
-import org.onap.aai.sa.rest.TestUtils;
-
-public class RangeQueryTest {
-
- @Test(expected = IllegalArgumentException.class)
- public void testSetGt() {
-
- RangeQuery rq = new RangeQuery();
- rq.setLt(new String("2x"));
- Assert.assertEquals("2x", rq.getLt());
- Assert.assertNotNull(rq.toElasticSearch());
- Assert.assertNotNull(rq.toString());
- rq.setGt(new Integer(1));
- }
-
- @Test(expected = IllegalArgumentException.class)
- public void testSetGte() {
-
- RangeQuery rq = new RangeQuery();
- rq.setGt(new Integer(1));
- Assert.assertNotNull(rq.toElasticSearch());
- Assert.assertNotNull(rq.toString());
- rq.setGte(new Integer(1));
- }
-
- @Test(expected = IllegalArgumentException.class)
- public void testSetLt() {
-
- RangeQuery rq = new RangeQuery();
- rq.setLt(new Integer(1));
- rq.setFormat("format-1");
- Assert.assertEquals(rq.getFormat(), "format-1");
- Assert.assertNotNull(rq.toElasticSearch());
- Assert.assertNotNull(rq.toString());
-
- rq.setGt(new Integer(1));
- Assert.assertNotNull(rq.toElasticSearch());
- Assert.assertNotNull(rq.toString());
- rq.setLt(new String("10"));
- }
-
- @Test(expected = IllegalArgumentException.class)
- public void testSetLte() {
- RangeQuery rq = new RangeQuery();
- rq.setGt(new Integer(1));
- rq.setTimeZone("CT");
- Assert.assertEquals(rq.getTimeZone(), "CT");
- Assert.assertNotNull(rq.toElasticSearch());
- Assert.assertNotNull(rq.toString());
-
- rq.setLte(new String("10"));
- }
-
- @Test
- public void testSearchStatementAggregations() throws IOException {
- File queryWithSubrangeFile = new File("src/test/resources/json/queries/query-with-subrange.json");
- String queryWithSubrangeStr = TestUtils.readFileToString(queryWithSubrangeFile);
-
- ObjectMapper mapper = new ObjectMapper();
- SearchStatement ss = mapper.readValue(queryWithSubrangeStr, SearchStatement.class);
-
- Aggregation a1 = getAggregationObject();
- Aggregation a2 = getAggregationObject();
- Aggregation[] aggs = new Aggregation[] {a1, a2};
- ss.setAggregations(aggs);
- Assert.assertNotNull(ss.toString());
- }
-
- private Aggregation getAggregationObject() {
- Aggregation a = new Aggregation();
-
- AggregationStatement as = new AggregationStatement();
- DateHistogramAggregation dha = new DateHistogramAggregation();
- dha.setField("field-1");
- dha.setInterval("interval-1");
- Assert.assertEquals(dha.getInterval(), "interval-1");
- dha.setTimeZone("CT");
- Assert.assertEquals(dha.getTimeZone(), "CT");
- dha.setFormat("format-1");
- Assert.assertEquals(dha.getFormat(), "format-1");
- dha.setSize(10);
- dha.setMinThreshold(1);
- Assert.assertNotNull(dha.toElasticSearch());
- Assert.assertNotNull(dha.toString());
- as.setDateHist(dha);
- as.toString();
-
- as.getNestedPath();
-
- DateRangeAggregation dra = new DateRangeAggregation();
- dra.setField("field-1");
- dra.setMinThreshold(1);
- dra.setFormat("format-1");
- Assert.assertEquals(dra.getFormat(), "format-1");
- DateRange dr = new DateRange();
- dr.setFromDate("01-12-2017");
- Assert.assertEquals(dr.getFromDate(), "01-12-2017");
- dr.setToDate("21-12-2017");
- Assert.assertEquals(dr.getToDate(), "21-12-2017");
- DateRange[] drs = {dr};
- dra.setDateRanges(drs);
- Assert.assertTrue(dra.getDateRanges().length == 1);
- Assert.assertNotNull(dra.toElasticSearch());
- Assert.assertNotNull(dra.toString());
- as.setDateRange(dra);
- as.toString();
-
- as.getNestedPath();
-
- GroupByAggregation gba = new GroupByAggregation();
- gba.setField("field-1");
- gba.setMinThreshold(1);
- Assert.assertNotNull(gba.toElasticSearch());
- Assert.assertNotNull(gba.toString());
- as.setGroupBy(gba);
- Assert.assertNotNull(as.toString());
-
- a.setStatement(as);
- Assert.assertNotNull(a.toString());
- return a;
- }
-}
+/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright © 2017-2018 Amdocs + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.onap.aai.sa.searchdbabstraction.searchapi; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +import com.fasterxml.jackson.databind.ObjectMapper; +import java.io.File; +import java.io.IOException; +import org.junit.Assert; +import org.junit.Test; +import org.onap.aai.sa.rest.TestUtils; + +public class RangeQueryTest { + + static { + // Set the location of the payload translation JSON file. + System.setProperty("CONFIG_HOME", "src/test/resources/json"); + } + + @Test(expected = IllegalArgumentException.class) + public void testSetGt() { + RangeQuery rq = new RangeQuery(); + rq.setLt(new String("2x")); + Assert.assertEquals("2x", rq.getLt()); + Assert.assertNotNull(rq.toElasticSearch()); + Assert.assertNotNull(rq.toString()); + rq.setGt(new Integer(1)); + } + + @Test(expected = IllegalArgumentException.class) + public void testSetGte() { + RangeQuery rq = new RangeQuery(); + rq.setGt(new Integer(1)); + Assert.assertNotNull(rq.toElasticSearch()); + Assert.assertNotNull(rq.toString()); + rq.setGte(new Integer(1)); + } + + @Test(expected = IllegalArgumentException.class) + public void testSetLt() { + RangeQuery rq = new RangeQuery(); + rq.setLt(new Integer(1)); + rq.setFormat("format-1"); + assertThat(rq.getFormat(), is(equalTo("format-1"))); + Assert.assertNotNull(rq.toElasticSearch()); + Assert.assertNotNull(rq.toString()); + + rq.setGt(new Integer(1)); + Assert.assertNotNull(rq.toElasticSearch()); + Assert.assertNotNull(rq.toString()); + rq.setLt(new String("10")); + } + + @Test(expected = IllegalArgumentException.class) + public void testSetLte() { + RangeQuery rq = new RangeQuery(); + rq.setGt(new Integer(1)); + rq.setTimeZone("CT"); + assertThat(rq.getTimeZone(), is(equalTo("CT"))); + Assert.assertNotNull(rq.toElasticSearch()); + Assert.assertNotNull(rq.toString()); + + rq.setLte(new String("10")); + } + + @Test + public void testSearchStatementAggregations() throws IOException { + File queryWithSubrangeFile = new File("src/test/resources/json/queries/query-with-subrange.json"); + String queryWithSubrangeStr = TestUtils.readFileToString(queryWithSubrangeFile); + + ObjectMapper mapper = new ObjectMapper(); + SearchStatement ss = mapper.readValue(queryWithSubrangeStr, SearchStatement.class); + + Aggregation a1 = getAggregationObject(); + Aggregation a2 = getAggregationObject(); + Aggregation[] aggs = new Aggregation[] {a1, a2}; + ss.setAggregations(aggs); + Assert.assertNotNull(ss.toString()); + } + + private Aggregation getAggregationObject() { + Aggregation a = new Aggregation(); + + AggregationStatement as = new AggregationStatement(); + DateHistogramAggregation dha = new DateHistogramAggregation(); + dha.setField("field-1"); + dha.setInterval("interval-1"); + assertThat(dha.getInterval(), is(equalTo("interval-1"))); + dha.setTimeZone("CT"); + assertThat(dha.getTimeZone(), is(equalTo("CT"))); + dha.setFormat("format-1"); + assertThat(dha.getFormat(), is(equalTo("format-1"))); + dha.setSize(10); + dha.setMinThreshold(1); + Assert.assertNotNull(dha.toElasticSearch()); + Assert.assertNotNull(dha.toString()); + as.setDateHist(dha); + as.toString(); + + as.getNestedPath(); + + DateRangeAggregation dra = new DateRangeAggregation(); + dra.setField("field-1"); + dra.setMinThreshold(1); + dra.setFormat("format-1"); + assertThat(dra.getFormat(), is(equalTo("format-1"))); + DateRange dr = new DateRange(); + dr.setFromDate("01-12-2017"); + assertThat(dr.getFromDate(), is(equalTo("01-12-2017"))); + dr.setToDate("21-12-2017"); + assertThat(dr.getToDate(), is(equalTo("21-12-2017"))); + DateRange[] drs = {dr}; + dra.setDateRanges(drs); + Assert.assertTrue(dra.getDateRanges().length == 1); + Assert.assertNotNull(dra.toElasticSearch()); + Assert.assertNotNull(dra.toString()); + as.setDateRange(dra); + as.toString(); + + as.getNestedPath(); + + GroupByAggregation gba = new GroupByAggregation(); + gba.setField("field-1"); + gba.setMinThreshold(1); + Assert.assertNotNull(gba.toElasticSearch()); + Assert.assertNotNull(gba.toString()); + as.setGroupBy(gba); + Assert.assertNotNull(as.toString()); + + a.setStatement(as); + Assert.assertNotNull(a.toString()); + return a; + } +} diff --git a/src/test/java/org/onap/aai/sa/searchdbabstraction/searchapi/TermQueryTest.java b/src/test/java/org/onap/aai/sa/searchdbabstraction/searchapi/TermQueryTest.java index 403ad6e..5a15913 100644 --- a/src/test/java/org/onap/aai/sa/searchdbabstraction/searchapi/TermQueryTest.java +++ b/src/test/java/org/onap/aai/sa/searchdbabstraction/searchapi/TermQueryTest.java @@ -29,11 +29,9 @@ public class TermQueryTest { @Test
public void testAllMethods() throws IOException {
-
String field = "searchTags.nested";
String stringValue = "theValue.nested";
String termQueryWithStringValueJson = "{\"field\": \"" + field + "\", \"value\": \"" + stringValue + "\"}";
- String termQueryWithStringValueExpectedES = "{\"term\": {\"" + field + "\" : \"" + stringValue + "\"}}";
ObjectMapper mapper = new ObjectMapper();
TermQuery stringTermQuery = mapper.readValue(termQueryWithStringValueJson, TermQuery.class);
|