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