441b529b16257713b3093d6513b833a8aa4787f8
[ccsdk/dashboard.git] /
1 /*******************************************************************************
2  * =============LICENSE_START=========================================================
3  *
4  * =================================================================================
5  *  Copyright (c) 2019 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  *  Licensed under the Apache License, Version 2.0 (the "License");
8  *  you may not use this file except in compliance with the License.
9  *  You may obtain a copy of the License at
10  *  
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *  
13  *  Unless required by applicable law or agreed to in writing, software
14  *  distributed under the License is distributed on an "AS IS" BASIS,
15  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  *  See the License for the specific language governing permissions and
17  *  limitations under the License.
18  * ============LICENSE_END=========================================================
19  *
20  *  ECOMP is a trademark and service mark of AT&T Intellectual Property.
21  *******************************************************************************/
22 package org.onap.ccsdk.dashboard.controller;
23
24 import java.text.DateFormat;
25 import java.text.SimpleDateFormat;
26 import java.util.ArrayList;
27 import java.util.List;
28
29 import javax.servlet.http.HttpServletRequest;
30
31 import org.onap.ccsdk.dashboard.domain.ControllerEndpoint;
32 import org.onap.ccsdk.dashboard.model.ControllerEndpointCredentials;
33 import org.onap.ccsdk.dashboard.model.ControllerOpsTools;
34 import org.onap.ccsdk.dashboard.rest.CloudifyClient;
35 import org.onap.ccsdk.dashboard.rest.CloudifyMockClientImpl;
36 import org.onap.ccsdk.dashboard.rest.CloudifyRestClientImpl;
37 import org.onap.ccsdk.dashboard.rest.ConsulClient;
38 import org.onap.ccsdk.dashboard.rest.ConsulMockClientImpl;
39 import org.onap.ccsdk.dashboard.rest.ConsulRestClientImpl;
40 import org.onap.ccsdk.dashboard.rest.DeploymentHandlerClient;
41 import org.onap.ccsdk.dashboard.rest.DeploymentHandlerClientImpl;
42 import org.onap.ccsdk.dashboard.rest.InventoryClient;
43 import org.onap.ccsdk.dashboard.rest.RestInventoryClientImpl;
44 import org.onap.ccsdk.dashboard.rest.RestInventoryClientMockImpl;
45 import org.onap.ccsdk.dashboard.service.ControllerEndpointService;
46 import org.onap.ccsdk.dashboard.util.DashboardProperties;
47 import org.onap.portalsdk.core.controller.RestrictedBaseController;
48 import org.onap.portalsdk.core.domain.User;
49 import org.onap.portalsdk.core.web.support.UserUtils;
50 import org.springframework.beans.factory.annotation.Autowired;
51
52 import com.fasterxml.jackson.annotation.JsonInclude;
53 import com.fasterxml.jackson.databind.ObjectMapper;
54 import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
55
56 /**
57  * This base class provides utility methods to child controllers.
58  */
59 public class DashboardRestrictedBaseController extends RestrictedBaseController {
60
61     /**
62      * Application name
63      */
64     protected static final String APP_NAME = "ecd-app";
65
66     /**
67      * EELF-approved format
68      */
69     protected static final DateFormat logDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
70
71     /**
72      * Query parameter for desired page number
73      */
74     protected static final String PAGE_NUM_QUERY_PARAM = "pageNum";
75
76     /**
77      * Query parameter for desired items per page
78      */
79     protected static final String PAGE_SIZE_QUERY_PARAM = "viewPerPage";
80
81     /**
82      * For general use in these methods and subclasses
83      */
84     protected final ObjectMapper objectMapper = new ObjectMapper();
85
86     /**
87      * Application properties - NOT available to constructor.
88      */
89     @Autowired
90     protected DashboardProperties appProperties;
91
92     /**
93      * For getting selected controller
94      */
95     @Autowired
96     private ControllerEndpointService controllerEndpointService;
97
98     /**
99      * Hello Spring, here's your no-arg constructor.
100      */
101     public DashboardRestrictedBaseController() {
102         // Do not serialize null values
103         objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
104         // Register Jdk8Module() for Stream and Optional types
105         objectMapper.registerModule(new Jdk8Module());
106     }
107
108     /**
109      * Access method for subclasses.
110      * 
111      * @return DbcappProperties object that was autowired by Spring.
112      */
113     protected DashboardProperties getAppProperties() {
114         return appProperties;
115     }
116
117     /**
118      * Gets the requested page number from a query parameter in the
119      * HttpServletRequest. Defaults to 1, which is useful to allow manual testing of
120      * endpoints without supplying those pesky parameters.
121      * 
122      * @param request HttpServletRequest
123      * @return Value of query parameter {@link #PAGE_NUM_QUERY_PARAM}; 1 if not
124      *         found.
125      */
126     protected int getRequestPageNumber(HttpServletRequest request) {
127         int pageNum = 1;
128         String param = request.getParameter(PAGE_NUM_QUERY_PARAM);
129         if (param != null)
130             pageNum = Integer.parseInt(param);
131         return pageNum;
132     }
133
134     /**
135      * Gets the requested page size from a query parameter in the
136      * HttpServletRequest. Defaults to 50, which is useful to allow manual testing
137      * of endpoints without supplying those pesky parameters.
138      * 
139      * @param request HttpServletRequest
140      * @return Value of query parameter {@link #PAGE_SIZE_QUERY_PARAM}; 50 if not
141      *         found.
142      */
143     protected int getRequestPageSize(HttpServletRequest request) {
144         int pageSize = 50;
145         String param = request.getParameter(PAGE_SIZE_QUERY_PARAM);
146         if (param != null)
147             pageSize = Integer.parseInt(param);
148         return pageSize;
149     }
150
151     /**
152      * Gets the items for the specified page from the specified list.
153      * 
154      * @param pageNum  Page number requested by user, indexed from 1
155      * @param pageSize Number of items per page
156      * @param itemList List of items to adjust
157      * @return List of items; empty list if from==to
158      */
159     @SuppressWarnings("rawtypes")
160     protected static List getPageOfList(final int pageNum, final int pageSize, final List itemList) {
161         int firstIndexOnThisPage = pageSize * (pageNum - 1);
162         int firstIndexOnNextPage = pageSize * pageNum;
163         int fromIndex = firstIndexOnThisPage < itemList.size() ? firstIndexOnThisPage : itemList.size();
164         int toIndex = firstIndexOnNextPage < itemList.size() ? firstIndexOnNextPage : itemList.size();
165         return itemList.subList(fromIndex, toIndex);
166     }
167
168     /**
169      * Gets all configured controllers from properties.
170      * 
171      * @return Array of ControllerEndpointRestricted objects
172      * @throws IllegalStateException if a required property is not found
173      */
174     protected ControllerEndpointCredentials[] getControllerEndpoints() {
175         final String[] controllerKeys = DashboardProperties.getCsvListProperty(DashboardProperties.CONTROLLER_KEY_LIST);
176         ControllerEndpointCredentials[] controllers = new ControllerEndpointCredentials[controllerKeys.length];
177         for (int i = 0; i < controllerKeys.length; ++i) {
178             String key = controllerKeys[i];
179             final String name = DashboardProperties.getControllerProperty(key,
180                     DashboardProperties.CONTROLLER_SUBKEY_NAME);
181             final String url = DashboardProperties.getControllerProperty(key,
182                     DashboardProperties.CONTROLLER_SUBKEY_URL);
183             final String inventoryUrl = DashboardProperties.getControllerProperty(key,
184                     DashboardProperties.CONTROLLER_SUBKEY_INVENTORY_URL);
185             final String dhandlerUrl = DashboardProperties.getControllerProperty(key,
186                     DashboardProperties.CONTROLLER_SUBKEY_DHANDLER_URL);
187             final String consulUrl = DashboardProperties.getControllerProperty(key,
188                     DashboardProperties.CONTROLLER_SUBKEY_CONSUL_URL);
189             final String user = DashboardProperties.getControllerProperty(key,
190                     DashboardProperties.CONTROLLER_SUBKEY_USERNAME);
191             final String pass = DashboardProperties.getControllerProperty(key,
192                     DashboardProperties.CONTROLLER_SUBKEY_PASS);
193             final boolean encr = Boolean.parseBoolean(
194                     DashboardProperties.getControllerProperty(key, DashboardProperties.CONTROLLER_SUBKEY_ENCRYPTED));
195             controllers[i] = new ControllerEndpointCredentials(false, name, url, inventoryUrl, dhandlerUrl, consulUrl,
196                     user, pass, encr);
197         }
198         return controllers;
199     }
200
201     /**
202      * Get the list of configured OPS Tools URLs from dashboard properties
203      * 
204      * @return Array of ControllerOpsTools objects
205      * @throws IllegalStateException if a required property is not found
206      */
207     protected List<ControllerOpsTools> getControllerOpsTools() {
208         List<ControllerOpsTools> opsList = new ArrayList<>();
209         final String[] controllerKeys = DashboardProperties.getCsvListProperty(DashboardProperties.CONTROLLER_KEY_LIST);
210         String key = controllerKeys[0];
211         final String cfyId = DashboardProperties.OPS_CLOUDIFY_URL.split("\\.")[1];
212         final String cfyUrl = DashboardProperties.getControllerProperty(key, DashboardProperties.OPS_CLOUDIFY_URL);
213         final String k8Id = DashboardProperties.OPS_K8S_URL.split("\\.")[1];
214         final String k8Url = DashboardProperties.getControllerProperty(key, DashboardProperties.OPS_K8S_URL);
215         final String grfId = DashboardProperties.OPS_GRAFANA_URL.split("\\.")[1];
216         final String grfUrl = DashboardProperties.getControllerProperty(key, DashboardProperties.OPS_GRAFANA_URL);
217         final String cnslId = DashboardProperties.OPS_CONSUL_URL.split("\\.")[1];
218         final String cnslUrl = DashboardProperties.getControllerProperty(key, DashboardProperties.OPS_CONSUL_URL);
219         final String promId = DashboardProperties.OPS_PROMETHEUS_URL.split("\\.")[1];
220         final String promUrl = DashboardProperties.getControllerProperty(key, DashboardProperties.OPS_PROMETHEUS_URL);
221         final String dbclId = DashboardProperties.OPS_DBCL_URL.split("\\.")[1];
222         final String dbclUrl = DashboardProperties.getControllerProperty(key, DashboardProperties.OPS_DBCL_URL);
223         opsList.add(new ControllerOpsTools(cfyId, cfyUrl));
224         opsList.add(new ControllerOpsTools(k8Id, k8Url));
225         opsList.add(new ControllerOpsTools(grfId, grfUrl));
226         opsList.add(new ControllerOpsTools(cnslId, cnslUrl));
227         opsList.add(new ControllerOpsTools(promId, promUrl));
228         opsList.add(new ControllerOpsTools(dbclId, dbclUrl));
229
230         return opsList;
231     }
232
233     /**
234      * Gets the controller endpoint for the specified user ID. Chooses the first one
235      * from properties if the user has not selected one previously.
236      * 
237      * @param userId Database User ID
238      * @return ControllerEndpointCredentials for the specified user
239      */
240     protected ControllerEndpointCredentials getOrSetControllerEndpointSelection(long userId) {
241         // Always need the complete list from properties
242         ControllerEndpointCredentials[] configured = getControllerEndpoints();
243         // See if the database has an entry for this user
244         ControllerEndpoint dbEntry = controllerEndpointService.getControllerEndpointSelection(userId);
245         // If no row found DAO returns an object with null entries.
246         if (dbEntry == null || dbEntry.getName() == null) {
247             // Arbitrarily choose the first one
248             ControllerEndpointCredentials first = configured[0];
249             dbEntry = new ControllerEndpoint(userId, first.getName(), first.getUrl(), first.getInventoryUrl(),
250                     first.getDhandlerUrl());
251             controllerEndpointService.updateControllerEndpointSelection(dbEntry);
252         }
253         // Fetch complete details for the selected item
254         ControllerEndpointCredentials selected = null;
255         for (ControllerEndpointCredentials cec : configured) {
256             if (dbEntry.getUrl().equals(cec.getUrl())) {
257                 selected = cec;
258                 break;
259             }
260         }
261         // Defend against a stale database entry.
262         if (selected == null) {
263             selected = configured[0];
264             dbEntry = new ControllerEndpoint(userId, selected.getName(), selected.getUrl(), selected.getInventoryUrl(),
265                     selected.getDhandlerUrl());
266             controllerEndpointService.updateControllerEndpointSelection(dbEntry);
267         }
268         return selected;
269     }
270
271     protected ControllerEndpointCredentials getOrSetControllerEndpointSelection() {
272         ControllerEndpointCredentials[] configured = getControllerEndpoints();
273         return configured[0];
274     }
275
276     /**
277      * Convenience method that gets the user ID from the session and fetches the
278      * REST client. Factors code out of subclass methods.
279      * 
280      * @param request HttpServletRequest
281      * @return REST client appropriate for the user
282      */
283     protected CloudifyClient getCloudifyRestClient(HttpServletRequest request) throws Exception {
284         User appUser = UserUtils.getUserSession(request);
285         if (appUser == null || appUser.getId() == null)
286             throw new Exception("getCloudifyRestClient: Failed to get application user");
287         return getCloudifyRestClient(appUser.getId());
288     }
289
290     /**
291      * Gets a REST client; either a mock client (returns canned data), or a real
292      * client with appropriate credentials from properties.
293      * 
294      * @return REST client.
295      */
296     protected CloudifyClient getCloudifyRestClient(long userId) throws Exception {
297         CloudifyClient result = null;
298         // Be robust to missing development-only property
299         boolean mock = false;
300         if (DashboardProperties.containsProperty(DashboardProperties.CONTROLLER_MOCK_DATA))
301             mock = DashboardProperties.getBooleanProperty(DashboardProperties.CONTROLLER_MOCK_DATA);
302         if (mock) {
303             result = new CloudifyMockClientImpl();
304         } else {
305             ControllerEndpointCredentials details = getOrSetControllerEndpointSelection(userId);
306             final String clearText = details.getEncryptedPassword() ? details.decryptPassword() : details.getPassword();
307             result = new CloudifyRestClientImpl(details.getUrl(), details.getUsername(), clearText);
308         }
309         return result;
310     }
311
312     /**
313      * Gets a REST client; either a mock client (returns canned data), or a real
314      * client with appropriate credentials from properties.
315      * 
316      * @return REST client.
317      */
318     protected CloudifyClient getCloudifyRestClient() throws Exception {
319         CloudifyClient result = null;
320         // Be robust to missing development-only property
321         boolean mock = false;
322         if (DashboardProperties.containsProperty(DashboardProperties.CONTROLLER_MOCK_DATA))
323             mock = DashboardProperties.getBooleanProperty(DashboardProperties.CONTROLLER_MOCK_DATA);
324         if (mock) {
325             result = new CloudifyMockClientImpl();
326         } else {
327             ControllerEndpointCredentials details = getOrSetControllerEndpointSelection();
328             final String clearText = details.getEncryptedPassword() ? details.decryptPassword() : details.getPassword();
329             result = new CloudifyRestClientImpl(details.getUrl(), details.getUsername(), clearText);
330         }
331         return result;
332     }
333
334     /**
335      * Convenience method that gets the user ID from the session and fetches the
336      * REST client. Factors code out of subclass methods.
337      * 
338      * @param request HttpServletRequest
339      * @return REST client appropriate for the user
340      */
341     protected ConsulClient getConsulRestClient(HttpServletRequest request) throws Exception {
342         User appUser = UserUtils.getUserSession(request);
343         if (appUser == null || appUser.getId() == null)
344             throw new Exception("getControllerRestClient: Failed to get application user");
345         return getConsulRestClient(appUser.getId());
346     }
347
348     /**
349      * Gets a REST client; either a mock client (returns canned data), or a real
350      * client with appropriate credentials from properties.
351      * 
352      * @return REST client.
353      */
354     protected ConsulClient getConsulRestClient(long userId) throws Exception {
355         ConsulClient result = null;
356         // Be robust to missing development-only property
357         boolean mock = false;
358         if (DashboardProperties.containsProperty(DashboardProperties.CONTROLLER_MOCK_DATA))
359             mock = DashboardProperties.getBooleanProperty(DashboardProperties.CONTROLLER_MOCK_DATA);
360         if (mock) {
361             result = new ConsulMockClientImpl();
362         } else {
363             ControllerEndpointCredentials details = getOrSetControllerEndpointSelection();
364             final String clearText = details.getEncryptedPassword() ? details.decryptPassword() : details.getPassword();
365             result = new ConsulRestClientImpl(details.getConsulUrl(), details.getUsername(), clearText);
366         }
367         return result;
368     }
369
370     /**
371      * Gets a REST client; either a mock client (returns canned data), or a real
372      * client with appropriate credentials from properties.
373      * 
374      * @return REST client.
375      */
376     protected ConsulClient getConsulRestClient() throws Exception {
377         ConsulClient result = null;
378         // Be robust to missing development-only property
379         boolean mock = false;
380         if (DashboardProperties.containsProperty(DashboardProperties.CONTROLLER_MOCK_DATA))
381             mock = DashboardProperties.getBooleanProperty(DashboardProperties.CONTROLLER_MOCK_DATA);
382         if (mock) {
383             result = new ConsulMockClientImpl();
384         } else {
385             ControllerEndpointCredentials details = getOrSetControllerEndpointSelection();
386             final String clearText = details.getEncryptedPassword() ? details.decryptPassword() : details.getPassword();
387             result = new ConsulRestClientImpl(details.getConsulUrl(), details.getUsername(), clearText);
388         }
389         return result;
390     }
391
392     /**
393      * Convenience method that gets the user ID from the session and fetches the
394      * Inventory client. Factors code out of subclass methods.
395      * 
396      * @param request HttpServletRequest
397      * @return Inventory client appropriate for the user
398      */
399     protected InventoryClient getInventoryClient(HttpServletRequest request) throws Exception {
400         User appUser = UserUtils.getUserSession(request);
401         if (appUser == null || appUser.getId() == null)
402             throw new Exception("getControllerRestClient: Failed to get application user");
403         return getInventoryClient(appUser.getId());
404     }
405
406     /**
407      * Gets an Inventory client with appropriate credentials from properties.
408      *
409      * @return Inventory Client.
410      */
411     protected InventoryClient getInventoryClient(long userId) throws Exception {
412         InventoryClient result = null;
413         boolean mock = false;
414         if (DashboardProperties.containsProperty(DashboardProperties.CONTROLLER_MOCK_DATA))
415             mock = DashboardProperties.getBooleanProperty(DashboardProperties.CONTROLLER_MOCK_DATA);
416         if (mock) {
417             result = new RestInventoryClientMockImpl();
418         } else {
419             ControllerEndpointCredentials details = getOrSetControllerEndpointSelection(userId);
420             final String clearText = details.getEncryptedPassword() ? details.decryptPassword() : details.getPassword();
421             result = new RestInventoryClientImpl(details.getInventoryUrl(), details.getUsername(), clearText);
422         }
423         return result;
424     }
425
426     protected InventoryClient getInventoryClient() throws Exception {
427         InventoryClient result = null;
428         ControllerEndpointCredentials details = getOrSetControllerEndpointSelection();
429         final String clearText = details.getEncryptedPassword() ? details.decryptPassword() : details.getPassword();
430         result = new RestInventoryClientImpl(details.getInventoryUrl(), details.getUsername(), clearText);
431         return result;
432     }
433
434     /**
435      * Convenience method that gets the user ID from the session and fetches the
436      * Deployment Handler client. Factors code out of subclass methods.
437      *
438      * @param request HttpServletRequest
439      * @return Deployment Handler client appropriate for the user
440      */
441     protected DeploymentHandlerClient getDeploymentHandlerClient(HttpServletRequest request) throws Exception {
442         User appUser = UserUtils.getUserSession(request);
443         if (appUser == null || appUser.getId() == null)
444             throw new Exception("getControllerRestClient: Failed to get application user");
445         return getDeploymentHandlerClient(appUser.getId());
446     }
447
448     /**
449      * Gets a Deployment Handler client with appropriate credentials from
450      * properties.
451      *
452      * @return Deployment Handler Client.
453      */
454     protected DeploymentHandlerClient getDeploymentHandlerClient(long userId) throws Exception {
455         DeploymentHandlerClient result = null;
456         ControllerEndpointCredentials details = getOrSetControllerEndpointSelection(userId);
457         final String clearText = details.getEncryptedPassword() ? details.decryptPassword() : details.getPassword();
458         result = new DeploymentHandlerClientImpl(details.getDhandlerUrl(), details.getUsername(), clearText);
459         return result;
460     }
461
462     protected DeploymentHandlerClient getDeploymentHandlerClient() throws Exception {
463         DeploymentHandlerClient result = null;
464         ControllerEndpointCredentials details = getOrSetControllerEndpointSelection();
465         final String clearText = details.getEncryptedPassword() ? details.decryptPassword() : details.getPassword();
466         result = new DeploymentHandlerClientImpl(details.getDhandlerUrl(), details.getUsername(), clearText);
467         return result;
468     }
469 }