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.ccsdk.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.ccsdk.dashboard.exception.DashboardControllerException;
31 import org.onap.ccsdk.dashboard.rest.ControllerRestClientMockImpl;
32 import org.onap.ccsdk.dashboard.service.ControllerEndpointService;
33 import org.onap.ccsdk.dashboard.domain.ControllerEndpoint;
34 import org.onap.ccsdk.dashboard.rest.IControllerRestClient;
35 import org.onap.ccsdk.dashboard.util.DashboardProperties;
36 import org.onap.ccsdk.dashboard.model.ControllerEndpointCredentials;
37 import org.onap.ccsdk.dashboard.rest.ControllerRestClientImpl;
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;
44 import com.fasterxml.jackson.annotation.JsonInclude;
45 import com.fasterxml.jackson.databind.ObjectMapper;
48 * This base class provides utility methods to child controllers.
50 public class DashboardRestrictedBaseController extends RestrictedBaseController {
53 * Logger that conforms with ECOMP guidelines
55 private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(DashboardRestrictedBaseController.class);
60 protected static final String APP_NAME = "ecd-app";
63 * EELF-approved format
65 protected static final DateFormat logDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
68 * Query parameter for desired page number
70 protected static final String PAGE_NUM_QUERY_PARAM = "pageNum";
73 * Query parameter for desired items per page
75 protected static final String PAGE_SIZE_QUERY_PARAM = "viewPerPage";
78 * For general use in these methods and subclasses
80 protected final ObjectMapper objectMapper = new ObjectMapper();
83 * Application properties - NOT available to constructor.
86 private DashboardProperties appProperties;
89 * For getting selected controller
92 private ControllerEndpointService controllerEndpointService;
95 * Hello Spring, here's your no-arg constructor.
97 public DashboardRestrictedBaseController() {
98 // Do not serialize null values
99 objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
103 * Access method for subclasses.
105 * @return DbcappProperties object that was autowired by Spring.
107 protected DashboardProperties getAppProperties() {
108 return appProperties;
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.
118 * @return Value of query parameter {@link #PAGE_NUM_QUERY_PARAM}; 1 if not
121 protected int getRequestPageNumber(HttpServletRequest request) {
123 String param = request.getParameter(PAGE_NUM_QUERY_PARAM);
125 pageNum = Integer.parseInt(param);
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.
136 * @return Value of query parameter {@link #PAGE_SIZE_QUERY_PARAM}; 50 if
139 protected int getRequestPageSize(HttpServletRequest request) {
141 String param = request.getParameter(PAGE_SIZE_QUERY_PARAM);
143 pageSize = Integer.parseInt(param);
148 * Gets the items for the specified page from the specified list.
151 * Page number requested by user, indexed from 1
153 * Number of items per page
155 * List of items to adjust
156 * @return List of items; empty list if from==to
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);
168 * Gets all configured controllers from properties.
170 * @return Array of ControllerEndpointRestricted objects
171 * @throws IllegalStateException
172 * if a required property is not found
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);
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.
199 * @return ControllerEndpointCredentials for the specified user
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);
213 // Fetch complete details for the selected item
214 ControllerEndpointCredentials selected = null;
215 for (ControllerEndpointCredentials cec : configured) {
216 if (dbEntry.getUrl().equals(cec.getUrl())) {
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);
231 * Convenience method that gets the user ID from the session and fetches the
232 * REST client. Factors code out of subclass methods.
236 * @return REST client appropriate for the user
237 * @throws DashboardControllerException
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());
247 * Gets a REST client; either a mock client (returns canned data), or a real
248 * client with appropriate credentials from properties.
250 * @return REST client.
251 * @throws DashboardControllerException on any failure; e.g., if the password cannot be decrypted.
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);
260 result = new ControllerRestClientMockImpl();
263 ControllerEndpointCredentials details = getOrSetControllerEndpointSelection(userId);
264 final String clearText = details.getEncryptedPassword() ? details.decryptPassword() : details.getPassword();
265 result = new ControllerRestClientImpl(details.getUrl(), details.getUsername(), clearText);
267 catch (Exception ex) {
268 logger.error("getControllerRestClient failed", ex);
269 throw new DashboardControllerException(ex);