diff options
author | mark.j.leonard <mark.j.leonard@gmail.com> | 2018-09-21 16:16:04 +0100 |
---|---|---|
committer | mark.j.leonard <mark.j.leonard@gmail.com> | 2018-09-21 16:16:04 +0100 |
commit | 15af66b115f3e8046b2d0f2634fb77b3d835f730 (patch) | |
tree | 9ed2889e541c0f24214becb6b82726e4bf8c319c /src/main/java | |
parent | 71393bb2bf9fb10962723e61cf0e70d9aa202645 (diff) |
Format Java code to ONAP standard
Use the Eclipse formatter to automatically format the code to adhere
to the defined standards.
Change-Id: I42a8c90c5b272facc4cc2a0c85233061ed64ba3f
Issue-ID: AAI-1650
Signed-off-by: mark.j.leonard <mark.j.leonard@gmail.com>
Diffstat (limited to 'src/main/java')
58 files changed, 4367 insertions, 4559 deletions
diff --git a/src/main/java/org/onap/aai/sa/Application.java b/src/main/java/org/onap/aai/sa/Application.java index cd253c6..4fe2202 100644 --- a/src/main/java/org/onap/aai/sa/Application.java +++ b/src/main/java/org/onap/aai/sa/Application.java @@ -33,11 +33,11 @@ public class Application extends SpringBootServletInitializer { public static void main(String[] args) {
String keyStorePassword = System.getProperty("KEY_STORE_PASSWORD");
- if(keyStorePassword==null || keyStorePassword.isEmpty()){
+ if (keyStorePassword == null || keyStorePassword.isEmpty()) {
throw new RuntimeException("Env property KEY_STORE_PASSWORD not set");
}
HashMap<String, Object> props = new HashMap<>();
props.put("server.ssl.key-store-password", Password.deobfuscate(keyStorePassword));
- new Application().configure(new SpringApplicationBuilder (Application.class).properties(props)).run(args);
+ new Application().configure(new SpringApplicationBuilder(Application.class).properties(props)).run(args);
}
}
diff --git a/src/main/java/org/onap/aai/sa/auth/SearchDbServiceAuth.java b/src/main/java/org/onap/aai/sa/auth/SearchDbServiceAuth.java index 1ef3dde..b64cb74 100644 --- a/src/main/java/org/onap/aai/sa/auth/SearchDbServiceAuth.java +++ b/src/main/java/org/onap/aai/sa/auth/SearchDbServiceAuth.java @@ -20,38 +20,37 @@ */ package org.onap.aai.sa.auth; - import javax.servlet.http.Cookie; +import javax.servlet.http.Cookie; import org.springframework.http.HttpHeaders; public class SearchDbServiceAuth { - public SearchDbServiceAuth() { - } + public SearchDbServiceAuth() {} - public boolean authBasic(String username, String authFunction) { - return SearchDbServiceAuthCore.authorize(username, authFunction); - } + public boolean authBasic(String username, String authFunction) { + return SearchDbServiceAuthCore.authorize(username, authFunction); + } - public String authUser(HttpHeaders headers, String authUser, String authFunction) { + public String authUser(HttpHeaders headers, String authUser, String authFunction) { - SearchDbServiceAuth aaiAuth = new SearchDbServiceAuth(); + SearchDbServiceAuth aaiAuth = new SearchDbServiceAuth(); - StringBuilder username = new StringBuilder(); + StringBuilder username = new StringBuilder(); - username.append(authUser); - if (aaiAuth.authBasic(username.toString(), authFunction) == false) { - return "AAI_9101"; + username.append(authUser); + if (aaiAuth.authBasic(username.toString(), authFunction) == false) { + return "AAI_9101"; + } + return "OK"; } - return "OK"; - } - public boolean authCookie(Cookie cookie, String authFunction, StringBuilder username) { + public boolean authCookie(Cookie cookie, String authFunction, StringBuilder username) { - if (cookie == null) { - return false; + if (cookie == null) { + return false; + } + return SearchDbServiceAuthCore.authorize(username.toString(), authFunction); } - return SearchDbServiceAuthCore.authorize(username.toString(), authFunction); - } } 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 1bd922f..48743b6 100644 --- a/src/main/java/org/onap/aai/sa/auth/SearchDbServiceAuthCore.java +++ b/src/main/java/org/onap/aai/sa/auth/SearchDbServiceAuthCore.java @@ -40,207 +40,206 @@ import org.onap.aai.sa.searchdbabstraction.util.SearchDbConstants; public class SearchDbServiceAuthCore { - private static Logger logger = LoggerFactory.getInstance() - .getLogger(SearchDbServiceAuthCore.class.getName()); + private static Logger logger = LoggerFactory.getInstance().getLogger(SearchDbServiceAuthCore.class.getName()); - private static String GlobalAuthFileName = SearchDbConstants.SDB_AUTH_CONFIG_FILENAME; + private static String GlobalAuthFileName = SearchDbConstants.SDB_AUTH_CONFIG_FILENAME; - private static enum HTTP_METHODS { - POST, GET, PUT, DELETE - } - - ; - - // Don't instantiate - private SearchDbServiceAuthCore() { - } + private enum HTTP_METHODS { + POST, + GET, + PUT, + DELETE + } - private static boolean usersInitialized = false; - private static HashMap<String, SearchDbAuthUser> users; - private static boolean timerSet = false; - private static Timer timer = null; + // Don't instantiate + private SearchDbServiceAuthCore() {} - public synchronized static void init() { + 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(); - SearchDbServiceAuthCore.reloadUsers(); - } + SearchDbServiceAuthCore.getConfigFile(); + 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; + public static void cleanup() { + timer.cancel(); } - return GlobalAuthFileName; - } - - public synchronized static void reloadUsers() { - users = new HashMap<String, SearchDbAuthUser>(); - ObjectMapper mapper = new ObjectMapper(); // can reuse, share globally - JSONParser parser = new JSONParser(); - try { - Object obj = parser.parse(new FileReader(GlobalAuthFileName)); - JsonNode rootNode = mapper.readTree(new File(GlobalAuthFileName)); - JsonNode rolesNode = rootNode.path("roles"); - - for (JsonNode roleNode : rolesNode) { - String roleName = roleNode.path("name").asText(); - - TabularAuthRole authRole = new TabularAuthRole(); - JsonNode usersNode = roleNode.path("users"); - JsonNode functionsNode = roleNode.path("functions"); - for (JsonNode functionNode : functionsNode) { - String function = functionNode.path("name").asText(); - JsonNode methodsNode = functionNode.path("methods"); - boolean hasMethods = false; - for (JsonNode methodNode : methodsNode) { - String methodName = methodNode.path("name").asText(); - hasMethods = true; - String thisFunction = methodName + ":" + function; - - authRole.addAllowedFunction(thisFunction); - } - - if (hasMethods == false) { - // iterate the list from HTTP_METHODS - for (HTTP_METHODS meth : HTTP_METHODS.values()) { - String thisFunction = meth.toString() + ":" + function; - - authRole.addAllowedFunction(thisFunction); - } - } + public static String getConfigFile() { + if (GlobalAuthFileName == null) { + String nc = GlobalAuthFileName; + if (nc == null) { + nc = "/home/aaiadmin/etc/aaipolicy.json"; + } + GlobalAuthFileName = nc; } - for (JsonNode userNode : usersNode) { - // make the user lower case - String username = userNode.path("username").asText().toLowerCase(); - SearchDbAuthUser authUser = null; - if (users.containsKey(username)) { - authUser = users.get(username); - } else { - authUser = new SearchDbAuthUser(); - } - - - authUser.setUser(username); - authUser.addRole(roleName, authRole); - users.put(username, authUser); - } - } - } catch (FileNotFoundException fnfe) { - logger.debug("Failed to load the policy file "); + return GlobalAuthFileName; + } - } catch (ParseException e) { - logger.debug("Failed to Parse the policy file "); + public synchronized static 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)); + JsonNode rolesNode = rootNode.path("roles"); + + for (JsonNode roleNode : rolesNode) { + String roleName = roleNode.path("name").asText(); + + TabularAuthRole authRole = new TabularAuthRole(); + JsonNode usersNode = roleNode.path("users"); + JsonNode functionsNode = roleNode.path("functions"); + for (JsonNode functionNode : functionsNode) { + String function = functionNode.path("name").asText(); + JsonNode methodsNode = functionNode.path("methods"); + boolean hasMethods = false; + for (JsonNode methodNode : methodsNode) { + String methodName = methodNode.path("name").asText(); + hasMethods = true; + String thisFunction = methodName + ":" + function; + + authRole.addAllowedFunction(thisFunction); + } + + if (hasMethods == false) { + // 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)) { + authUser = users.get(username); + } else { + authUser = new SearchDbAuthUser(); + } + + + authUser.setUser(username); + authUser.addRole(roleName, authRole); + users.put(username, authUser); + } + } + } catch (FileNotFoundException fnfe) { + logger.debug("Failed to load the policy file "); - } catch (JsonProcessingException e) { - logger.debug("JSON processing error while parsing policy file: " + e.getMessage()); + } catch (ParseException e) { + logger.debug("Failed to Parse the policy file "); - } catch (IOException e) { - logger.debug("IO Exception while parsing policy file: " + e.getMessage()); - } + } catch (JsonProcessingException e) { + logger.debug("JSON processing error while parsing policy file: " + e.getMessage()); - usersInitialized = true; + } catch (IOException e) { + logger.debug("IO Exception while parsing policy file: " + e.getMessage()); + } - } + usersInitialized = true; - public static class SearchDbAuthUser { - public SearchDbAuthUser() { - this.roles = new HashMap<String, TabularAuthRole>(); } - private String username; - private HashMap<String, TabularAuthRole> roles; + public static class SearchDbAuthUser { + public SearchDbAuthUser() { + this.roles = new HashMap<>(); + } - public String getUser() { - return this.username; - } + private String username; + private HashMap<String, TabularAuthRole> roles; - public HashMap<String, TabularAuthRole> getRoles() { - return this.roles; - } + public String getUser() { + return this.username; + } - public void addRole(String roleName, TabularAuthRole authRole) { - this.roles.put(roleName, authRole); - } + public HashMap<String, TabularAuthRole> getRoles() { + return this.roles; + } - public boolean checkAllowed(String checkFunc) { - for (Map.Entry<String, TabularAuthRole> roleEntry : this.roles.entrySet()) { - TabularAuthRole role = roleEntry.getValue(); - if (role.hasAllowedFunction(checkFunc)) { - // break out as soon as we find it - return true; + public void addRole(String roleName, TabularAuthRole authRole) { + this.roles.put(roleName, authRole); } - } - // we would have got positive confirmation had it been there - return false; - } - public void setUser(String myuser) { - this.username = myuser; - } + public boolean checkAllowed(String checkFunc) { + for (Map.Entry<String, TabularAuthRole> roleEntry : this.roles.entrySet()) { + TabularAuthRole role = roleEntry.getValue(); + if (role.hasAllowedFunction(checkFunc)) { + // break out as soon as we find it + return true; + } + } + // we would have got positive confirmation had it been there + return false; + } - } + public void setUser(String myuser) { + this.username = myuser; + } - public static class TabularAuthRole { - public TabularAuthRole() { - this.allowedFunctions = new ArrayList<String>(); } - private List<String> allowedFunctions; + public static class TabularAuthRole { + public TabularAuthRole() { + this.allowedFunctions = new ArrayList<>(); + } - public void addAllowedFunction(String func) { - this.allowedFunctions.add(func); - } + private List<String> allowedFunctions; - public void delAllowedFunction(String delFunc) { - if (this.allowedFunctions.contains(delFunc)) { - this.allowedFunctions.remove(delFunc); - } - } + public void addAllowedFunction(String func) { + this.allowedFunctions.add(func); + } + + public void delAllowedFunction(String delFunc) { + if (this.allowedFunctions.contains(delFunc)) { + this.allowedFunctions.remove(delFunc); + } + } - public boolean hasAllowedFunction(String afunc) { - if (this.allowedFunctions.contains(afunc)) { - return true; - } else { - return false; - } + public boolean hasAllowedFunction(String afunc) { + if (this.allowedFunctions.contains(afunc)) { + return true; + } else { + return false; + } + } } - } - public static HashMap<String, SearchDbAuthUser> getUsers(String key) { - if (!usersInitialized || (users == null)) { - reloadUsers(); + public static HashMap<String, SearchDbAuthUser> getUsers(String key) { + if (!usersInitialized || (users == null)) { + reloadUsers(); + } + return users; } - return users; - } - public static boolean authorize(String username, String authFunction) { + public static boolean authorize(String username, String authFunction) { - if (!usersInitialized || (users == null)) { - init(); - } - if (users.containsKey(username)) { - if (users.get(username).checkAllowed(authFunction) == true) { + if (!usersInitialized || (users == null)) { + init(); + } + if (users.containsKey(username)) { + if (users.get(username).checkAllowed(authFunction) == true) { - return true; - } else { + return true; + } else { - return false; - } - } else { + return false; + } + } else { - return false; + return false; + } } - } } diff --git a/src/main/java/org/onap/aai/sa/rest/AnalysisConfiguration.java b/src/main/java/org/onap/aai/sa/rest/AnalysisConfiguration.java index f30075a..0b8947e 100644 --- a/src/main/java/org/onap/aai/sa/rest/AnalysisConfiguration.java +++ b/src/main/java/org/onap/aai/sa/rest/AnalysisConfiguration.java @@ -30,207 +30,200 @@ import org.onap.aai.sa.searchdbabstraction.logging.SearchDbMsgs; import org.onap.aai.sa.searchdbabstraction.util.SearchDbConstants; /** - * This class encapsulates the configuration of the predefined - * Analyzer and Filter behaviours that help to tell the document - * store how to index the documents that are provided to it. + * This class encapsulates the configuration of the predefined Analyzer and Filter behaviours that help to tell the + * document store how to index the documents that are provided to it. */ public class AnalysisConfiguration { - /** - * Contains all of the predefined indexing filters. - */ - private FilterSchema[] customFilters; - - /** - * Contains all of the predefined indexing analyzers. - */ - private AnalyzerSchema[] customAnalysers; - - /** - * Indicates whether or not we have imported the filter and - * analyzer configurations. - */ - private AtomicBoolean configured = new AtomicBoolean(false); - - /** - * A json format string which is readable by Elastic Search and defines - * all of the custom filters and analyzers that we need Elastic Search - * to know about. - */ - private String esSettings = null; - - private static Logger logger = LoggerFactory.getInstance() - .getLogger(AnalysisConfiguration.class.getName()); - - - /** - * Imports the filter and analyzer configuration files and - * builds an Elastic Search readable settings file from the - * contents. - * - * @param filterConfigFile - Location of filter configuration json file - * @param analyzerConfigFile - Location of analyzer configuration json file - */ - public void init(String filterConfigFile, String analyzerConfigFile) { - - if (configured.compareAndSet(false, true)) { - ObjectMapper mapper = new ObjectMapper(); - - File filtersConfig = new File(filterConfigFile); - try { - customFilters = mapper.readValue(filtersConfig, FilterSchema[].class); - } catch (IOException e) { - - // generate log - logger.warn(SearchDbMsgs.FILTERS_CONFIG_FAILURE, filterConfigFile, e.getMessage()); - } - - File analysersConfig = new File(analyzerConfigFile); - try { - customAnalysers = mapper.readValue(analysersConfig, AnalyzerSchema[].class); - } catch (IOException e) { - - // generate log - logger.warn(SearchDbMsgs.ANALYSYS_CONFIG_FAILURE, analyzerConfigFile, e.getMessage()); - } - - esSettings = buildEsIndexSettings(); + /** + * Contains all of the predefined indexing filters. + */ + private FilterSchema[] customFilters; + + /** + * Contains all of the predefined indexing analyzers. + */ + private AnalyzerSchema[] customAnalysers; + + /** + * Indicates whether or not we have imported the filter and analyzer configurations. + */ + private AtomicBoolean configured = new AtomicBoolean(false); + + /** + * A json format string which is readable by Elastic Search and defines all of the custom filters and analyzers that + * we need Elastic Search to know about. + */ + private String esSettings = null; + + private static Logger logger = LoggerFactory.getInstance().getLogger(AnalysisConfiguration.class.getName()); + + + /** + * Imports the filter and analyzer configuration files and builds an Elastic Search readable settings file from the + * contents. + * + * @param filterConfigFile - Location of filter configuration json file + * @param analyzerConfigFile - Location of analyzer configuration json file + */ + public void init(String filterConfigFile, String analyzerConfigFile) { + + if (configured.compareAndSet(false, true)) { + ObjectMapper mapper = new ObjectMapper(); + + File filtersConfig = new File(filterConfigFile); + try { + customFilters = mapper.readValue(filtersConfig, FilterSchema[].class); + } catch (IOException e) { + + // generate log + logger.warn(SearchDbMsgs.FILTERS_CONFIG_FAILURE, filterConfigFile, e.getMessage()); + } + + File analysersConfig = new File(analyzerConfigFile); + try { + customAnalysers = mapper.readValue(analysersConfig, AnalyzerSchema[].class); + } catch (IOException e) { + + // generate log + logger.warn(SearchDbMsgs.ANALYSYS_CONFIG_FAILURE, analyzerConfigFile, e.getMessage()); + } + + esSettings = buildEsIndexSettings(); + } } - } - - - /** - * Returns the set of pre-configured filters. - * - * @return - An array of filters. - */ - public FilterSchema[] getFilters() { - return customFilters; - } - - - /** - * Returns the set of pre-configured analyzers. - * - * @return - An array of analyzers. - */ - public AnalyzerSchema[] getAnalyzers() { - init(SearchDbConstants.SDB_FILTER_CONFIG_FILE, SearchDbConstants.SDB_ANALYSIS_CONFIG_FILE); - return customAnalysers; - } - - - /** - * Imports the filter and analyzer configurations and translates those - * into a settings string that will be parseable by Elastic Search. - * - * @return - Elastic Search formatted settings string. - */ - public String getEsIndexSettings() { - - // Generate the es-settings string from our filter and analyzer - // configurations if we have not already done so. - init(SearchDbConstants.SDB_FILTER_CONFIG_FILE, SearchDbConstants.SDB_ANALYSIS_CONFIG_FILE); - - // Now, return the es-settings string. - return esSettings; - } - - - /** - * Constructs a settings string that is readable by Elastic Search based - * on the contents of the filter and analyzer configuration files. - * - * @return Elastic Search formatted settings string. - */ - public String buildEsIndexSettings() { - - StringBuilder sb = new StringBuilder(); - - sb.append("{"); - sb.append("\"analysis\": {"); - - // Define the custom filters. - boolean atLeastOneFilter = false; - sb.append("\"filter\": {"); - AtomicBoolean firstFilter = new AtomicBoolean(true); - for (FilterSchema filter : customFilters) { - - // Append a comma before the next entry, unless it is the - // first one. - if (!firstFilter.compareAndSet(true, false)) { - sb.append(", "); - } - - // Now, build the filter entry. - buildFilterEntry(filter, sb); - atLeastOneFilter = true; + + + /** + * Returns the set of pre-configured filters. + * + * @return - An array of filters. + */ + public FilterSchema[] getFilters() { + return customFilters; + } + + + /** + * Returns the set of pre-configured analyzers. + * + * @return - An array of analyzers. + */ + public AnalyzerSchema[] getAnalyzers() { + init(SearchDbConstants.SDB_FILTER_CONFIG_FILE, SearchDbConstants.SDB_ANALYSIS_CONFIG_FILE); + return customAnalysers; } - sb.append((atLeastOneFilter) ? "}," : "}"); - // Define the custom analyzers. - sb.append("\"analyzer\": {"); - AtomicBoolean firstAnalyzer = new AtomicBoolean(true); - for (AnalyzerSchema analyzer : customAnalysers) { - // Prepend a comma before the entry, unless it is the - // first one. - if (!firstAnalyzer.compareAndSet(true, false)) { - sb.append(","); - } + /** + * Imports the filter and analyzer configurations and translates those into a settings string that will be parseable + * by Elastic Search. + * + * @return - Elastic Search formatted settings string. + */ + public String getEsIndexSettings() { + + // Generate the es-settings string from our filter and analyzer + // configurations if we have not already done so. + init(SearchDbConstants.SDB_FILTER_CONFIG_FILE, SearchDbConstants.SDB_ANALYSIS_CONFIG_FILE); + + // Now, return the es-settings string. + return esSettings; + } + - // Now, construct the entry for this analyzer. - buildAnalyzerEntry(analyzer, sb); + /** + * Constructs a settings string that is readable by Elastic Search based on the contents of the filter and analyzer + * configuration files. + * + * @return Elastic Search formatted settings string. + */ + public String buildEsIndexSettings() { + + StringBuilder sb = new StringBuilder(); + + sb.append("{"); + sb.append("\"analysis\": {"); + + // Define the custom filters. + boolean atLeastOneFilter = false; + sb.append("\"filter\": {"); + AtomicBoolean firstFilter = new AtomicBoolean(true); + for (FilterSchema filter : customFilters) { + + // Append a comma before the next entry, unless it is the + // first one. + if (!firstFilter.compareAndSet(true, false)) { + sb.append(", "); + } + + // Now, build the filter entry. + buildFilterEntry(filter, sb); + atLeastOneFilter = true; + } + sb.append((atLeastOneFilter) ? "}," : "}"); + + // Define the custom analyzers. + sb.append("\"analyzer\": {"); + AtomicBoolean firstAnalyzer = new AtomicBoolean(true); + for (AnalyzerSchema analyzer : customAnalysers) { + + // Prepend a comma before the entry, unless it is the + // first one. + if (!firstAnalyzer.compareAndSet(true, false)) { + sb.append(","); + } + + // Now, construct the entry for this analyzer. + buildAnalyzerEntry(analyzer, sb); + } + sb.append("}"); + + sb.append("}"); + sb.append("}"); + + return sb.toString(); } - sb.append("}"); - - sb.append("}"); - sb.append("}"); - - return sb.toString(); - } - - - /** - * Constructs an ElasticSearch friendly custom filter definition. - * - * @param filter - The filter to generate ElasticSearch json for. - * @param sb - The string builder to append the filter definition - * to. - */ - private void buildFilterEntry(FilterSchema filter, StringBuilder sb) { - - sb.append("\"" + filter.getName()).append("\": {"); - - sb.append(filter.getConfiguration()); - - sb.append("}"); - } - - - /** - * Constructs an ElasticSearch friendly custom analyzer definition. - * - * @param analyzer - The analyzer to generate ElasticSearch json for. - * @param sb - The string builder to append the analyzer definition - * to. - */ - private void buildAnalyzerEntry(AnalyzerSchema analyzer, StringBuilder sb) { - - sb.append("\"").append(analyzer.getName()).append("\": {"); - sb.append("\"type\": \"custom\","); - sb.append("\"tokenizer\": ").append("\"").append(analyzer.getTokenizer()).append("\","); - sb.append("\"filter\": ["); - boolean firstFilter = true; - for (String filter : analyzer.getFilters()) { - if (!firstFilter) { - sb.append(","); - } else { - firstFilter = false; - } - sb.append("\"").append(filter).append("\""); + + + /** + * Constructs an ElasticSearch friendly custom filter definition. + * + * @param filter - The filter to generate ElasticSearch json for. + * @param sb - The string builder to append the filter definition to. + */ + private void buildFilterEntry(FilterSchema filter, StringBuilder sb) { + + sb.append("\"" + filter.getName()).append("\": {"); + + sb.append(filter.getConfiguration()); + + sb.append("}"); + } + + + /** + * Constructs an ElasticSearch friendly custom analyzer definition. + * + * @param analyzer - The analyzer to generate ElasticSearch json for. + * @param sb - The string builder to append the analyzer definition to. + */ + private void buildAnalyzerEntry(AnalyzerSchema analyzer, StringBuilder sb) { + + sb.append("\"").append(analyzer.getName()).append("\": {"); + sb.append("\"type\": \"custom\","); + sb.append("\"tokenizer\": ").append("\"").append(analyzer.getTokenizer()).append("\","); + sb.append("\"filter\": ["); + boolean firstFilter = true; + for (String filter : analyzer.getFilters()) { + if (!firstFilter) { + sb.append(","); + } else { + firstFilter = false; + } + sb.append("\"").append(filter).append("\""); + } + sb.append("]"); + sb.append("}"); } - sb.append("]"); - sb.append("}"); - } } 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 210953d..59b526f 100644 --- a/src/main/java/org/onap/aai/sa/rest/AnalyzerApi.java +++ b/src/main/java/org/onap/aai/sa/rest/AnalyzerApi.java @@ -46,121 +46,116 @@ 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()); - private static Logger auditLogger = LoggerFactory.getInstance() - .getAuditLogger(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) { + @RequestMapping(method = RequestMethod.GET, consumes = {"application/json"}, produces = {"application/json"}) + public ResponseEntity<String> processGet(HttpServletRequest request, @RequestHeader HttpHeaders headers, + ApiUtils apiUtils) { - HttpStatus responseCode = HttpStatus.INTERNAL_SERVER_ERROR; - String responseString = "Undefined error"; + HttpStatus responseCode = HttpStatus.INTERNAL_SERVER_ERROR; + String responseString = "Undefined error"; - // 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."); - return ResponseEntity.status(HttpStatus.FORBIDDEN).contentType ( MediaType.APPLICATION_JSON ).body("Authentication failure."); - } + if (!searchService.validateRequest(headers, request, ApiUtils.Action.GET, + ApiUtils.SEARCH_AUTH_POLICY_NAME)) { + 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()); - return ResponseEntity.status(HttpStatus.FORBIDDEN).contentType ( MediaType.APPLICATION_JSON ).body("Authentication failure."); - } + 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 { - responseString = buildAnalyzerList(ElasticSearchHttpController.getInstance() - .getAnalysisConfig()); - responseCode = HttpStatus.OK; + // 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(); + } - } catch (Exception e) { + // Build the HTTP response. + ResponseEntity response = + ResponseEntity.status(responseCode).contentType(MediaType.APPLICATION_JSON).body(responseString); - logger.warn(SearchDbMsgs.GET_ANALYZERS_FAILURE, - "Unexpected failure retrieving analysis configuration - cause: " + e.getMessage()); - responseString = "Failed to retrieve analysis configuration. Cause: " + e.getMessage(); + // 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(); + + return response; } - // Build the HTTP response. - ResponseEntity response = ResponseEntity.status(responseCode).contentType ( MediaType.APPLICATION_JSON ).body(responseString); - - // 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(); - - 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(", "); + + /** + * 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("}"); } - sb.append("\"").append(behaviour).append("\""); - } - sb.append("]"); - sb.append("}"); - } - sb.append("}"); + sb.append("}"); - return sb.toString(); - } + 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 a2ef2b1..bbbc02b 100644 --- a/src/main/java/org/onap/aai/sa/rest/ApiUtils.java +++ b/src/main/java/org/onap/aai/sa/rest/ApiUtils.java @@ -32,167 +32,150 @@ import org.springframework.http.HttpStatus; public class ApiUtils { - public static final String SEARCH_AUTH_POLICY_NAME = "search"; - public static final String URL_PREFIX = "services/search-data-service/v1/search"; - - public enum Action { - POST, GET, PUT, DELETE - }; - - /** - * This method uses the contents of the supplied HTTP headers and request - * structures to populate the MDC Context used for logging purposes. - * - * @param httpReq - HTTP request structure. - * @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) { -// // transId = headers.getRequestHeaders().getFirst("X-TransactionId"); -// transId = headers.getFirst("X-TransactionId"); -// -// if ((transId == null) || (transId.equals(""))) { -// transId = UUID.randomUUID().toString(); -// } -// } -// -// String fromIp = (httpReq != null) ? httpReq.getRemoteAddr() : ""; -// String fromApp = (headers != null) ? headers.getFirst("X-FromAppId") : ""; -// -// MdcContext.initialize(transId, SearchDbConstants.SDB_SERVICE_NAME, "", fromApp, fromIp); -// } - - protected static void initMdcContext ( HttpServletRequest httpReq, HttpHeaders headers) { - - // Auto generate a transaction if we were not provided one. - String transId = null; - if (headers != null) { - // transId = headers.getRequestHeaders().getFirst("X-TransactionId"); - transId = headers.getFirst("X-TransactionId"); - - if ((transId == null) || (transId.equals(""))) { - transId = UUID.randomUUID().toString(); - } - } + public static final String SEARCH_AUTH_POLICY_NAME = "search"; + public static final String URL_PREFIX = "services/search-data-service/v1/search"; + + public enum Action { + POST, + GET, + PUT, + DELETE + }; + + /** + * This method uses the contents of the supplied HTTP headers and request structures to populate the MDC Context + * used for logging purposes. + * + * @param httpReq - HTTP request structure. + * @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) { + transId = headers.getFirst("X-TransactionId"); + + if ((transId == null) || (transId.equals(""))) { + transId = UUID.randomUUID().toString(); + } + } - String fromIp = (httpReq != null) ? httpReq.getRemoteHost () : ""; - String fromApp = (headers != null) ? headers.getFirst("X-FromAppId") : ""; + String fromIp = (httpReq != null) ? httpReq.getRemoteHost() : ""; + String fromApp = (headers != null) ? headers.getFirst("X-FromAppId") : ""; - MdcContext.initialize(transId, SearchDbConstants.SDB_SERVICE_NAME, "", fromApp, fromIp); - } + MdcContext.initialize(transId, SearchDbConstants.SDB_SERVICE_NAME, "", fromApp, fromIp); + } - protected static void clearMdcContext() { - MDC.clear(); - } + protected static void clearMdcContext() { + MDC.clear(); + } - public static String buildIndexUri(String index) { + public static String buildIndexUri(String index) { - return (URL_PREFIX + "/indexes/") + index; - } + return (URL_PREFIX + "/indexes/") + index; + } - public static String buildDocumentUri(String index, String documentId) { + public static String buildDocumentUri(String index, String documentId) { - return buildIndexUri(index) + "/documents/" + documentId; - } + return buildIndexUri(index) + "/documents/" + documentId; + } - public static boolean validateIndexUri(String uri) { + public static boolean validateIndexUri(String uri) { - // If the URI starts with a leading '/' character, remove it. - uri = uri.startsWith("/") ? uri.substring(1) : 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("/"); + // Now, tokenize the URI string. + String[] tokens = uri.split("/"); - return (tokens.length == 6) && (tokens[4].equals("indexes")); + return (tokens.length == 6) && (tokens[4].equals("indexes")); - } + } - public static boolean validateDocumentUri(String uri, boolean requireId) { + 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; + // 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("/"); + // Now, tokenize the URI string. + String[] tokens = uri.split("/"); - if (requireId) { - return (tokens.length == 8) && (tokens[4].equals("indexes") - && (tokens[6].equals("documents"))); - } else { - return ((tokens.length == 8) || (tokens.length == 7)) - && (tokens[4].equals("indexes") && (tokens[6].equals("documents"))); + if (requireId) { + return (tokens.length == 8) && (tokens[4].equals("indexes") && (tokens[6].equals("documents"))); + } else { + return ((tokens.length == 8) || (tokens.length == 7)) + && (tokens[4].equals("indexes") && (tokens[6].equals("documents"))); + } } - } - public static String extractIndexFromUri(String uri) { + public static String extractIndexFromUri(String uri) { - // If the URI starts with a leading '/' character, remove it. - uri = uri.startsWith("/") ? uri.substring(1) : 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("/"); + // 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]; + int i = 0; + for (String token : tokens) { + if (token.equals("indexes")) { + if (i + 1 < tokens.length) { + return tokens[i + 1]; + } + } + i++; } - } - i++; - } - return null; - } + return null; + } - public static String extractIdFromUri(String uri) { + public static String extractIdFromUri(String uri) { - // If the URI starts with a leading '/' character, remove it. - uri = uri.startsWith("/") ? uri.substring(1) : 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("/"); + // 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]; + int i = 0; + for (String token : tokens) { + if (token.equals("documents")) { + if (i + 1 < tokens.length) { + return tokens[i + 1]; + } + } + i++; } - } - i++; - } - return null; - } - - 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 ); - } catch (IllegalArgumentException e) {} - - - if (status == null) { - switch (httpStatusCode) { - case 207: - statusString = "Multi Status"; - break; - default: - } - } else { - statusString = status.getReasonPhrase (); + return null; } - return statusString; - } + 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); + } catch (IllegalArgumentException e) { + } + + + if (status == null) { + switch (httpStatusCode) { + case 207: + statusString = "Multi Status"; + break; + default: + } + } 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 0770bf1..bf8f187 100644 --- a/src/main/java/org/onap/aai/sa/rest/BulkApi.java +++ b/src/main/java/org/onap/aai/sa/rest/BulkApi.java @@ -41,212 +41,196 @@ import org.springframework.http.ResponseEntity; /** - * This class encapsulates the REST end points associated with performing - * bulk operations against the document store. + * This class encapsulates the REST end points associated with performing bulk operations against the document store. */ public class BulkApi { - /** - * Indicates whether or not we have performed the one-time static - * initialization required for performing schema validation. - */ - protected static AtomicBoolean validationInitialized = new AtomicBoolean(false); - - /** - * Factory used for importing our payload schema for validation purposes. - */ - protected static JsonSchemaFactory schemaFactory = null; - - /** - * Imported payload schema that will be used by our validation methods. - */ - protected static JsonSchema schema = null; - - protected SearchServiceApi searchService = null; - - // Instantiate the loggers. - private static Logger logger = LoggerFactory.getInstance().getLogger(BulkApi.class.getName()); - private static Logger auditLogger = LoggerFactory.getInstance() - .getAuditLogger(BulkApi.class.getName()); - - - /** - * Create a new instance of the BulkApi end point. - */ - public BulkApi(SearchServiceApi searchService) { - this.searchService = searchService; - } - - - /** - * Processes client requests containing a set of operations to be - * performed in bulk. - * - * <p>Method: POST - * - * @param operations - JSON structure enumerating the operations to be - * performed. - * @param request - Raw HTTP request. - * @param headers - HTTP headers. - * @return - A standard REST response structure. - */ - public ResponseEntity<String> processPost(String operations, - HttpServletRequest request, - HttpHeaders headers, - DocumentStoreInterface documentStore, - ApiUtils apiUtils) { - - - // 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"; - - if (logger.isDebugEnabled()) { - logger.debug("SEARCH: Process Bulk Request - operations = [" - + operations.replaceAll("\n", "") + " ]"); - } + /** + * Indicates whether or not we have performed the one-time static initialization required for performing schema + * validation. + */ + protected static AtomicBoolean validationInitialized = new AtomicBoolean(false); - try { + /** + * Factory used for importing our payload schema for validation purposes. + */ + protected static JsonSchemaFactory schemaFactory = null; - // 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."); + /** + * Imported payload schema that will be used by our validation methods. + */ + protected static JsonSchema schema = null; - return buildResponse(HttpStatus.FORBIDDEN.value (), - "Authentication failure.", request, apiUtils); - } + protected SearchServiceApi searchService = null; - } catch (Exception e) { + // Instantiate the loggers. + private static Logger logger = LoggerFactory.getInstance().getLogger(BulkApi.class.getName()); + private static Logger auditLogger = LoggerFactory.getInstance().getAuditLogger(BulkApi.class.getName()); - // This is a catch all for any unexpected failure trying to perform - // the authentication. - logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE, - "Unexpected authentication failure - cause: " + e.getMessage()); - if (logger.isDebugEnabled()) { - logger.debug("Stack Trace:\n" + e.getStackTrace()); - } - return buildResponse(HttpStatus.FORBIDDEN.value (), - "Authentication failure - cause " + e.getMessage(), - request, - apiUtils); + /** + * Create a new instance of the BulkApi end point. + */ + public BulkApi(SearchServiceApi searchService) { + this.searchService = searchService; } - // 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); - } - - - // 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) { + /** + * Processes client requests containing a set of operations to be performed in bulk. + * + * <p> + * Method: POST + * + * @param operations - JSON structure enumerating the operations to be performed. + * @param request - Raw HTTP request. + * @param headers - HTTP headers. + * @return - A standard REST response structure. + */ + public ResponseEntity<String> processPost(String operations, HttpServletRequest request, HttpHeaders headers, + DocumentStoreInterface documentStore, ApiUtils apiUtils) { + + + // 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"; + + 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); + } + + } catch (Exception e) { + + // This is a catch all for any unexpected failure trying to perform + // the authentication. + logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE, + "Unexpected authentication failure - cause: " + e.getMessage()); + if (logger.isDebugEnabled()) { + logger.debug("Stack Trace:\n" + e.getStackTrace()); + } + + return buildResponse(HttpStatus.FORBIDDEN.value(), "Authentication failure - cause " + e.getMessage(), + request, apiUtils); + } + + // 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); + } + + + // 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); + } + + // Verify that our parsed operations list actually contains some valid + // operations. + if (requests.length == 0) { + logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE, "Empty operations list in bulk request"); + + + // 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); + } + try { + + // Now, forward the set of bulk operations to the DAO for processing. + OperationResult result = documentStore.performBulkOperations(requests); + + // Populate the result code and entity string for our HTTP response. + resultCode = result.getResultCode(); + resultString = (result.getFailureCause() == null) ? result.getResult() : result.getFailureCause(); + + } catch (DocumentStoreOperationException e) { + + logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE, + "Unexpected failure communicating with document store: " + e.getMessage()); + if (logger.isDebugEnabled()) { + logger.debug("Stack Trace:\n" + e.getStackTrace()); + } + + // Populate the result code and entity string for our HTTP response. + resultCode = HttpStatus.INTERNAL_SERVER_ERROR.value(); + resultString = "Unexpected failure processing bulk operations: " + e.getMessage(); + } - 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); + // Build our HTTP response. + ResponseEntity 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()); + } + + // Finally, return the HTTP response to the client. + return buildResponse(resultCode, resultString, request, apiUtils); } - // Verify that our parsed operations list actually contains some valid - // operations. - if (requests.length == 0) { - logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE, "Empty operations list in bulk request"); - - // 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); + /** + * This method generates an audit log and returns an HTTP response object. + * + * @param resultCode - The result code to report. + * @param resultString - The result string to report. + * @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) { + + ResponseEntity<String> response = + ResponseEntity.status(resultCode).contentType(MediaType.APPLICATION_JSON).body(resultString); + + // Generate our audit log. + 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.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(); + + return response; } - try { - - // Now, forward the set of bulk operations to the DAO for processing. - OperationResult result = documentStore.performBulkOperations(requests); - - // Populate the result code and entity string for our HTTP response. - resultCode = result.getResultCode(); - resultString = (result.getFailureCause() == null) - ? result.getResult() : result.getFailureCause(); - - } catch (DocumentStoreOperationException e) { - - logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE, - "Unexpected failure communicating with document store: " + e.getMessage()); - if (logger.isDebugEnabled()) { - logger.debug("Stack Trace:\n" + e.getStackTrace()); - } - - // Populate the result code and entity string for our HTTP response. - resultCode = HttpStatus.INTERNAL_SERVER_ERROR.value (); - resultString = "Unexpected failure processing bulk operations: " + e.getMessage(); - } - - // Build our HTTP response. - ResponseEntity 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 ()); - } - - // Finally, return the HTTP response to the client. - return buildResponse(resultCode, resultString, request, apiUtils); - } - - - /** - * This method generates an audit log and returns an HTTP response object. - * - * @param resultCode - The result code to report. - * @param resultString - The result string to report. - * @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) { - - ResponseEntity<String> response = ResponseEntity.status(resultCode).contentType ( MediaType.APPLICATION_JSON ) .body(resultString); - - // Generate our audit log. - 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.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(); - - return response; - } } diff --git a/src/main/java/org/onap/aai/sa/rest/BulkMetaData.java b/src/main/java/org/onap/aai/sa/rest/BulkMetaData.java index d2e3f5c..7c096a6 100644 --- a/src/main/java/org/onap/aai/sa/rest/BulkMetaData.java +++ b/src/main/java/org/onap/aai/sa/rest/BulkMetaData.java @@ -22,28 +22,28 @@ package org.onap.aai.sa.rest; public class BulkMetaData { - private String url; - private String etag; + private String url; + private String etag; - public String getUrl() { - return url; - } + public String getUrl() { + return url; + } - public void setUrl(String url) { - this.url = url; - } + public void setUrl(String url) { + this.url = url; + } - public String getEtag() { - return etag; - } + public String getEtag() { + return etag; + } - public void setEtag(String anEtag) { - this.etag = anEtag; - } + public void setEtag(String anEtag) { + this.etag = anEtag; + } - @Override - public String toString() { - return "MetaData: [url=" + url + ", etag=" + etag + "]"; - } + @Override + public String toString() { + return "MetaData: [url=" + url + ", etag=" + etag + "]"; + } } diff --git a/src/main/java/org/onap/aai/sa/rest/BulkOperation.java b/src/main/java/org/onap/aai/sa/rest/BulkOperation.java index 41325e5..1490f97 100644 --- a/src/main/java/org/onap/aai/sa/rest/BulkOperation.java +++ b/src/main/java/org/onap/aai/sa/rest/BulkOperation.java @@ -21,41 +21,39 @@ package org.onap.aai.sa.rest; /** - * This class represents a single instance of an operation to be performed - * as part of a bulk request. + * This class represents a single instance of an operation to be performed as part of a bulk request. */ public class BulkOperation { - /** - * Contains meta data to be passed to the document store for it - * to perform the operation. - */ - private BulkMetaData metaData; + /** + * Contains meta data to be passed to the document store for it to perform the operation. + */ + private BulkMetaData metaData; - /** - * Contains the contents of the document to be acted on. - */ - private Document document; + /** + * Contains the contents of the document to be acted on. + */ + private Document document; - public void setMetaData(BulkMetaData metaData) { - this.metaData = metaData; - } + public void setMetaData(BulkMetaData metaData) { + this.metaData = metaData; + } - public BulkMetaData getMetaData() { - return metaData; - } + public BulkMetaData getMetaData() { + return metaData; + } - public Document getDocument() { - return document; - } + public Document getDocument() { + return document; + } - public void setDocument(Document document) { - this.document = document; - } + public void setDocument(Document document) { + this.document = document; + } - @Override - public String toString() { - return "Operation: [" + metaData.toString() + ", " + document + "]"; - } + @Override + public String toString() { + return "Operation: [" + metaData.toString() + ", " + document + "]"; + } } diff --git a/src/main/java/org/onap/aai/sa/rest/BulkRequest.java b/src/main/java/org/onap/aai/sa/rest/BulkRequest.java index e86d7bd..1f8b50e 100644 --- a/src/main/java/org/onap/aai/sa/rest/BulkRequest.java +++ b/src/main/java/org/onap/aai/sa/rest/BulkRequest.java @@ -22,90 +22,89 @@ package org.onap.aai.sa.rest; /** - * This class represents a single instance of a request from the search client - * that would be part of a bundle of such operations sent in a single bulk - * request. + * This class represents a single instance of a request from the search client that would be part of a bundle of such + * operations sent in a single bulk request. */ public class BulkRequest { - public enum OperationType { - CREATE, - UPDATE, - DELETE - } - - private BulkOperation create; - private BulkOperation update; - private BulkOperation delete; - - public BulkOperation getCreate() { - return create; - } - - public void setCreate(BulkOperation create) { - this.create = create; - } - - public BulkOperation getUpdate() { - return update; - } - - public void setUpdate(BulkOperation update) { - this.update = update; - } - - public BulkOperation getDelete() { - return delete; - } - - public void setDelete(BulkOperation delete) { - this.delete = delete; - } - - public OperationType getOperationType() { - - if (create != null) { - return OperationType.CREATE; - } else if (update != null) { - return OperationType.UPDATE; - } else if (delete != null) { - return OperationType.DELETE; - } else { - return null; + public enum OperationType { + CREATE, + UPDATE, + DELETE } - } - - public BulkOperation getOperation() { - if (create != null) { - return create; - } else if (update != null) { - return update; - } else if (delete != null) { - return delete; - } else { - return null; + + private BulkOperation create; + private BulkOperation update; + private BulkOperation delete; + + public BulkOperation getCreate() { + return create; + } + + public void setCreate(BulkOperation create) { + this.create = create; + } + + public BulkOperation getUpdate() { + return update; } - } - - public String getIndex() { - return ApiUtils.extractIndexFromUri(getOperation().getMetaData().getUrl()); - } - - public String getId() { - return ApiUtils.extractIdFromUri(getOperation().getMetaData().getUrl()); - } - - @Override - public String toString() { - - if (create != null) { - return "create: [" + create.toString() + "]\n"; - } else if (update != null) { - return "update: [" + update.toString() + "]\n"; - } else if (delete != null) { - return "delete: [" + delete.toString() + "]\n"; - } else { - return "UNDEFINED"; + + public void setUpdate(BulkOperation update) { + this.update = update; + } + + public BulkOperation getDelete() { + return delete; + } + + public void setDelete(BulkOperation delete) { + this.delete = delete; + } + + public OperationType getOperationType() { + + if (create != null) { + return OperationType.CREATE; + } else if (update != null) { + return OperationType.UPDATE; + } else if (delete != null) { + return OperationType.DELETE; + } else { + return null; + } + } + + public BulkOperation getOperation() { + if (create != null) { + return create; + } else if (update != null) { + return update; + } else if (delete != null) { + return delete; + } else { + return null; + } + } + + public String getIndex() { + return ApiUtils.extractIndexFromUri(getOperation().getMetaData().getUrl()); + } + + public String getId() { + return ApiUtils.extractIdFromUri(getOperation().getMetaData().getUrl()); + } + + @Override + public String toString() { + + if (create != null) { + return "create: [" + create.toString() + "]\n"; + } else if (update != null) { + return "update: [" + update.toString() + "]\n"; + } else if (delete != null) { + return "delete: [" + delete.toString() + "]\n"; + } else { + return "UNDEFINED"; + } } - } } diff --git a/src/main/java/org/onap/aai/sa/rest/Document.java b/src/main/java/org/onap/aai/sa/rest/Document.java index 50ef9ea..89ac2e1 100644 --- a/src/main/java/org/onap/aai/sa/rest/Document.java +++ b/src/main/java/org/onap/aai/sa/rest/Document.java @@ -28,33 +28,33 @@ import java.util.HashMap; import java.util.Map; public class Document { - private Map<String, Object> fields = new HashMap<String, Object>(); + private Map<String, Object> fields = new HashMap<String, Object>(); - @JsonAnyGetter - public Map<String, Object> getFields() { - return fields; - } + @JsonAnyGetter + public Map<String, Object> getFields() { + return fields; + } - @JsonAnySetter - public void setField(String name, Object value) { - fields.put(name, value); - } + @JsonAnySetter + public void setField(String name, Object value) { + fields.put(name, value); + } - public String toJson() throws JsonProcessingException { + public String toJson() throws JsonProcessingException { - ObjectMapper mapper = new ObjectMapper(); - return mapper.writeValueAsString(this); - } + ObjectMapper mapper = new ObjectMapper(); + return mapper.writeValueAsString(this); + } - @Override - public String toString() { - String str = "Document: ["; - for (String key : fields.keySet()) { - str += key + ": " + fields.get(key); - } - str += "]"; + @Override + public String toString() { + String str = "Document: ["; + for (String key : fields.keySet()) { + str += key + ": " + fields.get(key); + } + str += "]"; - return str; - } + return str; + } } 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 ca1b351..2d9eb1f 100644 --- a/src/main/java/org/onap/aai/sa/rest/DocumentApi.java +++ b/src/main/java/org/onap/aai/sa/rest/DocumentApi.java @@ -25,11 +25,6 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -//import javax.ws.rs.core.HttpHeaders; -//import javax.ws.rs.core.MediaType; -//import javax.ws.rs.core.Response; -//import javax.ws.rs.core.Response.Status; -// Spring Imports import org.onap.aai.cl.api.LogFields; import org.onap.aai.cl.api.LogLine; import org.onap.aai.cl.api.Logger; @@ -48,587 +43,564 @@ import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; public class DocumentApi { - private static final String REQUEST_HEADER_RESOURCE_VERSION = "If-Match"; - private static final String RESPONSE_HEADER_RESOURCE_VERSION = "ETag"; - private static final String REQUEST_HEADER_ALLOW_IMPLICIT_INDEX_CREATION = "X-CreateIndex"; - - protected SearchServiceApi searchService = null; - - private Logger logger = LoggerFactory.getInstance().getLogger(DocumentApi.class.getName()); - private Logger auditLogger = LoggerFactory.getInstance() - .getAuditLogger(DocumentApi.class.getName()); - - public DocumentApi(SearchServiceApi searchService) { - this.searchService = searchService; - } - - public ResponseEntity<String> processPost(String content, HttpServletRequest request, HttpHeaders headers, - HttpServletResponse httpResponse, String index, - DocumentStoreInterface documentStore) { - - // Initialize the MDC Context for logging purposes. - ApiUtils.initMdcContext(request, headers); - - try { - ObjectMapper mapper = new ObjectMapper(); - mapper.setSerializationInclusion(Include.NON_EMPTY); - if (content == null) { - return handleError(request, content, HttpStatus.BAD_REQUEST); - } - - boolean isValid; - try { - isValid = searchService.validateRequest(headers, request, ApiUtils.Action.POST, - ApiUtils.SEARCH_AUTH_POLICY_NAME); - } catch (Exception e) { - logger.info(SearchDbMsgs.EXCEPTION_DURING_METHOD_CALL, - "DocumentApi.processPost", - e.getMessage()); - return handleError(request, content, HttpStatus.FORBIDDEN); - } - - if (!isValid) { - return handleError(request, content, HttpStatus.FORBIDDEN); - } - - DocumentStoreDataEntityImpl document = new DocumentStoreDataEntityImpl(); - document.setContent(content); - - DocumentOperationResult result = documentStore.createDocument(index, document, implicitlyCreateIndex(headers)); - String output = null; - if (result.getResultCode() >= 200 && result.getResultCode() <= 299) { - output = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(result.getDocument()); - } else { - output = result.getError() != null - ? mapper.writerWithDefaultPrettyPrinter().writeValueAsString(result.getError()) - : result.getFailureCause(); - } - - if (httpResponse != null) { - httpResponse.setHeader(RESPONSE_HEADER_RESOURCE_VERSION, result.getResultVersion()); - } - ResponseEntity response = ResponseEntity.status(result.getResultCode()).contentType ( MediaType.APPLICATION_JSON ).body(output); - logResult(request, HttpStatus.valueOf ( response.getStatusCodeValue () )); - logResult(request, HttpStatus.valueOf ( response.getStatusCodeValue () )); - - // Clear the MDC context so that no other transaction inadvertently - // uses our transaction id. - ApiUtils.clearMdcContext(); - - return response; - } catch (Exception e) { - return handleError(request, e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); + private static final String REQUEST_HEADER_RESOURCE_VERSION = "If-Match"; + private static final String RESPONSE_HEADER_RESOURCE_VERSION = "ETag"; + private static final String REQUEST_HEADER_ALLOW_IMPLICIT_INDEX_CREATION = "X-CreateIndex"; + + protected SearchServiceApi searchService = null; + + private Logger logger = LoggerFactory.getInstance().getLogger(DocumentApi.class.getName()); + private Logger auditLogger = LoggerFactory.getInstance().getAuditLogger(DocumentApi.class.getName()); + + public DocumentApi(SearchServiceApi searchService) { + this.searchService = searchService; } - } - - public ResponseEntity<String> processPut(String content, HttpServletRequest request, HttpHeaders headers, - HttpServletResponse httpResponse, String index, - String id, DocumentStoreInterface documentStore) { - - // Initialize the MDC Context for logging purposes. - ApiUtils.initMdcContext(request, headers); - - try { - ObjectMapper mapper = new ObjectMapper(); - mapper.setSerializationInclusion(Include.NON_EMPTY); - if (content == null) { - return handleError(request, content, HttpStatus.BAD_REQUEST); - } - - boolean isValid; - try { - isValid = searchService.validateRequest(headers, request, ApiUtils.Action.PUT, - ApiUtils.SEARCH_AUTH_POLICY_NAME); - } catch (Exception e) { - logger.info(SearchDbMsgs.EXCEPTION_DURING_METHOD_CALL, - "DocumentApi.processPut", - e.getMessage()); - return handleError(request, content, HttpStatus.FORBIDDEN); - } - - if (!isValid) { - return handleError(request, content, HttpStatus.FORBIDDEN); - } - - String resourceVersion = headers.getFirst(REQUEST_HEADER_RESOURCE_VERSION); - - DocumentStoreDataEntityImpl document = new DocumentStoreDataEntityImpl(); - document.setId(id); - document.setContent(content); - document.setVersion(resourceVersion); - - DocumentOperationResult result = null; - if (resourceVersion == null) { - result = documentStore.createDocument(index, document, implicitlyCreateIndex(headers)); - } else { - result = documentStore.updateDocument(index, document, implicitlyCreateIndex(headers)); - } - - String output = null; - if (result.getResultCode() >= 200 && result.getResultCode() <= 299) { - output = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(result.getDocument()); - } else { - output = result.getError() != null - ? mapper.writerWithDefaultPrettyPrinter().writeValueAsString(result.getError()) - : result.getFailureCause(); - } - if (httpResponse != null) { - httpResponse.setHeader(RESPONSE_HEADER_RESOURCE_VERSION, result.getResultVersion()); - } - ResponseEntity response = ResponseEntity.status(result.getResultCode()).contentType ( MediaType.APPLICATION_JSON ).body(output); - logResult(request, HttpStatus.valueOf ( response.getStatusCodeValue () )); - - // Clear the MDC context so that no other transaction inadvertently - // uses our transaction id. - ApiUtils.clearMdcContext(); - - return response; - } catch (Exception e) { - return handleError(request, e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); + + public ResponseEntity<String> processPost(String content, HttpServletRequest request, HttpHeaders headers, + HttpServletResponse httpResponse, String index, DocumentStoreInterface documentStore) { + + // Initialize the MDC Context for logging purposes. + ApiUtils.initMdcContext(request, headers); + + try { + ObjectMapper mapper = new ObjectMapper(); + mapper.setSerializationInclusion(Include.NON_EMPTY); + if (content == null) { + return handleError(request, content, HttpStatus.BAD_REQUEST); + } + + boolean isValid; + try { + isValid = searchService.validateRequest(headers, request, ApiUtils.Action.POST, + ApiUtils.SEARCH_AUTH_POLICY_NAME); + } catch (Exception e) { + logger.info(SearchDbMsgs.EXCEPTION_DURING_METHOD_CALL, "DocumentApi.processPost", e.getMessage()); + return handleError(request, content, HttpStatus.FORBIDDEN); + } + + if (!isValid) { + return handleError(request, content, HttpStatus.FORBIDDEN); + } + + DocumentStoreDataEntityImpl document = new DocumentStoreDataEntityImpl(); + document.setContent(content); + + DocumentOperationResult result = + documentStore.createDocument(index, document, implicitlyCreateIndex(headers)); + String output = null; + if (result.getResultCode() >= 200 && result.getResultCode() <= 299) { + output = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(result.getDocument()); + } else { + output = result.getError() != null + ? mapper.writerWithDefaultPrettyPrinter().writeValueAsString(result.getError()) + : result.getFailureCause(); + } + + if (httpResponse != null) { + httpResponse.setHeader(RESPONSE_HEADER_RESOURCE_VERSION, result.getResultVersion()); + } + ResponseEntity response = + ResponseEntity.status(result.getResultCode()).contentType(MediaType.APPLICATION_JSON).body(output); + logResult(request, HttpStatus.valueOf(response.getStatusCodeValue())); + logResult(request, HttpStatus.valueOf(response.getStatusCodeValue())); + + // Clear the MDC context so that no other transaction inadvertently + // uses our transaction id. + ApiUtils.clearMdcContext(); + + return response; + } catch (Exception e) { + return handleError(request, e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); + } } - } - - public ResponseEntity<String> processDelete(String content, HttpServletRequest request, HttpHeaders headers, - HttpServletResponse httpResponse, String index, String id, - DocumentStoreInterface documentStore) { - - // Initialize the MDC Context for logging purposes. - ApiUtils.initMdcContext(request, headers); - - try { - ObjectMapper mapper = new ObjectMapper(); - mapper.setSerializationInclusion(Include.NON_EMPTY); - boolean isValid; - try { - isValid = searchService.validateRequest(headers, request, ApiUtils.Action.DELETE, - ApiUtils.SEARCH_AUTH_POLICY_NAME); - } catch (Exception e) { - logger.info(SearchDbMsgs.EXCEPTION_DURING_METHOD_CALL, - "DocumentApi.processDelete", - e.getMessage()); - return handleError(request, content, HttpStatus.FORBIDDEN); - } - - if (!isValid) { - return handleError(request, content, HttpStatus.FORBIDDEN); - } - - String resourceVersion = headers.getFirst(REQUEST_HEADER_RESOURCE_VERSION); - if (resourceVersion == null || resourceVersion.isEmpty()) { - return handleError(request, "Request header 'If-Match' missing", - HttpStatus.BAD_REQUEST); - } - - DocumentStoreDataEntityImpl document = new DocumentStoreDataEntityImpl(); - document.setId(id); - document.setVersion(resourceVersion); - - DocumentOperationResult result = documentStore.deleteDocument(index, document); - String output = null; - if (!(result.getResultCode() >= 200 && result.getResultCode() <= 299)) { // - output = result.getError() != null - ? mapper.writerWithDefaultPrettyPrinter().writeValueAsString(result.getError()) - : result.getFailureCause(); - } - - if (httpResponse != null) { - httpResponse.setHeader(RESPONSE_HEADER_RESOURCE_VERSION, result.getResultVersion()); - } - ResponseEntity response; - if (output == null) { - response = ResponseEntity.status(result.getResultCode()).build(); - } else { - response = ResponseEntity.status(result.getResultCode()).contentType ( MediaType.APPLICATION_JSON ).body(output); - } - - logResult(request, HttpStatus.valueOf ( response.getStatusCodeValue () )); - - // Clear the MDC context so that no other transaction inadvertently - // uses our transaction id. - ApiUtils.clearMdcContext(); - - return response; - } catch (Exception e) { - return handleError(request, e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); + + public ResponseEntity<String> processPut(String content, HttpServletRequest request, HttpHeaders headers, + HttpServletResponse httpResponse, String index, String id, DocumentStoreInterface documentStore) { + + // Initialize the MDC Context for logging purposes. + ApiUtils.initMdcContext(request, headers); + + try { + ObjectMapper mapper = new ObjectMapper(); + mapper.setSerializationInclusion(Include.NON_EMPTY); + if (content == null) { + return handleError(request, content, HttpStatus.BAD_REQUEST); + } + + boolean isValid; + try { + isValid = searchService.validateRequest(headers, request, ApiUtils.Action.PUT, + ApiUtils.SEARCH_AUTH_POLICY_NAME); + } catch (Exception e) { + logger.info(SearchDbMsgs.EXCEPTION_DURING_METHOD_CALL, "DocumentApi.processPut", e.getMessage()); + return handleError(request, content, HttpStatus.FORBIDDEN); + } + + if (!isValid) { + return handleError(request, content, HttpStatus.FORBIDDEN); + } + + String resourceVersion = headers.getFirst(REQUEST_HEADER_RESOURCE_VERSION); + + DocumentStoreDataEntityImpl document = new DocumentStoreDataEntityImpl(); + document.setId(id); + document.setContent(content); + document.setVersion(resourceVersion); + + DocumentOperationResult result = null; + if (resourceVersion == null) { + result = documentStore.createDocument(index, document, implicitlyCreateIndex(headers)); + } else { + result = documentStore.updateDocument(index, document, implicitlyCreateIndex(headers)); + } + + String output = null; + if (result.getResultCode() >= 200 && result.getResultCode() <= 299) { + output = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(result.getDocument()); + } else { + output = result.getError() != null + ? mapper.writerWithDefaultPrettyPrinter().writeValueAsString(result.getError()) + : result.getFailureCause(); + } + if (httpResponse != null) { + httpResponse.setHeader(RESPONSE_HEADER_RESOURCE_VERSION, result.getResultVersion()); + } + ResponseEntity response = + ResponseEntity.status(result.getResultCode()).contentType(MediaType.APPLICATION_JSON).body(output); + logResult(request, HttpStatus.valueOf(response.getStatusCodeValue())); + + // Clear the MDC context so that no other transaction inadvertently + // uses our transaction id. + ApiUtils.clearMdcContext(); + + return response; + } catch (Exception e) { + return handleError(request, e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); + } } - } - - public ResponseEntity<String> processGet(String content, HttpServletRequest request, HttpHeaders headers, - HttpServletResponse httpResponse, String index, String id, - DocumentStoreInterface documentStore) { - - // Initialize the MDC Context for logging purposes. - ApiUtils.initMdcContext(request, headers); - - try { - ObjectMapper mapper = new ObjectMapper(); - mapper.setSerializationInclusion(Include.NON_EMPTY); - boolean isValid; - try { - isValid = searchService.validateRequest(headers, request, ApiUtils.Action.GET, - ApiUtils.SEARCH_AUTH_POLICY_NAME); - } catch (Exception e) { - logger.info(SearchDbMsgs.EXCEPTION_DURING_METHOD_CALL, - "DocumentApi.processGet", - e.getMessage()); - return handleError(request, content, HttpStatus.FORBIDDEN); - } - - if (!isValid) { - return handleError(request, content, HttpStatus.FORBIDDEN); - } - - String resourceVersion = headers.getFirst(REQUEST_HEADER_RESOURCE_VERSION); - - DocumentStoreDataEntityImpl document = new DocumentStoreDataEntityImpl(); - document.setId(id); - document.setVersion(resourceVersion); - - DocumentOperationResult result = documentStore.getDocument(index, document); - String output = null; - if (result.getResultCode() >= 200 && result.getResultCode() <= 299) { - output = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(result.getDocument()); - } else { - output = result.getError() != null - ? mapper.writerWithDefaultPrettyPrinter().writeValueAsString(result.getError()) - : result.getFailureCause(); - } - if (httpResponse != null) { - httpResponse.setHeader(RESPONSE_HEADER_RESOURCE_VERSION, result.getResultVersion()); - } - ResponseEntity response = ResponseEntity.status(result.getResultCode()).contentType ( MediaType.APPLICATION_JSON ).body(output); - logResult(request, HttpStatus.valueOf ( response.getStatusCodeValue () )); - - // Clear the MDC context so that no other transaction inadvertently - // uses our transaction id. - ApiUtils.clearMdcContext(); - - return response; - } catch (Exception e) { - return handleError(request, e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); + + public ResponseEntity<String> processDelete(String content, HttpServletRequest request, HttpHeaders headers, + HttpServletResponse httpResponse, String index, String id, DocumentStoreInterface documentStore) { + + // Initialize the MDC Context for logging purposes. + ApiUtils.initMdcContext(request, headers); + + try { + ObjectMapper mapper = new ObjectMapper(); + mapper.setSerializationInclusion(Include.NON_EMPTY); + boolean isValid; + try { + isValid = searchService.validateRequest(headers, request, ApiUtils.Action.DELETE, + ApiUtils.SEARCH_AUTH_POLICY_NAME); + } catch (Exception e) { + logger.info(SearchDbMsgs.EXCEPTION_DURING_METHOD_CALL, "DocumentApi.processDelete", e.getMessage()); + return handleError(request, content, HttpStatus.FORBIDDEN); + } + + if (!isValid) { + return handleError(request, content, HttpStatus.FORBIDDEN); + } + + String resourceVersion = headers.getFirst(REQUEST_HEADER_RESOURCE_VERSION); + if (resourceVersion == null || resourceVersion.isEmpty()) { + return handleError(request, "Request header 'If-Match' missing", HttpStatus.BAD_REQUEST); + } + + DocumentStoreDataEntityImpl document = new DocumentStoreDataEntityImpl(); + document.setId(id); + document.setVersion(resourceVersion); + + DocumentOperationResult result = documentStore.deleteDocument(index, document); + String output = null; + if (!(result.getResultCode() >= 200 && result.getResultCode() <= 299)) { // + output = result.getError() != null + ? mapper.writerWithDefaultPrettyPrinter().writeValueAsString(result.getError()) + : result.getFailureCause(); + } + + if (httpResponse != null) { + httpResponse.setHeader(RESPONSE_HEADER_RESOURCE_VERSION, result.getResultVersion()); + } + ResponseEntity response; + if (output == null) { + response = ResponseEntity.status(result.getResultCode()).build(); + } else { + response = ResponseEntity.status(result.getResultCode()).contentType(MediaType.APPLICATION_JSON) + .body(output); + } + + logResult(request, HttpStatus.valueOf(response.getStatusCodeValue())); + + // Clear the MDC context so that no other transaction inadvertently + // uses our transaction id. + ApiUtils.clearMdcContext(); + + return response; + } catch (Exception e) { + return handleError(request, e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); + } } - } - - public ResponseEntity<String> processSearchWithGet(String content, HttpServletRequest request, - HttpHeaders headers, String index, - String queryText, DocumentStoreInterface documentStore) { - - // Initialize the MDC Context for logging purposes. - ApiUtils.initMdcContext(request, headers); - - try { - ObjectMapper mapper = new ObjectMapper(); - mapper.setSerializationInclusion(Include.NON_EMPTY); - - boolean isValid; - try { - isValid = searchService.validateRequest(headers, request, ApiUtils.Action.GET, - ApiUtils.SEARCH_AUTH_POLICY_NAME); - } catch (Exception e) { - logger.info(SearchDbMsgs.EXCEPTION_DURING_METHOD_CALL, - "processSearchWithGet", - e.getMessage()); - return handleError(request, content, HttpStatus.FORBIDDEN); - } - - if (!isValid) { - return handleError(request, content, HttpStatus.FORBIDDEN); - } - - SearchOperationResult result = documentStore.search(index, queryText); - String output = null; - if (result.getResultCode() >= 200 && result.getResultCode() <= 299) { - output = mapper.writerWithDefaultPrettyPrinter() - .writeValueAsString(result.getSearchResult()); - } else { - output = result.getError() != null - ? mapper.writerWithDefaultPrettyPrinter().writeValueAsString(result.getError()) - : result.getFailureCause(); - } - ResponseEntity response = ResponseEntity.status(result.getResultCode()).contentType ( MediaType.APPLICATION_JSON ).body(output); - - // Clear the MDC context so that no other transaction inadvertently - // uses our transaction id. - ApiUtils.clearMdcContext(); - - return response; - } catch (Exception e) { - return handleError(request, e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); + + public ResponseEntity<String> processGet(String content, HttpServletRequest request, HttpHeaders headers, + HttpServletResponse httpResponse, String index, String id, DocumentStoreInterface documentStore) { + + // Initialize the MDC Context for logging purposes. + ApiUtils.initMdcContext(request, headers); + + try { + ObjectMapper mapper = new ObjectMapper(); + mapper.setSerializationInclusion(Include.NON_EMPTY); + boolean isValid; + try { + isValid = searchService.validateRequest(headers, request, ApiUtils.Action.GET, + ApiUtils.SEARCH_AUTH_POLICY_NAME); + } catch (Exception e) { + logger.info(SearchDbMsgs.EXCEPTION_DURING_METHOD_CALL, "DocumentApi.processGet", e.getMessage()); + return handleError(request, content, HttpStatus.FORBIDDEN); + } + + if (!isValid) { + return handleError(request, content, HttpStatus.FORBIDDEN); + } + + String resourceVersion = headers.getFirst(REQUEST_HEADER_RESOURCE_VERSION); + + DocumentStoreDataEntityImpl document = new DocumentStoreDataEntityImpl(); + document.setId(id); + document.setVersion(resourceVersion); + + DocumentOperationResult result = documentStore.getDocument(index, document); + String output = null; + if (result.getResultCode() >= 200 && result.getResultCode() <= 299) { + output = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(result.getDocument()); + } else { + output = result.getError() != null + ? mapper.writerWithDefaultPrettyPrinter().writeValueAsString(result.getError()) + : result.getFailureCause(); + } + if (httpResponse != null) { + httpResponse.setHeader(RESPONSE_HEADER_RESOURCE_VERSION, result.getResultVersion()); + } + ResponseEntity response = + ResponseEntity.status(result.getResultCode()).contentType(MediaType.APPLICATION_JSON).body(output); + logResult(request, HttpStatus.valueOf(response.getStatusCodeValue())); + + // Clear the MDC context so that no other transaction inadvertently + // uses our transaction id. + ApiUtils.clearMdcContext(); + + return response; + } catch (Exception e) { + return handleError(request, e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); + } } - } - public ResponseEntity<String> queryWithGetWithPayload(String content, HttpServletRequest request, - HttpHeaders headers, String index, - DocumentStoreInterface documentStore) { + public ResponseEntity<String> processSearchWithGet(String content, HttpServletRequest request, HttpHeaders headers, + String index, String queryText, DocumentStoreInterface documentStore) { + + // Initialize the MDC Context for logging purposes. + ApiUtils.initMdcContext(request, headers); + + try { + ObjectMapper mapper = new ObjectMapper(); + mapper.setSerializationInclusion(Include.NON_EMPTY); + + boolean isValid; + try { + isValid = searchService.validateRequest(headers, request, ApiUtils.Action.GET, + ApiUtils.SEARCH_AUTH_POLICY_NAME); + } catch (Exception e) { + logger.info(SearchDbMsgs.EXCEPTION_DURING_METHOD_CALL, "processSearchWithGet", e.getMessage()); + return handleError(request, content, HttpStatus.FORBIDDEN); + } + + if (!isValid) { + return handleError(request, content, HttpStatus.FORBIDDEN); + } + + SearchOperationResult result = documentStore.search(index, queryText); + String output = null; + if (result.getResultCode() >= 200 && result.getResultCode() <= 299) { + output = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(result.getSearchResult()); + } else { + output = result.getError() != null + ? mapper.writerWithDefaultPrettyPrinter().writeValueAsString(result.getError()) + : result.getFailureCause(); + } + ResponseEntity response = + ResponseEntity.status(result.getResultCode()).contentType(MediaType.APPLICATION_JSON).body(output); + + // Clear the MDC context so that no other transaction inadvertently + // uses our transaction id. + ApiUtils.clearMdcContext(); + + return response; + } catch (Exception e) { + return handleError(request, e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); + } + } + + public ResponseEntity<String> queryWithGetWithPayload(String content, HttpServletRequest request, + HttpHeaders headers, String index, DocumentStoreInterface documentStore) { - // Initialize the MDC Context for logging purposes. - ApiUtils.initMdcContext(request, headers); + // Initialize the MDC Context for logging purposes. + ApiUtils.initMdcContext(request, headers); - logger.info(SearchDbMsgs.PROCESS_PAYLOAD_QUERY, "GET", (request != null) - ? request.getRequestURL ().toString () : ""); - if (logger.isDebugEnabled()) { - logger.debug("Request Body: " + content); + logger.info(SearchDbMsgs.PROCESS_PAYLOAD_QUERY, "GET", + (request != null) ? request.getRequestURL().toString() : ""); + if (logger.isDebugEnabled()) { + logger.debug("Request Body: " + content); + } + return processQuery(index, content, request, headers, documentStore); } - return processQuery(index, content, request, headers, documentStore); - } - public ResponseEntity<String> processSearchWithPost(String content, HttpServletRequest request, - HttpHeaders headers, String index, - DocumentStoreInterface documentStore) { + public ResponseEntity<String> processSearchWithPost(String content, HttpServletRequest request, HttpHeaders headers, + String index, DocumentStoreInterface documentStore) { + + // Initialize the MDC Context for logging purposes. + ApiUtils.initMdcContext(request, headers); - // Initialize the MDC Context for logging purposes. - ApiUtils.initMdcContext(request, headers); + logger.info(SearchDbMsgs.PROCESS_PAYLOAD_QUERY, "POST", + (request != null) ? request.getRequestURL().toString() : ""); + if (logger.isDebugEnabled()) { + logger.debug("Request Body: " + content); + } - logger.info(SearchDbMsgs.PROCESS_PAYLOAD_QUERY, "POST", (request != null) - ? request.getRequestURL ().toString () : ""); - if (logger.isDebugEnabled()) { - logger.debug("Request Body: " + content); + return processQuery(index, content, request, headers, documentStore); } - return processQuery(index, content, request, headers, documentStore); - } + public ResponseEntity<String> processSuggestQueryWithPost(String content, HttpServletRequest request, + HttpHeaders headers, String index, DocumentStoreInterface documentStore) { - public ResponseEntity<String> processSuggestQueryWithPost(String content, HttpServletRequest request, - HttpHeaders headers, String index, DocumentStoreInterface documentStore) { + // Initialize the MDC Context for logging purposes. + ApiUtils.initMdcContext(request, headers); - // Initialize the MDC Context for logging purposes. - ApiUtils.initMdcContext(request, headers); + logger.info(SearchDbMsgs.PROCESS_PAYLOAD_QUERY, "POST", + (request != null) ? request.getRequestURL().toString() : ""); + if (logger.isDebugEnabled()) { + logger.debug("Request Body: " + content); + } - logger.info(SearchDbMsgs.PROCESS_PAYLOAD_QUERY, "POST", - (request != null) ? request.getRequestURL().toString() : ""); - if (logger.isDebugEnabled()) { - logger.debug("Request Body: " + content); + return processSuggestQuery(index, content, request, headers, documentStore); } - return processSuggestQuery(index, content, request, headers, documentStore); - } - - /** - * Common handler for query requests. This is called by both the GET with - * payload and POST with payload variants of the query endpoint. - * - * @param index - The index to be queried against. - * @param content - The payload containing the query structure. - * @param request - The HTTP request. - * @param headers - The HTTP headers. - * @return - A standard HTTP response. - */ - private ResponseEntity processQuery(String index, String content, HttpServletRequest request, - HttpHeaders headers, DocumentStoreInterface documentStore) { - - try { - ObjectMapper mapper = new ObjectMapper(); - mapper.setSerializationInclusion(Include.NON_EMPTY); - - // Make sure that we were supplied a payload before proceeding. - if (content == null) { - return handleError(request, content, HttpStatus.BAD_REQUEST); - } - - // Validate that the request has the appropriate authorization. - boolean isValid; - try { - isValid = searchService.validateRequest(headers, request, ApiUtils.Action.POST, - ApiUtils.SEARCH_AUTH_POLICY_NAME); - - } catch (Exception e) { - logger.info(SearchDbMsgs.EXCEPTION_DURING_METHOD_CALL, - "processQuery", - e.getMessage()); - return handleError(request, content, HttpStatus.FORBIDDEN); - } - - if (!isValid) { - return handleError(request, content, HttpStatus.FORBIDDEN); - } - - SearchStatement searchStatement; - - try { - // Marshall the supplied request payload into a search statement - // object. - searchStatement = mapper.readValue(content, SearchStatement.class); - - } catch (Exception e) { - return handleError(request, e.getMessage(), HttpStatus.BAD_REQUEST); - } - - // Now, submit the search statement, translated into - // ElasticSearch syntax, to the document store DAO. - SearchOperationResult result = documentStore.searchWithPayload(index, - searchStatement.toElasticSearch()); - String output = null; - if (result.getResultCode() >= 200 && result.getResultCode() <= 299) { - output = prepareOutput(mapper, result); - } else { - output = result.getError() != null - ? mapper.writerWithDefaultPrettyPrinter().writeValueAsString(result.getError()) - : result.getFailureCause(); - } - ResponseEntity response = ResponseEntity.status(result.getResultCode()).contentType ( MediaType.APPLICATION_JSON ).body(output); - - // Clear the MDC context so that no other transaction inadvertently - // uses our transaction id. - ApiUtils.clearMdcContext(); - - return response; - - } catch (Exception e) { - return handleError(request, e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); + /** + * Common handler for query requests. This is called by both the GET with payload and POST with payload variants of + * the query endpoint. + * + * @param index - The index to be queried against. + * @param content - The payload containing the query structure. + * @param request - The HTTP request. + * @param headers - The HTTP headers. + * @return - A standard HTTP response. + */ + private ResponseEntity processQuery(String index, String content, HttpServletRequest request, HttpHeaders headers, + DocumentStoreInterface documentStore) { + + try { + ObjectMapper mapper = new ObjectMapper(); + mapper.setSerializationInclusion(Include.NON_EMPTY); + + // Make sure that we were supplied a payload before proceeding. + if (content == null) { + return handleError(request, content, HttpStatus.BAD_REQUEST); + } + + // Validate that the request has the appropriate authorization. + boolean isValid; + try { + isValid = searchService.validateRequest(headers, request, ApiUtils.Action.POST, + ApiUtils.SEARCH_AUTH_POLICY_NAME); + + } catch (Exception e) { + logger.info(SearchDbMsgs.EXCEPTION_DURING_METHOD_CALL, "processQuery", e.getMessage()); + return handleError(request, content, HttpStatus.FORBIDDEN); + } + + if (!isValid) { + return handleError(request, content, HttpStatus.FORBIDDEN); + } + + SearchStatement searchStatement; + + try { + // Marshall the supplied request payload into a search statement + // object. + searchStatement = mapper.readValue(content, SearchStatement.class); + + } catch (Exception e) { + return handleError(request, e.getMessage(), HttpStatus.BAD_REQUEST); + } + + // Now, submit the search statement, translated into + // ElasticSearch syntax, to the document store DAO. + SearchOperationResult result = documentStore.searchWithPayload(index, searchStatement.toElasticSearch()); + String output = null; + if (result.getResultCode() >= 200 && result.getResultCode() <= 299) { + output = prepareOutput(mapper, result); + } else { + output = result.getError() != null + ? mapper.writerWithDefaultPrettyPrinter().writeValueAsString(result.getError()) + : result.getFailureCause(); + } + ResponseEntity response = + ResponseEntity.status(result.getResultCode()).contentType(MediaType.APPLICATION_JSON).body(output); + + // Clear the MDC context so that no other transaction inadvertently + // uses our transaction id. + ApiUtils.clearMdcContext(); + + return response; + + } catch (Exception e) { + return handleError(request, e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); + } } - } - - - /** - * Common handler for query requests. This is called by both the GET with payload and POST with - * payload variants of the query endpoint. - * - * @param index - The index to be queried against. - * @param content - The payload containing the query structure. - * @param request - The HTTP request. - * @param headers - The HTTP headers. - * @return - A standard HTTP response. - */ - private ResponseEntity<String> processSuggestQuery(String index, String content, HttpServletRequest request, - HttpHeaders headers, DocumentStoreInterface documentStore) { - - try { - ObjectMapper mapper = new ObjectMapper(); - mapper.setSerializationInclusion(Include.NON_EMPTY); - - // Make sure that we were supplied a payload before proceeding. - if (content == null) { - return handleError(request, content, HttpStatus.BAD_REQUEST); - } - - // Validate that the request has the appropriate authorization. - boolean isValid; - try { - isValid = searchService.validateRequest(headers, request, ApiUtils.Action.POST, - ApiUtils.SEARCH_AUTH_POLICY_NAME); - - } catch (Exception e) { - logger.info(SearchDbMsgs.EXCEPTION_DURING_METHOD_CALL, "processQuery", e.getMessage()); - return handleError(request, content, HttpStatus.FORBIDDEN); - } - - if (!isValid) { - return handleError(request, content, HttpStatus.FORBIDDEN); - } - - SuggestionStatement suggestionStatement; - - try { - // Marshall the supplied request payload into a search statement - // object. - suggestionStatement = mapper.readValue(content, SuggestionStatement.class); - - } catch (Exception e) { - return handleError(request, e.getMessage(), HttpStatus.BAD_REQUEST); - } - - // Now, submit the search statement, translated into - // ElasticSearch syntax, to the document store DAO. - SearchOperationResult result = - documentStore.suggestionQueryWithPayload(index, suggestionStatement.toElasticSearch()); - String output = null; - if (result.getResultCode() >= 200 && result.getResultCode() <= 299) { - output = prepareSuggestOutput(mapper, result); - } else { - output = result.getError() != null - ? mapper.writerWithDefaultPrettyPrinter().writeValueAsString(result.getError()) - : result.getFailureCause(); - } - ResponseEntity<String> response = ResponseEntity.status(result.getResultCode()).body(output); - - // Clear the MDC context so that no other transaction inadvertently - // uses our transaction id. - ApiUtils.clearMdcContext(); - - return response; - - } catch (Exception e) { - return handleError(request, e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); + + + /** + * Common handler for query requests. This is called by both the GET with payload and POST with payload variants of + * the query endpoint. + * + * @param index - The index to be queried against. + * @param content - The payload containing the query structure. + * @param request - The HTTP request. + * @param headers - The HTTP headers. + * @return - A standard HTTP response. + */ + private ResponseEntity<String> processSuggestQuery(String index, String content, HttpServletRequest request, + HttpHeaders headers, DocumentStoreInterface documentStore) { + + try { + ObjectMapper mapper = new ObjectMapper(); + mapper.setSerializationInclusion(Include.NON_EMPTY); + + // Make sure that we were supplied a payload before proceeding. + if (content == null) { + return handleError(request, content, HttpStatus.BAD_REQUEST); + } + + // Validate that the request has the appropriate authorization. + boolean isValid; + try { + isValid = searchService.validateRequest(headers, request, ApiUtils.Action.POST, + ApiUtils.SEARCH_AUTH_POLICY_NAME); + + } catch (Exception e) { + logger.info(SearchDbMsgs.EXCEPTION_DURING_METHOD_CALL, "processQuery", e.getMessage()); + return handleError(request, content, HttpStatus.FORBIDDEN); + } + + if (!isValid) { + return handleError(request, content, HttpStatus.FORBIDDEN); + } + + SuggestionStatement suggestionStatement; + + try { + // Marshall the supplied request payload into a search statement + // object. + suggestionStatement = mapper.readValue(content, SuggestionStatement.class); + + } catch (Exception e) { + return handleError(request, e.getMessage(), HttpStatus.BAD_REQUEST); + } + + // Now, submit the search statement, translated into + // ElasticSearch syntax, to the document store DAO. + SearchOperationResult result = + documentStore.suggestionQueryWithPayload(index, suggestionStatement.toElasticSearch()); + String output = null; + if (result.getResultCode() >= 200 && result.getResultCode() <= 299) { + output = prepareSuggestOutput(mapper, result); + } else { + output = result.getError() != null + ? mapper.writerWithDefaultPrettyPrinter().writeValueAsString(result.getError()) + : result.getFailureCause(); + } + ResponseEntity<String> response = ResponseEntity.status(result.getResultCode()).body(output); + + // Clear the MDC context so that no other transaction inadvertently + // uses our transaction id. + ApiUtils.clearMdcContext(); + + return response; + + } catch (Exception e) { + return handleError(request, e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); + } } - } - - /** - * Checks the supplied HTTP headers to see if we should allow the underlying document - * store to implicitly create the index referenced in a document PUT or POST if it - * does not already exist in the data store. - * - * @param headers - The HTTP headers to examine. - * - * @return - true if the headers indicate that missing indices should be implicitly created, - * false otherwise. - */ - private boolean implicitlyCreateIndex(HttpHeaders headers) { - - boolean createIndexIfNotPresent = false; - String implicitIndexCreationHeader = - headers.getFirst(REQUEST_HEADER_ALLOW_IMPLICIT_INDEX_CREATION); - - if( (implicitIndexCreationHeader != null) && (implicitIndexCreationHeader.equals("true")) ) { - createIndexIfNotPresent = true; + + /** + * Checks the supplied HTTP headers to see if we should allow the underlying document store to implicitly create the + * index referenced in a document PUT or POST if it does not already exist in the data store. + * + * @param headers - The HTTP headers to examine. + * + * @return - true if the headers indicate that missing indices should be implicitly created, false otherwise. + */ + private boolean implicitlyCreateIndex(HttpHeaders headers) { + + boolean createIndexIfNotPresent = false; + String implicitIndexCreationHeader = headers.getFirst(REQUEST_HEADER_ALLOW_IMPLICIT_INDEX_CREATION); + + if ((implicitIndexCreationHeader != null) && (implicitIndexCreationHeader.equals("true"))) { + createIndexIfNotPresent = true; + } + + return createIndexIfNotPresent; + } + + private String prepareOutput(ObjectMapper mapper, SearchOperationResult result) throws JsonProcessingException { + StringBuffer output = new StringBuffer(); + output.append("{\r\n\"searchResult\":"); + output.append(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(result.getSearchResult())); + AggregationResults aggs = result.getAggregationResult(); + if (aggs != null) { + output.append(",\r\n\"aggregationResult\":"); + output.append(mapper.setSerializationInclusion(Include.NON_NULL).writerWithDefaultPrettyPrinter() + .writeValueAsString(aggs)); + } + output.append("\r\n}"); + return output.toString(); + } + + private String prepareSuggestOutput(ObjectMapper mapper, SearchOperationResult result) + throws JsonProcessingException { + StringBuffer output = new StringBuffer(); + output.append("{\r\n\"searchResult\":"); + output.append(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(result.getSuggestResult())); + AggregationResults aggs = result.getAggregationResult(); + if (aggs != null) { + output.append(",\r\n\"aggregationResult\":"); + output.append(mapper.setSerializationInclusion(Include.NON_NULL).writerWithDefaultPrettyPrinter() + .writeValueAsString(aggs)); + } + output.append("\r\n}"); + return output.toString(); } - - return createIndexIfNotPresent; - } - - private String prepareOutput(ObjectMapper mapper, SearchOperationResult result) - throws JsonProcessingException { - StringBuffer output = new StringBuffer(); - output.append("{\r\n\"searchResult\":"); - output.append( - mapper.writerWithDefaultPrettyPrinter().writeValueAsString(result.getSearchResult())); - AggregationResults aggs = result.getAggregationResult(); - if (aggs != null) { - output.append(",\r\n\"aggregationResult\":"); - output.append(mapper.setSerializationInclusion(Include.NON_NULL) - .writerWithDefaultPrettyPrinter().writeValueAsString(aggs)); + + private ResponseEntity handleError(HttpServletRequest request, String message, HttpStatus status) { + logResult(request, status); + return ResponseEntity.status(status).contentType(MediaType.APPLICATION_JSON).body(message); } - output.append("\r\n}"); - return output.toString(); - } - - private String prepareSuggestOutput(ObjectMapper mapper, SearchOperationResult result) - throws JsonProcessingException { - StringBuffer output = new StringBuffer(); - output.append("{\r\n\"searchResult\":"); - output.append( - mapper.writerWithDefaultPrettyPrinter().writeValueAsString(result.getSuggestResult())); - AggregationResults aggs = result.getAggregationResult(); - if (aggs != null) { - output.append(",\r\n\"aggregationResult\":"); - output.append(mapper.setSerializationInclusion(Include.NON_NULL) - .writerWithDefaultPrettyPrinter().writeValueAsString(aggs)); + + void logResult(HttpServletRequest request, HttpStatus status) { + + logger.info(SearchDbMsgs.PROCESS_REST_REQUEST, (request != null) ? request.getMethod().toString() : "", + (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.getRequestURL().toString() : "", + (request != null) ? request.getRemoteHost() : "", Integer.toString(status.value())); + + // Clear the MDC context so that no other transaction inadvertently + // uses our transaction id. + ApiUtils.clearMdcContext(); } - output.append("\r\n}"); - return output.toString(); - } - - private ResponseEntity 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 () : "", - (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.getRequestURL ().toString () : "", - (request != null) ? request.getRemoteHost () : "", Integer.toString(status.value())); - - // 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 f5840e2..3371fcd 100644 --- a/src/main/java/org/onap/aai/sa/rest/IndexApi.java +++ b/src/main/java/org/onap/aai/sa/rest/IndexApi.java @@ -32,398 +32,383 @@ import org.onap.aai.sa.searchdbabstraction.elasticsearch.dao.DocumentStoreInterf import org.onap.aai.sa.searchdbabstraction.elasticsearch.exception.DocumentStoreOperationException; import org.onap.aai.sa.searchdbabstraction.entity.OperationResult; import org.onap.aai.sa.searchdbabstraction.logging.SearchDbMsgs; -// Spring Imports import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; -// import org.springframework.http.server.HttpServletRequest; 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. + * 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; - - /** - * Configuration for the custom analyzers that will be used for indexing. - */ - protected AnalysisConfiguration analysisConfig; - - // 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(); - } - - - /** - * Initializes the end point. - * - * @throws FileNotFoundException - * @throws IOException - * @throws DocumentStoreOperationException - */ - public void init() { - - // 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 - */ - public ResponseEntity<String> processCreateIndex (String documentSchema, - HttpServletRequest request, - HttpHeaders headers, - String index, - DocumentStoreInterface documentStore) { - - int resultCode = 500; - String resultString = "Unexpected error"; - - // Initialize the MDC Context for logging purposes. - ApiUtils.initMdcContext(request, headers); - - // Validate that the request is correctly authenticated before going - // any further. - 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); + 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; + + // 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(); } - // 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); + /** + * Initializes the end point. + * + * @throws FileNotFoundException + * @throws IOException + * @throws DocumentStoreOperationException + */ + public void init() { + + // Instantiate our analysis configuration object. + analysisConfig = new AnalysisConfiguration(); } - try { - // Marshal the supplied json string into a document schema object. - ObjectMapper mapper = new ObjectMapper(); - DocumentSchema schema = mapper.readValue(documentSchema, DocumentSchema.class); + /** + * 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 + */ + public ResponseEntity<String> processCreateIndex(String documentSchema, HttpServletRequest request, + HttpHeaders headers, String index, DocumentStoreInterface documentStore) { - // Now, ask the DAO to create the index. - OperationResult result = documentStore.createIndex(index, schema); + int resultCode = 500; + String resultString = "Unexpected error"; - // 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(); + // Initialize the MDC Context for logging purposes. + ApiUtils.initMdcContext(request, headers); - } catch (com.fasterxml.jackson.core.JsonParseException - | com.fasterxml.jackson.databind.JsonMappingException e) { + // Validate that the request is correctly authenticated before going + // any further. + try { - // 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(); + 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 (IOException e) { + } catch (Exception e) { - // We'll treat this is a general internal error. - resultCode = HttpStatus.INTERNAL_SERVER_ERROR.value(); - resultString = "IO Failure: " + e.getMessage(); - } + logger.warn(SearchDbMsgs.INDEX_CREATE_FAILURE, index, + "Unexpected authentication failure - cause: " + e.getMessage()); + return errorResponse(HttpStatus.FORBIDDEN, "Authentication failure.", request); + } - ResponseEntity<String> response = ResponseEntity.status(resultCode).contentType ( MediaType.APPLICATION_JSON ).body(resultString); + // 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); + } - // 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); - } + try { - // 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 ())); + // 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); + // 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(); - // Clear the MDC context so that no other transaction inadvertently - // uses our transaction id. - ApiUtils.clearMdcContext(); + } catch (com.fasterxml.jackson.core.JsonParseException + | com.fasterxml.jackson.databind.JsonMappingException e) { - // Finally, return the response. - return response; - } + // 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(); - /** - * 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) { + } catch (IOException e) { - ResponseEntity<String> response = null; + // We'll treat this is a general internal error. + resultCode = HttpStatus.INTERNAL_SERVER_ERROR.value(); + resultString = "IO Failure: " + e.getMessage(); + } - ResponseEntity<String> validationResponse = validateRequest(request, headers, index, SearchDbMsgs.INDEX_CREATE_FAILURE); + ResponseEntity<String> response = + ResponseEntity.status(resultCode).contentType(MediaType.APPLICATION_JSON).body(resultString); - if (validationResponse.getStatusCodeValue () != HttpStatus.OK.value ()) { - response = validationResponse; - } else { - OperationResult result = documentStore.createDynamicIndex(index, dynamicSchema); + // 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, + 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())); - int resultCode = (result.getResultCode() == 200) ? 201 : result.getResultCode(); - String resultString = (result.getFailureCause() == null) ? result.getResult() : result.getFailureCause(); - 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. - */ - 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); + // Clear the MDC context so that no other transaction inadvertently + // uses our transaction id. + ApiUtils.clearMdcContext(); + + // 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) { - try { - // Send the request to the document store. - response = responseFromOperationResult(documentStore.deleteIndex(index)); + ResponseEntity<String> response = null; - } catch (DocumentStoreOperationException e) { - response = ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).contentType ( MediaType.APPLICATION_JSON ).body(e.getMessage()); + 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(); + + response = ResponseEntity.status(resultCode).body(resultString); + } + + return response; } - // Log the result. - if ((response.getStatusCodeValue() >= 200) && (response.getStatusCodeValue() < 300)) { - logger.info(SearchDbMsgs.DELETED_INDEX, index); - } else { - logger.warn(SearchDbMsgs.INDEX_DELETE_FAILURE, index, (String) response.getBody ()); + /** + * 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. + */ + 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)); + + } 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 { + logger.warn(SearchDbMsgs.INDEX_DELETE_FAILURE, index, response.getBody()); + } + + // Generate our audit log. + auditLogger.info(SearchDbMsgs.PROCESS_REST_REQUEST, + new LogFields().setField(LogLine.DefinedFields.RESPONSE_CODE, response.getStatusCodeValue()).setField( + LogLine.DefinedFields.RESPONSE_DESCRIPTION, response.getStatusCode().getReasonPhrase()), + (request != null) ? request.getMethod().toString() : "Unknown", + (request != null) ? request.getRequestURL().toString() : "Unknown", + (request != null) ? request.getRemoteHost() : "Unknown", + Integer.toString(response.getStatusCodeValue())); + + // Clear the MDC context so that no other transaction inadvertently + // uses our transaction id. + ApiUtils.clearMdcContext(); + + return response; } - // 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())); - - // Clear the MDC context so that no other transaction inadvertently - // uses our transaction id. - ApiUtils.clearMdcContext(); - - 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) { - 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 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("}"); + + /** + * 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) { + 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 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("}"); + + logger.debug("Generated document mappings: " + sb.toString()); + + return sb.toString(); } - sb.append("}"); - sb.append("}"); - logger.debug("Generated document mappings: " + 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) { + + if ((result.getResultCode() >= 200) && (result.getResultCode() < 300)) { + return ResponseEntity.status(result.getResultCode()).contentType(MediaType.APPLICATION_JSON) + .body(result.getResult()); + } else { + if (result.getFailureCause() != null) { + return ResponseEntity.status(result.getResultCode()).contentType(MediaType.APPLICATION_JSON) + .body(result.getFailureCause()); + } else { + return ResponseEntity.status(result.getResultCode()).contentType(MediaType.APPLICATION_JSON) + .body(result.getResult()); + } + } + } - return sb.toString(); - } + public ResponseEntity<String> errorResponse(HttpStatus status, String msg, HttpServletRequest 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", + (request != null) ? request.getRemoteHost() : "Unknown", Integer.toString(status.value())); - /** - * 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) { + // Clear the MDC context so that no other transaction inadvertently + // uses our transaction id. + ApiUtils.clearMdcContext(); - if ((result.getResultCode() >= 200) && (result.getResultCode() < 300)) { - return ResponseEntity.status(result.getResultCode()).contentType ( MediaType.APPLICATION_JSON ).body(result.getResult()); - } else { - if (result.getFailureCause() != null) { - return ResponseEntity.status(result.getResultCode()).contentType ( MediaType.APPLICATION_JSON ).body(result.getFailureCause()); - } else { - return ResponseEntity.status(result.getResultCode()).contentType ( MediaType.APPLICATION_JSON ).body(result.getResult()); - } + return ResponseEntity.status(status).contentType(MediaType.APPLICATION_JSON).body(msg); } - } - - public ResponseEntity<String> errorResponse(HttpStatus status, String msg, HttpServletRequest 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", - (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(); - - 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 - */ - private ResponseEntity<String> validateRequest(HttpServletRequest request, HttpHeaders headers, String index, SearchDbMsgs failureMsgEnum) { - 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); + + + /** + * 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 { + 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); } - 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 aacba78..d807996 100644 --- a/src/main/java/org/onap/aai/sa/rest/SearchServiceApi.java +++ b/src/main/java/org/onap/aai/sa/rest/SearchServiceApi.java @@ -45,228 +45,175 @@ import org.springframework.web.bind.annotation.RestController; @RequestMapping("/services/search-data-service/v1/search") public class SearchServiceApi { - /** - * The Data Access Object that we will use to interact with the - * document store. - */ - protected DocumentStoreInterface documentStore = null; - protected ApiUtils apiUtils = null; - - /** - * Create a new instance of the end point. - */ - public SearchServiceApi() { - - // Perform one-time initialization. - init(); - } - - - /** - * 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" }) - public ResponseEntity<String> processCreateIndex(@RequestBody String requestBody, - HttpServletRequest request, - @RequestHeader HttpHeaders headers, - @PathVariable("index") String index) { - - // Forward the request to our index API to create the index. - IndexApi indexApi = new IndexApi(this); - return indexApi.processCreateIndex(requestBody, request, headers, index, documentStore); - } - - @RequestMapping(value = "/indexes/{index}", - method = RequestMethod.DELETE, - consumes = {"application/json"}, - produces = {"application/json"}) - public ResponseEntity<String> processDeleteIndex(HttpServletRequest request, - @RequestHeader HttpHeaders headers, - @PathVariable ("index") String index) { - - // Forward the request to our index API to delete the index. - IndexApi indexApi = new IndexApi(this); - return indexApi.processDelete(index, request, headers, documentStore); - } - - - @RequestMapping(value = "/indexes/{index}/documents", - method = RequestMethod.POST, - consumes = {"application/json"}) - public ResponseEntity<String> processCreateDocWithoutId(@RequestBody String requestBody, - HttpServletRequest request, - HttpServletResponse httpResponse, - @RequestHeader HttpHeaders headers, - @PathVariable ("index") String index) { - - // Forward the request to our document API to create the document. - DocumentApi documentApi = new DocumentApi(this); - return documentApi.processPost(requestBody, request, headers, httpResponse, - index, documentStore); - } - - @RequestMapping(value = "/indexes/{index}/documents/{id}", - method = RequestMethod.PUT, - consumes = {"application/json"}) - public ResponseEntity<String> processUpsertDoc(@RequestBody String requestBody, - HttpServletRequest request, - HttpServletResponse httpResponse, - @RequestHeader HttpHeaders headers, - @PathVariable ("index") String index, - @PathVariable ("id") String id) { - - // Forward the request to our document API to upsert the document. - DocumentApi documentApi = new DocumentApi(this); - return documentApi.processPut(requestBody, request, headers, httpResponse, - index, id, documentStore); - } - - @RequestMapping(value = "/indexes/{index}/documents/{id}", - method = RequestMethod.GET) - public ResponseEntity<String> processGetDocument(HttpServletRequest request, - HttpServletResponse httpResponse, - @RequestHeader HttpHeaders headers, - @PathVariable ("index") String index, - @PathVariable ("id") String id) { - - // Forward the request to our document API to retrieve the document. - DocumentApi documentApi = new DocumentApi(this); - return documentApi.processGet("", request, headers, httpResponse, - index, id, documentStore); - } - - @RequestMapping(value = "/indexes/{index}/documents/{id}", - method = RequestMethod.DELETE, - consumes = {"application/json"}) - public ResponseEntity<String> processDeleteDoc(HttpServletRequest request, - HttpServletResponse httpResponse, - @RequestHeader HttpHeaders headers, - @PathVariable ("index") String index, - @PathVariable ("id") String id) { - - // Forward the request to our document API to delete the document. - DocumentApi documentApi = new DocumentApi(this); - return documentApi.processDelete("", request, headers, httpResponse, - index, id, documentStore); - } - - @RequestMapping(value = "/indexes/{index}/query/{queryText}", - method = RequestMethod.GET) - public ResponseEntity<String> processInlineQuery(HttpServletRequest request, - @RequestHeader HttpHeaders headers, - @PathVariable ("index") String index, - @PathVariable ("queryText") String queryText) { - - // Forward the request to our document API to delete the document. - DocumentApi documentApi = new DocumentApi(this); - return documentApi.processSearchWithGet("", request, headers, - index, queryText, documentStore); - } - - @RequestMapping(value = "/indexes/{index}/query", - method = RequestMethod.GET, - consumes = {"application/json"}) - public ResponseEntity<String> processQueryWithGet(@RequestBody String requestBody, - HttpServletRequest request, - @RequestHeader HttpHeaders headers, - @PathVariable ("index") String index) { - - // Forward the request to our document API to delete the document. - DocumentApi documentApi = new DocumentApi(this); - return documentApi.queryWithGetWithPayload(requestBody, request, headers, index, documentStore); - } - - @RequestMapping(value = "/indexes/{index}/query", - method = RequestMethod.POST, - consumes = {"application/json"}) - public ResponseEntity<String> processQuery(@RequestBody String requestBody, - HttpServletRequest request, - @RequestHeader HttpHeaders headers, - @PathVariable ("index") String index) { - - // Forward the request to our document API to delete the document. - DocumentApi documentApi = new DocumentApi(this); - return documentApi.processSearchWithPost(requestBody, request, headers, index, documentStore); - } - - @RequestMapping(value = "/indexes/{index}/suggest", - method = RequestMethod.POST, - consumes = {"application/json"}) - public ResponseEntity<String> processSuggestQuery(@RequestBody String requestBody, HttpServletRequest request, - @RequestHeader HttpHeaders headers, @PathVariable("index") String index) { - // Forward the request to our document API to query suggestions in the - // document. - DocumentApi documentApi = new DocumentApi(this); - return documentApi.processSuggestQueryWithPost(requestBody, request, headers, index, - documentStore); - } - - @RequestMapping(value = "/indexes/dynamic/{index}", - method = RequestMethod.PUT, - consumes = {"application/json"}) - public ResponseEntity<String> processCreateDynamicIndex(@RequestBody String requestBody, - HttpServletRequest request, - @RequestHeader HttpHeaders headers, - @PathVariable ("index") String index) { - - // Forward the request to our index API to create the index. - IndexApi indexApi = new IndexApi(this); - return indexApi.processCreateDynamicIndex(requestBody, request, headers, index, documentStore); - } - - @RequestMapping(value = "/bulk", - method = RequestMethod.POST, - consumes = {"application/json"}, - produces = { "application/json"}) - public ResponseEntity<String> processBulkRequest(@RequestBody String requestBody, - HttpServletRequest request, - @RequestHeader HttpHeaders headers) { - - // 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; - } - - protected boolean validateRequest(HttpHeaders headers, - HttpServletRequest req, - Action action, - String authPolicyFunctionName) throws Exception { - - SearchDbServiceAuth serviceAuth = new SearchDbServiceAuth(); - - String cipherSuite = (String) req.getAttribute("javax.servlet.request.cipher_suite"); - String authUser = null; - if (cipherSuite != null) { - Object x509CertAttribute = req.getAttribute("javax.servlet.request.X509Certificate"); - if (x509CertAttribute != null) { - X509Certificate[] certChain = (X509Certificate[]) x509CertAttribute; - X509Certificate clientCert = certChain[0]; - X500Principal subjectDn = clientCert.getSubjectX500Principal(); - authUser = subjectDn.toString(); - } + /** + * The Data Access Object that we will use to interact with the document store. + */ + protected DocumentStoreInterface documentStore = null; + protected ApiUtils apiUtils = null; + + /** + * Create a new instance of the end point. + */ + public SearchServiceApi() { + + // Perform one-time initialization. + init(); } - if (authUser == null) { - return false; + + /** + * 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"}) + public ResponseEntity<String> processCreateIndex(@RequestBody String requestBody, HttpServletRequest request, + @RequestHeader HttpHeaders headers, @PathVariable("index") String index) { + + // Forward the request to our index API to create the index. + IndexApi indexApi = new IndexApi(this); + return indexApi.processCreateIndex(requestBody, request, headers, index, documentStore); + } + + @RequestMapping(value = "/indexes/{index}", method = RequestMethod.DELETE, consumes = {"application/json"}, + produces = {"application/json"}) + public ResponseEntity<String> processDeleteIndex(HttpServletRequest request, @RequestHeader HttpHeaders headers, + @PathVariable("index") String index) { + + // Forward the request to our index API to delete the index. + IndexApi indexApi = new IndexApi(this); + return indexApi.processDelete(index, request, headers, documentStore); + } + + + @RequestMapping(value = "/indexes/{index}/documents", method = RequestMethod.POST, consumes = {"application/json"}) + public ResponseEntity<String> processCreateDocWithoutId(@RequestBody String requestBody, HttpServletRequest request, + HttpServletResponse httpResponse, @RequestHeader HttpHeaders headers, @PathVariable("index") String index) { + + // Forward the request to our document API to create the document. + DocumentApi documentApi = new DocumentApi(this); + return documentApi.processPost(requestBody, request, headers, httpResponse, index, documentStore); + } + + @RequestMapping(value = "/indexes/{index}/documents/{id}", method = RequestMethod.PUT, + consumes = {"application/json"}) + public ResponseEntity<String> processUpsertDoc(@RequestBody String requestBody, HttpServletRequest request, + HttpServletResponse httpResponse, @RequestHeader HttpHeaders headers, @PathVariable("index") String index, + @PathVariable("id") String id) { + + // Forward the request to our document API to upsert the document. + DocumentApi documentApi = new DocumentApi(this); + return documentApi.processPut(requestBody, request, headers, httpResponse, index, id, documentStore); + } + + @RequestMapping(value = "/indexes/{index}/documents/{id}", method = RequestMethod.GET) + public ResponseEntity<String> processGetDocument(HttpServletRequest request, HttpServletResponse httpResponse, + @RequestHeader HttpHeaders headers, @PathVariable("index") String index, @PathVariable("id") String id) { + + // Forward the request to our document API to retrieve the document. + DocumentApi documentApi = new DocumentApi(this); + return documentApi.processGet("", request, headers, httpResponse, index, id, documentStore); } - String status = serviceAuth.authUser(headers, authUser.toLowerCase(), - action.toString() + ":" + authPolicyFunctionName); - if (!status.equals("OK")) { - return false; + @RequestMapping(value = "/indexes/{index}/documents/{id}", method = RequestMethod.DELETE, + consumes = {"application/json"}) + public ResponseEntity<String> processDeleteDoc(HttpServletRequest request, HttpServletResponse httpResponse, + @RequestHeader HttpHeaders headers, @PathVariable("index") String index, @PathVariable("id") String id) { + + // Forward the request to our document API to delete the document. + DocumentApi documentApi = new DocumentApi(this); + return documentApi.processDelete("", request, headers, httpResponse, index, id, documentStore); + } + + @RequestMapping(value = "/indexes/{index}/query/{queryText}", method = RequestMethod.GET) + public ResponseEntity<String> processInlineQuery(HttpServletRequest request, @RequestHeader HttpHeaders headers, + @PathVariable("index") String index, @PathVariable("queryText") String queryText) { + + // Forward the request to our document API to delete the document. + DocumentApi documentApi = new DocumentApi(this); + return documentApi.processSearchWithGet("", request, headers, index, queryText, documentStore); + } + + @RequestMapping(value = "/indexes/{index}/query", method = RequestMethod.GET, consumes = {"application/json"}) + public ResponseEntity<String> processQueryWithGet(@RequestBody String requestBody, HttpServletRequest request, + @RequestHeader HttpHeaders headers, @PathVariable("index") String index) { + + // Forward the request to our document API to delete the document. + DocumentApi documentApi = new DocumentApi(this); + return documentApi.queryWithGetWithPayload(requestBody, request, headers, index, documentStore); + } + + @RequestMapping(value = "/indexes/{index}/query", method = RequestMethod.POST, consumes = {"application/json"}) + public ResponseEntity<String> processQuery(@RequestBody String requestBody, HttpServletRequest request, + @RequestHeader HttpHeaders headers, @PathVariable("index") String index) { + + // Forward the request to our document API to delete the document. + DocumentApi documentApi = new DocumentApi(this); + return documentApi.processSearchWithPost(requestBody, request, headers, index, documentStore); } - return true; - } + @RequestMapping(value = "/indexes/{index}/suggest", method = RequestMethod.POST, consumes = {"application/json"}) + public ResponseEntity<String> processSuggestQuery(@RequestBody String requestBody, HttpServletRequest request, + @RequestHeader HttpHeaders headers, @PathVariable("index") String index) { + // Forward the request to our document API to query suggestions in the + // document. + DocumentApi documentApi = new DocumentApi(this); + return documentApi.processSuggestQueryWithPost(requestBody, request, headers, index, documentStore); + } + + @RequestMapping(value = "/indexes/dynamic/{index}", method = RequestMethod.PUT, consumes = {"application/json"}) + public ResponseEntity<String> processCreateDynamicIndex(@RequestBody String requestBody, HttpServletRequest request, + @RequestHeader HttpHeaders headers, @PathVariable("index") String index) { + + // Forward the request to our index API to create the index. + IndexApi indexApi = new IndexApi(this); + return indexApi.processCreateDynamicIndex(requestBody, request, headers, index, documentStore); + } + + @RequestMapping(value = "/bulk", method = RequestMethod.POST, consumes = {"application/json"}, + produces = {"application/json"}) + public ResponseEntity<String> processBulkRequest(@RequestBody String requestBody, HttpServletRequest request, + @RequestHeader HttpHeaders headers) { + + // 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; + } + + protected boolean validateRequest(HttpHeaders headers, HttpServletRequest req, Action action, + String authPolicyFunctionName) throws Exception { + + SearchDbServiceAuth serviceAuth = new SearchDbServiceAuth(); + + String cipherSuite = (String) req.getAttribute("javax.servlet.request.cipher_suite"); + String authUser = null; + if (cipherSuite != null) { + Object x509CertAttribute = req.getAttribute("javax.servlet.request.X509Certificate"); + if (x509CertAttribute != null) { + X509Certificate[] certChain = (X509Certificate[]) x509CertAttribute; + X509Certificate clientCert = certChain[0]; + X500Principal subjectDn = clientCert.getSubjectX500Principal(); + authUser = subjectDn.toString(); + } + } + + if (authUser == null) { + return false; + } + + String status = + serviceAuth.authUser(headers, authUser.toLowerCase(), action.toString() + ":" + authPolicyFunctionName); + if (!status.equals("OK")) { + return false; + } + + return true; + } } 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 1cbebc9..d92a1da 100644 --- a/src/main/java/org/onap/aai/sa/searchdbabstraction/RestEchoService.java +++ b/src/main/java/org/onap/aai/sa/searchdbabstraction/RestEchoService.java @@ -35,15 +35,15 @@ import org.springframework.web.bind.annotation.RestController; @RequestMapping("/services/search-data-service/v1") public class RestEchoService { - /** - * REST endpoint for a simple echo service. - * - * @param input - The value to be echoed back. - * @return - The input value. - */ - @RequestMapping(value = "/echo/{input}", method = {RequestMethod.GET}) - public String ping(@PathVariable("input") String input) { - return "[Search Database Abstraction Micro Service] - Echo Service: " + input + "."; - } + /** + * REST endpoint for a simple echo service. + * + * @param input - The value to be echoed back. + * @return - The input value. + */ + @RequestMapping(value = "/echo/{input}", method = {RequestMethod.GET}) + public String ping(@PathVariable("input") String input) { + return "[Search Database Abstraction Micro Service] - Echo Service: " + input + "."; + } } diff --git a/src/main/java/org/onap/aai/sa/searchdbabstraction/elasticsearch/config/ElasticSearchConfig.java b/src/main/java/org/onap/aai/sa/searchdbabstraction/elasticsearch/config/ElasticSearchConfig.java index 0cf2f2a..1bf1db7 100644 --- a/src/main/java/org/onap/aai/sa/searchdbabstraction/elasticsearch/config/ElasticSearchConfig.java +++ b/src/main/java/org/onap/aai/sa/searchdbabstraction/elasticsearch/config/ElasticSearchConfig.java @@ -23,61 +23,61 @@ package org.onap.aai.sa.searchdbabstraction.elasticsearch.config; import java.util.Properties; public class ElasticSearchConfig { - private String ipAddress; - private String httpPort; - private String javaApiPort; - private String clusterName; + private String ipAddress; + private String httpPort; + private String javaApiPort; + private String clusterName; - public static final String ES_CLUSTER_NAME = "es.cluster-name"; - public static final String ES_IP_ADDRESS = "es.ip-address"; - public static final String ES_HTTP_PORT = "es.http-port"; + public static final String ES_CLUSTER_NAME = "es.cluster-name"; + public static final String ES_IP_ADDRESS = "es.ip-address"; + public static final String ES_HTTP_PORT = "es.http-port"; - private static final String JAVA_API_PORT_DEFAULT = "9300"; + private static final String JAVA_API_PORT_DEFAULT = "9300"; - public ElasticSearchConfig(Properties props) { + public ElasticSearchConfig(Properties props) { - setClusterName(props.getProperty(ES_CLUSTER_NAME)); - setIpAddress(props.getProperty(ES_IP_ADDRESS)); - setHttpPort(props.getProperty(ES_HTTP_PORT)); - setJavaApiPort(JAVA_API_PORT_DEFAULT); - } + setClusterName(props.getProperty(ES_CLUSTER_NAME)); + setIpAddress(props.getProperty(ES_IP_ADDRESS)); + setHttpPort(props.getProperty(ES_HTTP_PORT)); + setJavaApiPort(JAVA_API_PORT_DEFAULT); + } - public String getIpAddress() { - return ipAddress; - } + public String getIpAddress() { + return ipAddress; + } - public void setIpAddress(String ipAddress) { - this.ipAddress = ipAddress; - } + public void setIpAddress(String ipAddress) { + this.ipAddress = ipAddress; + } - public String getHttpPort() { - return httpPort; - } + public String getHttpPort() { + return httpPort; + } - public void setHttpPort(String httpPort) { - this.httpPort = httpPort; - } + public void setHttpPort(String httpPort) { + this.httpPort = httpPort; + } - public String getJavaApiPort() { - return javaApiPort; - } + public String getJavaApiPort() { + return javaApiPort; + } - public void setJavaApiPort(String javaApiPort) { - this.javaApiPort = javaApiPort; - } + public void setJavaApiPort(String javaApiPort) { + this.javaApiPort = javaApiPort; + } - public String getClusterName() { - return clusterName; - } + public String getClusterName() { + return clusterName; + } - public void setClusterName(String clusterName) { - this.clusterName = clusterName; - } + public void setClusterName(String clusterName) { + this.clusterName = clusterName; + } - @Override - public String toString() { - return "ElasticSearchConfig [ipAddress=" + ipAddress + ", httpPort=" + httpPort - + ", javaApiPort=" + javaApiPort + ", clusterName=" + clusterName + "]"; - } + @Override + public String toString() { + return "ElasticSearchConfig [ipAddress=" + ipAddress + ", httpPort=" + httpPort + ", javaApiPort=" + javaApiPort + + ", clusterName=" + clusterName + "]"; + } -}
\ No newline at end of file +} diff --git a/src/main/java/org/onap/aai/sa/searchdbabstraction/elasticsearch/dao/DocumentStoreDataEntity.java b/src/main/java/org/onap/aai/sa/searchdbabstraction/elasticsearch/dao/DocumentStoreDataEntity.java index 116e784..3d95a1b 100644 --- a/src/main/java/org/onap/aai/sa/searchdbabstraction/elasticsearch/dao/DocumentStoreDataEntity.java +++ b/src/main/java/org/onap/aai/sa/searchdbabstraction/elasticsearch/dao/DocumentStoreDataEntity.java @@ -22,10 +22,10 @@ package org.onap.aai.sa.searchdbabstraction.elasticsearch.dao; public interface DocumentStoreDataEntity { - public String getId(); + public String getId(); - public String getContentInJson(); + public String getContentInJson(); - public String getVersion(); + public String getVersion(); } diff --git a/src/main/java/org/onap/aai/sa/searchdbabstraction/elasticsearch/dao/DocumentStoreDataEntityImpl.java b/src/main/java/org/onap/aai/sa/searchdbabstraction/elasticsearch/dao/DocumentStoreDataEntityImpl.java index 352c01d..413dbb4 100644 --- a/src/main/java/org/onap/aai/sa/searchdbabstraction/elasticsearch/dao/DocumentStoreDataEntityImpl.java +++ b/src/main/java/org/onap/aai/sa/searchdbabstraction/elasticsearch/dao/DocumentStoreDataEntityImpl.java @@ -22,39 +22,39 @@ package org.onap.aai.sa.searchdbabstraction.elasticsearch.dao; public class DocumentStoreDataEntityImpl implements DocumentStoreDataEntity { - private String id; - private String content; - private String version; - - public String getContent() { - return content; - } - - public void setContent(String content) { - this.content = content; - } - - public void setId(String id) { - this.id = id; - } - - @Override - public String getId() { - return id; - } - - @Override - public String getContentInJson() { - return content; - } - - @Override - public String getVersion() { - return version; - } - - public void setVersion(String version) { - this.version = version; - } + private String id; + private String content; + private String version; + + public String getContent() { + return content; + } + + public void setContent(String content) { + this.content = content; + } + + public void setId(String id) { + this.id = id; + } + + @Override + public String getId() { + return id; + } + + @Override + public String getContentInJson() { + return content; + } + + @Override + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } } diff --git a/src/main/java/org/onap/aai/sa/searchdbabstraction/elasticsearch/dao/DocumentStoreInterface.java b/src/main/java/org/onap/aai/sa/searchdbabstraction/elasticsearch/dao/DocumentStoreInterface.java index 5eaf9a3..5ea37e1 100644 --- a/src/main/java/org/onap/aai/sa/searchdbabstraction/elasticsearch/dao/DocumentStoreInterface.java +++ b/src/main/java/org/onap/aai/sa/searchdbabstraction/elasticsearch/dao/DocumentStoreInterface.java @@ -31,45 +31,40 @@ import org.onap.aai.sa.searchdbabstraction.entity.SearchOperationResult; public interface DocumentStoreInterface { - public OperationResult createIndex(String index, DocumentSchema documentSchema); + public OperationResult createIndex(String index, DocumentSchema documentSchema); - public OperationResult createDynamicIndex(String index, String dynamicSchema); + public OperationResult createDynamicIndex(String index, String dynamicSchema); - public OperationResult deleteIndex(String indexName) throws DocumentStoreOperationException; + public OperationResult deleteIndex(String indexName) throws DocumentStoreOperationException; - public DocumentOperationResult createDocument(String indexName, - DocumentStoreDataEntity document, - boolean allowImplicitIndexCreation) throws DocumentStoreOperationException; + public DocumentOperationResult createDocument(String indexName, DocumentStoreDataEntity document, + boolean allowImplicitIndexCreation) throws DocumentStoreOperationException; - public DocumentOperationResult updateDocument(String indexName, - DocumentStoreDataEntity document, - boolean allowImplicitIndexCreation) throws DocumentStoreOperationException; + public DocumentOperationResult updateDocument(String indexName, DocumentStoreDataEntity document, + boolean allowImplicitIndexCreation) throws DocumentStoreOperationException; - public SearchOperationResult suggestionQueryWithPayload(String indexName, String query) throws DocumentStoreOperationException; + public SearchOperationResult suggestionQueryWithPayload(String indexName, String query) + throws DocumentStoreOperationException; - public DocumentOperationResult deleteDocument(String indexName, DocumentStoreDataEntity document) - throws DocumentStoreOperationException; + public DocumentOperationResult deleteDocument(String indexName, DocumentStoreDataEntity document) + throws DocumentStoreOperationException; - public DocumentOperationResult getDocument(String indexName, DocumentStoreDataEntity document) - throws DocumentStoreOperationException; + public DocumentOperationResult getDocument(String indexName, DocumentStoreDataEntity document) + throws DocumentStoreOperationException; - public SearchOperationResult search(String indexName, String queryText) - throws DocumentStoreOperationException; + public SearchOperationResult search(String indexName, String queryText) throws DocumentStoreOperationException; - public SearchOperationResult searchWithPayload(String indexName, String query) - throws DocumentStoreOperationException; + public SearchOperationResult searchWithPayload(String indexName, String query) + throws DocumentStoreOperationException; - /** - * Forwards a set of operations to the document store as a single, bulk - * request. - * - * @param anIndex - The index to apply the operations to. - * @param operations - A java object containing the set of operations to - * be performed. - * @return - An operation result. - * @throws DocumentStoreOperationException - */ - public OperationResult performBulkOperations(BulkRequest[] request) - throws DocumentStoreOperationException; + /** + * Forwards a set of operations to the document store as a single, bulk request. + * + * @param anIndex - The index to apply the operations to. + * @param operations - A java object containing the set of operations to be performed. + * @return - An operation result. + * @throws DocumentStoreOperationException + */ + public OperationResult performBulkOperations(BulkRequest[] request) throws DocumentStoreOperationException; } diff --git a/src/main/java/org/onap/aai/sa/searchdbabstraction/elasticsearch/dao/ElasticSearchBulkOperationResult.java b/src/main/java/org/onap/aai/sa/searchdbabstraction/elasticsearch/dao/ElasticSearchBulkOperationResult.java index d1e5fd3..23181df 100644 --- a/src/main/java/org/onap/aai/sa/searchdbabstraction/elasticsearch/dao/ElasticSearchBulkOperationResult.java +++ b/src/main/java/org/onap/aai/sa/searchdbabstraction/elasticsearch/dao/ElasticSearchBulkOperationResult.java @@ -24,43 +24,43 @@ import java.util.Arrays; public class ElasticSearchBulkOperationResult { - private Integer took; - private Boolean errors; - private ElasticSearchResultItem[] items; + private Integer took; + private Boolean errors; + private ElasticSearchResultItem[] items; - public ElasticSearchBulkOperationResult() { + public ElasticSearchBulkOperationResult() { - } + } - public ElasticSearchResultItem[] getItems() { - return items; - } + public ElasticSearchResultItem[] getItems() { + return items; + } - public void setItems(ElasticSearchResultItem[] items) { - this.items = items; - } + public void setItems(ElasticSearchResultItem[] items) { + this.items = items; + } - public Integer getTook() { - return took; - } + public Integer getTook() { + return took; + } - public void setTook(Integer took) { - this.took = took; - } + public void setTook(Integer took) { + this.took = took; + } - public Boolean getErrors() { - return errors; - } + public Boolean getErrors() { + return errors; + } - public void setErrors(Boolean errors) { - this.errors = errors; - } + public void setErrors(Boolean errors) { + this.errors = errors; + } - @Override - public String toString() { - return "ElasticSearchOperationResult [took=" + took + ", errors=" - + errors + ", items=" + Arrays.toString(items) + "]"; - } + @Override + public String toString() { + return "ElasticSearchOperationResult [took=" + took + ", errors=" + errors + ", items=" + Arrays.toString(items) + + "]"; + } } diff --git a/src/main/java/org/onap/aai/sa/searchdbabstraction/elasticsearch/dao/ElasticSearchCause.java b/src/main/java/org/onap/aai/sa/searchdbabstraction/elasticsearch/dao/ElasticSearchCause.java index 7036440..ee12494 100644 --- a/src/main/java/org/onap/aai/sa/searchdbabstraction/elasticsearch/dao/ElasticSearchCause.java +++ b/src/main/java/org/onap/aai/sa/searchdbabstraction/elasticsearch/dao/ElasticSearchCause.java @@ -22,22 +22,22 @@ package org.onap.aai.sa.searchdbabstraction.elasticsearch.dao; public class ElasticSearchCause { - private String type; - private String reason; + private String type; + private String reason; - public String getType() { - return type; - } + public String getType() { + return type; + } - public void setType(String type) { - this.type = type; - } + public void setType(String type) { + this.type = type; + } - public String getReason() { - return reason; - } + public String getReason() { + return reason; + } - public void setReason(String reason) { - this.reason = reason; - } + public void setReason(String reason) { + this.reason = reason; + } } diff --git a/src/main/java/org/onap/aai/sa/searchdbabstraction/elasticsearch/dao/ElasticSearchError.java b/src/main/java/org/onap/aai/sa/searchdbabstraction/elasticsearch/dao/ElasticSearchError.java index 27493a0..afb1da3 100644 --- a/src/main/java/org/onap/aai/sa/searchdbabstraction/elasticsearch/dao/ElasticSearchError.java +++ b/src/main/java/org/onap/aai/sa/searchdbabstraction/elasticsearch/dao/ElasticSearchError.java @@ -27,44 +27,44 @@ import java.util.Map; public class ElasticSearchError { - private String type; - private String reason; - private ElasticSearchCause causedBy; + private String type; + private String reason; + private ElasticSearchCause causedBy; - private Map<String, Object> additionalProperties = new HashMap<String, Object>(); + private Map<String, Object> additionalProperties = new HashMap<String, Object>(); - public String getType() { - return type; - } + public String getType() { + return type; + } - public void setType(String type) { - this.type = type; - } + public void setType(String type) { + this.type = type; + } - public String getReason() { - return reason; - } + public String getReason() { + return reason; + } - public void setReason(String reason) { - this.reason = reason; - } + public void setReason(String reason) { + this.reason = reason; + } - public ElasticSearchCause getCausedBy() { - return causedBy; - } + public ElasticSearchCause getCausedBy() { + return causedBy; + } - public void setCausedBy(ElasticSearchCause causedBy) { - this.causedBy = causedBy; - } + public void setCausedBy(ElasticSearchCause causedBy) { + this.causedBy = causedBy; + } - @JsonAnyGetter - public Map<String, Object> getAdditionalProperties() { - return additionalProperties; - } + @JsonAnyGetter + public Map<String, Object> getAdditionalProperties() { + return additionalProperties; + } - @JsonAnySetter - public void setAdditionalProperties(String name, Object value) { - additionalProperties.put(name, value); - } + @JsonAnySetter + public void setAdditionalProperties(String name, Object value) { + additionalProperties.put(name, value); + } } diff --git a/src/main/java/org/onap/aai/sa/searchdbabstraction/elasticsearch/dao/ElasticSearchOperationStatus.java b/src/main/java/org/onap/aai/sa/searchdbabstraction/elasticsearch/dao/ElasticSearchOperationStatus.java index 8ad1ba8..a0941e7 100644 --- a/src/main/java/org/onap/aai/sa/searchdbabstraction/elasticsearch/dao/ElasticSearchOperationStatus.java +++ b/src/main/java/org/onap/aai/sa/searchdbabstraction/elasticsearch/dao/ElasticSearchOperationStatus.java @@ -27,88 +27,88 @@ import java.util.Map; public class ElasticSearchOperationStatus { - private String index; - private String type; - private String id; - private String version; - private ElasticSearchShardStatus shards; - private Integer status; - private ElasticSearchError error; - - private Map<String, Object> additionalProperties = new HashMap<String, Object>(); - - - public ElasticSearchError getError() { - return error; - } - - public void setError(ElasticSearchError error) { - this.error = error; - } - - public Integer getStatus() { - return status; - } - - public void setStatus(Integer status) { - this.status = status; - } - - public ElasticSearchShardStatus getShards() { - return shards; - } - - public void setShards(ElasticSearchShardStatus shards) { - this.shards = shards; - } - - public String getIndex() { - return index; - } - - public void setIndex(String index) { - this.index = index; - } - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public String getVersion() { - return version; - } - - public void setVersion(String version) { - this.version = version; - } - - @JsonAnyGetter - public Map<String, Object> getAdditionalProperties() { - return additionalProperties; - } - - @JsonAnySetter - public void setAdditionalProperties(String name, Object value) { - additionalProperties.put(name, value); - } - - @Override - public String toString() { - return "ElasticSearchIndexStatus [index=" + index + ", type=" + type + ", id=" - + id + ", version=" + version + ", shards=" + shards + ", status=" + status + "]"; - } + private String index; + private String type; + private String id; + private String version; + private ElasticSearchShardStatus shards; + private Integer status; + private ElasticSearchError error; + + private Map<String, Object> additionalProperties = new HashMap<String, Object>(); + + + public ElasticSearchError getError() { + return error; + } + + public void setError(ElasticSearchError error) { + this.error = error; + } + + public Integer getStatus() { + return status; + } + + public void setStatus(Integer status) { + this.status = status; + } + + public ElasticSearchShardStatus getShards() { + return shards; + } + + public void setShards(ElasticSearchShardStatus shards) { + this.shards = shards; + } + + public String getIndex() { + return index; + } + + public void setIndex(String index) { + this.index = index; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + @JsonAnyGetter + public Map<String, Object> getAdditionalProperties() { + return additionalProperties; + } + + @JsonAnySetter + public void setAdditionalProperties(String name, Object value) { + additionalProperties.put(name, value); + } + + @Override + public String toString() { + return "ElasticSearchIndexStatus [index=" + index + ", type=" + type + ", id=" + id + ", version=" + version + + ", shards=" + shards + ", status=" + status + "]"; + } } diff --git a/src/main/java/org/onap/aai/sa/searchdbabstraction/elasticsearch/dao/ElasticSearchResultItem.java b/src/main/java/org/onap/aai/sa/searchdbabstraction/elasticsearch/dao/ElasticSearchResultItem.java index f59805e..529900d 100644 --- a/src/main/java/org/onap/aai/sa/searchdbabstraction/elasticsearch/dao/ElasticSearchResultItem.java +++ b/src/main/java/org/onap/aai/sa/searchdbabstraction/elasticsearch/dao/ElasticSearchResultItem.java @@ -24,125 +24,126 @@ import org.onap.aai.sa.rest.ApiUtils; public class ElasticSearchResultItem { - public static final String REQUEST_URL = "REQUEST_URL"; + public static final String REQUEST_URL = "REQUEST_URL"; - private ElasticSearchOperationStatus create; - private ElasticSearchOperationStatus index; - private ElasticSearchOperationStatus delete; + private ElasticSearchOperationStatus create; + private ElasticSearchOperationStatus index; + private ElasticSearchOperationStatus delete; - public ElasticSearchOperationStatus getCreate() { - return create; - } - - public void setCreate(ElasticSearchOperationStatus index) { - this.create = index; - } - - public ElasticSearchOperationStatus getIndex() { - return index; - } - - public void setIndex(ElasticSearchOperationStatus index) { - this.index = index; - } - - public ElasticSearchOperationStatus getDelete() { - return delete; - } - - public void setDelete(ElasticSearchOperationStatus delete) { - this.delete = delete; - } - - public String operationType() { - - if (create != null) { - return "create"; - } - if (index != null) { - return "update"; - } - if (delete != null) { - return "delete"; + public ElasticSearchOperationStatus getCreate() { + return create; } - return "unknown"; - } - - public ElasticSearchOperationStatus operationStatus() { + public void setCreate(ElasticSearchOperationStatus index) { + this.create = index; + } - if (create != null) { - return create; + public ElasticSearchOperationStatus getIndex() { + return index; } - if (index != null) { - return index; + + public void setIndex(ElasticSearchOperationStatus index) { + this.index = index; } - if (delete != null) { - return delete; + + public ElasticSearchOperationStatus getDelete() { + return delete; } - return null; - } + public void setDelete(ElasticSearchOperationStatus delete) { + this.delete = delete; + } + public String operationType() { - public String toJson() { - StringBuilder sb = new StringBuilder(); + if (create != null) { + return "create"; + } + if (index != null) { + return "update"; + } + if (delete != null) { + return "delete"; + } - sb.append("{"); + return "unknown"; + } - sb.append("\"operation\": \"").append(operationType()).append("\", "); + public ElasticSearchOperationStatus operationStatus() { - if (operationStatus().getAdditionalProperties().containsKey(REQUEST_URL)) { - sb.append("\"url\": \"").append(operationStatus().getAdditionalProperties() - .get(REQUEST_URL)).append("\", "); - } else { - sb.append("\"url\": \"").append(ApiUtils.buildDocumentUri(operationStatus() - .getIndex(), operationStatus().getId())).append("\", "); - } + if (create != null) { + return create; + } + if (index != null) { + return index; + } + if (delete != null) { + return delete; + } - // We don't want to include an etag field in the response in - // the case of a delete, since that would imply that the client - // could still access that version of the file in some manner - // (which we are not supporting). - if (!operationType().equals("delete")) { - sb.append("\"etag\": \"").append(operationStatus().getVersion()).append("\", "); + return null; } - sb.append("\"status-code\": \"").append(operationStatus().getStatus()).append("\", "); - - sb.append("\"status-message\": \""); - - if ((operationStatus().getStatus() >= 200) && (operationStatus().getStatus() < 300)) { - sb.append("OK"); - } else { - // Sometimes the error object doesn't get populated, so check - // before we try to reference it... - if (operationStatus().getError() != null) { - sb.append(operationStatus().getError().getReason()); - } else { - sb.append(""); - } - } - sb.append("\""); - sb.append("}"); - return sb.toString(); - } + public String toJson() { + StringBuilder sb = new StringBuilder(); + + sb.append("{"); + + sb.append("\"operation\": \"").append(operationType()).append("\", "); + + if (operationStatus().getAdditionalProperties().containsKey(REQUEST_URL)) { + sb.append("\"url\": \"").append(operationStatus().getAdditionalProperties().get(REQUEST_URL)) + .append("\", "); + } else { + sb.append("\"url\": \"") + .append(ApiUtils.buildDocumentUri(operationStatus().getIndex(), operationStatus().getId())) + .append("\", "); + } + + // We don't want to include an etag field in the response in + // the case of a delete, since that would imply that the client + // could still access that version of the file in some manner + // (which we are not supporting). + if (!operationType().equals("delete")) { + sb.append("\"etag\": \"").append(operationStatus().getVersion()).append("\", "); + } + sb.append("\"status-code\": \"").append(operationStatus().getStatus()).append("\", "); + + sb.append("\"status-message\": \""); + + if ((operationStatus().getStatus() >= 200) && (operationStatus().getStatus() < 300)) { + sb.append("OK"); + } else { + // Sometimes the error object doesn't get populated, so check + // before we try to reference it... + if (operationStatus().getError() != null) { + sb.append(operationStatus().getError().getReason()); + } else { + sb.append(""); + } + } + sb.append("\""); + sb.append("}"); + + return sb.toString(); + } - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("ElasticSearchItemStatus ["); - if (create != null) { - sb.append("create " + create); - } else if (index != null) { - sb.append("index " + index); - } else if (delete != null) { - sb.append("delete " + index); + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + + sb.append("ElasticSearchItemStatus ["); + if (create != null) { + sb.append("create " + create); + } else if (index != null) { + sb.append("index " + index); + } else if (delete != null) { + sb.append("delete " + index); + } + sb.append("]"); + return sb.toString(); } - sb.append("]"); - return sb.toString(); - } } diff --git a/src/main/java/org/onap/aai/sa/searchdbabstraction/elasticsearch/dao/ElasticSearchShardStatus.java b/src/main/java/org/onap/aai/sa/searchdbabstraction/elasticsearch/dao/ElasticSearchShardStatus.java index ee29728..e846a38 100644 --- a/src/main/java/org/onap/aai/sa/searchdbabstraction/elasticsearch/dao/ElasticSearchShardStatus.java +++ b/src/main/java/org/onap/aai/sa/searchdbabstraction/elasticsearch/dao/ElasticSearchShardStatus.java @@ -22,39 +22,38 @@ package org.onap.aai.sa.searchdbabstraction.elasticsearch.dao; public class ElasticSearchShardStatus { - private int total; - private int successful; - private int failed; - - public int getTotal() { - return total; - } - - public void setTotal(int total) { - this.total = total; - } - - public int getSuccessful() { - return successful; - } - - public void setSuccessful(int successful) { - this.successful = successful; - } - - public int getFailed() { - return failed; - } - - public void setFailed(int failed) { - this.failed = failed; - } - - @Override - public String toString() { - return "ElasticSearchShardStatus [total=" + total + ", successful=" + successful - + ", failed=" + failed + "]"; - } + private int total; + private int successful; + private int failed; + + public int getTotal() { + return total; + } + + public void setTotal(int total) { + this.total = total; + } + + public int getSuccessful() { + return successful; + } + + public void setSuccessful(int successful) { + this.successful = successful; + } + + public int getFailed() { + return failed; + } + + public void setFailed(int failed) { + this.failed = failed; + } + + @Override + public String toString() { + return "ElasticSearchShardStatus [total=" + total + ", successful=" + successful + ", failed=" + failed + "]"; + } } diff --git a/src/main/java/org/onap/aai/sa/searchdbabstraction/entity/AggregationBucket.java b/src/main/java/org/onap/aai/sa/searchdbabstraction/entity/AggregationBucket.java index 9edea09..ae0a3e9 100644 --- a/src/main/java/org/onap/aai/sa/searchdbabstraction/entity/AggregationBucket.java +++ b/src/main/java/org/onap/aai/sa/searchdbabstraction/entity/AggregationBucket.java @@ -24,52 +24,52 @@ import com.fasterxml.jackson.annotation.JsonProperty; import java.util.Arrays; public class AggregationBucket { - private Object key; + private Object key; - @JsonProperty("formatted-key") - private String formattedKey; + @JsonProperty("formatted-key") + private String formattedKey; - private Number count; + private Number count; - @JsonProperty("sub-aggregations") - private AggregationResult[] subAggregationResult; + @JsonProperty("sub-aggregations") + private AggregationResult[] subAggregationResult; - public Object getKey() { - return key; - } + public Object getKey() { + return key; + } - public void setKey(Object key) { - this.key = key; - } + public void setKey(Object key) { + this.key = key; + } - public String getFormattedKey() { - return formattedKey; - } + public String getFormattedKey() { + return formattedKey; + } - public void setFormattedKey(String formattedKey) { - this.formattedKey = formattedKey; - } + public void setFormattedKey(String formattedKey) { + this.formattedKey = formattedKey; + } - public Number getCount() { - return count; - } + public Number getCount() { + return count; + } - public void setCount(Number count) { - this.count = count; - } + public void setCount(Number count) { + this.count = count; + } - public AggregationResult[] getSubAggregationResult() { - return subAggregationResult; - } + public AggregationResult[] getSubAggregationResult() { + return subAggregationResult; + } - public void setSubAggregationResult(AggregationResult[] subAggregationResult) { - this.subAggregationResult = subAggregationResult; - } + public void setSubAggregationResult(AggregationResult[] subAggregationResult) { + this.subAggregationResult = subAggregationResult; + } - @Override - public String toString() { - return "AggregationBucket [key=" + key + ", formattedKey=" + formattedKey + ", count=" + count - + ", subAggregationResult=" + Arrays.toString(subAggregationResult) + "]"; - } + @Override + public String toString() { + return "AggregationBucket [key=" + key + ", formattedKey=" + formattedKey + ", count=" + count + + ", subAggregationResult=" + Arrays.toString(subAggregationResult) + "]"; + } } diff --git a/src/main/java/org/onap/aai/sa/searchdbabstraction/entity/AggregationResult.java b/src/main/java/org/onap/aai/sa/searchdbabstraction/entity/AggregationResult.java index 88d33b8..923afbf 100644 --- a/src/main/java/org/onap/aai/sa/searchdbabstraction/entity/AggregationResult.java +++ b/src/main/java/org/onap/aai/sa/searchdbabstraction/entity/AggregationResult.java @@ -24,52 +24,51 @@ import com.fasterxml.jackson.annotation.JsonProperty; import java.util.Arrays; public class AggregationResult { - private String name; + private String name; - private Number count; + private Number count; - private AggregationBucket[] buckets; + private AggregationBucket[] buckets; - @JsonProperty("nested-aggregations") - private AggregationResult[] nestedAggregations; + @JsonProperty("nested-aggregations") + private AggregationResult[] nestedAggregations; - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public AggregationBucket[] getBuckets() { - return buckets; - } + public AggregationBucket[] getBuckets() { + return buckets; + } - public void setBuckets(AggregationBucket[] buckets) { - this.buckets = buckets; - } + public void setBuckets(AggregationBucket[] buckets) { + this.buckets = buckets; + } - public AggregationResult[] getNestedAggregations() { - return nestedAggregations; - } + public AggregationResult[] getNestedAggregations() { + return nestedAggregations; + } - public void setNestedAggregations(AggregationResult[] nestedAggregations) { - this.nestedAggregations = nestedAggregations; - } + public void setNestedAggregations(AggregationResult[] nestedAggregations) { + this.nestedAggregations = nestedAggregations; + } - public Number getCount() { - return count; - } + public Number getCount() { + return count; + } - public void setCount(Number count) { - this.count = count; - } + public void setCount(Number count) { + this.count = count; + } - @Override - public String toString() { - return "AggregationResult [name=" + name + ", count=" + count + ", buckets=" - + Arrays.toString(buckets) + ", nestedAggregations=" + Arrays.toString(nestedAggregations) - + "]"; - } + @Override + public String toString() { + return "AggregationResult [name=" + name + ", count=" + count + ", buckets=" + Arrays.toString(buckets) + + ", nestedAggregations=" + Arrays.toString(nestedAggregations) + "]"; + } } diff --git a/src/main/java/org/onap/aai/sa/searchdbabstraction/entity/AggregationResults.java b/src/main/java/org/onap/aai/sa/searchdbabstraction/entity/AggregationResults.java index bb8d282..f8f3ed3 100644 --- a/src/main/java/org/onap/aai/sa/searchdbabstraction/entity/AggregationResults.java +++ b/src/main/java/org/onap/aai/sa/searchdbabstraction/entity/AggregationResults.java @@ -23,19 +23,19 @@ package org.onap.aai.sa.searchdbabstraction.entity; import java.util.Arrays; public class AggregationResults { - private AggregationResult[] aggregations; + private AggregationResult[] aggregations; - public AggregationResult[] getAggregations() { - return aggregations; - } + public AggregationResult[] getAggregations() { + return aggregations; + } - public void setAggregations(AggregationResult[] aggregations) { - this.aggregations = aggregations; - } + public void setAggregations(AggregationResult[] aggregations) { + this.aggregations = aggregations; + } - @Override - public String toString() { - return "AggregationResults [aggregations=" + Arrays.toString(aggregations) + "]"; - } + @Override + public String toString() { + return "AggregationResults [aggregations=" + Arrays.toString(aggregations) + "]"; + } } diff --git a/src/main/java/org/onap/aai/sa/searchdbabstraction/entity/Document.java b/src/main/java/org/onap/aai/sa/searchdbabstraction/entity/Document.java index ae512bd..8b7df43 100644 --- a/src/main/java/org/onap/aai/sa/searchdbabstraction/entity/Document.java +++ b/src/main/java/org/onap/aai/sa/searchdbabstraction/entity/Document.java @@ -23,39 +23,39 @@ package org.onap.aai.sa.searchdbabstraction.entity; import org.json.simple.JSONObject; public class Document { - private String etag; - private String url; + private String etag; + private String url; - private JSONObject content; + private JSONObject content; - public String getEtag() { - return etag; - } + public String getEtag() { + return etag; + } - public void setEtag(String etag) { - this.etag = etag; - } + public void setEtag(String etag) { + this.etag = etag; + } - public String getUrl() { - return url; - } + public String getUrl() { + return url; + } - public void setUrl(String url) { - this.url = url; - } + public void setUrl(String url) { + this.url = url; + } - public JSONObject getContent() { - return content; - } + public JSONObject getContent() { + return content; + } - public void setContent(JSONObject content) { - this.content = content; - } + public void setContent(JSONObject content) { + this.content = content; + } - @Override - public String toString() { - return "Document [etag=" + etag + ", url=" + url + "]"; - } + @Override + public String toString() { + return "Document [etag=" + etag + ", url=" + url + "]"; + } } diff --git a/src/main/java/org/onap/aai/sa/searchdbabstraction/entity/DocumentOperationResult.java b/src/main/java/org/onap/aai/sa/searchdbabstraction/entity/DocumentOperationResult.java index f22c41a..9775446 100644 --- a/src/main/java/org/onap/aai/sa/searchdbabstraction/entity/DocumentOperationResult.java +++ b/src/main/java/org/onap/aai/sa/searchdbabstraction/entity/DocumentOperationResult.java @@ -21,20 +21,20 @@ package org.onap.aai.sa.searchdbabstraction.entity; public class DocumentOperationResult extends OperationResult { - private Document document; + private Document document; - public Document getDocument() { - return document; - } + public Document getDocument() { + return document; + } - public void setDocument(Document document) { - this.document = document; - } + public void setDocument(Document document) { + this.document = document; + } - @Override - public String toString() { - return "DocumentOperationResult [document=" + document + "]"; - } + @Override + public String toString() { + return "DocumentOperationResult [document=" + document + "]"; + } } 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 26253b9..06c788a 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 @@ -22,35 +22,35 @@ package org.onap.aai.sa.searchdbabstraction.entity; public class ErrorResult { - private String type; - private String reason; + private String type; + private String reason; - public ErrorResult(String type, String reason) { - super(); - this.type = type; - this.reason = reason; - } + public ErrorResult(String type, String reason) { + super(); + this.type = type; + this.reason = reason; + } - public String getType() { - return type; - } + public String getType() { + return type; + } - public void setType(String type) { - this.type = type; - } + public void setType(String type) { + this.type = type; + } - public String getReason() { - return reason; - } + public String getReason() { + return reason; + } - public void setReason(String reason) { - this.reason = reason; - } + public void setReason(String reason) { + this.reason = reason; + } - @Override - public String toString() { - return "ErrorResponse [type=" + type + ", reason=" + reason + "]"; - } + @Override + public String toString() { + return "ErrorResponse [type=" + type + ", reason=" + reason + "]"; + } } diff --git a/src/main/java/org/onap/aai/sa/searchdbabstraction/entity/OperationResult.java b/src/main/java/org/onap/aai/sa/searchdbabstraction/entity/OperationResult.java index 3545818..0d3a8bb 100644 --- a/src/main/java/org/onap/aai/sa/searchdbabstraction/entity/OperationResult.java +++ b/src/main/java/org/onap/aai/sa/searchdbabstraction/entity/OperationResult.java @@ -22,57 +22,57 @@ package org.onap.aai.sa.searchdbabstraction.entity; public class OperationResult { - private int resultCode; + private int resultCode; - private String failureCause; - private String resultVersion; - private String result; - private ErrorResult error; + private String failureCause; + private String resultVersion; + private String result; + private ErrorResult error; - public int getResultCode() { - return resultCode; - } + public int getResultCode() { + return resultCode; + } - public void setResultCode(int resultCode) { - this.resultCode = resultCode; - } + public void setResultCode(int resultCode) { + this.resultCode = resultCode; + } - public String getFailureCause() { - return failureCause; - } + public String getFailureCause() { + return failureCause; + } - public void setFailureCause(String failureCause) { - this.failureCause = failureCause; - } + public void setFailureCause(String failureCause) { + this.failureCause = failureCause; + } - public String getResultVersion() { - return resultVersion; - } + public String getResultVersion() { + return resultVersion; + } - public void setResultVersion(String resultVersion) { - this.resultVersion = resultVersion; - } + public void setResultVersion(String resultVersion) { + this.resultVersion = resultVersion; + } - public String getResult() { - return result; - } + public String getResult() { + return result; + } - public void setResult(String result) { - this.result = result; - } + public void setResult(String result) { + this.result = result; + } - public ErrorResult getError() { - return error; - } + public ErrorResult getError() { + return error; + } - public void setError(ErrorResult error) { - this.error = error; - } + public void setError(ErrorResult error) { + this.error = error; + } - @Override - public String toString() { - return "OperationResult [resultCode=" + resultCode + ", failureCause=" + failureCause - + ", resultVersion=" + resultVersion + ", result=" + result + ", error=" + error + "]"; - } + @Override + public String toString() { + return "OperationResult [resultCode=" + resultCode + ", failureCause=" + failureCause + ", resultVersion=" + + resultVersion + ", result=" + result + ", error=" + error + "]"; + } } diff --git a/src/main/java/org/onap/aai/sa/searchdbabstraction/entity/SearchHit.java b/src/main/java/org/onap/aai/sa/searchdbabstraction/entity/SearchHit.java index 1f4a5be..033dafe 100644 --- a/src/main/java/org/onap/aai/sa/searchdbabstraction/entity/SearchHit.java +++ b/src/main/java/org/onap/aai/sa/searchdbabstraction/entity/SearchHit.java @@ -21,28 +21,28 @@ package org.onap.aai.sa.searchdbabstraction.entity; public class SearchHit { - private String score; - Document document; + private String score; + Document document; - public String getScore() { - return score; - } + public String getScore() { + return score; + } - public void setScore(String score) { - this.score = score; - } + public void setScore(String score) { + this.score = score; + } - public Document getDocument() { - return document; - } + public Document getDocument() { + return document; + } - public void setDocument(Document document) { - this.document = document; - } + public void setDocument(Document document) { + this.document = document; + } - @Override - public String toString() { - return "SearchHit [score=" + score + ", document=" + document + "]"; - } + @Override + public String toString() { + return "SearchHit [score=" + score + ", document=" + document + "]"; + } } diff --git a/src/main/java/org/onap/aai/sa/searchdbabstraction/entity/SearchHits.java b/src/main/java/org/onap/aai/sa/searchdbabstraction/entity/SearchHits.java index f3fefe7..cf4fd3a 100644 --- a/src/main/java/org/onap/aai/sa/searchdbabstraction/entity/SearchHits.java +++ b/src/main/java/org/onap/aai/sa/searchdbabstraction/entity/SearchHits.java @@ -23,28 +23,28 @@ package org.onap.aai.sa.searchdbabstraction.entity; import java.util.Arrays; public class SearchHits { - private String totalHits; - private SearchHit[] hits; + private String totalHits; + private SearchHit[] hits; - public String getTotalHits() { - return totalHits; - } + public String getTotalHits() { + return totalHits; + } - public void setTotalHits(String totalHits) { - this.totalHits = totalHits; - } + public void setTotalHits(String totalHits) { + this.totalHits = totalHits; + } - public SearchHit[] getHits() { - return hits; - } + public SearchHit[] getHits() { + return hits; + } - public void setHits(SearchHit[] hits) { - this.hits = hits; - } + public void setHits(SearchHit[] hits) { + this.hits = hits; + } - @Override - public String toString() { - return "SearchHits [totalHits=" + totalHits + ", hits=" + Arrays.toString(hits) + "]"; - } + @Override + public String toString() { + return "SearchHits [totalHits=" + totalHits + ", hits=" + Arrays.toString(hits) + "]"; + } } diff --git a/src/main/java/org/onap/aai/sa/searchdbabstraction/entity/SearchOperationResult.java b/src/main/java/org/onap/aai/sa/searchdbabstraction/entity/SearchOperationResult.java index cdb9ee3..6834d33 100644 --- a/src/main/java/org/onap/aai/sa/searchdbabstraction/entity/SearchOperationResult.java +++ b/src/main/java/org/onap/aai/sa/searchdbabstraction/entity/SearchOperationResult.java @@ -22,36 +22,38 @@ package org.onap.aai.sa.searchdbabstraction.entity; public class SearchOperationResult extends OperationResult { - private SearchHits searchResult; - private AggregationResults aggregationResult; - private SuggestHits suggestResult; - - public SearchHits getSearchResult() { - return searchResult; - } - - public SuggestHits getSuggestResult() { - return suggestResult; - } - - public AggregationResults getAggregationResult() { - return aggregationResult; - } - - public void setAggregationResult(AggregationResults aggregations) { - this.aggregationResult = aggregations; - } - - public void setSearchResult(SearchHits hits) { - this.searchResult = hits; - } - - public void setSuggestResult(SuggestHits hits) { this.suggestResult = hits; } - - @Override - public String toString() { - return "SearchOperationResult [searchResult=" + searchResult - + ", aggregationResult=" + aggregationResult + ", suggestResult=" + suggestResult; - } + private SearchHits searchResult; + private AggregationResults aggregationResult; + private SuggestHits suggestResult; + + public SearchHits getSearchResult() { + return searchResult; + } + + public SuggestHits getSuggestResult() { + return suggestResult; + } + + public AggregationResults getAggregationResult() { + return aggregationResult; + } + + public void setAggregationResult(AggregationResults aggregations) { + this.aggregationResult = aggregations; + } + + public void setSearchResult(SearchHits hits) { + this.searchResult = hits; + } + + public void setSuggestResult(SuggestHits hits) { + this.suggestResult = hits; + } + + @Override + public String toString() { + return "SearchOperationResult [searchResult=" + searchResult + ", aggregationResult=" + aggregationResult + + ", suggestResult=" + suggestResult; + } } diff --git a/src/main/java/org/onap/aai/sa/searchdbabstraction/entity/SuggestHit.java b/src/main/java/org/onap/aai/sa/searchdbabstraction/entity/SuggestHit.java index 82a6c93..4ce267d 100644 --- a/src/main/java/org/onap/aai/sa/searchdbabstraction/entity/SuggestHit.java +++ b/src/main/java/org/onap/aai/sa/searchdbabstraction/entity/SuggestHit.java @@ -18,7 +18,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.onap.aai.sa.searchdbabstraction.entity; +package org.onap.aai.sa.searchdbabstraction.entity; public class SuggestHit { @@ -54,4 +54,4 @@ public class SuggestHit { public String toString() { return "SearchHit [text=" + text + ",score=" + score + ", document=" + document + "]"; } -}
\ No newline at end of file +} diff --git a/src/main/java/org/onap/aai/sa/searchdbabstraction/logging/SearchDbMsgs.java b/src/main/java/org/onap/aai/sa/searchdbabstraction/logging/SearchDbMsgs.java index 9ba8fef..d38de2a 100644 --- a/src/main/java/org/onap/aai/sa/searchdbabstraction/logging/SearchDbMsgs.java +++ b/src/main/java/org/onap/aai/sa/searchdbabstraction/logging/SearchDbMsgs.java @@ -25,198 +25,158 @@ import org.onap.aai.cl.eelf.LogMessageEnum; public enum SearchDbMsgs implements LogMessageEnum { - /** - * Arguments: - * None - */ - SERVICE_STARTED, - - /** - * Arguments: - * {0} = url - */ - ELASTIC_SEARCH_CONNECTION_ATTEMPT, - - /** - * Arguments: - * {0} = url - */ - ELASTIC_SEARCH_CONNECTION_SUCCESS, - - /** - * Arguments: - * {0} = url - * {1} = failure cause - */ - ELASTIC_SEARCH_CONNECTION_FAILURE, - - /** - * Arguments: - * {0} = Filter configuration file. - * {1} = Failure cause. - */ - FILTERS_CONFIG_FAILURE, - - /** - * Arguments: - * {0} = Analysys configuration file. - * {1} = Failure case. - */ - ANALYSYS_CONFIG_FAILURE, - - /** - * Arguments: - * {0} = Index name - */ - CREATED_INDEX, - - /** - * Arguments: - * {0} = Index name - * {1} = Document type - */ - CREATE_INDEX_TIME, - - /** - * Arguments: - * {0} = Index name - */ - DELETED_INDEX, - - /** - * Arguments: - * {0} = Index name - */ - DELETE_INDEX_TIME, - - /** - * Arguments: - * {0} = Index name - */ - CHECK_INDEX_TIME, - - /** - * Arguments: - * {0} = Index name - */ - CREATE_DOCUMENT_TIME, - - /** - * Arguments: - * {0} = Index name - * {1} = Document id - */ - UPDATE_DOCUMENT_TIME, - - /** - * Arguments: - * {0} = Index name - * {1} = Document id - */ - DELETE_DOCUMENT_TIME, - - /** - * Arguments: - * {0} = Index name - * {1} = Document id - */ - GET_DOCUMENT_TIME, - - /** - * Arguments: - * {0} = Index name - * {1} = Query string - */ - QUERY_DOCUMENT_TIME, - - /** - * Arguments: - */ - BULK_OPERATIONS_TIME, - - /** - * Arguments: - */ - PROCESSED_BULK_OPERATIONS, - - /** - * Arguments: - * {0} = Event - * {1} = Result - */ - PROCESS_EVENT, - - /** - * Arguments: - * {0} = URL. - */ - PROCESS_INLINE_QUERY, - - /** - * Arguments - * {0} - Operation type (GET or POST) - * {1} - URL. - */ - PROCESS_PAYLOAD_QUERY, - - /** - * Arguments: - * {0} = Index - * {1} = Error - */ - INDEX_CREATE_FAILURE, - - /** - * Arguments: - * {0} = Index name - * {1} = Error cause - */ - INDEX_DELETE_FAILURE, - - /** - * Arguments: - * {0} = Failure cause. - */ - GET_ANALYZERS_FAILURE, - - /** - * Arguments: - * {0} = Failure cause. - */ - BULK_OPERATION_FAILURE, - - /** - * Arguments: - * {0} = Method - * {1} = Exception - */ - EXCEPTION_DURING_METHOD_CALL, - - /** - * Received request {0} {1} from {2}. Sending response: {3} - * - * <p>Arguments: - * {0} = operation - * {1} = target URL - * {2} = source - * {3} = response code - */ - PROCESS_REST_REQUEST, - - STARTUP_EXCEPTION - /** - * Exception encountered during startup of search service: {0} - * - * <p>Arguments: - * {0} = exception - */ - ; - - /** - * Load message bundle (SearchDbMsgs.properties file) - */ - static { - EELFResourceManager.loadMessageBundle("logging/SearchDbMsgs"); - } + /** + * Arguments: None + */ + SERVICE_STARTED, + + /** + * Arguments: {0} = url + */ + ELASTIC_SEARCH_CONNECTION_ATTEMPT, + + /** + * Arguments: {0} = url + */ + ELASTIC_SEARCH_CONNECTION_SUCCESS, + + /** + * Arguments: {0} = url {1} = failure cause + */ + ELASTIC_SEARCH_CONNECTION_FAILURE, + + /** + * Arguments: {0} = Filter configuration file. {1} = Failure cause. + */ + FILTERS_CONFIG_FAILURE, + + /** + * Arguments: {0} = Analysys configuration file. {1} = Failure case. + */ + ANALYSYS_CONFIG_FAILURE, + + /** + * Arguments: {0} = Index name + */ + CREATED_INDEX, + + /** + * Arguments: {0} = Index name {1} = Document type + */ + CREATE_INDEX_TIME, + + /** + * Arguments: {0} = Index name + */ + DELETED_INDEX, + + /** + * Arguments: {0} = Index name + */ + DELETE_INDEX_TIME, + + /** + * Arguments: {0} = Index name + */ + CHECK_INDEX_TIME, + + /** + * Arguments: {0} = Index name + */ + CREATE_DOCUMENT_TIME, + + /** + * Arguments: {0} = Index name {1} = Document id + */ + UPDATE_DOCUMENT_TIME, + + /** + * Arguments: {0} = Index name {1} = Document id + */ + DELETE_DOCUMENT_TIME, + + /** + * Arguments: {0} = Index name {1} = Document id + */ + GET_DOCUMENT_TIME, + + /** + * Arguments: {0} = Index name {1} = Query string + */ + QUERY_DOCUMENT_TIME, + + /** + * Arguments: + */ + BULK_OPERATIONS_TIME, + + /** + * Arguments: + */ + PROCESSED_BULK_OPERATIONS, + + /** + * Arguments: {0} = Event {1} = Result + */ + PROCESS_EVENT, + + /** + * Arguments: {0} = URL. + */ + PROCESS_INLINE_QUERY, + + /** + * Arguments {0} - Operation type (GET or POST) {1} - URL. + */ + PROCESS_PAYLOAD_QUERY, + + /** + * Arguments: {0} = Index {1} = Error + */ + INDEX_CREATE_FAILURE, + + /** + * Arguments: {0} = Index name {1} = Error cause + */ + INDEX_DELETE_FAILURE, + + /** + * Arguments: {0} = Failure cause. + */ + GET_ANALYZERS_FAILURE, + + /** + * Arguments: {0} = Failure cause. + */ + BULK_OPERATION_FAILURE, + + /** + * Arguments: {0} = Method {1} = Exception + */ + EXCEPTION_DURING_METHOD_CALL, + + /** + * Received request {0} {1} from {2}. Sending response: {3} + * + * <p> + * Arguments: {0} = operation {1} = target URL {2} = source {3} = response code + */ + PROCESS_REST_REQUEST, + + STARTUP_EXCEPTION + /** + * Exception encountered during startup of search service: {0} + * + * <p> + * Arguments: {0} = exception + */ + ; + + /** + * Load message bundle (SearchDbMsgs.properties file) + */ + static { + EELFResourceManager.loadMessageBundle("logging/SearchDbMsgs"); + } } 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 99c99e5..80b4704 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 @@ -24,55 +24,54 @@ import com.fasterxml.jackson.annotation.JsonProperty; /** - * This is the common parent from which all aggregation types inherit. It defines - * the common fields that all aggregations must include. + * This is the common parent from which all aggregation types inherit. It defines the common fields that all + * aggregations must include. */ 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; + /** + * Optionally allows the number of buckets for the aggregation to be specified. + */ + 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; + /** + * 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; - 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(); + public abstract String toString(); } diff --git a/src/main/java/org/onap/aai/sa/searchdbabstraction/searchapi/Aggregation.java b/src/main/java/org/onap/aai/sa/searchdbabstraction/searchapi/Aggregation.java index 532571b..e1994fe 100644 --- a/src/main/java/org/onap/aai/sa/searchdbabstraction/searchapi/Aggregation.java +++ b/src/main/java/org/onap/aai/sa/searchdbabstraction/searchapi/Aggregation.java @@ -23,41 +23,41 @@ package org.onap.aai.sa.searchdbabstraction.searchapi; import com.fasterxml.jackson.annotation.JsonProperty; public class Aggregation { - private String name; + private String name; - @JsonProperty("aggregation") - private AggregationStatement aggregation; + @JsonProperty("aggregation") + private AggregationStatement aggregation; - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public AggregationStatement getStatement() { - return aggregation; - } + public AggregationStatement getStatement() { + return aggregation; + } - public void setStatement(AggregationStatement aggregation) { - this.aggregation = aggregation; - } + public void setStatement(AggregationStatement aggregation) { + this.aggregation = aggregation; + } - public String toElasticSearch() { - StringBuffer sb = new StringBuffer(); + public String toElasticSearch() { + StringBuffer sb = new StringBuffer(); - sb.append("\""); - sb.append(name); - sb.append("\": "); - sb.append(aggregation.toElasticSearch()); + sb.append("\""); + sb.append(name); + sb.append("\": "); + sb.append(aggregation.toElasticSearch()); - return sb.toString(); - } + return sb.toString(); + } - @Override - public String toString() { - return "{name: " + name + ", aggregation: " + aggregation.toString(); - } + @Override + public String toString() { + return "{name: " + name + ", aggregation: " + aggregation.toString(); + } } diff --git a/src/main/java/org/onap/aai/sa/searchdbabstraction/searchapi/AggregationStatement.java b/src/main/java/org/onap/aai/sa/searchdbabstraction/searchapi/AggregationStatement.java index 696c9d9..4b446fd 100644 --- a/src/main/java/org/onap/aai/sa/searchdbabstraction/searchapi/AggregationStatement.java +++ b/src/main/java/org/onap/aai/sa/searchdbabstraction/searchapi/AggregationStatement.java @@ -25,149 +25,149 @@ import java.util.Arrays; public class AggregationStatement { - @JsonProperty("group-by") - private GroupByAggregation groupBy; + @JsonProperty("group-by") + private GroupByAggregation groupBy; - @JsonProperty("date-range") - private DateRangeAggregation dateRange; + @JsonProperty("date-range") + private DateRangeAggregation dateRange; - @JsonProperty("date-histogram") - private DateHistogramAggregation dateHist; + @JsonProperty("date-histogram") + private DateHistogramAggregation dateHist; - @JsonProperty("nested") - private Aggregation[] nested; + @JsonProperty("nested") + private Aggregation[] nested; - @JsonProperty("sub-aggregations") - private Aggregation[] subAggregations; + @JsonProperty("sub-aggregations") + private Aggregation[] subAggregations; - public GroupByAggregation getGroupBy() { - return groupBy; - } - - public void setGroupBy(GroupByAggregation groupBy) { - this.groupBy = groupBy; - } - - public DateRangeAggregation getDateRange() { - return dateRange; - } + public GroupByAggregation getGroupBy() { + return groupBy; + } - public void setDateRange(DateRangeAggregation dateRange) { - this.dateRange = dateRange; - } + public void setGroupBy(GroupByAggregation groupBy) { + this.groupBy = groupBy; + } - public DateHistogramAggregation getDateHist() { - return dateHist; - } + public DateRangeAggregation getDateRange() { + return dateRange; + } - public void setDateHist(DateHistogramAggregation dateHist) { - this.dateHist = dateHist; - } + public void setDateRange(DateRangeAggregation dateRange) { + this.dateRange = dateRange; + } - public Aggregation[] getNested() { - return nested; - } + public DateHistogramAggregation getDateHist() { + return dateHist; + } - public void setNested(Aggregation[] nested) { - this.nested = nested; - } + public void setDateHist(DateHistogramAggregation dateHist) { + this.dateHist = dateHist; + } - public Aggregation[] getSubAggregations() { - return subAggregations; - } + public Aggregation[] getNested() { + return nested; + } - public void setSubAggregations(Aggregation[] subAggregations) { - this.subAggregations = subAggregations; - } + public void setNested(Aggregation[] nested) { + this.nested = nested; + } - public String toElasticSearch() { - StringBuffer sb = new StringBuffer(); + public Aggregation[] getSubAggregations() { + return subAggregations; + } - sb.append("{"); + public void setSubAggregations(Aggregation[] subAggregations) { + this.subAggregations = subAggregations; + } - if (nested != null && nested.length > 0) { - sb.append("\"nested\": {\"path\": \""); - if (nested[0].getStatement() != null) { - sb.append(nested[0].getStatement().getNestedPath()); - } - sb.append("\"}, \"aggs\": {"); - for (int i = 0; i < nested.length; i++) { - if (i > 0) { - sb.append(","); - } - sb.append(nested[i].toElasticSearch()); - } - - sb.append("}"); - } else { - if (groupBy != null) { - sb.append(groupBy.toElasticSearch()); - } else if (dateRange != null) { - sb.append(dateRange.toElasticSearch()); - } else if (dateHist != null) { - sb.append(dateHist.toElasticSearch()); - } - - if (subAggregations != null && subAggregations.length > 0) { - sb.append(", \"aggs\": {"); - for (int i = 0; i < subAggregations.length; i++) { - if (i > 0) { - sb.append(","); - } - sb.append(subAggregations[i].toElasticSearch()); + public String toElasticSearch() { + StringBuffer sb = new StringBuffer(); + + sb.append("{"); + + if (nested != null && nested.length > 0) { + sb.append("\"nested\": {\"path\": \""); + if (nested[0].getStatement() != null) { + sb.append(nested[0].getStatement().getNestedPath()); + } + sb.append("\"}, \"aggs\": {"); + for (int i = 0; i < nested.length; i++) { + if (i > 0) { + sb.append(","); + } + sb.append(nested[i].toElasticSearch()); + } + + sb.append("}"); + } else { + if (groupBy != null) { + sb.append(groupBy.toElasticSearch()); + } else if (dateRange != null) { + sb.append(dateRange.toElasticSearch()); + } else if (dateHist != null) { + sb.append(dateHist.toElasticSearch()); + } + + if (subAggregations != null && subAggregations.length > 0) { + sb.append(", \"aggs\": {"); + for (int i = 0; i < subAggregations.length; i++) { + if (i > 0) { + sb.append(","); + } + sb.append(subAggregations[i].toElasticSearch()); + } + sb.append("}"); + } } + sb.append("}"); - } - } - sb.append("}"); + return sb.toString(); + } - return sb.toString(); - } + @Override + public String toString() { + StringBuffer sb = new StringBuffer(); + + if (nested != null) { + sb.append("{nested: "); + sb.append(Arrays.toString(nested)); + } else if (groupBy != null) { + sb.append(groupBy.toString()); + } else if (dateHist != null) { + sb.append(dateHist.toString()); + } else if (dateRange != null) { + sb.append(dateRange.toString()); + } - @Override - public String toString() { - StringBuffer sb = new StringBuffer(); + if (subAggregations != null) { + sb.append(", sub-aggregations: "); + sb.append(Arrays.toString(subAggregations)); + } - if (nested != null) { - sb.append("{nested: "); - sb.append(Arrays.toString(nested)); - } else if (groupBy != null) { - sb.append(groupBy.toString()); - } else if (dateHist != null) { - sb.append(dateHist.toString()); - } else if (dateRange != null) { - sb.append(dateRange.toString()); - } + sb.append("}"); - if (subAggregations != null) { - sb.append(", sub-aggregations: "); - sb.append(Arrays.toString(subAggregations)); + return sb.toString(); } - sb.append("}"); - - return sb.toString(); - } + public String getNestedPath() { + String path = null; + String fieldName = null; - public String getNestedPath() { - String path = null; - String fieldName = null; + if (groupBy != null) { + fieldName = groupBy.getField(); + } else if (dateRange != null) { + fieldName = dateRange.getField(); + } else if (dateHist != null) { + fieldName = dateHist.getField(); + } - if (groupBy != null) { - fieldName = groupBy.getField(); - } else if (dateRange != null) { - fieldName = dateRange.getField(); - } else if (dateHist != null) { - fieldName = dateHist.getField(); - } + if (fieldName != null && fieldName.contains(".")) { + // we have nested field + path = fieldName.substring(0, fieldName.indexOf(".")); + } - if (fieldName != null && fieldName.contains(".")) { - // we have nested field - path = fieldName.substring(0, fieldName.indexOf(".")); + return path; } - return path; - } - } diff --git a/src/main/java/org/onap/aai/sa/searchdbabstraction/searchapi/DateHistogramAggregation.java b/src/main/java/org/onap/aai/sa/searchdbabstraction/searchapi/DateHistogramAggregation.java index 2967fd2..96bb25d 100644 --- a/src/main/java/org/onap/aai/sa/searchdbabstraction/searchapi/DateHistogramAggregation.java +++ b/src/main/java/org/onap/aai/sa/searchdbabstraction/searchapi/DateHistogramAggregation.java @@ -25,7 +25,9 @@ import com.fasterxml.jackson.annotation.JsonProperty; /** * An example of elasticsearch date_histogram aggregation: * - * <p><pre> + * <p> + * + * <pre> * { * "aggs": { * "my_group": { @@ -41,75 +43,75 @@ import com.fasterxml.jackson.annotation.JsonProperty; public class DateHistogramAggregation extends AbstractAggregation { - private String interval; + private String interval; - private String format; + private String format; - @JsonProperty("time-zone") - private String timeZone; + @JsonProperty("time-zone") + private String timeZone; - public String getInterval() { - return interval; - } - - public void setInterval(String interval) { - this.interval = interval; - } - - public String getTimeZone() { - return timeZone; - } - - public String getFormat() { - return format; - } - - public void setFormat(String format) { - this.format = format; - } - - public void setTimeZone(String timeZone) { - this.timeZone = timeZone; - } - - @Override - public String toElasticSearch() { - StringBuilder sb = new StringBuilder(); + public String getInterval() { + return interval; + } - sb.append("\"date_histogram\": {\"field\": \""); - sb.append(field); - sb.append("\""); - if (interval != null) { - sb.append(", \"interval\": \""); - sb.append(interval); - sb.append("\""); + public void setInterval(String interval) { + this.interval = interval; } - if (format != null) { - sb.append(", \"format\": \""); - sb.append(format); - sb.append("\""); + + public String getTimeZone() { + return timeZone; } - if (timeZone != null) { - sb.append(", \"time_zone\": \""); - sb.append(timeZone); - sb.append("\""); + + public String getFormat() { + return format; } - if (size != null) { - sb.append(", \"size\": "); - sb.append(size); + + public void setFormat(String format) { + this.format = format; } - if (minThreshold != null) { - sb.append(", \"min_doc_count\": ").append(minThreshold); + + public void setTimeZone(String timeZone) { + this.timeZone = timeZone; } - sb.append("}"); - return sb.toString(); - } + @Override + public String toElasticSearch() { + StringBuilder sb = new StringBuilder(); + + sb.append("\"date_histogram\": {\"field\": \""); + sb.append(field); + sb.append("\""); + if (interval != null) { + sb.append(", \"interval\": \""); + sb.append(interval); + sb.append("\""); + } + if (format != null) { + sb.append(", \"format\": \""); + sb.append(format); + sb.append("\""); + } + if (timeZone != null) { + sb.append(", \"time_zone\": \""); + sb.append(timeZone); + sb.append("\""); + } + if (size != null) { + sb.append(", \"size\": "); + sb.append(size); + } + if (minThreshold != null) { + sb.append(", \"min_doc_count\": ").append(minThreshold); + } + sb.append("}"); + + return sb.toString(); + } - @Override - public String toString() { - return "DateHistogramAggregation: [field=" + field + ", interval=" + interval + ", format=" - + format + ", timeZone=" + timeZone + ", size=" + size + " minThreshold=" + minThreshold; - } + @Override + public String toString() { + return "DateHistogramAggregation: [field=" + field + ", interval=" + interval + ", format=" + format + + ", timeZone=" + timeZone + ", size=" + size + " minThreshold=" + minThreshold; + } } 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 8d899b0..78f707a 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,6 +27,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; * <p> * The expected JSON structure for a ranges is as follows: * <p> + * * <pre> * { * "from": <from-date> @@ -35,6 +36,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; * <p> * or * <p> + * * <pre> * { * "to": <to-date> @@ -43,6 +45,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; * <p> * or * <p> + * * <pre> * { * "from": <from-date>, @@ -54,58 +57,58 @@ import com.fasterxml.jackson.annotation.JsonProperty; */ public class DateRange { - @JsonProperty("from") - private String fromDate; + @JsonProperty("from") + private String fromDate; - @JsonProperty("to") - private String toDate; + @JsonProperty("to") + private String toDate; - public String getFromDate() { - return fromDate; - } + public String getFromDate() { + return fromDate; + } - public void setFromDate(String fromDate) { - this.fromDate = fromDate; - } + public void setFromDate(String fromDate) { + this.fromDate = fromDate; + } - public String getToDate() { - return toDate; - } + public String getToDate() { + return toDate; + } - public void setToDate(String toDate) { - this.toDate = toDate; - } + public void setToDate(String toDate) { + this.toDate = toDate; + } - public String toElasticSearch() { - StringBuilder sb = new StringBuilder(); + public String toElasticSearch() { + StringBuilder sb = new StringBuilder(); - sb.append("{"); + sb.append("{"); - if (fromDate != null) { - sb.append("\"from\": \""); - sb.append(fromDate.toString()); - sb.append("\""); - } + if (fromDate != null) { + sb.append("\"from\": \""); + sb.append(fromDate.toString()); + sb.append("\""); + } - if (toDate != null) { - if (fromDate != null) { - sb.append(", \"to\": \""); - sb.append(toDate.toString()); - sb.append("\""); - } else { - sb.append("\"to\": \""); - sb.append(toDate.toString()); - sb.append("\""); - } - } + if (toDate != null) { + if (fromDate != null) { + sb.append(", \"to\": \""); + sb.append(toDate.toString()); + sb.append("\""); + } else { + sb.append("\"to\": \""); + sb.append(toDate.toString()); + sb.append("\""); + } + } - sb.append("}"); + sb.append("}"); - return sb.toString(); - } + return sb.toString(); + } - public String toString() { - return "{from: " + fromDate + ", to: " + toDate + "}"; - } + public String toString() { + return "{from: " + fromDate + ", to: " + toDate + "}"; + } } diff --git a/src/main/java/org/onap/aai/sa/searchdbabstraction/searchapi/DateRangeAggregation.java b/src/main/java/org/onap/aai/sa/searchdbabstraction/searchapi/DateRangeAggregation.java index 1ee42c9..5851f9a 100644 --- a/src/main/java/org/onap/aai/sa/searchdbabstraction/searchapi/DateRangeAggregation.java +++ b/src/main/java/org/onap/aai/sa/searchdbabstraction/searchapi/DateRangeAggregation.java @@ -25,7 +25,9 @@ import com.fasterxml.jackson.annotation.JsonProperty; /** * An example of a date_range aggregation: * - * <p><pre> + * <p> + * + * <pre> * { * "aggs": { * "range": { @@ -47,83 +49,83 @@ import com.fasterxml.jackson.annotation.JsonProperty; public class DateRangeAggregation extends AbstractAggregation { - private String format; + private String format; - @JsonProperty("ranges") - private DateRange[] dateRanges; + @JsonProperty("ranges") + private DateRange[] dateRanges; - public String getFormat() { - return format; - } + public String getFormat() { + return format; + } + + public void setFormat(String format) { + this.format = format; + } - public void setFormat(String format) { - this.format = format; - } + public DateRange[] getDateRanges() { + return dateRanges; + } - public DateRange[] getDateRanges() { - return dateRanges; - } + public void setDateRanges(DateRange[] dateRanges) { + this.dateRanges = dateRanges; + } - public void setDateRanges(DateRange[] dateRanges) { - this.dateRanges = dateRanges; - } + @Override + public String toElasticSearch() { + StringBuilder sb = new StringBuilder(); - @Override - public String toElasticSearch() { - StringBuilder sb = new StringBuilder(); + sb.append("\"date_range\": {\"field\": \""); + sb.append(field); + sb.append("\""); - sb.append("\"date_range\": {\"field\": \""); - sb.append(field); - sb.append("\""); + if (format != null) { + sb.append(", \"format\": \""); + sb.append(format); + sb.append("\""); + } - if (format != null) { - sb.append(", \"format\": \""); - sb.append(format); - sb.append("\""); - } + if (dateRanges != null && dateRanges.length > 0) { + sb.append(", \"ranges\": ["); - if (dateRanges != null && dateRanges.length > 0) { - sb.append(", \"ranges\": ["); + for (int i = 0; i < dateRanges.length; i++) { + if (i > 0) { + sb.append(","); + } + sb.append(dateRanges[i].toElasticSearch()); + } - for (int i = 0; i < dateRanges.length; i++) { - if (i > 0) { - sb.append(","); + sb.append("]"); } - sb.append(dateRanges[i].toElasticSearch()); - } - sb.append("]"); - } + if (size != null) { + sb.append(", \"size\": "); + sb.append(size); + } - if (size != null) { - sb.append(", \"size\": "); - sb.append(size); - } + if (minThreshold != null) { + sb.append(", \"min_doc_count\": ").append(minThreshold); + } - if (minThreshold != null) { - sb.append(", \"min_doc_count\": ").append(minThreshold); - } + sb.append("}"); - sb.append("}"); - - return sb.toString(); - } - - @Override - public String toString() { - StringBuffer sb = new StringBuffer(); - sb.append("date-range: {field: " + field + ", format: " + format + ", size: " + size - + ", minThreshold: " + minThreshold + "ranges: ["); - for (int i = 0; i < dateRanges.length; i++) { - if (i > 0) { - sb.append(","); - } - sb.append(dateRanges[i].toString()); + return sb.toString(); } - sb.append("]"); - return sb.toString(); - } + @Override + public String toString() { + StringBuffer sb = new StringBuffer(); + sb.append("date-range: {field: " + field + ", format: " + format + ", size: " + size + ", minThreshold: " + + minThreshold + "ranges: ["); + for (int i = 0; i < dateRanges.length; i++) { + if (i > 0) { + sb.append(","); + } + sb.append(dateRanges[i].toString()); + } + sb.append("]"); + + return sb.toString(); + } } diff --git a/src/main/java/org/onap/aai/sa/searchdbabstraction/searchapi/Filter.java b/src/main/java/org/onap/aai/sa/searchdbabstraction/searchapi/Filter.java index 2d9a8e1..4e8bdd0 100644 --- a/src/main/java/org/onap/aai/sa/searchdbabstraction/searchapi/Filter.java +++ b/src/main/java/org/onap/aai/sa/searchdbabstraction/searchapi/Filter.java @@ -26,7 +26,9 @@ import java.util.List; /** * This class represents the filter stanza in a search statement. * - * <p>The expected JSON structure for a filter stanza is as follows: + * <p> + * The expected JSON structure for a filter stanza is as follows: + * * <pre> * { * "filter": { @@ -38,149 +40,147 @@ import java.util.List; */ public class Filter { - /** - * All queries in this list must evaluate to true for the filter to pass. - */ - private QueryStatement[] all; - - /** - * Any one of the queries in this list must evaluate to true for the - * filter to pass. - */ - private QueryStatement[] any; - - - public QueryStatement[] getAll() { - return all; - } - - public void setAll(QueryStatement[] all) { - this.all = all; - } - - public QueryStatement[] getAny() { - return any; - } - - public void setAny(QueryStatement[] any) { - this.any = any; - } - - /** - * This method returns a string which represents this filter in syntax - * that is understandable by ElasticSearch and is suitable for inclusion - * in an ElasticSearch query string. - * - * @return - ElasticSearch syntax string. - */ - public String toElasticSearch() { - - StringBuilder sb = new StringBuilder(); - - List<QueryStatement> notMatchQueries = new ArrayList<QueryStatement>(); - sb.append("{"); - sb.append("\"bool\": {"); - - // Add the queries from our 'all' list. - int matchQueriesCount = 0; - int notMatchQueriesCount = 0; - if (all != null) { - sb.append("\"must\": ["); - - for (QueryStatement query : all) { - if (matchQueriesCount > 0) { - sb.append(", "); - } + /** + * All queries in this list must evaluate to true for the filter to pass. + */ + private QueryStatement[] all; - if (query.isNotMatch()) { - notMatchQueries.add(query); - } else { - sb.append(query.toElasticSearch()); - matchQueriesCount++; - } - } - sb.append("],"); + /** + * Any one of the queries in this list must evaluate to true for the filter to pass. + */ + private QueryStatement[] any; - sb.append("\"must_not\": ["); - for (QueryStatement query : notMatchQueries) { - if (notMatchQueriesCount > 0) { - sb.append(", "); - } - sb.append(query.toElasticSearch()); - notMatchQueriesCount++; - } - sb.append("]"); + public QueryStatement[] getAll() { + return all; } - // Add the queries from our 'any' list. - notMatchQueries.clear(); - if (any != null) { - if (all != null) { - sb.append(","); - } - sb.append("\"should\": ["); - - matchQueriesCount = 0; - for (QueryStatement query : any) { - //if(!firstQuery.compareAndSet(true, false)) { - if (matchQueriesCount > 0) { - sb.append(", "); - } + public void setAll(QueryStatement[] all) { + this.all = all; + } + + public QueryStatement[] getAny() { + return any; + } + + public void setAny(QueryStatement[] any) { + this.any = any; + } - if (query.isNotMatch()) { - notMatchQueries.add(query); - } else { - sb.append(query.toElasticSearch()); - matchQueriesCount++; + /** + * This method returns a string which represents this filter in syntax that is understandable by ElasticSearch and + * is suitable for inclusion in an ElasticSearch query string. + * + * @return - ElasticSearch syntax string. + */ + public String toElasticSearch() { + + StringBuilder sb = new StringBuilder(); + + List<QueryStatement> notMatchQueries = new ArrayList<QueryStatement>(); + sb.append("{"); + sb.append("\"bool\": {"); + + // Add the queries from our 'all' list. + int matchQueriesCount = 0; + int notMatchQueriesCount = 0; + if (all != null) { + sb.append("\"must\": ["); + + for (QueryStatement query : all) { + if (matchQueriesCount > 0) { + sb.append(", "); + } + + if (query.isNotMatch()) { + notMatchQueries.add(query); + } else { + sb.append(query.toElasticSearch()); + matchQueriesCount++; + } + } + sb.append("],"); + + + sb.append("\"must_not\": ["); + for (QueryStatement query : notMatchQueries) { + if (notMatchQueriesCount > 0) { + sb.append(", "); + } + sb.append(query.toElasticSearch()); + notMatchQueriesCount++; + } + sb.append("]"); } - } - sb.append("],"); - - //firstQuery.set(true); - notMatchQueriesCount = 0; - sb.append("\"must_not\": ["); - for (QueryStatement query : notMatchQueries) { - //if(!firstQuery.compareAndSet(true, false)) { - if (notMatchQueriesCount > 0) { - sb.append(", "); + + // Add the queries from our 'any' list. + notMatchQueries.clear(); + if (any != null) { + if (all != null) { + sb.append(","); + } + sb.append("\"should\": ["); + + matchQueriesCount = 0; + for (QueryStatement query : any) { + // if(!firstQuery.compareAndSet(true, false)) { + if (matchQueriesCount > 0) { + sb.append(", "); + } + + if (query.isNotMatch()) { + notMatchQueries.add(query); + } else { + sb.append(query.toElasticSearch()); + matchQueriesCount++; + } + } + sb.append("],"); + + // firstQuery.set(true); + notMatchQueriesCount = 0; + sb.append("\"must_not\": ["); + for (QueryStatement query : notMatchQueries) { + // if(!firstQuery.compareAndSet(true, false)) { + if (notMatchQueriesCount > 0) { + sb.append(", "); + } + sb.append(query.toElasticSearch()); + notMatchQueriesCount++; + } + sb.append("]"); } - sb.append(query.toElasticSearch()); - notMatchQueriesCount++; - } - sb.append("]"); - } - sb.append("}"); - sb.append("}"); + sb.append("}"); + sb.append("}"); - return sb.toString(); - } + return sb.toString(); + } - @Override - public String toString() { + @Override + public String toString() { - StringBuilder sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); - sb.append("{"); + sb.append("{"); - sb.append("all: ["); - if (all != null) { - for (QueryStatement query : all) { - sb.append(query.toString()); - } - } - sb.append("], "); + sb.append("all: ["); + if (all != null) { + for (QueryStatement query : all) { + sb.append(query.toString()); + } + } + sb.append("], "); - sb.append("any: ["); - if (any != null) { - for (QueryStatement query : any) { - sb.append(query.toString()); - } - } - sb.append("] "); + sb.append("any: ["); + if (any != null) { + for (QueryStatement query : any) { + sb.append(query.toString()); + } + } + sb.append("] "); - sb.append("}"); + sb.append("}"); - return sb.toString(); - } + return sb.toString(); + } } diff --git a/src/main/java/org/onap/aai/sa/searchdbabstraction/searchapi/GroupByAggregation.java b/src/main/java/org/onap/aai/sa/searchdbabstraction/searchapi/GroupByAggregation.java index df643f2..69730d2 100644 --- a/src/main/java/org/onap/aai/sa/searchdbabstraction/searchapi/GroupByAggregation.java +++ b/src/main/java/org/onap/aai/sa/searchdbabstraction/searchapi/GroupByAggregation.java @@ -23,7 +23,9 @@ package org.onap.aai.sa.searchdbabstraction.searchapi; /** * An example of a date_range aggregation: * - * <p><pre> + * <p> + * + * <pre> * { * "aggs": { * "my_group": { @@ -39,31 +41,30 @@ package org.onap.aai.sa.searchdbabstraction.searchapi; */ public class GroupByAggregation extends AbstractAggregation { - @Override - public String toElasticSearch() { - StringBuilder sb = new StringBuilder(); + @Override + public String toElasticSearch() { + StringBuilder sb = new StringBuilder(); - sb.append("\"terms\": {\"field\": \""); - sb.append(field); - sb.append("\""); - if (size != null) { - sb.append(", \"size\": "); - sb.append(size); - } + sb.append("\"terms\": {\"field\": \""); + sb.append(field); + sb.append("\""); + if (size != null) { + sb.append(", \"size\": "); + sb.append(size); + } - if (minThreshold != null) { - sb.append(", \"min_doc_count\": ").append(minThreshold); - } + if (minThreshold != null) { + sb.append(", \"min_doc_count\": ").append(minThreshold); + } - sb.append("}"); + sb.append("}"); - return sb.toString(); - } + return sb.toString(); + } - @Override - public String toString() { - return "{group-by: {field: " + field + ", size: " + size - + " minThreshold: " + minThreshold + "}}"; - } + @Override + public String toString() { + return "{group-by: {field: " + field + ", size: " + size + " minThreshold: " + minThreshold + "}}"; + } } diff --git a/src/main/java/org/onap/aai/sa/searchdbabstraction/searchapi/ParsedQuery.java b/src/main/java/org/onap/aai/sa/searchdbabstraction/searchapi/ParsedQuery.java index e8e3074..19bc250 100644 --- a/src/main/java/org/onap/aai/sa/searchdbabstraction/searchapi/ParsedQuery.java +++ b/src/main/java/org/onap/aai/sa/searchdbabstraction/searchapi/ParsedQuery.java @@ -25,29 +25,34 @@ import com.fasterxml.jackson.annotation.JsonProperty; /** * This class represents a simple parsed query statement. * - * <p>A 'parsed query' specifies a document field to inspect and a query - * string which will be parsed by the document store to generate the - * exact query to be performed. + * <p> + * A 'parsed query' specifies a document field to inspect and a query string which will be parsed by the document store + * to generate the exact query to be performed. * - * <p>The query string will be tokenized into 'terms' and 'operators' where: + * <p> + * The query string will be tokenized into 'terms' and 'operators' where: * - * <p>Terms may be any of the following: + * <p> + * Terms may be any of the following: * <ul> - * <li> single words </li> - * <li> exact phrases (denoted by surrounding the phrase with '"' characters) </li> - * <li> regular expressions (denoted by surrounding the phrase with '/' characters) </li> + * <li>single words</li> + * <li>exact phrases (denoted by surrounding the phrase with '"' characters)</li> + * <li>regular expressions (denoted by surrounding the phrase with '/' characters)</li> * </ul> * - * <p>Operators may be any of the following: + * <p> + * Operators may be any of the following: * <ul> - * <li> + -- The term to the right of the operator MUST be present to produce a match. </li> - * <li> - -- The term to the right of the operator MUST NOT be present to produce a match. </li> - * <li> AND -- Both the terms to the left and right of the operator MUST be present to produce a match. </li> - * <li> OR -- Either the term to the left or right of the operator MUST be present to produce a match. </li> - * <li> NOT -- The term to the right of the operator MUST NOT be present to produce a match. </li> + * <li>+ -- The term to the right of the operator MUST be present to produce a match.</li> + * <li>- -- The term to the right of the operator MUST NOT be present to produce a match.</li> + * <li>AND -- Both the terms to the left and right of the operator MUST be present to produce a match.</li> + * <li>OR -- Either the term to the left or right of the operator MUST be present to produce a match.</li> + * <li>NOT -- The term to the right of the operator MUST NOT be present to produce a match.</li> * </ul> * - * <p>The expected JSON structure for a parsed query is as follows: + * <p> + * The expected JSON structure for a parsed query is as follows: + * * <pre> * { * "parsed-query": { @@ -59,58 +64,57 @@ import com.fasterxml.jackson.annotation.JsonProperty; */ public class ParsedQuery { - /** - * The name of the field which the query is to be applied to. - */ - private String field; + /** + * The name of the field which the query is to be applied to. + */ + private String field; - /** - * The string to be parsed to generate the full query. - */ - @JsonProperty("query-string") - private String queryString; + /** + * The string to be parsed to generate the full query. + */ + @JsonProperty("query-string") + private String queryString; - 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 String getQueryString() { - return queryString; - } + public String getQueryString() { + return queryString; + } - public void setQueryString(String queryString) { - this.queryString = queryString; - } + public void setQueryString(String queryString) { + this.queryString = queryString; + } - /** - * This method returns a string which represents this query in syntax - * that is understandable by ElasticSearch and is suitable for inclusion - * in an ElasticSearch query string. - * - * @return - ElasticSearch syntax string. - */ - public String toElasticSearch() { + /** + * This method returns a string which represents this query in syntax that is understandable by ElasticSearch and is + * suitable for inclusion in an ElasticSearch query string. + * + * @return - ElasticSearch syntax string. + */ + public String toElasticSearch() { - StringBuilder sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); - sb.append("{"); - sb.append("\"query_string\": {"); - sb.append("\"default_field\": \"").append(field).append("\", "); - sb.append("\"query\": \"").append(queryString).append("\""); - sb.append("}"); - sb.append("}"); + sb.append("{"); + sb.append("\"query_string\": {"); + sb.append("\"default_field\": \"").append(field).append("\", "); + sb.append("\"query\": \"").append(queryString).append("\""); + sb.append("}"); + sb.append("}"); - return sb.toString(); - } + return sb.toString(); + } - @Override - public String toString() { - return "{field:" + field + ", query-string: '" + queryString + "'}"; - } + @Override + public String toString() { + return "{field:" + field + ", query-string: '" + queryString + "'}"; + } } diff --git a/src/main/java/org/onap/aai/sa/searchdbabstraction/searchapi/Query.java b/src/main/java/org/onap/aai/sa/searchdbabstraction/searchapi/Query.java index 3e4f537..ee8ffdc 100644 --- a/src/main/java/org/onap/aai/sa/searchdbabstraction/searchapi/Query.java +++ b/src/main/java/org/onap/aai/sa/searchdbabstraction/searchapi/Query.java @@ -22,69 +22,69 @@ package org.onap.aai.sa.searchdbabstraction.searchapi; public class Query { - private QueryStatement may; - private QueryStatement must; + private QueryStatement may; + private QueryStatement must; - public QueryStatement getMay() { - return may; - } + public QueryStatement getMay() { + return may; + } - public void setMay(QueryStatement may) { - this.may = may; - } + public void setMay(QueryStatement may) { + this.may = may; + } - public QueryStatement getMust() { - return must; - } + public QueryStatement getMust() { + return must; + } - public void setMust(QueryStatement must) { - this.must = must; - } + public void setMust(QueryStatement must) { + this.must = must; + } - public QueryStatement getQueryStatement() { - if (isMust()) { - return must; - } else if (isMay()) { - return may; - } else { - return null; + public QueryStatement getQueryStatement() { + if (isMust()) { + return must; + } else if (isMay()) { + return may; + } else { + return null; + } } - } - public boolean isMust() { - return must != null; - } + public boolean isMust() { + return must != null; + } - public boolean isMay() { - return may != null; - } + public boolean isMay() { + return may != null; + } - public String toElasticSearch() { + public String toElasticSearch() { - if (isMust()) { - return must.toElasticSearch(); - } else if (isMay()) { - return may.toElasticSearch(); - } else { - return ""; // throw an exception? + if (isMust()) { + return must.toElasticSearch(); + } else if (isMay()) { + return may.toElasticSearch(); + } else { + return ""; // throw an exception? + } } - } - @Override - public String toString() { + @Override + public String toString() { - StringBuilder sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); - sb.append("Query:["); - if (isMust()) { - sb.append("must: ").append(must.toString()); - } else if (isMay()) { - sb.append("may: ").append(may.toString()); - } else { - sb.append("INVALID"); - } - sb.append("]"); + sb.append("Query:["); + if (isMust()) { + sb.append("must: ").append(must.toString()); + } else if (isMay()) { + sb.append("may: ").append(may.toString()); + } else { + sb.append("INVALID"); + } + sb.append("]"); - return sb.toString(); - } + return sb.toString(); + } } diff --git a/src/main/java/org/onap/aai/sa/searchdbabstraction/searchapi/QueryStatement.java b/src/main/java/org/onap/aai/sa/searchdbabstraction/searchapi/QueryStatement.java index 6cfbd40..7764051 100644 --- a/src/main/java/org/onap/aai/sa/searchdbabstraction/searchapi/QueryStatement.java +++ b/src/main/java/org/onap/aai/sa/searchdbabstraction/searchapi/QueryStatement.java @@ -24,115 +24,115 @@ import com.fasterxml.jackson.annotation.JsonProperty; public class QueryStatement { - private TermQuery match; + private TermQuery match; - @JsonProperty("not-match") - private TermQuery notMatch; + @JsonProperty("not-match") + private TermQuery notMatch; - @JsonProperty("parsed-query") - private ParsedQuery parsedQuery; + @JsonProperty("parsed-query") + private ParsedQuery parsedQuery; - private RangeQuery range; + private RangeQuery range; - public TermQuery getMatch() { - return match; - } + public TermQuery getMatch() { + return match; + } - public void setMatch(TermQuery match) { - this.match = match; - } + public void setMatch(TermQuery match) { + this.match = match; + } - public TermQuery getNotMatch() { - return notMatch; - } + public TermQuery getNotMatch() { + return notMatch; + } - public void setNotMatch(TermQuery notMatch) { - this.notMatch = notMatch; - } + public void setNotMatch(TermQuery notMatch) { + this.notMatch = notMatch; + } - public ParsedQuery getParsedQuery() { - return parsedQuery; - } + public ParsedQuery getParsedQuery() { + return parsedQuery; + } - public void setParsedQuery(ParsedQuery parsedQuery) { - this.parsedQuery = parsedQuery; - } + public void setParsedQuery(ParsedQuery parsedQuery) { + this.parsedQuery = parsedQuery; + } - public RangeQuery getRange() { - return range; - } + public RangeQuery getRange() { + return range; + } - public void setRange(RangeQuery range) { - this.range = range; - } + public void setRange(RangeQuery range) { + this.range = range; + } - public boolean isNotMatch() { - return (notMatch != null); - } + public boolean isNotMatch() { + return (notMatch != null); + } - public String toElasticSearch() { + public String toElasticSearch() { - if (match != null) { - return match.toElasticSearch(); + if (match != null) { + return match.toElasticSearch(); - } else if (notMatch != null) { - return notMatch.toElasticSearch(); + } else if (notMatch != null) { + return notMatch.toElasticSearch(); - } else if (parsedQuery != null) { + } else if (parsedQuery != null) { - // We need some special wrapping if this query is against a nested field. - if (fieldIsNested(parsedQuery.getField())) { - return "{\"nested\": { \"path\": \"" + pathForNestedField(parsedQuery.getField()) - + "\", \"query\": " + parsedQuery.toElasticSearch() + "}}"; - } else { - return parsedQuery.toElasticSearch(); - } + // We need some special wrapping if this query is against a nested field. + if (fieldIsNested(parsedQuery.getField())) { + return "{\"nested\": { \"path\": \"" + pathForNestedField(parsedQuery.getField()) + "\", \"query\": " + + parsedQuery.toElasticSearch() + "}}"; + } else { + return parsedQuery.toElasticSearch(); + } - } else if (range != null) { + } else if (range != null) { - // We need some special wrapping if this query is against a nested field. - if (fieldIsNested(range.getField())) { - return "{\"nested\": { \"path\": \"" + pathForNestedField(range.getField()) - + "\", \"query\": " + range.toElasticSearch() + "}}"; - } else { - return range.toElasticSearch(); - } + // We need some special wrapping if this query is against a nested field. + if (fieldIsNested(range.getField())) { + return "{\"nested\": { \"path\": \"" + pathForNestedField(range.getField()) + "\", \"query\": " + + range.toElasticSearch() + "}}"; + } else { + return range.toElasticSearch(); + } - } else { - // throw an exception? - return null; + } else { + // throw an exception? + return null; + } } - } - - private boolean fieldIsNested(String field) { - return field.contains("."); - } - - private String pathForNestedField(String field) { - int index = field.lastIndexOf('.'); - return field.substring(0, index); - } - - @Override - public String toString() { - - StringBuilder sb = new StringBuilder(); - - sb.append("{"); - - if (match != null) { - sb.append("TERM QUERY: { match: {").append(match.toString()).append("}}"); - } else if (notMatch != null) { - sb.append("TERM QUERY: { not-match: {").append(match.toString()).append("}}"); - } else if (parsedQuery != null) { - sb.append("PARSED QUERY: { ").append(parsedQuery.toString()).append("}"); - } else if (range != null) { - sb.append("RANGE QUERY: { ").append(range.toString()).append("}"); - } else { - sb.append("UNDEFINED"); + + private boolean fieldIsNested(String field) { + return field.contains("."); + } + + private String pathForNestedField(String field) { + int index = field.lastIndexOf('.'); + return field.substring(0, index); } - sb.append("}"); - return sb.toString(); - } + @Override + public String toString() { + + StringBuilder sb = new StringBuilder(); + + sb.append("{"); + + if (match != null) { + sb.append("TERM QUERY: { match: {").append(match.toString()).append("}}"); + } else if (notMatch != null) { + sb.append("TERM QUERY: { not-match: {").append(match.toString()).append("}}"); + } else if (parsedQuery != null) { + sb.append("PARSED QUERY: { ").append(parsedQuery.toString()).append("}"); + } else if (range != null) { + sb.append("RANGE QUERY: { ").append(range.toString()).append("}"); + } else { + sb.append("UNDEFINED"); + } + + sb.append("}"); + return sb.toString(); + } } diff --git a/src/main/java/org/onap/aai/sa/searchdbabstraction/searchapi/RangeQuery.java b/src/main/java/org/onap/aai/sa/searchdbabstraction/searchapi/RangeQuery.java index c5b4886..60cc9e6 100644 --- a/src/main/java/org/onap/aai/sa/searchdbabstraction/searchapi/RangeQuery.java +++ b/src/main/java/org/onap/aai/sa/searchdbabstraction/searchapi/RangeQuery.java @@ -25,22 +25,26 @@ import com.fasterxml.jackson.annotation.JsonProperty; /** * This class represents a simple range query. * - * <p>A range query is composed of one or more operator/value pairs which define - * the upper and lower bounds of the range, and a field to apply the query to. + * <p> + * A range query is composed of one or more operator/value pairs which define the upper and lower bounds of the range, + * and a field to apply the query to. * - * <p>Operators may be one of the following: + * <p> + * Operators may be one of the following: * <ul> - * <li>gt - Greater than. </li> - * <li>gte - Greater than or equal to. </li> - * <li>lt - Less than. </li> - * <li>lte - Less than or equal to. </li> + * <li>gt - Greater than.</li> + * <li>gte - Greater than or equal to.</li> + * <li>lt - Less than.</li> + * <li>lte - Less than or equal to.</li> * </ul> - * Values may be either numeric values (Integer or Double) or Strings representing - * dates. + * Values may be either numeric values (Integer or Double) or Strings representing dates. * - * <p>The following examples illustrate a couple of variants of the range query: + * <p> + * The following examples illustrate a couple of variants of the range query: * - * <p><pre> + * <p> + * + * <pre> * // A simple numeric range query: * { * "range": { @@ -62,283 +66,271 @@ import com.fasterxml.jackson.annotation.JsonProperty; */ public class RangeQuery { - /** - * The name of the field to apply the range query against. - */ - private String field; - - /** - * The value of the field must be greater than this value to be a match.<br> - * NOTE: Only one of 'gt' or 'gte' should be set on any single {@link RangeQuery} - * instance. - */ - private Object gt; - - /** - * The value of the field must be greater than or equal to this value to be a match.<br> - * NOTE: Only one of 'gt' or 'gte' should be set on any single {@link RangeQuery} - * instance. - */ - private Object gte; - - /** - * The value of the field must be less than this value to be a match.<br> - * NOTE: Only one of 'lt' or 'lte' should be set on any single {@link RangeQuery} - * instance. - */ - private Object lt; - - /** - * The value of the field must be less than or equal to than this value to be a match.<br> - * NOTE: Only one of 'lt' or 'lte' should be set on any single {@link RangeQuery} - * instance. - */ - private Object lte; - - private String format; - - @JsonProperty("time-zone") - private String timeZone; - - public String getField() { - return field; - } - - public void setField(String field) { - this.field = field; - } - - public Object getGt() { - return gt; - } - - public void setGt(Object gt) { - - // It does not make sense to assign a value to both the 'greater than' - // and 'greater than or equal' operations, so make sure we are not - // trying to do that. - if (gte == null) { - - // Make sure that we are not trying to mix both numeric and date - // type values in the same queries. - if (((lt != null) && !typesMatch(gt, lt)) - || ((lte != null) && !typesMatch(gt, lte))) { - throw new IllegalArgumentException("Cannot mix date and numeric values in the same ranged query"); - } - - // If we made it here, then we're all good. Store the value. - this.gt = gt; - } else { - throw new IllegalArgumentException("Cannot assign both 'gt' and 'gte' fields in the same ranged query"); + /** + * The name of the field to apply the range query against. + */ + private String field; + + /** + * The value of the field must be greater than this value to be a match.<br> + * NOTE: Only one of 'gt' or 'gte' should be set on any single {@link RangeQuery} instance. + */ + private Object gt; + + /** + * The value of the field must be greater than or equal to this value to be a match.<br> + * NOTE: Only one of 'gt' or 'gte' should be set on any single {@link RangeQuery} instance. + */ + private Object gte; + + /** + * The value of the field must be less than this value to be a match.<br> + * NOTE: Only one of 'lt' or 'lte' should be set on any single {@link RangeQuery} instance. + */ + private Object lt; + + /** + * The value of the field must be less than or equal to than this value to be a match.<br> + * NOTE: Only one of 'lt' or 'lte' should be set on any single {@link RangeQuery} instance. + */ + private Object lte; + + private String format; + + @JsonProperty("time-zone") + private String timeZone; + + public String getField() { + return field; } - } + public void setField(String field) { + this.field = field; + } - public Object getGte() { - return gte; - } - - public void setGte(Object gte) { + public Object getGt() { + return gt; + } - // It does not make sense to assign a value to both the 'greater than' - // and 'greater than or equal' operations, so make sure we are not - // trying to do that. - if (gt == null) { + public void setGt(Object gt) { - // Make sure that we are not trying to mix both numeric and date - // type values in the same queries. - if (((lt != null) && !typesMatch(gte, lt)) - || ((lte != null) && !typesMatch(gte, lte))) { - throw new IllegalArgumentException("Cannot mix date and numeric values in the same ranged query"); - } + // It does not make sense to assign a value to both the 'greater than' + // and 'greater than or equal' operations, so make sure we are not + // trying to do that. + if (gte == null) { - // If we made it here, then we're all good. Store the value. - this.gte = gte; + // Make sure that we are not trying to mix both numeric and date + // type values in the same queries. + if (((lt != null) && !typesMatch(gt, lt)) || ((lte != null) && !typesMatch(gt, lte))) { + throw new IllegalArgumentException("Cannot mix date and numeric values in the same ranged query"); + } - } else { - throw new IllegalArgumentException("Cannot assign both 'gt' and 'gte' fields in the same ranged query"); + // If we made it here, then we're all good. Store the value. + this.gt = gt; + } else { + throw new IllegalArgumentException("Cannot assign both 'gt' and 'gte' fields in the same ranged query"); + } } - } - public Object getLt() { - return lt; - } - public void setLt(Object lt) { + public Object getGte() { + return gte; + } + + public void setGte(Object gte) { - // It does not make sense to assign a value to both the 'less than' - // and 'less than or equal' operations, so make sure we are not - // trying to do that. - if (lte == null) { + // It does not make sense to assign a value to both the 'greater than' + // and 'greater than or equal' operations, so make sure we are not + // trying to do that. + if (gt == null) { - // Make sure that we are not trying to mix both numeric and date - // type values in the same queries. - if (((gt != null) && !typesMatch(lt, gt)) - || ((gte != null) && !typesMatch(lt, gte))) { - throw new IllegalArgumentException("Cannot mix date and numeric values in the same ranged query"); - } + // Make sure that we are not trying to mix both numeric and date + // type values in the same queries. + if (((lt != null) && !typesMatch(gte, lt)) || ((lte != null) && !typesMatch(gte, lte))) { + throw new IllegalArgumentException("Cannot mix date and numeric values in the same ranged query"); + } - // If we made it here, then we're all good. Store the value. + // If we made it here, then we're all good. Store the value. + this.gte = gte; - this.lt = lt; - } else { - throw new IllegalArgumentException("Cannot assign both 'lt' and 'lte' fields in the same ranged query"); + } else { + throw new IllegalArgumentException("Cannot assign both 'gt' and 'gte' fields in the same ranged query"); + } } - } - public Object getLte() { - return lte; - } + public Object getLt() { + return lt; + } - public void setLte(Object lte) { + public void setLt(Object lt) { - // It does not make sense to assign a value to both the 'greater than' - // and 'greater than or equal' operations, so make sure we are not - // trying to do that. - if (lt == null) { + // It does not make sense to assign a value to both the 'less than' + // and 'less than or equal' operations, so make sure we are not + // trying to do that. + if (lte == null) { - // Make sure that we are not trying to mix both numeric and date - // type values in the same queries. - if (((gt != null) && !typesMatch(lte, gt)) - || ((gte != null) && !typesMatch(lte, gte))) { - throw new IllegalArgumentException("Cannot mix date and numeric values in the same ranged query"); - } + // Make sure that we are not trying to mix both numeric and date + // type values in the same queries. + if (((gt != null) && !typesMatch(lt, gt)) || ((gte != null) && !typesMatch(lt, gte))) { + throw new IllegalArgumentException("Cannot mix date and numeric values in the same ranged query"); + } - // If we made it here, then we're all good. Store the value. + // If we made it here, then we're all good. Store the value. - this.lte = lte; - } else { - throw new IllegalArgumentException("Cannot assign both 'lt' and 'lte' fields in the same ranged query"); + this.lt = lt; + } else { + throw new IllegalArgumentException("Cannot assign both 'lt' and 'lte' fields in the same ranged query"); + } } - } - - public String getFormat() { - return format; - } - - public void setFormat(String format) { - this.format = format; - } - - public String getTimeZone() { - return timeZone; - } - - public void setTimeZone(String timeZone) { - this.timeZone = timeZone; - } - - /** - * This convenience method determines whether or not the supplied - * value needs to be enclosed in '"' characters when generating - * ElasticSearch compatible syntax. - * - * @param val - The value to check. - * @return - A string representation of the value for inclusion - * in an ElasticSearch syntax string. - */ - private String formatStringOrNumericVal(Object val) { - - if (val instanceof String) { - return "\"" + val.toString() + "\""; - } else { - return val.toString(); + + public Object getLte() { + return lte; } - } - - - /** - * This convenience method verifies that the supplied objects are - * of classes considered to be compatible for a ranged query. - * - * @param value1 - The first value to check. - * @param value2 - The second value to check. - * @return - True if the two objects are compatible for inclusion in the - * same ranged query, False, otherwise. - */ - boolean typesMatch(Object value1, Object value2) { - - return ((value1 instanceof String) && (value2 instanceof String)) - || (!(value1 instanceof String) && !(value2 instanceof String)); - } - - - /** - * This method returns a string which represents this query in syntax - * that is understandable by ElasticSearch and is suitable for inclusion - * in an ElasticSearch query string. - * - * @return - ElasticSearch syntax string. - */ - public String toElasticSearch() { - - StringBuilder sb = new StringBuilder(); - - sb.append("{"); - sb.append("\"range\": {"); - sb.append("\"").append(field).append("\": {"); - - // We may have one or zero of 'greater than' or 'greater - // than or equal' - boolean needComma = false; - if (gte != null) { - sb.append("\"gte\": ").append(formatStringOrNumericVal(gte)); - needComma = true; - } else if (gt != null) { - sb.append("\"gt\": ").append(formatStringOrNumericVal(gt)); - needComma = true; + + public void setLte(Object lte) { + + // It does not make sense to assign a value to both the 'greater than' + // and 'greater than or equal' operations, so make sure we are not + // trying to do that. + if (lt == null) { + + // Make sure that we are not trying to mix both numeric and date + // type values in the same queries. + if (((gt != null) && !typesMatch(lte, gt)) || ((gte != null) && !typesMatch(lte, gte))) { + throw new IllegalArgumentException("Cannot mix date and numeric values in the same ranged query"); + } + + // If we made it here, then we're all good. Store the value. + + this.lte = lte; + } else { + throw new IllegalArgumentException("Cannot assign both 'lt' and 'lte' fields in the same ranged query"); + } } - // We may have one or zero of 'less than' or 'less - // than or equal' - if (lte != null) { - if (needComma) { - sb.append(", "); - } - sb.append("\"lte\": ").append(formatStringOrNumericVal(lte)); - } else if (lt != null) { - if (needComma) { - sb.append(", "); - } - sb.append("\"lt\": ").append(formatStringOrNumericVal(lt)); + public String getFormat() { + return format; } - // Append the format specifier if one was provided. - if (format != null) { - sb.append(", \"format\": \"").append(format).append("\""); + public void setFormat(String format) { + this.format = format; } - // Append the time zone specifier if one was provided. - if (timeZone != null) { - sb.append(", \"time_zone\": \"").append(timeZone).append("\""); + public String getTimeZone() { + return timeZone; } - sb.append("}"); - sb.append("}"); - sb.append("}"); + public void setTimeZone(String timeZone) { + this.timeZone = timeZone; + } - return sb.toString(); - } + /** + * This convenience method determines whether or not the supplied value needs to be enclosed in '"' characters when + * generating ElasticSearch compatible syntax. + * + * @param val - The value to check. + * @return - A string representation of the value for inclusion in an ElasticSearch syntax string. + */ + private String formatStringOrNumericVal(Object val) { + + if (val instanceof String) { + return "\"" + val.toString() + "\""; + } else { + return val.toString(); + } + } - @Override - public String toString() { - String str = "{ field: " + field + ", "; + /** + * This convenience method verifies that the supplied objects are of classes considered to be compatible for a + * ranged query. + * + * @param value1 - The first value to check. + * @param value2 - The second value to check. + * @return - True if the two objects are compatible for inclusion in the same ranged query, False, otherwise. + */ + boolean typesMatch(Object value1, Object value2) { - if (gt != null) { - str += "gt: " + gt; - } else if (gte != null) { - str += "gte: " + gte; + return ((value1 instanceof String) && (value2 instanceof String)) + || (!(value1 instanceof String) && !(value2 instanceof String)); } - if (lt != null) { - str += (((gt != null) || (gte != null)) ? ", " : "") + "lt: " + lt; - } else if (lte != null) { - str += (((gt != null) || (gte != null)) ? ", " : "") + "lte: " + lte; + + /** + * This method returns a string which represents this query in syntax that is understandable by ElasticSearch and is + * suitable for inclusion in an ElasticSearch query string. + * + * @return - ElasticSearch syntax string. + */ + public String toElasticSearch() { + + StringBuilder sb = new StringBuilder(); + + sb.append("{"); + sb.append("\"range\": {"); + sb.append("\"").append(field).append("\": {"); + + // We may have one or zero of 'greater than' or 'greater + // than or equal' + boolean needComma = false; + if (gte != null) { + sb.append("\"gte\": ").append(formatStringOrNumericVal(gte)); + needComma = true; + } else if (gt != null) { + sb.append("\"gt\": ").append(formatStringOrNumericVal(gt)); + needComma = true; + } + + // We may have one or zero of 'less than' or 'less + // than or equal' + if (lte != null) { + if (needComma) { + sb.append(", "); + } + sb.append("\"lte\": ").append(formatStringOrNumericVal(lte)); + } else if (lt != null) { + if (needComma) { + sb.append(", "); + } + sb.append("\"lt\": ").append(formatStringOrNumericVal(lt)); + } + + // Append the format specifier if one was provided. + if (format != null) { + sb.append(", \"format\": \"").append(format).append("\""); + } + + // Append the time zone specifier if one was provided. + if (timeZone != null) { + sb.append(", \"time_zone\": \"").append(timeZone).append("\""); + } + + sb.append("}"); + sb.append("}"); + sb.append("}"); + + return sb.toString(); } - str += "}"; + @Override + public String toString() { - return str; - } + String str = "{ field: " + field + ", "; + + if (gt != null) { + str += "gt: " + gt; + } else if (gte != null) { + str += "gte: " + gte; + } + + if (lt != null) { + str += (((gt != null) || (gte != null)) ? ", " : "") + "lt: " + lt; + } else if (lte != null) { + str += (((gt != null) || (gte != null)) ? ", " : "") + "lte: " + lte; + } + + str += "}"; + + return str; + } } diff --git a/src/main/java/org/onap/aai/sa/searchdbabstraction/searchapi/SearchStatement.java b/src/main/java/org/onap/aai/sa/searchdbabstraction/searchapi/SearchStatement.java index f008a7c..9f37856 100644 --- a/src/main/java/org/onap/aai/sa/searchdbabstraction/searchapi/SearchStatement.java +++ b/src/main/java/org/onap/aai/sa/searchdbabstraction/searchapi/SearchStatement.java @@ -29,9 +29,12 @@ import org.radeox.util.logging.Logger; /** * This class represents the structure of a search statement. * - * <p>The expected JSON structure to represent a search statement is as follows: + * <p> + * The expected JSON structure to represent a search statement is as follows: * - * <p><pre> + * <p> + * + * <pre> * { * "results-start": int, - Optional: index of starting point in result set. * "results-size": int, - Optional: maximum number of documents to include in result set. @@ -60,261 +63,258 @@ import org.radeox.util.logging.Logger; */ public class SearchStatement { - /** - * Defines the filters that should be applied before running the - * actual queries. This is optional. - */ - private Filter filter; + /** + * Defines the filters that should be applied before running the actual queries. This is optional. + */ + private Filter filter; - /** - * The list of queries to be applied to the document store. - */ - private Query[] queries; - - /** - * The list of aggregations to be applied to the search - */ - private Aggregation[] aggregations; - - /** - * Defines the sort criteria to apply to the query result set. - * This is optional. - */ - private Sort sort; - - @JsonProperty("results-start") - private Integer resultsStart; - - @JsonProperty("results-size") - private Integer size; - - public Filter getFilter() { - return filter; - } - - public void setFilter(Filter filter) { - this.filter = filter; - } - - public Query[] getQueries() { - return queries; - } - - public void setQueries(Query[] queries) { - this.queries = queries; - } - - public Sort getSort() { - return sort; - } - - public void setSort(Sort sort) { - this.sort = sort; - } - - public boolean isFiltered() { - return filter != null; - } - - public Aggregation[] getAggregations() { - return aggregations; - } - - public void setAggregations(Aggregation[] aggregations) { - this.aggregations = aggregations; - } - - public boolean hasAggregations() { - return aggregations != null && aggregations.length > 0; - } - - public Integer getFrom() { - return resultsStart; - } - - public void setFrom(Integer from) { - this.resultsStart = from; - } - - public Integer getSize() { - return size; - } - - public void setSize(Integer size) { - this.size = size; - } - - /** - * This method returns a string which represents this statement in syntax - * that is understandable by ElasticSearch and is suitable for inclusion - * in an ElasticSearch query string. - * - * @return - ElasticSearch syntax string. - */ - public String toElasticSearch() { - - StringBuilder sb = new StringBuilder(); - List<QueryStatement> notMatchQueries = new ArrayList<QueryStatement>(); - List<QueryStatement> mustQueries = new ArrayList<QueryStatement>(); - List<QueryStatement> shouldQueries = new ArrayList<QueryStatement>(); - - createQueryLists(queries, mustQueries, shouldQueries, notMatchQueries); - - sb.append("{"); - - sb.append("\"version\": true,"); - - // If the client has specified an index into the results for the first - // document in the result set then include that in the ElasticSearch - // query. - if (resultsStart != null) { - sb.append("\"from\": ").append(resultsStart).append(", "); - } + /** + * The list of queries to be applied to the document store. + */ + private Query[] queries; + + /** + * The list of aggregations to be applied to the search + */ + private Aggregation[] aggregations; + + /** + * Defines the sort criteria to apply to the query result set. This is optional. + */ + private Sort sort; - // If the client has specified a maximum number of documents to be returned - // in the result set then include that in the ElasticSearch query. - if (size != null) { - sb.append("\"size\": ").append(size).append(", "); + @JsonProperty("results-start") + private Integer resultsStart; + + @JsonProperty("results-size") + private Integer size; + + public Filter getFilter() { + return filter; } - sb.append("\"query\": {"); - sb.append("\"bool\": {"); + public void setFilter(Filter filter) { + this.filter = filter; + } - sb.append("\"must\": ["); - AtomicBoolean firstQuery = new AtomicBoolean(true); - for (QueryStatement query : mustQueries) { + public Query[] getQueries() { + return queries; + } - if (!firstQuery.compareAndSet(true, false)) { - sb.append(", "); - } + public void setQueries(Query[] queries) { + this.queries = queries; + } - sb.append(query.toElasticSearch()); + public Sort getSort() { + return sort; } - sb.append("], "); - sb.append("\"should\": ["); + public void setSort(Sort sort) { + this.sort = sort; + } - firstQuery = new AtomicBoolean(true); - for (QueryStatement query : shouldQueries) { + public boolean isFiltered() { + return filter != null; + } - if (!firstQuery.compareAndSet(true, false)) { - sb.append(", "); - } + public Aggregation[] getAggregations() { + return aggregations; + } - sb.append(query.toElasticSearch()); + public void setAggregations(Aggregation[] aggregations) { + this.aggregations = aggregations; } - sb.append("],"); // close should list + public boolean hasAggregations() { + return aggregations != null && aggregations.length > 0; + } - sb.append("\"must_not\": ["); - firstQuery.set(true); - for (QueryStatement query : notMatchQueries) { - sb.append(query.toElasticSearch()); + public Integer getFrom() { + return resultsStart; } - sb.append("]"); - // Add the filter stanza, if one is required. - if (isFiltered()) { - sb.append(", \"filter\": ").append(filter.toElasticSearch()); + public void setFrom(Integer from) { + this.resultsStart = from; } - sb.append("}"); // close bool clause - sb.append("}"); // close query clause + public Integer getSize() { + return size; + } - // Add the sort directive, if one is required. - if (sort != null) { - sb.append(", \"sort\": ").append(sort.toElasticSearch()); + public void setSize(Integer size) { + this.size = size; } - // Add aggregations - if (hasAggregations()) { - sb.append(", \"aggs\": {"); + /** + * This method returns a string which represents this statement in syntax that is understandable by ElasticSearch + * and is suitable for inclusion in an ElasticSearch query string. + * + * @return - ElasticSearch syntax string. + */ + public String toElasticSearch() { + + StringBuilder sb = new StringBuilder(); + List<QueryStatement> notMatchQueries = new ArrayList<QueryStatement>(); + List<QueryStatement> mustQueries = new ArrayList<QueryStatement>(); + List<QueryStatement> shouldQueries = new ArrayList<QueryStatement>(); + + createQueryLists(queries, mustQueries, shouldQueries, notMatchQueries); - for (int i = 0; i < aggregations.length; i++) { - if (i > 0) { - sb.append(","); + sb.append("{"); + + sb.append("\"version\": true,"); + + // If the client has specified an index into the results for the first + // document in the result set then include that in the ElasticSearch + // query. + if (resultsStart != null) { + sb.append("\"from\": ").append(resultsStart).append(", "); } - sb.append(aggregations[i].toElasticSearch()); - } - sb.append("}"); - } + // If the client has specified a maximum number of documents to be returned + // in the result set then include that in the ElasticSearch query. + if (size != null) { + sb.append("\"size\": ").append(size).append(", "); + } + + sb.append("\"query\": {"); + sb.append("\"bool\": {"); + + sb.append("\"must\": ["); + AtomicBoolean firstQuery = new AtomicBoolean(true); + for (QueryStatement query : mustQueries) { + + if (!firstQuery.compareAndSet(true, false)) { + sb.append(", "); + } + + sb.append(query.toElasticSearch()); + } + sb.append("], "); - sb.append("}"); + sb.append("\"should\": ["); - Logger.debug("Generated raw ElasticSearch query statement: " + sb.toString()); - return sb.toString(); - } + firstQuery = new AtomicBoolean(true); + for (QueryStatement query : shouldQueries) { - private void createQueryLists(Query[] queries, List<QueryStatement> mustList, - List<QueryStatement> mayList, List<QueryStatement> mustNotList) { + if (!firstQuery.compareAndSet(true, false)) { + sb.append(", "); + } - for (Query query : queries) { + sb.append(query.toElasticSearch()); + } - if (query.isMust()) { + sb.append("],"); // close should list - if (query.getQueryStatement().isNotMatch()) { - mustNotList.add(query.getQueryStatement()); - } else { - mustList.add(query.getQueryStatement()); + sb.append("\"must_not\": ["); + firstQuery.set(true); + for (QueryStatement query : notMatchQueries) { + sb.append(query.toElasticSearch()); } - } else { + sb.append("]"); - if (query.getQueryStatement().isNotMatch()) { - mustNotList.add(query.getQueryStatement()); - } else { - mayList.add(query.getQueryStatement()); + // Add the filter stanza, if one is required. + if (isFiltered()) { + sb.append(", \"filter\": ").append(filter.toElasticSearch()); } - } - } - } + sb.append("}"); // close bool clause + sb.append("}"); // close query clause - @Override - public String toString() { + // Add the sort directive, if one is required. + if (sort != null) { + sb.append(", \"sort\": ").append(sort.toElasticSearch()); + } - StringBuilder sb = new StringBuilder(); + // Add aggregations + if (hasAggregations()) { + sb.append(", \"aggs\": {"); - sb.append("SEARCH STATEMENT: {"); + for (int i = 0; i < aggregations.length; i++) { + if (i > 0) { + sb.append(","); + } + sb.append(aggregations[i].toElasticSearch()); + } - if (size != null) { - sb.append("from: ").append(resultsStart).append(", size: ").append(size).append(", "); - } + sb.append("}"); + } - if (filter != null) { - sb.append("filter: ").append(filter.toString()).append(", "); + sb.append("}"); + + Logger.debug("Generated raw ElasticSearch query statement: " + sb.toString()); + return sb.toString(); } - sb.append("queries: ["); - AtomicBoolean firstQuery = new AtomicBoolean(true); - if (queries != null) { - for (Query query : queries) { + private void createQueryLists(Query[] queries, List<QueryStatement> mustList, List<QueryStatement> mayList, + List<QueryStatement> mustNotList) { + + for (Query query : queries) { + + if (query.isMust()) { - if (!firstQuery.compareAndSet(true, false)) { - sb.append(", "); + if (query.getQueryStatement().isNotMatch()) { + mustNotList.add(query.getQueryStatement()); + } else { + mustList.add(query.getQueryStatement()); + } + } else { + + if (query.getQueryStatement().isNotMatch()) { + mustNotList.add(query.getQueryStatement()); + } else { + mayList.add(query.getQueryStatement()); + } + } } - sb.append(query.toString()); - } } - sb.append("]"); - sb.append("aggregations: ["); - firstQuery = new AtomicBoolean(true); - if (aggregations != null) { - for (Aggregation agg : aggregations) { + @Override + public String toString() { + + StringBuilder sb = new StringBuilder(); + + sb.append("SEARCH STATEMENT: {"); - if (!firstQuery.compareAndSet(true, false)) { - sb.append(", "); + if (size != null) { + sb.append("from: ").append(resultsStart).append(", size: ").append(size).append(", "); } - sb.append(agg.toString()); - } - } - sb.append("]"); - sb.append("]}"); + if (filter != null) { + sb.append("filter: ").append(filter.toString()).append(", "); + } + + sb.append("queries: ["); + AtomicBoolean firstQuery = new AtomicBoolean(true); + if (queries != null) { + for (Query query : queries) { + + if (!firstQuery.compareAndSet(true, false)) { + sb.append(", "); + } + sb.append(query.toString()); + } + } + sb.append("]"); + + sb.append("aggregations: ["); + firstQuery = new AtomicBoolean(true); - return sb.toString(); - } + if (aggregations != null) { + for (Aggregation agg : aggregations) { + + if (!firstQuery.compareAndSet(true, false)) { + sb.append(", "); + } + sb.append(agg.toString()); + } + } + sb.append("]"); + + sb.append("]}"); + + return sb.toString(); + } } diff --git a/src/main/java/org/onap/aai/sa/searchdbabstraction/searchapi/Sort.java b/src/main/java/org/onap/aai/sa/searchdbabstraction/searchapi/Sort.java index 641ac55..104c4b0 100644 --- a/src/main/java/org/onap/aai/sa/searchdbabstraction/searchapi/Sort.java +++ b/src/main/java/org/onap/aai/sa/searchdbabstraction/searchapi/Sort.java @@ -22,51 +22,51 @@ package org.onap.aai.sa.searchdbabstraction.searchapi; public class Sort { - private String field; - private SortDirection order = null; + private String field; + private SortDirection order = null; - public enum SortDirection { - ascending, - descending - } + public enum SortDirection { + ascending, + descending + } - 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 SortDirection getOrder() { - return order; - } + public SortDirection getOrder() { + return order; + } - public void setOrder(SortDirection order) { - this.order = order; - } + public void setOrder(SortDirection order) { + this.order = order; + } - public String toElasticSearch() { + public String toElasticSearch() { - StringBuilder sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); - sb.append("{ \"").append(field).append("\": { \"order\": "); + sb.append("{ \"").append(field).append("\": { \"order\": "); - // If a sort order wasn't explicitly supplied, default to 'ascending'. - if (order != null) { - switch (order) { - case ascending: - sb.append("\"asc\"}}"); - break; - case descending: - sb.append("\"desc\"}}"); - break; - default: - } - } else { - sb.append("\"asc\"}}"); - } + // If a sort order wasn't explicitly supplied, default to 'ascending'. + if (order != null) { + switch (order) { + case ascending: + sb.append("\"asc\"}}"); + break; + case descending: + sb.append("\"desc\"}}"); + break; + default: + } + } else { + sb.append("\"asc\"}}"); + } - return sb.toString(); - } + return sb.toString(); + } } diff --git a/src/main/java/org/onap/aai/sa/searchdbabstraction/searchapi/SuggestionStatement.java b/src/main/java/org/onap/aai/sa/searchdbabstraction/searchapi/SuggestionStatement.java index 1bc93b6..2002748 100644 --- a/src/main/java/org/onap/aai/sa/searchdbabstraction/searchapi/SuggestionStatement.java +++ b/src/main/java/org/onap/aai/sa/searchdbabstraction/searchapi/SuggestionStatement.java @@ -67,8 +67,8 @@ public class SuggestionStatement { } /** - * This method returns a string which represents this statement in syntax that is understandable - * by ElasticSearch and is suitable for inclusion in an ElasticSearch query string. + * This method returns a string which represents this statement in syntax that is understandable by ElasticSearch + * and is suitable for inclusion in an ElasticSearch query string. * * @return - ElasticSearch syntax string. */ diff --git a/src/main/java/org/onap/aai/sa/searchdbabstraction/searchapi/TermQuery.java b/src/main/java/org/onap/aai/sa/searchdbabstraction/searchapi/TermQuery.java index 08bd501..b8afa7e 100644 --- a/src/main/java/org/onap/aai/sa/searchdbabstraction/searchapi/TermQuery.java +++ b/src/main/java/org/onap/aai/sa/searchdbabstraction/searchapi/TermQuery.java @@ -28,18 +28,20 @@ import java.util.concurrent.atomic.AtomicBoolean; /** * This class represents a simple term query. * - * <p>A term query takes an operator, a field to apply the query to and a value to match - * against the query contents. + * <p> + * A term query takes an operator, a field to apply the query to and a value to match against the query contents. * - * <p>Valid operators include: + * <p> + * Valid operators include: * <ul> - * <li> match - Field must contain the supplied value to produce a match. </li> - * <li> not-match - Field must NOT contain the supplied value to produce a match. </li> + * <li>match - Field must contain the supplied value to produce a match.</li> + * <li>not-match - Field must NOT contain the supplied value to produce a match.</li> * </ul> - * The following examples illustrate the structure of a few variants of the - * term query: + * The following examples illustrate the structure of a few variants of the term query: * - * <p><pre> + * <p> + * + * <pre> * // Single Field Match Query: * { * "match": {"field": "searchTags", "value": "abcd"} @@ -51,7 +53,9 @@ import java.util.concurrent.atomic.AtomicBoolean; * } * </pre> * - * <p><pre> + * <p> + * + * <pre> * // Multi Field Match Query With A Single Value: * { * "match": {"field": "entityType searchTags", "value": "pserver"} @@ -65,280 +69,274 @@ import java.util.concurrent.atomic.AtomicBoolean; */ public class TermQuery { - /** - * The name of the field to apply the term query to. - */ - private String field; + /** + * The name of the field to apply the term query to. + */ + private String field; + + /** + * The value which the field must contain in order to have a match. + */ + private Object value; + + /** + * For multi field queries only. Determines the rules for whether or not a document matches the query, as follows: + * + * <p> + * "and" - At least one occurrence of every supplied value must be present in any of the supplied fields. + * + * <p> + * "or" - At least one occurrence of any of the supplied values must be present in any of the supplied fields. + */ + private String operator; + + @JsonProperty("analyzer") + private String searchAnalyzer; + + + public String getField() { + return field; + } + + public void setField(String field) { + this.field = field; + } - /** - * The value which the field must contain in order to have a match. - */ - private Object value; - - /** - * For multi field queries only. Determines the rules for whether or not a document matches - * the query, as follows: - * - * <p>"and" - At least one occurrence of every supplied value must be present in any of the - * supplied fields. - * - * <p>"or" - At least one occurrence of any of the supplied values must be present in any of - * the supplied fields. - */ - private String operator; - - @JsonProperty("analyzer") - private String searchAnalyzer; - - - public String getField() { - return field; - } - - public void setField(String field) { - this.field = field; - } - - public Object getValue() { - return value; - } - - public void setValue(Object value) { - this.value = value; - } - - private boolean isNumericValue() { - return ((value instanceof Integer) || (value instanceof Double)); - } - - public String getOperator() { - return operator; - } - - public void setOperator(String operator) { - this.operator = operator; - } - - public String getSearchAnalyzer() { - return searchAnalyzer; - } - - public void setSearchAnalyzer(String searchAnalyzer) { - this.searchAnalyzer = searchAnalyzer; - } - - /** - * This method returns a string which represents this query in syntax - * that is understandable by ElasticSearch and is suitable for inclusion - * in an ElasticSearch query string. - * - * @return - ElasticSearch syntax string. - */ - public String toElasticSearch() { - - StringBuilder sb = new StringBuilder(); - - sb.append("{"); - - // Are we generating a multi field query? - if (isMultiFieldQuery()) { - - // For multi field queries, we have to be careful about how we handle - // nested fields, so check to see if any of the specified fields are - // nested. - if (field.contains(".")) { - - // Build the equivalent of a multi match query across one or more nested fields. - toElasticSearchNestedMultiMatchQuery(sb); - - } else { - - // Build a real multi match query, since we don't need to worry about nested fields. - toElasticSearchMultiFieldQuery(sb); - } - } else { - - // Single field query. - - // Add the necessary wrapping if this is a query against a nested field. - if (fieldIsNested(field)) { - sb.append("{\"nested\": { \"path\": \"").append(pathForNestedField(field)) - .append("\", \"query\": "); - } - - // Build the query. - toElasticSearchSingleFieldQuery(sb); - - if (fieldIsNested(field)) { - sb.append("}}"); - } + public Object getValue() { + return value; } - sb.append("}"); + public void setValue(Object value) { + this.value = value; + } + + private boolean isNumericValue() { + return ((value instanceof Integer) || (value instanceof Double)); + } - return sb.toString(); - } + public String getOperator() { + return operator; + } + public void setOperator(String operator) { + this.operator = operator; + } - /** - * Determines whether or not the client has specified a term query with - * multiple fields. - * - * @return - true if the query is referencing multiple fields, false, otherwise. - */ - private boolean isMultiFieldQuery() { + public String getSearchAnalyzer() { + return searchAnalyzer; + } - return (field.split(" ").length > 1); - } + public void setSearchAnalyzer(String searchAnalyzer) { + this.searchAnalyzer = searchAnalyzer; + } + /** + * This method returns a string which represents this query in syntax that is understandable by ElasticSearch and is + * suitable for inclusion in an ElasticSearch query string. + * + * @return - ElasticSearch syntax string. + */ + public String toElasticSearch() { - /** - * Constructs a single field term query in ElasticSearch syntax. - * - * @param sb - The string builder to assemble the query string with. - * @return - The single term query. - */ - private void toElasticSearchSingleFieldQuery(StringBuilder sb) { + StringBuilder sb = new StringBuilder(); - sb.append("\"term\": {\"").append(field).append("\" : "); + sb.append("{"); - // For numeric values, don't enclose the value in quotes. - if (!isNumericValue()) { - sb.append("\"").append(value).append("\""); - } else { - sb.append(value); - } + // Are we generating a multi field query? + if (isMultiFieldQuery()) { - sb.append("}"); - } + // For multi field queries, we have to be careful about how we handle + // nested fields, so check to see if any of the specified fields are + // nested. + if (field.contains(".")) { + // Build the equivalent of a multi match query across one or more nested fields. + toElasticSearchNestedMultiMatchQuery(sb); - /** - * Constructs a multi field query in ElasticSearch syntax. - * - * @param sb - The string builder to assemble the query string with. - * @return - The multi field query. - */ - private void toElasticSearchMultiFieldQuery(StringBuilder sb) { + } else { - sb.append("\"multi_match\": {"); + // Build a real multi match query, since we don't need to worry about nested fields. + toElasticSearchMultiFieldQuery(sb); + } + } else { - sb.append("\"query\": \"").append(value).append("\", "); - sb.append("\"type\": \"cross_fields\","); - sb.append("\"fields\": ["); + // Single field query. - List<String> fields = Arrays.asList(field.split(" ")); - AtomicBoolean firstField = new AtomicBoolean(true); - for (String f : fields) { - if (!firstField.compareAndSet(true, false)) { - sb.append(", "); - } - sb.append("\"").append(f.trim()).append("\""); - } - sb.append("],"); + // Add the necessary wrapping if this is a query against a nested field. + if (fieldIsNested(field)) { + sb.append("{\"nested\": { \"path\": \"").append(pathForNestedField(field)).append("\", \"query\": "); + } - sb.append("\"operator\": \"").append((operator != null) - ? operator.toLowerCase() : "and").append("\""); + // Build the query. + toElasticSearchSingleFieldQuery(sb); - if (searchAnalyzer != null) { - sb.append(", \"analyzer\": \"").append(searchAnalyzer).append("\""); + if (fieldIsNested(field)) { + sb.append("}}"); + } + } + + sb.append("}"); + + return sb.toString(); } - sb.append("}"); - } + /** + * Determines whether or not the client has specified a term query with multiple fields. + * + * @return - true if the query is referencing multiple fields, false, otherwise. + */ + private boolean isMultiFieldQuery() { - /** - * Constructs the equivalent of an ElasticSearch multi match query across - * multiple nested fields. - * - * <p>Since ElasticSearch doesn't really let you do that, we have to be clever - * and construct an equivalent query using boolean operators to produce - * the same result. - * - * @param sb - The string builder to use to build the query. - */ - public void toElasticSearchNestedMultiMatchQuery(StringBuilder sb) { + return (field.split(" ").length > 1); + } - // Break out our whitespace delimited list of fields and values into a actual lists. - List<String> fields = Arrays.asList(field.split(" ")); - List<String> values = Arrays.asList(((String) value).split(" ")); // GDF: revisit this cast. - sb.append("\"bool\": {"); + /** + * Constructs a single field term query in ElasticSearch syntax. + * + * @param sb - The string builder to assemble the query string with. + * @return - The single term query. + */ + private void toElasticSearchSingleFieldQuery(StringBuilder sb) { - if (operator != null) { + sb.append("\"term\": {\"").append(field).append("\" : "); - if (operator.toLowerCase().equals("and")) { - sb.append("\"must\": ["); - } else if (operator.toLowerCase().equals("or")) { - sb.append("\"should\": ["); - } + // For numeric values, don't enclose the value in quotes. + if (!isNumericValue()) { + sb.append("\"").append(value).append("\""); + } else { + sb.append(value); + } - } else { - sb.append("\"must\": ["); + sb.append("}"); } - AtomicBoolean firstField = new AtomicBoolean(true); - for (String f : fields) { - if (!firstField.compareAndSet(true, false)) { - sb.append(", "); - } + /** + * Constructs a multi field query in ElasticSearch syntax. + * + * @param sb - The string builder to assemble the query string with. + * @return - The multi field query. + */ + private void toElasticSearchMultiFieldQuery(StringBuilder sb) { - sb.append("{ "); + sb.append("\"multi_match\": {"); - // Is this a nested field? - if (fieldIsNested(f)) { + sb.append("\"query\": \"").append(value).append("\", "); + sb.append("\"type\": \"cross_fields\","); + sb.append("\"fields\": ["); - sb.append("\"nested\": {"); - sb.append("\"path\": \"").append(pathForNestedField(f)).append("\", "); - sb.append("\"query\": "); - } + List<String> fields = Arrays.asList(field.split(" ")); + AtomicBoolean firstField = new AtomicBoolean(true); + for (String f : fields) { + if (!firstField.compareAndSet(true, false)) { + sb.append(", "); + } + sb.append("\"").append(f.trim()).append("\""); + } + sb.append("],"); - sb.append("{\"bool\": {"); - sb.append("\"should\": ["); + sb.append("\"operator\": \"").append((operator != null) ? operator.toLowerCase() : "and").append("\""); - AtomicBoolean firstValue = new AtomicBoolean(true); - for (String v : values) { - if (!firstValue.compareAndSet(true, false)) { - sb.append(", "); + if (searchAnalyzer != null) { + sb.append(", \"analyzer\": \"").append(searchAnalyzer).append("\""); } - sb.append("{\"match\": { \""); - sb.append(f).append("\": {\"query\": \"").append(v).append("\""); - if (searchAnalyzer != null) { - sb.append(", \"analyzer\": \"").append(searchAnalyzer).append("\""); + sb.append("}"); + } + + + /** + * Constructs the equivalent of an ElasticSearch multi match query across multiple nested fields. + * + * <p> + * Since ElasticSearch doesn't really let you do that, we have to be clever and construct an equivalent query using + * boolean operators to produce the same result. + * + * @param sb - The string builder to use to build the query. + */ + public void toElasticSearchNestedMultiMatchQuery(StringBuilder sb) { + + // Break out our whitespace delimited list of fields and values into a actual lists. + List<String> fields = Arrays.asList(field.split(" ")); + List<String> values = Arrays.asList(((String) value).split(" ")); // GDF: revisit this cast. + + sb.append("\"bool\": {"); + + if (operator != null) { + + if (operator.toLowerCase().equals("and")) { + sb.append("\"must\": ["); + } else if (operator.toLowerCase().equals("or")) { + sb.append("\"should\": ["); + } + + } else { + sb.append("\"must\": ["); } - sb.append("}}}"); - } - sb.append("]"); - sb.append("}"); + AtomicBoolean firstField = new AtomicBoolean(true); + for (String f : fields) { - if (fieldIsNested(f)) { - sb.append("}"); - sb.append("}"); - } + if (!firstField.compareAndSet(true, false)) { + sb.append(", "); + } - sb.append("}"); - } + sb.append("{ "); + + // Is this a nested field? + if (fieldIsNested(f)) { + + sb.append("\"nested\": {"); + sb.append("\"path\": \"").append(pathForNestedField(f)).append("\", "); + sb.append("\"query\": "); + } - sb.append("]"); - sb.append("}"); - } + sb.append("{\"bool\": {"); + sb.append("\"should\": ["); + AtomicBoolean firstValue = new AtomicBoolean(true); + for (String v : values) { + if (!firstValue.compareAndSet(true, false)) { + sb.append(", "); + } + sb.append("{\"match\": { \""); + sb.append(f).append("\": {\"query\": \"").append(v).append("\""); - @Override - public String toString() { - return "field: " + field + ", value: " + value + " (" + value.getClass().getName() + ")"; - } + if (searchAnalyzer != null) { + sb.append(", \"analyzer\": \"").append(searchAnalyzer).append("\""); + } + sb.append("}}}"); + } - public boolean fieldIsNested(String field) { - return field.contains("."); - } + sb.append("]"); + sb.append("}"); - public String pathForNestedField(String field) { - int index = field.lastIndexOf('.'); - return field.substring(0, index); - } + if (fieldIsNested(f)) { + sb.append("}"); + sb.append("}"); + } + + sb.append("}"); + } + + sb.append("]"); + sb.append("}"); + } + + + @Override + public String toString() { + return "field: " + field + ", value: " + value + " (" + value.getClass().getName() + ")"; + } + + public boolean fieldIsNested(String field) { + return field.contains("."); + } + + public String pathForNestedField(String field) { + int index = field.lastIndexOf('.'); + return field.substring(0, index); + } } 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 2d7a290..350ddf0 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 @@ -32,25 +32,25 @@ import org.springframework.beans.factory.annotation.Autowired; public class SearchService { - private ElasticSearchHttpController esController = null; + 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)); + esController = 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 93ee23e..def3f04 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 @@ -29,73 +29,71 @@ import org.onap.aai.sa.searchdbabstraction.entity.AggregationBucket; import org.onap.aai.sa.searchdbabstraction.entity.AggregationResult; public class AggregationParsingUtil { - public static AggregationResult[] parseAggregationResults(JSONObject aggregations) - throws JsonProcessingException { + public static AggregationResult[] parseAggregationResults(JSONObject aggregations) throws JsonProcessingException { - // Obtain the set of aggregation names - Set keySet = aggregations.keySet(); - AggregationResult[] aggResults = new AggregationResult[keySet.size()]; + // Obtain the set of aggregation names + Set keySet = aggregations.keySet(); + AggregationResult[] aggResults = new AggregationResult[keySet.size()]; - int index = 0; - for (Iterator it = keySet.iterator(); it.hasNext(); ) { - String key = (String) it.next(); - AggregationResult aggResult = new AggregationResult(); - aggResult.setName(key); + int index = 0; + for (Iterator it = keySet.iterator(); it.hasNext();) { + String key = (String) it.next(); + AggregationResult aggResult = new AggregationResult(); + aggResult.setName(key); - JSONObject bucketsOrNested = (JSONObject) aggregations.get(key); - Object buckets = bucketsOrNested.get("buckets"); - if (buckets == null) { - // we have a nested - Number count = (Number) bucketsOrNested.remove("doc_count"); - aggResult.setCount(count); - AggregationResult[] nestedResults = parseAggregationResults(bucketsOrNested); - aggResult.setNestedAggregations(nestedResults); - } else { - AggregationBucket[] aggBuckets = parseAggregationBuckets((JSONArray) buckets); - aggResult.setBuckets(aggBuckets); - } + JSONObject bucketsOrNested = (JSONObject) aggregations.get(key); + Object buckets = bucketsOrNested.get("buckets"); + if (buckets == null) { + // we have a nested + Number count = (Number) bucketsOrNested.remove("doc_count"); + aggResult.setCount(count); + AggregationResult[] nestedResults = parseAggregationResults(bucketsOrNested); + aggResult.setNestedAggregations(nestedResults); + } else { + AggregationBucket[] aggBuckets = parseAggregationBuckets((JSONArray) buckets); + aggResult.setBuckets(aggBuckets); + } - aggResults[index] = aggResult; - index++; - } + aggResults[index] = aggResult; + index++; + } - return aggResults; + return aggResults; - } + } - private static AggregationBucket[] parseAggregationBuckets(JSONArray buckets) - throws JsonProcessingException { - AggregationBucket[] aggBuckets = new AggregationBucket[buckets.size()]; - for (int i = 0; i < buckets.size(); i++) { - AggregationBucket aggBucket = new AggregationBucket(); - JSONObject bucketContent = (JSONObject) buckets.get(i); - Object key = bucketContent.remove("key"); - aggBucket.setKey(key); - Object formatted = bucketContent.remove("key_as_string"); - if (formatted != null) { - aggBucket.setFormattedKey((String) formatted); - } - Object count = bucketContent.remove("doc_count"); - if (count != null) { - aggBucket.setCount((Number) count); - } - bucketContent.remove("from"); - bucketContent.remove("from_as_string"); - bucketContent.remove("to"); - bucketContent.remove("to_as_string"); + private static AggregationBucket[] parseAggregationBuckets(JSONArray buckets) throws JsonProcessingException { + AggregationBucket[] aggBuckets = new AggregationBucket[buckets.size()]; + for (int i = 0; i < buckets.size(); i++) { + AggregationBucket aggBucket = new AggregationBucket(); + JSONObject bucketContent = (JSONObject) buckets.get(i); + Object key = bucketContent.remove("key"); + aggBucket.setKey(key); + Object formatted = bucketContent.remove("key_as_string"); + if (formatted != null) { + aggBucket.setFormattedKey((String) formatted); + } + Object count = bucketContent.remove("doc_count"); + if (count != null) { + aggBucket.setCount((Number) count); + } + bucketContent.remove("from"); + bucketContent.remove("from_as_string"); + bucketContent.remove("to"); + bucketContent.remove("to_as_string"); - if (!bucketContent.entrySet().isEmpty()) { - // we have results from sub-aggregation - AggregationResult[] subResult = parseAggregationResults(bucketContent); - if (subResult != null) { - aggBucket.setSubAggregationResult(subResult); + if (!bucketContent.entrySet().isEmpty()) { + // we have results from sub-aggregation + AggregationResult[] subResult = parseAggregationResults(bucketContent); + if (subResult != null) { + aggBucket.setSubAggregationResult(subResult); + } + } + aggBuckets[i] = aggBucket; } - } - aggBuckets[i] = aggBucket; - } - return aggBuckets; - } + return aggBuckets; + } } 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 a22f59e..09ef76b 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 @@ -34,104 +34,106 @@ import org.onap.aai.sa.rest.DocumentSchema; public class DocumentSchemaUtil { - 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 { + private static String dynamicCustomMapping = null; + private static final String DYNAMIC_CUSTOM_TEMPALTE_FILE = + System.getProperty("CONFIG_HOME") + File.separator + "dynamic-custom-template.json"; - // Unmarshal the json content into a document schema object. - ObjectMapper mapper = new ObjectMapper(); - DocumentSchema schema = mapper.readValue(documentSchema, DocumentSchema.class); + public static String generateDocumentMappings(String documentSchema) + throws JsonParseException, JsonMappingException, IOException { - return generateDocumentMappings(schema); - } + // Unmarshal the json content into a document schema object. + ObjectMapper mapper = new ObjectMapper(); + DocumentSchema schema = mapper.readValue(documentSchema, DocumentSchema.class); - public static String generateDocumentMappings(DocumentSchema schema) throws IOException { - - // Adding dynamic template to add fielddata=true to dynamic fields of type "string" - // in order to avoid aggregation queries breaking in ESv6.1.2 - if(dynamicCustomMapping == null) { - try { - dynamicCustomMapping = IOUtils.toString(new FileInputStream(DYNAMIC_CUSTOM_TEMPALTE_FILE), "UTF-8").replaceAll("\\s+", ""); - } catch (IOException e) { - throw new IOException("Dynamic Custom template configuration went wrong! Please check for the correct template file.", e); - } - } - - // Now, generate the Elastic Search mapping json and return it. - StringBuilder sb = new StringBuilder(); - sb.append("{"); - // Adding custom mapping which adds fielddata=true to dynamic fields of type "string" - sb.append(dynamicCustomMapping != null ? dynamicCustomMapping : ""); - sb.append("\"properties\": {"); - - generateFieldMappings(schema.getFields(), sb); - - sb.append("}"); - sb.append("}"); + return generateDocumentMappings(schema); + } - return sb.toString(); - } + public static String generateDocumentMappings(DocumentSchema schema) throws IOException { + + // Adding dynamic template to add fielddata=true to dynamic fields of type "string" + // in order to avoid aggregation queries breaking in ESv6.1.2 + if (dynamicCustomMapping == null) { + try { + dynamicCustomMapping = IOUtils.toString(new FileInputStream(DYNAMIC_CUSTOM_TEMPALTE_FILE), "UTF-8") + .replaceAll("\\s+", ""); + } catch (IOException e) { + throw new IOException( + "Dynamic Custom template configuration went wrong! Please check for the correct template file.", + e); + } + } + + // Now, generate the Elastic Search mapping json and return it. + StringBuilder sb = new StringBuilder(); + sb.append("{"); + // Adding custom mapping which adds fielddata=true to dynamic fields of type "string" + sb.append(dynamicCustomMapping != null ? dynamicCustomMapping : ""); + sb.append("\"properties\": {"); + + generateFieldMappings(schema.getFields(), sb); + + sb.append("}"); + sb.append("}"); + + return sb.toString(); + } - private static void generateFieldMappings(List<DocumentFieldSchema> fields, StringBuilder sb) { + private static void generateFieldMappings(List<DocumentFieldSchema> fields, StringBuilder sb) { - AtomicBoolean firstField = new AtomicBoolean(true); + AtomicBoolean firstField = new AtomicBoolean(true); - for (DocumentFieldSchema field : fields) { + for (DocumentFieldSchema field : fields) { - // If this isn't the first field in the list, prepend it with a ',' - if (!firstField.compareAndSet(true, false)) { - sb.append(", "); - } + // If this isn't the first field in the list, prepend it with a ',' + if (!firstField.compareAndSet(true, false)) { + sb.append(", "); + } - // Now, append the translated field contents. - generateFieldMapping(field, sb); + // Now, append the translated field contents. + generateFieldMapping(field, sb); + } } - } - private static void generateFieldMapping(DocumentFieldSchema fieldSchema, StringBuilder sb) { + private static void generateFieldMapping(DocumentFieldSchema fieldSchema, StringBuilder sb) { - sb.append("\"").append(fieldSchema.getName()).append("\": {"); + sb.append("\"").append(fieldSchema.getName()).append("\": {"); - // The field type is mandatory. - sb.append("\"type\": \"").append(fieldSchema.getDataType()).append("\""); + // The field type is mandatory. + 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("\""); - } - } + // 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 the index field was specified, then append it. - if (fieldSchema.getSearchable() != null) { - sb.append(", \"index\": \"").append(fieldSchema.getSearchable() - ? "analyzed" : "not_analyzed").append("\""); - } + // If the index field was specified, then append it. + if (fieldSchema.getSearchable() != null) { + sb.append(", \"index\": \"").append(fieldSchema.getSearchable() ? "analyzed" : "not_analyzed").append("\""); + } - // If a search analyzer was specified, then append it. - if (fieldSchema.getSearchAnalyzer() != null) { - sb.append(", \"search_analyzer\": \"").append(fieldSchema.getSearchAnalyzer()).append("\""); - } + // If a search analyzer was specified, then append it. + if (fieldSchema.getSearchAnalyzer() != null) { + sb.append(", \"search_analyzer\": \"").append(fieldSchema.getSearchAnalyzer()).append("\""); + } - // If an indexing analyzer was specified, then append it. - if (fieldSchema.getIndexAnalyzer() != null) { - sb.append(", \"analyzer\": \"").append(fieldSchema.getIndexAnalyzer()).append("\""); - } + // If an indexing analyzer was specified, then append it. + if (fieldSchema.getIndexAnalyzer() != null) { + sb.append(", \"analyzer\": \"").append(fieldSchema.getIndexAnalyzer()).append("\""); + } - if (fieldSchema.getDataType().equals("nested")) { + if (fieldSchema.getDataType().equals("nested")) { - sb.append(", \"properties\": {"); - generateFieldMappings(fieldSchema.getSubFields(), sb); - sb.append("}"); - } + sb.append(", \"properties\": {"); + generateFieldMappings(fieldSchema.getSubFields(), sb); + sb.append("}"); + } - sb.append("}"); - } + sb.append("}"); + } } 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 d73001b..79b145d 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 @@ -37,62 +37,64 @@ 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. + * 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". + * 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. + * 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 * */ public class ElasticSearchPayloadTranslator { - private static Logger logger = LoggerFactory.getInstance().getLogger(ElasticSearchPayloadTranslator.class.getName()); - private static final String CONFIG_DIRECTORY = System.getProperty("CONFIG_HOME"); - private static final String ES_PAYLOAD_TRANSLATION_FILE = "es-payload-translation.json"; + private static Logger logger = + LoggerFactory.getInstance().getLogger(ElasticSearchPayloadTranslator.class.getName()); + private static final String CONFIG_DIRECTORY = System.getProperty("CONFIG_HOME"); + private static final String ES_PAYLOAD_TRANSLATION_FILE = "es-payload-translation.json"; - /** - * 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 + "]"); - String pathToTranslationFile = CONFIG_DIRECTORY + File.separator + ES_PAYLOAD_TRANSLATION_FILE; + /** + * 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 + "]"); + 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"); - DocumentContext payloadToTranslate = JsonPath.parse(source); + try { - for(Object obj : attrTranslations) { - JSONObject jsonObj = ((JSONObject) obj); - String query = jsonObj.get("query").toString(); - JSONObject attrToUpdate = (JSONObject) jsonObj.get("update"); - List<Map<String, Object>> filteredObjects = payloadToTranslate.read(query); - for(Map<String, Object> objMap : filteredObjects) { - objMap.putAll(attrToUpdate.toMap()); - } - } - - 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); - } - } + JSONObject translationConfigPayload = + new JSONObject(IOUtils.toString(new FileInputStream(new File(pathToTranslationFile)), "UTF-8")); + JSONArray attrTranslations = translationConfigPayload.getJSONArray("attr-translations"); + DocumentContext payloadToTranslate = JsonPath.parse(source); + + for (Object obj : attrTranslations) { + JSONObject jsonObj = ((JSONObject) obj); + String query = jsonObj.get("query").toString(); + JSONObject attrToUpdate = (JSONObject) jsonObj.get("update"); + List<Map<String, Object>> filteredObjects = payloadToTranslate.read(query); + for (Map<String, Object> objMap : filteredObjects) { + objMap.putAll(attrToUpdate.toMap()); + } + } + + 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); + } + } } 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 bd7d58b..1171895 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 @@ -21,37 +21,32 @@ package org.onap.aai.sa.searchdbabstraction.util; public class SearchDbConstants { - 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; + 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; - // Elastic Search related - public static final String SDB_SPECIFIC_CONFIG = (System.getProperty("CONFIG_HOME") == null) - ? SDB_CONFIG_APP_LOCATION : System.getProperty("CONFIG_HOME") + SDB_FILESEP; - public static final String ES_CONFIG_FILE = SDB_SPECIFIC_CONFIG + SDB_FILESEP - + "elastic-search.properties"; - public static final String SDB_AUTH = SDB_SPECIFIC_CONFIG + "auth" + SDB_FILESEP; - public static final String SDB_AUTH_CONFIG_FILENAME = SDB_AUTH + "search_policy.json"; - 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"; + // Elastic Search related + public static final String SDB_SPECIFIC_CONFIG = (System.getProperty("CONFIG_HOME") == null) + ? SDB_CONFIG_APP_LOCATION : System.getProperty("CONFIG_HOME") + SDB_FILESEP; + public static final String ES_CONFIG_FILE = SDB_SPECIFIC_CONFIG + SDB_FILESEP + "elastic-search.properties"; + public static final String SDB_AUTH = SDB_SPECIFIC_CONFIG + "auth" + SDB_FILESEP; + public static final String SDB_AUTH_CONFIG_FILENAME = SDB_AUTH + "search_policy.json"; + 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"; + // 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"; + // Logging related + public static final String SDB_SERVICE_NAME = "SearchDataService"; } |