2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
6 * Copyright © 2017-2018 Amdocs
7 * ================================================================================
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
19 * ============LICENSE_END=========================================================
21 package org.onap.aai.sa.rest;
23 import java.util.concurrent.atomic.AtomicBoolean;
24 import javax.servlet.http.HttpServletRequest;
25 import org.onap.aai.cl.api.LogFields;
26 import org.onap.aai.cl.api.LogLine;
27 import org.onap.aai.cl.api.Logger;
28 import org.onap.aai.cl.eelf.LoggerFactory;
29 import org.onap.aai.sa.searchdbabstraction.elasticsearch.dao.ElasticSearchHttpController;
30 import org.onap.aai.sa.searchdbabstraction.logging.SearchDbMsgs;
31 import org.springframework.beans.factory.annotation.Qualifier;
32 import org.springframework.http.HttpHeaders;
33 import org.springframework.http.HttpStatus;
34 import org.springframework.http.MediaType;
35 import org.springframework.http.ResponseEntity;
36 import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
37 import org.springframework.stereotype.Component;
38 import org.springframework.web.bind.annotation.RequestHeader;
39 import org.springframework.web.bind.annotation.RequestMapping;
40 import org.springframework.web.bind.annotation.RequestMethod;
41 import org.springframework.web.bind.annotation.RestController;
46 @RequestMapping("/services/search-data-service/v1/analyzers/search")
47 public class AnalyzerApi {
49 private SearchServiceApi searchService = null;
51 // Set up the loggers.
52 private static Logger logger = LoggerFactory.getInstance().getLogger(IndexApi.class.getName());
53 private static Logger auditLogger = LoggerFactory.getInstance()
54 .getAuditLogger(IndexApi.class.getName());
56 public AnalyzerApi( @Qualifier("searchServiceApi") SearchServiceApi searchService) {
57 this.searchService = searchService;
60 @RequestMapping(method = RequestMethod.GET,
61 consumes = {"application/json"},
62 produces = {"application/json"})
63 public ResponseEntity<String> processGet(HttpServletRequest request,
64 @RequestHeader HttpHeaders headers,
67 HttpStatus responseCode = HttpStatus.INTERNAL_SERVER_ERROR;
68 String responseString = "Undefined error";
70 // Initialize the MDC Context for logging purposes.
71 ApiUtils.initMdcContext(request, headers);
73 // Validate that the request is correctly authenticated before going
77 if (!searchService.validateRequest(headers, request,
78 ApiUtils.Action.GET, ApiUtils.SEARCH_AUTH_POLICY_NAME)) {
79 logger.warn(SearchDbMsgs.GET_ANALYZERS_FAILURE, "Authentication failure.");
80 return ResponseEntity.status(HttpStatus.FORBIDDEN).contentType ( MediaType.APPLICATION_JSON ).body("Authentication failure.");
83 } catch (Exception e) {
85 logger.warn(SearchDbMsgs.GET_ANALYZERS_FAILURE,
86 "Unexpected authentication failure - cause: " + e.getMessage());
87 return ResponseEntity.status(HttpStatus.FORBIDDEN).contentType ( MediaType.APPLICATION_JSON ).body("Authentication failure.");
91 // Now, build the list of analyzers.
93 responseString = buildAnalyzerList(ElasticSearchHttpController.getInstance()
94 .getAnalysisConfig());
95 responseCode = HttpStatus.OK;
97 } catch (Exception e) {
99 logger.warn(SearchDbMsgs.GET_ANALYZERS_FAILURE,
100 "Unexpected failure retrieving analysis configuration - cause: " + e.getMessage());
101 responseString = "Failed to retrieve analysis configuration. Cause: " + e.getMessage();
104 // Build the HTTP response.
105 ResponseEntity response = ResponseEntity.status(responseCode).contentType ( MediaType.APPLICATION_JSON ).body(responseString);
107 // Generate our audit log.
108 auditLogger.info(SearchDbMsgs.PROCESS_REST_REQUEST,
110 .setField(LogLine.DefinedFields.RESPONSE_CODE, responseCode.value ())
111 .setField(LogLine.DefinedFields.RESPONSE_DESCRIPTION, responseCode.value()),
112 (request != null) ? request.getMethod() : "Unknown",
113 (request != null) ? request.getRequestURL ().toString () : "Unknown",
114 (request != null) ? request.getRemoteHost () : "Unknown",
115 Integer.toString(response.getStatusCodeValue ()));
117 // Clear the MDC context so that no other transaction inadvertently
118 // uses our transaction id.
119 ApiUtils.clearMdcContext();
126 * This method takes a list of analyzer objects and generates a simple json
127 * structure to enumerate them.
129 * <p>Note, this includes only the aspects of the analyzer object that we want
130 * to make public to an external client.
132 * @param analysisConfig - The analysis configuration object to extract the
134 * @return - A json string enumerating the defined analyzers.
136 private String buildAnalyzerList(AnalysisConfiguration analysisConfig) {
138 StringBuilder sb = new StringBuilder();
141 AtomicBoolean firstAnalyzer = new AtomicBoolean(true);
142 for (AnalyzerSchema analyzer : analysisConfig.getAnalyzers()) {
144 if (!firstAnalyzer.compareAndSet(true, false)) {
149 sb.append("\"name\": \"").append(analyzer.getName()).append("\", ");
150 sb.append("\"description\": \"").append(analyzer.getDescription()).append("\", ");
151 sb.append("\"behaviours\": [");
152 AtomicBoolean firstBehaviour = new AtomicBoolean(true);
153 for (String behaviour : analyzer.getBehaviours()) {
154 if (!firstBehaviour.compareAndSet(true, false)) {
157 sb.append("\"").append(behaviour).append("\"");
164 return sb.toString();