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 org.onap.aai.sa.searchdbabstraction.elasticsearch.dao.ElasticSearchHttpController;
24 import org.onap.aai.sa.searchdbabstraction.logging.SearchDbMsgs;
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.rest.AnalyzerSchema;
31 import java.util.concurrent.atomic.AtomicBoolean;
32 import javax.servlet.http.HttpServletRequest;
35 import org.springframework.beans.factory.annotation.Qualifier;
36 import org.springframework.http.HttpHeaders;
37 import org.springframework.http.MediaType;
38 import org.springframework.http.ResponseEntity;
39 import org.springframework.http.HttpStatus;
40 import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
41 import org.springframework.stereotype.Component;
42 import org.springframework.web.bind.annotation.RequestHeader;
43 import org.springframework.web.bind.annotation.RequestMapping;
44 import org.springframework.web.bind.annotation.RequestMethod;
45 import org.springframework.web.bind.annotation.RestController;
50 @RequestMapping("/services/search-data-service/v1/analyzers/search")
51 public class AnalyzerApi {
53 private SearchServiceApi searchService = null;
55 // Set up the loggers.
56 private static Logger logger = LoggerFactory.getInstance().getLogger(IndexApi.class.getName());
57 private static Logger auditLogger = LoggerFactory.getInstance()
58 .getAuditLogger(IndexApi.class.getName());
60 public AnalyzerApi( @Qualifier("searchServiceApi") SearchServiceApi searchService) {
61 this.searchService = searchService;
64 @RequestMapping(method = RequestMethod.GET,
65 consumes = {"application/json"},
66 produces = {"application/json"})
67 public ResponseEntity<String> processGet(HttpServletRequest request,
68 @RequestHeader HttpHeaders headers,
71 HttpStatus responseCode = HttpStatus.INTERNAL_SERVER_ERROR;
72 String responseString = "Undefined error";
74 // Initialize the MDC Context for logging purposes.
75 ApiUtils.initMdcContext(request, headers);
77 // Validate that the request is correctly authenticated before going
81 if (!searchService.validateRequest(headers, request,
82 ApiUtils.Action.GET, ApiUtils.SEARCH_AUTH_POLICY_NAME)) {
83 logger.warn(SearchDbMsgs.GET_ANALYZERS_FAILURE, "Authentication failure.");
84 return ResponseEntity.status(HttpStatus.FORBIDDEN).contentType ( MediaType.APPLICATION_JSON ).body("Authentication failure.");
87 } catch (Exception e) {
89 logger.warn(SearchDbMsgs.GET_ANALYZERS_FAILURE,
90 "Unexpected authentication failure - cause: " + e.getMessage());
91 return ResponseEntity.status(HttpStatus.FORBIDDEN).contentType ( MediaType.APPLICATION_JSON ).body("Authentication failure.");
95 // Now, build the list of analyzers.
97 responseString = buildAnalyzerList(ElasticSearchHttpController.getInstance()
98 .getAnalysisConfig());
99 responseCode = HttpStatus.OK;
101 } catch (Exception e) {
103 logger.warn(SearchDbMsgs.GET_ANALYZERS_FAILURE,
104 "Unexpected failure retrieving analysis configuration - cause: " + e.getMessage());
105 responseString = "Failed to retrieve analysis configuration. Cause: " + e.getMessage();
108 // Build the HTTP response.
109 ResponseEntity response = ResponseEntity.status(responseCode).contentType ( MediaType.APPLICATION_JSON ).body(responseString);
111 // Generate our audit log.
112 auditLogger.info(SearchDbMsgs.PROCESS_REST_REQUEST,
114 .setField(LogLine.DefinedFields.RESPONSE_CODE, responseCode.value ())
115 .setField(LogLine.DefinedFields.RESPONSE_DESCRIPTION, responseCode.value()),
116 (request != null) ? request.getMethod() : "Unknown",
117 (request != null) ? request.getRequestURL ().toString () : "Unknown",
118 (request != null) ? request.getRemoteHost () : "Unknown",
119 Integer.toString(response.getStatusCodeValue ()));
121 // Clear the MDC context so that no other transaction inadvertently
122 // uses our transaction id.
123 ApiUtils.clearMdcContext();
130 * This method takes a list of analyzer objects and generates a simple json
131 * structure to enumerate them.
133 * <p>Note, this includes only the aspects of the analyzer object that we want
134 * to make public to an external client.
136 * @param analysisConfig - The analysis configuration object to extract the
138 * @return - A json string enumerating the defined analyzers.
140 private String buildAnalyzerList(AnalysisConfiguration analysisConfig) {
142 StringBuilder sb = new StringBuilder();
145 AtomicBoolean firstAnalyzer = new AtomicBoolean(true);
146 for (AnalyzerSchema analyzer : analysisConfig.getAnalyzers()) {
148 if (!firstAnalyzer.compareAndSet(true, false)) {
153 sb.append("\"name\": \"").append(analyzer.getName()).append("\", ");
154 sb.append("\"description\": \"").append(analyzer.getDescription()).append("\", ");
155 sb.append("\"behaviours\": [");
156 AtomicBoolean firstBehaviour = new AtomicBoolean(true);
157 for (String behaviour : analyzer.getBehaviours()) {
158 if (!firstBehaviour.compareAndSet(true, false)) {
161 sb.append("\"").append(behaviour).append("\"");
168 return sb.toString();