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