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