c92160867ea65d4ffa8d6abe3cdeb5c548ec0b5e
[ccsdk/dashboard.git] /
1 /*******************************************************************************
2  * =============LICENSE_START=========================================================
3  *
4  * =================================================================================
5  *  Copyright (c) 2017 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.oom.dashboard.controller;
23
24 import java.text.DateFormat;
25 import java.text.SimpleDateFormat;
26 import java.util.List;
27
28 import javax.servlet.http.HttpServletRequest;
29
30 import org.onap.oom.dashboard.domain.ControllerEndpoint;
31 import org.onap.oom.dashboard.model.ControllerEndpointCredentials;
32 import org.onap.oom.dashboard.rest.ControllerRestClientImpl;
33 import org.onap.oom.dashboard.rest.ControllerRestClientMockImpl;
34 import org.onap.oom.dashboard.rest.IControllerRestClient;
35 import org.onap.oom.dashboard.service.ControllerEndpointService;
36 import org.onap.oom.dashboard.util.DashboardProperties;
37 import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
38 import org.openecomp.portalsdk.core.domain.User;
39 import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
40 import org.openecomp.portalsdk.core.web.support.UserUtils;
41 import org.springframework.beans.factory.annotation.Autowired;
42
43 import com.fasterxml.jackson.annotation.JsonInclude;
44 import com.fasterxml.jackson.databind.ObjectMapper;
45
46 /**
47  * This base class provides utility methods to child controllers.
48  */
49 public class DashboardRestrictedBaseController extends RestrictedBaseController {
50
51         /**
52          * Logger that conforms with ECOMP guidelines
53          */
54         private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(DashboardRestrictedBaseController.class);
55
56         /**
57          * Application name
58          */
59         protected static final String APP_NAME = "ecd-app";
60
61         /**
62          * EELF-approved format
63          */
64         protected static final DateFormat logDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
65
66         /**
67          * Query parameter for desired page number
68          */
69         protected static final String PAGE_NUM_QUERY_PARAM = "pageNum";
70
71         /**
72          * Query parameter for desired items per page
73          */
74         protected static final String PAGE_SIZE_QUERY_PARAM = "viewPerPage";
75
76         /**
77          * For general use in these methods and subclasses
78          */
79         protected final ObjectMapper objectMapper = new ObjectMapper();
80
81         /**
82          * Application properties - NOT available to constructor.
83          */
84         @Autowired
85         private DashboardProperties appProperties;
86
87         /**
88          * For getting selected controller
89          */
90         @Autowired
91         private ControllerEndpointService controllerEndpointService;
92
93         /**
94          * Hello Spring, here's your no-arg constructor.
95          */
96         public DashboardRestrictedBaseController() {
97                 // Do not serialize null values
98                 objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
99         }
100
101         /**
102          * Access method for subclasses.
103          * 
104          * @return DbcappProperties object that was autowired by Spring.
105          */
106         protected DashboardProperties getAppProperties() {
107                 return appProperties;
108         }
109
110         /**
111          * Gets the requested page number from a query parameter in the
112          * HttpServletRequest. Defaults to 1, which is useful to allow manual
113          * testing of endpoints without supplying those pesky parameters.
114          * 
115          * @param request
116          *            HttpServletRequest
117          * @return Value of query parameter {@link #PAGE_NUM_QUERY_PARAM}; 1 if not
118          *         found.
119          */
120         protected int getRequestPageNumber(HttpServletRequest request) {
121                 int pageNum = 1;
122                 String param = request.getParameter(PAGE_NUM_QUERY_PARAM);
123                 if (param != null)
124                         pageNum = Integer.parseInt(param);
125                 return pageNum;
126         }
127
128         /**
129          * Gets the requested page size from a query parameter in the
130          * HttpServletRequest. Defaults to 50, which is useful to allow manual
131          * testing of endpoints without supplying those pesky parameters.
132          * 
133          * @param request
134          *            HttpServletRequest
135          * @return Value of query parameter {@link #PAGE_SIZE_QUERY_PARAM}; 50 if
136          *         not found.
137          */
138         protected int getRequestPageSize(HttpServletRequest request) {
139                 int pageSize = 50;
140                 String param = request.getParameter(PAGE_SIZE_QUERY_PARAM);
141                 if (param != null)
142                         pageSize = Integer.parseInt(param);
143                 return pageSize;
144         }
145
146         /**
147          * Gets the items for the specified page from the specified list.
148          * 
149          * @param pageNum
150          *            Page number requested by user, indexed from 1
151          * @param pageSize
152          *            Number of items per page
153          * @param itemList
154          *            List of items to adjust
155          * @return List of items; empty list if from==to
156          */
157         @SuppressWarnings("rawtypes")
158         protected static List getPageOfList(final int pageNum, final int pageSize, final List itemList) {
159                 int firstIndexOnThisPage = pageSize * (pageNum - 1);
160                 int firstIndexOnNextPage = pageSize * pageNum;
161                 int fromIndex = firstIndexOnThisPage < itemList.size() ? firstIndexOnThisPage : itemList.size();
162                 int toIndex = firstIndexOnNextPage < itemList.size() ? firstIndexOnNextPage : itemList.size();
163                 return itemList.subList(fromIndex, toIndex);
164         }
165
166         /**
167          * Gets all configured controllers from properties.
168          * 
169          * @return Array of ControllerEndpointRestricted objects
170          * @throws IllegalStateException
171          *             if a required property is not found
172          */
173         protected ControllerEndpointCredentials[] getControllerEndpoints() {
174                 final String[] controllerKeys = appProperties.getCsvListProperty(DashboardProperties.CONTROLLER_KEY_LIST);
175                 ControllerEndpointCredentials[] controllers = new ControllerEndpointCredentials[controllerKeys.length];
176                 for (int i = 0; i < controllerKeys.length; ++i) {
177                         String key = controllerKeys[i];
178                         final String name = appProperties.getControllerProperty(key, DashboardProperties.CONTROLLER_SUBKEY_NAME);
179                         final String url = appProperties.getControllerProperty(key, DashboardProperties.CONTROLLER_SUBKEY_URL);
180                         final String user = appProperties.getControllerProperty(key,
181                                         DashboardProperties.CONTROLLER_SUBKEY_USERNAME);
182                         final String pass = appProperties.getControllerProperty(key,
183                                         DashboardProperties.CONTROLLER_SUBKEY_PASSWORD);
184                         final boolean encr = new Boolean(
185                                         appProperties.getControllerProperty(key, DashboardProperties.CONTROLLER_SUBKEY_ENCRYPTED));
186                         logger.debug(EELFLoggerDelegate.debugLogger, "getConfiguredControllers: key {} yields url {}", key, url);
187                         controllers[i] = new ControllerEndpointCredentials(false, name, url, user, pass, encr);
188                 }
189                 return controllers;
190         }
191
192         /**
193          * Gets the controller endpoint for the specified user ID. Chooses the first
194          * one from properties if the user has not selected one previously.
195          * 
196          * @param userId
197          *            Database User ID
198          * @return ControllerEndpointCredentials for the specified user
199          */
200         protected ControllerEndpointCredentials getOrSetControllerEndpointSelection(long userId) {
201                 // Always need the complete list from properties
202                 ControllerEndpointCredentials[] configured = getControllerEndpoints();
203                 // See if the database has an entry for this user
204                 ControllerEndpoint dbEntry = controllerEndpointService.getControllerEndpointSelection(userId);
205                 // If no row found DAO returns an object with null entries.
206                 if (dbEntry == null || dbEntry.getName() == null) {
207                         // Arbitrarily choose the first one
208                         ControllerEndpointCredentials first = configured[0];
209                         dbEntry = new ControllerEndpoint(userId, first.getName(), first.getUrl());
210                         controllerEndpointService.updateControllerEndpointSelection(dbEntry);
211                 }
212                 // Fetch complete details for the selected item
213                 ControllerEndpointCredentials selected = null;
214                 for (ControllerEndpointCredentials cec : configured) {
215                         if (dbEntry.getUrl().equals(cec.getUrl())) {
216                                 selected = cec;
217                                 break;
218                         }
219                 }
220                 // Defend against a stale database entry.
221                 if (selected == null) {
222                         selected = configured[0];
223                         dbEntry = new ControllerEndpoint(userId, selected.getName(), selected.getUrl());
224                         controllerEndpointService.updateControllerEndpointSelection(dbEntry);
225                 }
226                 return selected;
227         }
228
229         /**
230          * Convenience method that gets the user ID from the session and fetches the
231          * REST client. Factors code out of subclass methods.
232          * 
233          * @param request
234          *            HttpServletRequest
235          * @return REST client appropriate for the user
236          */
237         protected IControllerRestClient getControllerRestClient(HttpServletRequest request) throws Exception {
238                 User appUser = UserUtils.getUserSession(request);
239                 if (appUser == null || appUser.getLoginId() == null || appUser.getLoginId().length() == 0)
240                         throw new Exception("getControllerRestClient: Failed to get application user");
241                 return getControllerRestClient(appUser.getId());
242         }
243
244         /**
245          * Gets a REST client; either a mock client (returns canned data), or a real
246          * client with appropriate credentials from properties.
247          * 
248          * @return REST client.
249          */
250         protected IControllerRestClient getControllerRestClient(long userId) throws Exception {
251                 IControllerRestClient result = null;
252                 // Be robust to missing development-only property
253                 boolean mock = false;
254                 if (appProperties.containsProperty(DashboardProperties.CONTROLLER_MOCK_DATA))
255                         mock = appProperties.getBooleanProperty(DashboardProperties.CONTROLLER_MOCK_DATA);
256                 if (mock) {
257                         result = new ControllerRestClientMockImpl();
258                 } else {
259                         ControllerEndpointCredentials details = getOrSetControllerEndpointSelection(userId);
260                         final String clearText = details.getEncryptedPassword() ? details.decryptPassword() : details.getPassword();
261                         result = new ControllerRestClientImpl(details.getUrl(), details.getUsername(), clearText);
262                 }
263                 return result;
264         }
265
266 }