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