1 /*******************************************************************************
2 * =============LICENSE_START=========================================================
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
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.oom.dashboard.controller;
24 import java.text.DateFormat;
25 import java.text.SimpleDateFormat;
26 import java.util.List;
28 import javax.servlet.http.HttpServletRequest;
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;
43 import com.fasterxml.jackson.annotation.JsonInclude;
44 import com.fasterxml.jackson.databind.ObjectMapper;
47 * This base class provides utility methods to child controllers.
49 public class DashboardRestrictedBaseController extends RestrictedBaseController {
52 * Logger that conforms with ECOMP guidelines
54 private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(DashboardRestrictedBaseController.class);
59 protected static final String APP_NAME = "ecd-app";
62 * EELF-approved format
64 protected static final DateFormat logDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
67 * Query parameter for desired page number
69 protected static final String PAGE_NUM_QUERY_PARAM = "pageNum";
72 * Query parameter for desired items per page
74 protected static final String PAGE_SIZE_QUERY_PARAM = "viewPerPage";
77 * For general use in these methods and subclasses
79 protected final ObjectMapper objectMapper = new ObjectMapper();
82 * Application properties - NOT available to constructor.
85 private DashboardProperties appProperties;
88 * For getting selected controller
91 private ControllerEndpointService controllerEndpointService;
94 * Hello Spring, here's your no-arg constructor.
96 public DashboardRestrictedBaseController() {
97 // Do not serialize null values
98 objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
102 * Access method for subclasses.
104 * @return DbcappProperties object that was autowired by Spring.
106 protected DashboardProperties getAppProperties() {
107 return appProperties;
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.
117 * @return Value of query parameter {@link #PAGE_NUM_QUERY_PARAM}; 1 if not
120 protected int getRequestPageNumber(HttpServletRequest request) {
122 String param = request.getParameter(PAGE_NUM_QUERY_PARAM);
124 pageNum = Integer.parseInt(param);
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.
135 * @return Value of query parameter {@link #PAGE_SIZE_QUERY_PARAM}; 50 if
138 protected int getRequestPageSize(HttpServletRequest request) {
140 String param = request.getParameter(PAGE_SIZE_QUERY_PARAM);
142 pageSize = Integer.parseInt(param);
147 * Gets the items for the specified page from the specified list.
150 * Page number requested by user, indexed from 1
152 * Number of items per page
154 * List of items to adjust
155 * @return List of items; empty list if from==to
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);
167 * Gets all configured controllers from properties.
169 * @return Array of ControllerEndpointRestricted objects
170 * @throws IllegalStateException
171 * if a required property is not found
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);
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.
198 * @return ControllerEndpointCredentials for the specified user
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);
212 // Fetch complete details for the selected item
213 ControllerEndpointCredentials selected = null;
214 for (ControllerEndpointCredentials cec : configured) {
215 if (dbEntry.getUrl().equals(cec.getUrl())) {
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);
230 * Convenience method that gets the user ID from the session and fetches the
231 * REST client. Factors code out of subclass methods.
235 * @return REST client appropriate for the user
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());
245 * Gets a REST client; either a mock client (returns canned data), or a real
246 * client with appropriate credentials from properties.
248 * @return REST client.
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);
257 result = new ControllerRestClientMockImpl();
259 ControllerEndpointCredentials details = getOrSetControllerEndpointSelection(userId);
260 final String clearText = details.getEncryptedPassword() ? details.decryptPassword() : details.getPassword();
261 result = new ControllerRestClientImpl(details.getUrl(), details.getUsername(), clearText);