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