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