Add missing distributionManagement section to poms
[aai/search-data-service.git] / search-data-service / 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 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;
42
43 @Component
44 @EnableWebSecurity
45 @RestController
46 @RequestMapping("/services/search-data-service/v1/analyzers/search")
47 public class AnalyzerApi {
48
49     private SearchServiceApi searchService = null;
50
51     // Set up the loggers.
52     private static Logger logger = LoggerFactory.getInstance().getLogger(IndexApi.class.getName());
53     private static Logger auditLogger = LoggerFactory.getInstance().getAuditLogger(IndexApi.class.getName());
54
55     private static final String MSG_AUTHENTICATION_FAILURE = "Authentication failure.";
56
57     public AnalyzerApi(@Qualifier("searchServiceApi") SearchServiceApi searchService) {
58         this.searchService = searchService;
59     }
60
61     @RequestMapping(method = RequestMethod.GET, consumes = {"application/json"}, produces = {"application/json"})
62     public ResponseEntity<String> processGet(HttpServletRequest request, @RequestHeader HttpHeaders headers,
63             ApiUtils apiUtils) {
64
65         HttpStatus responseCode = HttpStatus.INTERNAL_SERVER_ERROR;
66         String responseString;
67
68         // Initialize the MDC Context for logging purposes.
69         ApiUtils.initMdcContext(request, headers);
70
71         // Validate that the request is correctly authenticated before going
72         // any further.
73         try {
74
75             if (!searchService.validateRequest(headers, request, ApiUtils.Action.GET,
76                     ApiUtils.SEARCH_AUTH_POLICY_NAME)) {
77                 logger.warn(SearchDbMsgs.GET_ANALYZERS_FAILURE, MSG_AUTHENTICATION_FAILURE);
78                 return ResponseEntity.status(HttpStatus.FORBIDDEN).contentType(MediaType.APPLICATION_JSON)
79                         .body(MSG_AUTHENTICATION_FAILURE);
80             }
81
82         } catch (Exception e) {
83
84             logger.warn(SearchDbMsgs.GET_ANALYZERS_FAILURE,
85                     "Unexpected authentication failure - cause: " + e.getMessage());
86             return ResponseEntity.status(HttpStatus.FORBIDDEN).contentType(MediaType.APPLICATION_JSON)
87                     .body(MSG_AUTHENTICATION_FAILURE);
88         }
89
90
91         // Now, build the list of analyzers.
92         try {
93             responseString = buildAnalyzerList(ElasticSearchHttpController.getInstance().getAnalysisConfig());
94             responseCode = HttpStatus.OK;
95         } catch (Exception e) {
96             logger.warn(SearchDbMsgs.GET_ANALYZERS_FAILURE,
97                     "Unexpected failure retrieving analysis configuration - cause: " + e.getMessage());
98             responseString = "Failed to retrieve analysis configuration.  Cause: " + e.getMessage();
99         }
100
101         // Build the HTTP response.
102         ResponseEntity<String> response =
103                 ResponseEntity.status(responseCode).contentType(MediaType.APPLICATION_JSON).body(responseString);
104
105         // Generate our audit log.
106         String unknownLogField = "Unknown";
107         auditLogger.info(SearchDbMsgs.PROCESS_REST_REQUEST,
108                 new LogFields().setField(LogLine.DefinedFields.RESPONSE_CODE, responseCode.value())
109                         .setField(LogLine.DefinedFields.RESPONSE_DESCRIPTION, responseCode.value()),
110                 (request != null) ? request.getMethod() : unknownLogField,
111                 (request != null) ? request.getRequestURL().toString() : unknownLogField,
112                 (request != null) ? request.getRemoteHost() : unknownLogField,
113                 Integer.toString(response.getStatusCodeValue()));
114
115         // Clear the MDC context so that no other transaction inadvertently
116         // uses our transaction id.
117         ApiUtils.clearMdcContext();
118
119         return response;
120     }
121
122     /**
123      * This method takes a list of analyzer objects and generates a simple json structure to enumerate them.
124      *
125      * <p>
126      * Note, this includes only the aspects of the analyzer object that we want to make public to an external client.
127      *
128      * @param analysisConfig - The analysis configuration object to extract the analyzers from.
129      * @return - A json string enumerating the defined analyzers.
130      */
131     private String buildAnalyzerList(AnalysisConfiguration analysisConfig) {
132
133         StringBuilder sb = new StringBuilder();
134
135         sb.append("{");
136         AtomicBoolean firstAnalyzer = new AtomicBoolean(true);
137         for (AnalyzerSchema analyzer : analysisConfig.getAnalyzers()) {
138
139             if (!firstAnalyzer.compareAndSet(true, false)) {
140                 sb.append(", ");
141             }
142
143             sb.append("{");
144             sb.append("\"name\": \"").append(analyzer.getName()).append("\", ");
145             sb.append("\"description\": \"").append(analyzer.getDescription()).append("\", ");
146             sb.append("\"behaviours\": [");
147             AtomicBoolean firstBehaviour = new AtomicBoolean(true);
148             for (String behaviour : analyzer.getBehaviours()) {
149                 if (!firstBehaviour.compareAndSet(true, false)) {
150                     sb.append(", ");
151                 }
152                 sb.append("\"").append(behaviour).append("\"");
153             }
154             sb.append("]");
155             sb.append("}");
156         }
157         sb.append("}");
158
159         return sb.toString();
160     }
161 }