@SpringBootApplication\r
public class Application extends SpringBootServletInitializer {\r
\r
-\r
public static void main(String[] args) {\r
-\r
String keyStorePassword = System.getProperty("KEY_STORE_PASSWORD");\r
if (keyStorePassword == null || keyStorePassword.isEmpty()) {\r
throw new RuntimeException("Env property KEY_STORE_PASSWORD not set");\r
-/**
+/**
* ============LICENSE_START=======================================================
* org.onap.aai
* ================================================================================
private static Logger logger = LoggerFactory.getInstance().getLogger(SearchDbServiceAuthCore.class.getName());
- private static String GlobalAuthFileName = SearchDbConstants.SDB_AUTH_CONFIG_FILENAME;
+ private static String authFileName = SearchDbConstants.SDB_AUTH_CONFIG_FILENAME;
private enum HTTP_METHODS {
POST,
private static boolean usersInitialized = false;
private static HashMap<String, SearchDbAuthUser> users;
- private static boolean timerSet = false;
private static Timer timer = null;
- public synchronized static void init() {
-
-
- SearchDbServiceAuthCore.getConfigFile();
+ public static synchronized void init() {
+ if (SearchDbServiceAuthCore.authFileName == null) {
+ SearchDbServiceAuthCore.authFileName = "/home/aaiadmin/etc/aaipolicy.json";
+ }
SearchDbServiceAuthCore.reloadUsers();
-
}
public static void cleanup() {
timer.cancel();
}
- public static String getConfigFile() {
- if (GlobalAuthFileName == null) {
- String nc = GlobalAuthFileName;
- if (nc == null) {
- nc = "/home/aaiadmin/etc/aaipolicy.json";
- }
- GlobalAuthFileName = nc;
- }
- return GlobalAuthFileName;
- }
-
- public synchronized static void reloadUsers() {
+ public static synchronized void reloadUsers() {
users = new HashMap<>();
ObjectMapper mapper = new ObjectMapper(); // can reuse, share globally
JSONParser parser = new JSONParser();
try {
- parser.parse(new FileReader(GlobalAuthFileName));
- JsonNode rootNode = mapper.readTree(new File(GlobalAuthFileName));
+ parser.parse(new FileReader(authFileName));
+ JsonNode rootNode = mapper.readTree(new File(authFileName));
JsonNode rolesNode = rootNode.path("roles");
for (JsonNode roleNode : rolesNode) {
authRole.addAllowedFunction(thisFunction);
}
- if (hasMethods == false) {
+ if (!hasMethods) {
// iterate the list from HTTP_METHODS
for (HTTP_METHODS meth : HTTP_METHODS.values()) {
String thisFunction = meth.toString() + ":" + function;
-
authRole.addAllowedFunction(thisFunction);
}
}
}
for (JsonNode userNode : usersNode) {
- // make the user lower case
String username = userNode.path("username").asText().toLowerCase();
SearchDbAuthUser authUser = null;
if (users.containsKey(username)) {
authUser = new SearchDbAuthUser();
}
-
authUser.setUser(username);
authUser.addRole(roleName, authRole);
users.put(username, authUser);
return this.username;
}
- public HashMap<String, TabularAuthRole> getRoles() {
+ public Map<String, TabularAuthRole> getRoles() {
return this.roles;
}
}
public boolean hasAllowedFunction(String afunc) {
- if (this.allowedFunctions.contains(afunc)) {
- return true;
- } else {
- return false;
- }
+ return this.allowedFunctions.contains(afunc);
}
}
- public static HashMap<String, SearchDbAuthUser> getUsers(String key) {
+ public static Map<String, SearchDbAuthUser> getUsers() {
if (!usersInitialized || (users == null)) {
reloadUsers();
}
}
public static boolean authorize(String username, String authFunction) {
-
if (!usersInitialized || (users == null)) {
init();
}
if (users.containsKey(username)) {
- if (users.get(username).checkAllowed(authFunction) == true) {
-
- return true;
- } else {
-
-
- return false;
- }
+ return users.get(username).checkAllowed(authFunction);
} else {
-
return false;
}
}
-/**
+/**
* ============LICENSE_START=======================================================
* org.onap.aai
* ================================================================================
@RequestMapping("/services/search-data-service/v1/analyzers/search")
public class AnalyzerApi {
- private SearchServiceApi searchService = null;
+ private SearchServiceApi searchService = null;
- // Set up the loggers.
- private static Logger logger = LoggerFactory.getInstance().getLogger(IndexApi.class.getName());
+ // Set up the loggers.
+ private static Logger logger = LoggerFactory.getInstance().getLogger(IndexApi.class.getName());
private static Logger auditLogger = LoggerFactory.getInstance().getAuditLogger(IndexApi.class.getName());
- public AnalyzerApi(@Qualifier("searchServiceApi") SearchServiceApi searchService) {
- this.searchService = searchService;
- }
+ public AnalyzerApi( @Qualifier("searchServiceApi") SearchServiceApi searchService) {
+ this.searchService = searchService;
+ }
@RequestMapping(method = RequestMethod.GET, consumes = {"application/json"}, produces = {"application/json"})
public ResponseEntity<String> processGet(HttpServletRequest request, @RequestHeader HttpHeaders headers,
- ApiUtils apiUtils) {
+ ApiUtils apiUtils) {
- HttpStatus responseCode = HttpStatus.INTERNAL_SERVER_ERROR;
- String responseString = "Undefined error";
+ HttpStatus responseCode = HttpStatus.INTERNAL_SERVER_ERROR;
+ String responseString;
- // Initialize the MDC Context for logging purposes.
- ApiUtils.initMdcContext(request, headers);
+ // Initialize the MDC Context for logging purposes.
+ ApiUtils.initMdcContext(request, headers);
- // Validate that the request is correctly authenticated before going
- // any further.
- try {
+ // Validate that the request is correctly authenticated before going
+ // any further.
+ try {
if (!searchService.validateRequest(headers, request, ApiUtils.Action.GET,
ApiUtils.SEARCH_AUTH_POLICY_NAME)) {
- logger.warn(SearchDbMsgs.GET_ANALYZERS_FAILURE, "Authentication failure.");
+ logger.warn(SearchDbMsgs.GET_ANALYZERS_FAILURE, "Authentication failure.");
return ResponseEntity.status(HttpStatus.FORBIDDEN).contentType(MediaType.APPLICATION_JSON)
.body("Authentication failure.");
- }
+ }
- } catch (Exception e) {
+ } catch (Exception e) {
- logger.warn(SearchDbMsgs.GET_ANALYZERS_FAILURE,
- "Unexpected authentication failure - cause: " + e.getMessage());
+ logger.warn(SearchDbMsgs.GET_ANALYZERS_FAILURE,
+ "Unexpected authentication failure - cause: " + e.getMessage());
return ResponseEntity.status(HttpStatus.FORBIDDEN).contentType(MediaType.APPLICATION_JSON)
.body("Authentication failure.");
- }
+ }
- // Now, build the list of analyzers.
- try {
+ // Now, build the list of analyzers.
+ try {
responseString = buildAnalyzerList(ElasticSearchHttpController.getInstance().getAnalysisConfig());
- responseCode = HttpStatus.OK;
-
- } catch (Exception e) {
-
- logger.warn(SearchDbMsgs.GET_ANALYZERS_FAILURE,
- "Unexpected failure retrieving analysis configuration - cause: " + e.getMessage());
- responseString = "Failed to retrieve analysis configuration. Cause: " + e.getMessage();
- }
+ responseCode = HttpStatus.OK;
+ } catch (Exception e) {
+ logger.warn(SearchDbMsgs.GET_ANALYZERS_FAILURE,
+ "Unexpected failure retrieving analysis configuration - cause: " + e.getMessage());
+ responseString = "Failed to retrieve analysis configuration. Cause: " + e.getMessage();
+ }
- // Build the HTTP response.
- ResponseEntity response =
+ // Build the HTTP response.
+ ResponseEntity<String> response =
ResponseEntity.status(responseCode).contentType(MediaType.APPLICATION_JSON).body(responseString);
- // Generate our audit log.
- auditLogger.info(SearchDbMsgs.PROCESS_REST_REQUEST,
+ // Generate our audit log.
+ auditLogger.info(SearchDbMsgs.PROCESS_REST_REQUEST,
new LogFields().setField(LogLine.DefinedFields.RESPONSE_CODE, responseCode.value())
- .setField(LogLine.DefinedFields.RESPONSE_DESCRIPTION, responseCode.value()),
- (request != null) ? request.getMethod() : "Unknown",
- (request != null) ? request.getRequestURL().toString() : "Unknown",
- (request != null) ? request.getRemoteHost() : "Unknown",
- Integer.toString(response.getStatusCodeValue()));
-
- // Clear the MDC context so that no other transaction inadvertently
- // uses our transaction id.
- ApiUtils.clearMdcContext();
+ .setField(LogLine.DefinedFields.RESPONSE_DESCRIPTION, responseCode.value()),
+ (request != null) ? request.getMethod() : "Unknown",
+ (request != null) ? request.getRequestURL ().toString () : "Unknown",
+ (request != null) ? request.getRemoteHost () : "Unknown",
+ Integer.toString(response.getStatusCodeValue ()));
- return response;
- }
+ // Clear the MDC context so that no other transaction inadvertently
+ // uses our transaction id.
+ ApiUtils.clearMdcContext();
+ return response;
+ }
- /**
+ /**
* This method takes a list of analyzer objects and generates a simple json structure to enumerate them.
- *
+ *
* <p>
* Note, this includes only the aspects of the analyzer object that we want to make public to an external client.
- *
+ *
* @param analysisConfig - The analysis configuration object to extract the analyzers from.
- * @return - A json string enumerating the defined analyzers.
- */
- private String buildAnalyzerList(AnalysisConfiguration analysisConfig) {
-
- StringBuilder sb = new StringBuilder();
-
- sb.append("{");
- AtomicBoolean firstAnalyzer = new AtomicBoolean(true);
- for (AnalyzerSchema analyzer : analysisConfig.getAnalyzers()) {
-
- if (!firstAnalyzer.compareAndSet(true, false)) {
- sb.append(", ");
- }
-
- sb.append("{");
- sb.append("\"name\": \"").append(analyzer.getName()).append("\", ");
- sb.append("\"description\": \"").append(analyzer.getDescription()).append("\", ");
- sb.append("\"behaviours\": [");
- AtomicBoolean firstBehaviour = new AtomicBoolean(true);
- for (String behaviour : analyzer.getBehaviours()) {
- if (!firstBehaviour.compareAndSet(true, false)) {
- sb.append(", ");
- }
- sb.append("\"").append(behaviour).append("\"");
- }
- sb.append("]");
- sb.append("}");
+ * @return - A json string enumerating the defined analyzers.
+ */
+ private String buildAnalyzerList(AnalysisConfiguration analysisConfig) {
+
+ StringBuilder sb = new StringBuilder();
+
+ sb.append("{");
+ AtomicBoolean firstAnalyzer = new AtomicBoolean(true);
+ for (AnalyzerSchema analyzer : analysisConfig.getAnalyzers()) {
+
+ if (!firstAnalyzer.compareAndSet(true, false)) {
+ sb.append(", ");
+ }
+
+ sb.append("{");
+ sb.append("\"name\": \"").append(analyzer.getName()).append("\", ");
+ sb.append("\"description\": \"").append(analyzer.getDescription()).append("\", ");
+ sb.append("\"behaviours\": [");
+ AtomicBoolean firstBehaviour = new AtomicBoolean(true);
+ for (String behaviour : analyzer.getBehaviours()) {
+ if (!firstBehaviour.compareAndSet(true, false)) {
+ sb.append(", ");
}
- sb.append("}");
-
- return sb.toString();
+ sb.append("\"").append(behaviour).append("\"");
+ }
+ sb.append("]");
+ sb.append("}");
}
+ sb.append("}");
+
+ return sb.toString();
+ }
}
-/**
+/**
* ============LICENSE_START=======================================================
* org.onap.aai
* ================================================================================
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
-// Spring Imports
-
+/**
+ * Spring Imports.
+ *
+ */
public class ApiUtils {
public static final String SEARCH_AUTH_POLICY_NAME = "search";
GET,
PUT,
DELETE
- };
+ }
/**
* This method uses the contents of the supplied HTTP headers and request structures to populate the MDC Context
* @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) {
}
}
-
String fromIp = (httpReq != null) ? httpReq.getRemoteHost() : "";
String fromApp = (headers != null) ? headers.getFirst("X-FromAppId") : "";
}
public static boolean validateDocumentUri(String uri, boolean requireId) {
-
- // If the URI starts with a leading '/' character, remove it.
uri = uri.startsWith("/") ? uri.substring(1) : uri;
// Now, tokenize the URI string.
}
public static String extractIndexFromUri(String uri) {
-
- // If the URI starts with a leading '/' character, remove it.
uri = uri.startsWith("/") ? uri.substring(1) : uri;
- // Now, tokenize the URI string.
String[] tokens = uri.split("/");
int i = 0;
for (String token : tokens) {
- if (token.equals("indexes")) {
- if (i + 1 < tokens.length) {
- return tokens[i + 1];
- }
+ if (token.equals("indexes") && i + 1 < tokens.length) {
+ return tokens[i + 1];
}
i++;
}
}
public static String extractIdFromUri(String uri) {
-
- // If the URI starts with a leading '/' character, remove it.
uri = uri.startsWith("/") ? uri.substring(1) : uri;
- // Now, tokenize the URI string.
String[] tokens = uri.split("/");
int i = 0;
for (String token : tokens) {
- if (token.equals("documents")) {
- if (i + 1 < tokens.length) {
- return tokens[i + 1];
- }
+ if (token.equals("documents") && i + 1 < tokens.length) {
+ return tokens[i + 1];
}
i++;
}
}
public static String getHttpStatusString(int httpStatusCode) {
- // Some of the status codes we use are still in draft state in the standards, and are not
- // recognized in the javax library. We need to manually translate these to human-readable
- // strings.
- String statusString = "Unknown";
- HttpStatus status = null;
-
try {
- status = HttpStatus.valueOf(httpStatusCode);
+ return HttpStatus.valueOf(httpStatusCode).getReasonPhrase();
} catch (IllegalArgumentException e) {
- }
-
-
- if (status == null) {
- switch (httpStatusCode) {
- case 207:
- statusString = "Multi Status";
- break;
- default:
+ if (httpStatusCode == 207) {
+ return "Multi-Status";
+ } else {
+ return "Unknown";
}
- } else {
- statusString = status.getReasonPhrase();
}
-
- return statusString;
}
}
-/**
+/**
* ============LICENSE_START=======================================================
* org.onap.aai
* ================================================================================
* @return - A standard REST response structure.
*/
public ResponseEntity<String> processPost(String operations, HttpServletRequest request, HttpHeaders headers,
- DocumentStoreInterface documentStore, ApiUtils apiUtils) {
-
-
+ DocumentStoreInterface documentStore) {
// Initialize the MDC Context for logging purposes.
ApiUtils.initMdcContext(request, headers);
// Set a default result code and entity string for the request.
int resultCode = 500;
- String resultString = "Unexpected error";
+ String resultString;
if (logger.isDebugEnabled()) {
logger.debug("SEARCH: Process Bulk Request - operations = [" + operations.replaceAll("\n", "") + " ]");
}
try {
-
// Validate that the request is correctly authenticated before going
// any further.
if (!searchService.validateRequest(headers, request, ApiUtils.Action.POST,
ApiUtils.SEARCH_AUTH_POLICY_NAME)) {
logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE, "Authentication failure.");
- return buildResponse(HttpStatus.FORBIDDEN.value(), "Authentication failure.", request, apiUtils);
+ return buildResponse(HttpStatus.FORBIDDEN.value(), "Authentication failure.", request);
}
-
} catch (Exception e) {
-
// This is a catch all for any unexpected failure trying to perform
// the authentication.
logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE,
}
return buildResponse(HttpStatus.FORBIDDEN.value(), "Authentication failure - cause " + e.getMessage(),
- request, apiUtils);
+ request);
}
// We expect a payload containing a JSON structure enumerating the
// operations to be performed.
if (operations == null) {
logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE, "Missing operations list payload");
-
- return buildResponse(resultCode, "Missing payload", request, apiUtils);
+ return buildResponse(resultCode, "Missing payload", request);
}
-
// Marshal the supplied json string into a Java object.
ObjectMapper mapper = new ObjectMapper();
BulkRequest[] requests = null;
try {
requests = mapper.readValue(operations, BulkRequest[].class);
-
} catch (IOException e) {
-
logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE, "Failed to marshal operations list: " + e.getMessage());
if (logger.isDebugEnabled()) {
logger.debug("Stack Trace:\n" + e.getStackTrace());
}
-
// Populate the result code and entity string for our HTTP response
// and return the response to the client..
return buildResponse(HttpStatus.BAD_REQUEST.value(), "Unable to marshal operations: " + e.getMessage(),
- request, apiUtils);
+ request);
}
// Verify that our parsed operations list actually contains some valid
// Populate the result code and entity string for our HTTP response
// and return the response to the client..
- return buildResponse(HttpStatus.BAD_REQUEST.value(), "Empty operations list in bulk request", request,
- apiUtils);
+ return buildResponse(HttpStatus.BAD_REQUEST.value(), "Empty operations list in bulk request", request);
}
try {
}
// Build our HTTP response.
- ResponseEntity response =
+ ResponseEntity<String> response =
ResponseEntity.status(resultCode).contentType(MediaType.APPLICATION_JSON).body(resultString);
// Log the result.
if ((response.getStatusCodeValue() >= 200) && (response.getStatusCodeValue() < 300)) {
logger.info(SearchDbMsgs.PROCESSED_BULK_OPERATIONS);
} else {
- logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE, (String) response.getBody());
+ logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE, response.getBody());
}
// Finally, return the HTTP response to the client.
- return buildResponse(resultCode, resultString, request, apiUtils);
+ return buildResponse(resultCode, resultString, request);
}
* @param request - The HTTP request to extract data from for the audit log.
* @return - An HTTP response object.
*/
- private ResponseEntity<String> buildResponse(int resultCode, String resultString, HttpServletRequest request,
- ApiUtils apiUtils) {
-
+ private ResponseEntity<String> buildResponse(int resultCode, String resultString, HttpServletRequest request) {
ResponseEntity<String> response =
ResponseEntity.status(resultCode).contentType(MediaType.APPLICATION_JSON).body(resultString);
auditLogger.info(SearchDbMsgs.PROCESS_REST_REQUEST,
new LogFields().setField(LogLine.DefinedFields.RESPONSE_CODE, resultCode)
.setField(LogLine.DefinedFields.RESPONSE_DESCRIPTION, ApiUtils.getHttpStatusString(resultCode)),
- (request != null) ? request.getMethod().toString() : "Unknown",
+ (request != null) ? request.getMethod() : "Unknown",
(request != null) ? request.getRequestURL().toString() : "Unknown",
(request != null) ? request.getRemoteHost() : "Unknown",
Integer.toString(response.getStatusCodeValue()));
-/**
+/**
* ============LICENSE_START=======================================================
* org.onap.aai
* ================================================================================
if (httpResponse != null) {
httpResponse.setHeader(RESPONSE_HEADER_RESOURCE_VERSION, result.getResultVersion());
}
- ResponseEntity response =
+ ResponseEntity<String> response =
ResponseEntity.status(result.getResultCode()).contentType(MediaType.APPLICATION_JSON).body(output);
logResult(request, HttpStatus.valueOf(response.getStatusCodeValue()));
logResult(request, HttpStatus.valueOf(response.getStatusCodeValue()));
if (httpResponse != null) {
httpResponse.setHeader(RESPONSE_HEADER_RESOURCE_VERSION, result.getResultVersion());
}
- ResponseEntity response =
+ ResponseEntity<String> response =
ResponseEntity.status(result.getResultCode()).contentType(MediaType.APPLICATION_JSON).body(output);
logResult(request, HttpStatus.valueOf(response.getStatusCodeValue()));
if (httpResponse != null) {
httpResponse.setHeader(RESPONSE_HEADER_RESOURCE_VERSION, result.getResultVersion());
}
- ResponseEntity response;
+ ResponseEntity<String> response;
if (output == null) {
response = ResponseEntity.status(result.getResultCode()).build();
} else {
if (httpResponse != null) {
httpResponse.setHeader(RESPONSE_HEADER_RESOURCE_VERSION, result.getResultVersion());
}
- ResponseEntity response =
+ ResponseEntity<String> response =
ResponseEntity.status(result.getResultCode()).contentType(MediaType.APPLICATION_JSON).body(output);
logResult(request, HttpStatus.valueOf(response.getStatusCodeValue()));
? mapper.writerWithDefaultPrettyPrinter().writeValueAsString(result.getError())
: result.getFailureCause();
}
- ResponseEntity response =
+ ResponseEntity<String> response =
ResponseEntity.status(result.getResultCode()).contentType(MediaType.APPLICATION_JSON).body(output);
// Clear the MDC context so that no other transaction inadvertently
* @param headers - The HTTP headers.
* @return - A standard HTTP response.
*/
- private ResponseEntity processQuery(String index, String content, HttpServletRequest request, HttpHeaders headers,
- DocumentStoreInterface documentStore) {
+ private ResponseEntity<String> processQuery(String index, String content, HttpServletRequest request,
+ HttpHeaders headers, DocumentStoreInterface documentStore) {
try {
ObjectMapper mapper = new ObjectMapper();
? mapper.writerWithDefaultPrettyPrinter().writeValueAsString(result.getError())
: result.getFailureCause();
}
- ResponseEntity response =
+ ResponseEntity<String> response =
ResponseEntity.status(result.getResultCode()).contentType(MediaType.APPLICATION_JSON).body(output);
// Clear the MDC context so that no other transaction inadvertently
return output.toString();
}
- private ResponseEntity handleError(HttpServletRequest request, String message, HttpStatus status) {
+ private ResponseEntity<String> handleError(HttpServletRequest request, String message, HttpStatus status) {
logResult(request, status);
return ResponseEntity.status(status).contentType(MediaType.APPLICATION_JSON).body(message);
}
void logResult(HttpServletRequest request, HttpStatus status) {
- logger.info(SearchDbMsgs.PROCESS_REST_REQUEST, (request != null) ? request.getMethod().toString() : "",
+ logger.info(SearchDbMsgs.PROCESS_REST_REQUEST, (request != null) ? request.getMethod() : "",
(request != null) ? request.getRequestURL().toString() : "",
(request != null) ? request.getRemoteHost() : "", Integer.toString(status.value()));
auditLogger.info(SearchDbMsgs.PROCESS_REST_REQUEST,
new LogFields().setField(LogLine.DefinedFields.RESPONSE_CODE, status.value())
.setField(LogLine.DefinedFields.RESPONSE_DESCRIPTION, status.getReasonPhrase()),
- (request != null) ? request.getMethod().toString() : "",
+ (request != null) ? request.getMethod() : "",
(request != null) ? request.getRequestURL().toString() : "",
(request != null) ? request.getRemoteHost() : "", Integer.toString(status.value()));
- // Clear the MDC context so that no other transaction inadvertently
- // uses our transaction id.
+ // Clear the MDC context so that no other transaction inadvertently uses our transaction id.
ApiUtils.clearMdcContext();
}
}
-/**
+/**
* ============LICENSE_START=======================================================
* org.onap.aai
* ================================================================================
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
-
/**
* This class encapsulates the REST end points associated with manipulating indexes in the document store.
*/
public class IndexApi {
- private static final String HEADER_VALIDATION_SUCCESS = "SUCCESS";
- protected SearchServiceApi searchService = null;
+ private static final String HEADER_VALIDATION_SUCCESS = "SUCCESS";
+ protected SearchServiceApi searchService = null;
- /**
- * Configuration for the custom analyzers that will be used for indexing.
- */
- protected AnalysisConfiguration analysisConfig;
+ /**
+ * Configuration for the custom analyzers that will be used for indexing.
+ */
+ protected AnalysisConfiguration analysisConfig;
- // Set up the loggers.
+ // Set up the loggers.
private static Logger logger = LoggerFactory.getInstance().getLogger(IndexApi.class.getName());
private static Logger auditLogger = LoggerFactory.getInstance().getAuditLogger(IndexApi.class.getName());
- public IndexApi(SearchServiceApi searchService) {
- this.searchService = searchService;
- init();
- }
+ public IndexApi(SearchServiceApi searchService) {
+ this.searchService = searchService;
+ init();
+ }
- /**
- * Initializes the end point.
- *
- * @throws FileNotFoundException
- * @throws IOException
- * @throws DocumentStoreOperationException
- */
- public void init() {
+ /**
+ * Initializes the end point.
+ *
+ * @throws FileNotFoundException
+ * @throws IOException
+ * @throws DocumentStoreOperationException
+ */
+ public void init() {
- // Instantiate our analysis configuration object.
- analysisConfig = new AnalysisConfiguration();
- }
+ // Instantiate our analysis configuration object.
+ analysisConfig = new AnalysisConfiguration();
+ }
- /**
+ /**
* Processes client requests to create a new index and document type in the document store.
- *
+ *
* @param documentSchema - The contents of the request body which is expected to be a JSON structure which
* corresponds to the schema defined in document.schema.json
- * @param index - The name of the index to create.
- * @return - A Standard REST response
- */
+ * @param index - The name of the index to create.
+ * @return - A Standard REST response
+ */
public ResponseEntity<String> processCreateIndex(String documentSchema, HttpServletRequest request,
HttpHeaders headers, String index, DocumentStoreInterface documentStore) {
- int resultCode = 500;
- String resultString = "Unexpected error";
+ int resultCode = 500;
+
+ // Initialize the MDC Context for logging purposes.
+ ApiUtils.initMdcContext(request, headers);
- // Initialize the MDC Context for logging purposes.
- ApiUtils.initMdcContext(request, headers);
-
- // Validate that the request is correctly authenticated before going
- // any further.
- try {
+ // Validate that the request is correctly authenticated before going
+ // any further.
+ try {
if (!searchService.validateRequest(headers, request, ApiUtils.Action.POST,
ApiUtils.SEARCH_AUTH_POLICY_NAME)) {
- logger.warn(SearchDbMsgs.INDEX_CREATE_FAILURE, index, "Authentication failure.");
- return errorResponse(HttpStatus.FORBIDDEN, "Authentication failure.", request);
- }
+ logger.warn(SearchDbMsgs.INDEX_CREATE_FAILURE, index, "Authentication failure.");
+ return errorResponse(HttpStatus.FORBIDDEN, "Authentication failure.", request);
+ }
- } catch (Exception e) {
+ } catch (Exception e) {
- logger.warn(SearchDbMsgs.INDEX_CREATE_FAILURE, index,
- "Unexpected authentication failure - cause: " + e.getMessage());
- return errorResponse(HttpStatus.FORBIDDEN, "Authentication failure.", request);
- }
+ logger.warn(SearchDbMsgs.INDEX_CREATE_FAILURE, index,
+ "Unexpected authentication failure - cause: " + e.getMessage());
+ return errorResponse(HttpStatus.FORBIDDEN, "Authentication failure.", request);
+ }
- // We expect a payload containing the document schema. Make sure
- // it is present.
- if (documentSchema == null) {
- logger.warn(SearchDbMsgs.INDEX_CREATE_FAILURE, index, "Missing document schema payload");
- return errorResponse(HttpStatus.valueOf(resultCode), "Missing payload", request);
- }
+ // We expect a payload containing the document schema. Make sure
+ // it is present.
+ if (documentSchema == null) {
+ logger.warn(SearchDbMsgs.INDEX_CREATE_FAILURE, index, "Missing document schema payload");
+ return errorResponse(HttpStatus.valueOf(resultCode), "Missing payload", request);
+ }
- try {
+ String resultString;
- // Marshal the supplied json string into a document schema object.
- ObjectMapper mapper = new ObjectMapper();
- DocumentSchema schema = mapper.readValue(documentSchema, DocumentSchema.class);
+ try {
+ // Marshal the supplied json string into a document schema object.
+ ObjectMapper mapper = new ObjectMapper();
+ DocumentSchema schema = mapper.readValue(documentSchema, DocumentSchema.class);
- // Now, ask the DAO to create the index.
- OperationResult result = documentStore.createIndex(index, schema);
+ // Now, ask the DAO to create the index.
+ OperationResult result = documentStore.createIndex(index, schema);
- // Extract the result code and string from the OperationResult
- // object so that we can use them to generate a standard REST
- // response.
- // Note that we want to return a 201 result code on a successful
- // create, so if we get back a 200 from the document store,
- // translate that int a 201.
- resultCode = (result.getResultCode() == 200) ? 201 : result.getResultCode();
+ // Extract the result code and string from the OperationResult
+ // object so that we can use them to generate a standard REST
+ // response.
+ // Note that we want to return a 201 result code on a successful
+ // create, so if we get back a 200 from the document store,
+ // translate that int a 201.
+ resultCode = (result.getResultCode() == 200) ? 201 : result.getResultCode();
resultString = (result.getFailureCause() == null) ? result.getResult() : result.getFailureCause();
- } catch (com.fasterxml.jackson.core.JsonParseException
- | com.fasterxml.jackson.databind.JsonMappingException e) {
+ } catch (com.fasterxml.jackson.core.JsonParseException
+ | com.fasterxml.jackson.databind.JsonMappingException e) {
- // We were unable to marshal the supplied json string into a valid
- // document schema, so return an appropriate error response.
- resultCode = HttpStatus.BAD_REQUEST.value();
- resultString = "Malformed schema: " + e.getMessage();
+ // We were unable to marshal the supplied json string into a valid
+ // document schema, so return an appropriate error response.
+ resultCode = HttpStatus.BAD_REQUEST.value();
+ resultString = "Malformed schema: " + e.getMessage();
- } catch (IOException e) {
+ } catch (IOException e) {
- // We'll treat this is a general internal error.
- resultCode = HttpStatus.INTERNAL_SERVER_ERROR.value();
- resultString = "IO Failure: " + e.getMessage();
- }
+ // We'll treat this is a general internal error.
+ resultCode = HttpStatus.INTERNAL_SERVER_ERROR.value();
+ resultString = "IO Failure: " + e.getMessage();
+ }
ResponseEntity<String> response =
ResponseEntity.status(resultCode).contentType(MediaType.APPLICATION_JSON).body(resultString);
- // Log the result.
- if ((response.getStatusCodeValue() >= 200) && (response.getStatusCodeValue() < 300)) {
- logger.info(SearchDbMsgs.CREATED_INDEX, index);
- } else {
- logger.warn(SearchDbMsgs.INDEX_CREATE_FAILURE, index, resultString);
- }
+ // Log the result.
+ if ((response.getStatusCodeValue() >= 200) && (response.getStatusCodeValue() < 300)) {
+ logger.info(SearchDbMsgs.CREATED_INDEX, index);
+ } else {
+ logger.warn(SearchDbMsgs.INDEX_CREATE_FAILURE, index, resultString);
+ }
- // Generate our audit log.
- auditLogger.info(SearchDbMsgs.PROCESS_REST_REQUEST,
+ // Generate our audit log.
+ auditLogger.info(SearchDbMsgs.PROCESS_REST_REQUEST,
new LogFields().setField(LogLine.DefinedFields.RESPONSE_CODE, resultCode).setField(
LogLine.DefinedFields.RESPONSE_DESCRIPTION, HttpStatus.valueOf(resultCode).toString()),
- (request != null) ? request.getMethod().toString() : "Unknown",
- (request != null) ? request.getRequestURL().toString() : "Unknown",
- (request != null) ? request.getRemoteHost() : "Unknown",
- Integer.toString(response.getStatusCodeValue()));
+ (request != null) ? request.getMethod() : "Unknown",
+ (request != null) ? request.getRequestURL ().toString () : "Unknown",
+ (request != null) ? request.getRemoteHost () : "Unknown",
+ Integer.toString(response.getStatusCodeValue ()));
- // Clear the MDC context so that no other transaction inadvertently
- // uses our transaction id.
- ApiUtils.clearMdcContext();
+ // Clear the MDC context so that no other transaction inadvertently
+ // uses our transaction id.
+ ApiUtils.clearMdcContext();
- // Finally, return the response.
- return response;
- }
+ // Finally, return the response.
+ return response;
+ }
- /**
+ /**
* This function accepts any JSON and will "blindly" write it to the document store.
- *
+ *
* Note, eventually this "dynamic" flow should follow the same JSON-Schema validation procedure as the normal create
* index flow.
- *
- * @param dynamicSchema - The JSON string that will be sent to the document store.
- * @param index - The name of the index to be created.
- * @param documentStore - The document store specific interface.
- * @return The result of the document store interface's operation.
- */
- public ResponseEntity<String> processCreateDynamicIndex(String dynamicSchema, HttpServletRequest request,
- HttpHeaders headers, String index, DocumentStoreInterface documentStore) {
+ *
+ * @param dynamicSchema - The JSON string that will be sent to the document store.
+ * @param index - The name of the index to be created.
+ * @param documentStore - The document store specific interface.
+ * @return The result of the document store interface's operation.
+ */
+ public ResponseEntity<String> processCreateDynamicIndex(String dynamicSchema, HttpServletRequest request,
+ HttpHeaders headers, String index, DocumentStoreInterface documentStore) {
- ResponseEntity<String> response = null;
+ ResponseEntity<String> response = null;
ResponseEntity<String> validationResponse =
validateRequest(request, headers, index, SearchDbMsgs.INDEX_CREATE_FAILURE);
- if (validationResponse.getStatusCodeValue() != HttpStatus.OK.value()) {
- response = validationResponse;
- } else {
- OperationResult result = documentStore.createDynamicIndex(index, dynamicSchema);
-
- int resultCode = (result.getResultCode() == 200) ? 201 : result.getResultCode();
- String resultString = (result.getFailureCause() == null) ? result.getResult() : result.getFailureCause();
+ if (validationResponse.getStatusCodeValue () != HttpStatus.OK.value ()) {
+ response = validationResponse;
+ } else {
+ OperationResult result = documentStore.createDynamicIndex(index, dynamicSchema);
- response = ResponseEntity.status(resultCode).body(resultString);
- }
+ int resultCode = (result.getResultCode() == 200) ? 201 : result.getResultCode();
+ String resultString = (result.getFailureCause() == null) ? result.getResult() : result.getFailureCause();
- return response;
+ response = ResponseEntity.status(resultCode).body(resultString);
}
- /**
+ return response;
+ }
+
+ /**
* Processes a client request to remove an index from the document store. Note that this implicitly deletes all
* documents contained within that index.
- *
- * @param index - The index to be deleted.
- * @return - A standard REST response.
- */
+ *
+ * @param index - The index to be deleted.
+ * @return - A standard REST response.
+ */
public ResponseEntity<String> processDelete(String index, HttpServletRequest request, HttpHeaders headers,
- DocumentStoreInterface documentStore) {
-
- // Initialize the MDC Context for logging purposes.
- ApiUtils.initMdcContext(request, headers);
-
- // Set a default response in case something unexpected goes wrong.
- ResponseEntity<String> response = ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Unknown");
-
- // Validate that the request is correctly authenticated before going
- // any further.
- try {
-
- if (!searchService.validateRequest(headers, request, ApiUtils.Action.POST,
- ApiUtils.SEARCH_AUTH_POLICY_NAME)) {
- logger.warn(SearchDbMsgs.INDEX_CREATE_FAILURE, index, "Authentication failure.");
- return errorResponse(HttpStatus.FORBIDDEN, "Authentication failure.", request);
- }
-
- } catch (Exception e) {
-
- logger.warn(SearchDbMsgs.INDEX_CREATE_FAILURE, index,
- "Unexpected authentication failure - cause: " + e.getMessage());
- return errorResponse(HttpStatus.FORBIDDEN, "Authentication failure.", request);
- }
-
-
- try {
- // Send the request to the document store.
- response = responseFromOperationResult(documentStore.deleteIndex(index));
+ DocumentStoreInterface documentStore) {
+
+ // Initialize the MDC Context for logging purposes.
+ ApiUtils.initMdcContext(request, headers);
+
+ ResponseEntity<String> response;
+
+ // Validate that the request is correctly authenticated before going
+ // any further.
+ try {
+ if (!searchService.validateRequest(headers, request, ApiUtils.Action.POST,
+ ApiUtils.SEARCH_AUTH_POLICY_NAME)) {
+ logger.warn(SearchDbMsgs.INDEX_CREATE_FAILURE, index, "Authentication failure.");
+ return errorResponse(HttpStatus.FORBIDDEN, "Authentication failure.", request);
+ }
+
+ } catch (Exception e) {
+ logger.warn(SearchDbMsgs.INDEX_CREATE_FAILURE, index,
+ "Unexpected authentication failure - cause: " + e.getMessage());
+ return errorResponse(HttpStatus.FORBIDDEN, "Authentication failure.", request);
+ }
- } catch (DocumentStoreOperationException e) {
+ try {
+ // Send the request to the document store.
+ response = responseFromOperationResult(documentStore.deleteIndex(index));
+ } catch (DocumentStoreOperationException e) {
response = ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).contentType(MediaType.APPLICATION_JSON)
.body(e.getMessage());
- }
+ }
- // Log the result.
- if ((response.getStatusCodeValue() >= 200) && (response.getStatusCodeValue() < 300)) {
- logger.info(SearchDbMsgs.DELETED_INDEX, index);
- } else {
+ // Log the result.
+ if ((response.getStatusCodeValue() >= 200) && (response.getStatusCodeValue() < 300)) {
+ logger.info(SearchDbMsgs.DELETED_INDEX, index);
+ } else {
logger.warn(SearchDbMsgs.INDEX_DELETE_FAILURE, index, response.getBody());
- }
+ }
- // Generate our audit log.
- auditLogger.info(SearchDbMsgs.PROCESS_REST_REQUEST,
+ // Generate our audit log.
+ auditLogger.info(SearchDbMsgs.PROCESS_REST_REQUEST,
new LogFields().setField(LogLine.DefinedFields.RESPONSE_CODE, response.getStatusCodeValue()).setField(
LogLine.DefinedFields.RESPONSE_DESCRIPTION, response.getStatusCode().getReasonPhrase()),
- (request != null) ? request.getMethod().toString() : "Unknown",
- (request != null) ? request.getRequestURL().toString() : "Unknown",
- (request != null) ? request.getRemoteHost() : "Unknown",
- Integer.toString(response.getStatusCodeValue()));
+ (request != null) ? request.getMethod() : "Unknown",
+ (request != null) ? request.getRequestURL ().toString () : "Unknown",
+ (request != null) ? request.getRemoteHost () : "Unknown",
+ Integer.toString(response.getStatusCodeValue()));
- // Clear the MDC context so that no other transaction inadvertently
- // uses our transaction id.
- ApiUtils.clearMdcContext();
+ // Clear the MDC context so that no other transaction inadvertently
+ // uses our transaction id.
+ ApiUtils.clearMdcContext();
- return response;
- }
+ return response;
+ }
- /**
+ /**
* This method takes a JSON format document schema and produces a set of field mappings in the form that Elastic
* Search expects.
- *
- * @param documentSchema - A document schema expressed as a JSON string.
- * @return - A JSON string expressing an Elastic Search mapping configuration.
- * @throws com.fasterxml.jackson.core.JsonParseException
- * @throws com.fasterxml.jackson.databind.JsonMappingException
- * @throws IOException
- */
- public String generateDocumentMappings(String documentSchema) throws com.fasterxml.jackson.core.JsonParseException,
- com.fasterxml.jackson.databind.JsonMappingException, IOException {
-
- // Unmarshal the json content into a document schema object.
- ObjectMapper mapper = new ObjectMapper();
- DocumentSchema schema = mapper.readValue(documentSchema, DocumentSchema.class);
-
- // Now, generate the Elastic Search mapping json and return it.
- StringBuilder sb = new StringBuilder();
- sb.append("{");
- sb.append("\"properties\": {");
-
- boolean first = true;
- for (DocumentFieldSchema field : schema.getFields()) {
-
- if (!first) {
- sb.append(",");
- } else {
- first = false;
- }
-
- sb.append("\"").append(field.getName()).append("\": {");
-
- // The field type is mandatory.
- sb.append("\"type\": \"").append(field.getDataType()).append("\"");
-
- // If the index field was specified, then append it.
- if (field.getSearchable() != null) {
+ *
+ * @param documentSchema - A document schema expressed as a JSON string.
+ * @return - A JSON string expressing an Elastic Search mapping configuration.
+ * @throws com.fasterxml.jackson.core.JsonParseException
+ * @throws com.fasterxml.jackson.databind.JsonMappingException
+ * @throws IOException
+ */
+ public String generateDocumentMappings(String documentSchema) throws IOException {
+
+ // Unmarshal the json content into a document schema object.
+ ObjectMapper mapper = new ObjectMapper();
+ DocumentSchema schema = mapper.readValue(documentSchema, DocumentSchema.class);
+
+ // Now, generate the Elastic Search mapping json and return it.
+ StringBuilder sb = new StringBuilder();
+ sb.append("{");
+ sb.append("\"properties\": {");
+
+ boolean first = true;
+ for (DocumentFieldSchema field : schema.getFields()) {
+
+ if (!first) {
+ sb.append(",");
+ } else {
+ first = false;
+ }
+
+ sb.append("\"").append(field.getName()).append("\": {");
+
+ // The field type is mandatory.
+ sb.append("\"type\": \"").append(field.getDataType()).append("\"");
+
+ // If the index field was specified, then append it.
+ if (field.getSearchable() != null) {
sb.append(", \"index\": \"").append(field.getSearchable() ? "analyzed" : "not_analyzed").append("\"");
- }
+ }
- // If a search analyzer was specified, then append it.
- if (field.getSearchAnalyzer() != null) {
- sb.append(", \"search_analyzer\": \"").append(field.getSearchAnalyzer()).append("\"");
- }
+ // If a search analyzer was specified, then append it.
+ if (field.getSearchAnalyzer() != null) {
+ sb.append(", \"search_analyzer\": \"").append(field.getSearchAnalyzer()).append("\"");
+ }
- // If an indexing analyzer was specified, then append it.
- if (field.getIndexAnalyzer() != null) {
- sb.append(", \"analyzer\": \"").append(field.getIndexAnalyzer()).append("\"");
- } else {
- sb.append(", \"analyzer\": \"").append("whitespace").append("\"");
- }
+ // If an indexing analyzer was specified, then append it.
+ if (field.getIndexAnalyzer() != null) {
+ sb.append(", \"analyzer\": \"").append(field.getIndexAnalyzer()).append("\"");
+ } else {
+ sb.append(", \"analyzer\": \"").append("whitespace").append("\"");
+ }
- sb.append("}");
- }
+ sb.append("}");
+ }
- sb.append("}");
- sb.append("}");
+ sb.append("}");
+ sb.append("}");
- logger.debug("Generated document mappings: " + sb.toString());
+ logger.debug("Generated document mappings: " + sb.toString());
- return sb.toString();
- }
+ return sb.toString();
+ }
- /**
+ /**
* Converts an {@link OperationResult} to a standard REST {@link ResponseEntity} object.
- *
- * @param result - The {@link OperationResult} to be converted.
- * @return - The equivalent {@link ResponseEntity} object.
- */
- public ResponseEntity<String> responseFromOperationResult(OperationResult result) {
+ *
+ * @param result - The {@link OperationResult} to be converted.
+ * @return - The equivalent {@link ResponseEntity} object.
+ */
+ public ResponseEntity<String> responseFromOperationResult(OperationResult result) {
- if ((result.getResultCode() >= 200) && (result.getResultCode() < 300)) {
+ if ((result.getResultCode() >= 200) && (result.getResultCode() < 300)) {
return ResponseEntity.status(result.getResultCode()).contentType(MediaType.APPLICATION_JSON)
.body(result.getResult());
- } else {
- if (result.getFailureCause() != null) {
+ } else {
+ if (result.getFailureCause() != null) {
return ResponseEntity.status(result.getResultCode()).contentType(MediaType.APPLICATION_JSON)
.body(result.getFailureCause());
- } else {
+ } else {
return ResponseEntity.status(result.getResultCode()).contentType(MediaType.APPLICATION_JSON)
.body(result.getResult());
- }
- }
+ }
}
+ }
- public ResponseEntity<String> errorResponse(HttpStatus status, String msg, HttpServletRequest request) {
+ public ResponseEntity<String> errorResponse(HttpStatus status, String msg, HttpServletRequest request) {
- // Generate our audit log.
- auditLogger.info(SearchDbMsgs.PROCESS_REST_REQUEST,
+ // Generate our audit log.
+ auditLogger.info(SearchDbMsgs.PROCESS_REST_REQUEST,
new LogFields().setField(LogLine.DefinedFields.RESPONSE_CODE, status.value())
- .setField(LogLine.DefinedFields.RESPONSE_DESCRIPTION, status.getReasonPhrase()),
- (request != null) ? request.getMethod().toString() : "Unknown",
- (request != null) ? request.getRequestURL().toString() : "Unknown",
+ .setField(LogLine.DefinedFields.RESPONSE_DESCRIPTION, status.getReasonPhrase()),
+ (request != null) ? request.getMethod() : "Unknown",
+ (request != null) ? request.getRequestURL ().toString () : "Unknown",
(request != null) ? request.getRemoteHost() : "Unknown", Integer.toString(status.value()));
- // Clear the MDC context so that no other transaction inadvertently
- // uses our transaction id.
- ApiUtils.clearMdcContext();
+ // Clear the MDC context so that no other transaction inadvertently
+ // uses our transaction id.
+ ApiUtils.clearMdcContext();
- return ResponseEntity.status(status).contentType(MediaType.APPLICATION_JSON).body(msg);
- }
+ return ResponseEntity.status(status).contentType ( MediaType.APPLICATION_JSON ).body(msg);
+ }
- /**
- * A helper method used for validating/authenticating an incoming request.
- *
- * @param request - The http request that will be validated.
- * @param headers - The http headers that will be validated.
- * @param index - The name of the index that the document store request is being made against.
- * @param failureMsgEnum - The logging message to be used upon validation failure.
- * @return A success or failure response
- */
+ /**
+ * A helper method used for validating/authenticating an incoming request.
+ *
+ * @param request - The http request that will be validated.
+ * @param headers - The http headers that will be validated.
+ * @param index - The name of the index that the document store request is being made against.
+ * @param failureMsgEnum - The logging message to be used upon validation failure.
+ * @return A success or failure response
+ */
private ResponseEntity<String> validateRequest(HttpServletRequest request, HttpHeaders headers, String index,
SearchDbMsgs failureMsgEnum) {
- try {
+ try {
if (!searchService.validateRequest(headers, request, ApiUtils.Action.POST,
ApiUtils.SEARCH_AUTH_POLICY_NAME)) {
- logger.warn(failureMsgEnum, index, "Authentication failure.");
- return errorResponse(HttpStatus.FORBIDDEN, "Authentication failure.", request);
- }
- } catch (Exception e) {
- logger.warn(failureMsgEnum, index, "Unexpected authentication failure - cause: " + e.getMessage());
- return errorResponse(HttpStatus.FORBIDDEN, "Authentication failure.", request);
- }
- return ResponseEntity.status(HttpStatus.OK).body(HEADER_VALIDATION_SUCCESS);
+ logger.warn(failureMsgEnum, index, "Authentication failure.");
+ return errorResponse(HttpStatus.FORBIDDEN, "Authentication failure.", request);
+ }
+ } catch (Exception e) {
+ logger.warn(failureMsgEnum, index, "Unexpected authentication failure - cause: " + e.getMessage());
+ return errorResponse(HttpStatus.FORBIDDEN, "Authentication failure.", request);
}
+ return ResponseEntity.status(HttpStatus.OK).body(HEADER_VALIDATION_SUCCESS);
+ }
}
-/**
+/**
* ============LICENSE_START=======================================================
* org.onap.aai
* ================================================================================
* 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"})
// Forward the request to our document API to delete the document.
BulkApi bulkApi = new BulkApi(this);
- ResponseEntity<String> dbugResp = bulkApi.processPost(requestBody, request, headers, documentStore, apiUtils);
- return dbugResp;
+ return bulkApi.processPost(requestBody, request, headers, documentStore);
}
protected boolean validateRequest(HttpHeaders headers, HttpServletRequest req, Action action,
- String authPolicyFunctionName) throws Exception {
-
+ String authPolicyFunctionName) {
SearchDbServiceAuth serviceAuth = new SearchDbServiceAuth();
String cipherSuite = (String) req.getAttribute("javax.servlet.request.cipher_suite");
String status =
serviceAuth.authUser(headers, authUser.toLowerCase(), action.toString() + ":" + authPolicyFunctionName);
- if (!status.equals("OK")) {
- return false;
- }
-
- return true;
+ return status.equals("OK");
}
}
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-package org.onap.aai.sa.searchdbabstraction;
-
+package org.onap.aai.sa.searchdbabstraction;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
-
/**
* Exposes REST endpoints for a simple echo service.
*/
private String type;
private String reason;
-
public ErrorResult(String type, String reason) {
super();
this.type = type;
-/**
+/**
* ============LICENSE_START=======================================================
* org.onap.aai
* ================================================================================
*/
public abstract class AbstractAggregation {
- /**
- * The name of the field to apply the aggregation against.
- */
- protected String field;
+ /**
+ * The name of the field to apply the aggregation against.
+ */
+ protected String field;
- /**
+ /**
* Optionally allows the number of buckets for the aggregation to be specified.
- */
- protected Integer size;
+ */
+ protected Integer size;
- /**
+ /**
* Optionally sets the minimum number of matches that must occur before a particular bucket is included in the
* aggregation result.
- */
- @JsonProperty("min-threshold")
- protected Integer minThreshold;
+ */
+ @JsonProperty("min-threshold")
+ protected Integer minThreshold;
- public String getField() {
- return field;
- }
+ public String getField() {
+ return field;
+ }
- public void setField(String field) {
- this.field = field;
- }
+ public void setField(String field) {
+ this.field = field;
+ }
- public Integer getSize() {
- return size;
- }
+ public Integer getSize() {
+ return size;
+ }
- public void setSize(Integer size) {
- this.size = size;
- }
+ public void setSize(Integer size) {
+ this.size = size;
+ }
- public Integer getMinThreshold() {
- return minThreshold;
- }
+ public Integer getMinThreshold() {
+ return minThreshold;
+ }
- public void setMinThreshold(Integer minThreshold) {
- this.minThreshold = minThreshold;
- }
+ public void setMinThreshold(Integer minThreshold) {
+ this.minThreshold = minThreshold;
+ }
- public abstract String toElasticSearch();
+ public abstract String toElasticSearch();
- public abstract String toString();
}
* <p>
* The expected JSON structure for a ranges is as follows:
* <p>
- *
+ *
* <pre>
* {
* "from": <from-date>
* <p>
* or
* <p>
- *
+ *
* <pre>
* {
* "to": <to-date>
* <p>
* or
* <p>
- *
+ *
* <pre>
* {
* "from": <from-date>,
if (fromDate != null) {
sb.append("\"from\": \"");
- sb.append(fromDate.toString());
+ sb.append(fromDate);
sb.append("\"");
}
if (toDate != null) {
if (fromDate != null) {
sb.append(", \"to\": \"");
- sb.append(toDate.toString());
+ sb.append(toDate);
sb.append("\"");
} else {
sb.append("\"to\": \"");
- sb.append(toDate.toString());
+ sb.append(toDate);
sb.append("\"");
}
}
return sb.toString();
}
+ @Override
public String toString() {
return "{from: " + fromDate + ", to: " + toDate + "}";
}
-/**
+/**
* ============LICENSE_START=======================================================
* org.onap.aai
* ================================================================================
import org.onap.aai.sa.searchdbabstraction.util.SearchDbConstants;
import org.springframework.beans.factory.annotation.Autowired;
-
public class SearchService {
- private ElasticSearchHttpController esController = null;
-
- static Logger logger = LoggerFactory.getInstance().getLogger(SearchService.class.getName());
+ static Logger logger = LoggerFactory.getInstance().getLogger(SearchService.class.getName());
- @Autowired
- private ElasticSearchConfig esConfig;
+ @Autowired
+ private ElasticSearchConfig esConfig;
- public SearchService() {
- try {
- start();
- } catch (Exception e) {
- logger.error(SearchDbMsgs.STARTUP_EXCEPTION, e.getLocalizedMessage());
- }
+ public SearchService() {
+ try {
+ start();
+ } catch (Exception e) {
+ logger.error(SearchDbMsgs.STARTUP_EXCEPTION, e.getLocalizedMessage());
}
+ }
- protected void start() throws Exception {
- Properties configProperties = new Properties();
- configProperties.load(new FileInputStream(SearchDbConstants.ES_CONFIG_FILE));
- esController = new ElasticSearchHttpController(esConfig);
- logger.info(SearchDbMsgs.SERVICE_STARTED);
- }
+ protected void start() throws Exception {
+ Properties configProperties = new Properties();
+ configProperties.load(new FileInputStream(SearchDbConstants.ES_CONFIG_FILE));
+ new ElasticSearchHttpController(esConfig);
+ logger.info(SearchDbMsgs.SERVICE_STARTED);
+ }
}
-/**
+/**
* ============LICENSE_START=======================================================
* org.onap.aai
* ================================================================================
import org.onap.aai.sa.searchdbabstraction.entity.AggregationResult;
public class AggregationParsingUtil {
+
+ private AggregationParsingUtil() { // Do not instantiate
+ }
+
public static AggregationResult[] parseAggregationResults(JSONObject aggregations) throws JsonProcessingException {
// Obtain the set of aggregation names
- Set keySet = aggregations.keySet();
+ Set<?> keySet = aggregations.keySet();
AggregationResult[] aggResults = new AggregationResult[keySet.size()];
int index = 0;
- for (Iterator it = keySet.iterator(); it.hasNext();) {
+ for (Iterator<?> it = keySet.iterator(); it.hasNext();) {
String key = (String) it.next();
AggregationResult aggResult = new AggregationResult();
aggResult.setName(key);
-/**
+/**
* ============LICENSE_START=======================================================
* org.onap.aai
* ================================================================================
*/
package org.onap.aai.sa.searchdbabstraction.util;
-import com.fasterxml.jackson.core.JsonParseException;
-import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.File;
import java.io.FileInputStream;
public class DocumentSchemaUtil {
+ private DocumentSchemaUtil() { // Do not instantiate
+ }
+
private static String dynamicCustomMapping = null;
private static final String DYNAMIC_CUSTOM_TEMPALTE_FILE =
System.getProperty("CONFIG_HOME") + File.separator + "dynamic-custom-template.json";
- public static String generateDocumentMappings(String documentSchema)
- throws JsonParseException, JsonMappingException, IOException {
+ public static String generateDocumentMappings(String documentSchema) throws IOException {
// Unmarshal the json content into a document schema object.
ObjectMapper mapper = new ObjectMapper();
sb.append("\"type\": \"").append(fieldSchema.getDataType()).append("\"");
// For date type fields we may optionally supply a format specifier.
- if (fieldSchema.getDataType().equals("date")) {
- if (fieldSchema.getFormat() != null) {
- sb.append(", \"format\": \"").append(fieldSchema.getFormat()).append("\"");
- }
+ if (fieldSchema.getDataType().equals("date") && fieldSchema.getFormat() != null) {
+ sb.append(", \"format\": \"").append(fieldSchema.getFormat()).append("\"");
}
// If the index field was specified, then append it.
/**
* This class as the name suggests is to translate the payload of PUT & POST requests to ElasticSearch (ES) to its
* compatible syntax, specially compatible with ES v6 or above.
- *
+ *
* For example, data type such as "string" is now replaced by "text" or "keyword".
- *
+ *
* So this class will make those translations reading off from a json configuration file, therefore the configuration
* can be updated with new translations as and when required without touching the code.
- *
+ *
* @author EDWINL
*
*/
private static final String CONFIG_DIRECTORY = System.getProperty("CONFIG_HOME");
private static final String ES_PAYLOAD_TRANSLATION_FILE = "es-payload-translation.json";
+ private ElasticSearchPayloadTranslator() { // Do not instantiate
+ }
/**
* Using JSON Path query to filter objects to translate the payload to ES compatible version The filter queries and
* the replacement attributes are configured in the es-payload-translation.json file.
- *
+ *
* @param source
* @return translated payload in String
* @throws IOException
*/
public static String translateESPayload(String source) throws IOException {
- logger.info(SearchDbMsgs.PROCESS_PAYLOAD_QUERY, "translateESPayload, method-params[ source=" + source + "]");
+ logger.info(SearchDbMsgs.PROCESS_PAYLOAD_QUERY, "translateESPayload, method-params[ source=" + source + "]",
+ "(unknown)");
String pathToTranslationFile = CONFIG_DIRECTORY + File.separator + ES_PAYLOAD_TRANSLATION_FILE;
try {
-
JSONObject translationConfigPayload =
new JSONObject(IOUtils.toString(new FileInputStream(new File(pathToTranslationFile)), "UTF-8"));
JSONArray attrTranslations = translationConfigPayload.getJSONArray("attr-translations");
logger.info(SearchDbMsgs.PROCESS_PAYLOAD_QUERY,
"Payload after translation: " + payloadToTranslate.jsonString());
return payloadToTranslate.jsonString();
-
- } catch (JSONException | IOException e) {
- logger.error(SearchDbMsgs.FILTERS_CONFIG_FAILURE, e, ES_PAYLOAD_TRANSLATION_FILE, e.getMessage());
- if (e instanceof JSONException) {
- throw new IOException("Payload translation configuration looks corrupted. Please correct!", e);
- }
- throw new IOException("Error in configuring payload translation file. Please check if it exists.", e);
+ } catch (JSONException ex) {
+ logger.error(SearchDbMsgs.FILTERS_CONFIG_FAILURE, ex, ES_PAYLOAD_TRANSLATION_FILE, ex.getMessage());
+ throw new IOException("Payload translation configuration looks corrupted. Please correct!", ex);
+ } catch (IOException ex) {
+ logger.error(SearchDbMsgs.FILTERS_CONFIG_FAILURE, ex, ES_PAYLOAD_TRANSLATION_FILE, ex.getMessage());
+ throw new IOException("Error in configuring payload translation file. Please check if it exists.", ex);
}
}
}
-/**
+/**
* ============LICENSE_START=======================================================
* org.onap.aai
* ================================================================================
package org.onap.aai.sa.searchdbabstraction.util;
public class SearchDbConstants {
+
+ private SearchDbConstants() { // Do not instantiate
+ }
+
public static final String SDB_FILESEP =
(System.getProperty("file.separator") == null) ? "/" : System.getProperty("file.separator");
public static final String SDB_BUNDLECONFIG_NAME =
(System.getProperty("BUNDLECONFIG_DIR") == null) ? "bundleconfig" : System.getProperty("BUNDLECONFIG_DIR");
- //
+
public static final String SDB_HOME_BUNDLECONFIG = (System.getProperty("AJSC_HOME") == null)
? SDB_FILESEP + "opt" + SDB_FILESEP + "app" + SDB_FILESEP + "searchdb" + SDB_FILESEP + SDB_BUNDLECONFIG_NAME
: System.getProperty("AJSC_HOME") + SDB_FILESEP + SDB_BUNDLECONFIG_NAME;
- //
+
public static final String SDB_HOME_ETC = SDB_HOME_BUNDLECONFIG + SDB_FILESEP + "etc" + SDB_FILESEP;
public static final String SDB_CONFIG_APP_LOCATION = SDB_HOME_ETC + "appprops" + SDB_FILESEP;
public static final String SDB_FILTER_CONFIG_FILE = SDB_SPECIFIC_CONFIG + "filter-config.json";
public static final String SDB_ANALYSIS_CONFIG_FILE = SDB_SPECIFIC_CONFIG + "analysis-config.json";
- // public static final String SDB_HOME_SEARCHCONFIG = (System.getProperty("app.config") == null)
- // ? System.getProperty("user.dir") + SDB_FILESEP + "config" + SDB_FILESEP + "searchdb"
- // + SDB_FILESEP + "elastic-search.properties"
- // : System.getProperty("app.config") + SDB_FILESEP + "searchdb" + SDB_FILESEP + "elastic-search.properties";
-
// Logging related
public static final String SDB_SERVICE_NAME = "SearchDataService";
}
-/**
+/**
* ============LICENSE_START=======================================================
* org.onap.aai
* ================================================================================
*/
package org.onap.aai.sa.rest;
-import static org.junit.Assert.assertEquals;
+import static org.hamcrest.CoreMatchers.equalTo;
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertThat;
import org.junit.Test;
-
public class ApiUtilsTest {
@Test
public void testHTTPStatusConversion() {
- String statusString;
- statusString = ApiUtils.getHttpStatusString(201);
- assertEquals(0, statusString.compareToIgnoreCase("Created"));
-
- statusString = ApiUtils.getHttpStatusString(207);
- assertEquals(0, statusString.compareToIgnoreCase("Multi-Status"));
-
- statusString = ApiUtils.getHttpStatusString(9999);
- assertEquals(0, statusString.compareToIgnoreCase("Unknown"));
+ assertThat(ApiUtils.getHttpStatusString(201), is(equalTo("Created")));
+ assertThat(ApiUtils.getHttpStatusString(207), is(equalTo("Multi-Status")));
+ assertThat(ApiUtils.getHttpStatusString(9999), is(equalTo("Unknown")));
}
}
-/**
+/**
* ============LICENSE_START=======================================================
* org.onap.aai
* ================================================================================
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
-import org.springframework.test.web.servlet.ResultActions;
/**
this.mockMvc.perform(post(TOP_URI).contentType(MediaType.APPLICATION_JSON).content(validPayloadStr))
.andExpect(status().isOk());
-
// Post a request to the bulk operations endpoint with an invalid
// operations list payload.
File inValidBulkOpsFile = new File("src/test/resources/json/bulk-ops-invalid.json");
String inValidPayloadStr = TestUtils.readFileToString(inValidBulkOpsFile);
- ResultActions invalid =
- this.mockMvc.perform(post(TOP_URI).contentType(MediaType.APPLICATION_JSON).content(inValidPayloadStr))
- .andExpect(status().isBadRequest());
+ this.mockMvc.perform(post(TOP_URI).contentType(MediaType.APPLICATION_JSON).content(inValidPayloadStr))
+ .andExpect(status().isBadRequest());
}
}
-/**
+/**
* ============LICENSE_START=======================================================
* org.onap.aai
* ================================================================================
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import java.io.IOException;
-//import org.glassfish.jersey.server.ResourceConfig;
-//import org.glassfish.jersey.test.JerseyTest;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
}
- //
- // /**
- // * This test validates the behaviour of the 'Search Documents' GET request
- // * endpoint.
- // *
- // * @throws IOException
- // * @throws ParseException
- // */
+
+ /**
+ * This test validates the behaviour of the 'Search Documents' GET request endpoint.
+ *
+ * @throws Exception
+ */
@Ignore
- @Test
public void searchDocumentTest1() throws Exception {
- // String result = target(INDEXES_URI + INDEX_NAME + "/" + SEARCH_URI +
- // SIMPLE_QUERY).request().get(String.class);
-
MvcResult result = this.mockMvc
.perform(get(INDEXES_URI + INDEX_NAME + "/" + SEARCH_URI + SIMPLE_QUERY)
.contentType(MediaType.APPLICATION_JSON).header("If-Match", "1").content(CREATE_JSON_CONTENT))
.andReturn();
- // Our stub document store DAO returns the parameters that it was
- // passed as the result string, so now we can validate that our
- // endpoint invoked it with the correct parameters.
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(result.getResponse().getContentAsString());
assertTrue("Unexpected Result ", json.get("totalHits").toString().equals("1"));
-
-
}
- //
/**
* This test validates the behaviour of the 'Search Documents' GET request endpoint.
*
*/
@Test
public void searchDocumentTest2() throws Exception {
- // String result = target(INDEXES_URI + INDEX_NAME + "/" +
- // SEARCH_URI).request().post(Entity.json(COMPLEX_QUERY), String.class);
-
MvcResult result = this.mockMvc.perform(get(INDEXES_URI + INDEX_NAME + "/" + SEARCH_URI)
.contentType(MediaType.APPLICATION_JSON).content(COMPLEX_QUERY)).andReturn();
- // Our stub document store DAO returns the parameters that it was
- // passed as the result string, so now we can validate that our
- // endpoint invoked it with the correct parameters.
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(result.getResponse().getContentAsString());
JSONObject resultJson = (JSONObject) json.get("searchResult");
assertTrue("Unexpected Result ", resultJson.get("totalHits").toString().equals("1"));
-
}
}
import java.io.IOException;
import org.junit.Test;
-
public class DocumentSchemaTest {
private final String SIMPLE_DOC_SCHEMA_JSON = "src/test/resources/json/simpleDocument.json";
Assert.assertTrue(HttpStatus.BAD_REQUEST.value() == response.getStatusCodeValue());\r
}\r
\r
+ @SuppressWarnings("unchecked")\r
@Test\r
public void testProcessPost_NotNullContent() throws Exception {\r
String transactionId = "transactionId-1";\r
Mockito.when(searchServiceApi.validateRequest(Mockito.any(HttpHeaders.class),\r
Mockito.any(HttpServletRequest.class), Mockito.any(ApiUtils.Action.class), Mockito.anyString()))\r
.thenThrow(IllegalArgumentException.class);\r
- ResponseEntity response =\r
+ ResponseEntity<?> response =\r
documentApi.processPost(content, request, headers, httpResponse, "index", documentStore);\r
Assert.assertNotNull(response);\r
Assert.assertTrue(HttpStatus.FORBIDDEN.value() == response.getStatusCodeValue());\r
\r
}\r
\r
- //\r
+ @SuppressWarnings("unchecked")\r
@Test\r
public void testProcessSearchWithGet_ValidateThrowsException() throws Exception {\r
String transactionId = "transactionId-1";\r
\r
}\r
\r
- //\r
@Test\r
public void testProcessSearchWithGet_ValidateIsFalse() throws Exception {\r
String transactionId = "transactionId-1";\r
Assert.assertTrue(HttpStatus.BAD_REQUEST.value() == response.getStatusCodeValue());\r
}\r
\r
+ @SuppressWarnings("unchecked")\r
@Test\r
public void testProcessPut_RequestThrowsException() throws Exception {\r
String transactionId = "transactionId-1";\r
Assert.assertTrue(HttpStatus.FORBIDDEN.value() == response.getStatusCodeValue());\r
}\r
\r
- @Ignore\r
@Test\r
public void testProcessPut_ResultInvalid() throws Exception {\r
String transactionId = "transactionId-1";\r
Mockito.when(searchServiceApi.validateRequest(Mockito.any(HttpHeaders.class),\r
Mockito.any(HttpServletRequest.class), Mockito.any(ApiUtils.Action.class), Mockito.anyString()))\r
.thenReturn(true);\r
- Mockito.when(documentStore.updateDocument(Mockito.anyString(), Mockito.any(DocumentStoreDataEntity.class),\r
+ Mockito.when(documentStore.createDocument(Mockito.anyString(), Mockito.any(DocumentStoreDataEntity.class),\r
Mockito.anyBoolean())).thenReturn(result);\r
ResponseEntity<String> response =\r
documentApi.processPut(content, request, headers, httpResponse, "index", "id-1", documentStore);\r
Assert.assertTrue(HttpStatus.FOUND.value() == response.getStatusCodeValue());\r
}\r
\r
+ @SuppressWarnings("unchecked")\r
@Test\r
public void testProcessDelete_RequestThrowsException() throws Exception {\r
String transactionId = "transactionId-1";\r
Assert.assertTrue(HttpStatus.FOUND.value() == response.getStatusCodeValue());\r
}\r
\r
+ @SuppressWarnings("unchecked")\r
@Test\r
public void testProcessGet_RequestThrowsException() throws Exception {\r
String transactionId = "transactionId-1";\r
Assert.assertTrue(HttpStatus.BAD_REQUEST.value() == response.getStatusCodeValue());\r
}\r
\r
+ @SuppressWarnings("unchecked")\r
@Test\r
public void testQueryWithGetWithPayload_RequestThrowsException() throws Exception {\r
String transactionId = "transactionId-1";\r
Assert.assertTrue(HttpStatus.FORBIDDEN.value() == response.getStatusCodeValue());\r
}\r
\r
+ @SuppressWarnings("unchecked")\r
@Test\r
public void testCreateProcessIndex_IndexApi_RequestThrowsException() throws Exception {\r
String transactionId = "transactionId-1";\r
Assert.assertTrue(HttpStatus.FORBIDDEN.value() == response.getStatusCodeValue());\r
}\r
\r
+ @SuppressWarnings("unchecked")\r
@Test\r
public void testProcessDelete_IndexApi_RequestThrowsException() throws Exception {\r
String transactionId = "transactionId-1";\r
Assert.assertTrue(HttpStatus.FORBIDDEN.value() == response.getStatusCodeValue());\r
}\r
\r
+ @SuppressWarnings("unchecked")\r
@Test\r
public void testProcessDelete_IndexApi_DeleteIndexException() throws Exception {\r
String transactionId = "transactionId-1";\r
successResult.setResult(SUCCESS_RESULT_STRING);
// Convert our success OperationResult to a standard REST Response...
- ResponseEntity successResponse = indexApi.responseFromOperationResult(successResult);
+ ResponseEntity<?> successResponse = indexApi.responseFromOperationResult(successResult);
// ...and validate that the Response is correctly populated.
assertEquals("Unexpected result code", SUCCESS_RESULT_CODE, successResponse.getStatusCodeValue());
failureResult.setFailureCause(FAILURE_CAUSE_STRING);
// Convert our failure OperationResult to a standard REST Response...
- ResponseEntity failureResponse = indexApi.responseFromOperationResult(failureResult);
+ ResponseEntity<?> failureResponse = indexApi.responseFromOperationResult(failureResult);
// ...and validate that the Response is correctly populated.
assertEquals("Unexpected result code", FAILURE_RESULT_CODE, failureResponse.getStatusCodeValue());
@Override
protected boolean validateRequest(HttpHeaders headers, HttpServletRequest req, ApiUtils.Action action,
- String authPolicyFunctionName) throws Exception {
-
+ String authPolicyFunctionName) {
return authenticationShouldSucceed;
}
}
opResult.setResultCode(404);
} else {
opResult.setResultCode(200);
- String id = "dummy";
- if (document.getId() != null) {
- id = document.getId();
- }
opResult.setResultVersion("1");
}
SearchHit searchHit = new SearchHit();
Document doc = new Document();
doc.setEtag("etag1");
- Map<String, Object> content = new HashMap<String, Object>();
+ Map<String, Object> content = new HashMap<>();
content.put("key1", "value1");
doc.setContent(new JSONObject());
searchHit.setDocument(doc);
-/**
+/**
* ============LICENSE_START=======================================================
* org.onap.aai
* ================================================================================
public class QueryTest {
- /**
+ /**
* This test validates that we are able to marshal json structures representing term queries into POJOs and that we
* can then unmarshal those POJOs into ElasticSearch syntax.
- *
- * @throws JsonParseException
- * @throws JsonMappingException
- * @throws IOException
- */
- @Test
- public void termQueryTest() throws JsonParseException, JsonMappingException, IOException {
+ *
+ * @throws JsonParseException
+ * @throws JsonMappingException
+ * @throws IOException
+ */
+ @Test
+ public void termQueryTest() throws JsonParseException, JsonMappingException, IOException {
- Integer intValue = 1;
- String field = "searchTags";
- String termQueryWithIntegerValueJson = "{\"field\": \"" + field + "\", \"value\": " + intValue + "}";
- String termQueryWithIntegerValueExpectedES = "{\"term\": {\"" + field + "\" : " + intValue + "}}";
+ Integer intValue = 1;
+ String field = "searchTags";
+ String termQueryWithIntegerValueJson = "{\"field\": \"" + field + "\", \"value\": " + intValue + "}";
+ String termQueryWithIntegerValueExpectedES = "{\"term\": {\"" + field + "\" : " + intValue + "}}";
- Double doubleValue = 5.7;
- String termQueryWithDoubleValueJson = "{\"field\": \"" + field + "\", \"value\": " + doubleValue + "}";
- String termQueryWithDoubleValueExpectedES = "{\"term\": {\"" + field + "\" : " + doubleValue + "}}";
+ Double doubleValue = 5.7;
+ String termQueryWithDoubleValueJson = "{\"field\": \"" + field + "\", \"value\": " + doubleValue + "}";
+ String termQueryWithDoubleValueExpectedES = "{\"term\": {\"" + field + "\" : " + doubleValue + "}}";
- String stringValue = "theValue";
- String termQueryWithStringValueJson = "{\"field\": \"" + field + "\", \"value\": \"" + stringValue + "\"}";
- String termQueryWithStringValueExpectedES = "{\"term\": {\"" + field + "\" : \"" + stringValue + "\"}}";
+ String stringValue = "theValue";
+ String termQueryWithStringValueJson = "{\"field\": \"" + field + "\", \"value\": \"" + stringValue + "\"}";
+ String termQueryWithStringValueExpectedES = "{\"term\": {\"" + field + "\" : \"" + stringValue + "\"}}";
- ObjectMapper mapper = new ObjectMapper();
+ ObjectMapper mapper = new ObjectMapper();
- // Validate that we can marshal a term query where the supplied value
- // is an Integer.
- TermQuery integerTermQuery = mapper.readValue(termQueryWithIntegerValueJson, TermQuery.class);
+ // Validate that we can marshal a term query where the supplied value
+ // is an Integer.
+ TermQuery integerTermQuery = mapper.readValue(termQueryWithIntegerValueJson, TermQuery.class);
assertTrue(
"Expected value to be of type Integer, but was type "
+ integerTermQuery.getValue().getClass().getName(),
- integerTermQuery.getValue() instanceof Integer);
- assertEquals(intValue, integerTermQuery.getValue());
+ integerTermQuery.getValue() instanceof Integer);
+ assertEquals(intValue, integerTermQuery.getValue());
- assertTrue("ElasticSearch term query translation does not match the expected result",
- termQueryWithIntegerValueExpectedES.equals(integerTermQuery.toElasticSearch()));
+ assertTrue("ElasticSearch term query translation does not match the expected result",
+ termQueryWithIntegerValueExpectedES.equals(integerTermQuery.toElasticSearch()));
- // Validate that we can marshal a term query where the supplied value
- // is a Double.
- TermQuery doubleTermQuery = mapper.readValue(termQueryWithDoubleValueJson, TermQuery.class);
+ // Validate that we can marshal a term query where the supplied value
+ // is a Double.
+ TermQuery doubleTermQuery = mapper.readValue(termQueryWithDoubleValueJson, TermQuery.class);
assertTrue(
"Expected value to be of type Double, but was type " + doubleTermQuery.getValue().getClass().getName(),
- doubleTermQuery.getValue() instanceof Double);
- assertEquals(doubleValue, doubleTermQuery.getValue());
- assertTrue("ElasticSearch term query translation does not match the expected result",
- termQueryWithDoubleValueExpectedES.equals(doubleTermQuery.toElasticSearch()));
-
- // Validate that we can marshal a term query where the supplied value
- // is a String literal.
- TermQuery stringTermQuery = mapper.readValue(termQueryWithStringValueJson, TermQuery.class);
+ doubleTermQuery.getValue() instanceof Double);
+ assertEquals(doubleValue, doubleTermQuery.getValue());
+ assertTrue("ElasticSearch term query translation does not match the expected result",
+ termQueryWithDoubleValueExpectedES.equals(doubleTermQuery.toElasticSearch()));
+
+ // Validate that we can marshal a term query where the supplied value
+ // is a String literal.
+ TermQuery stringTermQuery = mapper.readValue(termQueryWithStringValueJson, TermQuery.class);
assertTrue(
"Expected value to be of type String, but was type " + stringTermQuery.getValue().getClass().getName(),
- stringTermQuery.getValue() instanceof String);
- assertEquals(stringValue, stringTermQuery.getValue());
- assertTrue("ElasticSearch term query translation does not match the expected result",
- termQueryWithStringValueExpectedES.equals(stringTermQuery.toElasticSearch()));
+ stringTermQuery.getValue() instanceof String);
+ assertEquals(stringValue, stringTermQuery.getValue());
+ assertTrue("ElasticSearch term query translation does not match the expected result",
+ termQueryWithStringValueExpectedES.equals(stringTermQuery.toElasticSearch()));
- }
+ }
- /**
+ /**
* This test validates that we are able to marshal json structures representing parsed queries into POJOs and that
* we can then unmarshal those POJOs into ElasticSearch syntax.
- *
- * @throws JsonParseException
- * @throws JsonMappingException
- * @throws IOException
- */
- @Test
- public void parsedQueryTest() throws JsonParseException, JsonMappingException, IOException {
-
- String field = "fieldname";
- String queryString = "The query string";
-
- String queryJson = "{\"field\": \"" + field + "\", \"query-string\": \"" + queryString + "\"}";
+ *
+ * @throws JsonParseException
+ * @throws JsonMappingException
+ * @throws IOException
+ */
+ @Test
+ public void parsedQueryTest() throws JsonParseException, JsonMappingException, IOException {
+
+ String field = "fieldname";
+ String queryString = "The query string";
+
+ String queryJson = "{\"field\": \"" + field + "\", \"query-string\": \"" + queryString + "\"}";
String queryExpectedES =
"{\"query_string\": {\"default_field\": \"" + field + "\", \"query\": \"" + queryString + "\"}}";
- ObjectMapper mapper = new ObjectMapper();
- ParsedQuery pq = mapper.readValue(queryJson, ParsedQuery.class);
+ ObjectMapper mapper = new ObjectMapper();
+ ParsedQuery pq = mapper.readValue(queryJson, ParsedQuery.class);
- assertTrue("Unexpected marshalled value for 'field' - expected: " + field + " actual: " + pq.getField(),
- field.equals(pq.getField()));
+ assertTrue("Unexpected marshalled value for 'field' - expected: " + field + " actual: " + pq.getField(),
+ field.equals(pq.getField()));
assertTrue("Unexpected marshalled value for 'query-string' - expected: " + queryString + " actual: "
+ pq.getQueryString(), queryString.equals(pq.getQueryString()));
assertTrue(
"Unexpected ElasticSearch syntax. Expected: " + queryExpectedES + " Actual: " + pq.toElasticSearch(),
- queryExpectedES.equals(pq.toElasticSearch()));
- }
+ queryExpectedES.equals(pq.toElasticSearch()));
+ }
- /**
+ /**
* This test validates that a ranged query cannot be parsed with values for both the 'gte' and 'gt' fields or the
* 'lte' and 'lt' fields, and that we do not allow mixing of numeric and date types in the same query.
- *
- * @throws JsonParseException
- * @throws IOException
- */
- @Test
- public void rangeQueryConflictingBoundsTest() throws JsonParseException, IOException {
+ *
+ * @throws JsonParseException
+ * @throws IOException
+ */
+ @Test
+ public void rangeQueryConflictingBoundsTest() throws JsonParseException, IOException {
String invalidGTAndGTE =
"{ \"field\": \"timestamp\", \"gte\": \"2016-10-06T00:00:00.558+03:00\", \"gt\": \"2016-10-06T23:59:59.558+03:00\"}";
String invalidLTAndLTE =
"{ \"field\": \"timestamp\", \"lte\": \"2016-10-06T00:00:00.558+03:00\", \"lt\": \"2016-10-06T23:59:59.558+03:00\"}";
- String invalidTypes = "{ \"field\": \"timestamp\", \"lte\": 5, \"gte\": \"2016-10-06T23:59:59.558+03:00\"}";
-
- ObjectMapper mapper = new ObjectMapper();
-
- // Attempt to parse a query where we are setting values for both the
- // 'greater than' and 'greater than and equal to' operators.
- boolean gotExpectedException = false;
- try {
- RangeQuery badRangeQuery = mapper.readValue(invalidGTAndGTE, RangeQuery.class);
- } catch (JsonMappingException e) {
- gotExpectedException = true;
- }
- assertTrue("Attempting to set both a 'gt' and 'gte' value on the same query should not have been allowed",
- gotExpectedException);
-
- // Attempt to parse a query where we are setting values for both the
- // 'less than' and 'less than and equal to' operators.
- gotExpectedException = false;
- try {
- RangeQuery badRangeQuery = mapper.readValue(invalidLTAndLTE, RangeQuery.class);
- } catch (JsonMappingException e) {
- gotExpectedException = true;
- }
- assertTrue("Attempting to set both a 'lt' and 'lte' value on the same query should not have been allowed",
- gotExpectedException);
-
- // Attempt to parse a query where we are mixing numeric and date values
- // in the same query.
- gotExpectedException = false;
- try {
- RangeQuery badRangeQuery = mapper.readValue(invalidTypes, RangeQuery.class);
- } catch (JsonMappingException e) {
- gotExpectedException = true;
- }
- assertTrue("Attempting to mix numeric and date values in the same query should not have been allowed",
- gotExpectedException);
+ String invalidTypes = "{ \"field\": \"timestamp\", \"lte\": 5, \"gte\": \"2016-10-06T23:59:59.558+03:00\"}";
+ ObjectMapper mapper = new ObjectMapper();
+ // Attempt to parse a query where we are setting values for both the
+ // 'greater than' and 'greater than and equal to' operators.
+ boolean gotExpectedException = false;
+ try {
+ mapper.readValue(invalidGTAndGTE, RangeQuery.class);
+ } catch (JsonMappingException e) {
+ gotExpectedException = true;
+ }
+ assertTrue("Attempting to set both a 'gt' and 'gte' value on the same query should not have been allowed",
+ gotExpectedException);
+
+ // Attempt to parse a query where we are setting values for both the
+ // 'less than' and 'less than and equal to' operators.
+ gotExpectedException = false;
+ try {
+ mapper.readValue(invalidLTAndLTE, RangeQuery.class);
+ } catch (JsonMappingException e) {
+ gotExpectedException = true;
+ }
+ assertTrue("Attempting to set both a 'lt' and 'lte' value on the same query should not have been allowed",
+ gotExpectedException);
+
+ // Attempt to parse a query where we are mixing numeric and date values
+ // in the same query.
+ gotExpectedException = false;
+ try {
+ mapper.readValue(invalidTypes, RangeQuery.class);
+ } catch (JsonMappingException e) {
+ gotExpectedException = true;
}
+ assertTrue("Attempting to mix numeric and date values in the same query should not have been allowed",
+ gotExpectedException);
- /**
+ }
+
+
+ /**
* This test validates that date range queries can be marshalled to a Java POJO and unmarshalled to ElasticSearch
* syntax.
- *
- * @throws JsonParseException
- * @throws JsonMappingException
- * @throws IOException
- */
- @Test
- public void dateRangeQueryTest() throws JsonParseException, JsonMappingException, IOException {
-
- String field = "timestamp";
- String greaterThanDate = "2016-10-06T00:00:00.558+03:00";
- String lessThanDate = "2016-10-06T23:59:59.558+03:00";
-
- ObjectMapper mapper = new ObjectMapper();
-
- // Generate a date range query using 'greater than or equal' and 'less
- // than or equal' operations.
+ *
+ * @throws JsonParseException
+ * @throws JsonMappingException
+ * @throws IOException
+ */
+ @Test
+ public void dateRangeQueryTest() throws JsonParseException, JsonMappingException, IOException {
+
+ String field = "timestamp";
+ String greaterThanDate = "2016-10-06T00:00:00.558+03:00";
+ String lessThanDate = "2016-10-06T23:59:59.558+03:00";
+
+ ObjectMapper mapper = new ObjectMapper();
+
+ // Generate a date range query using 'greater than or equal' and 'less
+ // than or equal' operations.
String dateRangeJson = "{ \"field\": \"" + field + "\", \"gte\": \"" + greaterThanDate + "\", \"lte\": \""
+ lessThanDate + "\"}";
- String dateRangeExpectedES =
- "{\"range\": {\"timestamp\": {\"gte\": \"2016-10-06T00:00:00.558+03:00\", \"lte\": \"2016-10-06T23:59:59.558+03:00\"}}}";
+ String dateRangeExpectedES =
+ "{\"range\": {\"timestamp\": {\"gte\": \"2016-10-06T00:00:00.558+03:00\", \"lte\": \"2016-10-06T23:59:59.558+03:00\"}}}";
- // Validate that the query is marshalled correctly to the POJO and that
- // the generated ElasticSearch syntax looks as expected.
- RangeQuery dateRangeQuery = mapper.readValue(dateRangeJson, RangeQuery.class);
+ // Validate that the query is marshalled correctly to the POJO and that
+ // the generated ElasticSearch syntax looks as expected.
+ RangeQuery dateRangeQuery = mapper.readValue(dateRangeJson, RangeQuery.class);
assertTrue("Unexpected marshalled value for 'field'. Expected: " + field + " Actual: "
+ dateRangeQuery.getField(), field.equals(dateRangeQuery.getField()));
assertTrue(
"Unexpected ElasticSearch syntax. Expected: " + dateRangeExpectedES + " Actual: "
+ dateRangeQuery.toElasticSearch(),
- dateRangeExpectedES.equals(dateRangeQuery.toElasticSearch()));
+ dateRangeExpectedES.equals(dateRangeQuery.toElasticSearch()));
- // Generate a date range query using 'greater than' and 'less than or
- // equal' operations.
+ // Generate a date range query using 'greater than' and 'less than or
+ // equal' operations.
dateRangeJson = "{ \"field\": \"" + field + "\", \"gt\": \"" + greaterThanDate + "\", \"lte\": \""
+ lessThanDate + "\"}";
- dateRangeExpectedES =
- "{\"range\": {\"timestamp\": {\"gt\": \"2016-10-06T00:00:00.558+03:00\", \"lte\": \"2016-10-06T23:59:59.558+03:00\"}}}";
+ dateRangeExpectedES =
+ "{\"range\": {\"timestamp\": {\"gt\": \"2016-10-06T00:00:00.558+03:00\", \"lte\": \"2016-10-06T23:59:59.558+03:00\"}}}";
- // Validate that the query is marshalled correctly to the POJO and that
- // the generated ElasticSearch syntax looks as expected.
- dateRangeQuery = mapper.readValue(dateRangeJson, RangeQuery.class);
+ // Validate that the query is marshalled correctly to the POJO and that
+ // the generated ElasticSearch syntax looks as expected.
+ dateRangeQuery = mapper.readValue(dateRangeJson, RangeQuery.class);
assertTrue("Unexpected marshalled value for 'field'. Expected: " + field + " Actual: "
+ dateRangeQuery.getField(), field.equals(dateRangeQuery.getField()));
assertTrue(
"Unexpected ElasticSearch syntax. Expected: " + dateRangeExpectedES + " Actual: "
+ dateRangeQuery.toElasticSearch(),
- dateRangeExpectedES.equals(dateRangeQuery.toElasticSearch()));
+ dateRangeExpectedES.equals(dateRangeQuery.toElasticSearch()));
- // Generate a date range query using only a 'greater than' operation.
+ // Generate a date range query using only a 'greater than' operation.
dateRangeJson = "{ \"field\": \"" + field + "\", \"gt\": \"" + greaterThanDate + "\"}";
dateRangeExpectedES = "{\"range\": {\"timestamp\": {\"gt\": \"2016-10-06T00:00:00.558+03:00\"}}}";
- // Validate that the query is marshalled correctly to the POJO and that
- // the generated ElasticSearch syntax looks as expected.
- dateRangeQuery = mapper.readValue(dateRangeJson, RangeQuery.class);
+ // Validate that the query is marshalled correctly to the POJO and that
+ // the generated ElasticSearch syntax looks as expected.
+ dateRangeQuery = mapper.readValue(dateRangeJson, RangeQuery.class);
assertTrue("Unexpected marshalled value for 'field'. Expected: " + field + " Actual: "
+ dateRangeQuery.getField(), field.equals(dateRangeQuery.getField()));
assertTrue(
"Unexpected ElasticSearch syntax. Expected: " + dateRangeExpectedES + " Actual: "
+ dateRangeQuery.toElasticSearch(),
- dateRangeExpectedES.equals(dateRangeQuery.toElasticSearch()));
+ dateRangeExpectedES.equals(dateRangeQuery.toElasticSearch()));
- }
+ }
- /**
+ /**
* This test validates that numeric range queries can be marshalled to a Java POJO and unmarshalled to ElasticSearch
* syntax.
- *
- * @throws JsonParseException
- * @throws JsonMappingException
- * @throws IOException
- */
- @Test
- public void numericRangeQueryTest() throws JsonParseException, JsonMappingException, IOException {
-
- String field = "version";
- Integer greaterThanInt = 5;
- Integer lessThanInt = 100;
-
- ObjectMapper mapper = new ObjectMapper();
-
- // Generate a numeric range query using 'greater than or equal' and 'less
- // than or equal' operations.
- String numericRangeJson =
- "{ \"field\": \"" + field + "\", \"gte\": " + greaterThanInt + ", \"lte\": " + lessThanInt + "}";
- String numericRangeExpectedES =
- "{\"range\": {\"" + field + "\": {\"gte\": " + greaterThanInt + ", \"lte\": " + lessThanInt + "}}}";
-
- // Validate that the query is marshalled correctly to the POJO and that
- // the generated ElasticSearch syntax looks as expected.
- RangeQuery numericRangeQuery = mapper.readValue(numericRangeJson, RangeQuery.class);
+ *
+ * @throws JsonParseException
+ * @throws JsonMappingException
+ * @throws IOException
+ */
+ @Test
+ public void numericRangeQueryTest() throws JsonParseException, JsonMappingException, IOException {
+
+ String field = "version";
+ Integer greaterThanInt = 5;
+ Integer lessThanInt = 100;
+
+ ObjectMapper mapper = new ObjectMapper();
+
+ // Generate a numeric range query using 'greater than or equal' and 'less
+ // than or equal' operations.
+ String numericRangeJson =
+ "{ \"field\": \"" + field + "\", \"gte\": " + greaterThanInt + ", \"lte\": " + lessThanInt + "}";
+ String numericRangeExpectedES =
+ "{\"range\": {\"" + field + "\": {\"gte\": " + greaterThanInt + ", \"lte\": " + lessThanInt + "}}}";
+
+ // Validate that the query is marshalled correctly to the POJO and that
+ // the generated ElasticSearch syntax looks as expected.
+ RangeQuery numericRangeQuery = mapper.readValue(numericRangeJson, RangeQuery.class);
assertTrue("Unexpected marshalled value for 'field'. Expected: " + field + " Actual: "
+ numericRangeQuery.getField(), field.equals(numericRangeQuery.getField()));
assertTrue(
"Unexpected type for 'gte' value. Expected: Integer Actual: "
+ numericRangeQuery.getGte().getClass().getName(),
- numericRangeQuery.getGte() instanceof Integer);
+ numericRangeQuery.getGte() instanceof Integer);
assertTrue(
"Unexpected type for 'lte' value. Expected: Integer Actual: "
+ numericRangeQuery.getLte().getClass().getName(),
- numericRangeQuery.getLte() instanceof Integer);
+ numericRangeQuery.getLte() instanceof Integer);
assertEquals("Unexpected marshalled value for 'gte'. Expected: " + greaterThanInt + " Actual: "
+ numericRangeQuery.getGte(), greaterThanInt, numericRangeQuery.getGte());
assertEquals("Unexpected marshalled value for 'lte'. Expected: " + lessThanInt + " Actual: "
assertTrue(
"Unexpected ElasticSearch syntax. Expected: " + numericRangeExpectedES + " Actual: "
+ numericRangeQuery.toElasticSearch(),
- numericRangeExpectedES.equals(numericRangeQuery.toElasticSearch()));
+ numericRangeExpectedES.equals(numericRangeQuery.toElasticSearch()));
- Double greaterThanDouble = 5.0;
- Double lessThanDouble = 100.0;
+ Double greaterThanDouble = 5.0;
+ Double lessThanDouble = 100.0;
- // Generate a date range query using 'greater than' and 'less than or
- // equal' operations.
- numericRangeJson =
- "{ \"field\": \"" + field + "\", \"gt\": " + greaterThanDouble + ", \"lte\": " + lessThanDouble + "}";
+ // Generate a date range query using 'greater than' and 'less than or
+ // equal' operations.
+ numericRangeJson =
+ "{ \"field\": \"" + field + "\", \"gt\": " + greaterThanDouble + ", \"lte\": " + lessThanDouble + "}";
numericRangeExpectedES = "{\"range\": {\"" + field + "\": {\"gt\": " + greaterThanDouble + ", \"lte\": "
+ lessThanDouble + "}}}";
- // Validate that the query is marshalled correctly to the POJO and that
- // the generated ElasticSearch syntax looks as expected.
- numericRangeQuery = mapper.readValue(numericRangeJson, RangeQuery.class);
+ // Validate that the query is marshalled correctly to the POJO and that
+ // the generated ElasticSearch syntax looks as expected.
+ numericRangeQuery = mapper.readValue(numericRangeJson, RangeQuery.class);
assertTrue("Unexpected marshalled value for 'field'. Expected: " + field + " Actual: "
+ numericRangeQuery.getField(), field.equals(numericRangeQuery.getField()));
assertTrue(
"Unexpected type for 'lte' value. Expected: Double Actual: "
+ numericRangeQuery.getLte().getClass().getName(),
- numericRangeQuery.getLte() instanceof Double);
+ numericRangeQuery.getLte() instanceof Double);
assertEquals("Unexpected marshalled value for 'gt'. Expected: " + greaterThanDouble + " Actual: "
+ numericRangeQuery.getGt(), greaterThanDouble, numericRangeQuery.getGt());
assertTrue(
"Unexpected ElasticSearch syntax. Expected: " + numericRangeExpectedES + " Actual: "
+ numericRangeQuery.toElasticSearch(),
- numericRangeExpectedES.equals(numericRangeQuery.toElasticSearch()));
- }
+ numericRangeExpectedES.equals(numericRangeQuery.toElasticSearch()));
+ }
}
-/**\r
- * ============LICENSE_START=======================================================\r
- * org.onap.aai\r
- * ================================================================================\r
- * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.\r
- * Copyright © 2017-2018 Amdocs\r
- * ================================================================================\r
- * Licensed under the Apache License, Version 2.0 (the "License");\r
- * you may not use this file except in compliance with the License.\r
- * You may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * Unless required by applicable law or agreed to in writing, software\r
- * distributed under the License is distributed on an "AS IS" BASIS,\r
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- * See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ============LICENSE_END=========================================================\r
- */\r
-package org.onap.aai.sa.searchdbabstraction.searchapi;\r
-\r
-import com.fasterxml.jackson.databind.ObjectMapper;\r
-import java.io.File;\r
-import java.io.IOException;\r
-import org.junit.Assert;\r
-import org.junit.Test;\r
-import org.onap.aai.sa.rest.TestUtils;\r
-\r
-public class RangeQueryTest {\r
-\r
- @Test(expected = IllegalArgumentException.class)\r
- public void testSetGt() {\r
-\r
- RangeQuery rq = new RangeQuery();\r
- rq.setLt(new String("2x"));\r
- Assert.assertEquals("2x", rq.getLt());\r
- Assert.assertNotNull(rq.toElasticSearch());\r
- Assert.assertNotNull(rq.toString());\r
- rq.setGt(new Integer(1));\r
- }\r
-\r
- @Test(expected = IllegalArgumentException.class)\r
- public void testSetGte() {\r
-\r
- RangeQuery rq = new RangeQuery();\r
- rq.setGt(new Integer(1));\r
- Assert.assertNotNull(rq.toElasticSearch());\r
- Assert.assertNotNull(rq.toString());\r
- rq.setGte(new Integer(1));\r
- }\r
-\r
- @Test(expected = IllegalArgumentException.class)\r
- public void testSetLt() {\r
-\r
- RangeQuery rq = new RangeQuery();\r
- rq.setLt(new Integer(1));\r
- rq.setFormat("format-1");\r
- Assert.assertEquals(rq.getFormat(), "format-1");\r
- Assert.assertNotNull(rq.toElasticSearch());\r
- Assert.assertNotNull(rq.toString());\r
-\r
- rq.setGt(new Integer(1));\r
- Assert.assertNotNull(rq.toElasticSearch());\r
- Assert.assertNotNull(rq.toString());\r
- rq.setLt(new String("10"));\r
- }\r
-\r
- @Test(expected = IllegalArgumentException.class)\r
- public void testSetLte() {\r
- RangeQuery rq = new RangeQuery();\r
- rq.setGt(new Integer(1));\r
- rq.setTimeZone("CT");\r
- Assert.assertEquals(rq.getTimeZone(), "CT");\r
- Assert.assertNotNull(rq.toElasticSearch());\r
- Assert.assertNotNull(rq.toString());\r
-\r
- rq.setLte(new String("10"));\r
- }\r
-\r
- @Test\r
- public void testSearchStatementAggregations() throws IOException {\r
- File queryWithSubrangeFile = new File("src/test/resources/json/queries/query-with-subrange.json");\r
- String queryWithSubrangeStr = TestUtils.readFileToString(queryWithSubrangeFile);\r
-\r
- ObjectMapper mapper = new ObjectMapper();\r
- SearchStatement ss = mapper.readValue(queryWithSubrangeStr, SearchStatement.class);\r
-\r
- Aggregation a1 = getAggregationObject();\r
- Aggregation a2 = getAggregationObject();\r
- Aggregation[] aggs = new Aggregation[] {a1, a2};\r
- ss.setAggregations(aggs);\r
- Assert.assertNotNull(ss.toString());\r
- }\r
-\r
- private Aggregation getAggregationObject() {\r
- Aggregation a = new Aggregation();\r
-\r
- AggregationStatement as = new AggregationStatement();\r
- DateHistogramAggregation dha = new DateHistogramAggregation();\r
- dha.setField("field-1");\r
- dha.setInterval("interval-1");\r
- Assert.assertEquals(dha.getInterval(), "interval-1");\r
- dha.setTimeZone("CT");\r
- Assert.assertEquals(dha.getTimeZone(), "CT");\r
- dha.setFormat("format-1");\r
- Assert.assertEquals(dha.getFormat(), "format-1");\r
- dha.setSize(10);\r
- dha.setMinThreshold(1);\r
- Assert.assertNotNull(dha.toElasticSearch());\r
- Assert.assertNotNull(dha.toString());\r
- as.setDateHist(dha);\r
- as.toString();\r
-\r
- as.getNestedPath();\r
-\r
- DateRangeAggregation dra = new DateRangeAggregation();\r
- dra.setField("field-1");\r
- dra.setMinThreshold(1);\r
- dra.setFormat("format-1");\r
- Assert.assertEquals(dra.getFormat(), "format-1");\r
- DateRange dr = new DateRange();\r
- dr.setFromDate("01-12-2017");\r
- Assert.assertEquals(dr.getFromDate(), "01-12-2017");\r
- dr.setToDate("21-12-2017");\r
- Assert.assertEquals(dr.getToDate(), "21-12-2017");\r
- DateRange[] drs = {dr};\r
- dra.setDateRanges(drs);\r
- Assert.assertTrue(dra.getDateRanges().length == 1);\r
- Assert.assertNotNull(dra.toElasticSearch());\r
- Assert.assertNotNull(dra.toString());\r
- as.setDateRange(dra);\r
- as.toString();\r
-\r
- as.getNestedPath();\r
-\r
- GroupByAggregation gba = new GroupByAggregation();\r
- gba.setField("field-1");\r
- gba.setMinThreshold(1);\r
- Assert.assertNotNull(gba.toElasticSearch());\r
- Assert.assertNotNull(gba.toString());\r
- as.setGroupBy(gba);\r
- Assert.assertNotNull(as.toString());\r
-\r
- a.setStatement(as);\r
- Assert.assertNotNull(a.toString());\r
- return a;\r
- }\r
-}\r
+/**
+ * ============LICENSE_START=======================================================
+ * org.onap.aai
+ * ================================================================================
+ * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright © 2017-2018 Amdocs
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+package org.onap.aai.sa.searchdbabstraction.searchapi;
+
+import static org.hamcrest.CoreMatchers.equalTo;
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertThat;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import java.io.File;
+import java.io.IOException;
+import org.junit.Assert;
+import org.junit.Test;
+import org.onap.aai.sa.rest.TestUtils;
+
+public class RangeQueryTest {
+
+ static {
+ // Set the location of the payload translation JSON file.
+ System.setProperty("CONFIG_HOME", "src/test/resources/json");
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void testSetGt() {
+ RangeQuery rq = new RangeQuery();
+ rq.setLt(new String("2x"));
+ Assert.assertEquals("2x", rq.getLt());
+ Assert.assertNotNull(rq.toElasticSearch());
+ Assert.assertNotNull(rq.toString());
+ rq.setGt(new Integer(1));
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void testSetGte() {
+ RangeQuery rq = new RangeQuery();
+ rq.setGt(new Integer(1));
+ Assert.assertNotNull(rq.toElasticSearch());
+ Assert.assertNotNull(rq.toString());
+ rq.setGte(new Integer(1));
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void testSetLt() {
+ RangeQuery rq = new RangeQuery();
+ rq.setLt(new Integer(1));
+ rq.setFormat("format-1");
+ assertThat(rq.getFormat(), is(equalTo("format-1")));
+ Assert.assertNotNull(rq.toElasticSearch());
+ Assert.assertNotNull(rq.toString());
+
+ rq.setGt(new Integer(1));
+ Assert.assertNotNull(rq.toElasticSearch());
+ Assert.assertNotNull(rq.toString());
+ rq.setLt(new String("10"));
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void testSetLte() {
+ RangeQuery rq = new RangeQuery();
+ rq.setGt(new Integer(1));
+ rq.setTimeZone("CT");
+ assertThat(rq.getTimeZone(), is(equalTo("CT")));
+ Assert.assertNotNull(rq.toElasticSearch());
+ Assert.assertNotNull(rq.toString());
+
+ rq.setLte(new String("10"));
+ }
+
+ @Test
+ public void testSearchStatementAggregations() throws IOException {
+ File queryWithSubrangeFile = new File("src/test/resources/json/queries/query-with-subrange.json");
+ String queryWithSubrangeStr = TestUtils.readFileToString(queryWithSubrangeFile);
+
+ ObjectMapper mapper = new ObjectMapper();
+ SearchStatement ss = mapper.readValue(queryWithSubrangeStr, SearchStatement.class);
+
+ Aggregation a1 = getAggregationObject();
+ Aggregation a2 = getAggregationObject();
+ Aggregation[] aggs = new Aggregation[] {a1, a2};
+ ss.setAggregations(aggs);
+ Assert.assertNotNull(ss.toString());
+ }
+
+ private Aggregation getAggregationObject() {
+ Aggregation a = new Aggregation();
+
+ AggregationStatement as = new AggregationStatement();
+ DateHistogramAggregation dha = new DateHistogramAggregation();
+ dha.setField("field-1");
+ dha.setInterval("interval-1");
+ assertThat(dha.getInterval(), is(equalTo("interval-1")));
+ dha.setTimeZone("CT");
+ assertThat(dha.getTimeZone(), is(equalTo("CT")));
+ dha.setFormat("format-1");
+ assertThat(dha.getFormat(), is(equalTo("format-1")));
+ dha.setSize(10);
+ dha.setMinThreshold(1);
+ Assert.assertNotNull(dha.toElasticSearch());
+ Assert.assertNotNull(dha.toString());
+ as.setDateHist(dha);
+ as.toString();
+
+ as.getNestedPath();
+
+ DateRangeAggregation dra = new DateRangeAggregation();
+ dra.setField("field-1");
+ dra.setMinThreshold(1);
+ dra.setFormat("format-1");
+ assertThat(dra.getFormat(), is(equalTo("format-1")));
+ DateRange dr = new DateRange();
+ dr.setFromDate("01-12-2017");
+ assertThat(dr.getFromDate(), is(equalTo("01-12-2017")));
+ dr.setToDate("21-12-2017");
+ assertThat(dr.getToDate(), is(equalTo("21-12-2017")));
+ DateRange[] drs = {dr};
+ dra.setDateRanges(drs);
+ Assert.assertTrue(dra.getDateRanges().length == 1);
+ Assert.assertNotNull(dra.toElasticSearch());
+ Assert.assertNotNull(dra.toString());
+ as.setDateRange(dra);
+ as.toString();
+
+ as.getNestedPath();
+
+ GroupByAggregation gba = new GroupByAggregation();
+ gba.setField("field-1");
+ gba.setMinThreshold(1);
+ Assert.assertNotNull(gba.toElasticSearch());
+ Assert.assertNotNull(gba.toString());
+ as.setGroupBy(gba);
+ Assert.assertNotNull(as.toString());
+
+ a.setStatement(as);
+ Assert.assertNotNull(a.toString());
+ return a;
+ }
+}
\r
@Test\r
public void testAllMethods() throws IOException {\r
-\r
String field = "searchTags.nested";\r
String stringValue = "theValue.nested";\r
String termQueryWithStringValueJson = "{\"field\": \"" + field + "\", \"value\": \"" + stringValue + "\"}";\r
- String termQueryWithStringValueExpectedES = "{\"term\": {\"" + field + "\" : \"" + stringValue + "\"}}";\r
\r
ObjectMapper mapper = new ObjectMapper();\r
TermQuery stringTermQuery = mapper.readValue(termQueryWithStringValueJson, TermQuery.class);\r