fix ping communication with search to datarouter
[aai/search-data-service.git] / src / main / java / org / onap / aai / sa / rest / AnalyzerApi.java
1 /**
2  * ============LICENSE_START=======================================================
3  * org.onap.aai
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
11  *
12  *       http://www.apache.org/licenses/LICENSE-2.0
13  *
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=========================================================
20  */
21 package org.onap.aai.sa.rest;
22
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;
30
31 import java.util.concurrent.atomic.AtomicBoolean;
32 import javax.servlet.http.HttpServletRequest;
33
34
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;
46
47 @Component
48 @EnableWebSecurity
49 @RestController
50 @RequestMapping("/services/search-data-service/v1/analyzers/search")
51 public class AnalyzerApi {
52
53   private SearchServiceApi searchService = null;
54
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());
59
60   public AnalyzerApi( @Qualifier("searchServiceApi") SearchServiceApi searchService) {
61     this.searchService = searchService;
62   }
63
64   @RequestMapping(method = RequestMethod.GET,
65           consumes = {"application/json"},
66           produces = {"application/json"})
67   public ResponseEntity<String> processGet(HttpServletRequest request,
68                                            @RequestHeader HttpHeaders headers,
69                                            ApiUtils apiUtils) {
70
71     HttpStatus responseCode = HttpStatus.INTERNAL_SERVER_ERROR;
72     String responseString = "Undefined error";
73
74     // Initialize the MDC Context for logging purposes.
75     ApiUtils.initMdcContext(request, headers);
76
77     // Validate that the request is correctly authenticated before going
78     // any further.
79     try {
80
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.");
85       }
86
87     } catch (Exception e) {
88
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.");
92     }
93
94
95     // Now, build the list of analyzers.
96     try {
97       responseString = buildAnalyzerList(ElasticSearchHttpController.getInstance()
98           .getAnalysisConfig());
99       responseCode = HttpStatus.OK;
100
101     } catch (Exception e) {
102
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();
106     }
107
108     // Build the HTTP response.
109     ResponseEntity response = ResponseEntity.status(responseCode).contentType ( MediaType.APPLICATION_JSON ).body(responseString);
110
111     // Generate our audit log.
112     auditLogger.info(SearchDbMsgs.PROCESS_REST_REQUEST,
113         new LogFields()
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 ()));
120
121     // Clear the MDC context so that no other transaction inadvertently
122     // uses our transaction id.
123     ApiUtils.clearMdcContext();
124
125     return response;
126   }
127
128
129   /**
130    * This method takes a list of analyzer objects and generates a simple json
131    * structure to enumerate them.
132    *
133    * <p>Note, this includes only the aspects of the analyzer object that we want
134    * to make public to an external client.
135    *
136    * @param analysisConfig - The analysis configuration object to extract the
137    *                       analyzers from.
138    * @return - A json string enumerating the defined analyzers.
139    */
140   private String buildAnalyzerList(AnalysisConfiguration analysisConfig) {
141
142     StringBuilder sb = new StringBuilder();
143
144     sb.append("{");
145     AtomicBoolean firstAnalyzer = new AtomicBoolean(true);
146     for (AnalyzerSchema analyzer : analysisConfig.getAnalyzers()) {
147
148       if (!firstAnalyzer.compareAndSet(true, false)) {
149         sb.append(", ");
150       }
151
152       sb.append("{");
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)) {
159           sb.append(", ");
160         }
161         sb.append("\"").append(behaviour).append("\"");
162       }
163       sb.append("]");
164       sb.append("}");
165     }
166     sb.append("}");
167
168     return sb.toString();
169   }
170 }