1 /*******************************************************************************
2 * =============LICENSE_START=========================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
20 * ECOMP is a trademark and service mark of AT&T Intellectual Property.
21 *******************************************************************************/
22 package org.onap.ccsdk.dashboard.controller;
24 import java.text.DateFormat;
25 import java.text.SimpleDateFormat;
26 import java.util.ArrayList;
27 import java.util.List;
29 import javax.servlet.http.HttpServletRequest;
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;
52 import com.fasterxml.jackson.annotation.JsonInclude;
53 import com.fasterxml.jackson.databind.ObjectMapper;
54 import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
57 * This base class provides utility methods to child controllers.
59 public class DashboardRestrictedBaseController extends RestrictedBaseController {
64 protected static final String APP_NAME = "ecd-app";
67 * EELF-approved format
69 protected static final DateFormat logDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
72 * Query parameter for desired page number
74 protected static final String PAGE_NUM_QUERY_PARAM = "pageNum";
77 * Query parameter for desired items per page
79 protected static final String PAGE_SIZE_QUERY_PARAM = "viewPerPage";
82 * For general use in these methods and subclasses
84 protected final ObjectMapper objectMapper = new ObjectMapper();
87 * Application properties - NOT available to constructor.
90 protected DashboardProperties appProperties;
93 * For getting selected controller
96 private ControllerEndpointService controllerEndpointService;
99 * Hello Spring, here's your no-arg constructor.
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());
109 * Access method for subclasses.
111 * @return DbcappProperties object that was autowired by Spring.
113 protected DashboardProperties getAppProperties() {
114 return appProperties;
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.
122 * @param request HttpServletRequest
123 * @return Value of query parameter {@link #PAGE_NUM_QUERY_PARAM}; 1 if not
126 protected int getRequestPageNumber(HttpServletRequest request) {
128 String param = request.getParameter(PAGE_NUM_QUERY_PARAM);
130 pageNum = Integer.parseInt(param);
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.
139 * @param request HttpServletRequest
140 * @return Value of query parameter {@link #PAGE_SIZE_QUERY_PARAM}; 50 if not
143 protected int getRequestPageSize(HttpServletRequest request) {
145 String param = request.getParameter(PAGE_SIZE_QUERY_PARAM);
147 pageSize = Integer.parseInt(param);
152 * Gets the items for the specified page from the specified list.
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
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);
169 * Gets all configured controllers from properties.
171 * @return Array of ControllerEndpointRestricted objects
172 * @throws IllegalStateException if a required property is not found
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,
202 * Get the list of configured OPS Tools URLs from dashboard properties
204 * @return Array of ControllerOpsTools objects
205 * @throws IllegalStateException if a required property is not found
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));
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.
237 * @param userId Database User ID
238 * @return ControllerEndpointCredentials for the specified user
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);
253 // Fetch complete details for the selected item
254 ControllerEndpointCredentials selected = null;
255 for (ControllerEndpointCredentials cec : configured) {
256 if (dbEntry.getUrl().equals(cec.getUrl())) {
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);
271 protected ControllerEndpointCredentials getOrSetControllerEndpointSelection() {
272 ControllerEndpointCredentials[] configured = getControllerEndpoints();
273 return configured[0];
277 * Convenience method that gets the user ID from the session and fetches the
278 * REST client. Factors code out of subclass methods.
280 * @param request HttpServletRequest
281 * @return REST client appropriate for the user
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());
291 * Gets a REST client; either a mock client (returns canned data), or a real
292 * client with appropriate credentials from properties.
294 * @return REST client.
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);
303 result = new CloudifyMockClientImpl();
305 ControllerEndpointCredentials details = getOrSetControllerEndpointSelection(userId);
306 final String clearText = details.getEncryptedPassword() ? details.decryptPassword() : details.getPassword();
307 result = new CloudifyRestClientImpl(details.getUrl(), details.getUsername(), clearText);
313 * Gets a REST client; either a mock client (returns canned data), or a real
314 * client with appropriate credentials from properties.
316 * @return REST client.
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);
325 result = new CloudifyMockClientImpl();
327 ControllerEndpointCredentials details = getOrSetControllerEndpointSelection();
328 final String clearText = details.getEncryptedPassword() ? details.decryptPassword() : details.getPassword();
329 result = new CloudifyRestClientImpl(details.getUrl(), details.getUsername(), clearText);
335 * Convenience method that gets the user ID from the session and fetches the
336 * REST client. Factors code out of subclass methods.
338 * @param request HttpServletRequest
339 * @return REST client appropriate for the user
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());
349 * Gets a REST client; either a mock client (returns canned data), or a real
350 * client with appropriate credentials from properties.
352 * @return REST client.
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);
361 result = new ConsulMockClientImpl();
363 ControllerEndpointCredentials details = getOrSetControllerEndpointSelection();
364 final String clearText = details.getEncryptedPassword() ? details.decryptPassword() : details.getPassword();
365 result = new ConsulRestClientImpl(details.getConsulUrl(), details.getUsername(), clearText);
371 * Gets a REST client; either a mock client (returns canned data), or a real
372 * client with appropriate credentials from properties.
374 * @return REST client.
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);
383 result = new ConsulMockClientImpl();
385 ControllerEndpointCredentials details = getOrSetControllerEndpointSelection();
386 final String clearText = details.getEncryptedPassword() ? details.decryptPassword() : details.getPassword();
387 result = new ConsulRestClientImpl(details.getConsulUrl(), details.getUsername(), clearText);
393 * Convenience method that gets the user ID from the session and fetches the
394 * Inventory client. Factors code out of subclass methods.
396 * @param request HttpServletRequest
397 * @return Inventory client appropriate for the user
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());
407 * Gets an Inventory client with appropriate credentials from properties.
409 * @return Inventory Client.
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);
417 result = new RestInventoryClientMockImpl();
419 ControllerEndpointCredentials details = getOrSetControllerEndpointSelection(userId);
420 final String clearText = details.getEncryptedPassword() ? details.decryptPassword() : details.getPassword();
421 result = new RestInventoryClientImpl(details.getInventoryUrl(), details.getUsername(), clearText);
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);
435 * Convenience method that gets the user ID from the session and fetches the
436 * Deployment Handler client. Factors code out of subclass methods.
438 * @param request HttpServletRequest
439 * @return Deployment Handler client appropriate for the user
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());
449 * Gets a Deployment Handler client with appropriate credentials from
452 * @return Deployment Handler Client.
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);
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);