430b7a6ac5893e4fff7449cccce93fb41fdbc07d
[aai/search-data-service.git] / src / main / java / org / openecomp / sa / rest / AnalyzerApi.java
1 /**
2  * ============LICENSE_START=======================================================
3  * Search Data Service
4  * ================================================================================
5  * Copyright © 2017 AT&T Intellectual Property.
6  * Copyright © 2017 Amdocs
7  * All rights reserved.
8  * ================================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License ati
12  *
13  *    http://www.apache.org/licenses/LICENSE-2.0
14  *
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * ============LICENSE_END=========================================================
21  *
22  * ECOMP and OpenECOMP are trademarks
23  * and service marks of AT&T Intellectual Property.
24  */
25 package org.openecomp.sa.rest;
26
27 import org.openecomp.cl.api.LogFields;
28 import org.openecomp.cl.api.LogLine;
29 import org.openecomp.cl.api.Logger;
30 import org.openecomp.cl.eelf.LoggerFactory;
31 import org.openecomp.sa.searchdbabstraction.elasticsearch.dao.ElasticSearchHttpController;
32 import org.openecomp.sa.searchdbabstraction.logging.SearchDbMsgs;
33
34 import java.util.concurrent.atomic.AtomicBoolean;
35 import javax.servlet.http.HttpServletRequest;
36 import javax.ws.rs.GET;
37 import javax.ws.rs.Path;
38 import javax.ws.rs.core.Context;
39 import javax.ws.rs.core.HttpHeaders;
40 import javax.ws.rs.core.Response;
41
42 @Path("/analyzers")
43 public class AnalyzerApi {
44
45   private SearchServiceApi searchService = null;
46
47   // Set up the loggers.
48   private static Logger logger = LoggerFactory.getInstance().getLogger(IndexApi.class.getName());
49   private static Logger auditLogger = LoggerFactory.getInstance()
50       .getAuditLogger(IndexApi.class.getName());
51
52   public AnalyzerApi(SearchServiceApi searchService) {
53     this.searchService = searchService;
54   }
55
56   @GET
57   public Response processGet(@Context HttpServletRequest request,
58                              @Context HttpHeaders headers,
59                              ApiUtils apiUtils) {
60
61     Response.Status responseCode = Response.Status.INTERNAL_SERVER_ERROR;
62     String responseString = "Undefined error";
63
64     // Initialize the MDC Context for logging purposes.
65     ApiUtils.initMdcContext(request, headers);
66
67     // Validate that the request is correctly authenticated before going
68     // any further.
69     try {
70
71       if (!searchService.validateRequest(headers, request,
72           ApiUtils.Action.GET, ApiUtils.SEARCH_AUTH_POLICY_NAME)) {
73         logger.warn(SearchDbMsgs.GET_ANALYZERS_FAILURE, "Authentication failure.");
74         return Response.status(Response.Status.FORBIDDEN).entity("Authentication failure.").build();
75       }
76
77     } catch (Exception e) {
78
79       logger.warn(SearchDbMsgs.GET_ANALYZERS_FAILURE,
80           "Unexpected authentication failure - cause: " + e.getMessage());
81       return Response.status(Response.Status.FORBIDDEN).entity("Authentication failure.").build();
82     }
83
84
85     // Now, build the list of analyzers.
86     try {
87       responseString = buildAnalyzerList(ElasticSearchHttpController.getInstance()
88           .getAnalysisConfig());
89       responseCode = Response.Status.OK;
90
91     } catch (Exception e) {
92
93       logger.warn(SearchDbMsgs.GET_ANALYZERS_FAILURE,
94           "Unexpected failure retrieving analysis configuration - cause: " + e.getMessage());
95       responseString = "Failed to retrieve analysis configuration.  Cause: " + e.getMessage();
96     }
97
98     // Build the HTTP response.
99     Response response = Response.status(responseCode).entity(responseString).build();
100
101     // Generate our audit log.
102     auditLogger.info(SearchDbMsgs.PROCESS_REST_REQUEST,
103         new LogFields()
104             .setField(LogLine.DefinedFields.RESPONSE_CODE, responseCode.getStatusCode())
105             .setField(LogLine.DefinedFields.RESPONSE_DESCRIPTION, responseCode.getStatusCode()),
106         (request != null) ? request.getMethod() : "Unknown",
107         (request != null) ? request.getRequestURL().toString() : "Unknown",
108         (request != null) ? request.getRemoteHost() : "Unknown",
109         Integer.toString(response.getStatus()));
110
111     // Clear the MDC context so that no other transaction inadvertently
112     // uses our transaction id.
113     ApiUtils.clearMdcContext();
114
115     return response;
116   }
117
118
119   /**
120    * This method takes a list of analyzer objects and generates a simple json
121    * structure to enumerate them.
122    *
123    * <p>Note, this includes only the aspects of the analyzer object that we want
124    * to make public to an external client.
125    *
126    * @param analysisConfig - The analysis configuration object to extract the
127    *                       analyzers from.
128    * @return - A json string enumerating the defined analyzers.
129    */
130   private String buildAnalyzerList(AnalysisConfiguration analysisConfig) {
131
132     StringBuilder sb = new StringBuilder();
133
134     sb.append("{");
135     AtomicBoolean firstAnalyzer = new AtomicBoolean(true);
136     for (AnalyzerSchema analyzer : analysisConfig.getAnalyzers()) {
137
138       if (!firstAnalyzer.compareAndSet(true, false)) {
139         sb.append(", ");
140       }
141
142       sb.append("{");
143       sb.append("\"name\": \"").append(analyzer.getName()).append("\", ");
144       sb.append("\"description\": \"").append(analyzer.getDescription()).append("\", ");
145       sb.append("\"behaviours\": [");
146       AtomicBoolean firstBehaviour = new AtomicBoolean(true);
147       for (String behaviour : analyzer.getBehaviours()) {
148         if (!firstBehaviour.compareAndSet(true, false)) {
149           sb.append(", ");
150         }
151         sb.append("\"").append(behaviour).append("\"");
152       }
153       sb.append("]");
154       sb.append("}");
155     }
156     sb.append("}");
157
158     return sb.toString();
159   }
160 }