summaryrefslogtreecommitdiffstats
path: root/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller
diff options
context:
space:
mode:
Diffstat (limited to 'ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller')
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/AppCatalogController.java44
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/AppContactUsController.java24
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/AppsController.java112
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/AppsControllerExternalRequest.java748
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/AuditLogController.java212
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/BEPropertyReaderController.java92
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/BasicAuthAccountController.java115
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/BasicAuthenticationController.java56
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/ConsulClientController.java185
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/DashboardController.java770
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/ExternalAppsRestfulController.java412
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/FunctionalMenuController.java1217
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/HealthCheckController.java60
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/MicroserviceController.java280
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/MicroserviceProxyController.java206
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/PortalAdminController.java409
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/RoleManageController.java332
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/RolesApprovalSystemController.java199
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/SharedContextRestController.java35
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/TicketEventController.java363
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/UserController.java104
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/UserNotificationController.java433
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/UserRecommendationController.java87
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/UserRolesController.java296
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/WebAnalyticsExtAppController.java398
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/WidgetsCatalogController.java768
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/WidgetsCatalogMarkupController.java169
27 files changed, 4465 insertions, 3661 deletions
diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/AppCatalogController.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/AppCatalogController.java
index a799f496..5260a47d 100644
--- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/AppCatalogController.java
+++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/AppCatalogController.java
@@ -25,18 +25,10 @@ import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.EnableAspectJAutoProxy;
-import org.springframework.web.bind.annotation.RequestBody;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestMethod;
-import org.springframework.web.bind.annotation.RestController;
-
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-
import org.openecomp.portalapp.controller.EPRestrictedBaseController;
import org.openecomp.portalapp.portal.domain.EPApp;
import org.openecomp.portalapp.portal.domain.EPUser;
+import org.openecomp.portalapp.portal.ecomp.model.AppCatalogItem;
import org.openecomp.portalapp.portal.logging.aop.EPAuditLog;
import org.openecomp.portalapp.portal.service.AdminRolesService;
import org.openecomp.portalapp.portal.service.EPAppService;
@@ -44,28 +36,40 @@ import org.openecomp.portalapp.portal.service.PersUserAppService;
import org.openecomp.portalapp.portal.transport.AppCatalogPersonalization;
import org.openecomp.portalapp.portal.transport.FieldsValidator;
import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
-import org.openecomp.portalapp.portal.ecomp.model.AppCatalogItem;
import org.openecomp.portalapp.util.EPUserUtils;
+import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.EnableAspectJAutoProxy;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.RestController;
@RestController
@org.springframework.context.annotation.Configuration
@EnableAspectJAutoProxy
@EPAuditLog
public class AppCatalogController extends EPRestrictedBaseController {
- EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AppCatalogController.class);
+
+ private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AppCatalogController.class);
@Autowired
- AdminRolesService adminRolesService;
+ private AdminRolesService adminRolesService;
@Autowired
- EPAppService appService;
+ private EPAppService appService;
@Autowired
- PersUserAppService persUserAppService;
+ private PersUserAppService persUserAppService;
/**
* RESTful service method to fetch all enabled applications, with details
* about which are accessible to the current user, selected by the current
* user.
*
+ * @param request
+ * HttpServletRequest
+ * @param response
+ * HttpServletResponse
+ * @throws IOException If sendError fails
* @return List of items suitable for display
*/
@RequestMapping(value = { "/portalApi/appCatalog" }, method = RequestMethod.GET, produces = "application/json")
@@ -81,10 +85,10 @@ public class AppCatalogController extends EPRestrictedBaseController {
appCatalog = appService.getAdminAppCatalog(user);
else
appCatalog = appService.getUserAppCatalog(user);
- EcompPortalUtils.logAndSerializeObject(logger,"/portalApi/getAppCatalog", "GET result =", appCatalog);
+ EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/getAppCatalog", "GET result =", appCatalog);
}
} catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "Failed in getAppCatalog", e);
+ logger.error(EELFLoggerDelegate.errorLogger, "getAppCatalog failed", e);
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
}
return appCatalog;
@@ -95,11 +99,13 @@ public class AppCatalogController extends EPRestrictedBaseController {
* catalog.
*
* @param request
- * @param selectRequest
+ * HttpServletRequest
+ * @param persRequest
* JSON with data including application ID
* @param response
+ * HttpServletResponse
* @return FieldsValidator
- * @throws IOException
+ * @throws IOException If sendError fails
*/
@RequestMapping(value = { "/portalApi/appCatalog" }, method = RequestMethod.PUT, produces = "application/json")
public FieldsValidator putAppCatalogSelection(HttpServletRequest request,
@@ -114,7 +120,7 @@ public class AppCatalogController extends EPRestrictedBaseController {
persUserAppService.setPersUserAppValue(user, app, persRequest.getSelect(), persRequest.getPending());
}
} catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "Failed in putAppCatalogSelection", e);
+ logger.error(EELFLoggerDelegate.errorLogger, "putAppCatalogSelection failed", e);
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
}
result.httpStatusCode = new Long(HttpServletResponse.SC_OK);
diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/AppContactUsController.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/AppContactUsController.java
index 9b476e05..7e781049 100644
--- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/AppContactUsController.java
+++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/AppContactUsController.java
@@ -63,8 +63,8 @@ public class AppContactUsController extends EPRestrictedBaseController {
* Answers a JSON object with three items from the system.properties file:
* user self-help ticket URL, email for feedback, and Portal info link.
*
- * @param request
- * @return
+ * @param request HttpServletRequest
+ * @return PortalRestResponse
*/
@RequestMapping(value = "/feedback", method = RequestMethod.GET, produces = "application/json")
public PortalRestResponse<String> getPortalDetails(HttpServletRequest request) {
@@ -91,8 +91,8 @@ public class AppContactUsController extends EPRestrictedBaseController {
* Answers the contents of the contact-us table, extended with the
* application name.
*
- * @param request
- * @return
+ * @param request HttpServletRequest
+ * @return PortalRestResponse<List<AppContactUsItem>>
*/
@RequestMapping(value = "/list", method = RequestMethod.GET, produces = "application/json")
public PortalRestResponse<List<AppContactUsItem>> getAppContactUsList(HttpServletRequest request) {
@@ -113,8 +113,8 @@ public class AppContactUsController extends EPRestrictedBaseController {
* Answers a list of objects, one per application, extended with available
* data on how to contact that app's organization (possibly none).
*
- * @param request
- * @return
+ * @param request HttpServletRequest
+ * @return PortalRestResponse<List<AppContactUsItem>>
*/
@RequestMapping(value = "/allapps", method = RequestMethod.GET, produces = "application/json")
public PortalRestResponse<List<AppContactUsItem>> getAppsAndContacts(HttpServletRequest request) {
@@ -145,8 +145,8 @@ public class AppContactUsController extends EPRestrictedBaseController {
* Answers a list of objects with category-application-function details. Not
* all applications participate in the functional menu.
*
- * @param request
- * @return
+ * @param request HttpServletRequest
+ * @return PortalRestResponse<List<AppCategoryFunctionsItem>>
*/
@RequestMapping(value = "/functions", method = RequestMethod.GET, produces = "application/json")
public PortalRestResponse<List<AppCategoryFunctionsItem>> getAppCategoryFunctions(HttpServletRequest request) {
@@ -171,8 +171,8 @@ public class AppContactUsController extends EPRestrictedBaseController {
/**
* Accepts a new application's contact us details.
*
- * @param contactUs
- * @return
+ * @param contactUs AppContactUsItem
+ * @return PortalRestResponse<String>
*/
@RequestMapping(value = "/save", method = RequestMethod.POST, produces = "application/json")
public PortalRestResponse<String> save(@RequestBody AppContactUsItem contactUs) {
@@ -206,8 +206,8 @@ public class AppContactUsController extends EPRestrictedBaseController {
* Deletes the specified application's contact-us details entry from the
* table.
*
- * @param id
- * @return
+ * @param id app ID
+ * @return PortalRestResponse<String>
*/
@RequestMapping(value = "/delete/{appid}", method = RequestMethod.POST, produces = "application/json")
public PortalRestResponse<String> delete(@PathVariable("appid") Long id) {
diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/AppsController.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/AppsController.java
index 7a05d676..2c1da820 100644
--- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/AppsController.java
+++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/AppsController.java
@@ -80,7 +80,11 @@ public class AppsController extends EPRestrictedBaseController {
* RESTful service method to fetch all Applications available to current
* user
*
- * @return
+ * @param request
+ * HttpServletRequest
+ * @param response
+ * HttpServletResponse
+ * @return List<EcompApp>
*/
@RequestMapping(value = { "/portalApi/userApps" }, method = RequestMethod.GET, produces = "application/json")
public List<EcompApp> getUserApps(HttpServletRequest request, HttpServletResponse response) {
@@ -105,7 +109,13 @@ public class AppsController extends EPRestrictedBaseController {
* RESTful service method to fetch all applications accessible to the
* current user, with personalizations.
*
- * @return
+ * @param request
+ * HttpServletRequest
+ * @param response
+ * HttpServletResponse
+ * @return List<EcompApp>
+ * @throws IOException
+ * if sendError fails
*/
@RequestMapping(value = { "/portalApi/persUserApps" }, method = RequestMethod.GET, produces = "application/json")
public List<EcompApp> getPersUserApps(HttpServletRequest request, HttpServletResponse response) throws IOException {
@@ -134,7 +144,11 @@ public class AppsController extends EPRestrictedBaseController {
* RESTful service method to fetch applications for which the current user
* is an Administrator
*
- * @return
+ * @param request
+ * HttpServletRequest
+ * @param response
+ * HttpServletResponse
+ * @return List<AppIdAndNameTransportModel>
*/
@RequestMapping(value = { "/portalApi/adminApps" }, method = RequestMethod.GET, produces = "application/json")
public List<AppIdAndNameTransportModel> getAdminApps(HttpServletRequest request, HttpServletResponse response) {
@@ -159,7 +173,11 @@ public class AppsController extends EPRestrictedBaseController {
* RESTful service method to fetch Applications for user who is super admin
* and/or app admin.
*
- * @return
+ * @param request
+ * HttpServletRequest
+ * @param response
+ * HttpServletResponse
+ * @return List<AppIdAndNameTransportModel>
*/
@RequestMapping(value = {
"/portalApi/appsForSuperAdminAndAccountAdmin" }, method = RequestMethod.GET, produces = "application/json")
@@ -186,6 +204,10 @@ public class AppsController extends EPRestrictedBaseController {
/**
* RESTful service method to fetch left menu items from the user's session.
*
+ * @param request
+ * HttpServletRequest
+ * @param response
+ * HttpServletResponse
* @return JSON with left menu
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
@@ -254,18 +276,21 @@ public class AppsController extends EPRestrictedBaseController {
return ecompApps;
}
- /*
- * This method sends the user apps manual sort preference Data to service
- *
- * @request: HTTP servlet request
+ /**
+ * Sets the user apps manual sort preference
*
- * @response: HTTP servlet response
+ * @param request
+ * HTTP servlet request
+ * @param response
+ * HTTP servlet response
+ * @param epAppsManualPref
+ * sort pref
+ * @return FieldsValidator
*/
@RequestMapping(value = {
"/portalApi/saveUserAppsSortingManual" }, method = RequestMethod.PUT, produces = "application/json")
public FieldsValidator putUserAppsSortingManual(HttpServletRequest request,
- @RequestBody List<EPAppsManualPreference> epAppsManualPref, HttpServletResponse response)
- throws IOException {
+ @RequestBody List<EPAppsManualPreference> epAppsManualPref, HttpServletResponse response) {
FieldsValidator fieldsValidator = null;
try {
EPUser user = EPUserUtils.getUserSession(request);
@@ -316,13 +341,16 @@ public class AppsController extends EPRestrictedBaseController {
return fieldsValidator;
}
- /*
- * This method is being called to delete the user app manual sort preference
- * record
- *
- * @request: HTTP servlet request
+ /**
+ * Deletes the user app manual sort preference record
*
- * @response: HTTP servlet response
+ * @param request
+ * HTTP servlet request
+ * @param response
+ * HTTP servlet response
+ * @param delManualAppData
+ * data to delete
+ * @return FieldsValidator
*/
@RequestMapping(value = {
"/portalApi/UpdateUserAppsSortManual" }, method = RequestMethod.PUT, produces = "application/json")
@@ -389,7 +417,11 @@ public class AppsController extends EPRestrictedBaseController {
* Administrator user. Attention: Users which have Super Administrator roles
* only are not included!
*
- * @return
+ * @param request
+ * HTTP servlet request
+ * @param response
+ * HTTP servlet response
+ * @return List<AdminUserApplications>
*/
@RequestMapping(value = { "/portalApi/accountAdmins" }, method = RequestMethod.GET, produces = "application/json")
public List<AdminUserApplications> getAppsAdministrators(HttpServletRequest request, HttpServletResponse response) {
@@ -432,10 +464,11 @@ public class AppsController extends EPRestrictedBaseController {
* regardless of enabled status.
*
* @param request
+ * HTTP servlet request
* @param response
+ * HTTP servlet response
* @return List of applications
*/
- // This API returns
@RequestMapping(value = {
"/portalApi/allAvailableApps" }, method = RequestMethod.GET, produces = "application/json")
public List<AppsResponse> getAllApps(HttpServletRequest request, HttpServletResponse response) {
@@ -458,8 +491,10 @@ public class AppsController extends EPRestrictedBaseController {
/**
*
* @param request
+ * HTTP servlet request
* @param response
- * @return
+ * HTTP servlet response
+ * @return List of applications
*/
@RequestMapping(value = { "/portalApi/appsFullList" }, method = RequestMethod.GET, produces = "application/json")
public List<EcompApp> getAppsFullList(HttpServletRequest request, HttpServletResponse response) {
@@ -477,8 +512,10 @@ public class AppsController extends EPRestrictedBaseController {
/**
*
* @param request
+ * HTTP servlet request
* @param response
- * @return
+ * HTTP servlet response
+ * @return UserRoles
*/
@RequestMapping(value = { "/portalApi/userProfile" }, method = RequestMethod.GET, produces = "application/json")
public UserRoles getUserProfile(HttpServletRequest request, HttpServletResponse response) {
@@ -502,8 +539,10 @@ public class AppsController extends EPRestrictedBaseController {
/**
*
* @param request
+ * HTTP servlet request
* @param appId
- * @return
+ * application ID
+ * @return List<LocalRole>
*/
@RequestMapping(value = { "/portalApi/appRoles/{appId}" }, method = {
RequestMethod.GET }, produces = "application/json")
@@ -522,8 +561,10 @@ public class AppsController extends EPRestrictedBaseController {
/**
*
* @param request
+ * HTTP servlet request
* @param response
- * @return
+ * HTTP servlet response
+ * @return List<OnboardingApp>
*/
@RequestMapping(value = { "/portalApi/onboardingApps" }, method = RequestMethod.GET, produces = "application/json")
public List<OnboardingApp> getOnboardingApps(HttpServletRequest request, HttpServletResponse response) {
@@ -547,9 +588,12 @@ public class AppsController extends EPRestrictedBaseController {
/**
*
* @param request
- * @param modifiedOnboardingApp
+ * HTTP servlet request
* @param response
- * @return
+ * HTTP servlet response
+ * @param modifiedOnboardingApp
+ * app to update
+ * @return FieldsValidator
*/
@RequestMapping(value = { "/portalApi/onboardingApps" }, method = RequestMethod.PUT, produces = "application/json")
public FieldsValidator putOnboardingApp(HttpServletRequest request,
@@ -576,9 +620,12 @@ public class AppsController extends EPRestrictedBaseController {
/**
*
* @param request
- * @param newOnboardingApp
+ * HTTP servlet request
* @param response
- * @return
+ * HTTP servlet response
+ * @param newOnboardingApp
+ * app to add
+ * @return FieldsValidator
*/
@RequestMapping(value = { "/portalApi/onboardingApps" }, method = RequestMethod.POST, produces = "application/json")
public FieldsValidator postOnboardingApp(HttpServletRequest request, @RequestBody OnboardingApp newOnboardingApp,
@@ -606,9 +653,12 @@ public class AppsController extends EPRestrictedBaseController {
* REST endpoint to process a request to delete an on-boarded application.
*
* @param request
- * @param appId
+ * HTTP servlet request
* @param response
- * @return
+ * HTTP servlet response
+ * @param appId
+ * ID of app to delete
+ * @return FieldsValidator
*/
@RequestMapping(value = { "/portalApi/onboardingApps/{appId}" }, method = {
RequestMethod.DELETE }, produces = "application/json")
@@ -637,7 +687,9 @@ public class AppsController extends EPRestrictedBaseController {
* Gets the application thumbnail image; sets status 404 if none exists.
*
* @param request
- * HttpServletRequest
+ * HTTP servlet request
+ * @param response
+ * HTTP servlet response
* @param appId
* Application ID
* @return Bytes with the app thumbnail image; null if not available.
diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/AppsControllerExternalRequest.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/AppsControllerExternalRequest.java
index fa49d5b2..774eb3ee 100644
--- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/AppsControllerExternalRequest.java
+++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/AppsControllerExternalRequest.java
@@ -1,374 +1,374 @@
-/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.controller;
-
-import java.util.List;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.openecomp.portalapp.portal.domain.EPApp;
-import org.openecomp.portalapp.portal.domain.EPUser;
-import org.openecomp.portalapp.portal.ecomp.model.PortalRestResponse;
-import org.openecomp.portalapp.portal.ecomp.model.PortalRestStatusEnum;
-import org.openecomp.portalapp.portal.logging.aop.EPAuditLog;
-import org.openecomp.portalapp.portal.service.AdminRolesService;
-import org.openecomp.portalapp.portal.service.EPAppService;
-import org.openecomp.portalapp.portal.service.PortalAdminService;
-import org.openecomp.portalapp.portal.service.UserService;
-import org.openecomp.portalapp.portal.transport.FieldsValidator;
-import org.openecomp.portalapp.portal.transport.OnboardingApp;
-import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
-import org.openecomp.portalapp.portal.utils.PortalConstants;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.context.annotation.EnableAspectJAutoProxy;
-import org.springframework.web.bind.annotation.PathVariable;
-import org.springframework.web.bind.annotation.RequestBody;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestMethod;
-import org.springframework.web.bind.annotation.ResponseBody;
-import org.springframework.web.bind.annotation.RestController;
-
-import io.swagger.annotations.ApiOperation;
-
-/**
- * Processes requests from external systems (i.e., not the front-end web UI).
- * First use case is ECOMP Controller, which has to create an admin and onboard
- * itself upon launch of a fresh Portal.
- *
- * Listens on the "auxapi" path prefix. Provides alternate implementations of
- * methods in several existing controllers because an EPUser object is not
- * available in the session for these requests.
- *
- * Checks credentials sent via HTTP Basic Authentication. The Portal's basic
- * HTTP authentication system requires that the user names and endpoints are
- * registered together.
- */
-@RestController
-@RequestMapping(PortalConstants.REST_AUX_API)
-@Configuration
-@EnableAspectJAutoProxy
-@EPAuditLog
-public class AppsControllerExternalRequest implements BasicAuthenticationController {
-
- private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AppsControllerExternalRequest.class);
-
- private static final String ONBOARD_APP = "/onboardApp";
-
- // Where is this used?
- public boolean isAuxRESTfulCall() {
- return true;
- }
-
- /**
- * For testing whether a user is a superadmin.
- */
- @Autowired
- private AdminRolesService adminRolesService;
-
- /**
- * For onboarding or updating an app
- */
- @Autowired
- private EPAppService appService;
-
- /**
- * For promoting a user to Portal admin
- */
- @Autowired
- private PortalAdminService portalAdminService;
-
- /**
- * For creating a new user
- */
- @Autowired
- private UserService userService;
-
- /**
- * Creates a new user as a Portal administrator.
- *
- * <PRE>
- {
- "loginId" : "abc123",
- "loginPwd": "",
- "email":"ecomp@controller"
- }
- * </PRE>
- *
- * @param request
- * HttpServletRequest
- * @param epUser
- * User details; the email and orgUserId fields are mandatory
- * @param response
- * HttpServletResponse
- * @return PortalRestResponse with success or failure
- */
- @ApiOperation(value = "Creates a new user as a Portal administrator.", response = PortalRestResponse.class)
- @RequestMapping(value = "/portalAdmin", method = RequestMethod.POST, produces = "application/json")
- @ResponseBody
- public PortalRestResponse<String> postPortalAdmin(HttpServletRequest request, HttpServletResponse response,
- @RequestBody EPUser epUser) {
- EcompPortalUtils.logAndSerializeObject(logger, "postPortalAdmin", "request", epUser);
- PortalRestResponse<String> portalResponse = new PortalRestResponse<>();
-
- // Check mandatory fields.
- if (epUser.getEmail() == null || epUser.getEmail().trim().length() == 0 //
- || epUser.getLoginId() == null || epUser.getLoginId().trim().length() == 0 //
- || epUser.getLoginPwd() == null) {
- portalResponse.setStatus(PortalRestStatusEnum.ERROR);
- portalResponse.setMessage("Missing required field: email, loginId, or loginPwd");
- return portalResponse;
- }
-
- try {
- // Check for existing user; create if not found.
- List<EPUser> userList = userService.getUserByUserId(epUser.getOrgUserId());
- if (userList == null || userList.size() == 0) {
- // Create user with first, last names etc.; do check for
- // duplicates.
- String userCreateResult = userService.saveNewUser(epUser, "Yes");
- if (!"success".equals(userCreateResult)) {
- portalResponse.setStatus(PortalRestStatusEnum.ERROR);
- portalResponse.setMessage(userCreateResult);
- return portalResponse;
- }
- }
-
- // Check for Portal admin status; promote if not.
- if (adminRolesService.isSuperAdmin(epUser)) {
- portalResponse.setStatus(PortalRestStatusEnum.OK);
- } else {
- FieldsValidator fv = portalAdminService.createPortalAdmin(epUser.getOrgUserId());
- if (fv.httpStatusCode.intValue() == HttpServletResponse.SC_OK) {
- portalResponse.setStatus(PortalRestStatusEnum.OK);
- } else {
- portalResponse.setStatus(PortalRestStatusEnum.ERROR);
- portalResponse.setMessage(fv.toString());
- }
- }
- } catch (Exception ex) {
- // Uncaught exceptions yield 404 and an empty error page
- response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
- portalResponse.setStatus(PortalRestStatusEnum.ERROR);
- portalResponse.setMessage(ex.toString());
- }
-
- EcompPortalUtils.logAndSerializeObject(logger, "postPortalAdmin", "response", portalResponse);
- return portalResponse;
- }
-
- /**
- * Gets the specified application that is on-boarded in Portal.
- *
- * @param request
- * HttpServletRequest
- * @param appId
- * Application ID to get
- * @param response
- * httpServletResponse
- * @return OnboardingApp objects
- */
- @ApiOperation(value = "Gets the specified application that is on-boarded in Portal.", response = OnboardingApp.class)
- @RequestMapping(value = { ONBOARD_APP + "/{appId}" }, method = RequestMethod.GET, produces = "application/json")
- @ResponseBody
- public OnboardingApp getOnboardAppExternal(HttpServletRequest request, HttpServletResponse response,
- @PathVariable("appId") Long appId) {
- EPApp epApp = appService.getApp(appId);
- OnboardingApp obApp = new OnboardingApp();
- appService.createOnboardingFromApp(epApp, obApp);
- EcompPortalUtils.logAndSerializeObject(logger, "getOnboardAppExternal", "response", obApp);
- return obApp;
- }
-
- /**
- * Adds a new application to Portal. The My Logins App Owner in the request
- * must be the organization user ID of a person who is a Portal
- * administrator.
- *
- * <pre>
- * {
- "myLoginsAppOwner" : "abc123",
- "name": "dashboard",
- "url": "http://k8s/something",
- "restUrl" : "http://aic.att.com",
- "restrictedApp" : true,
- "isOpen" : true,
- "isEnabled": false
- }
- * </pre>
- *
- * @param request
- * HttpServletRequest
- * @param response
- * httpServletResponse
- * @param newOnboardApp
- * Message with details about the app to add
- * @return PortalRestResponse
- */
- @ApiOperation(value = "Adds a new application to Portal.", response = PortalRestResponse.class)
- @RequestMapping(value = { ONBOARD_APP }, method = RequestMethod.POST, produces = "application/json")
- @ResponseBody
- public PortalRestResponse<String> postOnboardAppExternal(HttpServletRequest request, HttpServletResponse response,
- @RequestBody OnboardingApp newOnboardApp) {
- EcompPortalUtils.logAndSerializeObject(logger, "postOnboardAppExternal", "request", newOnboardApp);
- PortalRestResponse<String> portalResponse = new PortalRestResponse<>();
-
- // Validate fields
- if (newOnboardApp.id != null) {
- portalResponse.setStatus(PortalRestStatusEnum.ERROR);
- portalResponse.setMessage("Unexpected field: id");
- return portalResponse;
- }
- if (newOnboardApp.name == null || newOnboardApp.name.trim().length() == 0 //
- || newOnboardApp.url == null || newOnboardApp.url.trim().length() == 0 //
- || newOnboardApp.restUrl == null || newOnboardApp.restUrl.trim().length() == 0
- || newOnboardApp.myLoginsAppOwner == null || newOnboardApp.myLoginsAppOwner.trim().length() == 0
- || newOnboardApp.restrictedApp == null //
- || newOnboardApp.isOpen == null //
- || newOnboardApp.isEnabled == null) {
- portalResponse.setStatus(PortalRestStatusEnum.ERROR);
- portalResponse.setMessage(
- "Missing required field: name, url, restUrl, restrictedApp, isOpen, isEnabled, myLoginsAppOwner");
- return portalResponse;
- }
-
- try {
- List<EPUser> userList = userService.getUserByUserId(newOnboardApp.myLoginsAppOwner);
- if (userList == null || userList.size() != 1) {
- portalResponse.setStatus(PortalRestStatusEnum.ERROR);
- portalResponse.setMessage("Failed to find user: " + newOnboardApp.myLoginsAppOwner);
- return portalResponse;
- }
-
- EPUser epUser = userList.get(0);
- // Check for Portal admin status
- if (! adminRolesService.isSuperAdmin(epUser)) {
- portalResponse.setStatus(PortalRestStatusEnum.ERROR);
- portalResponse.setMessage("User lacks Portal admin role: " + epUser.getLoginId());
- return portalResponse;
- }
-
- newOnboardApp.normalize();
- FieldsValidator fv = appService.addOnboardingApp(newOnboardApp, epUser);
- if (fv.httpStatusCode.intValue() == HttpServletResponse.SC_OK) {
- portalResponse.setStatus(PortalRestStatusEnum.OK);
- } else {
- portalResponse.setStatus(PortalRestStatusEnum.ERROR);
- portalResponse.setMessage(fv.toString());
- }
- } catch (Exception ex) {
- // Uncaught exceptions yield 404 and an empty error page
- response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
- portalResponse.setStatus(PortalRestStatusEnum.ERROR);
- portalResponse.setMessage(ex.toString());
- }
- EcompPortalUtils.logAndSerializeObject(logger, "postOnboardAppExternal", "response", portalResponse);
- return portalResponse;
- }
-
- /**
- * Updates information about an on-boarded application in Portal. The My
- * Logins App Owner in the request must be the organization user ID of a
- * person who is a Portal administrator.
- * <pre>
- {
- "id" : 123,
- "myLoginsAppOwner" : "abc123",
- "name": "dashboard",
- "url": "http://k8s/something",
- "restUrl" : "http://aic.att.com",
- "restrictedApp" : true,
- "isOpen" : true,
- "isEnabled": false
- }
- </pre>
- * @param request
- * HttpServletRequest
- * @param response
- * httpServletResponse
- * @param appId
- * application id
- * @param oldOnboardApp
- * Message with details about the app to add
- * @return PortalRestResponse
- */
- @ApiOperation(value = "Updates information about an on-boarded application in Portal.", response = PortalRestResponse.class)
- @RequestMapping(value = { ONBOARD_APP + "/{appId}" }, method = RequestMethod.PUT, produces = "application/json")
- @ResponseBody
- public PortalRestResponse<String> putOnboardAppExternal(HttpServletRequest request, HttpServletResponse response,
- @PathVariable("appId") Long appId, @RequestBody OnboardingApp oldOnboardApp) {
- EcompPortalUtils.logAndSerializeObject(logger, "putOnboardAppExternal", "request", oldOnboardApp);
- PortalRestResponse<String> portalResponse = new PortalRestResponse<>();
- // Validate fields.
- if (oldOnboardApp.id == null || !appId.equals(oldOnboardApp.id)) {
- portalResponse.setStatus(PortalRestStatusEnum.ERROR);
- portalResponse.setMessage("Unexpected value for field: id");
- return portalResponse;
- }
- if (oldOnboardApp.name == null || oldOnboardApp.name.trim().length() == 0 //
- || oldOnboardApp.url == null || oldOnboardApp.url.trim().length() == 0 //
- || oldOnboardApp.restUrl == null || oldOnboardApp.restUrl.trim().length() == 0
- || oldOnboardApp.myLoginsAppOwner == null || oldOnboardApp.myLoginsAppOwner.trim().length() == 0
- || oldOnboardApp.restrictedApp == null //
- || oldOnboardApp.isOpen == null //
- || oldOnboardApp.isEnabled == null) {
- portalResponse.setStatus(PortalRestStatusEnum.ERROR);
- portalResponse.setMessage(
- "Missing required field: name, url, restUrl, restrictedApp, isOpen, isEnabled, myLoginsAppOwner");
- return portalResponse;
- }
-
- try {
- List<EPUser> userList = userService.getUserByUserId(oldOnboardApp.myLoginsAppOwner);
- if (userList == null || userList.size() != 1) {
- portalResponse.setStatus(PortalRestStatusEnum.ERROR);
- portalResponse.setMessage("Failed to find user: " + oldOnboardApp.myLoginsAppOwner);
- return portalResponse;
- }
-
- EPUser epUser = userList.get(0);
- // Check for Portal admin status
- if (! adminRolesService.isSuperAdmin(epUser)) {
- portalResponse.setStatus(PortalRestStatusEnum.ERROR);
- portalResponse.setMessage("User lacks Portal admin role: " + epUser.getLoginId());
- return portalResponse;
- }
-
- oldOnboardApp.normalize();
- FieldsValidator fv = appService.modifyOnboardingApp(oldOnboardApp, epUser);
- if (fv.httpStatusCode.intValue() == HttpServletResponse.SC_OK) {
- portalResponse.setStatus(PortalRestStatusEnum.OK);
- } else {
- portalResponse.setStatus(PortalRestStatusEnum.ERROR);
- portalResponse.setMessage(fv.toString());
- }
- } catch (Exception ex) {
- // Uncaught exceptions yield 404 and an empty error page
- response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
- portalResponse.setStatus(PortalRestStatusEnum.ERROR);
- portalResponse.setMessage(ex.toString());
- }
- EcompPortalUtils.logAndSerializeObject(logger, "putOnboardAppExternal", "response", portalResponse);
- return portalResponse;
- }
-
-}
+/*-
+ * ================================================================================
+ * ECOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.controller;
+
+import java.util.List;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.openecomp.portalapp.portal.domain.EPApp;
+import org.openecomp.portalapp.portal.domain.EPUser;
+import org.openecomp.portalapp.portal.ecomp.model.PortalRestResponse;
+import org.openecomp.portalapp.portal.ecomp.model.PortalRestStatusEnum;
+import org.openecomp.portalapp.portal.logging.aop.EPAuditLog;
+import org.openecomp.portalapp.portal.service.AdminRolesService;
+import org.openecomp.portalapp.portal.service.EPAppService;
+import org.openecomp.portalapp.portal.service.PortalAdminService;
+import org.openecomp.portalapp.portal.service.UserService;
+import org.openecomp.portalapp.portal.transport.FieldsValidator;
+import org.openecomp.portalapp.portal.transport.OnboardingApp;
+import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
+import org.openecomp.portalapp.portal.utils.PortalConstants;
+import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.EnableAspectJAutoProxy;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.ResponseBody;
+import org.springframework.web.bind.annotation.RestController;
+
+import io.swagger.annotations.ApiOperation;
+
+/**
+ * Processes requests from external systems (i.e., not the front-end web UI).
+ * First use case is ECOMP Controller, which has to create an admin and onboard
+ * itself upon launch of a fresh Portal.
+ *
+ * Listens on the "auxapi" path prefix. Provides alternate implementations of
+ * methods in several existing controllers because an EPUser object is not
+ * available in the session for these requests.
+ *
+ * Checks credentials sent via HTTP Basic Authentication. The Portal's basic
+ * HTTP authentication system requires that the user names and endpoints are
+ * registered together.
+ */
+@RestController
+@RequestMapping(PortalConstants.REST_AUX_API)
+@Configuration
+@EnableAspectJAutoProxy
+@EPAuditLog
+public class AppsControllerExternalRequest implements BasicAuthenticationController {
+
+ private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AppsControllerExternalRequest.class);
+
+ private static final String ONBOARD_APP = "/onboardApp";
+
+ // Where is this used?
+ public boolean isAuxRESTfulCall() {
+ return true;
+ }
+
+ /**
+ * For testing whether a user is a superadmin.
+ */
+ @Autowired
+ private AdminRolesService adminRolesService;
+
+ /**
+ * For onboarding or updating an app
+ */
+ @Autowired
+ private EPAppService appService;
+
+ /**
+ * For promoting a user to Portal admin
+ */
+ @Autowired
+ private PortalAdminService portalAdminService;
+
+ /**
+ * For creating a new user
+ */
+ @Autowired
+ private UserService userService;
+
+ /**
+ * Creates a new user as a Portal administrator.
+ *
+ * <PRE>
+ {
+ "loginId" : "abc123",
+ "loginPwd": "",
+ "email":"ecomp@controller"
+ }
+ * </PRE>
+ *
+ * @param request
+ * HttpServletRequest
+ * @param epUser
+ * User details; the email and orgUserId fields are mandatory
+ * @param response
+ * HttpServletResponse
+ * @return PortalRestResponse with success or failure
+ */
+ @ApiOperation(value = "Creates a new user as a Portal administrator.", response = PortalRestResponse.class)
+ @RequestMapping(value = "/portalAdmin", method = RequestMethod.POST, produces = "application/json")
+ @ResponseBody
+ public PortalRestResponse<String> postPortalAdmin(HttpServletRequest request, HttpServletResponse response,
+ @RequestBody EPUser epUser) {
+ EcompPortalUtils.logAndSerializeObject(logger, "postPortalAdmin", "request", epUser);
+ PortalRestResponse<String> portalResponse = new PortalRestResponse<>();
+
+ // Check mandatory fields.
+ if (epUser.getEmail() == null || epUser.getEmail().trim().length() == 0 //
+ || epUser.getLoginId() == null || epUser.getLoginId().trim().length() == 0 //
+ || epUser.getLoginPwd() == null) {
+ portalResponse.setStatus(PortalRestStatusEnum.ERROR);
+ portalResponse.setMessage("Missing required field: email, loginId, or loginPwd");
+ return portalResponse;
+ }
+
+ try {
+ // Check for existing user; create if not found.
+ List<EPUser> userList = userService.getUserByUserId(epUser.getOrgUserId());
+ if (userList == null || userList.size() == 0) {
+ // Create user with first, last names etc.; do check for
+ // duplicates.
+ String userCreateResult = userService.saveNewUser(epUser, "Yes");
+ if (!"success".equals(userCreateResult)) {
+ portalResponse.setStatus(PortalRestStatusEnum.ERROR);
+ portalResponse.setMessage(userCreateResult);
+ return portalResponse;
+ }
+ }
+
+ // Check for Portal admin status; promote if not.
+ if (adminRolesService.isSuperAdmin(epUser)) {
+ portalResponse.setStatus(PortalRestStatusEnum.OK);
+ } else {
+ FieldsValidator fv = portalAdminService.createPortalAdmin(epUser.getOrgUserId());
+ if (fv.httpStatusCode.intValue() == HttpServletResponse.SC_OK) {
+ portalResponse.setStatus(PortalRestStatusEnum.OK);
+ } else {
+ portalResponse.setStatus(PortalRestStatusEnum.ERROR);
+ portalResponse.setMessage(fv.toString());
+ }
+ }
+ } catch (Exception ex) {
+ // Uncaught exceptions yield 404 and an empty error page
+ response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ portalResponse.setStatus(PortalRestStatusEnum.ERROR);
+ portalResponse.setMessage(ex.toString());
+ }
+
+ EcompPortalUtils.logAndSerializeObject(logger, "postPortalAdmin", "response", portalResponse);
+ return portalResponse;
+ }
+
+ /**
+ * Gets the specified application that is on-boarded in Portal.
+ *
+ * @param request
+ * HttpServletRequest
+ * @param appId
+ * Application ID to get
+ * @param response
+ * httpServletResponse
+ * @return OnboardingApp objects
+ */
+ @ApiOperation(value = "Gets the specified application that is on-boarded in Portal.", response = OnboardingApp.class)
+ @RequestMapping(value = { ONBOARD_APP + "/{appId}" }, method = RequestMethod.GET, produces = "application/json")
+ @ResponseBody
+ public OnboardingApp getOnboardAppExternal(HttpServletRequest request, HttpServletResponse response,
+ @PathVariable("appId") Long appId) {
+ EPApp epApp = appService.getApp(appId);
+ OnboardingApp obApp = new OnboardingApp();
+ appService.createOnboardingFromApp(epApp, obApp);
+ EcompPortalUtils.logAndSerializeObject(logger, "getOnboardAppExternal", "response", obApp);
+ return obApp;
+ }
+
+ /**
+ * Adds a new application to Portal. The My Logins App Owner in the request
+ * must be the organization user ID of a person who is a Portal
+ * administrator.
+ *
+ * <pre>
+ * {
+ "myLoginsAppOwner" : "abc123",
+ "name": "dashboard",
+ "url": "http://k8s/something",
+ "restUrl" : "http://aic.att.com",
+ "restrictedApp" : true,
+ "isOpen" : true,
+ "isEnabled": false
+ }
+ * </pre>
+ *
+ * @param request
+ * HttpServletRequest
+ * @param response
+ * httpServletResponse
+ * @param newOnboardApp
+ * Message with details about the app to add
+ * @return PortalRestResponse
+ */
+ @ApiOperation(value = "Adds a new application to Portal.", response = PortalRestResponse.class)
+ @RequestMapping(value = { ONBOARD_APP }, method = RequestMethod.POST, produces = "application/json")
+ @ResponseBody
+ public PortalRestResponse<String> postOnboardAppExternal(HttpServletRequest request, HttpServletResponse response,
+ @RequestBody OnboardingApp newOnboardApp) {
+ EcompPortalUtils.logAndSerializeObject(logger, "postOnboardAppExternal", "request", newOnboardApp);
+ PortalRestResponse<String> portalResponse = new PortalRestResponse<>();
+
+ // Validate fields
+ if (newOnboardApp.id != null) {
+ portalResponse.setStatus(PortalRestStatusEnum.ERROR);
+ portalResponse.setMessage("Unexpected field: id");
+ return portalResponse;
+ }
+ if (newOnboardApp.name == null || newOnboardApp.name.trim().length() == 0 //
+ || newOnboardApp.url == null || newOnboardApp.url.trim().length() == 0 //
+ || newOnboardApp.restUrl == null || newOnboardApp.restUrl.trim().length() == 0
+ || newOnboardApp.myLoginsAppOwner == null || newOnboardApp.myLoginsAppOwner.trim().length() == 0
+ || newOnboardApp.restrictedApp == null //
+ || newOnboardApp.isOpen == null //
+ || newOnboardApp.isEnabled == null) {
+ portalResponse.setStatus(PortalRestStatusEnum.ERROR);
+ portalResponse.setMessage(
+ "Missing required field: name, url, restUrl, restrictedApp, isOpen, isEnabled, myLoginsAppOwner");
+ return portalResponse;
+ }
+
+ try {
+ List<EPUser> userList = userService.getUserByUserId(newOnboardApp.myLoginsAppOwner);
+ if (userList == null || userList.size() != 1) {
+ portalResponse.setStatus(PortalRestStatusEnum.ERROR);
+ portalResponse.setMessage("Failed to find user: " + newOnboardApp.myLoginsAppOwner);
+ return portalResponse;
+ }
+
+ EPUser epUser = userList.get(0);
+ // Check for Portal admin status
+ if (! adminRolesService.isSuperAdmin(epUser)) {
+ portalResponse.setStatus(PortalRestStatusEnum.ERROR);
+ portalResponse.setMessage("User lacks Portal admin role: " + epUser.getLoginId());
+ return portalResponse;
+ }
+
+ newOnboardApp.normalize();
+ FieldsValidator fv = appService.addOnboardingApp(newOnboardApp, epUser);
+ if (fv.httpStatusCode.intValue() == HttpServletResponse.SC_OK) {
+ portalResponse.setStatus(PortalRestStatusEnum.OK);
+ } else {
+ portalResponse.setStatus(PortalRestStatusEnum.ERROR);
+ portalResponse.setMessage(fv.toString());
+ }
+ } catch (Exception ex) {
+ // Uncaught exceptions yield 404 and an empty error page
+ response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ portalResponse.setStatus(PortalRestStatusEnum.ERROR);
+ portalResponse.setMessage(ex.toString());
+ }
+ EcompPortalUtils.logAndSerializeObject(logger, "postOnboardAppExternal", "response", portalResponse);
+ return portalResponse;
+ }
+
+ /**
+ * Updates information about an on-boarded application in Portal. The My
+ * Logins App Owner in the request must be the organization user ID of a
+ * person who is a Portal administrator.
+ * <pre>
+ {
+ "id" : 123,
+ "myLoginsAppOwner" : "abc123",
+ "name": "dashboard",
+ "url": "http://k8s/something",
+ "restUrl" : "http://aic.att.com",
+ "restrictedApp" : true,
+ "isOpen" : true,
+ "isEnabled": false
+ }
+ </pre>
+ * @param request
+ * HttpServletRequest
+ * @param response
+ * httpServletResponse
+ * @param appId
+ * application id
+ * @param oldOnboardApp
+ * Message with details about the app to add
+ * @return PortalRestResponse
+ */
+ @ApiOperation(value = "Updates information about an on-boarded application in Portal.", response = PortalRestResponse.class)
+ @RequestMapping(value = { ONBOARD_APP + "/{appId}" }, method = RequestMethod.PUT, produces = "application/json")
+ @ResponseBody
+ public PortalRestResponse<String> putOnboardAppExternal(HttpServletRequest request, HttpServletResponse response,
+ @PathVariable("appId") Long appId, @RequestBody OnboardingApp oldOnboardApp) {
+ EcompPortalUtils.logAndSerializeObject(logger, "putOnboardAppExternal", "request", oldOnboardApp);
+ PortalRestResponse<String> portalResponse = new PortalRestResponse<>();
+ // Validate fields.
+ if (oldOnboardApp.id == null || !appId.equals(oldOnboardApp.id)) {
+ portalResponse.setStatus(PortalRestStatusEnum.ERROR);
+ portalResponse.setMessage("Unexpected value for field: id");
+ return portalResponse;
+ }
+ if (oldOnboardApp.name == null || oldOnboardApp.name.trim().length() == 0 //
+ || oldOnboardApp.url == null || oldOnboardApp.url.trim().length() == 0 //
+ || oldOnboardApp.restUrl == null || oldOnboardApp.restUrl.trim().length() == 0
+ || oldOnboardApp.myLoginsAppOwner == null || oldOnboardApp.myLoginsAppOwner.trim().length() == 0
+ || oldOnboardApp.restrictedApp == null //
+ || oldOnboardApp.isOpen == null //
+ || oldOnboardApp.isEnabled == null) {
+ portalResponse.setStatus(PortalRestStatusEnum.ERROR);
+ portalResponse.setMessage(
+ "Missing required field: name, url, restUrl, restrictedApp, isOpen, isEnabled, myLoginsAppOwner");
+ return portalResponse;
+ }
+
+ try {
+ List<EPUser> userList = userService.getUserByUserId(oldOnboardApp.myLoginsAppOwner);
+ if (userList == null || userList.size() != 1) {
+ portalResponse.setStatus(PortalRestStatusEnum.ERROR);
+ portalResponse.setMessage("Failed to find user: " + oldOnboardApp.myLoginsAppOwner);
+ return portalResponse;
+ }
+
+ EPUser epUser = userList.get(0);
+ // Check for Portal admin status
+ if (! adminRolesService.isSuperAdmin(epUser)) {
+ portalResponse.setStatus(PortalRestStatusEnum.ERROR);
+ portalResponse.setMessage("User lacks Portal admin role: " + epUser.getLoginId());
+ return portalResponse;
+ }
+
+ oldOnboardApp.normalize();
+ FieldsValidator fv = appService.modifyOnboardingApp(oldOnboardApp, epUser);
+ if (fv.httpStatusCode.intValue() == HttpServletResponse.SC_OK) {
+ portalResponse.setStatus(PortalRestStatusEnum.OK);
+ } else {
+ portalResponse.setStatus(PortalRestStatusEnum.ERROR);
+ portalResponse.setMessage(fv.toString());
+ }
+ } catch (Exception ex) {
+ // Uncaught exceptions yield 404 and an empty error page
+ response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ portalResponse.setStatus(PortalRestStatusEnum.ERROR);
+ portalResponse.setMessage(ex.toString());
+ }
+ EcompPortalUtils.logAndSerializeObject(logger, "putOnboardAppExternal", "response", portalResponse);
+ return portalResponse;
+ }
+
+}
diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/AuditLogController.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/AuditLogController.java
index 705c9008..8d6b8e63 100644
--- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/AuditLogController.java
+++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/AuditLogController.java
@@ -1,106 +1,106 @@
-/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.controller;
-
-import javax.servlet.http.HttpServletRequest;
-
-import org.slf4j.MDC;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestMethod;
-import org.springframework.web.bind.annotation.RequestParam;
-import org.springframework.web.bind.annotation.RestController;
-
-import org.openecomp.portalsdk.core.domain.AuditLog;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalsdk.core.service.AuditService;
-import org.openecomp.portalapp.controller.EPRestrictedBaseController;
-import org.openecomp.portalapp.portal.domain.EPUser;
-import org.openecomp.portalapp.portal.logging.aop.EPEELFLoggerAdvice;
-import org.openecomp.portalapp.portal.logging.logic.EPLogUtil;
-import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties;
-import org.openecomp.portalapp.util.EPUserUtils;
-
-@RestController
-@RequestMapping("/portalApi/auditLog")
-public class AuditLogController extends EPRestrictedBaseController {
- private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(DashboardController.class);
-
- @Autowired
- private AuditService auditService;
-
- /**
- * Store audit log of the specified access type.
- *
- * @param request
- * @param affectedAppId
- * @param type
- * @param comment
- */
- @RequestMapping(value = "/store", method = RequestMethod.GET, produces = "application/json")
- public void auditLog(HttpServletRequest request, @RequestParam String affectedAppId, @RequestParam String type,
- @RequestParam String comment) {
- logger.debug(EELFLoggerDelegate.debugLogger, "auditLog: appId {}, type {], comment {}",
- affectedAppId, type, comment);
- String cd_type = null;
- try {
- EPUser user = EPUserUtils.getUserSession(request);
- /* Check type of Activity CD */
- if (type.equals("app")) {
- cd_type = AuditLog.CD_ACTIVITY_APP_ACCESS;
- } else if (type.equals("tab")) {
- cd_type = AuditLog.CD_ACTIVITY_TAB_ACCESS;
- } else if (type.equals("functional")) {
- cd_type = AuditLog.CD_ACTIVITY_FUNCTIONAL_ACCESS;
- } else if (type.equals("leftMenu")) {
- cd_type = AuditLog.CD_ACTIVITY_LEFT_MENU_ACCESS;
- } else {
- logger.error(EELFLoggerDelegate.errorLogger, "Storing auditLog failed! Activity CD type is not correct.");
- }
- /* Store the audit log only if it contains valid Activity CD */
- if (cd_type != null) {
- AuditLog auditLog = new AuditLog();
- auditLog.setActivityCode(cd_type);
- /*
- * Check affectedAppId and comment and see if these two values are
- * valid
- */
- if (comment != null && !comment.equals("") && !comment.equals("undefined"))
- auditLog.setComments(comment);
- if (affectedAppId != null && !affectedAppId.equals("") && !affectedAppId.equals("undefined"))
- auditLog.setAffectedRecordId(affectedAppId);
- long userId = EPUserUtils.getUserId(request);
- auditLog.setUserId(userId);
- auditService.logActivity(auditLog, null);
-
- // Log file
- MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP,EPEELFLoggerAdvice.getCurrentDateTimeUTC());
- MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP,EPEELFLoggerAdvice.getCurrentDateTimeUTC());
- logger.info(EELFLoggerDelegate.auditLogger, EPLogUtil.formatAuditLogMessage("AuditLogController.auditLog",
- cd_type, user.getOrgUserId(), affectedAppId, comment));
- MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
- MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
- }
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "auditLog failed", e);
- }
- }
-
-}
+/*-
+ * ================================================================================
+ * ECOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.controller;
+
+import javax.servlet.http.HttpServletRequest;
+
+import org.slf4j.MDC;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.RequestParam;
+import org.springframework.web.bind.annotation.RestController;
+
+import org.openecomp.portalsdk.core.domain.AuditLog;
+import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.openecomp.portalsdk.core.service.AuditService;
+import org.openecomp.portalapp.controller.EPRestrictedBaseController;
+import org.openecomp.portalapp.portal.domain.EPUser;
+import org.openecomp.portalapp.portal.logging.aop.EPEELFLoggerAdvice;
+import org.openecomp.portalapp.portal.logging.logic.EPLogUtil;
+import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties;
+import org.openecomp.portalapp.util.EPUserUtils;
+
+@RestController
+@RequestMapping("/portalApi/auditLog")
+public class AuditLogController extends EPRestrictedBaseController {
+ private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(DashboardController.class);
+
+ @Autowired
+ private AuditService auditService;
+
+ /**
+ * Store audit log of the specified access type.
+ *
+ * @param request
+ * @param affectedAppId
+ * @param type
+ * @param comment
+ */
+ @RequestMapping(value = "/store", method = RequestMethod.GET, produces = "application/json")
+ public void auditLog(HttpServletRequest request, @RequestParam String affectedAppId, @RequestParam String type,
+ @RequestParam String comment) {
+ logger.debug(EELFLoggerDelegate.debugLogger, "auditLog: appId {}, type {], comment {}",
+ affectedAppId, type, comment);
+ String cd_type = null;
+ try {
+ EPUser user = EPUserUtils.getUserSession(request);
+ /* Check type of Activity CD */
+ if (type.equals("app")) {
+ cd_type = AuditLog.CD_ACTIVITY_APP_ACCESS;
+ } else if (type.equals("tab")) {
+ cd_type = AuditLog.CD_ACTIVITY_TAB_ACCESS;
+ } else if (type.equals("functional")) {
+ cd_type = AuditLog.CD_ACTIVITY_FUNCTIONAL_ACCESS;
+ } else if (type.equals("leftMenu")) {
+ cd_type = AuditLog.CD_ACTIVITY_LEFT_MENU_ACCESS;
+ } else {
+ logger.error(EELFLoggerDelegate.errorLogger, "Storing auditLog failed! Activity CD type is not correct.");
+ }
+ /* Store the audit log only if it contains valid Activity CD */
+ if (cd_type != null) {
+ AuditLog auditLog = new AuditLog();
+ auditLog.setActivityCode(cd_type);
+ /*
+ * Check affectedAppId and comment and see if these two values are
+ * valid
+ */
+ if (comment != null && !comment.equals("") && !comment.equals("undefined"))
+ auditLog.setComments(comment);
+ if (affectedAppId != null && !affectedAppId.equals("") && !affectedAppId.equals("undefined"))
+ auditLog.setAffectedRecordId(affectedAppId);
+ long userId = EPUserUtils.getUserId(request);
+ auditLog.setUserId(userId);
+ auditService.logActivity(auditLog, null);
+
+ // Log file
+ MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP,EPEELFLoggerAdvice.getCurrentDateTimeUTC());
+ MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP,EPEELFLoggerAdvice.getCurrentDateTimeUTC());
+ logger.info(EELFLoggerDelegate.auditLogger, EPLogUtil.formatAuditLogMessage("AuditLogController.auditLog",
+ cd_type, user.getOrgUserId(), affectedAppId, comment));
+ MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
+ MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
+ }
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "auditLog failed", e);
+ }
+ }
+
+}
diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/BEPropertyReaderController.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/BEPropertyReaderController.java
index a7b3f1a1..5be6614c 100644
--- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/BEPropertyReaderController.java
+++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/BEPropertyReaderController.java
@@ -1,46 +1,46 @@
-/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.controller;
-
-import javax.servlet.http.HttpServletRequest;
-
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestMethod;
-import org.springframework.web.bind.annotation.RequestParam;
-import org.springframework.web.bind.annotation.RestController;
-
-import org.openecomp.portalsdk.core.controller.FusionBaseController;
-import org.openecomp.portalsdk.core.util.SystemProperties;
-import org.openecomp.portalapp.portal.domain.BEProperty;
-import org.openecomp.portalapp.portal.ecomp.model.PortalRestResponse;
-import org.openecomp.portalapp.portal.ecomp.model.PortalRestStatusEnum;
-
-@RestController
-@RequestMapping("/portalApi/properties")
-public class BEPropertyReaderController extends FusionBaseController{
- @RequestMapping(value = "/readProperty", method = RequestMethod.GET, produces = "application/json")
- public PortalRestResponse<BEProperty> readProperty(HttpServletRequest request, @RequestParam String key) {
- try {
- return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", new BEProperty(key, SystemProperties.getProperty(key)));
- } catch (Exception e) {
- return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.toString(), null);
- }
- }
-}
+/*-
+ * ================================================================================
+ * ECOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.controller;
+
+import javax.servlet.http.HttpServletRequest;
+
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.RequestParam;
+import org.springframework.web.bind.annotation.RestController;
+
+import org.openecomp.portalsdk.core.controller.FusionBaseController;
+import org.openecomp.portalsdk.core.util.SystemProperties;
+import org.openecomp.portalapp.portal.domain.BEProperty;
+import org.openecomp.portalapp.portal.ecomp.model.PortalRestResponse;
+import org.openecomp.portalapp.portal.ecomp.model.PortalRestStatusEnum;
+
+@RestController
+@RequestMapping("/portalApi/properties")
+public class BEPropertyReaderController extends FusionBaseController{
+ @RequestMapping(value = "/readProperty", method = RequestMethod.GET, produces = "application/json")
+ public PortalRestResponse<BEProperty> readProperty(HttpServletRequest request, @RequestParam String key) {
+ try {
+ return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", new BEProperty(key, SystemProperties.getProperty(key)));
+ } catch (Exception e) {
+ return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.toString(), null);
+ }
+ }
+}
diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/BasicAuthAccountController.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/BasicAuthAccountController.java
index f23054bd..c16fa78f 100644
--- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/BasicAuthAccountController.java
+++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/BasicAuthAccountController.java
@@ -24,13 +24,12 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
-@SuppressWarnings("unchecked")
@RestController
@org.springframework.context.annotation.Configuration
@EnableAspectJAutoProxy
@EPAuditLog
-public class BasicAuthAccountController extends EPRestrictedBaseController{
-
+public class BasicAuthAccountController extends EPRestrictedBaseController {
+
@Autowired
private BasicAuthAccountService basicAuthAccountService;
@@ -38,69 +37,99 @@ public class BasicAuthAccountController extends EPRestrictedBaseController{
private AdminRolesService adminRolesService;
/**
- * Saves Basic Authentication account for external systems
- * @param BasicAuthCredentials
+ * Saves Basic Authentication account for external systems
+ *
+ * @param request
+ * HttpServletRequest
+ * @param response
+ * HttpServletResponse
+ * @param newBasicAuthAccount
+ * BasicAuthCredentials
* @return Id of the newly created account
- */
-
+ * @throws Exception
+ * on failure
+ */
@RequestMapping(value = { "/portalApi/basicAuthAccount" }, method = RequestMethod.POST)
public PortalRestResponse<String> createBasicAuthAccount(HttpServletRequest request, HttpServletResponse response,
@RequestBody BasicAuthCredentials newBasicAuthAccount) throws Exception {
-
+
EPUser user = EPUserUtils.getUserSession(request);
- if (!adminRolesService.isSuperAdmin(user)){
- return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "Authorization Required", "Admin Only Operation! ");
+ if (!adminRolesService.isSuperAdmin(user)) {
+ return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "Authorization Required",
+ "Admin Only Operation! ");
}
-
- if(newBasicAuthAccount == null){
+
+ if (newBasicAuthAccount == null) {
return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "FAILURE",
"newBasicAuthAccount cannot be null or empty");
}
long accountId = basicAuthAccountService.saveBasicAuthAccount(newBasicAuthAccount);
-
+
List<Long> endpointIdList = new ArrayList<>();
try {
- for(EPEndpoint ep: newBasicAuthAccount.getEndpoints()){
+ for (EPEndpoint ep : newBasicAuthAccount.getEndpoints()) {
endpointIdList.add(basicAuthAccountService.saveEndpoints(ep));
}
- for(Long endpointId: endpointIdList){
+ for (Long endpointId : endpointIdList) {
basicAuthAccountService.saveEndpointAccount(accountId, endpointId);
}
} catch (Exception e) {
return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "FAILURE", e.getMessage());
}
-
+
return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "SUCCESS", "");
}
-
+
/**
- * Returns list of all BasicAuthCredentials in the system
+ * Returns list of all BasicAuthCredentials in the system
+ *
+ * @param request
+ * HttpServletRequest
+ * @param response
+ * HttpServletResponse
* @return List<BasicAuthCredentials>
+ * @throws Exception
+ * on failure
*/
-
+
@RequestMapping(value = { "/portalApi/basicAuthAccount" }, method = RequestMethod.GET)
- public PortalRestResponse<List<BasicAuthCredentials>> getBasicAuthAccount(HttpServletRequest request, HttpServletResponse response)
- throws Exception {
-
+ public PortalRestResponse<List<BasicAuthCredentials>> getBasicAuthAccount(HttpServletRequest request,
+ HttpServletResponse response) throws Exception {
+
EPUser user = EPUserUtils.getUserSession(request);
- if (!adminRolesService.isSuperAdmin(user)){
- return new PortalRestResponse<List<BasicAuthCredentials>>(PortalRestStatusEnum.ERROR, "UnAuthorized! Admin Only Operation", new ArrayList<>());
+ if (!adminRolesService.isSuperAdmin(user)) {
+ return new PortalRestResponse<List<BasicAuthCredentials>>(PortalRestStatusEnum.ERROR,
+ "UnAuthorized! Admin Only Operation", new ArrayList<>());
}
- return new PortalRestResponse<List<BasicAuthCredentials>>(PortalRestStatusEnum.OK, "Success", basicAuthAccountService.getAccountData());
+ return new PortalRestResponse<List<BasicAuthCredentials>>(PortalRestStatusEnum.OK, "Success",
+ basicAuthAccountService.getAccountData());
}
-
+
/**
* Updates an existing BasicAuthCredentials account
+ *
+ * @param request
+ * HttpServletRequest
+ * @param response
+ * HttpServletResponse
+ * @param accountId
+ * account ID
+ * @param newBasicAuthAccount
+ * BasicAuthCredentials
+ * @return PortalRestResponse<String>
+ * @throws Exception
+ * on failure
*/
-
@RequestMapping(value = { "/portalApi/basicAuthAccount/{accountId}" }, method = RequestMethod.PUT)
public PortalRestResponse<String> updateAccount(HttpServletRequest request, HttpServletResponse response,
- @PathVariable("accountId") long accountId, @RequestBody BasicAuthCredentials newBasicAuthAccount) throws Exception {
-
+ @PathVariable("accountId") long accountId, @RequestBody BasicAuthCredentials newBasicAuthAccount)
+ throws Exception {
+
EPUser user = EPUserUtils.getUserSession(request);
- if (!adminRolesService.isSuperAdmin(user)){
- return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "Authorization Required", "Admin Only Operation! ");
+ if (!adminRolesService.isSuperAdmin(user)) {
+ return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "Authorization Required",
+ "Admin Only Operation! ");
}
if (newBasicAuthAccount == null) {
@@ -114,21 +143,30 @@ public class BasicAuthAccountController extends EPRestrictedBaseController{
}
return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "SUCCESS", "");
}
-
+
/**
* deletes an existing BasicAuthCredentials account
+ *
+ * @param request
+ * HttpServletRequest
+ * @param response
+ * HttpServletResponse
+ * @param accountId
+ * account ID
+ * @return PortalRestResponse<String>
+ * @throws Exception
+ * on failure
*/
-
@RequestMapping(value = { "/portalApi/basicAuthAccount/{accountId}" }, method = RequestMethod.DELETE)
public PortalRestResponse<String> deleteAccount(HttpServletRequest request, HttpServletResponse response,
@PathVariable("accountId") long accountId) throws Exception {
-
+
EPUser user = EPUserUtils.getUserSession(request);
- if (!adminRolesService.isSuperAdmin(user)){
- return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "Authorization Required", "Admin Only Operation! ");
+ if (!adminRolesService.isSuperAdmin(user)) {
+ return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "Authorization Required",
+ "Admin Only Operation! ");
}
-
try {
basicAuthAccountService.deleteEndpointAccout(accountId);
} catch (Exception e) {
@@ -136,6 +174,5 @@ public class BasicAuthAccountController extends EPRestrictedBaseController{
}
return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "SUCCESS", "");
}
-
-
+
}
diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/BasicAuthenticationController.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/BasicAuthenticationController.java
index d9bdf3dc..874edad0 100644
--- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/BasicAuthenticationController.java
+++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/BasicAuthenticationController.java
@@ -1,28 +1,28 @@
-/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.controller;
-
-/**
- * Marker interface to indicate that requests to this controller present HTTP
- * Basic Authentication credentials.
- */
-public interface BasicAuthenticationController {
-
-}
+/*-
+ * ================================================================================
+ * ECOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.controller;
+
+/**
+ * Marker interface to indicate that requests to this controller present HTTP
+ * Basic Authentication credentials.
+ */
+public interface BasicAuthenticationController {
+
+}
diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/ConsulClientController.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/ConsulClientController.java
index 8db94849..808220c5 100644
--- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/ConsulClientController.java
+++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/ConsulClientController.java
@@ -1,90 +1,95 @@
-/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.controller;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.web.bind.annotation.PathVariable;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestMethod;
-import org.springframework.web.bind.annotation.RestController;
-
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalapp.controller.EPRestrictedBaseController;
-import org.openecomp.portalapp.portal.service.ConsulHealthService;
-import org.openecomp.portalapp.portal.ecomp.model.PortalRestResponse;
-import org.openecomp.portalapp.portal.ecomp.model.PortalRestStatusEnum;
-import com.orbitz.consul.ConsulException;
-import com.orbitz.consul.model.health.ServiceHealth;
-
-import io.searchbox.client.config.exception.NoServerConfiguredException;
-
-@RestController
-@RequestMapping("/portalApi/consul")
-public class ConsulClientController extends EPRestrictedBaseController {
- private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ConsulClientController.class);
-
- @Autowired
- private ConsulHealthService consulHealthService;
- //Get location of a healthy node running our service
- @RequestMapping(value = { "/service/{service}" }, method = RequestMethod.GET, produces = "application/json")
- public PortalRestResponse<String> getServiceLocation(HttpServletRequest request, HttpServletResponse response, @PathVariable("service") String service) {
-
- try{
- return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "Success!", consulHealthService.getServiceLocation(service));
- }
- catch(NoServerConfiguredException e){
- logger.error(logger.errorLogger, "No healthy service exception!");
- return new PortalRestResponse<String>(PortalRestStatusEnum.WARN, "Warning!", "No healthy service exception!");
- }
- catch(ConsulException e){
- logger.error(logger.errorLogger, "Couldn't connect ot consul - Is consul running?");
- return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "Error!", "Couldn't connect ot consul - Is consul running?");
- }
- }
-
- @RequestMapping(value = { "/service/healthy/{service}" }, method = RequestMethod.GET, produces = "application/json")
- public PortalRestResponse<List<ServiceHealth>> getAllHealthyNodes(HttpServletRequest request, HttpServletResponse response, @PathVariable("service") String service) {
- try{
- return new PortalRestResponse<List<ServiceHealth>>(PortalRestStatusEnum.OK, "Success!", consulHealthService.getAllHealthyNodes(service));
- }
- catch(ConsulException e){
- logger.error(logger.errorLogger, "Couldn't connect to consul - shouldn't break anything.");
- return new PortalRestResponse<List<ServiceHealth>>(PortalRestStatusEnum.ERROR,"Error!", new ArrayList<>());
- }
- }
-
- @RequestMapping(value = { "/service/all/{service}" }, method = RequestMethod.GET, produces = "application/json")
- public PortalRestResponse<List<ServiceHealth>> getAllNodes(HttpServletRequest request, HttpServletResponse response, @PathVariable("service") String service) {
- try{
- return new PortalRestResponse<List<ServiceHealth>>(PortalRestStatusEnum.OK, "Success!", consulHealthService.getAllNodes(service));
- }
- catch(ConsulException e){
- logger.error(logger.errorLogger, "Couldn't connect to consul - shouldn't break anything.");
- return new PortalRestResponse<List<ServiceHealth>>(PortalRestStatusEnum.ERROR,"Error!", new ArrayList<>());
- }
- }
-
-}
+/*-
+ * ================================================================================
+ * ECOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.controller;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.openecomp.portalapp.controller.EPRestrictedBaseController;
+import org.openecomp.portalapp.portal.ecomp.model.PortalRestResponse;
+import org.openecomp.portalapp.portal.ecomp.model.PortalRestStatusEnum;
+import org.openecomp.portalapp.portal.service.ConsulHealthService;
+import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.RestController;
+
+import com.orbitz.consul.ConsulException;
+import com.orbitz.consul.model.health.ServiceHealth;
+
+import io.searchbox.client.config.exception.NoServerConfiguredException;
+
+@RestController
+@RequestMapping("/portalApi/consul")
+public class ConsulClientController extends EPRestrictedBaseController {
+ private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ConsulClientController.class);
+
+ @Autowired
+ private ConsulHealthService consulHealthService;
+
+ // Get location of a healthy node running our service
+ @RequestMapping(value = { "/service/{service}" }, method = RequestMethod.GET, produces = "application/json")
+ public PortalRestResponse<String> getServiceLocation(HttpServletRequest request, HttpServletResponse response,
+ @PathVariable("service") String service) {
+
+ try {
+ return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "Success!",
+ consulHealthService.getServiceLocation(service, null));
+ } catch (NoServerConfiguredException e) {
+ logger.error(logger.errorLogger, "No healthy service exception!");
+ return new PortalRestResponse<String>(PortalRestStatusEnum.WARN, "Warning!",
+ "No healthy service exception!");
+ } catch (ConsulException e) {
+ logger.error(logger.errorLogger, "Couldn't connect ot consul - Is consul running?");
+ return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "Error!",
+ "Couldn't connect ot consul - Is consul running?");
+ }
+ }
+
+ @RequestMapping(value = { "/service/healthy/{service}" }, method = RequestMethod.GET, produces = "application/json")
+ public PortalRestResponse<List<ServiceHealth>> getAllHealthyNodes(HttpServletRequest request,
+ HttpServletResponse response, @PathVariable("service") String service) {
+ try {
+ return new PortalRestResponse<List<ServiceHealth>>(PortalRestStatusEnum.OK, "Success!",
+ consulHealthService.getAllHealthyNodes(service));
+ } catch (ConsulException e) {
+ logger.error(logger.errorLogger, "Couldn't connect to consul - shouldn't break anything.");
+ return new PortalRestResponse<List<ServiceHealth>>(PortalRestStatusEnum.ERROR, "Error!", new ArrayList<>());
+ }
+ }
+
+ @RequestMapping(value = { "/service/all/{service}" }, method = RequestMethod.GET, produces = "application/json")
+ public PortalRestResponse<List<ServiceHealth>> getAllNodes(HttpServletRequest request, HttpServletResponse response,
+ @PathVariable("service") String service) {
+ try {
+ return new PortalRestResponse<List<ServiceHealth>>(PortalRestStatusEnum.OK, "Success!",
+ consulHealthService.getAllNodes(service));
+ } catch (ConsulException e) {
+ logger.error(logger.errorLogger, "Couldn't connect to consul - shouldn't break anything.");
+ return new PortalRestResponse<List<ServiceHealth>>(PortalRestStatusEnum.ERROR, "Error!", new ArrayList<>());
+ }
+ }
+
+}
diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/DashboardController.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/DashboardController.java
index 290a5ffc..81a61d57 100644
--- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/DashboardController.java
+++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/DashboardController.java
@@ -1,385 +1,385 @@
-/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.controller;
-
-import java.text.ParseException;
-import java.text.SimpleDateFormat;
-import java.util.ArrayList;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-
-import javax.servlet.http.HttpServletRequest;
-
-import org.openecomp.portalapp.controller.EPRestrictedBaseController;
-import org.openecomp.portalapp.portal.domain.EPUser;
-import org.openecomp.portalapp.portal.domain.EcompAuditLog;
-import org.openecomp.portalapp.portal.ecomp.model.PortalRestResponse;
-import org.openecomp.portalapp.portal.ecomp.model.PortalRestStatusEnum;
-import org.openecomp.portalapp.portal.ecomp.model.SearchResultItem;
-import org.openecomp.portalapp.portal.logging.aop.EPAuditLog;
-import org.openecomp.portalapp.portal.logging.aop.EPEELFLoggerAdvice;
-import org.openecomp.portalapp.portal.logging.logic.EPLogUtil;
-import org.openecomp.portalapp.portal.service.DashboardSearchService;
-import org.openecomp.portalapp.portal.transport.CommonWidget;
-import org.openecomp.portalapp.portal.transport.CommonWidgetMeta;
-import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties;
-import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
-import org.openecomp.portalapp.util.EPUserUtils;
-import org.openecomp.portalsdk.core.domain.AuditLog;
-import org.openecomp.portalsdk.core.domain.support.CollaborateList;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalsdk.core.service.AuditService;
-import org.openecomp.portalsdk.core.util.SystemProperties;
-import org.slf4j.MDC;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.web.bind.annotation.RequestBody;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestMethod;
-import org.springframework.web.bind.annotation.RequestParam;
-import org.springframework.web.bind.annotation.RestController;
-
-/**
- * Controller supplies data to Angular services on the dashboard page.
- */
-@Configuration
-@RestController
-@RequestMapping("/portalApi/dashboard")
-public class DashboardController extends EPRestrictedBaseController {
-
- private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(DashboardController.class);
-
- @Autowired
- private DashboardSearchService searchService;
- @Autowired
- private AuditService auditService;
-
- public enum WidgetCategory {
- EVENTS, NEWS, IMPORTANTRESOURCES;
- }
-
- /**
- * Validates the resource type parameter.
- *
- * @param resourceType
- * @return True if known in the enum WidgetCategory, else false.
- */
- private boolean isValidResourceType(String resourceType) {
- if (resourceType == null)
- return false;
- for (WidgetCategory wc : WidgetCategory.values())
- if (wc.name().equals(resourceType))
- return true;
- return false;
- }
-
- /**
- * Gets all widgets of the specified resource type.
- * In iteration 41 (when widget will utilized service onboarding), this method can be removed, instead we will use CommonWidgetController.java (basic auth based)
- *
- * @param request
- * @param resourceType
- * Request parameter.
- * @return Rest response wrapped around a CommonWidgetMeta object.
- */
- @RequestMapping(value = "/widgetData", method = RequestMethod.GET, produces = "application/json")
- public PortalRestResponse<CommonWidgetMeta> getWidgetData(HttpServletRequest request,
- @RequestParam String resourceType) {
- if (!isValidResourceType(resourceType))
- return new PortalRestResponse<CommonWidgetMeta>(PortalRestStatusEnum.ERROR,
- "Unexpected resource type " + resourceType, null);
- return new PortalRestResponse<CommonWidgetMeta>(PortalRestStatusEnum.OK, "success",
- searchService.getWidgetData(resourceType));
- }
-
-
- /**
- * Saves a batch of events, news or resources.
- *
- * @param commonWidgetMeta
- * read from POST body.
- * @return Rest response wrapped around a String; e.g., "success" or "ERROR"
- */
- @RequestMapping(value = "/widgetDataBulk", method = RequestMethod.POST, produces = "application/json")
- public PortalRestResponse<String> saveWidgetDataBulk(@RequestBody CommonWidgetMeta commonWidgetMeta) {
- logger.debug(EELFLoggerDelegate.debugLogger, "saveWidgetDataBulk: argument is {}", commonWidgetMeta);
- if (commonWidgetMeta.getCategory() == null || commonWidgetMeta.getCategory().trim().equals(""))
- return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "ERROR",
- "Category cannot be null or empty");
- if (!isValidResourceType(commonWidgetMeta.getCategory()))
- return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR,
- "Unexpected resource type " + commonWidgetMeta.getCategory(), null);
- // validate dates
- for (CommonWidget cw : commonWidgetMeta.getItems()) {
- String err = validateCommonWidget(cw);
- if (err != null)
- return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, err, null);
- }
- return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "success",
- searchService.saveWidgetDataBulk(commonWidgetMeta));
- }
-
- /**
- * Saves one: event, news or resource
- *
- * @param commonWidget
- * read from POST body
- * @return Rest response wrapped around a String; e.g., "success" or "ERROR"
- */
- @RequestMapping(value = "/widgetData", method = RequestMethod.POST, produces = "application/json")
- public PortalRestResponse<String> saveWidgetData(@RequestBody CommonWidget commonWidget) {
- logger.debug(EELFLoggerDelegate.debugLogger, "saveWidgetData: argument is {}", commonWidget);
- if (commonWidget.getCategory() == null || commonWidget.getCategory().trim().equals(""))
- return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "ERROR",
- "Category cannot be null or empty");
- String err = validateCommonWidget(commonWidget);
- if (err != null)
- return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, err, null);
- return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "success",
- searchService.saveWidgetData(commonWidget));
- }
-
- /**
- * Used by the validate function
- */
- private final SimpleDateFormat yearMonthDayFormat = new SimpleDateFormat("yyyy-MM-dd");
-
- /**
- * Validates the content of a common widget.
- *
- * @param cw
- * @return null on success; an error message if validation fails.
- * @throws Exception
- */
- private String validateCommonWidget(CommonWidget cw) {
- if (!isValidResourceType(cw.getCategory()))
- return "Invalid category: " + cw.getCategory();
- if (cw.getTitle() == null || cw.getTitle().trim().length() == 0)
- return "Title is missing";
- if (cw.getHref() == null || cw.getHref().trim().length() == 0)
- return "HREF is missing";
- if (!cw.getHref().toLowerCase().startsWith("http"))
- return "HREF does not start with http";
- if (cw.getSortOrder() == null)
- return "Sort order is null";
- if (WidgetCategory.EVENTS.name().equals(cw.getCategory())) {
- if (cw.getEventDate() == null || cw.getEventDate().trim().length() == 0)
- return "Date is missing";
- try {
- yearMonthDayFormat.setLenient(false);
- Date date = yearMonthDayFormat.parse(cw.getEventDate());
- if (date == null)
- return "Failed to parse date " + cw.getEventDate();
- } catch (ParseException ex) {
- return ex.toString();
- }
- }
- return null;
- }
-
- /**
- * Deletes one: event, news or resource
- *
- * @param commonWidget
- * read from POST body
- * @return Rest response wrapped around a String; e.g., "success" or "ERROR"
- */
- @RequestMapping(value = "/deleteData", method = RequestMethod.POST, produces = "application/json")
- public PortalRestResponse<String> deleteWidgetData(@RequestBody CommonWidget commonWidget) {
- logger.debug(EELFLoggerDelegate.debugLogger, "deleteWidgetData: argument is {}", commonWidget);
- return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "success",
- searchService.deleteWidgetData(commonWidget));
- }
-
- /**
- * Searches all portal for the input string.
- *
- * @param request
- * @param searchString
- * @return Rest response wrapped around a Map of String to List of Search
- * Result Item.
- */
- @EPAuditLog
- @RequestMapping(value = "/search", method = RequestMethod.GET, produces = "application/json")
- public PortalRestResponse<Map<String, List<SearchResultItem>>> searchPortal(HttpServletRequest request,
- @RequestParam String searchString) {
-
- if (searchString != null)
- searchString = searchString.trim();
- EPUser user = EPUserUtils.getUserSession(request);
- try {
- if (user == null) {
- return new PortalRestResponse<>(PortalRestStatusEnum.ERROR,
- "searchPortal: User object is null? - check logs",
- new HashMap<String, List<SearchResultItem>>());
- } else if (searchString == null || searchString.length() == 0) {
- return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "searchPortal: String string is null",
- new HashMap<String, List<SearchResultItem>>());
- } else {
- logger.debug(EELFLoggerDelegate.debugLogger, "searchPortal: user {}, search string '{}'",
- user.getLoginId(), searchString);
- Map<String, List<SearchResultItem>> results = searchService.searchResults(user.getLoginId(),
- searchString);
- /*Audit log the search*/
- AuditLog auditLog = new AuditLog();
- auditLog.setUserId(user.getId());
- auditLog.setActivityCode(EcompAuditLog.CD_ACTIVITY_SEARCH);
- auditLog.setComments(searchString);
- MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP,EPEELFLoggerAdvice.getCurrentDateTimeUTC());
- auditService.logActivity(auditLog, null);
- MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP,EPEELFLoggerAdvice.getCurrentDateTimeUTC());
- EcompPortalUtils.calculateDateTimeDifferenceForLog(MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
- logger.info(EELFLoggerDelegate.auditLogger, EPLogUtil.formatAuditLogMessage("DashboardController.PortalRestResponse",
- EcompAuditLog.CD_ACTIVITY_SEARCH, user.getOrgUserId(), null, searchString));
- MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
- MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
- MDC.remove(SystemProperties.MDC_TIMER);
- return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", results);
- }
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "searchPortal failed", e);
- return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage() + " - check logs.",
- new HashMap<String, List<SearchResultItem>>());
- }
- }
-
- /**
- * Gets all active users.
- *
- * TODO: should only the superuser be allowed to use this API?
- *
- * @param request
- * @return Rest response wrapped around a list of String
- */
- @RequestMapping(value = "/activeUsers", method = RequestMethod.GET, produces = "application/json")
- public List<String> getActiveUsers(HttpServletRequest request) {
- List<String> activeUsers = null;
- List<String> onlineUsers = new ArrayList<>();
- try {
- EPUser user = EPUserUtils.getUserSession(request);
- String userId = user.getOrgUserId();
-
- activeUsers = searchService.getRelatedUsers(userId);
- HashSet<String> usersSet = CollaborateList.getInstance().getAllUserName();
- for (String users : activeUsers) {
- if (usersSet.contains(users)) {
- onlineUsers.add(users);
- }
- }
-
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "getActiveUsers failed", e);
- }
- return onlineUsers;
- }
-
- /**
- * Gets the refresh interval and duration of a cycle of continuous refreshing for the online users side panel, both in milliseconds.
- *
- * @param request
- * @return Rest response wrapped around a number that is the number of milliseconds.
- */
- @RequestMapping(value = "/onlineUserUpdateRate", method = RequestMethod.GET, produces = "application/json")
- public PortalRestResponse<Map<String, String>> getOnlineUserUpdateRate(HttpServletRequest request) {
- try {
- String updateRate = SystemProperties.getProperty(EPCommonSystemProperties.ONLINE_USER_UPDATE_RATE);
- String updateDuration = SystemProperties.getProperty(EPCommonSystemProperties.ONLINE_USER_UPDATE_DURATION);
- Integer rateInMiliSec = Integer.valueOf(updateRate)*1000;
- Integer durationInMiliSec = Integer.valueOf(updateDuration)*1000;
- Map<String, String> results = new HashMap<String,String>();
- results.put("onlineUserUpdateRate", String.valueOf(rateInMiliSec));
- results.put("onlineUserUpdateDuration", String.valueOf(durationInMiliSec));
- return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", results);
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "getOnlineUserUpdateRate failed", e);
- return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.toString(), null);
- }
- }
-
- /**
- * Gets the window width threshold for collapsing right menu from system.properties.
- *
- * @param request
- * @return Rest response wrapped around a number that is the window width threshold to collapse right menu.
- */
- @RequestMapping(value = "/windowWidthThresholdRightMenu", method = RequestMethod.GET, produces = "application/json")
- public PortalRestResponse<Map<String, String>> getWindowWidthThresholdForRightMenu(HttpServletRequest request) {
- try {
- String windowWidthString = SystemProperties.getProperty(EPCommonSystemProperties.WINDOW_WIDTH_THRESHOLD_RIGHT_MENU);
- Integer windowWidth = Integer.valueOf(windowWidthString);
- Map<String, String> results = new HashMap<String,String>();
- results.put("windowWidth", String.valueOf(windowWidth));
- return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", results);
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "getWindowWidthThresholdForRightMenu failed", e);
- return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.toString(), null);
- }
- }
-
-
- /**
- * Gets the window width threshold for collapsing left menu from system.properties.
- *
- * @param request
- * @return Rest response wrapped around a number that is the window width threshold to collapse the left menu.
- */
- @RequestMapping(value = "/windowWidthThresholdLeftMenu", method = RequestMethod.GET, produces = "application/json")
- public PortalRestResponse<Map<String, String>> getWindowWidthThresholdForLeftMenu(HttpServletRequest request) {
- try {
- String windowWidthString = SystemProperties.getProperty(EPCommonSystemProperties.WINDOW_WIDTH_THRESHOLD_LEFT_MENU);
- Integer windowWidth = Integer.valueOf(windowWidthString);
- Map<String, String> results = new HashMap<String,String>();
- results.put("windowWidth", String.valueOf(windowWidth));
- return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", results);
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "getWindowWidthThresholdForLeftMenu failed", e);
- return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.toString(), null);
- }
- }
-
- /**
- * Gets only those users that are 'related' to the currently logged-in user.
- *
- * @param request
- * @return Rest response wrapped around a List of String
- */
- @RequestMapping(value = "/relatedUsers", method = RequestMethod.GET, produces = "application/json")
- public PortalRestResponse<List<String>> activeUsers(HttpServletRequest request) {
- EPUser user = EPUserUtils.getUserSession(request);
- try {
- if (user == null) {
- return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "User object is null? - check logs",
- new ArrayList<>());
- } else {
- logger.debug(EELFLoggerDelegate.debugLogger, "activeUsers: searching for user {}", user.getLoginId());
- return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success",
- searchService.getRelatedUsers(user.getLoginId()));
- }
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "activeUsers failed", e);
- return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage() + " - check logs.",
- new ArrayList<>());
- }
- }
-
-}
+/*-
+ * ================================================================================
+ * ECOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.controller;
+
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+
+import javax.servlet.http.HttpServletRequest;
+
+import org.openecomp.portalapp.controller.EPRestrictedBaseController;
+import org.openecomp.portalapp.portal.domain.EPUser;
+import org.openecomp.portalapp.portal.domain.EcompAuditLog;
+import org.openecomp.portalapp.portal.ecomp.model.PortalRestResponse;
+import org.openecomp.portalapp.portal.ecomp.model.PortalRestStatusEnum;
+import org.openecomp.portalapp.portal.ecomp.model.SearchResultItem;
+import org.openecomp.portalapp.portal.logging.aop.EPAuditLog;
+import org.openecomp.portalapp.portal.logging.aop.EPEELFLoggerAdvice;
+import org.openecomp.portalapp.portal.logging.logic.EPLogUtil;
+import org.openecomp.portalapp.portal.service.DashboardSearchService;
+import org.openecomp.portalapp.portal.transport.CommonWidget;
+import org.openecomp.portalapp.portal.transport.CommonWidgetMeta;
+import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties;
+import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
+import org.openecomp.portalapp.util.EPUserUtils;
+import org.openecomp.portalsdk.core.domain.AuditLog;
+import org.openecomp.portalsdk.core.domain.support.CollaborateList;
+import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.openecomp.portalsdk.core.service.AuditService;
+import org.openecomp.portalsdk.core.util.SystemProperties;
+import org.slf4j.MDC;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.RequestParam;
+import org.springframework.web.bind.annotation.RestController;
+
+/**
+ * Controller supplies data to Angular services on the dashboard page.
+ */
+@Configuration
+@RestController
+@RequestMapping("/portalApi/dashboard")
+public class DashboardController extends EPRestrictedBaseController {
+
+ private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(DashboardController.class);
+
+ @Autowired
+ private DashboardSearchService searchService;
+ @Autowired
+ private AuditService auditService;
+
+ public enum WidgetCategory {
+ EVENTS, NEWS, IMPORTANTRESOURCES;
+ }
+
+ /**
+ * Validates the resource type parameter.
+ *
+ * @param resourceType
+ * @return True if known in the enum WidgetCategory, else false.
+ */
+ private boolean isValidResourceType(String resourceType) {
+ if (resourceType == null)
+ return false;
+ for (WidgetCategory wc : WidgetCategory.values())
+ if (wc.name().equals(resourceType))
+ return true;
+ return false;
+ }
+
+ /**
+ * Gets all widgets of the specified resource type.
+ * In iteration 41 (when widget will utilized service onboarding), this method can be removed, instead we will use CommonWidgetController.java (basic auth based)
+ *
+ * @param request
+ * @param resourceType
+ * Request parameter.
+ * @return Rest response wrapped around a CommonWidgetMeta object.
+ */
+ @RequestMapping(value = "/widgetData", method = RequestMethod.GET, produces = "application/json")
+ public PortalRestResponse<CommonWidgetMeta> getWidgetData(HttpServletRequest request,
+ @RequestParam String resourceType) {
+ if (!isValidResourceType(resourceType))
+ return new PortalRestResponse<CommonWidgetMeta>(PortalRestStatusEnum.ERROR,
+ "Unexpected resource type " + resourceType, null);
+ return new PortalRestResponse<CommonWidgetMeta>(PortalRestStatusEnum.OK, "success",
+ searchService.getWidgetData(resourceType));
+ }
+
+
+ /**
+ * Saves a batch of events, news or resources.
+ *
+ * @param commonWidgetMeta
+ * read from POST body.
+ * @return Rest response wrapped around a String; e.g., "success" or "ERROR"
+ */
+ @RequestMapping(value = "/widgetDataBulk", method = RequestMethod.POST, produces = "application/json")
+ public PortalRestResponse<String> saveWidgetDataBulk(@RequestBody CommonWidgetMeta commonWidgetMeta) {
+ logger.debug(EELFLoggerDelegate.debugLogger, "saveWidgetDataBulk: argument is {}", commonWidgetMeta);
+ if (commonWidgetMeta.getCategory() == null || commonWidgetMeta.getCategory().trim().equals(""))
+ return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "ERROR",
+ "Category cannot be null or empty");
+ if (!isValidResourceType(commonWidgetMeta.getCategory()))
+ return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR,
+ "Unexpected resource type " + commonWidgetMeta.getCategory(), null);
+ // validate dates
+ for (CommonWidget cw : commonWidgetMeta.getItems()) {
+ String err = validateCommonWidget(cw);
+ if (err != null)
+ return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, err, null);
+ }
+ return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "success",
+ searchService.saveWidgetDataBulk(commonWidgetMeta));
+ }
+
+ /**
+ * Saves one: event, news or resource
+ *
+ * @param commonWidget
+ * read from POST body
+ * @return Rest response wrapped around a String; e.g., "success" or "ERROR"
+ */
+ @RequestMapping(value = "/widgetData", method = RequestMethod.POST, produces = "application/json")
+ public PortalRestResponse<String> saveWidgetData(@RequestBody CommonWidget commonWidget) {
+ logger.debug(EELFLoggerDelegate.debugLogger, "saveWidgetData: argument is {}", commonWidget);
+ if (commonWidget.getCategory() == null || commonWidget.getCategory().trim().equals(""))
+ return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "ERROR",
+ "Category cannot be null or empty");
+ String err = validateCommonWidget(commonWidget);
+ if (err != null)
+ return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, err, null);
+ return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "success",
+ searchService.saveWidgetData(commonWidget));
+ }
+
+ /**
+ * Used by the validate function
+ */
+ private final SimpleDateFormat yearMonthDayFormat = new SimpleDateFormat("yyyy-MM-dd");
+
+ /**
+ * Validates the content of a common widget.
+ *
+ * @param cw
+ * @return null on success; an error message if validation fails.
+ * @throws Exception
+ */
+ private String validateCommonWidget(CommonWidget cw) {
+ if (!isValidResourceType(cw.getCategory()))
+ return "Invalid category: " + cw.getCategory();
+ if (cw.getTitle() == null || cw.getTitle().trim().length() == 0)
+ return "Title is missing";
+ if (cw.getHref() == null || cw.getHref().trim().length() == 0)
+ return "HREF is missing";
+ if (!cw.getHref().toLowerCase().startsWith("http"))
+ return "HREF does not start with http";
+ if (cw.getSortOrder() == null)
+ return "Sort order is null";
+ if (WidgetCategory.EVENTS.name().equals(cw.getCategory())) {
+ if (cw.getEventDate() == null || cw.getEventDate().trim().length() == 0)
+ return "Date is missing";
+ try {
+ yearMonthDayFormat.setLenient(false);
+ Date date = yearMonthDayFormat.parse(cw.getEventDate());
+ if (date == null)
+ return "Failed to parse date " + cw.getEventDate();
+ } catch (ParseException ex) {
+ return ex.toString();
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Deletes one: event, news or resource
+ *
+ * @param commonWidget
+ * read from POST body
+ * @return Rest response wrapped around a String; e.g., "success" or "ERROR"
+ */
+ @RequestMapping(value = "/deleteData", method = RequestMethod.POST, produces = "application/json")
+ public PortalRestResponse<String> deleteWidgetData(@RequestBody CommonWidget commonWidget) {
+ logger.debug(EELFLoggerDelegate.debugLogger, "deleteWidgetData: argument is {}", commonWidget);
+ return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "success",
+ searchService.deleteWidgetData(commonWidget));
+ }
+
+ /**
+ * Searches all portal for the input string.
+ *
+ * @param request
+ * @param searchString
+ * @return Rest response wrapped around a Map of String to List of Search
+ * Result Item.
+ */
+ @EPAuditLog
+ @RequestMapping(value = "/search", method = RequestMethod.GET, produces = "application/json")
+ public PortalRestResponse<Map<String, List<SearchResultItem>>> searchPortal(HttpServletRequest request,
+ @RequestParam String searchString) {
+
+ if (searchString != null)
+ searchString = searchString.trim();
+ EPUser user = EPUserUtils.getUserSession(request);
+ try {
+ if (user == null) {
+ return new PortalRestResponse<>(PortalRestStatusEnum.ERROR,
+ "searchPortal: User object is null? - check logs",
+ new HashMap<String, List<SearchResultItem>>());
+ } else if (searchString == null || searchString.length() == 0) {
+ return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "searchPortal: String string is null",
+ new HashMap<String, List<SearchResultItem>>());
+ } else {
+ logger.debug(EELFLoggerDelegate.debugLogger, "searchPortal: user {}, search string '{}'",
+ user.getLoginId(), searchString);
+ Map<String, List<SearchResultItem>> results = searchService.searchResults(user.getLoginId(),
+ searchString);
+ /*Audit log the search*/
+ AuditLog auditLog = new AuditLog();
+ auditLog.setUserId(user.getId());
+ auditLog.setActivityCode(EcompAuditLog.CD_ACTIVITY_SEARCH);
+ auditLog.setComments(searchString);
+ MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP,EPEELFLoggerAdvice.getCurrentDateTimeUTC());
+ auditService.logActivity(auditLog, null);
+ MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP,EPEELFLoggerAdvice.getCurrentDateTimeUTC());
+ EcompPortalUtils.calculateDateTimeDifferenceForLog(MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
+ logger.info(EELFLoggerDelegate.auditLogger, EPLogUtil.formatAuditLogMessage("DashboardController.PortalRestResponse",
+ EcompAuditLog.CD_ACTIVITY_SEARCH, user.getOrgUserId(), null, searchString));
+ MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
+ MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
+ MDC.remove(SystemProperties.MDC_TIMER);
+ return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", results);
+ }
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "searchPortal failed", e);
+ return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage() + " - check logs.",
+ new HashMap<String, List<SearchResultItem>>());
+ }
+ }
+
+ /**
+ * Gets all active users.
+ *
+ * TODO: should only the superuser be allowed to use this API?
+ *
+ * @param request
+ * @return Rest response wrapped around a list of String
+ */
+ @RequestMapping(value = "/activeUsers", method = RequestMethod.GET, produces = "application/json")
+ public List<String> getActiveUsers(HttpServletRequest request) {
+ List<String> activeUsers = null;
+ List<String> onlineUsers = new ArrayList<>();
+ try {
+ EPUser user = EPUserUtils.getUserSession(request);
+ String userId = user.getOrgUserId();
+
+ activeUsers = searchService.getRelatedUsers(userId);
+ HashSet<String> usersSet = CollaborateList.getInstance().getAllUserName();
+ for (String users : activeUsers) {
+ if (usersSet.contains(users)) {
+ onlineUsers.add(users);
+ }
+ }
+
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "getActiveUsers failed", e);
+ }
+ return onlineUsers;
+ }
+
+ /**
+ * Gets the refresh interval and duration of a cycle of continuous refreshing for the online users side panel, both in milliseconds.
+ *
+ * @param request
+ * @return Rest response wrapped around a number that is the number of milliseconds.
+ */
+ @RequestMapping(value = "/onlineUserUpdateRate", method = RequestMethod.GET, produces = "application/json")
+ public PortalRestResponse<Map<String, String>> getOnlineUserUpdateRate(HttpServletRequest request) {
+ try {
+ String updateRate = SystemProperties.getProperty(EPCommonSystemProperties.ONLINE_USER_UPDATE_RATE);
+ String updateDuration = SystemProperties.getProperty(EPCommonSystemProperties.ONLINE_USER_UPDATE_DURATION);
+ Integer rateInMiliSec = Integer.valueOf(updateRate)*1000;
+ Integer durationInMiliSec = Integer.valueOf(updateDuration)*1000;
+ Map<String, String> results = new HashMap<String,String>();
+ results.put("onlineUserUpdateRate", String.valueOf(rateInMiliSec));
+ results.put("onlineUserUpdateDuration", String.valueOf(durationInMiliSec));
+ return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", results);
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "getOnlineUserUpdateRate failed", e);
+ return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.toString(), null);
+ }
+ }
+
+ /**
+ * Gets the window width threshold for collapsing right menu from system.properties.
+ *
+ * @param request
+ * @return Rest response wrapped around a number that is the window width threshold to collapse right menu.
+ */
+ @RequestMapping(value = "/windowWidthThresholdRightMenu", method = RequestMethod.GET, produces = "application/json")
+ public PortalRestResponse<Map<String, String>> getWindowWidthThresholdForRightMenu(HttpServletRequest request) {
+ try {
+ String windowWidthString = SystemProperties.getProperty(EPCommonSystemProperties.WINDOW_WIDTH_THRESHOLD_RIGHT_MENU);
+ Integer windowWidth = Integer.valueOf(windowWidthString);
+ Map<String, String> results = new HashMap<String,String>();
+ results.put("windowWidth", String.valueOf(windowWidth));
+ return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", results);
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "getWindowWidthThresholdForRightMenu failed", e);
+ return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.toString(), null);
+ }
+ }
+
+
+ /**
+ * Gets the window width threshold for collapsing left menu from system.properties.
+ *
+ * @param request
+ * @return Rest response wrapped around a number that is the window width threshold to collapse the left menu.
+ */
+ @RequestMapping(value = "/windowWidthThresholdLeftMenu", method = RequestMethod.GET, produces = "application/json")
+ public PortalRestResponse<Map<String, String>> getWindowWidthThresholdForLeftMenu(HttpServletRequest request) {
+ try {
+ String windowWidthString = SystemProperties.getProperty(EPCommonSystemProperties.WINDOW_WIDTH_THRESHOLD_LEFT_MENU);
+ Integer windowWidth = Integer.valueOf(windowWidthString);
+ Map<String, String> results = new HashMap<String,String>();
+ results.put("windowWidth", String.valueOf(windowWidth));
+ return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", results);
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "getWindowWidthThresholdForLeftMenu failed", e);
+ return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.toString(), null);
+ }
+ }
+
+ /**
+ * Gets only those users that are 'related' to the currently logged-in user.
+ *
+ * @param request
+ * @return Rest response wrapped around a List of String
+ */
+ @RequestMapping(value = "/relatedUsers", method = RequestMethod.GET, produces = "application/json")
+ public PortalRestResponse<List<String>> activeUsers(HttpServletRequest request) {
+ EPUser user = EPUserUtils.getUserSession(request);
+ try {
+ if (user == null) {
+ return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "User object is null? - check logs",
+ new ArrayList<>());
+ } else {
+ logger.debug(EELFLoggerDelegate.debugLogger, "activeUsers: searching for user {}", user.getLoginId());
+ return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success",
+ searchService.getRelatedUsers(user.getLoginId()));
+ }
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "activeUsers failed", e);
+ return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage() + " - check logs.",
+ new ArrayList<>());
+ }
+ }
+
+}
diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/ExternalAppsRestfulController.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/ExternalAppsRestfulController.java
index 41da3357..ac1b9254 100644
--- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/ExternalAppsRestfulController.java
+++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/ExternalAppsRestfulController.java
@@ -1,206 +1,206 @@
-/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.controller;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Calendar;
-import java.util.List;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.openecomp.portalapp.controller.EPRestrictedRESTfulBaseController;
-import org.openecomp.portalapp.portal.domain.EPApp;
-import org.openecomp.portalapp.portal.domain.EPRole;
-import org.openecomp.portalapp.portal.domain.EPUser;
-import org.openecomp.portalapp.portal.logging.aop.EPAuditLog;
-import org.openecomp.portalapp.portal.service.AdminRolesService;
-import org.openecomp.portalapp.portal.service.EPLoginService;
-import org.openecomp.portalapp.portal.service.EPRoleService;
-import org.openecomp.portalapp.portal.service.FunctionalMenuService;
-import org.openecomp.portalapp.portal.service.UserNotificationService;
-import org.openecomp.portalapp.portal.transport.EpNotificationItem;
-import org.openecomp.portalapp.portal.transport.FavoritesFunctionalMenuItemJson;
-import org.openecomp.portalapp.portal.transport.FieldsValidator;
-import org.openecomp.portalapp.portal.transport.FunctionalMenuItem;
-import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties;
-import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
-import org.openecomp.portalapp.portal.utils.PortalConstants;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalsdk.core.onboarding.crossapi.PortalAPIResponse;
-import org.slf4j.MDC;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.context.annotation.EnableAspectJAutoProxy;
-import org.springframework.http.HttpStatus;
-import org.springframework.web.bind.annotation.ExceptionHandler;
-import org.springframework.web.bind.annotation.RequestBody;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestMethod;
-import org.springframework.web.bind.annotation.ResponseBody;
-import org.springframework.web.bind.annotation.RestController;
-
-import io.swagger.annotations.ApiOperation;
-
-@RestController
-@RequestMapping(PortalConstants.REST_AUX_API)
-@Configuration
-@EnableAspectJAutoProxy
-@EPAuditLog
-public class ExternalAppsRestfulController extends EPRestrictedRESTfulBaseController {
-
- private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ExternalAppsRestfulController.class);
-
- @Autowired
- private FunctionalMenuService functionalMenuService;
-
- @Autowired
- private EPLoginService epLoginService;
-
- @Autowired
- private AdminRolesService adminRolesService;
-
- @Autowired
- private UserNotificationService userNotificationService;
-
- @Autowired
- private EPRoleService epRoleService;
-
- @ApiOperation(value = "Creates a Portal user notification for roles identified in the content from an external application.", response = PortalAPIResponse.class)
- @RequestMapping(value = { "/publishNotification" }, method = RequestMethod.POST, produces = "application/json")
- @ResponseBody
- public PortalAPIResponse publishNotification(HttpServletRequest request,
- @RequestBody EpNotificationItem notificationItem) throws Exception {
- String appKey = request.getHeader("uebkey");
- EPApp app = findEpApp(appKey);
- List<Long> postRoleIds = new ArrayList<Long>();
- for (Long roleId : notificationItem.getRoleIds()) {
- EPRole role = epRoleService.getRole(app.getId(), roleId);
- if (role != null)
- postRoleIds.add(role.getId());
- }
-
- // --- recreate the user notification object with the POrtal Role Ids
- EpNotificationItem postItem = new EpNotificationItem();
- postItem.setRoleIds(postRoleIds);
- postItem.setIsForAllRoles("N");
- postItem.setIsForOnlineUsers("N");
- postItem.setActiveYn("Y");
- postItem.setPriority(notificationItem.getPriority());
- postItem.setMsgHeader(notificationItem.getMsgHeader());
- postItem.setMsgDescription(notificationItem.getMsgDescription());
- postItem.setStartTime(notificationItem.getStartTime());
- postItem.setEndTime(notificationItem.getEndTime());
- postItem.setCreatedDate(Calendar.getInstance().getTime());
- // default creator to 1 for now
- postItem.setCreatorId(PortalConstants.DEFAULT_NOTIFICATION_CREATOR);
- // ----
-
- try {
- userNotificationService.saveNotification(postItem);
- } catch (Exception e) {
- return new PortalAPIResponse(false, e.getMessage());
- }
-
- PortalAPIResponse response = new PortalAPIResponse(true, "success");
- return response;
- }
-
- private EPApp findEpApp(String uebKey) {
- List<?> list = null;
- StringBuffer criteria = new StringBuffer();
- criteria.append(" where ueb_key = '" + uebKey + "'");
- list = getDataAccessService().getList(EPApp.class, criteria.toString(), null, null);
- return (list == null || list.size() == 0) ? null : (EPApp) list.get(0);
- }
-
- @ApiOperation(value = "Gets favorite items within the functional menu for the current user.", response = FavoritesFunctionalMenuItemJson.class, responseContainer="List")
- @RequestMapping(value = { "/getFavorites" }, method = RequestMethod.GET, produces = "application/json")
- public List<FavoritesFunctionalMenuItemJson> getFavoritesForUser(HttpServletRequest request,
- HttpServletResponse response) throws Exception {
- String loginId = "";
- String userAgent = "";
- List<FavoritesFunctionalMenuItemJson> favorites = null;
-
- loginId = request.getHeader(EPCommonSystemProperties.MDC_LOGIN_ID);
- userAgent = MDC.get(EPCommonSystemProperties.PARTNER_NAME);
-
- EPUser epUser = epLoginService.findUserWithoutPwd(loginId);
- logger.info(EELFLoggerDelegate.errorLogger,
- "getFavorites request was received from " + userAgent + " for the user " + loginId + ".");
- if (epUser == null || epUser.getId() == null) {
- logger.error(EELFLoggerDelegate.errorLogger,
- "No User record found for the LoginId '" + loginId + "' in the database.");
- throw new Exception("Received null for Login-Id.");
- } else {
- favorites = functionalMenuService.getFavoriteItems(epUser.getId());
- FieldsValidator fieldsValidator = new FieldsValidator();
- response.setStatus(fieldsValidator.httpStatusCode.intValue());
-
- EcompPortalUtils.logAndSerializeObject(logger, "/getFavorites", "result = ", favorites);
- }
-
- return favorites;
- }
-
- @ApiOperation(value = "Gets functional menu items appropriate for the current user.", response = FunctionalMenuItem.class, responseContainer="List")
- @RequestMapping(value = {
- "/functionalMenuItemsForUser" }, method = RequestMethod.GET, produces = "application/json")
- public List<FunctionalMenuItem> getFunctionalMenuItemsForUser(HttpServletRequest request,
- HttpServletResponse response) throws Exception {
- String loginId = "";
- String userAgent = "";
- List<FunctionalMenuItem> fnMenuItems = null;
-
- loginId = request.getHeader("LoginId");
- userAgent = MDC.get(EPCommonSystemProperties.PARTNER_NAME);
-
- EPUser epUser = epLoginService.findUserWithoutPwd(loginId);
- logger.info(EELFLoggerDelegate.errorLogger, "getFunctionalMenuItemsForUser request was received from "
- + userAgent + " for the user " + loginId + ".");
- if (epUser == null || epUser.getId() == null) {
- logger.error(EELFLoggerDelegate.errorLogger,
- "No User record found for the LoginId '" + loginId + "' in the database.");
- throw new Exception("Received null for Login-Id.");
- } else if (adminRolesService.isSuperAdmin(epUser)) {
- logger.debug(EELFLoggerDelegate.debugLogger,
- "FunctionalMenuHandler: SuperUser, about to call getFunctionalMenuItems()");
- fnMenuItems = functionalMenuService.getFunctionalMenuItems();
- } else {
- logger.debug(EELFLoggerDelegate.debugLogger,
- "getMenuItemsForAuthUser: about to call getFunctionalMenuItemsForUser()");
- fnMenuItems = functionalMenuService.getFunctionalMenuItemsForUser(epUser.getOrgUserId());
- }
-
- FieldsValidator fieldsValidator = new FieldsValidator();
- response.setStatus(fieldsValidator.httpStatusCode.intValue());
-
- EcompPortalUtils.logAndSerializeObject(logger, "/functionalMenuItemsForUser", "result = ", fnMenuItems);
-
- return fnMenuItems;
- }
-
- @ExceptionHandler(Exception.class)
- protected void handleBadRequests(Exception e, HttpServletResponse response) throws IOException {
- logger.warn(EELFLoggerDelegate.errorLogger, "Handling bad request", e);
- response.sendError(HttpStatus.BAD_REQUEST.value(), e.getMessage());
- }
-}
+/*-
+ * ================================================================================
+ * ECOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.controller;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Calendar;
+import java.util.List;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.openecomp.portalapp.controller.EPRestrictedRESTfulBaseController;
+import org.openecomp.portalapp.portal.domain.EPApp;
+import org.openecomp.portalapp.portal.domain.EPRole;
+import org.openecomp.portalapp.portal.domain.EPUser;
+import org.openecomp.portalapp.portal.logging.aop.EPAuditLog;
+import org.openecomp.portalapp.portal.service.AdminRolesService;
+import org.openecomp.portalapp.portal.service.EPLoginService;
+import org.openecomp.portalapp.portal.service.EPRoleService;
+import org.openecomp.portalapp.portal.service.FunctionalMenuService;
+import org.openecomp.portalapp.portal.service.UserNotificationService;
+import org.openecomp.portalapp.portal.transport.EpNotificationItem;
+import org.openecomp.portalapp.portal.transport.FavoritesFunctionalMenuItemJson;
+import org.openecomp.portalapp.portal.transport.FieldsValidator;
+import org.openecomp.portalapp.portal.transport.FunctionalMenuItem;
+import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties;
+import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
+import org.openecomp.portalapp.portal.utils.PortalConstants;
+import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.openecomp.portalsdk.core.onboarding.crossapi.PortalAPIResponse;
+import org.slf4j.MDC;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.EnableAspectJAutoProxy;
+import org.springframework.http.HttpStatus;
+import org.springframework.web.bind.annotation.ExceptionHandler;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.ResponseBody;
+import org.springframework.web.bind.annotation.RestController;
+
+import io.swagger.annotations.ApiOperation;
+
+@RestController
+@RequestMapping(PortalConstants.REST_AUX_API)
+@Configuration
+@EnableAspectJAutoProxy
+@EPAuditLog
+public class ExternalAppsRestfulController extends EPRestrictedRESTfulBaseController {
+
+ private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ExternalAppsRestfulController.class);
+
+ @Autowired
+ private FunctionalMenuService functionalMenuService;
+
+ @Autowired
+ private EPLoginService epLoginService;
+
+ @Autowired
+ private AdminRolesService adminRolesService;
+
+ @Autowired
+ private UserNotificationService userNotificationService;
+
+ @Autowired
+ private EPRoleService epRoleService;
+
+ @ApiOperation(value = "Creates a Portal user notification for roles identified in the content from an external application.", response = PortalAPIResponse.class)
+ @RequestMapping(value = { "/publishNotification" }, method = RequestMethod.POST, produces = "application/json")
+ @ResponseBody
+ public PortalAPIResponse publishNotification(HttpServletRequest request,
+ @RequestBody EpNotificationItem notificationItem) throws Exception {
+ String appKey = request.getHeader("uebkey");
+ EPApp app = findEpApp(appKey);
+ List<Long> postRoleIds = new ArrayList<Long>();
+ for (Long roleId : notificationItem.getRoleIds()) {
+ EPRole role = epRoleService.getRole(app.getId(), roleId);
+ if (role != null)
+ postRoleIds.add(role.getId());
+ }
+
+ // --- recreate the user notification object with the POrtal Role Ids
+ EpNotificationItem postItem = new EpNotificationItem();
+ postItem.setRoleIds(postRoleIds);
+ postItem.setIsForAllRoles("N");
+ postItem.setIsForOnlineUsers("N");
+ postItem.setActiveYn("Y");
+ postItem.setPriority(notificationItem.getPriority());
+ postItem.setMsgHeader(notificationItem.getMsgHeader());
+ postItem.setMsgDescription(notificationItem.getMsgDescription());
+ postItem.setStartTime(notificationItem.getStartTime());
+ postItem.setEndTime(notificationItem.getEndTime());
+ postItem.setCreatedDate(Calendar.getInstance().getTime());
+ // default creator to 1 for now
+ postItem.setCreatorId(PortalConstants.DEFAULT_NOTIFICATION_CREATOR);
+ // ----
+
+ try {
+ userNotificationService.saveNotification(postItem);
+ } catch (Exception e) {
+ return new PortalAPIResponse(false, e.getMessage());
+ }
+
+ PortalAPIResponse response = new PortalAPIResponse(true, "success");
+ return response;
+ }
+
+ private EPApp findEpApp(String uebKey) {
+ List<?> list = null;
+ StringBuffer criteria = new StringBuffer();
+ criteria.append(" where ueb_key = '" + uebKey + "'");
+ list = getDataAccessService().getList(EPApp.class, criteria.toString(), null, null);
+ return (list == null || list.size() == 0) ? null : (EPApp) list.get(0);
+ }
+
+ @ApiOperation(value = "Gets favorite items within the functional menu for the current user.", response = FavoritesFunctionalMenuItemJson.class, responseContainer="List")
+ @RequestMapping(value = { "/getFavorites" }, method = RequestMethod.GET, produces = "application/json")
+ public List<FavoritesFunctionalMenuItemJson> getFavoritesForUser(HttpServletRequest request,
+ HttpServletResponse response) throws Exception {
+ String loginId = "";
+ String userAgent = "";
+ List<FavoritesFunctionalMenuItemJson> favorites = null;
+
+ loginId = request.getHeader(EPCommonSystemProperties.MDC_LOGIN_ID);
+ userAgent = MDC.get(EPCommonSystemProperties.PARTNER_NAME);
+
+ EPUser epUser = epLoginService.findUserWithoutPwd(loginId);
+ logger.info(EELFLoggerDelegate.errorLogger,
+ "getFavorites request was received from " + userAgent + " for the user " + loginId + ".");
+ if (epUser == null || epUser.getId() == null) {
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "No User record found for the LoginId '" + loginId + "' in the database.");
+ throw new Exception("Received null for Login-Id.");
+ } else {
+ favorites = functionalMenuService.getFavoriteItems(epUser.getId());
+ FieldsValidator fieldsValidator = new FieldsValidator();
+ response.setStatus(fieldsValidator.httpStatusCode.intValue());
+
+ EcompPortalUtils.logAndSerializeObject(logger, "/getFavorites", "result = ", favorites);
+ }
+
+ return favorites;
+ }
+
+ @ApiOperation(value = "Gets functional menu items appropriate for the current user.", response = FunctionalMenuItem.class, responseContainer="List")
+ @RequestMapping(value = {
+ "/functionalMenuItemsForUser" }, method = RequestMethod.GET, produces = "application/json")
+ public List<FunctionalMenuItem> getFunctionalMenuItemsForUser(HttpServletRequest request,
+ HttpServletResponse response) throws Exception {
+ String loginId = "";
+ String userAgent = "";
+ List<FunctionalMenuItem> fnMenuItems = null;
+
+ loginId = request.getHeader("LoginId");
+ userAgent = MDC.get(EPCommonSystemProperties.PARTNER_NAME);
+
+ EPUser epUser = epLoginService.findUserWithoutPwd(loginId);
+ logger.info(EELFLoggerDelegate.errorLogger, "getFunctionalMenuItemsForUser request was received from "
+ + userAgent + " for the user " + loginId + ".");
+ if (epUser == null || epUser.getId() == null) {
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "No User record found for the LoginId '" + loginId + "' in the database.");
+ throw new Exception("Received null for Login-Id.");
+ } else if (adminRolesService.isSuperAdmin(epUser)) {
+ logger.debug(EELFLoggerDelegate.debugLogger,
+ "FunctionalMenuHandler: SuperUser, about to call getFunctionalMenuItems()");
+ fnMenuItems = functionalMenuService.getFunctionalMenuItems();
+ } else {
+ logger.debug(EELFLoggerDelegate.debugLogger,
+ "getMenuItemsForAuthUser: about to call getFunctionalMenuItemsForUser()");
+ fnMenuItems = functionalMenuService.getFunctionalMenuItemsForUser(epUser.getOrgUserId());
+ }
+
+ FieldsValidator fieldsValidator = new FieldsValidator();
+ response.setStatus(fieldsValidator.httpStatusCode.intValue());
+
+ EcompPortalUtils.logAndSerializeObject(logger, "/functionalMenuItemsForUser", "result = ", fnMenuItems);
+
+ return fnMenuItems;
+ }
+
+ @ExceptionHandler(Exception.class)
+ protected void handleBadRequests(Exception e, HttpServletResponse response) throws IOException {
+ logger.warn(EELFLoggerDelegate.errorLogger, "Handling bad request", e);
+ response.sendError(HttpStatus.BAD_REQUEST.value(), e.getMessage());
+ }
+}
diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/FunctionalMenuController.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/FunctionalMenuController.java
index de71766d..490a1829 100644
--- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/FunctionalMenuController.java
+++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/FunctionalMenuController.java
@@ -1,555 +1,662 @@
-/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.controller;
-
-import java.io.IOException;
-import java.text.SimpleDateFormat;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.apache.cxf.transport.http.HTTPException;
-import org.json.JSONObject;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.EnableAspectJAutoProxy;
-import org.springframework.web.bind.annotation.PathVariable;
-import org.springframework.web.bind.annotation.RequestBody;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestMethod;
-import org.springframework.web.bind.annotation.RequestParam;
-import org.springframework.web.bind.annotation.RestController;
-
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalsdk.core.service.UserProfileService;
-import org.openecomp.portalapp.controller.EPRestrictedBaseController;
-import org.openecomp.portalapp.portal.domain.EPUser;
-import org.openecomp.portalapp.portal.domain.SharedContext;
-import org.openecomp.portalapp.portal.logging.aop.EPAuditLog;
-import org.openecomp.portalapp.portal.service.AdminRolesService;
-import org.openecomp.portalapp.portal.service.EPAuditService;
-import org.openecomp.portalapp.portal.service.FunctionalMenuService;
-import org.openecomp.portalapp.portal.service.SearchService;
-import org.openecomp.portalapp.portal.service.SharedContextService;
-import org.openecomp.portalapp.portal.transport.BusinessCardApplicationRole;
-import org.openecomp.portalapp.portal.transport.BusinessCardApplicationRolesList;
-import org.openecomp.portalapp.portal.transport.FavoritesFunctionalMenuItem;
-import org.openecomp.portalapp.portal.transport.FavoritesFunctionalMenuItemJson;
-import org.openecomp.portalapp.portal.transport.FieldsValidator;
-import org.openecomp.portalapp.portal.transport.FunctionalMenuItem;
-import org.openecomp.portalapp.portal.transport.FunctionalMenuItemWithRoles;
-import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties;
-import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
-import org.openecomp.portalapp.util.EPUserUtils;
-
-/**
- * Supports menus at the top of the Portal app landing page.
- */
-@RestController
-@org.springframework.context.annotation.Configuration
-@EnableAspectJAutoProxy
-@EPAuditLog
-public class FunctionalMenuController extends EPRestrictedBaseController {
- EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(FunctionalMenuController.class);
-
- @Autowired
- AdminRolesService adminRolesService;
- @Autowired
- FunctionalMenuService functionalMenuService;
- @Autowired
- SharedContextService sharedContextService;
- @Autowired
- UserProfileService service;
- @Autowired
- SearchService searchService;
- @Autowired
- EPAuditService epAuditService;
-
- /**
- * RESTful service method to fetch all the FunctionalMenuItems.
- *
- * @return List of FunctionalMenuItem objects
- */
- @RequestMapping(value = { "/portalApi/functionalMenu" }, method = RequestMethod.GET, produces = "application/json")
- public List<FunctionalMenuItem> getMenuItems(HttpServletRequest request, HttpServletResponse response) {
- // TODO: should only the superuser be allowed to use this API?
- List<FunctionalMenuItem> menuItems = null;
- try {
- menuItems = functionalMenuService.getFunctionalMenuItems();
- functionalMenuService.assignHelpURLs(menuItems);
- EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/functionalMenu", "result =", menuItems);
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger,
- "Exception occurred while calling functionalMenu. Details: " + EcompPortalUtils.getStackTrace(e));
- }
- return menuItems;
- }
-
- /**
- * RESTful service method to fetch all the FunctionalMenuItems, both active
- * and inactive, for the EditFunctionalMenu feature. Can only be accessed by
- * the portal admin.
- *
- * @return List of FunctionalMenuItem objects
- */
- @RequestMapping(value = {
- "/portalApi/functionalMenuForEditing" }, method = RequestMethod.GET, produces = "application/json")
- public List<FunctionalMenuItem> getMenuItemsForEditing(HttpServletRequest request, HttpServletResponse response) {
- // TODO: should only the superuser be allowed to use this API?
- EPUser user = EPUserUtils.getUserSession(request);
- List<FunctionalMenuItem> menuItems = null;
- try {
- if (!adminRolesService.isSuperAdmin(user)) {
- EcompPortalUtils.setBadPermissions(user, response, "getFunctionalMenuItemDetails");
- } else {
- menuItems = functionalMenuService.getFunctionalMenuItems(true);
- }
- EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/functionalMenuForEditing", "result =", menuItems);
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger,
- "Exception occurred while calling functionalMenuForEditing. Details: "
- + EcompPortalUtils.getStackTrace(e));
- }
- return menuItems;
- }
-
- /**
- * RESTful service method to fetch all the FunctionalMenuItems, active
- *, for the Functional menu in notification Tree feature.
- *
- * @return List of FunctionalMenuItem objects
- */
- @RequestMapping(value = {
- "/portalApi/functionalMenuForNotificationTree" }, method = RequestMethod.GET, produces = "application/json")
- public List<FunctionalMenuItem> getMenuItemsForNotifications(HttpServletRequest request, HttpServletResponse response) {
- // TODO: should only the superuser be allowed to use this API?
- EPUser user = EPUserUtils.getUserSession(request);
- List<FunctionalMenuItem> menuItems = null;
- try {
- menuItems = functionalMenuService.getFunctionalMenuItemsForNotificationTree(true);
- EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/functionalMenuForNotificationTree", "result =", menuItems);
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger,
- "Exception occurred while calling functionalMenuForNotifications. Details: "
- + EcompPortalUtils.getStackTrace(e));
- }
- return menuItems;
- }
-
- /**
- * RESTful service method to fetch all FunctionalMenuItems associated with
- * an application.
- *
- * @return List of FunctionalMenuItem objects
- */
- @RequestMapping(value = {
- "/portalApi/functionalMenuForApp/{appId}" }, method = RequestMethod.GET, produces = "application/json")
- public List<FunctionalMenuItem> getMenuItemsForApp(HttpServletRequest request, @PathVariable("appId") Integer appId)
- throws HTTPException {
- // TODO: should only the superuser be allowed to use this API?
- List<FunctionalMenuItem> menuItems = null;
- try {
- menuItems = functionalMenuService.getFunctionalMenuItemsForApp(appId);
- functionalMenuService.assignHelpURLs(menuItems);
- EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/functionalMenuForApp/" + appId, "result =", menuItems);
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger,
- "Exception occurred while calling functionalMenuForApp. Details: "
- + EcompPortalUtils.getStackTrace(e));
- }
- return menuItems;
- }
-
- /**
- * RESTful service method to fetch all FunctionalMenuItems associated with
- * the applications and roles that a user has access to.
- *
- * @return List of FunctionalMenuItem objects
- */
- @RequestMapping(value = {
- "/portalApi/functionalMenuForUser/{orgUserId}" }, method = RequestMethod.GET, produces = "application/json")
- public List<FunctionalMenuItem> getMenuItemsForUser(HttpServletRequest request,
- @PathVariable("orgUserId") String orgUserId) throws HTTPException {
- // TODO: should only the superuser be allowed to use this API?
- List<FunctionalMenuItem> menuItems = null;
- try {
- menuItems = functionalMenuService.getFunctionalMenuItemsForUser(orgUserId);
- functionalMenuService.assignHelpURLs(menuItems);
- EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/functionalMenuForUser/" + orgUserId, "result =", menuItems);
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger,
- "Exception occurred while calling functionalMenuForUser. Details: "
- + EcompPortalUtils.getStackTrace(e));
- }
-
- return menuItems;
- }
-
- /**
- * RESTful service method to fetch all FunctionalMenuItems associated with
- * the applications and roles that the authenticated user has access to.
- *
- * @return List of FunctionalMenuItem objects
- */
- @RequestMapping(value = {
- "/portalApi/functionalMenuForAuthUser" }, method = RequestMethod.GET, produces = "application/json")
- public List<FunctionalMenuItem> getMenuItemsForAuthUser(HttpServletRequest request, HttpServletResponse response) {
- EPUser user = EPUserUtils.getUserSession(request);
- List<FunctionalMenuItem> menuItems = null;
- try {
- if (user == null) {
- EcompPortalUtils.setBadPermissions(user, response, "getMenuItemsForAuthUser");
- } else if (adminRolesService.isSuperAdmin(user)) {
- menuItems = functionalMenuService.getFunctionalMenuItems();
- } else {
- // calculate the menu items
- String orgUserId = user.getOrgUserId();
- menuItems = functionalMenuService.getFunctionalMenuItemsForUser(orgUserId);
- EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/functionalMenuForUser/" + orgUserId, "result =",
- menuItems);
- }
- functionalMenuService.assignHelpURLs(menuItems);
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger,
- "Exception occurred while calling getMenuItemsForAuthUser. Details: "
- + EcompPortalUtils.getStackTrace(e));
- }
- return menuItems;
- }
-
- /**
- * RESTful service method to fetch the details for a functional menu item.
- * Requirement: you must be the Ecomp portal super admin user.
- *
- * @return FunctionalMenuItem object
- */
- @RequestMapping(value = {
- "/portalApi/functionalMenuItemDetails/{menuId}" }, method = RequestMethod.GET, produces = "application/json")
- public FunctionalMenuItem getFunctionalMenuItemDetails(HttpServletRequest request,
- @PathVariable("menuId") Integer menuId, HttpServletResponse response) throws HTTPException {
- // TODO: return FunctionalMenuItemJson
- // TODO: modify FunctionalMenuItem to not include the transient fields
- FunctionalMenuItem menuItem = null;
- try {
- EPUser user = EPUserUtils.getUserSession(request);
- if (!adminRolesService.isSuperAdmin(user)) {
- EcompPortalUtils.setBadPermissions(user, response, "getFunctionalMenuItemDetails");
- } else {
- menuItem = functionalMenuService.getFunctionalMenuItemDetails(menuId);
- EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/functionalMenuItemDetails/" + menuId, "result =",
- menuItem);
- }
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger,
- "Exception occurred while calling functionalMenuItemDetails. Details: "
- + EcompPortalUtils.getStackTrace(e));
- }
-
- return menuItem;
- }
-
- /**
- * RESTful service method to create a new menu item.
- *
- * Requirement: you must be the Ecomp portal super admin user.
- */
- @RequestMapping(value = { "/portalApi/functionalMenuItem" }, method = RequestMethod.POST)
- public FieldsValidator createFunctionalMenuItem(HttpServletRequest request,
- @RequestBody FunctionalMenuItemWithRoles menuItemJson, HttpServletResponse response) {
- EPUser user = EPUserUtils.getUserSession(request);
- FieldsValidator fieldsValidator = null;
- if (!adminRolesService.isSuperAdmin(user)) {
- logger.debug(EELFLoggerDelegate.debugLogger,
- "FunctionalMenuController.createFunctionalMenuItem bad permissions");
- EcompPortalUtils.setBadPermissions(user, response, "createFunctionalMenuItem");
- } else {
- fieldsValidator = functionalMenuService.createFunctionalMenuItem(menuItemJson);
- response.setStatus(fieldsValidator.httpStatusCode.intValue());
- EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/functionalMenuItem", "POST result =",
- response.getStatus());
- }
-
- return fieldsValidator;
- }
-
- /**
- * RESTful service method to update an existing menu item
- *
- * Requirement: you must be the Ecomp portal super admin user.
- *
- * @return FieldsValidator
- */
- @RequestMapping(value = { "/portalApi/functionalMenuItem" }, method = RequestMethod.PUT)
- public FieldsValidator editFunctionalMenuItem(HttpServletRequest request,
- @RequestBody FunctionalMenuItemWithRoles menuItemJson, HttpServletResponse response) {
- EPUser user = EPUserUtils.getUserSession(request);
- FieldsValidator fieldsValidator = null;
- if (!adminRolesService.isSuperAdmin(user)) {
- EcompPortalUtils.setBadPermissions(user, response, "editFunctionalMenuItem");
- } else {
- fieldsValidator = functionalMenuService.editFunctionalMenuItem(menuItemJson);
- response.setStatus(fieldsValidator.httpStatusCode.intValue());
- EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/functionalMenuItem", "PUT result =",
- response.getStatus());
- }
-
- return fieldsValidator;
- }
-
- /**
- * RESTful service method to delete a menu item
- *
- * @return FieldsValidator
- */
- @RequestMapping(value = { "/portalApi/functionalMenuItem/{menuId}" }, method = RequestMethod.DELETE)
- public FieldsValidator deleteFunctionalMenuItem(HttpServletRequest request, @PathVariable("menuId") Long menuId,
- HttpServletResponse response) {
- EPUser user = EPUserUtils.getUserSession(request);
- FieldsValidator fieldsValidator = null;
- if (!adminRolesService.isSuperAdmin(user)) {
- EcompPortalUtils.setBadPermissions(user, response, "deleteFunctionalMenuItem");
- } else {
- fieldsValidator = functionalMenuService.deleteFunctionalMenuItem(menuId);
- response.setStatus(fieldsValidator.httpStatusCode.intValue());
- EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/functionalMenuItem", "DELETE result =",
- response.getStatus());
- }
-
- return fieldsValidator;
- }
-
- /**
- * RESTful service to regenerate table
- *
- * @param request
- * @param response
- *
- * @return FieldsValidator
- */
- @RequestMapping(value = { "/portalApi/regenerateFunctionalMenuAncestors" }, method = RequestMethod.GET)
- public FieldsValidator regenerateAncestorTable(HttpServletRequest request, HttpServletResponse response) {
- // TODO: should only the superuser be allowed to use this API?
- EPUser user = EPUserUtils.getUserSession(request);
- FieldsValidator fieldsValidator = null;
-
- if (!adminRolesService.isSuperAdmin(user)) {
- EcompPortalUtils.setBadPermissions(user, response, "deleteFunctionalMenuItem");
- } else {
- fieldsValidator = functionalMenuService.regenerateAncestorTable();
- response.setStatus(fieldsValidator.httpStatusCode.intValue());
- EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/regenerateAncestorTable", "GET result =",
- response.getStatus());
- }
-
- return fieldsValidator;
- }
-
- /**
- * RESful service to set a favorite item.
- *
- * @return FieldsValidator
- */
- @RequestMapping(value = { "/portalApi/setFavoriteItem" }, method = RequestMethod.POST)
- public FieldsValidator addFavoriteItem(HttpServletRequest request,
- @RequestBody FavoritesFunctionalMenuItem menuItemJson, HttpServletResponse response) {
- EPUser user = EPUserUtils.getUserSession(request);
- FieldsValidator fieldsValidator = null;
- menuItemJson.userId = user.getId();
- fieldsValidator = functionalMenuService.setFavoriteItem(menuItemJson);
- response.setStatus(fieldsValidator.httpStatusCode.intValue());
- EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/setFavoriteItem", "Post result =", response.getStatus());
-
- return fieldsValidator;
- }
-
- /**
- * RESTful service to get favorites for the current user as identified in
- * the session
- *
- * @return List of FavoritesFunctionalMenuItemJson
- */
- @RequestMapping(value = {
- "/portalApi/getFavoriteItems" }, method = RequestMethod.GET, produces = "application/json")
- public List<FavoritesFunctionalMenuItemJson> getFavoritesForUser(HttpServletRequest request,
- HttpServletResponse response) {
- EPUser user = EPUserUtils.getUserSession(request);
- List<FavoritesFunctionalMenuItemJson> favorites = functionalMenuService.getFavoriteItems(user.getId());
- FieldsValidator fieldsValidator = new FieldsValidator();
- response.setStatus(fieldsValidator.httpStatusCode.intValue());
- EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/getFavoriteItems", "GET result =", response.getStatus());
- return favorites;
- }
-
- /**
- * RESTful service to delete a favorite menu item for the current user as
- * identified in the session.
- *
- * @return FieldsValidator
- */
- @RequestMapping(value = { "/portalApi/removeFavoriteItem/{menuId}" }, method = RequestMethod.DELETE)
- public FieldsValidator deleteFavoriteItem(HttpServletRequest request, @PathVariable("menuId") Long menuId,
- HttpServletResponse response) {
- EPUser user = EPUserUtils.getUserSession(request);
- FieldsValidator fieldsValidator = null;
- Long userId = user.getId();
- fieldsValidator = functionalMenuService.removeFavoriteItem(userId, menuId);
- response.setStatus(fieldsValidator.httpStatusCode.intValue());
- EcompPortalUtils.logAndSerializeObject(logger, "/deleteFavoriteItem", "DELETE result =", response.getStatus());
-
- return fieldsValidator;
- }
-
- /**
- * RESTful service to get user information: user's first and last names, ATT
- * UID, email and last-login. (Actually has nothing to do with the real
- * functional menu.) First attempts to get the information from the Tomcat
- * session (i.e., the CSP cookie); if that fails, calls the shared context
- * service to read the information from the database. Gives back what it
- * found, any of which may be null, as a JSON collection.
- *
- * @return JSON collection of key-value pairs shown below.
- */
- @RequestMapping(value = {
- "/portalApi/functionalMenuStaticInfo" }, method = RequestMethod.GET, produces = "application/json")
- public String getFunctionalMenuStaticInfo(HttpServletRequest request, HttpServletResponse response) {
-
- // Get user details from session
- logger.debug(EELFLoggerDelegate.debugLogger, "getFunctionalMenuStaticInfo: getting user info");
- String fnMenuStaticResponse = null;
- try {
- String orgUserIdStr = null, firstNameStr = null, lastNameStr = null, emailStr = null, lastLogin = null;
- EPUser user = EPUserUtils.getUserSession(request);
- firstNameStr = user.getFirstName();
- lastNameStr = user.getLastName();
- orgUserIdStr = user.getOrgUserId();
- emailStr = user.getEmail();
- if (emailStr == null || emailStr.equals("")) {
- EPUser userResult = searchService.searchUserByUserId(orgUserIdStr);
- emailStr = userResult.getEmail();
- }
- SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ssZ");
- Date lastLoginDate = user.getLastLoginDate();
- if (lastLoginDate == null) {
- // should never happen
- logger.error(EELFLoggerDelegate.errorLogger, "getFunctionalMenuStaticInfo: no last login in session");
- lastLogin = "no last login available";
- }
- else {
- lastLogin = sdf.format(lastLoginDate);
- }
-
- // If any item is missing from session, try the Shared Context
- // service.
- SharedContext orgUserIdSC = null, firstNameSC = null, lastNameSC = null, emailSC = null;
- String sessionId = request.getSession().getId();
- if (firstNameStr == null)
- firstNameSC = sharedContextService.getSharedContext(sessionId, EPCommonSystemProperties.USER_FIRST_NAME);
- if (lastNameStr == null)
- lastNameSC = sharedContextService.getSharedContext(sessionId, EPCommonSystemProperties.USER_LAST_NAME);
- if (emailStr == null)
- emailSC = sharedContextService.getSharedContext(sessionId, EPCommonSystemProperties.USER_EMAIL);
- if (orgUserIdStr == null)
- orgUserIdSC = sharedContextService.getSharedContext(sessionId, EPCommonSystemProperties.USER_ORG_USERID);
-
- // Build the response
- Map<String, String> map = new HashMap<String, String>();
- map.put("firstName",
- firstNameStr != null ? firstNameStr : (firstNameSC != null ? firstNameSC.getCvalue() : null));
- map.put("lastName",
- lastNameStr != null ? lastNameStr : (lastNameSC != null ? lastNameSC.getCvalue() : null));
- map.put("email", emailStr != null ? emailStr : (emailSC != null ? emailSC.getCvalue() : null));
- map.put("userId", orgUserIdStr != null ? orgUserIdStr : (orgUserIdSC != null ? orgUserIdSC.getCvalue() : null));
- map.put("last_login", lastLogin);
- JSONObject j = new JSONObject(map);
- fnMenuStaticResponse = j.toString();
- // Be chatty in the log
- EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/functionalMenuStaticInfo", "GET result =",
- fnMenuStaticResponse);
- } catch (Exception e) {
- // Should never happen.
- logger.error(EELFLoggerDelegate.errorLogger, "getFunctionalMenuStaticInfo failed", e);
- // Return a real error?
- // fnMenuStaticResponse = "{ \"status\": \"error\", \"message\": \""
- // + e.toString() + "\" }";
- // But the angular controller expects null on error.
- }
- return fnMenuStaticResponse;
- }
-
- private Comparator<BusinessCardApplicationRole> getUserAppRolesComparator = new Comparator<BusinessCardApplicationRole>() {
- public int compare(BusinessCardApplicationRole o1, BusinessCardApplicationRole o2) {
- return o1.getAppName().compareTo(o2.getAppName());
- }
- };
-
- @RequestMapping(value = {
- "/portalApi/userApplicationRoles" }, method = RequestMethod.GET, produces = "application/json")
- public List<BusinessCardApplicationRolesList> getAppList(HttpServletRequest request,@RequestParam("userId") String userId) throws IOException {
-
-
- List<BusinessCardApplicationRolesList> AppRoles = null;
- try {
- List<BusinessCardApplicationRole> userAppRoleList = functionalMenuService.getUserAppRolesList(userId);
-
- Collections.sort(userAppRoleList, getUserAppRolesComparator);
- EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/userApplicationRoles", "result =", userAppRoleList);
-
- AppRoles = new ArrayList<BusinessCardApplicationRolesList>();
- for(BusinessCardApplicationRole userAppRole: userAppRoleList)
- {
- boolean found = false;
- List<String> roles = null;
-
- for(BusinessCardApplicationRolesList app :AppRoles)
- {
- if(app.getAppName().equals(userAppRole.getAppName()))
- {
- roles= app.getRoleNames();
- roles.add(userAppRole.getRoleName());
- app.setRoleNames(roles);
- found = true;
- break;
- }
- }
-
- if(!found)
- {
- roles = new ArrayList<String>();
- roles.add(userAppRole.getRoleName());
- AppRoles.add(new BusinessCardApplicationRolesList(userAppRole.getAppName(), roles));
- }
-
- Collections.sort(roles);
- }
- } catch (Exception e) {
- // TODO Auto-generated catch block
- logger.error(EELFLoggerDelegate.errorLogger, "getAppList failed", e);
- }
-
- return AppRoles;
-
- }
-}
+/*-
+ * ================================================================================
+ * ECOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.controller;
+
+import java.io.IOException;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.json.JSONObject;
+import org.openecomp.portalapp.controller.EPRestrictedBaseController;
+import org.openecomp.portalapp.portal.domain.EPUser;
+import org.openecomp.portalapp.portal.domain.SharedContext;
+import org.openecomp.portalapp.portal.ecomp.model.PortalRestResponse;
+import org.openecomp.portalapp.portal.ecomp.model.PortalRestStatusEnum;
+import org.openecomp.portalapp.portal.logging.aop.EPAuditLog;
+import org.openecomp.portalapp.portal.service.AdminRolesService;
+import org.openecomp.portalapp.portal.service.FunctionalMenuService;
+import org.openecomp.portalapp.portal.service.SearchService;
+import org.openecomp.portalapp.portal.service.SharedContextService;
+import org.openecomp.portalapp.portal.transport.BusinessCardApplicationRole;
+import org.openecomp.portalapp.portal.transport.BusinessCardApplicationRolesList;
+import org.openecomp.portalapp.portal.transport.FavoritesFunctionalMenuItem;
+import org.openecomp.portalapp.portal.transport.FavoritesFunctionalMenuItemJson;
+import org.openecomp.portalapp.portal.transport.FieldsValidator;
+import org.openecomp.portalapp.portal.transport.FunctionalMenuItem;
+import org.openecomp.portalapp.portal.transport.FunctionalMenuItemWithRoles;
+import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties;
+import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
+import org.openecomp.portalapp.util.EPUserUtils;
+import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.openecomp.portalsdk.core.util.SystemProperties;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.EnableAspectJAutoProxy;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.RequestParam;
+import org.springframework.web.bind.annotation.RestController;
+
+/**
+ * Supports menus at the top of the Portal app landing page.
+ */
+@RestController
+@org.springframework.context.annotation.Configuration
+@EnableAspectJAutoProxy
+@EPAuditLog
+public class FunctionalMenuController extends EPRestrictedBaseController {
+
+ private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(FunctionalMenuController.class);
+
+ @Autowired
+ private AdminRolesService adminRolesService;
+ @Autowired
+ private FunctionalMenuService functionalMenuService;
+ @Autowired
+ private SharedContextService sharedContextService;
+ @Autowired
+ private SearchService searchService;
+
+ /**
+ * RESTful service method to fetch all the FunctionalMenuItems.
+ *
+ * @param request
+ * HttpServletRequest
+ * @param response
+ * HttpServletResponse
+ * @return List of FunctionalMenuItem objects
+ */
+ @RequestMapping(value = { "/portalApi/functionalMenu" }, method = RequestMethod.GET, produces = "application/json")
+ public List<FunctionalMenuItem> getMenuItems(HttpServletRequest request, HttpServletResponse response) {
+ // TODO: should only the superuser be allowed to use this API?
+ List<FunctionalMenuItem> menuItems = null;
+ try {
+ menuItems = functionalMenuService.getFunctionalMenuItems();
+ functionalMenuService.assignHelpURLs(menuItems);
+ EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/functionalMenu", "result =", menuItems);
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "Exception occurred while calling functionalMenu. Details: " + EcompPortalUtils.getStackTrace(e));
+ }
+ return menuItems;
+ }
+
+ /**
+ * RESTful service method to get ECOMP Portal Title.
+ *
+ * @param request
+ * HttpServletRequest
+ * @param response
+ * HttpServletResponse
+ * @return PortalRestResponse of ECOMP portal title
+ */
+ @RequestMapping(value = { "/portalApi/ecompTitle" }, method = RequestMethod.GET, produces = "application/json")
+ public PortalRestResponse<String> getECOMPTitle(HttpServletRequest request, HttpServletResponse response) {
+ PortalRestResponse<String> portalRestResponse = null;
+ try {
+ String ecompTitle = SystemProperties.getProperty(SystemProperties.APP_DISPLAY_NAME);
+ portalRestResponse = new PortalRestResponse<String>(PortalRestStatusEnum.OK, "success", ecompTitle);
+ EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/ecompTitle", "result =", ecompTitle);
+ } catch (Exception e) {
+ portalRestResponse = new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, e.getMessage(), null);
+ logger.error(EELFLoggerDelegate.errorLogger, "getEcompTitle failed", e);
+ }
+ return portalRestResponse;
+ }
+
+ /**
+ * RESTful service method to fetch all the FunctionalMenuItems, both active
+ * and inactive, for the EditFunctionalMenu feature. Can only be accessed by
+ * the portal admin.
+ *
+ * @param request
+ * HttpServletRequest
+ * @param response
+ * HttpServletResponse
+ * @return List of FunctionalMenuItem objects
+ */
+ @RequestMapping(value = {
+ "/portalApi/functionalMenuForEditing" }, method = RequestMethod.GET, produces = "application/json")
+ public List<FunctionalMenuItem> getMenuItemsForEditing(HttpServletRequest request, HttpServletResponse response) {
+ // TODO: should only the superuser be allowed to use this API?
+ EPUser user = EPUserUtils.getUserSession(request);
+ List<FunctionalMenuItem> menuItems = null;
+ try {
+ if (!adminRolesService.isSuperAdmin(user)) {
+ EcompPortalUtils.setBadPermissions(user, response, "getFunctionalMenuItemDetails");
+ } else {
+ menuItems = functionalMenuService.getFunctionalMenuItems(true);
+ }
+ EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/functionalMenuForEditing", "result =",
+ menuItems);
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "Exception occurred while calling functionalMenuForEditing. Details: "
+ + EcompPortalUtils.getStackTrace(e));
+ }
+ return menuItems;
+ }
+
+ /**
+ * RESTful service method to fetch all the FunctionalMenuItems, active , for
+ * the Functional menu in notification Tree feature.
+ *
+ * @param request
+ * HttpServletRequest
+ * @param response
+ * HttpServletResponse
+ * @return List of FunctionalMenuItem objects
+ */
+ @RequestMapping(value = {
+ "/portalApi/functionalMenuForNotificationTree" }, method = RequestMethod.GET, produces = "application/json")
+ public List<FunctionalMenuItem> getMenuItemsForNotifications(HttpServletRequest request,
+ HttpServletResponse response) {
+ // TODO: should only the superuser be allowed to use this API?
+ // EPUser user = EPUserUtils.getUserSession(request);
+ List<FunctionalMenuItem> menuItems = null;
+ try {
+ menuItems = functionalMenuService.getFunctionalMenuItemsForNotificationTree(true);
+ EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/functionalMenuForNotificationTree", "result =",
+ menuItems);
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "Exception occurred while calling functionalMenuForNotifications. Details: "
+ + EcompPortalUtils.getStackTrace(e));
+ }
+ return menuItems;
+ }
+
+ /**
+ * RESTful service method to fetch all FunctionalMenuItems associated with
+ * an application.
+ *
+ * @param request
+ * HttpServletRequest
+ * @param response
+ * HttpServletResponse
+ * @param appId
+ * application ID
+ * @return List of FunctionalMenuItem objects
+ */
+ @RequestMapping(value = {
+ "/portalApi/functionalMenuForApp/{appId}" }, method = RequestMethod.GET, produces = "application/json")
+ public List<FunctionalMenuItem> getMenuItemsForApp(HttpServletRequest request,
+ @PathVariable("appId") Integer appId) {
+ // TODO: should only the superuser be allowed to use this API?
+ List<FunctionalMenuItem> menuItems = null;
+ try {
+ menuItems = functionalMenuService.getFunctionalMenuItemsForApp(appId);
+ functionalMenuService.assignHelpURLs(menuItems);
+ EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/functionalMenuForApp/" + appId, "result =",
+ menuItems);
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "Exception occurred while calling functionalMenuForApp. Details: "
+ + EcompPortalUtils.getStackTrace(e));
+ }
+ return menuItems;
+ }
+
+ /**
+ * RESTful service method to fetch all FunctionalMenuItems associated with
+ * the applications and roles that a user has access to.
+ *
+ * @param request
+ * HttpServletRequest
+ * @param orgUserId
+ * user ID
+ * @return List of FunctionalMenuItem objects
+ */
+ @RequestMapping(value = {
+ "/portalApi/functionalMenuForUser/{orgUserId}" }, method = RequestMethod.GET, produces = "application/json")
+ public List<FunctionalMenuItem> getMenuItemsForUser(HttpServletRequest request,
+ @PathVariable("orgUserId") String orgUserId) {
+ // TODO: should only the superuser be allowed to use this API?
+ List<FunctionalMenuItem> menuItems = null;
+ try {
+ menuItems = functionalMenuService.getFunctionalMenuItemsForUser(orgUserId);
+ functionalMenuService.assignHelpURLs(menuItems);
+ EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/functionalMenuForUser/" + orgUserId, "result =",
+ menuItems);
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "Exception occurred while calling functionalMenuForUser. Details: "
+ + EcompPortalUtils.getStackTrace(e));
+ }
+
+ return menuItems;
+ }
+
+ /**
+ * RESTful service method to fetch all FunctionalMenuItems associated with
+ * the applications and roles that the authenticated user has access to.
+ *
+ * @param request
+ * HttpServletRequest
+ * @param response
+ * HttpServletResponse
+ * @return List of FunctionalMenuItem objects
+ */
+ @RequestMapping(value = {
+ "/portalApi/functionalMenuForAuthUser" }, method = RequestMethod.GET, produces = "application/json")
+ public List<FunctionalMenuItem> getMenuItemsForAuthUser(HttpServletRequest request, HttpServletResponse response) {
+ EPUser user = EPUserUtils.getUserSession(request);
+ List<FunctionalMenuItem> menuItems = null;
+ try {
+ if (user == null) {
+ EcompPortalUtils.setBadPermissions(user, response, "getMenuItemsForAuthUser");
+ } else if (adminRolesService.isSuperAdmin(user)) {
+ menuItems = functionalMenuService.getFunctionalMenuItems();
+ } else {
+ // calculate the menu items
+ String orgUserId = user.getOrgUserId();
+ menuItems = functionalMenuService.getFunctionalMenuItemsForUser(orgUserId);
+ EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/functionalMenuForUser/" + orgUserId,
+ "result =", menuItems);
+ }
+ functionalMenuService.assignHelpURLs(menuItems);
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "Exception occurred while calling getMenuItemsForAuthUser. Details: "
+ + EcompPortalUtils.getStackTrace(e));
+ }
+ return menuItems;
+ }
+
+ /**
+ * RESTful service method to fetch the details for a functional menu item.
+ * Requirement: you must be the Ecomp portal super admin user.
+ *
+ * @param request
+ * HttpServletRequest
+ * @param response
+ * HttpServletResponse
+ * @param menuId
+ * menu ID
+ * @return FunctionalMenuItem object
+ */
+ @RequestMapping(value = {
+ "/portalApi/functionalMenuItemDetails/{menuId}" }, method = RequestMethod.GET, produces = "application/json")
+ public FunctionalMenuItem getFunctionalMenuItemDetails(HttpServletRequest request,
+ @PathVariable("menuId") Integer menuId, HttpServletResponse response) {
+ // TODO: return FunctionalMenuItemJson
+ // TODO: modify FunctionalMenuItem to not include the transient fields
+ FunctionalMenuItem menuItem = null;
+ try {
+ EPUser user = EPUserUtils.getUserSession(request);
+ if (!adminRolesService.isSuperAdmin(user)) {
+ EcompPortalUtils.setBadPermissions(user, response, "getFunctionalMenuItemDetails");
+ } else {
+ menuItem = functionalMenuService.getFunctionalMenuItemDetails(menuId);
+ EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/functionalMenuItemDetails/" + menuId,
+ "result =", menuItem);
+ }
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "Exception occurred while calling functionalMenuItemDetails. Details: "
+ + EcompPortalUtils.getStackTrace(e));
+ }
+
+ return menuItem;
+ }
+
+ /**
+ * RESTful service method to create a new menu item.
+ *
+ * Requirement: you must be the Ecomp portal super admin user.
+ *
+ * @param request
+ * HttpServletRequest
+ * @param response
+ * HttpServletResponse
+ * @param menuItemJson
+ * FunctionalMenuItemWithRoles
+ * @return FieldsValidator
+ */
+ @RequestMapping(value = { "/portalApi/functionalMenuItem" }, method = RequestMethod.POST)
+ public FieldsValidator createFunctionalMenuItem(HttpServletRequest request,
+ @RequestBody FunctionalMenuItemWithRoles menuItemJson, HttpServletResponse response) {
+ EPUser user = EPUserUtils.getUserSession(request);
+ FieldsValidator fieldsValidator = null;
+ if (!adminRolesService.isSuperAdmin(user)) {
+ logger.debug(EELFLoggerDelegate.debugLogger,
+ "FunctionalMenuController.createFunctionalMenuItem bad permissions");
+ EcompPortalUtils.setBadPermissions(user, response, "createFunctionalMenuItem");
+ } else {
+ fieldsValidator = functionalMenuService.createFunctionalMenuItem(menuItemJson);
+ response.setStatus(fieldsValidator.httpStatusCode.intValue());
+ EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/functionalMenuItem", "POST result =",
+ response.getStatus());
+ }
+
+ return fieldsValidator;
+ }
+
+ /**
+ * RESTful service method to update an existing menu item
+ *
+ * Requirement: you must be the Ecomp portal super admin user.
+ *
+ * @param request
+ * HttpServletRequest
+ * @param response
+ * HttpServletResponse
+ * @param menuItemJson
+ * FunctionalMenuItemWithRoles
+ * @return FieldsValidator
+ */
+ @RequestMapping(value = { "/portalApi/functionalMenuItem" }, method = RequestMethod.PUT)
+ public FieldsValidator editFunctionalMenuItem(HttpServletRequest request,
+ @RequestBody FunctionalMenuItemWithRoles menuItemJson, HttpServletResponse response) {
+ EPUser user = EPUserUtils.getUserSession(request);
+ FieldsValidator fieldsValidator = null;
+ if (!adminRolesService.isSuperAdmin(user)) {
+ EcompPortalUtils.setBadPermissions(user, response, "editFunctionalMenuItem");
+ } else {
+ fieldsValidator = functionalMenuService.editFunctionalMenuItem(menuItemJson);
+ response.setStatus(fieldsValidator.httpStatusCode.intValue());
+ EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/functionalMenuItem", "PUT result =",
+ response.getStatus());
+ }
+
+ return fieldsValidator;
+ }
+
+ /**
+ * RESTful service method to delete a menu item
+ *
+ * @param request
+ * HttpServletRequest
+ * @param response
+ * HttpServletResponse
+ * @param menuId
+ * menu identifier
+ * @return FieldsValidator
+ */
+ @RequestMapping(value = { "/portalApi/functionalMenuItem/{menuId}" }, method = RequestMethod.DELETE)
+ public FieldsValidator deleteFunctionalMenuItem(HttpServletRequest request, @PathVariable("menuId") Long menuId,
+ HttpServletResponse response) {
+ EPUser user = EPUserUtils.getUserSession(request);
+ FieldsValidator fieldsValidator = null;
+ if (!adminRolesService.isSuperAdmin(user)) {
+ EcompPortalUtils.setBadPermissions(user, response, "deleteFunctionalMenuItem");
+ } else {
+ fieldsValidator = functionalMenuService.deleteFunctionalMenuItem(menuId);
+ response.setStatus(fieldsValidator.httpStatusCode.intValue());
+ EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/functionalMenuItem", "DELETE result =",
+ response.getStatus());
+ }
+
+ return fieldsValidator;
+ }
+
+ /**
+ * RESTful service to regenerate table
+ *
+ * @param request
+ * HttpServletRequest
+ * @param response
+ * HttpServletResponse
+ * @return FieldsValidator
+ */
+ @RequestMapping(value = { "/portalApi/regenerateFunctionalMenuAncestors" }, method = RequestMethod.GET)
+ public FieldsValidator regenerateAncestorTable(HttpServletRequest request, HttpServletResponse response) {
+ // TODO: should only the superuser be allowed to use this API?
+ EPUser user = EPUserUtils.getUserSession(request);
+ FieldsValidator fieldsValidator = null;
+
+ if (!adminRolesService.isSuperAdmin(user)) {
+ EcompPortalUtils.setBadPermissions(user, response, "deleteFunctionalMenuItem");
+ } else {
+ fieldsValidator = functionalMenuService.regenerateAncestorTable();
+ response.setStatus(fieldsValidator.httpStatusCode.intValue());
+ EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/regenerateAncestorTable", "GET result =",
+ response.getStatus());
+ }
+
+ return fieldsValidator;
+ }
+
+ /**
+ * RESful service to set a favorite item.
+ *
+ * @param request
+ * HttpServletRequest
+ * @param response
+ * HttpServletResponse
+ * @param menuItemJson
+ * FunctionalMenuItemWithRoles
+ * @return FieldsValidator
+ */
+ @RequestMapping(value = { "/portalApi/setFavoriteItem" }, method = RequestMethod.POST)
+ public FieldsValidator addFavoriteItem(HttpServletRequest request,
+ @RequestBody FavoritesFunctionalMenuItem menuItemJson, HttpServletResponse response) {
+ EPUser user = EPUserUtils.getUserSession(request);
+ FieldsValidator fieldsValidator = null;
+ menuItemJson.userId = user.getId();
+ fieldsValidator = functionalMenuService.setFavoriteItem(menuItemJson);
+ response.setStatus(fieldsValidator.httpStatusCode.intValue());
+ EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/setFavoriteItem", "Post result =",
+ response.getStatus());
+
+ return fieldsValidator;
+ }
+
+ /**
+ * RESTful service to get favorites for the current user as identified in
+ * the session
+ *
+ * @param request
+ * HttpServletRequest
+ * @param response
+ * HttpServletResponse
+ * @return List of FavoritesFunctionalMenuItemJson
+ */
+ @RequestMapping(value = {
+ "/portalApi/getFavoriteItems" }, method = RequestMethod.GET, produces = "application/json")
+ public List<FavoritesFunctionalMenuItemJson> getFavoritesForUser(HttpServletRequest request,
+ HttpServletResponse response) {
+ EPUser user = EPUserUtils.getUserSession(request);
+ List<FavoritesFunctionalMenuItemJson> favorites = functionalMenuService.getFavoriteItems(user.getId());
+ FieldsValidator fieldsValidator = new FieldsValidator();
+ response.setStatus(fieldsValidator.httpStatusCode.intValue());
+ EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/getFavoriteItems", "GET result =",
+ response.getStatus());
+ return favorites;
+ }
+
+ /**
+ * RESTful service to delete a favorite menu item for the current user as
+ * identified in the session.
+ *
+ * @param request
+ * HttpServletRequest
+ * @param response
+ * HttpServletResponse
+ * @param menuId
+ * menu identifier
+ * @return FieldsValidator
+ */
+ @RequestMapping(value = { "/portalApi/removeFavoriteItem/{menuId}" }, method = RequestMethod.DELETE)
+ public FieldsValidator deleteFavoriteItem(HttpServletRequest request, @PathVariable("menuId") Long menuId,
+ HttpServletResponse response) {
+ EPUser user = EPUserUtils.getUserSession(request);
+ FieldsValidator fieldsValidator = null;
+ Long userId = user.getId();
+ fieldsValidator = functionalMenuService.removeFavoriteItem(userId, menuId);
+ response.setStatus(fieldsValidator.httpStatusCode.intValue());
+ EcompPortalUtils.logAndSerializeObject(logger, "/deleteFavoriteItem", "DELETE result =", response.getStatus());
+
+ return fieldsValidator;
+ }
+
+ /**
+ * RESTful service to get user information: user's first and last names, org
+ * user ID, email and last-login. (Actually has nothing to do with the real
+ * functional menu.) First attempts to get the information from the Tomcat
+ * session (i.e., the CSP cookie); if that fails, calls the shared context
+ * service to read the information from the database. Gives back what it
+ * found, any of which may be null, as a JSON collection.
+ *
+ * @param request
+ * HttpServletRequest
+ * @param response
+ * HttpServletResponse
+ * @return JSON collection of key-value pairs shown below.
+ */
+ @RequestMapping(value = {
+ "/portalApi/functionalMenuStaticInfo" }, method = RequestMethod.GET, produces = "application/json")
+ public String getFunctionalMenuStaticInfo(HttpServletRequest request, HttpServletResponse response) {
+
+ // Get user details from session
+ logger.debug(EELFLoggerDelegate.debugLogger, "getFunctionalMenuStaticInfo: getting user info");
+ String fnMenuStaticResponse = null;
+ try {
+ String orgUserIdStr = null, firstNameStr = null, lastNameStr = null, emailStr = null, lastLogin = null;
+ EPUser user = EPUserUtils.getUserSession(request);
+ firstNameStr = user.getFirstName();
+ lastNameStr = user.getLastName();
+ orgUserIdStr = user.getOrgUserId();
+ emailStr = user.getEmail();
+ if (emailStr == null || emailStr.equals("")) {
+ EPUser userResult = searchService.searchUserByUserId(orgUserIdStr);
+ emailStr = userResult.getEmail();
+ }
+ SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ssZ");
+ Date lastLoginDate = user.getLastLoginDate();
+ if (lastLoginDate == null) {
+ // should never happen
+ logger.error(EELFLoggerDelegate.errorLogger, "getFunctionalMenuStaticInfo: no last login in session");
+ lastLogin = "no last login available";
+ } else {
+ lastLogin = sdf.format(lastLoginDate);
+ }
+
+ // If any item is missing from session, try the Shared Context
+ // service.
+ SharedContext orgUserIdSC = null, firstNameSC = null, lastNameSC = null, emailSC = null;
+ String sessionId = request.getSession().getId();
+ if (firstNameStr == null)
+ firstNameSC = sharedContextService.getSharedContext(sessionId,
+ EPCommonSystemProperties.USER_FIRST_NAME);
+ if (lastNameStr == null)
+ lastNameSC = sharedContextService.getSharedContext(sessionId, EPCommonSystemProperties.USER_LAST_NAME);
+ if (emailStr == null)
+ emailSC = sharedContextService.getSharedContext(sessionId, EPCommonSystemProperties.USER_EMAIL);
+ if (orgUserIdStr == null)
+ orgUserIdSC = sharedContextService.getSharedContext(sessionId,
+ EPCommonSystemProperties.USER_ORG_USERID);
+
+ // Build the response
+ Map<String, String> map = new HashMap<String, String>();
+ map.put("firstName",
+ firstNameStr != null ? firstNameStr : (firstNameSC != null ? firstNameSC.getCvalue() : null));
+ map.put("lastName",
+ lastNameStr != null ? lastNameStr : (lastNameSC != null ? lastNameSC.getCvalue() : null));
+ map.put("email", emailStr != null ? emailStr : (emailSC != null ? emailSC.getCvalue() : null));
+ map.put("userId",
+ orgUserIdStr != null ? orgUserIdStr : (orgUserIdSC != null ? orgUserIdSC.getCvalue() : null));
+ map.put("last_login", lastLogin);
+ JSONObject j = new JSONObject(map);
+ fnMenuStaticResponse = j.toString();
+ // Be chatty in the log
+ EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/functionalMenuStaticInfo", "GET result =",
+ fnMenuStaticResponse);
+ } catch (Exception e) {
+ // Should never happen.
+ logger.error(EELFLoggerDelegate.errorLogger, "getFunctionalMenuStaticInfo failed", e);
+ // Return a real error?
+ // fnMenuStaticResponse = "{ \"status\": \"error\", \"message\": \""
+ // + e.toString() + "\" }";
+ // But the angular controller expects null on error.
+ }
+ return fnMenuStaticResponse;
+ }
+
+ private Comparator<BusinessCardApplicationRole> getUserAppRolesComparator = new Comparator<BusinessCardApplicationRole>() {
+ public int compare(BusinessCardApplicationRole o1, BusinessCardApplicationRole o2) {
+ return o1.getAppName().compareTo(o2.getAppName());
+ }
+ };
+
+ /**
+ *
+ * @param request
+ * HttpServletRequest
+ * @param userId
+ * user ID
+ * @return List<BusinessCardApplicationRolesList>
+ * @throws IOException
+ * on error
+ */
+ @RequestMapping(value = {
+ "/portalApi/userApplicationRoles" }, method = RequestMethod.GET, produces = "application/json")
+ public List<BusinessCardApplicationRolesList> getAppList(HttpServletRequest request,
+ @RequestParam("userId") String userId) throws IOException {
+
+ List<BusinessCardApplicationRolesList> AppRoles = null;
+ try {
+ List<BusinessCardApplicationRole> userAppRoleList = functionalMenuService.getUserAppRolesList(userId);
+
+ Collections.sort(userAppRoleList, getUserAppRolesComparator);
+ EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/userApplicationRoles", "result =",
+ userAppRoleList);
+
+ AppRoles = new ArrayList<BusinessCardApplicationRolesList>();
+ for (BusinessCardApplicationRole userAppRole : userAppRoleList) {
+ boolean found = false;
+ List<String> roles = null;
+
+ for (BusinessCardApplicationRolesList app : AppRoles) {
+ if (app.getAppName().equals(userAppRole.getAppName())) {
+ roles = app.getRoleNames();
+ roles.add(userAppRole.getRoleName());
+ app.setRoleNames(roles);
+ found = true;
+ break;
+ }
+ }
+
+ if (!found) {
+ roles = new ArrayList<String>();
+ roles.add(userAppRole.getRoleName());
+ AppRoles.add(new BusinessCardApplicationRolesList(userAppRole.getAppName(), roles));
+ }
+
+ Collections.sort(roles);
+ }
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "getAppList failed", e);
+ }
+
+ return AppRoles;
+
+ }
+}
diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/HealthCheckController.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/HealthCheckController.java
index 84731af4..ee5e5eea 100644
--- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/HealthCheckController.java
+++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/HealthCheckController.java
@@ -41,16 +41,17 @@ import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties;
import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
import com.google.gson.Gson;
-/*
- * This controller checks the health status and returns JSON response.
- * It does not require authentication or session.
+/**
+ * This controller processes requests for the health-check feature implemented
+ * in the HealthMonitor, which runs in its own thread. These requests do not
+ * require any authentication nor an active user session.
*/
@RestController
@org.springframework.context.annotation.Configuration
@EnableAspectJAutoProxy
@EPAuditLog
public class HealthCheckController extends EPUnRestrictedBaseController {
-
+
private class HealthStatus {
public int statusCode;
@SuppressWarnings("unused")
@@ -96,8 +97,8 @@ public class HealthCheckController extends EPUnRestrictedBaseController {
private final String statusDown = "DOWN";
private final String statusOk = "OK";
- EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(HealthCheckController.class);
-
+ private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(HealthCheckController.class);
+
@RequestMapping(value = { "/portalApi/healthCheck" }, method = RequestMethod.GET, produces = "application/json")
public HealthStatus healthCheck(HttpServletRequest request, HttpServletResponse response) {
HealthStatus healthStatus = new HealthStatus(500, "");
@@ -106,7 +107,8 @@ public class HealthCheckController extends EPUnRestrictedBaseController {
if (HealthMonitor.isSuspended) {
healthStatus.body = "Suspended";
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
- MDC.put(EPCommonSystemProperties.RESPONSE_CODE, Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR));
+ MDC.put(EPCommonSystemProperties.RESPONSE_CODE,
+ Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR));
return healthStatus;
}
@@ -142,28 +144,27 @@ public class HealthCheckController extends EPUnRestrictedBaseController {
dbInfo.description = "Check the logs for more details";
EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError);
}
-
+
if (!HealthMonitor.isClusterStatusOk()) {
dbInfo.dbClusterStatus = "Problem, check the logs for more details";
EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError);
- }
- else {
+ } else {
dbInfo.dbClusterStatus = statusOk;
}
-
+
if (!HealthMonitor.isDatabasePermissionsOk()) {
dbInfo.dbPermissions = "Problem, check the logs for more details";
EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError);
- }
- else {
+ } else {
dbInfo.dbPermissions = statusOk;
}
statusCollection.add(dbInfo);
HealthStatusInfo uebInfo = new HealthStatusInfo("UEB");
if (!HealthMonitor.isUebUp()) {
- //As per test case review meeting, UEB is considered as critical as DB. Hence commenting
- //overallStatus = false;
+ // As per test case review meeting, UEB is considered as
+ // critical as DB. Hence commenting
+ // overallStatus = false;
uebInfo.healthCheckStatus = statusDown;
uebInfo.description = "Check the logs for more details";
EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeUebConnectionError);
@@ -186,12 +187,13 @@ public class HealthCheckController extends EPUnRestrictedBaseController {
}
MDC.put(EPCommonSystemProperties.RESPONSE_CODE, Integer.toString(healthStatus.statusCode));
} catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while performing the healthcheck. Details: "
- + EcompPortalUtils.getStackTrace(e));
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "Exception occurred while performing the healthcheck. Details: "
+ + EcompPortalUtils.getStackTrace(e));
}
-
+
EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/healthCheck", "GET result =", response.getStatus());
-
+
return healthStatus;
}
@@ -202,10 +204,10 @@ public class HealthCheckController extends EPUnRestrictedBaseController {
HealthMonitor.isSuspended = true;
healthStatus.statusCode = 200;
-
+
EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/healthCheckSuspend", "GET result =",
- response.getStatus());
-
+ response.getStatus());
+
return healthStatus;
}
@@ -217,19 +219,15 @@ public class HealthCheckController extends EPUnRestrictedBaseController {
HealthMonitor.isSuspended = false;
healthStatus.statusCode = 200;
EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/healthCheckResume", "GET result =",
- response.getStatus());
+ response.getStatus());
return healthStatus;
}
-
-
- @RequestMapping(value = {
- "/portalApi/ping" }, method = RequestMethod.GET, produces = "application/json")
+ @RequestMapping(value = { "/portalApi/ping" }, method = RequestMethod.GET, produces = "application/json")
public HealthStatus ping(HttpServletRequest request, HttpServletResponse response) {
- HealthStatus healthStatus = new HealthStatus(200, "OK");
- EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/ping", "GET result =",
- response.getStatus());
-
+ HealthStatus healthStatus = new HealthStatus(200, "OK");
+ EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/ping", "GET result =", response.getStatus());
+
return healthStatus;
}
}
diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/MicroserviceController.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/MicroserviceController.java
index 82d70ecd..bc21dd98 100644
--- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/MicroserviceController.java
+++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/MicroserviceController.java
@@ -1,141 +1,139 @@
-/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.controller;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.openecomp.portalapp.controller.EPRestrictedBaseController;
-import org.openecomp.portalapp.portal.domain.MicroserviceData;
-import org.openecomp.portalapp.portal.domain.WidgetCatalog;
-import org.openecomp.portalapp.portal.domain.WidgetServiceHeaders;
-import org.openecomp.portalapp.portal.ecomp.model.PortalRestResponse;
-import org.openecomp.portalapp.portal.ecomp.model.PortalRestStatusEnum;
-import org.openecomp.portalapp.portal.logging.aop.EPAuditLog;
-import org.openecomp.portalapp.portal.service.ConsulHealthService;
-import org.openecomp.portalapp.portal.service.MicroserviceService;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.EnableAspectJAutoProxy;
-import org.springframework.core.ParameterizedTypeReference;
-import org.springframework.http.HttpEntity;
-import org.springframework.http.HttpMethod;
-import org.springframework.http.ResponseEntity;
-import org.springframework.web.bind.annotation.PathVariable;
-import org.springframework.web.bind.annotation.RequestBody;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestMethod;
-import org.springframework.web.bind.annotation.RestController;
-import org.springframework.web.client.RestClientException;
-import org.springframework.web.client.RestTemplate;
-
-@SuppressWarnings("unchecked")
-@RestController
-@org.springframework.context.annotation.Configuration
-@EnableAspectJAutoProxy
-@EPAuditLog
-public class MicroserviceController extends EPRestrictedBaseController {
-
- private static final String HTTPS = "https://";
-
- String whatService = "widgets-service";
- RestTemplate template = new RestTemplate();
-
- @Autowired
- private ConsulHealthService consulHealthService;
-
- @Autowired
- private MicroserviceService microserviceService;
-
- @RequestMapping(value = { "/portalApi/microservices" }, method = RequestMethod.POST)
- public PortalRestResponse<String> createMicroservice(HttpServletRequest request, HttpServletResponse response,
- @RequestBody MicroserviceData newServiceData) throws Exception {
- if (newServiceData == null) {
- return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "FAILURE",
- "MicroserviceData cannot be null or empty");
- }
- long serviceId = microserviceService.saveMicroservice(newServiceData);
-
- try {
- microserviceService.saveServiceParameters(serviceId, newServiceData.getParameterList());
- } catch (Exception e) {
- return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "FAILURE", e.getMessage());
- }
-
- return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "SUCCESS", "");
- }
-
- @RequestMapping(value = { "/portalApi/microservices" }, method = RequestMethod.GET)
- public List<MicroserviceData> getMicroservice(HttpServletRequest request, HttpServletResponse response)
- throws Exception {
- List<MicroserviceData> list = microserviceService.getMicroserviceData();
- return list;
- }
-
- @RequestMapping(value = { "/portalApi/microservices/{serviceId}" }, method = RequestMethod.PUT)
- public PortalRestResponse<String> updateMicroservice(HttpServletRequest request, HttpServletResponse response,
- @PathVariable("serviceId") long serviceId, @RequestBody MicroserviceData newServiceData) throws Exception {
-
- if (newServiceData == null) {
- return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "FAILURE",
- "MicroserviceData cannot be null or empty");
- }
- try {
- microserviceService.updateMicroservice(serviceId, newServiceData);
- } catch (Exception e) {
- return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "FAILURE", e.getMessage());
- }
- return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "SUCCESS", "");
- }
-
- @RequestMapping(value = { "/portalApi/microservices/{serviceId}" }, method = RequestMethod.DELETE)
- public PortalRestResponse<String> deleteMicroservice(HttpServletRequest request, HttpServletResponse response,
- @PathVariable("serviceId") long serviceId) throws Exception {
- try {
- ParameterizedTypeReference<List<WidgetCatalog>> typeRef = new ParameterizedTypeReference<List<WidgetCatalog>>() {
- };
- // If this service is assoicated with widgets, cannnot be deleted
- ResponseEntity<List<WidgetCatalog>> ans = (ResponseEntity<List<WidgetCatalog>>) template.exchange(
- HTTPS + consulHealthService.getServiceLocation(whatService)
- + "/widget/microservices/widgetCatalog/service/" + serviceId,
- HttpMethod.GET, new HttpEntity(WidgetServiceHeaders.getInstance()), typeRef);
- List<WidgetCatalog> widgets = ans.getBody();
- if(widgets.size() == 0)
- microserviceService.deleteMicroservice(serviceId);
- else{
- StringBuilder sb = new StringBuilder();
- for(int i = 0; i < widgets.size(); i++){
- sb.append("'" + widgets.get(i).getName() + "' ");
- if(i < (widgets.size()-1)){
- sb.append(",");
- }
- }
- return new PortalRestResponse<String>(PortalRestStatusEnum.WARN, "SOME WIDGETS ASSOICATE WITH THIS SERVICE", sb.toString());
- }
- } catch (Exception e) {
- return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "FAILURE", e.getMessage());
- }
- return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "SUCCESS", "");
- }
-
-}
+/*-
+ * ================================================================================
+ * ECOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.controller;
+
+import java.util.List;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.openecomp.portalapp.controller.EPRestrictedBaseController;
+import org.openecomp.portalapp.portal.domain.MicroserviceData;
+import org.openecomp.portalapp.portal.domain.WidgetCatalog;
+import org.openecomp.portalapp.portal.domain.WidgetServiceHeaders;
+import org.openecomp.portalapp.portal.ecomp.model.PortalRestResponse;
+import org.openecomp.portalapp.portal.ecomp.model.PortalRestStatusEnum;
+import org.openecomp.portalapp.portal.logging.aop.EPAuditLog;
+import org.openecomp.portalapp.portal.service.ConsulHealthService;
+import org.openecomp.portalapp.portal.service.MicroserviceService;
+import org.openecomp.portalsdk.core.util.SystemProperties;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.EnableAspectJAutoProxy;
+import org.springframework.core.ParameterizedTypeReference;
+import org.springframework.http.HttpEntity;
+import org.springframework.http.HttpMethod;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.client.RestTemplate;
+
+@SuppressWarnings("unchecked")
+@RestController
+@org.springframework.context.annotation.Configuration
+@EnableAspectJAutoProxy
+@EPAuditLog
+public class MicroserviceController extends EPRestrictedBaseController {
+
+ private static final String HTTPS = "https://";
+
+ String whatService = "widgets-service";
+ RestTemplate template = new RestTemplate();
+
+ @Autowired
+ private ConsulHealthService consulHealthService;
+
+ @Autowired
+ private MicroserviceService microserviceService;
+
+ @RequestMapping(value = { "/portalApi/microservices" }, method = RequestMethod.POST)
+ public PortalRestResponse<String> createMicroservice(HttpServletRequest request, HttpServletResponse response,
+ @RequestBody MicroserviceData newServiceData) throws Exception {
+ if (newServiceData == null) {
+ return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "FAILURE",
+ "MicroserviceData cannot be null or empty");
+ }
+ long serviceId = microserviceService.saveMicroservice(newServiceData);
+
+ try {
+ microserviceService.saveServiceParameters(serviceId, newServiceData.getParameterList());
+ } catch (Exception e) {
+ return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "FAILURE", e.getMessage());
+ }
+
+ return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "SUCCESS", "");
+ }
+
+ @RequestMapping(value = { "/portalApi/microservices" }, method = RequestMethod.GET)
+ public List<MicroserviceData> getMicroservice(HttpServletRequest request, HttpServletResponse response)
+ throws Exception {
+ List<MicroserviceData> list = microserviceService.getMicroserviceData();
+ return list;
+ }
+
+ @RequestMapping(value = { "/portalApi/microservices/{serviceId}" }, method = RequestMethod.PUT)
+ public PortalRestResponse<String> updateMicroservice(HttpServletRequest request, HttpServletResponse response,
+ @PathVariable("serviceId") long serviceId, @RequestBody MicroserviceData newServiceData) throws Exception {
+
+ if (newServiceData == null) {
+ return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "FAILURE",
+ "MicroserviceData cannot be null or empty");
+ }
+ try {
+ microserviceService.updateMicroservice(serviceId, newServiceData);
+ } catch (Exception e) {
+ return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "FAILURE", e.getMessage());
+ }
+ return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "SUCCESS", "");
+ }
+
+ @RequestMapping(value = { "/portalApi/microservices/{serviceId}" }, method = RequestMethod.DELETE)
+ public PortalRestResponse<String> deleteMicroservice(HttpServletRequest request, HttpServletResponse response,
+ @PathVariable("serviceId") long serviceId) throws Exception {
+ try {
+ ParameterizedTypeReference<List<WidgetCatalog>> typeRef = new ParameterizedTypeReference<List<WidgetCatalog>>() {
+ };
+ // If this service is assoicated with widgets, cannnot be deleted
+ ResponseEntity<List<WidgetCatalog>> ans = (ResponseEntity<List<WidgetCatalog>>) template.exchange(
+ HTTPS + consulHealthService.getServiceLocation(whatService, SystemProperties.getProperty("microservices.widget.local.port"))
+ + "/widget/microservices/widgetCatalog/service/" + serviceId,
+ HttpMethod.GET, new HttpEntity(WidgetServiceHeaders.getInstance()), typeRef);
+ List<WidgetCatalog> widgets = ans.getBody();
+ if(widgets.size() == 0)
+ microserviceService.deleteMicroservice(serviceId);
+ else{
+ StringBuilder sb = new StringBuilder();
+ for(int i = 0; i < widgets.size(); i++){
+ sb.append("'" + widgets.get(i).getName() + "' ");
+ if(i < (widgets.size()-1)){
+ sb.append(",");
+ }
+ }
+ return new PortalRestResponse<String>(PortalRestStatusEnum.WARN, "SOME WIDGETS ASSOICATE WITH THIS SERVICE", sb.toString());
+ }
+ } catch (Exception e) {
+ return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "FAILURE", e.getMessage());
+ }
+ return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "SUCCESS", "");
+ }
+
+}
diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/MicroserviceProxyController.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/MicroserviceProxyController.java
index 6724d4c6..6313822a 100644
--- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/MicroserviceProxyController.java
+++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/MicroserviceProxyController.java
@@ -1,108 +1,98 @@
-/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.controller;
-
-import java.util.List;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.openecomp.portalapp.controller.EPUnRestrictedBaseController;
-import org.openecomp.portalapp.portal.domain.EPUser;
-import org.openecomp.portalapp.portal.domain.WidgetParameterResult;
-import org.openecomp.portalapp.portal.ecomp.model.PortalRestResponse;
-import org.openecomp.portalapp.portal.ecomp.model.PortalRestStatusEnum;
-import org.openecomp.portalapp.portal.logging.aop.EPAuditLog;
-import org.openecomp.portalapp.portal.service.MicroserviceProxyService;
-import org.openecomp.portalapp.util.EPUserUtils;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.EnableAspectJAutoProxy;
-import org.springframework.web.bind.annotation.PathVariable;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestMethod;
-import org.springframework.web.bind.annotation.RestController;
-import org.springframework.web.client.HttpClientErrorException;
-
-import com.fasterxml.jackson.core.JsonProcessingException;
-import com.fasterxml.jackson.databind.ObjectMapper;
-
-@SuppressWarnings("unchecked")
-@RestController
-@org.springframework.context.annotation.Configuration
-@EnableAspectJAutoProxy
-@EPAuditLog
-public class MicroserviceProxyController extends EPUnRestrictedBaseController {
-
- @Autowired
- private MicroserviceProxyService microserviceProxyService;
-
- EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MicroserviceProxyController.class);
-
- @RequestMapping(value = { "/portalApi/microservice/proxy/{serviceId}" }, method = {
- RequestMethod.GET }, produces = "application/json")
- public String getMicroserviceProxy(HttpServletRequest request, HttpServletResponse response,
- @PathVariable("serviceId") long serviceId) throws Exception {
- EPUser user = EPUserUtils.getUserSession(request);
- String answer = "";
- try{
- answer = microserviceProxyService.proxyToDestination(serviceId, user, request);
- }catch(HttpClientErrorException e){
- //Check whether the error message is valid JSON format
- boolean valid = true;
- ObjectMapper objectMapper = new ObjectMapper();
- try{
- objectMapper.readTree(e.getResponseBodyAsString());
- } catch(JsonProcessingException exception){
- valid = false;
- }
- if(valid)
- return e.getResponseBodyAsString();
- else
- return "{\"error\":\""+ e.getResponseBodyAsString() +"\"}";
- }
- return answer;
- }
-
- @RequestMapping(value = { "/portalApi/microservice/proxy/parameter/{widgetId}" }, method = {
- RequestMethod.GET }, produces = "application/json")
- public String getMicroserviceProxyByWidgetId(HttpServletRequest request, HttpServletResponse response,
- @PathVariable("widgetId") long widgetId) throws Exception {
- EPUser user = EPUserUtils.getUserSession(request);
- String answer = "";
- try{
- answer = microserviceProxyService.proxyToDestinationByWidgetId(widgetId, user, request);
- }catch(HttpClientErrorException e){
- //Check whether the error message is valid JSON format
- boolean valid = true;
- ObjectMapper objectMapper = new ObjectMapper();
- try{
- objectMapper.readTree(e.getResponseBodyAsString());
- } catch(JsonProcessingException exception){
- valid = false;
- }
- if(valid)
- return e.getResponseBodyAsString();
- else
- return "{\"error\":\""+ e.getResponseBodyAsString() +"\"}";
- }
- return answer;
- }
-}
+/*-
+ * ================================================================================
+ * ECOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.controller;
+
+import java.io.IOException;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.openecomp.portalapp.controller.EPUnRestrictedBaseController;
+import org.openecomp.portalapp.portal.domain.EPUser;
+import org.openecomp.portalapp.portal.logging.aop.EPAuditLog;
+import org.openecomp.portalapp.portal.service.MicroserviceProxyService;
+import org.openecomp.portalapp.util.EPUserUtils;
+import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.EnableAspectJAutoProxy;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.client.HttpClientErrorException;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+@SuppressWarnings("unchecked")
+@RestController
+@org.springframework.context.annotation.Configuration
+@EnableAspectJAutoProxy
+@EPAuditLog
+public class MicroserviceProxyController extends EPUnRestrictedBaseController {
+
+ @Autowired
+ private MicroserviceProxyService microserviceProxyService;
+
+ EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MicroserviceProxyController.class);
+
+ @RequestMapping(value = { "/portalApi/microservice/proxy/{serviceId}" }, method = {
+ RequestMethod.GET }, produces = "application/json")
+ public String getMicroserviceProxy(HttpServletRequest request, HttpServletResponse response,
+ @PathVariable("serviceId") long serviceId) throws Exception {
+ EPUser user = EPUserUtils.getUserSession(request);
+ String answer = "";
+ try {
+ answer = microserviceProxyService.proxyToDestination(serviceId, user, request);
+ } catch (HttpClientErrorException e) {
+ answer = e.getResponseBodyAsString();
+ }
+ return isValidJSON(answer) ? answer : "{\"error\":\"" + answer.replace(System.getProperty("line.separator"), "") + "\"}";
+ }
+
+ @RequestMapping(value = { "/portalApi/microservice/proxy/parameter/{widgetId}" }, method = {
+ RequestMethod.GET }, produces = "application/json")
+ public String getMicroserviceProxyByWidgetId(HttpServletRequest request, HttpServletResponse response,
+ @PathVariable("widgetId") long widgetId) throws Exception {
+ EPUser user = EPUserUtils.getUserSession(request);
+ String answer = "";
+ try {
+ answer = microserviceProxyService.proxyToDestinationByWidgetId(widgetId, user, request);
+ } catch (HttpClientErrorException e) {
+ answer = e.getResponseBodyAsString();
+ }
+ return isValidJSON(answer) ? answer : "{\"error\":\"" + answer.replace(System.getProperty("line.separator"), "") + "\"}";
+ }
+
+ /**
+ * Check whether the response is a valid JSON
+ * @param response
+ * @return true if the response is valid JSON, otherwise, false
+ */
+ private boolean isValidJSON(String response) {
+ try {
+ final ObjectMapper mapper = new ObjectMapper();
+ mapper.readTree(response);
+ return true;
+ } catch (IOException e) {
+ return false;
+ }
+ }
+}
diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/PortalAdminController.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/PortalAdminController.java
index 2499ec66..b98a7cb4 100644
--- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/PortalAdminController.java
+++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/PortalAdminController.java
@@ -1,200 +1,209 @@
-/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.controller;
-
-import java.util.List;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.slf4j.MDC;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.EnableAspectJAutoProxy;
-import org.springframework.web.bind.annotation.PathVariable;
-import org.springframework.web.bind.annotation.RequestBody;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestMethod;
-import org.springframework.web.bind.annotation.RestController;
-
-import org.openecomp.portalsdk.core.domain.AuditLog;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalsdk.core.service.AuditService;
-import org.openecomp.portalapp.controller.EPRestrictedBaseController;
-import org.openecomp.portalapp.portal.domain.EPRole;
-import org.openecomp.portalapp.portal.domain.EPUser;
-import org.openecomp.portalapp.portal.domain.EcompAuditLog;
-import org.openecomp.portalapp.portal.logging.aop.EPAuditLog;
-import org.openecomp.portalapp.portal.logging.aop.EPEELFLoggerAdvice;
-import org.openecomp.portalapp.portal.logging.logic.EPLogUtil;
-import org.openecomp.portalapp.portal.service.AdminRolesService;
-import org.openecomp.portalapp.portal.service.PortalAdminService;
-import org.openecomp.portalapp.portal.transport.FieldsValidator;
-import org.openecomp.portalapp.portal.transport.PortalAdmin;
-import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties;
-import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
-import org.openecomp.portalapp.util.EPUserUtils;
-
-@RestController
-@org.springframework.context.annotation.Configuration
-@EnableAspectJAutoProxy
-@EPAuditLog
-public class PortalAdminController extends EPRestrictedBaseController {
- @Autowired
- PortalAdminService portalAdminService;
- @Autowired
- AdminRolesService adminRolesService;
- @Autowired
- AuditService auditService;
-
- EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PortalAdminController.class);
-
- @RequestMapping(value = { "/portalApi/portalAdmins" }, method = RequestMethod.GET, produces = "application/json")
- public List<PortalAdmin> getPortalAdmins(HttpServletRequest request, HttpServletResponse response) {
- EPUser user = EPUserUtils.getUserSession(request);
- List<PortalAdmin> portalAdmins = null;
- if (user == null) {
- logger.debug(EELFLoggerDelegate.debugLogger, "PortalAdminController.getPortalAdmins, null user");
- EcompPortalUtils.setBadPermissions(user, response, "getPortalAdmins");
- } else if (!adminRolesService.isSuperAdmin(user)) {
- logger.debug(EELFLoggerDelegate.debugLogger, "PortalAdminController.getPortalAdmins, bad permissions");
- EcompPortalUtils.setBadPermissions(user, response, "createPortalAdmin");
- } else {
- // return the list of portal admins
- portalAdmins = portalAdminService.getPortalAdmins();
- logger.debug(EELFLoggerDelegate.debugLogger, "portalAdmins: called getPortalAdmins()");
- EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/getPortalAdmins", "result =", portalAdmins);
- }
-
- return portalAdmins;
- }
-
- /**
- * RESTful service method to create a new portal admin. Requirement: you
- * must be the Ecomp portal super admin user.
- */
-
- @RequestMapping(value = { "/portalApi/portalAdmin" }, method = RequestMethod.POST)
- public FieldsValidator createPortalAdmin(HttpServletRequest request, @RequestBody String sbcid,
- HttpServletResponse response) {
- EPUser user = EPUserUtils.getUserSession(request);
- FieldsValidator fieldsValidator = null;
- if (user == null) {
- logger.debug(EELFLoggerDelegate.debugLogger, "PortalAdminController.createPortalAdmin, null user");
- EcompPortalUtils.setBadPermissions(user, response, "createPortalAdmin");
- } else if (!adminRolesService.isSuperAdmin(user)) {
- logger.debug(EELFLoggerDelegate.debugLogger, "PortalAdminController.createPortalAdmin bad permissions");
- EcompPortalUtils.setBadPermissions(user, response, "createPortalAdmin");
- } else {
- fieldsValidator = portalAdminService.createPortalAdmin(sbcid);
- int statusCode = fieldsValidator.httpStatusCode.intValue();
- response.setStatus(statusCode);
- if (statusCode == 200) {
- AuditLog auditLog = new AuditLog();
- auditLog.setUserId(user.getId());
- auditLog.setActivityCode(EcompAuditLog.CD_ACTIVITY_ADD_PORTAL_ADMIN);
- auditLog.setAffectedRecordId(sbcid);
- auditService.logActivity(auditLog, null);
-
- MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
- MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
- logger.info(EELFLoggerDelegate.auditLogger,
- EPLogUtil.formatAuditLogMessage("PortalAdminController.createPortalAdmin",
- EcompAuditLog.CD_ACTIVITY_ADD_PORTAL_ADMIN, user.getOrgUserId(), sbcid,
- "A new Portal Admin has been added"));
- MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
- MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
- }
- }
- EcompPortalUtils.logAndSerializeObject(logger, "/portalAdmin", "POST result =", response.getStatus());
-
- return fieldsValidator;
- }
-
- @RequestMapping(value = { "/portalApi/portalAdmin/{userInfo}" }, method = RequestMethod.DELETE)
- public FieldsValidator deletePortalAdmin(HttpServletRequest request, @PathVariable("userInfo") String userInfo,
- HttpServletResponse response) {
- int userIdIdx = userInfo.indexOf("-");
- Long userId = null;
- String sbcid = null;
- FieldsValidator fieldsValidator = null;
- try{
- if(userIdIdx==-1){
- logger.error(EELFLoggerDelegate.errorLogger,"deletePortalAdmin missing userId");
- return fieldsValidator;
- }else{
- String userIdStr = userInfo.substring(0, userIdIdx);
- userId = Long.valueOf(userIdStr);
- sbcid = userInfo.substring(userIdIdx+1, userInfo.length());
- }
- }catch(Exception e){
- logger.error(EELFLoggerDelegate.errorLogger,"deletePortalAdmin error while parsing the userInfo",e);
- }
- EPUser user = EPUserUtils.getUserSession(request);
- if (!adminRolesService.isSuperAdmin(user)) {
- EcompPortalUtils.setBadPermissions(user, response, "deletePortalAdmin");
- } else {
- fieldsValidator = portalAdminService.deletePortalAdmin(userId);
- int statusCode = fieldsValidator.httpStatusCode.intValue();
- response.setStatus(statusCode);
- if (statusCode == 200) {
- AuditLog auditLog = new AuditLog();
- auditLog.setUserId(user.getId());
- auditLog.setActivityCode(EcompAuditLog.CD_ACTIVITY_DELETE_PORTAL_ADMIN);
- auditLog.setAffectedRecordId(sbcid);
- auditService.logActivity(auditLog, null);
-
- MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
- MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
- logger.info(EELFLoggerDelegate.auditLogger,
- EPLogUtil.formatAuditLogMessage("PortalAdminController.deletePortalAdmin",
- EcompAuditLog.CD_ACTIVITY_DELETE_PORTAL_ADMIN, user.getOrgUserId(), sbcid,
- "A Portal Admin has been deleted"));
- MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
- MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
- }
- }
- EcompPortalUtils.logAndSerializeObject(logger, "/portalAdmin", "DELETE result =", response.getStatus());
-
- return fieldsValidator;
- }
-
- @RequestMapping(value = {
- "/portalApi/adminAppsRoles/{appId}" }, method = RequestMethod.GET, produces = "application/json")
- public List<EPRole> getRolesByApp(HttpServletRequest request, @PathVariable("appId") Long appId,
- HttpServletResponse response) {
- EPUser user = EPUserUtils.getUserSession(request);
- List<EPRole> rolesByApp = null;
-
- try {
- if (user == null) {
- EcompPortalUtils.setBadPermissions(user, response, "getUserApps");
- } else {
- rolesByApp = adminRolesService.getRolesByApp(user, appId);
- }
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger,
- "Exception occurred while performing getRolesByApp operation, Details: "
- + EcompPortalUtils.getStackTrace(e));
- }
-
- return rolesByApp;
- }
-
-}
+/*-
+ * ================================================================================
+ * ECOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.controller;
+
+import java.util.List;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.slf4j.MDC;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.EnableAspectJAutoProxy;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.RestController;
+
+import org.openecomp.portalsdk.core.domain.AuditLog;
+import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.openecomp.portalsdk.core.service.AuditService;
+import org.openecomp.portalsdk.core.util.SystemProperties;
+import org.openecomp.portalapp.controller.EPRestrictedBaseController;
+import org.openecomp.portalapp.portal.domain.EPRole;
+import org.openecomp.portalapp.portal.domain.EPUser;
+import org.openecomp.portalapp.portal.domain.EcompAuditLog;
+import org.openecomp.portalapp.portal.logging.aop.EPAuditLog;
+import org.openecomp.portalapp.portal.logging.aop.EPEELFLoggerAdvice;
+import org.openecomp.portalapp.portal.logging.logic.EPLogUtil;
+import org.openecomp.portalapp.portal.service.AdminRolesService;
+import org.openecomp.portalapp.portal.service.PortalAdminService;
+import org.openecomp.portalapp.portal.transport.FieldsValidator;
+import org.openecomp.portalapp.portal.transport.PortalAdmin;
+import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties;
+import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
+import org.openecomp.portalapp.util.EPUserUtils;
+
+@RestController
+@org.springframework.context.annotation.Configuration
+@EnableAspectJAutoProxy
+@EPAuditLog
+public class PortalAdminController extends EPRestrictedBaseController {
+ @Autowired
+ PortalAdminService portalAdminService;
+ @Autowired
+ AdminRolesService adminRolesService;
+ @Autowired
+ AuditService auditService;
+
+ EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PortalAdminController.class);
+
+ @RequestMapping(value = { "/portalApi/portalAdmins" }, method = RequestMethod.GET, produces = "application/json")
+ public List<PortalAdmin> getPortalAdmins(HttpServletRequest request, HttpServletResponse response) {
+ EPUser user = EPUserUtils.getUserSession(request);
+ List<PortalAdmin> portalAdmins = null;
+ if (user == null) {
+ logger.debug(EELFLoggerDelegate.debugLogger, "PortalAdminController.getPortalAdmins, null user");
+ EcompPortalUtils.setBadPermissions(user, response, "getPortalAdmins");
+ } else if (!adminRolesService.isSuperAdmin(user)) {
+ logger.debug(EELFLoggerDelegate.debugLogger, "PortalAdminController.getPortalAdmins, bad permissions");
+ EcompPortalUtils.setBadPermissions(user, response, "createPortalAdmin");
+ } else {
+ // return the list of portal admins
+ portalAdmins = portalAdminService.getPortalAdmins();
+ logger.debug(EELFLoggerDelegate.debugLogger, "portalAdmins: called getPortalAdmins()");
+ EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/getPortalAdmins", "result =", portalAdmins);
+ }
+
+ return portalAdmins;
+ }
+
+ /**
+ * RESTful service method to create a new portal admin. Requirement: you
+ * must be the Ecomp portal super admin user.
+ */
+
+ @RequestMapping(value = { "/portalApi/portalAdmin" }, method = RequestMethod.POST)
+ public FieldsValidator createPortalAdmin(HttpServletRequest request, @RequestBody String userId,
+ HttpServletResponse response) {
+ EPUser user = EPUserUtils.getUserSession(request);
+ FieldsValidator fieldsValidator = null;
+ if (user == null) {
+ logger.debug(EELFLoggerDelegate.debugLogger, "PortalAdminController.createPortalAdmin, null user");
+ EcompPortalUtils.setBadPermissions(user, response, "createPortalAdmin");
+ } else if (!adminRolesService.isSuperAdmin(user)) {
+ logger.debug(EELFLoggerDelegate.debugLogger, "PortalAdminController.createPortalAdmin bad permissions");
+ EcompPortalUtils.setBadPermissions(user, response, "createPortalAdmin");
+ } else {
+ fieldsValidator = portalAdminService.createPortalAdmin(userId);
+ int statusCode = fieldsValidator.httpStatusCode.intValue();
+ response.setStatus(statusCode);
+ if (statusCode == 200) {
+ AuditLog auditLog = new AuditLog();
+ auditLog.setUserId(user.getId());
+ auditLog.setActivityCode(EcompAuditLog.CD_ACTIVITY_ADD_PORTAL_ADMIN);
+ auditLog.setAffectedRecordId(userId);
+ auditService.logActivity(auditLog, null);
+
+ MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
+ MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
+ EcompPortalUtils.calculateDateTimeDifferenceForLog(
+ MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),
+ MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
+ logger.info(EELFLoggerDelegate.auditLogger,
+ EPLogUtil.formatAuditLogMessage("PortalAdminController.createPortalAdmin",
+ EcompAuditLog.CD_ACTIVITY_ADD_PORTAL_ADMIN, user.getOrgUserId(), userId,
+ "A new Portal Admin has been added"));
+ MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
+ MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
+ MDC.remove(SystemProperties.MDC_TIMER);
+ }
+ }
+ EcompPortalUtils.logAndSerializeObject(logger, "/portalAdmin", "POST result =", response.getStatus());
+
+ return fieldsValidator;
+ }
+
+ @RequestMapping(value = { "/portalApi/portalAdmin/{userInfo}" }, method = RequestMethod.DELETE)
+ public FieldsValidator deletePortalAdmin(HttpServletRequest request, @PathVariable("userInfo") String userInfo,
+ HttpServletResponse response) {
+ int userIdIdx = userInfo.indexOf("-");
+ Long userId = null;
+ String sbcid = null;
+ FieldsValidator fieldsValidator = null;
+ try {
+ if (userIdIdx == -1) {
+ logger.error(EELFLoggerDelegate.errorLogger, "deletePortalAdmin missing userId");
+ return fieldsValidator;
+ } else {
+ String userIdStr = userInfo.substring(0, userIdIdx);
+ userId = Long.valueOf(userIdStr);
+ sbcid = userInfo.substring(userIdIdx + 1, userInfo.length());
+ }
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "deletePortalAdmin error while parsing the userInfo", e);
+ }
+ EPUser user = EPUserUtils.getUserSession(request);
+ if (!adminRolesService.isSuperAdmin(user)) {
+ EcompPortalUtils.setBadPermissions(user, response, "deletePortalAdmin");
+ } else {
+ fieldsValidator = portalAdminService.deletePortalAdmin(userId);
+ int statusCode = fieldsValidator.httpStatusCode.intValue();
+ response.setStatus(statusCode);
+ if (statusCode == 200) {
+ AuditLog auditLog = new AuditLog();
+ auditLog.setUserId(user.getId());
+ auditLog.setActivityCode(EcompAuditLog.CD_ACTIVITY_DELETE_PORTAL_ADMIN);
+ auditLog.setAffectedRecordId(sbcid);
+ auditService.logActivity(auditLog, null);
+
+ MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
+ MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
+ EcompPortalUtils.calculateDateTimeDifferenceForLog(
+ MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),
+ MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
+ logger.info(EELFLoggerDelegate.auditLogger,
+ EPLogUtil.formatAuditLogMessage("PortalAdminController.deletePortalAdmin",
+ EcompAuditLog.CD_ACTIVITY_DELETE_PORTAL_ADMIN, user.getOrgUserId(), sbcid,
+ "A Portal Admin has been deleted"));
+ MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
+ MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
+ MDC.remove(SystemProperties.MDC_TIMER);
+ }
+ }
+ EcompPortalUtils.logAndSerializeObject(logger, "/portalAdmin", "DELETE result =", response.getStatus());
+
+ return fieldsValidator;
+ }
+
+ @RequestMapping(value = {
+ "/portalApi/adminAppsRoles/{appId}" }, method = RequestMethod.GET, produces = "application/json")
+ public List<EPRole> getRolesByApp(HttpServletRequest request, @PathVariable("appId") Long appId,
+ HttpServletResponse response) {
+ EPUser user = EPUserUtils.getUserSession(request);
+ List<EPRole> rolesByApp = null;
+
+ try {
+ if (user == null) {
+ EcompPortalUtils.setBadPermissions(user, response, "getUserApps");
+ } else {
+ rolesByApp = adminRolesService.getRolesByApp(user, appId);
+ }
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "Exception occurred while performing getRolesByApp operation, Details: "
+ + EcompPortalUtils.getStackTrace(e));
+ }
+
+ return rolesByApp;
+ }
+
+}
diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/RoleManageController.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/RoleManageController.java
index d567269f..2d0fe279 100644
--- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/RoleManageController.java
+++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/RoleManageController.java
@@ -1,166 +1,166 @@
-/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.controller;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.openecomp.portalapp.controller.EPRestrictedBaseController;
-import org.openecomp.portalapp.controller.core.RoleController;
-import org.openecomp.portalapp.controller.core.RoleFunctionListController;
-import org.openecomp.portalapp.controller.core.RoleListController;
-import org.openecomp.portalapp.portal.ecomp.model.PortalRestResponse;
-import org.openecomp.portalapp.portal.ecomp.model.PortalRestStatusEnum;
-import org.openecomp.portalapp.portal.logging.aop.EPAuditLog;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.EnableAspectJAutoProxy;
-import org.springframework.web.bind.annotation.RequestBody;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestMethod;
-import org.springframework.web.bind.annotation.RestController;
-import org.springframework.web.servlet.ModelAndView;
-
-/**
- * Proxies REST calls to role-management functions that arrive on paths
- * /portalApi/* over to controller methods provided by the SDK-Core library.
- * Those controller methods are mounted on paths not exposed by the Portal FE.
- */
-@RestController
-@org.springframework.context.annotation.Configuration
-@EnableAspectJAutoProxy
-@EPAuditLog
-public class RoleManageController extends EPRestrictedBaseController {
-
- @Autowired
- private RoleController roleController;
-
- @Autowired
- private RoleListController roleListController;
-
- @Autowired
- private RoleFunctionListController roleFunctionListController;
-
- /**
- * Calls an SDK-Core library method that gets the available roles and writes
- * them to the request object. Portal specifies a Hibernate mappings from
- * the Role class to the fn_role_v view, which ensures that only Portal
- * (app_id is null) roles are fetched.
- *
- * Any method declared void (no return value) or returning null causes the
- * audit log aspect method to declare failure. TODO: should return a JSON
- * string.
- *
- * @param request
- * @param response
- */
- @RequestMapping(value = { "/portalApi/get_roles" }, method = RequestMethod.GET)
- public void getRoles(HttpServletRequest request, HttpServletResponse response) {
- getRoleListController().getRoles(request, response);
- }
-
- @RequestMapping(value = { "/portalApi/role_list/toggleRole" }, method = RequestMethod.POST)
- public PortalRestResponse<String> toggleRole(HttpServletRequest request, HttpServletResponse response) {
- PortalRestResponse<String> portalRestResponse = null;
- try{
- getRoleListController().toggleRole(request, response);
- portalRestResponse = new PortalRestResponse<String>(PortalRestStatusEnum.OK, "success", null);
- }catch (Exception e) {
- return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "failure", e.getMessage());
- }
- return portalRestResponse;
- }
-
- @RequestMapping(value = { "/portalApi/role_list/removeRole" }, method = RequestMethod.POST)
- public ModelAndView removeRole(HttpServletRequest request, HttpServletResponse response) throws Exception {
- return getRoleListController().removeRole(request, response);
- }
-
- @RequestMapping(value = { "/portalApi/role/saveRole" }, method = RequestMethod.POST)
- public ModelAndView saveRole(HttpServletRequest request, HttpServletResponse response) throws Exception {
- return getRoleController().saveRole(request, response);
- }
-
- @RequestMapping(value = { "/portalApi/role/removeRoleFunction" }, method = RequestMethod.POST)
- public ModelAndView removeRoleRoleFunction(HttpServletRequest request, HttpServletResponse response)
- throws Exception {
- return getRoleController().removeRoleFunction(request, response);
- }
-
- @RequestMapping(value = { "/portalApi/role/addRoleFunction" }, method = RequestMethod.POST)
- public ModelAndView addRoleRoRoleFunction(HttpServletRequest request, HttpServletResponse response)
- throws Exception {
- return getRoleController().addRoleFunction(request, response);
- }
-
- @RequestMapping(value = { "/portalApi/role/removeChildRole" }, method = RequestMethod.POST)
- public ModelAndView removeChildRole(HttpServletRequest request, HttpServletResponse response) throws Exception {
- return getRoleController().removeChildRole(request, response);
- }
-
- @RequestMapping(value = { "/portalApi/role/addChildRole" }, method = RequestMethod.POST)
- public ModelAndView addChildRole(HttpServletRequest request, HttpServletResponse response) throws Exception {
- return getRoleController().addChildRole(request, response);
- }
-
- @RequestMapping(value = { "/portalApi/get_role" }, method = RequestMethod.GET)
- public void getRole(HttpServletRequest request, HttpServletResponse response) {
- getRoleController().getRole(request, response);
- }
-
- @RequestMapping(value = { "/portalApi/get_role_functions" }, method = RequestMethod.GET)
- public void getRoleFunctionList(HttpServletRequest request, HttpServletResponse response) {
- getRoleFunctionListController().getRoleFunctionList(request, response);
- }
-
- @RequestMapping(value = { "/portalApi/role_function_list/saveRoleFunction" }, method = RequestMethod.POST)
- public void saveRoleFunction(HttpServletRequest request, HttpServletResponse response, @RequestBody String roleFunc) throws Exception {
- getRoleFunctionListController().saveRoleFunction(request, response, roleFunc);
- }
-
- @RequestMapping(value = { "/portalApi/role_function_list/removeRoleFunction" }, method = RequestMethod.POST)
- public void removeRoleFunction(HttpServletRequest request, HttpServletResponse response, @RequestBody String roleFunc) throws Exception {
- getRoleFunctionListController().removeRoleFunction(request, response, roleFunc);
- }
-
- public RoleListController getRoleListController() {
- return roleListController;
- }
-
- public void setRoleListController(RoleListController roleListController) {
- this.roleListController = roleListController;
- }
-
- public RoleController getRoleController() {
- return roleController;
- }
-
- public void setRoleController(RoleController roleController) {
- this.roleController = roleController;
- }
-
- public RoleFunctionListController getRoleFunctionListController() {
- return roleFunctionListController;
- }
-
- public void setRoleFunctionListController(RoleFunctionListController roleFunctionListController) {
- this.roleFunctionListController = roleFunctionListController;
- }
-
-}
+/*-
+ * ================================================================================
+ * ECOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.controller;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.openecomp.portalapp.controller.EPRestrictedBaseController;
+import org.openecomp.portalapp.controller.core.RoleController;
+import org.openecomp.portalapp.controller.core.RoleFunctionListController;
+import org.openecomp.portalapp.controller.core.RoleListController;
+import org.openecomp.portalapp.portal.ecomp.model.PortalRestResponse;
+import org.openecomp.portalapp.portal.ecomp.model.PortalRestStatusEnum;
+import org.openecomp.portalapp.portal.logging.aop.EPAuditLog;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.EnableAspectJAutoProxy;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.servlet.ModelAndView;
+
+/**
+ * Proxies REST calls to role-management functions that arrive on paths
+ * /portalApi/* over to controller methods provided by the SDK-Core library.
+ * Those controller methods are mounted on paths not exposed by the Portal FE.
+ */
+@RestController
+@org.springframework.context.annotation.Configuration
+@EnableAspectJAutoProxy
+@EPAuditLog
+public class RoleManageController extends EPRestrictedBaseController {
+
+ @Autowired
+ private RoleController roleController;
+
+ @Autowired
+ private RoleListController roleListController;
+
+ @Autowired
+ private RoleFunctionListController roleFunctionListController;
+
+ /**
+ * Calls an SDK-Core library method that gets the available roles and writes
+ * them to the request object. Portal specifies a Hibernate mappings from
+ * the Role class to the fn_role_v view, which ensures that only Portal
+ * (app_id is null) roles are fetched.
+ *
+ * Any method declared void (no return value) or returning null causes the
+ * audit log aspect method to declare failure. TODO: should return a JSON
+ * string.
+ *
+ * @param request
+ * @param response
+ */
+ @RequestMapping(value = { "/portalApi/get_roles" }, method = RequestMethod.GET)
+ public void getRoles(HttpServletRequest request, HttpServletResponse response) {
+ getRoleListController().getRoles(request, response);
+ }
+
+ @RequestMapping(value = { "/portalApi/role_list/toggleRole" }, method = RequestMethod.POST)
+ public PortalRestResponse<String> toggleRole(HttpServletRequest request, HttpServletResponse response) {
+ PortalRestResponse<String> portalRestResponse = null;
+ try{
+ getRoleListController().toggleRole(request, response);
+ portalRestResponse = new PortalRestResponse<String>(PortalRestStatusEnum.OK, "success", null);
+ }catch (Exception e) {
+ return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "failure", e.getMessage());
+ }
+ return portalRestResponse;
+ }
+
+ @RequestMapping(value = { "/portalApi/role_list/removeRole" }, method = RequestMethod.POST)
+ public ModelAndView removeRole(HttpServletRequest request, HttpServletResponse response) throws Exception {
+ return getRoleListController().removeRole(request, response);
+ }
+
+ @RequestMapping(value = { "/portalApi/role/saveRole" }, method = RequestMethod.POST)
+ public ModelAndView saveRole(HttpServletRequest request, HttpServletResponse response) throws Exception {
+ return getRoleController().saveRole(request, response);
+ }
+
+ @RequestMapping(value = { "/portalApi/role/removeRoleFunction" }, method = RequestMethod.POST)
+ public ModelAndView removeRoleRoleFunction(HttpServletRequest request, HttpServletResponse response)
+ throws Exception {
+ return getRoleController().removeRoleFunction(request, response);
+ }
+
+ @RequestMapping(value = { "/portalApi/role/addRoleFunction" }, method = RequestMethod.POST)
+ public ModelAndView addRoleRoRoleFunction(HttpServletRequest request, HttpServletResponse response)
+ throws Exception {
+ return getRoleController().addRoleFunction(request, response);
+ }
+
+ @RequestMapping(value = { "/portalApi/role/removeChildRole" }, method = RequestMethod.POST)
+ public ModelAndView removeChildRole(HttpServletRequest request, HttpServletResponse response) throws Exception {
+ return getRoleController().removeChildRole(request, response);
+ }
+
+ @RequestMapping(value = { "/portalApi/role/addChildRole" }, method = RequestMethod.POST)
+ public ModelAndView addChildRole(HttpServletRequest request, HttpServletResponse response) throws Exception {
+ return getRoleController().addChildRole(request, response);
+ }
+
+ @RequestMapping(value = { "/portalApi/get_role" }, method = RequestMethod.GET)
+ public void getRole(HttpServletRequest request, HttpServletResponse response) {
+ getRoleController().getRole(request, response);
+ }
+
+ @RequestMapping(value = { "/portalApi/get_role_functions" }, method = RequestMethod.GET)
+ public void getRoleFunctionList(HttpServletRequest request, HttpServletResponse response) {
+ getRoleFunctionListController().getRoleFunctionList(request, response);
+ }
+
+ @RequestMapping(value = { "/portalApi/role_function_list/saveRoleFunction" }, method = RequestMethod.POST)
+ public void saveRoleFunction(HttpServletRequest request, HttpServletResponse response, @RequestBody String roleFunc) throws Exception {
+ getRoleFunctionListController().saveRoleFunction(request, response, roleFunc);
+ }
+
+ @RequestMapping(value = { "/portalApi/role_function_list/removeRoleFunction" }, method = RequestMethod.POST)
+ public void removeRoleFunction(HttpServletRequest request, HttpServletResponse response, @RequestBody String roleFunc) throws Exception {
+ getRoleFunctionListController().removeRoleFunction(request, response, roleFunc);
+ }
+
+ public RoleListController getRoleListController() {
+ return roleListController;
+ }
+
+ public void setRoleListController(RoleListController roleListController) {
+ this.roleListController = roleListController;
+ }
+
+ public RoleController getRoleController() {
+ return roleController;
+ }
+
+ public void setRoleController(RoleController roleController) {
+ this.roleController = roleController;
+ }
+
+ public RoleFunctionListController getRoleFunctionListController() {
+ return roleFunctionListController;
+ }
+
+ public void setRoleFunctionListController(RoleFunctionListController roleFunctionListController) {
+ this.roleFunctionListController = roleFunctionListController;
+ }
+
+}
diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/RolesApprovalSystemController.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/RolesApprovalSystemController.java
new file mode 100644
index 00000000..c150528e
--- /dev/null
+++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/RolesApprovalSystemController.java
@@ -0,0 +1,199 @@
+/*-
+ * ================================================================================
+ * ECOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+
+package org.openecomp.portalapp.portal.controller;
+
+import java.util.ArrayList;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.openecomp.portalapp.externalsystemapproval.model.ExternalSystemRoleApproval;
+import org.openecomp.portalapp.externalsystemapproval.model.ExternalSystemUser;
+import org.openecomp.portalapp.portal.ecomp.model.PortalRestResponse;
+import org.openecomp.portalapp.portal.ecomp.model.PortalRestStatusEnum;
+import org.openecomp.portalapp.portal.logging.aop.EPAuditLog;
+import org.openecomp.portalapp.portal.service.UserRolesService;
+import org.openecomp.portalapp.portal.transport.ExternalRequestFieldsValidator;
+import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.EnableAspectJAutoProxy;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.RestController;
+
+import io.swagger.annotations.ApiOperation;
+
+@RestController
+@RequestMapping("/auxapi")
+@Configuration
+@EnableAspectJAutoProxy
+@EPAuditLog
+public class RolesApprovalSystemController implements BasicAuthenticationController {
+
+ private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RolesApprovalSystemController.class);
+
+ @Autowired
+ private UserRolesService userRolesService;
+
+ /**
+ * Creates an application user with the specified roles.
+ *
+ * @param request
+ * @param extSysUser
+ * @return PortalRestResponse with appropriate status value and message
+ */
+ @ApiOperation(value = "Creates an application user with the specified roles.", response = PortalRestResponse.class)
+ @RequestMapping(value = { "/userProfile" }, method = RequestMethod.POST, produces = "application/json")
+ public PortalRestResponse<String> postUserProfile(HttpServletRequest request,
+ @RequestBody ExternalSystemUser extSysUser, HttpServletResponse response) {
+ ExternalRequestFieldsValidator reqResult = null;
+ try {
+ logger.info(EELFLoggerDelegate.debugLogger, "postUserProfile: request received for app {}, user {}",
+ extSysUser.getApplicationName(), extSysUser.getLoginId());
+
+ validateExtSystemUser(extSysUser, true);
+ reqResult = userRolesService.setExternalRequestUserAppRole(extSysUser, "POST");
+ if (!reqResult.isResult())
+ throw new Exception(reqResult.getDetailMessage());
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "postUserProfile: failed for app {}, user {}",
+ extSysUser.getApplicationName(), extSysUser.getLoginId(), e);
+ if(reqResult == null || (!reqResult.isResult() && !e.getMessage().contains("404"))){
+ response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
+ return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR,
+ e.getMessage(), "save user profile failed");
+ } else if(e.getMessage().contains("404")){
+ response.setStatus(HttpServletResponse.SC_NOT_FOUND);
+ return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR,
+ e.getMessage(), "save user profile failed");
+ } else{
+ response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR,
+ e.getMessage(), "save user profile failed");
+ }
+ }
+ return new PortalRestResponse<String>(PortalRestStatusEnum.OK, reqResult.getDetailMessage(), "Success");
+ }
+
+ /**
+ * Updates an application user to have only the specified roles.
+ *
+ * @param request
+ * @param extSysUser
+ * @return PortalRestResponse with appropriate status value and message
+ */
+ @ApiOperation(value = "Updates an application user to have only the specified roles.", response = PortalRestResponse.class)
+ @RequestMapping(value = { "/userProfile" }, method = RequestMethod.PUT, produces = "application/json")
+ public PortalRestResponse<String> putUserProfile(HttpServletRequest request,
+ @RequestBody ExternalSystemUser extSysUser, HttpServletResponse response) {
+ ExternalRequestFieldsValidator reqResult = null;
+ try {
+ logger.info(EELFLoggerDelegate.debugLogger, "putUserProfile: request received for app {}, user {}",
+ extSysUser.getApplicationName(), extSysUser.getLoginId());
+ validateExtSystemUser(extSysUser, true);
+ reqResult = userRolesService.setExternalRequestUserAppRole(extSysUser, "PUT");
+ if (!reqResult.isResult())
+ throw new Exception(reqResult.getDetailMessage());
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "putUserProfile: failed for app {}, user {}",
+ extSysUser.getApplicationName(), extSysUser.getLoginId(), e);
+ if(reqResult == null || (!reqResult.isResult() && !e.getMessage().contains("404"))){
+ response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
+ return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR,
+ e.getMessage(), "save user profile failed");
+ } else if(e.getMessage().contains("404")){
+ response.setStatus(HttpServletResponse.SC_NOT_FOUND);
+ return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR,
+ e.getMessage(), "save user profile failed");
+ } else{
+ response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR,
+ e.getMessage(), "save user profile failed");
+ }
+ }
+ return new PortalRestResponse<String>(PortalRestStatusEnum.OK, reqResult.getDetailMessage() , "Success");
+ }
+
+ /**
+ * Deletes an application user by removing all assigned roles.
+ *
+ * @param request
+ * @param extSysUser
+ * This object must have zero roles.
+ * @return PortalRestResponse with appropriate status value and message
+ */
+ @ApiOperation(value = "Processes a request to delete one or more application roles for one specified user who has roles.", response = PortalRestResponse.class)
+ @RequestMapping(value = { "/userProfile" }, method = RequestMethod.DELETE, produces = "application/json")
+ public PortalRestResponse<String> deleteUserProfile(HttpServletRequest request,
+ @RequestBody ExternalSystemUser extSysUser, HttpServletResponse response) {
+ ExternalRequestFieldsValidator reqResult = null;
+ try {
+ logger.info(EELFLoggerDelegate.debugLogger, "deleteUserProfile: request received for app {}, user {}",
+ extSysUser.getApplicationName(), extSysUser.getLoginId());
+ validateExtSystemUser(extSysUser, false);
+ // Ignore any roles that might be mistakenly present in the request
+ extSysUser.setRoles(new ArrayList<ExternalSystemRoleApproval>());
+ reqResult = userRolesService.setExternalRequestUserAppRole(extSysUser, "DELETE");
+ if (!reqResult.isResult())
+ throw new Exception(reqResult.getDetailMessage());
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "deleteUserProfile: failed for app {}, user {}",
+ extSysUser.getApplicationName(), extSysUser.getLoginId(), e);
+ if(reqResult == null || (!reqResult.isResult() && !e.getMessage().contains("404"))){
+ response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
+ return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR,
+ e.getMessage(), "delete user profile failed");
+ }else if(e.getMessage().contains("404")){
+ response.setStatus(HttpServletResponse.SC_NOT_FOUND);
+ return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR,
+ e.getMessage(), "delete user profile failed");
+ } else{
+ response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR,
+ e.getMessage(), "delete user profile failed");
+ }
+ }
+ return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "Deleted Successfully", "Success");
+ }
+
+ /**
+ * Checks for presence of required fields.
+ *
+ * @param extSysUser
+ * @param rolesRequired
+ * If true, checks whether roles are present
+ * @throws Exception
+ * If any field is missing.
+ */
+ private void validateExtSystemUser(ExternalSystemUser extSysUser, boolean rolesRequired) throws Exception {
+ if (extSysUser.getLoginId() == null || extSysUser.getLoginId() == "")
+ throw new Exception("Request has no login ID");
+ if (extSysUser.getApplicationName() == null || extSysUser.getApplicationName() == "")
+ throw new Exception("Request has no application name");
+ if (extSysUser.getMyloginrequestId() == null)
+ throw new Exception("Request has no request ID");
+ if (rolesRequired && (extSysUser.getRoles() == null || extSysUser.getRoles().size() == 0))
+ throw new Exception("Request has no roles");
+ }
+
+} \ No newline at end of file
diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/SharedContextRestController.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/SharedContextRestController.java
index a59a4579..984bbf75 100644
--- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/SharedContextRestController.java
+++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/SharedContextRestController.java
@@ -69,12 +69,12 @@ import io.swagger.annotations.ApiOperation;
public class SharedContextRestController extends EPRestrictedRESTfulBaseController {
/**
- * Model for a one-element JSON object returned by many methods.
+ * Model for a one-element JSON object returned by many methods.
*/
class SharedContextJsonResponse {
String response;
}
-
+
/**
* Access to the database
*/
@@ -94,12 +94,16 @@ public class SharedContextRestController extends EPRestrictedRESTfulBaseControll
/**
* Gets a value for the specified context and key (RESTful service method).
*
- * @param ctxtId
+ * @param request
+ * HTTP servlet request
+ * @param context_id
* ID that identifies the context, usually the ECOMP Portal
* session key.
* @param ckey
* Key for the key-value pair to fetch
* @return JSON with shared context object; response=null if not found.
+ * @throws Exception
+ * on bad arguments
*/
@ApiOperation(value = "Gets a value for the specified context and key.", response = SharedContext.class)
@RequestMapping(value = { "/get" }, method = RequestMethod.GET, produces = "application/json")
@@ -123,12 +127,15 @@ public class SharedContextRestController extends EPRestrictedRESTfulBaseControll
/**
* Gets user information for the specified context (RESTful service method).
*
- * @param ctxtId
+ * @param request
+ * HTTP servlet request
+ * @param context_id
* ID that identifies the context, usually the ECOMP Portal
* session key.
- *
* @return List of shared-context objects as JSON; should have user's first
* name, last name and email address; null if none found
+ * @throws Exception
+ * on bad arguments
*/
@ApiOperation(value = "Gets user information for the specified context.", response = SharedContext.class, responseContainer = "List")
@RequestMapping(value = { "/get_user" }, method = RequestMethod.GET, produces = "application/json")
@@ -162,6 +169,8 @@ public class SharedContextRestController extends EPRestrictedRESTfulBaseControll
* Tests for presence of the specified key in the specified context (RESTful
* service method).
*
+ * @param request
+ * HTTP servlet request
* @param context_id
* ID that identifies the context, usually the ECOMP Portal
* session key.
@@ -169,6 +178,8 @@ public class SharedContextRestController extends EPRestrictedRESTfulBaseControll
* Key for the key-value pair to test
* @return JSON with result indicating whether the context and key were
* found.
+ * @throws Exception
+ * on bad arguments
*/
@ApiOperation(value = "Tests for presence of the specified key in the specified context.", response = SharedContextJsonResponse.class)
@RequestMapping(value = { "/check" }, method = RequestMethod.GET, produces = "application/json")
@@ -192,6 +203,8 @@ public class SharedContextRestController extends EPRestrictedRESTfulBaseControll
* Removes the specified key in the specified context (RESTful service
* method).
*
+ * @param request
+ * HTTP servlet request
* @param context_id
* ID that identifies the context, usually the ECOMP Portal
* session key.
@@ -199,6 +212,8 @@ public class SharedContextRestController extends EPRestrictedRESTfulBaseControll
* Key for the key-value pair to remove
* @return JSON with result indicating whether the context and key were
* found.
+ * @throws Exception
+ * on bad arguments
*/
@ApiOperation(value = "Removes the specified key in the specified context.", response = SharedContextJsonResponse.class)
@RequestMapping(value = { "/remove" }, method = RequestMethod.GET, produces = "application/json")
@@ -224,11 +239,15 @@ public class SharedContextRestController extends EPRestrictedRESTfulBaseControll
* Clears all key-value pairs in the specified context (RESTful service
* method).
*
+ * @param request
+ * HTTP servlet request
* @param context_id
* ID that identifies the context, usually the ECOMP Portal
* session key.
* @return JSON with result indicating the number of key-value pairs
* removed.
+ * @throws Exception
+ * on bad arguments
*/
@ApiOperation(value = "Clears all key-value pairs in the specified context.", response = SharedContextJsonResponse.class)
@RequestMapping(value = { "/clear" }, method = RequestMethod.GET, produces = "application/json")
@@ -248,6 +267,8 @@ public class SharedContextRestController extends EPRestrictedRESTfulBaseControll
* method). Creates the context if no context with the specified ID-key pair
* exists, overwrites the value if it exists already.
*
+ * @param request
+ * HTTP servlet request
* @param userJson
* JSON block with these tag-value pairs:
* <UL>
@@ -257,6 +278,8 @@ public class SharedContextRestController extends EPRestrictedRESTfulBaseControll
* </UL>
* @return JSON with result indicating whether the value was added (key not
* previously known) or replaced (key previously known).
+ * @throws Exception
+ * on bad arguments
*/
@ApiOperation(value = "Sets a context value for the specified context and key. Creates the context if no context with the specified ID-key pair exists, overwrites the value if it exists already.", response = SharedContextJsonResponse.class)
@RequestMapping(value = { "/set" }, method = RequestMethod.POST, produces = "application/json")
@@ -314,7 +337,7 @@ public class SharedContextRestController extends EPRestrictedRESTfulBaseControll
/**
* Creates a JSON object with the content of the shared context; null is ok.
*
- * @param responseBody
+ * @param context
* @return tag "response" with collection of context object's fields
* @throws JsonProcessingException
*/
diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/TicketEventController.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/TicketEventController.java
index 0dd344d7..e0a9e587 100644
--- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/TicketEventController.java
+++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/TicketEventController.java
@@ -1,179 +1,184 @@
-/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.controller;
-
-import java.util.Arrays;
-import java.util.Calendar;
-import java.util.Date;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.openecomp.portalapp.portal.domain.EPUser;
-import org.openecomp.portalapp.portal.ecomp.model.PortalRestResponse;
-import org.openecomp.portalapp.portal.ecomp.model.PortalRestStatusEnum;
-import org.openecomp.portalapp.portal.logging.aop.EPAuditLog;
-import org.openecomp.portalapp.portal.service.UserNotificationService;
-import org.openecomp.portalapp.portal.transport.EpNotificationItem;
-import org.openecomp.portalapp.portal.transport.EpRoleNotificationItem;
-import org.openecomp.portalapp.portal.utils.PortalConstants;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.context.annotation.EnableAspectJAutoProxy;
-import org.springframework.web.bind.annotation.RequestBody;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestMethod;
-import org.springframework.web.bind.annotation.RestController;
-
-import com.fasterxml.jackson.databind.JsonNode;
-import com.fasterxml.jackson.databind.ObjectMapper;
-
-import io.swagger.annotations.ApiOperation;
-
-/**
- * Receives messages from the Collaboration Bus (C-BUS) notification and event
- * brokering tool. Creates notifications for ECOMP Portal users.
- */
-@RestController
-@RequestMapping(PortalConstants.REST_AUX_API)
-@Configuration
-@EnableAspectJAutoProxy
-@EPAuditLog
-public class TicketEventController implements BasicAuthenticationController {
-
- @Autowired
- private UserNotificationService userNotificationService;
-
- private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(TicketEventController.class);
-
- public boolean isAuxRESTfulCall() {
- return true;
- }
-
- private final ObjectMapper mapper = new ObjectMapper();
-
- @ApiOperation(value = "Accepts messages from external ticketing systems and creates notifications for Portal users.", response = PortalRestResponse.class)
- @RequestMapping(value = { "/ticketevent" }, method = RequestMethod.POST)
- public PortalRestResponse<String> handleRequest(HttpServletRequest request, HttpServletResponse response,
- @RequestBody String ticketEventJson) throws Exception {
-
- logger.debug(EELFLoggerDelegate.debugLogger, "Ticket Event notification" + ticketEventJson);
- PortalRestResponse<String> portalResponse = new PortalRestResponse<>();
- try {
- JsonNode ticketEventNotif = mapper.readTree(ticketEventJson);
-
- // Reject request if required fields are missing.
- String error = validateTicketEventMessage(ticketEventNotif);
- if (error != null) {
- portalResponse.setStatus(PortalRestStatusEnum.ERROR);
- portalResponse.setMessage(error);
- response.setStatus(400);
- return portalResponse;
- }
-
- EpNotificationItem epItem = new EpNotificationItem();
- epItem.setCreatedDate(new Date());
- epItem.setIsForOnlineUsers("Y");
- epItem.setIsForAllRoles("N");
- epItem.setActiveYn("Y");
- //JsonNode application = ticketEventNotif.get("application");
- JsonNode event = ticketEventNotif.get("event");
- JsonNode header = event.get("header");
- JsonNode body = event.get("body");
- epItem.setMsgDescription(body.toString());
- Long eventDate = body.get("eventDate").asLong();
-
- String assetID = body.get("assetID").asText();
- epItem.setMsgHeader(assetID);
- String eventSource = header.get("eventSource").asText();
- epItem.setMsgSource(eventSource);
- epItem.setStartTime(new Date(eventDate));
- Calendar calendar = Calendar.getInstance();
- calendar.setTime(epItem.getStartTime());
- int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
- calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth + 30);
- epItem.setEndTime(calendar.getTime());
- String severityString= (body.get("severity").toString()).substring(1, 2);
- Long severity=Long.parseLong(severityString);
- epItem.setPriority(severity);
- epItem.setCreatorId(null);
- Set<EpRoleNotificationItem> roles = new HashSet<>();
- JsonNode SubscriberInfo = ticketEventNotif.get("SubscriberInfo");
- JsonNode userList = SubscriberInfo.get("UserList");
- String UserIds[] = userList.toString().replace("[", "").replace("]", "").trim().replace("\"", "")
- .split(",");
- List<EPUser> users = userNotificationService.getUsersByOrgIds(Arrays.asList(UserIds));
- for (String userId : UserIds) {
- EpRoleNotificationItem roleNotifItem = new EpRoleNotificationItem();
- for (EPUser user : users) {
- if (user.getOrgUserId().equals(userId)) {
- roleNotifItem.setRecvUserId(user.getId().intValue());
- roles.add(roleNotifItem);
- break;
- }
- }
-
- }
- epItem.setRoles(roles);
- userNotificationService.saveNotification(epItem);
-
- portalResponse.setStatus(PortalRestStatusEnum.OK);
- portalResponse.setMessage("processEventNotification: notification created");
- portalResponse.setResponse("NotificationId is :" + epItem.notificationId);
- } catch (Exception ex) {
- portalResponse.setStatus(PortalRestStatusEnum.ERROR);
- response.setStatus(400);
- portalResponse.setMessage(ex.toString());
- }
- return portalResponse;
- }
-
- /**
- * Validates that mandatory fields are present.
- *
- * @param ticketEventNotif
- * @return Error message if a problem is found; null if all is well.
- */
- private String validateTicketEventMessage(JsonNode ticketEventNotif) {
- JsonNode application = ticketEventNotif.get("application");
- JsonNode event = ticketEventNotif.get("event");
- JsonNode header = event.get("header");
- JsonNode body = event.get("body");
- JsonNode SubscriberInfo = ticketEventNotif.get("SubscriberInfo");
- if (application == null)
- return "application is mandatory";
- if (body == null)
- return "body is mandatory";
- if (body.get("assetID") == null)
- return "Asset Id is mandatory";
- if (body.get("eventDate") == null)
- return "Event Date is mandatory";
- if (header.get("eventSource") == null)
- return "Message Source is mandatory";
- if (SubscriberInfo.get("UserList") == null)
- return "At least one user Id is mandatory";
- return null;
- }
-
-}
+/*-
+ * ================================================================================
+ * ECOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.controller;
+
+import java.util.Arrays;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.openecomp.portalapp.portal.domain.EPUser;
+import org.openecomp.portalapp.portal.ecomp.model.PortalRestResponse;
+import org.openecomp.portalapp.portal.ecomp.model.PortalRestStatusEnum;
+import org.openecomp.portalapp.portal.logging.aop.EPAuditLog;
+import org.openecomp.portalapp.portal.service.UserNotificationService;
+import org.openecomp.portalapp.portal.transport.EpNotificationItem;
+import org.openecomp.portalapp.portal.transport.EpRoleNotificationItem;
+import org.openecomp.portalapp.portal.utils.PortalConstants;
+import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.EnableAspectJAutoProxy;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.RestController;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+import io.swagger.annotations.ApiOperation;
+
+/**
+ * Receives messages from the Collaboration Bus (C-BUS) notification and event
+ * brokering tool. Creates notifications for ECOMP Portal users.
+ */
+@RestController
+@RequestMapping(PortalConstants.REST_AUX_API)
+@Configuration
+@EnableAspectJAutoProxy
+@EPAuditLog
+public class TicketEventController implements BasicAuthenticationController {
+
+ @Autowired
+ private UserNotificationService userNotificationService;
+
+ private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(TicketEventController.class);
+
+ public boolean isAuxRESTfulCall() {
+ return true;
+ }
+
+ private final ObjectMapper mapper = new ObjectMapper();
+
+ @ApiOperation(value = "Accepts messages from external ticketing systems and creates notifications for Portal users.", response = PortalRestResponse.class)
+ @RequestMapping(value = { "/ticketevent" }, method = RequestMethod.POST)
+ public PortalRestResponse<String> handleRequest(HttpServletRequest request, HttpServletResponse response,
+ @RequestBody String ticketEventJson) throws Exception {
+
+ logger.debug(EELFLoggerDelegate.debugLogger, "Ticket Event notification" + ticketEventJson);
+ PortalRestResponse<String> portalResponse = new PortalRestResponse<>();
+ try {
+ JsonNode ticketEventNotif = mapper.readTree(ticketEventJson);
+
+ // Reject request if required fields are missing.
+ String error = validateTicketEventMessage(ticketEventNotif);
+ if (error != null) {
+ portalResponse.setStatus(PortalRestStatusEnum.ERROR);
+ portalResponse.setMessage(error);
+ response.setStatus(400);
+ return portalResponse;
+ }
+
+ EpNotificationItem epItem = new EpNotificationItem();
+ epItem.setCreatedDate(new Date());
+ epItem.setIsForOnlineUsers("Y");
+ epItem.setIsForAllRoles("N");
+ epItem.setActiveYn("Y");
+
+ JsonNode event = ticketEventNotif.get("event");
+ JsonNode header = event.get("header");
+ JsonNode body = event.get("body");
+ epItem.setMsgDescription(body.toString());
+ Long eventDate = System.currentTimeMillis();
+ if (body.get("eventDate") != null) {
+ eventDate = body.get("eventDate").asLong();
+ }
+ String eventSource = header.get("eventSource").asText();
+ epItem.setMsgSource(eventSource);
+ epItem.setStartTime(new Date(eventDate));
+ Calendar calendar = Calendar.getInstance();
+ calendar.setTime(epItem.getStartTime());
+ int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
+ calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth + 30);
+ epItem.setEndTime(calendar.getTime());
+ String severityString = "1";
+ if (body.get("severity") != null) {
+ severityString = (body.get("severity").toString()).substring(1, 2);
+ }
+ Long severity = Long.parseLong(severityString);
+ epItem.setPriority(severity);
+ epItem.setCreatorId(null);
+ Set<EpRoleNotificationItem> roles = new HashSet<>();
+ JsonNode SubscriberInfo = ticketEventNotif.get("SubscriberInfo");
+ JsonNode userList = SubscriberInfo.get("UserList");
+ String UserIds[] = userList.toString().replace("[", "").replace("]", "").trim().replace("\"", "")
+ .split(",");
+ String assetID = eventSource + ' '
+ + userList.toString().replace("[", "").replace("]", "").trim().replace("\"", "") + ' '
+ + new Date(eventDate);
+ if (body.get("assetID") != null) {
+ assetID = body.get("assetID").asText();
+ }
+ epItem.setMsgHeader(assetID);
+ List<EPUser> users = userNotificationService.getUsersByOrgIds(Arrays.asList(UserIds));
+ for (String userId : UserIds) {
+ EpRoleNotificationItem roleNotifItem = new EpRoleNotificationItem();
+ for (EPUser user : users) {
+ if (user.getOrgUserId().equals(userId)) {
+ roleNotifItem.setRecvUserId(user.getId().intValue());
+ roles.add(roleNotifItem);
+ break;
+ }
+ }
+
+ }
+ epItem.setRoles(roles);
+ userNotificationService.saveNotification(epItem);
+
+ portalResponse.setStatus(PortalRestStatusEnum.OK);
+ portalResponse.setMessage("processEventNotification: notification created");
+ portalResponse.setResponse("NotificationId is :" + epItem.notificationId);
+ } catch (Exception ex) {
+ portalResponse.setStatus(PortalRestStatusEnum.ERROR);
+ response.setStatus(400);
+ portalResponse.setMessage(ex.toString());
+ }
+ return portalResponse;
+ }
+
+ /**
+ * Validates that mandatory fields are present.
+ *
+ * @param ticketEventNotif
+ * @return Error message if a problem is found; null if all is well.
+ */
+ private String validateTicketEventMessage(JsonNode ticketEventNotif) {
+ JsonNode application = ticketEventNotif.get("application");
+ JsonNode event = ticketEventNotif.get("event");
+ JsonNode header = event.get("header");
+ JsonNode body = event.get("body");
+ JsonNode SubscriberInfo = ticketEventNotif.get("SubscriberInfo");
+ if (application == null)
+ return "application is mandatory";
+ if (body == null)
+ return "body is mandatory";
+ if (header.get("eventSource") == null)
+ return "Message Source is mandatory";
+ if (SubscriberInfo.get("UserList") == null)
+ return "At least one user Id is mandatory";
+ return null;
+ }
+}
diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/UserController.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/UserController.java
new file mode 100644
index 00000000..4cf7ca63
--- /dev/null
+++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/UserController.java
@@ -0,0 +1,104 @@
+package org.openecomp.portalapp.portal.controller;
+
+import javax.servlet.http.HttpServletRequest;
+
+import org.openecomp.portalapp.controller.EPRestrictedBaseController;
+import org.openecomp.portalapp.portal.domain.EPUser;
+import org.openecomp.portalapp.portal.ecomp.model.PortalRestResponse;
+import org.openecomp.portalapp.portal.ecomp.model.PortalRestStatusEnum;
+import org.openecomp.portalapp.portal.logging.aop.EPAuditLog;
+import org.openecomp.portalapp.portal.service.UserService;
+import org.openecomp.portalapp.portal.transport.ProfileDetail;
+import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
+import org.openecomp.portalapp.util.EPUserUtils;
+import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.openecomp.portalsdk.core.onboarding.util.CipherUtil;
+import org.openecomp.portalsdk.core.util.SystemProperties;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.EnableAspectJAutoProxy;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.RestController;
+
+@RestController
+@org.springframework.context.annotation.Configuration
+@EnableAspectJAutoProxy
+@EPAuditLog
+public class UserController extends EPRestrictedBaseController {
+
+ private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(UserController.class);
+
+ @Autowired
+ private UserService userService;
+
+ /**
+ * RESTful service method to get ECOMP Logged in User details.
+ *
+ * @param request
+ * HttpServletRequest
+ *
+ * @return PortalRestResponse of EPUser
+ */
+ @RequestMapping(value = { "/portalApi/loggedinUser" }, method = RequestMethod.GET, produces = "application/json")
+ public PortalRestResponse<ProfileDetail> getLoggedinUser(HttpServletRequest request) {
+ PortalRestResponse<ProfileDetail> portalRestResponse = null;
+ try {
+ EPUser user = EPUserUtils.getUserSession(request);
+ ProfileDetail profileDetail = new ProfileDetail(user.getFirstName(), user.getLastName(),
+ user.getMiddleInitial(), user.getEmail(), user.getLoginId(), CipherUtil.decrypt(user.getLoginPwd()));
+ portalRestResponse = new PortalRestResponse<ProfileDetail>(PortalRestStatusEnum.OK, "success",
+ profileDetail);
+ EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/loggedinUser", "result =", profileDetail);
+ } catch (Exception e) {
+ portalRestResponse = new PortalRestResponse<ProfileDetail>(PortalRestStatusEnum.ERROR, e.getMessage(),
+ null);
+ logger.error(EELFLoggerDelegate.errorLogger, "getLoggedinUser failed", e);
+ }
+ return portalRestResponse;
+ }
+
+ /**
+ * RESTful service method to update ECOMP Logged in User in DB.
+ *
+ * @param request
+ * HttpServletRequest
+ * @param profileDetail
+ * Body with user information
+ * @return PortalRestResponse of String
+ */
+ @RequestMapping(value = {
+ "/portalApi/modifyLoggedinUser" }, method = RequestMethod.PUT, produces = "application/json")
+ public PortalRestResponse<String> modifyLoggedinUser(HttpServletRequest request,
+ @RequestBody ProfileDetail profileDetail) {
+ PortalRestResponse<String> portalRestResponse = null;
+ try {
+ String errorMsg = "";
+ if (profileDetail.getFirstName().equals("") || profileDetail.getLastName().equals("")
+ || profileDetail.getEmail().equals("") || profileDetail.getLoginId().equals("")
+ || profileDetail.getLoginPassword().equals("")) {
+ errorMsg = "Required field(s) is missing";
+ portalRestResponse = new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, errorMsg, null);
+ logger.error(EELFLoggerDelegate.errorLogger, "modifyLoggedinUser failed", errorMsg);
+ } else {
+ EPUser user = EPUserUtils.getUserSession(request);
+ user.setFirstName(profileDetail.getFirstName());
+ user.setLastName(profileDetail.getLastName());
+ user.setEmail(profileDetail.getEmail());
+ user.setMiddleInitial(profileDetail.getMiddleName());
+ user.setLoginId(profileDetail.getLoginId());
+ user.setLoginPwd(CipherUtil.encrypt(profileDetail.getLoginPassword()));
+ userService.saveUser(user);
+ // Update user info in the session
+ request.getSession().setAttribute(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME),
+ user);
+ portalRestResponse = new PortalRestResponse<String>(PortalRestStatusEnum.OK, "success", null);
+ EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/modifyLoggedinUser", "result =", user);
+ }
+ } catch (Exception e) {
+ portalRestResponse = new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, e.toString(), null);
+ logger.error(EELFLoggerDelegate.errorLogger, "modifyLoggedinUser failed", e);
+ }
+ return portalRestResponse;
+ }
+}
diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/UserNotificationController.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/UserNotificationController.java
index 777fb91d..24b698e8 100644
--- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/UserNotificationController.java
+++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/UserNotificationController.java
@@ -1,216 +1,217 @@
-/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.controller;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.EnableAspectJAutoProxy;
-import org.springframework.web.bind.annotation.PathVariable;
-import org.springframework.web.bind.annotation.RequestBody;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestMethod;
-import org.springframework.web.bind.annotation.RequestParam;
-import org.springframework.web.bind.annotation.RestController;
-
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalsdk.core.util.SystemProperties;
-import org.openecomp.portalsdk.core.web.support.UserUtils;
-import org.openecomp.portalapp.controller.EPRestrictedBaseController;
-import org.openecomp.portalapp.portal.domain.EPUser;
-import org.openecomp.portalapp.portal.domain.EcompAppRole;
-import org.openecomp.portalapp.portal.logging.aop.EPAuditLog;
-import org.openecomp.portalapp.portal.service.FunctionalMenuService;
-import org.openecomp.portalapp.portal.service.UserNotificationService;
-import org.openecomp.portalapp.portal.transport.EpNotificationItem;
-import org.openecomp.portalapp.portal.transport.EpNotificationItemVO;
-import org.openecomp.portalapp.portal.transport.EpRoleNotificationItem;
-import org.openecomp.portalapp.portal.transport.FunctionalMenuRole;
-import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties;
-import org.openecomp.portalapp.portal.ecomp.model.PortalRestResponse;
-import org.openecomp.portalapp.portal.ecomp.model.PortalRestStatusEnum;
-import org.openecomp.portalapp.util.EPUserUtils;
-
-@RestController
-@org.springframework.context.annotation.Configuration
-@EnableAspectJAutoProxy
-@EPAuditLog
-public class UserNotificationController extends EPRestrictedBaseController {
-
- @Autowired
- FunctionalMenuService functionalMenuService;
-
- @Autowired
- UserNotificationService userNotificationService;
-
- EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(UserNotificationController.class);
-
- @RequestMapping(value = {
- "/portalApi/getFunctionalMenuRole" }, method = RequestMethod.GET, produces = "application/json")
- public List<FunctionalMenuRole> getMenuIdRoleId(HttpServletRequest request, HttpServletResponse response) {
- // EPUser user = EPUserUtils.getUserSession(request);
- List<FunctionalMenuRole> menuRoleList = null;
- menuRoleList = functionalMenuService.getFunctionalMenuRole();
- return menuRoleList;
- }
-
- @RequestMapping(value = {
- "/portalApi/getNotifications" }, method = RequestMethod.GET, produces = "application/json")
- public PortalRestResponse<List<EpNotificationItem>> getNotifications(HttpServletRequest request,
- HttpServletResponse response) {
- EPUser user = EPUserUtils.getUserSession(request);
- PortalRestResponse<List<EpNotificationItem>> portalRestResponse = null;
- try {
- List<EpNotificationItem> notificationList = userNotificationService.getNotifications(user.getId());
- portalRestResponse = new PortalRestResponse<List<EpNotificationItem>>(PortalRestStatusEnum.OK, "success",
- notificationList);
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "getAllAppsAndContacts failed", e);
- portalRestResponse = new PortalRestResponse<List<EpNotificationItem>>(PortalRestStatusEnum.ERROR,
- e.getMessage(), null);
- }
- return portalRestResponse;
- }
-
- @RequestMapping(value = {
- "/portalApi/getAdminNotifications" }, method = RequestMethod.GET, produces = "application/json")
- public List<EpNotificationItemVO> getAdminNotifications(HttpServletRequest request, HttpServletResponse response) {
- List<EpNotificationItemVO> adminNotificationList = null;
- adminNotificationList = userNotificationService.getAdminNotificationVOS();
- return adminNotificationList;
- }
-
- @RequestMapping(value = "/portalApi/saveNotification", method = RequestMethod.POST, produces = "application/json")
- public PortalRestResponse<String> save(HttpServletRequest request, HttpServletResponse response,
- @RequestBody EpNotificationItem notificationItem) {
-
- if (notificationItem == null || notificationItem.getMsgHeader() == null)
- return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "FAILURE",
- "Notification Header cannot be null or empty");
- if (notificationItem.getEndTime().compareTo(notificationItem.getStartTime()) < 0) {
- return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "FAILURE",
- "End Time should be greater than start time");
- }
-
- if ((notificationItem.getIsForAllRoles() == "N") && notificationItem.getRoleIds().isEmpty()) {
- return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "FAILURE",
- "No Roles Ids Exist for the selected Roles");
- }
-
- Long creatorId = UserUtils.getUserIdAsLong(request);
- notificationItem.setCreatorId(creatorId);
-
- // Front-end date picker does not accept a time value, so all
- // values are the start of the chosen day in the local time zone.
- // Move the end time value to the very end of the chosen day.
- // Avoid Calendar.getDefault() which uses the server's locale.
- Long endTime = notificationItem.getEndTime().getTime();
- endTime += (23 * 3600 + 59 * 60 + 59) * 1000;
- notificationItem.getEndTime().setTime(endTime);
-
- try {
- userNotificationService.saveNotification(notificationItem);
- } catch (Exception e) {
- return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "FAILURE", e.getMessage());
- }
- return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "SUCCESS", "");
- }
-
- @RequestMapping(value = {
- "/portalApi/notificationUpdateRate" }, method = RequestMethod.GET, produces = "application/json")
- public PortalRestResponse<Map<String, String>> getNotificationUpdateRate(HttpServletRequest request) {
- try {
- String updateRate = SystemProperties.getProperty(EPCommonSystemProperties.NOTIFICATION_UPDATE_RATE);
- String updateDuration = SystemProperties.getProperty(EPCommonSystemProperties.NOTIFICATION_UPDATE_DURATION);
- Integer rateInMiliSec = Integer.valueOf(updateRate) * 1000;
- Integer durationInMiliSec = Integer.valueOf(updateDuration) * 1000;
- Map<String, String> results = new HashMap<String, String>();
- results.put("updateRate", String.valueOf(rateInMiliSec));
- results.put("updateDuration", String.valueOf(durationInMiliSec));
- return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", results);
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "getNotificationUpdateRate failed", e);
- return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.toString(), null);
- }
- }
-
- @RequestMapping(value = {
- "/portalApi/notificationRead" }, method = RequestMethod.GET, produces = "application/json")
- public PortalRestResponse<Map<String, String>> notificationRead(
- @RequestParam("notificationId") String notificationID, HttpServletRequest request) {
- try {
- userNotificationService.setNotificationRead(Long.parseLong(notificationID), UserUtils.getUserId(request));
- return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", null);
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "notificationRead failed", e);
- return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.toString(), null);
- }
- }
-
- @RequestMapping(value = {
- "/portalApi/getNotificationHistory" }, method = RequestMethod.GET, produces = "application/json")
- public List<EpNotificationItemVO> getNotificationHistory(HttpServletRequest request, HttpServletResponse response) {
- EPUser user = EPUserUtils.getUserSession(request);
- List<EpNotificationItemVO> notificationList = null;
- notificationList = userNotificationService.getNotificationHistoryVO(user.getId());
- return notificationList;
- }
-
- @RequestMapping(value = { "/portalApi/notificationRole/{notificationId}/roles" }, method = {
- RequestMethod.GET }, produces = "application/json")
- public List<Integer> testGetRoles(HttpServletRequest request, @PathVariable("notificationId") Long notificationId) {
- List<EpRoleNotificationItem> NotifRoles = userNotificationService.getNotificationRoles(notificationId);
- ArrayList<Integer> rolesList = new ArrayList<Integer>();
- for (EpRoleNotificationItem notifRole : NotifRoles) {
- rolesList.add(notifRole.roleId);
- }
- return rolesList;
- }
-
- @RequestMapping(value = { "/portalApi/getNotificationAppRoles" }, method = {
- RequestMethod.GET }, produces = "application/json")
- public List<EcompAppRole> getNotificationAppRoles(HttpServletRequest request, HttpServletResponse response) {
- List<EcompAppRole> epAppRoleList = null;
- try {
- epAppRoleList = userNotificationService.getAppRoleList();
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger,
- "Exception occurred while performing UserNofiticationController.getNotificationAppRoles. Details: ",
- e);
- }
- return epAppRoleList;
- }
-
- @RequestMapping(value = {
- "/portalApi/getMessageRecipients" }, method = RequestMethod.GET, produces = "application/json")
- public List<String> getMessageRecipients(@RequestParam("notificationId") Long notificationID) {
- // EPUser user = EPUserUtils.getUserSession(request);
- List<String> messageUserRecipients = null;
- messageUserRecipients = userNotificationService.getMessageRecipients(notificationID);
- return messageUserRecipients;
- }
-
-}
+/*-
+ * ================================================================================
+ * ECOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.controller;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.EnableAspectJAutoProxy;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.RequestParam;
+import org.springframework.web.bind.annotation.RestController;
+
+import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.openecomp.portalsdk.core.util.SystemProperties;
+import org.openecomp.portalsdk.core.web.support.UserUtils;
+import org.openecomp.portalapp.controller.EPRestrictedBaseController;
+import org.openecomp.portalapp.portal.domain.EPUser;
+import org.openecomp.portalapp.portal.domain.EcompAppRole;
+import org.openecomp.portalapp.portal.logging.aop.EPAuditLog;
+import org.openecomp.portalapp.portal.service.FunctionalMenuService;
+import org.openecomp.portalapp.portal.service.UserNotificationService;
+import org.openecomp.portalapp.portal.transport.EpNotificationItem;
+import org.openecomp.portalapp.portal.transport.EpNotificationItemVO;
+import org.openecomp.portalapp.portal.transport.EpRoleNotificationItem;
+import org.openecomp.portalapp.portal.transport.FunctionalMenuRole;
+import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties;
+import org.openecomp.portalapp.portal.ecomp.model.PortalRestResponse;
+import org.openecomp.portalapp.portal.ecomp.model.PortalRestStatusEnum;
+import org.openecomp.portalapp.util.EPUserUtils;
+
+@RestController
+@org.springframework.context.annotation.Configuration
+@EnableAspectJAutoProxy
+@EPAuditLog
+public class UserNotificationController extends EPRestrictedBaseController {
+
+ @Autowired
+ FunctionalMenuService functionalMenuService;
+
+ @Autowired
+ UserNotificationService userNotificationService;
+
+ EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(UserNotificationController.class);
+
+ @RequestMapping(value = {
+ "/portalApi/getFunctionalMenuRole" }, method = RequestMethod.GET, produces = "application/json")
+ public List<FunctionalMenuRole> getMenuIdRoleId(HttpServletRequest request, HttpServletResponse response) {
+ // EPUser user = EPUserUtils.getUserSession(request);
+ List<FunctionalMenuRole> menuRoleList = null;
+ menuRoleList = functionalMenuService.getFunctionalMenuRole();
+ return menuRoleList;
+ }
+
+ @RequestMapping(value = {
+ "/portalApi/getNotifications" }, method = RequestMethod.GET, produces = "application/json")
+ public PortalRestResponse<List<EpNotificationItem>> getNotifications(HttpServletRequest request,
+ HttpServletResponse response) {
+ EPUser user = EPUserUtils.getUserSession(request);
+ PortalRestResponse<List<EpNotificationItem>> portalRestResponse = null;
+ try {
+ List<EpNotificationItem> notificationList = userNotificationService.getNotifications(user.getId());
+ portalRestResponse = new PortalRestResponse<List<EpNotificationItem>>(PortalRestStatusEnum.OK, "success",
+ notificationList);
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "getAllAppsAndContacts failed", e);
+ portalRestResponse = new PortalRestResponse<List<EpNotificationItem>>(PortalRestStatusEnum.ERROR,
+ e.getMessage(), null);
+ }
+ return portalRestResponse;
+ }
+
+ @RequestMapping(value = {
+ "/portalApi/getAdminNotifications" }, method = RequestMethod.GET, produces = "application/json")
+ public List<EpNotificationItemVO> getAdminNotifications(HttpServletRequest request, HttpServletResponse response) {
+ List<EpNotificationItemVO> adminNotificationList = null;
+ EPUser user = EPUserUtils.getUserSession(request);
+ adminNotificationList = userNotificationService.getAdminNotificationVOS(user.getId());
+ return adminNotificationList;
+ }
+
+ @RequestMapping(value = "/portalApi/saveNotification", method = RequestMethod.POST, produces = "application/json")
+ public PortalRestResponse<String> save(HttpServletRequest request, HttpServletResponse response,
+ @RequestBody EpNotificationItem notificationItem) {
+
+ if (notificationItem == null || notificationItem.getMsgHeader() == null)
+ return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "FAILURE",
+ "Notification Header cannot be null or empty");
+ if (notificationItem.getEndTime().compareTo(notificationItem.getStartTime()) < 0) {
+ return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "FAILURE",
+ "End Time should be greater than start time");
+ }
+
+ if ((notificationItem.getIsForAllRoles() == "N") && notificationItem.getRoleIds().isEmpty()) {
+ return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "FAILURE",
+ "No Roles Ids Exist for the selected Roles");
+ }
+
+ Long creatorId = UserUtils.getUserIdAsLong(request);
+ notificationItem.setCreatorId(creatorId);
+
+ // Front-end date picker does not accept a time value, so all
+ // values are the start of the chosen day in the local time zone.
+ // Move the end time value to the very end of the chosen day.
+ // Avoid Calendar.getDefault() which uses the server's locale.
+ Long endTime = notificationItem.getEndTime().getTime();
+ endTime += (23 * 3600 + 59 * 60 + 59) * 1000;
+ notificationItem.getEndTime().setTime(endTime);
+
+ try {
+ userNotificationService.saveNotification(notificationItem);
+ } catch (Exception e) {
+ return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "FAILURE", e.getMessage());
+ }
+ return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "SUCCESS", "");
+ }
+
+ @RequestMapping(value = {
+ "/portalApi/notificationUpdateRate" }, method = RequestMethod.GET, produces = "application/json")
+ public PortalRestResponse<Map<String, String>> getNotificationUpdateRate(HttpServletRequest request) {
+ try {
+ String updateRate = SystemProperties.getProperty(EPCommonSystemProperties.NOTIFICATION_UPDATE_RATE);
+ String updateDuration = SystemProperties.getProperty(EPCommonSystemProperties.NOTIFICATION_UPDATE_DURATION);
+ Integer rateInMiliSec = Integer.valueOf(updateRate) * 1000;
+ Integer durationInMiliSec = Integer.valueOf(updateDuration) * 1000;
+ Map<String, String> results = new HashMap<String, String>();
+ results.put("updateRate", String.valueOf(rateInMiliSec));
+ results.put("updateDuration", String.valueOf(durationInMiliSec));
+ return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", results);
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "getNotificationUpdateRate failed", e);
+ return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.toString(), null);
+ }
+ }
+
+ @RequestMapping(value = {
+ "/portalApi/notificationRead" }, method = RequestMethod.GET, produces = "application/json")
+ public PortalRestResponse<Map<String, String>> notificationRead(
+ @RequestParam("notificationId") String notificationID, HttpServletRequest request) {
+ try {
+ userNotificationService.setNotificationRead(Long.parseLong(notificationID), UserUtils.getUserId(request));
+ return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", null);
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "notificationRead failed", e);
+ return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.toString(), null);
+ }
+ }
+
+ @RequestMapping(value = {
+ "/portalApi/getNotificationHistory" }, method = RequestMethod.GET, produces = "application/json")
+ public List<EpNotificationItemVO> getNotificationHistory(HttpServletRequest request, HttpServletResponse response) {
+ EPUser user = EPUserUtils.getUserSession(request);
+ List<EpNotificationItemVO> notificationList = null;
+ notificationList = userNotificationService.getNotificationHistoryVO(user.getId());
+ return notificationList;
+ }
+
+ @RequestMapping(value = { "/portalApi/notificationRole/{notificationId}/roles" }, method = {
+ RequestMethod.GET }, produces = "application/json")
+ public List<Integer> testGetRoles(HttpServletRequest request, @PathVariable("notificationId") Long notificationId) {
+ List<EpRoleNotificationItem> NotifRoles = userNotificationService.getNotificationRoles(notificationId);
+ ArrayList<Integer> rolesList = new ArrayList<Integer>();
+ for (EpRoleNotificationItem notifRole : NotifRoles) {
+ rolesList.add(notifRole.roleId);
+ }
+ return rolesList;
+ }
+
+ @RequestMapping(value = { "/portalApi/getNotificationAppRoles" }, method = {
+ RequestMethod.GET }, produces = "application/json")
+ public List<EcompAppRole> getNotificationAppRoles(HttpServletRequest request, HttpServletResponse response) {
+ List<EcompAppRole> epAppRoleList = null;
+ try {
+ epAppRoleList = userNotificationService.getAppRoleList();
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "Exception occurred while performing UserNofiticationController.getNotificationAppRoles. Details: ",
+ e);
+ }
+ return epAppRoleList;
+ }
+
+ @RequestMapping(value = {
+ "/portalApi/getMessageRecipients" }, method = RequestMethod.GET, produces = "application/json")
+ public List<String> getMessageRecipients(@RequestParam("notificationId") Long notificationID) {
+ // EPUser user = EPUserUtils.getUserSession(request);
+ List<String> messageUserRecipients = null;
+ messageUserRecipients = userNotificationService.getMessageRecipients(notificationID);
+ return messageUserRecipients;
+ }
+
+}
diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/UserRecommendationController.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/UserRecommendationController.java
new file mode 100644
index 00000000..3ec06ed3
--- /dev/null
+++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/UserRecommendationController.java
@@ -0,0 +1,87 @@
+package org.openecomp.portalapp.portal.controller;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.openecomp.portalapp.controller.EPRestrictedBaseController;
+import org.openecomp.portalapp.portal.domain.EPUser;
+import org.openecomp.portalapp.portal.logging.aop.EPAuditLog;
+import org.openecomp.portalapp.portal.service.ConsulHealthService;
+import org.openecomp.portalapp.util.EPUserUtils;
+import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.openecomp.portalsdk.core.util.SystemProperties;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.EnableAspectJAutoProxy;
+import org.springframework.http.HttpEntity;
+import org.springframework.http.HttpHeaders;
+import org.springframework.http.HttpMethod;
+import org.springframework.http.MediaType;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.client.RestTemplate;
+
+@RestController
+@org.springframework.context.annotation.Configuration
+@EnableAspectJAutoProxy
+@EPAuditLog
+public class UserRecommendationController extends EPRestrictedBaseController {
+
+ private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(UserRecommendationController.class);
+
+ @Autowired
+ private ConsulHealthService consulHealthService;
+
+ private static final String MACHINE_LEARNING_SERVICE_CTX = "/ml_api";
+ private static final String GET_RECOMMENDATION = MACHINE_LEARNING_SERVICE_CTX + "/" + "getRecommendation";
+ private static final String GET_RECOMM_COUNT = MACHINE_LEARNING_SERVICE_CTX + "/" + "getRecommCount";
+ private static final String CONSUL_ML_SERVICE_ID = "mlearning-service";
+ private static final String SERVICE_PROTOCOL = "http";
+
+ @RequestMapping(value = {
+ "/portalApi/getRecommendationsCount" }, method = RequestMethod.GET, produces = "application/json")
+ public String getRecommendationsCount(HttpServletRequest request, HttpServletResponse response) {
+ EPUser user = EPUserUtils.getUserSession(request);
+ Map<String, String> requestMapping = new HashMap<String, String>();
+ requestMapping.put("id", user.getOrgUserId());
+ requestMapping.put("action", "reports");
+
+ HttpHeaders headers = new HttpHeaders();
+ headers.setContentType(MediaType.APPLICATION_JSON);
+
+ // set your entity to send
+ HttpEntity<Map<String,String>> entity = new HttpEntity<>(requestMapping, headers);
+ String endpoint = SERVICE_PROTOCOL + "://"+ consulHealthService.getServiceLocation(CONSUL_ML_SERVICE_ID,
+ SystemProperties.getProperty("microservices.m-learn.local.port")) + GET_RECOMM_COUNT;
+ logger.debug(EELFLoggerDelegate.debugLogger, "Going to hit mlearning endpoint on: {1}", endpoint);
+ ResponseEntity<String> out = new RestTemplate().exchange(endpoint, HttpMethod.POST, entity, String.class);
+ return out.getBody();
+ }
+
+ @RequestMapping(value = {
+ "/portalApi/getRecommendations" }, method = RequestMethod.GET, produces = "application/json")
+ public String getRecommendations(HttpServletRequest request, HttpServletResponse response) {
+ EPUser user = EPUserUtils.getUserSession(request);
+ Map<String, String> requestMapping = new HashMap<String, String>();
+ requestMapping.put("id", user.getOrgUserId());
+ requestMapping.put("action", "reports");
+ requestMapping.put("recommendations", "1");
+
+ HttpHeaders headers = new HttpHeaders();
+ headers.setContentType(MediaType.APPLICATION_JSON);
+
+ // set your entity to send
+ HttpEntity<Map<String,String>> entity = new HttpEntity<>(requestMapping, headers);
+ String endpoint = SERVICE_PROTOCOL + "://"+
+ consulHealthService.getServiceLocation(CONSUL_ML_SERVICE_ID,
+ SystemProperties.getProperty("microservices.m-learn.local.port")) + GET_RECOMMENDATION;
+ logger.debug(EELFLoggerDelegate.debugLogger, "Going to hit mlearning endpoint on: {1}", endpoint);
+ ResponseEntity<String> out = new RestTemplate().exchange(endpoint, HttpMethod.POST, entity, String.class);
+ return out.getBody();
+ }
+
+} \ No newline at end of file
diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/UserRolesController.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/UserRolesController.java
index 719b7d45..7bcd5845 100644
--- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/UserRolesController.java
+++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/UserRolesController.java
@@ -57,7 +57,7 @@ import org.openecomp.portalsdk.core.domain.AuditLog;
import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
import org.openecomp.portalsdk.core.restful.domain.EcompRole;
import org.openecomp.portalsdk.core.service.AuditService;
-import org.openecomp.portalsdk.core.service.RoleService;
+import org.openecomp.portalsdk.core.util.SystemProperties;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
@@ -74,29 +74,34 @@ import org.springframework.web.bind.annotation.RestController;
@EPAuditLog
public class UserRolesController extends EPRestrictedBaseController {
+ private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(UserRolesController.class);
+
@Autowired
- SearchService searchService;
- @Autowired
- AdminRolesService adminRolesService;
- @Autowired
- UserRolesService userRolesService;
+ private SearchService searchService;
@Autowired
- ApplicationsRestClientService applicationsRestClientService;
+ private AdminRolesService adminRolesService;
+ private @Autowired UserRolesService userRolesService;
@Autowired
- RoleService roleService;
+ private ApplicationsRestClientService applicationsRestClientService;
@Autowired
- AuditService auditService;
- EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(UserRolesController.class);
-
- static final String FAILURE = "failure";
+ private AuditService auditService;
+
+ private static final String FAILURE = "failure";
/**
* RESTful service method to fetch users in the WebPhone external service
*
+ * @param request
+ * HttpServletRequest
+ * @param searchString
+ * search string
+ * @param response
+ * HttpServletResponse
* @return array of found users as json
*/
@RequestMapping(value = { "/portalApi/queryUsers" }, method = RequestMethod.GET, produces = "application/json")
- public String getPhoneBookSearchResult(HttpServletRequest request, @RequestParam("search") String searchString, HttpServletResponse response) {
+ public String getPhoneBookSearchResult(HttpServletRequest request, @RequestParam("search") String searchString,
+ HttpServletResponse response) {
EPUser user = EPUserUtils.getUserSession(request);
String searchResult = null;
if (!adminRolesService.isSuperAdmin(user) && !adminRolesService.isAccountAdmin(user)) {
@@ -106,23 +111,32 @@ public class UserRolesController extends EPRestrictedBaseController {
if (searchString.length() > 2) {
searchResult = searchService.searchUsersInPhoneBook(searchString);
} else {
- logger.info(EELFLoggerDelegate.errorLogger, "getPhoneBookSearchResult - too short search string: " + searchString);
+ logger.info(EELFLoggerDelegate.errorLogger,
+ "getPhoneBookSearchResult - too short search string: " + searchString);
}
}
EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/queryUsers", "result =", searchResult);
-
+
return searchResult;
}
/**
* RESTful service method to fetch applications where user is admin
*
- * @return for GET: array of all applications with boolean isAdmin=true/false for each application
+ * @param request
+ * HttpServletRequest
+ * @param orgUserId
+ * search string
+ * @param response
+ * HttpServletResponse
+ * @return for GET: array of all applications with boolean
+ * isAdmin=true/false for each application
*/
- @RequestMapping(value = { "/portalApi/adminAppsRoles" }, method = { RequestMethod.GET }, produces = "application/json")
- public AppsListWithAdminRole getAppsWithAdminRoleStateForUser(HttpServletRequest request, @RequestParam("user") String orgUserId,
- HttpServletResponse response) {
-
+ @RequestMapping(value = { "/portalApi/adminAppsRoles" }, method = {
+ RequestMethod.GET }, produces = "application/json")
+ public AppsListWithAdminRole getAppsWithAdminRoleStateForUser(HttpServletRequest request,
+ @RequestParam("user") String orgUserId, HttpServletResponse response) {
+
EPUser user = EPUserUtils.getUserSession(request);
AppsListWithAdminRole result = null;
if (!adminRolesService.isSuperAdmin(user)) {
@@ -131,15 +145,16 @@ public class UserRolesController extends EPRestrictedBaseController {
if (EcompPortalUtils.legitimateUserId(orgUserId)) {
result = adminRolesService.getAppsWithAdminRoleStateForUser(orgUserId);
} else {
- logger.info(EELFLoggerDelegate.errorLogger, "getAppsWithAdminRoleStateForUser - parms error, no Organization User ID");
+ logger.info(EELFLoggerDelegate.errorLogger,
+ "getAppsWithAdminRoleStateForUser - parms error, no Organization User ID");
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
}
}
StringBuilder adminAppRoles = new StringBuilder();
- if(result != null && result.appsRoles.size() >= 1) {
+ if (result != null && result.appsRoles.size() >= 1) {
adminAppRoles.append("User '" + result.orgUserId + "' has admin role to the apps = {");
- for(AppNameIdIsAdmin adminAppRole : result.appsRoles) {
+ for (AppNameIdIsAdmin adminAppRole : result.appsRoles) {
if (adminAppRole.isAdmin) {
adminAppRoles.append(adminAppRole.appName + ", ");
}
@@ -149,36 +164,47 @@ public class UserRolesController extends EPRestrictedBaseController {
adminAppRoles.append("User '" + result.orgUserId + "' has no Apps with Admin Role.");
}
logger.info(EELFLoggerDelegate.errorLogger, adminAppRoles.toString());
-
+
EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/adminAppsRoles", "get result =", result);
return result;
}
- @RequestMapping(value = { "/portalApi/adminAppsRoles" }, method = { RequestMethod.PUT }, produces = "application/json")
- public FieldsValidator putAppsWithAdminRoleStateForUser(HttpServletRequest request, @RequestBody AppsListWithAdminRole newAppsListWithAdminRoles,
- HttpServletResponse response) {
-
- //newAppsListWithAdminRoles.appsRoles
+ /**
+ *
+ * @param request
+ * HttpServletRequest
+ * @param newAppsListWithAdminRoles
+ * new apps
+ * @param response
+ * HttpServletResponse
+ * @return FieldsValidator
+ */
+ @RequestMapping(value = { "/portalApi/adminAppsRoles" }, method = {
+ RequestMethod.PUT }, produces = "application/json")
+ public FieldsValidator putAppsWithAdminRoleStateForUser(HttpServletRequest request,
+ @RequestBody AppsListWithAdminRole newAppsListWithAdminRoles, HttpServletResponse response) {
+
+ // newAppsListWithAdminRoles.appsRoles
FieldsValidator fieldsValidator = new FieldsValidator();
StringBuilder newAppRoles = new StringBuilder();
- if(newAppsListWithAdminRoles != null && newAppsListWithAdminRoles.appsRoles.size() >= 1) {
+ if (newAppsListWithAdminRoles != null && newAppsListWithAdminRoles.appsRoles.size() >= 1) {
newAppRoles.append("User '" + newAppsListWithAdminRoles.orgUserId + "' has admin role to the apps = { ");
- for(AppNameIdIsAdmin adminAppRole : newAppsListWithAdminRoles.appsRoles) {
+ for (AppNameIdIsAdmin adminAppRole : newAppsListWithAdminRoles.appsRoles) {
if (adminAppRole.isAdmin) {
newAppRoles.append(adminAppRole.appName + " ,");
}
}
- newAppRoles.deleteCharAt(newAppRoles.length()-1);
+ newAppRoles.deleteCharAt(newAppRoles.length() - 1);
newAppRoles.append("}.");
} else {
newAppRoles.append("User '" + newAppsListWithAdminRoles.orgUserId + "' has no Apps with Admin Role.");
}
logger.info(EELFLoggerDelegate.errorLogger, newAppRoles.toString());
-
+
EPUser user = EPUserUtils.getUserSession(request);
boolean changesApplied = false;
-
+
if (!adminRolesService.isSuperAdmin(user)) {
EcompPortalUtils.setBadPermissions(user, response, "putAppsWithAdminRoleStateForUser");
} else {
@@ -190,20 +216,44 @@ public class UserRolesController extends EPRestrictedBaseController {
auditLog.setComments(newAppRoles.toString());
auditService.logActivity(auditLog, null);
- MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP,EPEELFLoggerAdvice.getCurrentDateTimeUTC());
- MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP,EPEELFLoggerAdvice.getCurrentDateTimeUTC());
- logger.info(EELFLoggerDelegate.auditLogger, EPLogUtil.formatAuditLogMessage("UserRolesController.putAppsWithAdminRoleStateForUser",
- EcompAuditLog.CD_ACTIVITY_UPDATE_ACCOUNT_ADMIN, user.getOrgUserId(), newAppsListWithAdminRoles.orgUserId, newAppRoles.toString()));
+ MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
+ MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
+ EcompPortalUtils.calculateDateTimeDifferenceForLog(
+ MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),
+ MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
+ logger.info(EELFLoggerDelegate.auditLogger,
+ EPLogUtil.formatAuditLogMessage("UserRolesController.putAppsWithAdminRoleStateForUser",
+ EcompAuditLog.CD_ACTIVITY_UPDATE_ACCOUNT_ADMIN, user.getOrgUserId(),
+ newAppsListWithAdminRoles.orgUserId, newAppRoles.toString()));
MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
+ MDC.remove(SystemProperties.MDC_TIMER);
}
EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/adminAppsRoles", "put result =", changesApplied);
-
+
return fieldsValidator;
}
- @RequestMapping(value = { "/portalApi/userAppRoles" }, method = { RequestMethod.GET }, produces = "application/json")
- public List<RoleInAppForUser> getAppRolesForUser(HttpServletRequest request, @RequestParam("user") String orgUserId, @RequestParam("app") Long appid, HttpServletResponse response) {
+ /**
+ * It returns a list of user app roles for single app
+ *
+ * @param request
+ * HttpServletRequest
+ * @param response
+ * HttpServletResponse
+ * @param orgUserId
+ * user ID
+ * @param appid
+ * application ID
+ * @param extRequestValue
+ * set to false if request is from users page otherwise true
+ * @return List<RoleInAppForUser>
+ */
+ @RequestMapping(value = { "/portalApi/userAppRoles" }, method = {
+ RequestMethod.GET }, produces = "application/json")
+ public List<RoleInAppForUser> getAppRolesForUser(HttpServletRequest request, @RequestParam("user") String orgUserId,
+ @RequestParam("app") Long appid, @RequestParam("externalRequest") Boolean extRequestValue,
+ HttpServletResponse response) {
EPUser user = EPUserUtils.getUserSession(request);
List<RoleInAppForUser> result = null;
String feErrorString = "";
@@ -212,16 +262,18 @@ public class UserRolesController extends EPRestrictedBaseController {
feErrorString = EcompPortalUtils.getFEErrorString(true, response.getStatus());
} else {
if (EcompPortalUtils.legitimateUserId(orgUserId)) {
- result = userRolesService.getAppRolesForUser(appid, orgUserId);
+ result = userRolesService.getAppRolesForUser(appid, orgUserId, extRequestValue);
int responseCode = EcompPortalUtils.getExternalAppResponseCode();
if (responseCode != 0 && responseCode != 200) {
// external error
response.setStatus(responseCode);
feErrorString = EcompPortalUtils.getFEErrorString(false, responseCode);
} else if (result == null) {
- // If the result is null, there was an internal ecomp error in the service call.
+ // If the result is null, there was an internal ecomp error
+ // in the service call.
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
- feErrorString = EcompPortalUtils.getFEErrorString(true, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ feErrorString = EcompPortalUtils.getFEErrorString(true,
+ HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
} else {
logger.info(EELFLoggerDelegate.errorLogger, "getAppRolesForUser - no Organization User ID");
@@ -229,29 +281,29 @@ public class UserRolesController extends EPRestrictedBaseController {
feErrorString = EcompPortalUtils.getFEErrorString(true, HttpServletResponse.SC_BAD_REQUEST);
}
}
-
+
StringBuilder sbUserApps = new StringBuilder();
- if (result!=null && result.size()>=1) {
+ if (result != null && result.size() >= 1) {
sbUserApps.append("User '" + orgUserId + "' has Roles={");
- for(RoleInAppForUser appRole : result) {
+ for (RoleInAppForUser appRole : result) {
if (appRole.isApplied) {
sbUserApps.append(appRole.roleName + ", ");
}
}
sbUserApps.append("} assigned to the appId '" + appid + "'.");
} else {
- //Not sure creating an empty object will make any difference
- //but would like to give it a shot for defect #DE221057
- if (result==null) {
+ // Not sure creating an empty object will make any difference
+ // but would like to give it a shot for defect #DE221057
+ if (result == null) {
result = new ArrayList<RoleInAppForUser>();
}
sbUserApps.append("User '" + orgUserId + "' and appid " + appid + " has no roles");
}
logger.info(EELFLoggerDelegate.errorLogger, sbUserApps.toString());
-
+
EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/userAppRoles", "get result =", result);
if (feErrorString != "") {
- logger.debug(EELFLoggerDelegate.debugLogger, "LR: FEErrorString to header: "+feErrorString);
+ logger.debug(EELFLoggerDelegate.debugLogger, "LR: FEErrorString to header: " + feErrorString);
response.addHeader("FEErrorString", feErrorString);
response.addHeader("Access-Control-Expose-Headers", "FEErrorString");
@@ -259,129 +311,155 @@ public class UserRolesController extends EPRestrictedBaseController {
return result;
}
- @RequestMapping(value = { "/portalApi/userAppRoles" }, method = { RequestMethod.PUT }, produces = "application/json")
- public FieldsValidator putAppWithUserRoleStateForUser(HttpServletRequest request, @RequestBody AppWithRolesForUser newAppRolesForUser,
- HttpServletResponse response) {
+ @RequestMapping(value = { "/portalApi/userAppRoles" }, method = {
+ RequestMethod.PUT }, produces = "application/json")
+ public FieldsValidator putAppWithUserRoleStateForUser(HttpServletRequest request,
+ @RequestBody AppWithRolesForUser newAppRolesForUser, HttpServletResponse response) {
FieldsValidator fieldsValidator = new FieldsValidator();
StringBuilder sbUserApps = new StringBuilder();
- if (newAppRolesForUser!=null) {
+ if (newAppRolesForUser != null) {
sbUserApps.append("User '" + newAppRolesForUser.orgUserId);
- if (newAppRolesForUser.appRoles!=null && newAppRolesForUser.appRoles.size()>=1) {
+ if (newAppRolesForUser.appRoles != null && newAppRolesForUser.appRoles.size() >= 1) {
sbUserApps.append("' has roles = { ");
- for(RoleInAppForUser appRole : newAppRolesForUser.appRoles) {
- if (appRole.isApplied) {
- sbUserApps.append(appRole.roleName + " ,");
- }
+ for (RoleInAppForUser appRole : newAppRolesForUser.appRoles) {
+ if (appRole.isApplied) {
+ sbUserApps.append(appRole.roleName + " ,");
+ }
}
- sbUserApps.deleteCharAt(sbUserApps.length()-1);
+ sbUserApps.deleteCharAt(sbUserApps.length() - 1);
sbUserApps.append("} assigned for the app " + newAppRolesForUser.appId);
} else {
sbUserApps.append("' has no roles assigned for app " + newAppRolesForUser.appId);
}
}
logger.info(EELFLoggerDelegate.applicationLogger, "putAppWithUserRoleStateForUser: {}", sbUserApps.toString());
-
+
EPUser user = EPUserUtils.getUserSession(request);
boolean changesApplied = false;
if (!adminRolesService.isAccountAdmin(user)) {
EcompPortalUtils.setBadPermissions(user, response, "putAppWithUserRoleStateForUser");
} else {
changesApplied = userRolesService.setAppWithUserRoleStateForUser(user, newAppRolesForUser);
- if (changesApplied){
- logger.info(EELFLoggerDelegate.applicationLogger, "putAppWithUserRoleStateForUser: succeeded for app {}, user {}",
- newAppRolesForUser.appId, newAppRolesForUser.orgUserId);
+ if (changesApplied) {
+ logger.info(EELFLoggerDelegate.applicationLogger,
+ "putAppWithUserRoleStateForUser: succeeded for app {}, user {}", newAppRolesForUser.appId,
+ newAppRolesForUser.orgUserId);
AuditLog auditLog = new AuditLog();
auditLog.setUserId(user.getId());
auditLog.setActivityCode(EcompAuditLog.CD_ACTIVITY_UPDATE_USER);
auditLog.setAffectedRecordId(newAppRolesForUser.orgUserId);
auditLog.setComments(sbUserApps.toString());
- MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
+ MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
auditService.logActivity(auditLog, null);
- MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP,EPEELFLoggerAdvice.getCurrentDateTimeUTC());
- logger.info(EELFLoggerDelegate.auditLogger, EPLogUtil.formatAuditLogMessage("UserRolesController.putAppWithUserRoleStateForUser",
- EcompAuditLog.CD_ACTIVITY_UPDATE_USER, user.getOrgUserId(), newAppRolesForUser.orgUserId, sbUserApps.toString()));
+ MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
+ EcompPortalUtils.calculateDateTimeDifferenceForLog(
+ MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),
+ MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
+ logger.info(EELFLoggerDelegate.auditLogger,
+ EPLogUtil.formatAuditLogMessage("UserRolesController.putAppWithUserRoleStateForUser",
+ EcompAuditLog.CD_ACTIVITY_UPDATE_USER, user.getOrgUserId(),
+ newAppRolesForUser.orgUserId, sbUserApps.toString()));
MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
+ MDC.remove(SystemProperties.MDC_TIMER);
} else {
- logger.error(EELFLoggerDelegate.errorLogger, "putAppWithUserRoleStateForUser: failed for app {}, user {}",
- newAppRolesForUser.appId, newAppRolesForUser.orgUserId);
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "putAppWithUserRoleStateForUser: failed for app {}, user {}", newAppRolesForUser.appId,
+ newAppRolesForUser.orgUserId);
}
}
EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/userAppRoles", "put result =", changesApplied);
return fieldsValidator;
}
-
- @RequestMapping(value = { "/portalApi/updateRemoteUserProfile" }, method = { RequestMethod.GET }, produces = "application/json")
- public PortalRestResponse<String> updateRemoteUserProfile(HttpServletRequest request,HttpServletResponse response) {
-
+
+ @RequestMapping(value = { "/portalApi/updateRemoteUserProfile" }, method = {
+ RequestMethod.GET }, produces = "application/json")
+ public PortalRestResponse<String> updateRemoteUserProfile(HttpServletRequest request,
+ HttpServletResponse response) {
+
String updateRemoteUserFlag = FAILURE;
try {
- //saveNewUser = userService.saveNewUser(newUser);
+ // saveNewUser = userService.saveNewUser(newUser);
String orgUserId = request.getParameter("loginId");
Long appId = Long.parseLong(request.getParameter("appId"));
userRolesService.updateRemoteUserProfile(orgUserId, appId);
-
+
} catch (Exception e) {
return new PortalRestResponse<String>(PortalRestStatusEnum.OK, updateRemoteUserFlag, e.getMessage());
}
return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, updateRemoteUserFlag, "");
-
+
}
- @RequestMapping(value = { "/portalApi/app/{appId}/users" }, method = { RequestMethod.GET }, produces = "application/json")
- public List<UserApplicationRoles> getUsersFromAppEndpoint(HttpServletRequest request, @PathVariable("appId") Long appId) throws HTTPException {
+ @RequestMapping(value = { "/portalApi/app/{appId}/users" }, method = {
+ RequestMethod.GET }, produces = "application/json")
+ public List<UserApplicationRoles> getUsersFromAppEndpoint(HttpServletRequest request,
+ @PathVariable("appId") Long appId) throws HTTPException {
try {
logger.debug(EELFLoggerDelegate.debugLogger, "/portalApi/app/{}/users was invoked", appId);
List<UserApplicationRoles> appUsers = userRolesService.getUsersFromAppEndpoint(appId);
return appUsers;
- } catch(Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while performing UserRolesController.getUsersFromAppEndpoint. Details: " + EcompPortalUtils.getStackTrace(e));
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "Exception occurred while performing UserRolesController.getUsersFromAppEndpoint. Details: "
+ + EcompPortalUtils.getStackTrace(e));
return new ArrayList<UserApplicationRoles>();
}
}
- @RequestMapping(value = { "/portalApi/app/{appId}/roles" }, method = { RequestMethod.GET }, produces = "application/json")
- public List<EcompRole> testGetRoles(HttpServletRequest request, @PathVariable("appId") Long appId) throws HTTPException {
+ @RequestMapping(value = { "/portalApi/app/{appId}/roles" }, method = {
+ RequestMethod.GET }, produces = "application/json")
+ public List<EcompRole> testGetRoles(HttpServletRequest request, @PathVariable("appId") Long appId)
+ throws HTTPException {
EcompRole[] appRoles = applicationsRestClientService.get(EcompRole[].class, appId, "/roles");
List<EcompRole> rolesList = Arrays.asList(appRoles);
- EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/app/{appId}/roles", "response for appId=" + appId, rolesList);
-
+ EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/app/{appId}/roles", "response for appId=" + appId,
+ rolesList);
+
return rolesList;
}
- @RequestMapping(value = { "/portalApi/admin/import/app/{appId}/roles" }, method = { RequestMethod.GET }, produces = "application/json")
- public List<EPRole> importRolesFromRemoteApplication(HttpServletRequest request, @PathVariable("appId") Long appId) throws HTTPException {
+ @RequestMapping(value = { "/portalApi/admin/import/app/{appId}/roles" }, method = {
+ RequestMethod.GET }, produces = "application/json")
+ public List<EPRole> importRolesFromRemoteApplication(HttpServletRequest request, @PathVariable("appId") Long appId)
+ throws HTTPException {
List<EPRole> rolesList = userRolesService.importRolesFromRemoteApplication(appId);
- EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/admin/import/app/{appId}/roles", "response for appId=" + appId, rolesList);
-
+ EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/admin/import/app/{appId}/roles",
+ "response for appId=" + appId, rolesList);
+
return rolesList;
}
- @RequestMapping(value = { "/portalApi/app/{appId}/user/{orgUserId}/roles" }, method = { RequestMethod.GET }, produces = "application/json")
- public EcompRole testGetRoles(HttpServletRequest request, @PathVariable("appId") Long appId, @PathVariable("orgUserId") String orgUserId) throws Exception {
+ @RequestMapping(value = { "/portalApi/app/{appId}/user/{orgUserId}/roles" }, method = {
+ RequestMethod.GET }, produces = "application/json")
+ public EcompRole testGetRoles(HttpServletRequest request, @PathVariable("appId") Long appId,
+ @PathVariable("orgUserId") String orgUserId) throws Exception {
if (!EcompPortalUtils.legitimateUserId(orgUserId)) {
String msg = "Error /user/<user>/roles not legitimate orgUserId = " + orgUserId;
logger.error(EELFLoggerDelegate.errorLogger, msg);
throw new Exception(msg);
}
- EcompRole[] roles = applicationsRestClientService.get(EcompRole[].class, appId, String.format("/user/%s/roles", orgUserId));
+ EcompRole[] roles = applicationsRestClientService.get(EcompRole[].class, appId,
+ String.format("/user/%s/roles", orgUserId));
if (roles.length != 1) {
String msg = "Error /user/<user>/roles returned array. expected size 1 recieved size = " + roles.length;
logger.error(EELFLoggerDelegate.errorLogger, msg);
throw new Exception(msg);
}
-
- EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/app/{appId}/user/{orgUserId}/roles", "response for appId='" + appId + "' and orgUserId='" + orgUserId + "'", roles[0]);
+
+ EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/app/{appId}/user/{orgUserId}/roles",
+ "response for appId='" + appId + "' and orgUserId='" + orgUserId + "'", roles[0]);
return roles[0];
}
-
- @RequestMapping(value = { "/portalApi/saveUserAppRoles" }, method = { RequestMethod.PUT }, produces = "application/json")
- public FieldsValidator putAppWithUserRoleRequest(HttpServletRequest request, @RequestBody AppWithRolesForUser newAppRolesForUser,
- HttpServletResponse response) {
+
+ @RequestMapping(value = { "/portalApi/saveUserAppRoles" }, method = {
+ RequestMethod.PUT }, produces = "application/json")
+ public FieldsValidator putAppWithUserRoleRequest(HttpServletRequest request,
+ @RequestBody AppWithRolesForUser newAppRolesForUser, HttpServletResponse response) {
FieldsValidator fieldsValidator = null;
try {
-
+
EPUser user = EPUserUtils.getUserSession(request);
fieldsValidator = userRolesService.putUserAppRolesRequest(newAppRolesForUser, user);
response.setStatus(fieldsValidator.httpStatusCode.intValue());
@@ -395,7 +473,7 @@ public class UserRolesController extends EPRestrictedBaseController {
response.getStatus());
return fieldsValidator;
}
-
+
@RequestMapping(value = { "/portalApi/appCatalogRoles" }, method = {
RequestMethod.GET }, produces = "application/json")
public List<EPUserAppCatalogRoles> getUserAppCatalogRoles(HttpServletRequest request,
@@ -414,22 +492,24 @@ public class UserRolesController extends EPRestrictedBaseController {
return userAppRoleList;
}
+
private Comparator<EPUserAppCatalogRoles> getUserAppCatalogRolesComparator = new Comparator<EPUserAppCatalogRoles>() {
public int compare(EPUserAppCatalogRoles o1, EPUserAppCatalogRoles o2) {
return o1.getRolename().compareTo(o2.getRolename());
}
};
-
+
@RequestMapping(value = "/portalApi/externalRequestAccessSystem", method = RequestMethod.GET, produces = "application/json")
public ExternalSystemAccess readExternalRequestAccess(HttpServletRequest request) {
ExternalSystemAccess result = null;
- try {
+ try {
result = userRolesService.getExternalRequestAccess();
- EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/externalRequestAccessSystem", "GET result =", result);
+ EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/externalRequestAccessSystem", "GET result =",
+ result);
} catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger,"readExternalRequestAccess failed: " + e.getMessage());
- }
+ logger.error(EELFLoggerDelegate.errorLogger, "readExternalRequestAccess failed: " + e.getMessage());
+ }
return result;
}
-
+
}
diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/WebAnalyticsExtAppController.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/WebAnalyticsExtAppController.java
index f1d77a3f..b5761617 100644
--- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/WebAnalyticsExtAppController.java
+++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/WebAnalyticsExtAppController.java
@@ -1,157 +1,241 @@
-/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.controller;
-
-import java.io.InputStream;
-import java.nio.charset.StandardCharsets;
-
-import javax.servlet.http.HttpServletRequest;
-
-import org.apache.commons.io.IOUtils;
-import org.openecomp.portalapp.controller.EPRestrictedRESTfulBaseController;
-import org.openecomp.portalapp.portal.domain.EPApp;
-import org.openecomp.portalapp.portal.domain.EcompAuditLog;
-import org.openecomp.portalapp.portal.logging.aop.EPAuditLog;
-import org.openecomp.portalapp.portal.logging.aop.EPEELFLoggerAdvice;
-import org.openecomp.portalapp.portal.logging.logic.EPLogUtil;
-import org.openecomp.portalapp.portal.service.AppsCacheService;
-import org.openecomp.portalapp.portal.transport.Analytics;
-import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties;
-import org.openecomp.portalapp.portal.utils.PortalConstants;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalsdk.core.onboarding.crossapi.PortalAPIResponse;
-import org.openecomp.portalsdk.core.service.AuditService;
-import org.openecomp.portalsdk.core.util.SystemProperties;
-import org.slf4j.MDC;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.context.annotation.EnableAspectJAutoProxy;
-import org.springframework.web.bind.annotation.RequestBody;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestMethod;
-import org.springframework.web.bind.annotation.ResponseBody;
-import org.springframework.web.bind.annotation.RestController;
-
-import io.swagger.annotations.ApiOperation;
-
-@RestController
-@RequestMapping(PortalConstants.REST_AUX_API)
-@Configuration
-@EnableAspectJAutoProxy
-@EPAuditLog
-public class WebAnalyticsExtAppController extends EPRestrictedRESTfulBaseController{
-
- private static final String APP_KEY = "uebkey";
-
- @Autowired
- AuditService auditService;
-
- @Autowired
- AppsCacheService appCacheService;
-
- EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(WebAnalyticsExtAppController.class);
-
- protected boolean isAuxRESTfulCall() {
- return true;
- }
-
- /*
- * Answers requests from partner applications for a file that is expected to
- * contain javascript to support web analytics.
- *
- * @param request
- * @return
- * @throws Exception
- */
- @ApiOperation(value = "Gets javascript with functions that support gathering and reporting web analytics.", response = String.class)
- @RequestMapping(value = { "/analytics" }, method = RequestMethod.GET, produces = "application/javascript")
- public String getAnalyticsScript(HttpServletRequest request) throws Exception {
- String responseText = "";
- final String fileName = "analytics.txt";
- InputStream analyticsFileStream = null;
- try {
- analyticsFileStream = this.getClass().getClassLoader().getResourceAsStream(fileName);
- responseText = IOUtils.toString(analyticsFileStream, StandardCharsets.UTF_8.name());
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "Error reading contents of the file " + fileName, e);
- } finally {
- if (analyticsFileStream != null)
- analyticsFileStream.close();
- }
-
- String feURLContext = SystemProperties.getProperty("frontend_url");
- String feURL = feURLContext.substring(0, feURLContext.lastIndexOf('/'));
-
- responseText = responseText.replace("PORTAL_ENV_URL", feURL);
- return responseText;
- }
-
- /**
- * Accepts data from partner applications with web analytics data.
- *
- * @param request
- * @param analyticsMap
- * @param response
- * @return
- * @throws Exception
- */
- @RequestMapping(value = { "/storeAnalytics" }, method = RequestMethod.POST, produces = "application/json")
- @ResponseBody
- @ApiOperation(value = "Accepts data from partner applications with web analytics data.", response = PortalAPIResponse.class)
- public PortalAPIResponse storeAnalyticsScript(HttpServletRequest request, @RequestBody Analytics analyticsMap) throws Exception {
- try{
- MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP,EPEELFLoggerAdvice.getCurrentDateTimeUTC());
- MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP,EPEELFLoggerAdvice.getCurrentDateTimeUTC());
- String appName = "";
- try {
-
- String appKeyValue = request.getHeader(APP_KEY);
- if(appKeyValue == null || appKeyValue.equals("")) {
- logger.error(EELFLoggerDelegate.errorLogger, " App Key unavailable; Proceeding with null app name");
- } else {
- EPApp appRecord = appCacheService.getAppForAnalytics(appKeyValue);
- if(appRecord == null){
- logger.error(EELFLoggerDelegate.errorLogger, " App could not be found for the key "+ appKeyValue);
- }
- else appName = appRecord.getName();
-
- }
-
- } catch(Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, " Error retrieving Application to capture app name for analytics; Proceeding with empty app name");
- }
-
-
-
- logger.info(EELFLoggerDelegate.auditLogger, EPLogUtil.formatStoreAnalyticsAuditLogMessage(analyticsMap.getUserId(),appName, "WebAnalyticsExtAppController.postWebAnalyticsData",
- EcompAuditLog.CD_ACTIVITY_STORE_ANALYTICS, analyticsMap.getAction(),analyticsMap.getPage(),analyticsMap.getFunction(),analyticsMap.getType()));
- MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
- MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
-
- PortalAPIResponse response = new PortalAPIResponse(true, "success");
- return response;
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "storeAnalytics failed", e);
- PortalAPIResponse response = new PortalAPIResponse(true, "error");
- return response;
- }
- }
-
-}
+/*-
+ * ================================================================================
+ * ECOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.controller;
+
+import java.io.InputStream;
+import java.nio.charset.StandardCharsets;
+import java.util.HashMap;
+import java.util.Map;
+
+import javax.servlet.http.HttpServletRequest;
+
+import org.apache.commons.io.IOUtils;
+import org.openecomp.portalapp.controller.EPRestrictedRESTfulBaseController;
+import org.openecomp.portalapp.portal.domain.EPApp;
+import org.openecomp.portalapp.portal.domain.EcompAuditLog;
+import org.openecomp.portalapp.portal.logging.aop.EPAuditLog;
+import org.openecomp.portalapp.portal.logging.aop.EPEELFLoggerAdvice;
+import org.openecomp.portalapp.portal.logging.logic.EPLogUtil;
+import org.openecomp.portalapp.portal.service.AppsCacheService;
+import org.openecomp.portalapp.portal.service.ConsulHealthService;
+import org.openecomp.portalapp.portal.transport.Analytics;
+import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties;
+import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
+import org.openecomp.portalapp.portal.utils.PortalConstants;
+import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.openecomp.portalsdk.core.onboarding.crossapi.PortalAPIResponse;
+import org.openecomp.portalsdk.core.service.AuditService;
+import org.openecomp.portalsdk.core.util.SystemProperties;
+import org.slf4j.MDC;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.EnableAspectJAutoProxy;
+import org.springframework.http.HttpEntity;
+import org.springframework.http.HttpHeaders;
+import org.springframework.http.HttpMethod;
+import org.springframework.http.MediaType;
+import org.springframework.http.ResponseEntity;
+import org.springframework.util.concurrent.FailureCallback;
+import org.springframework.util.concurrent.ListenableFuture;
+import org.springframework.util.concurrent.SuccessCallback;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.ResponseBody;
+import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.client.AsyncRestTemplate;
+
+import io.swagger.annotations.ApiOperation;
+
+@RestController
+@RequestMapping(PortalConstants.REST_AUX_API)
+@Configuration
+@EnableAspectJAutoProxy
+@EPAuditLog
+public class WebAnalyticsExtAppController extends EPRestrictedRESTfulBaseController {
+
+ @Autowired
+ private ConsulHealthService consulHealthService;
+
+ private static final String MACHINE_LEARNING_SERVICE_CTX = "/ml_api";
+ private static final String REGISTER_ACTION = MACHINE_LEARNING_SERVICE_CTX + "/" + "registerAction";
+ private static final String CONSUL_ML_SERVICE_ID = "machine-learning";
+ private static final String SERVICE_PROTOCOL = "http";
+ private static final String APP_KEY = "uebkey";
+
+ @Autowired
+ AuditService auditService;
+
+ @Autowired
+ AppsCacheService appCacheService;
+
+ private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(WebAnalyticsExtAppController.class);
+
+ private AsyncRestTemplate restTemplate = new AsyncRestTemplate();
+
+ SuccessCallback<ResponseEntity<String>> successCallback = new SuccessCallback<ResponseEntity<String>>() {
+ @Override
+ public void onSuccess(ResponseEntity<String> arg) {
+ logger.info(EELFLoggerDelegate.debugLogger, arg.getBody());
+ }
+ };
+
+ FailureCallback failureCallback = new FailureCallback() {
+ @Override
+ public void onFailure(Throwable arg) {
+ logger.error(EELFLoggerDelegate.errorLogger, "storeAuxAnalytics failed", arg);
+ }
+ };
+
+ protected boolean isAuxRESTfulCall() {
+ return true;
+ }
+
+ /**
+ * Answers requests from partner applications for a file that is expected to
+ * contain javascript to support web analytics.
+ *
+ * @param request
+ * HttpServletRequest
+ * @return String
+ * @throws Exception
+ * on failure
+ */
+ @ApiOperation(value = "Gets javascript with functions that support gathering and reporting web analytics.", response = String.class)
+ @RequestMapping(value = { "/analytics" }, method = RequestMethod.GET, produces = "application/javascript")
+ public String getAnalyticsScript(HttpServletRequest request) throws Exception {
+ String responseText = "";
+ final String fileName = "analytics.txt";
+ InputStream analyticsFileStream = null;
+ try {
+ analyticsFileStream = this.getClass().getClassLoader().getResourceAsStream(fileName);
+ responseText = IOUtils.toString(analyticsFileStream, StandardCharsets.UTF_8.name());
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "Error reading contents of the file " + fileName, e);
+ } finally {
+ if (analyticsFileStream != null)
+ analyticsFileStream.close();
+ }
+
+ String feURLContext = SystemProperties.getProperty("frontend_url");
+ String feURL = feURLContext.substring(0, feURLContext.lastIndexOf('/'));
+
+ responseText = responseText.replace("PORTAL_ENV_URL", feURL);
+ return responseText;
+ }
+
+ /**
+ * Accepts data from partner applications with web analytics data.
+ *
+ * @param request
+ * HttpServletRequest
+ * @param analyticsMap
+ * Analytics
+ * @return PortalAPIResponse
+ * @throws Exception
+ * on failure
+ */
+ @RequestMapping(value = { "/storeAnalytics" }, method = RequestMethod.POST, produces = "application/json")
+ @ResponseBody
+ @ApiOperation(value = "Accepts data from partner applications with web analytics data.", response = PortalAPIResponse.class)
+ public PortalAPIResponse storeAnalyticsScript(HttpServletRequest request, @RequestBody Analytics analyticsMap)
+ throws Exception {
+ try {
+ MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
+ String appName = "";
+ try {
+ appName = getAppName(request, appName);
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger,
+ " Error retrieving Application to capture app name for analytics; Proceeding with empty app name");
+ }
+
+ try {
+ storeAuxAnalytics(analyticsMap, appName);
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger,
+ " Error retrieving Application to capture app name for analytics; Proceeding with empty app name");
+ }
+
+ MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
+
+ EcompPortalUtils.calculateDateTimeDifferenceForLog(
+ MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),
+ MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
+ logger.info(EELFLoggerDelegate.auditLogger,
+ EPLogUtil.formatStoreAnalyticsAuditLogMessage(analyticsMap.getUserId(), appName,
+ "WebAnalyticsExtAppController.postWebAnalyticsData",
+ EcompAuditLog.CD_ACTIVITY_STORE_ANALYTICS, analyticsMap.getAction(), analyticsMap.getPage(),
+ analyticsMap.getFunction(), analyticsMap.getType()));
+
+ MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
+ MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
+ MDC.remove(SystemProperties.MDC_TIMER);
+
+ PortalAPIResponse response = new PortalAPIResponse(true, "success");
+ return response;
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "storeAnalytics failed", e);
+ PortalAPIResponse response = new PortalAPIResponse(true, "error");
+ return response;
+ }
+ }
+
+ protected String getAppName(HttpServletRequest request, String appName) {
+ String appKeyValue = request.getHeader(APP_KEY);
+ if (appKeyValue == null || appKeyValue.equals("")) {
+ logger.error(EELFLoggerDelegate.errorLogger, " App Key unavailable; Proceeding with null app name");
+ } else {
+ EPApp appRecord = appCacheService.getAppForAnalytics(appKeyValue);
+ if (appRecord == null) {
+ logger.error(EELFLoggerDelegate.errorLogger, " App could not be found for the key " + appKeyValue);
+ } else
+ appName = appRecord.getName();
+
+ }
+ return appName;
+ }
+
+ protected void storeAuxAnalytics(Analytics analyticsMap, String appName) {
+ logger.info(EELFLoggerDelegate.debugLogger,
+ " Registering an action for recommendation: AppName/Function/UserId " + appName + "/"
+ + analyticsMap.getFunction() + "/" + analyticsMap.getUserId());
+
+ Map<String, String> requestMapping = new HashMap<String, String>();
+ requestMapping.put("id", analyticsMap.getUserId());
+ requestMapping.put("action", appName + "|" + analyticsMap.getFunction());
+
+ HttpHeaders headers = new HttpHeaders();
+ headers.setContentType(MediaType.APPLICATION_JSON);
+
+ // set your entity to send
+ HttpEntity<Map<String, String>> entity = new HttpEntity<Map<String, String>>(requestMapping, headers);
+
+ // send it!
+ ListenableFuture<ResponseEntity<String>> out = restTemplate.exchange(
+ SERVICE_PROTOCOL + "://"
+ + consulHealthService.getServiceLocation(CONSUL_ML_SERVICE_ID,
+ SystemProperties.getProperty("microservices.m-learn.local.port"))
+ + REGISTER_ACTION,
+ HttpMethod.POST, entity, String.class);
+ out.addCallback(successCallback, failureCallback);
+ }
+
+}
diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/WidgetsCatalogController.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/WidgetsCatalogController.java
index f69a6484..9ac81e9a 100644
--- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/WidgetsCatalogController.java
+++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/WidgetsCatalogController.java
@@ -1,376 +1,392 @@
-/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.controller;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.OutputStream;
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.openecomp.portalapp.controller.EPRestrictedBaseController;
-import org.openecomp.portalapp.portal.domain.EPUser;
-import org.openecomp.portalapp.portal.domain.MicroserviceData;
-import org.openecomp.portalapp.portal.domain.MicroserviceParameter;
-import org.openecomp.portalapp.portal.domain.WidgetCatalog;
-import org.openecomp.portalapp.portal.domain.WidgetCatalogParameter;
-import org.openecomp.portalapp.portal.domain.WidgetParameterResult;
-import org.openecomp.portalapp.portal.domain.WidgetServiceHeaders;
-import org.openecomp.portalapp.portal.ecomp.model.PortalRestResponse;
-import org.openecomp.portalapp.portal.ecomp.model.PortalRestStatusEnum;
-import org.openecomp.portalapp.portal.logging.aop.EPAuditLog;
-import org.openecomp.portalapp.portal.service.ConsulHealthService;
-import org.openecomp.portalapp.portal.service.MicroserviceService;
-import org.openecomp.portalapp.portal.service.WidgetParameterService;
-import org.openecomp.portalapp.util.EPUserUtils;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.EnableAspectJAutoProxy;
-import org.springframework.core.io.FileSystemResource;
-import org.springframework.http.HttpEntity;
-import org.springframework.http.HttpHeaders;
-import org.springframework.http.HttpMethod;
-import org.springframework.http.MediaType;
-import org.springframework.http.ResponseEntity;
-import org.springframework.util.LinkedMultiValueMap;
-import org.springframework.util.MultiValueMap;
-import org.springframework.web.bind.annotation.PathVariable;
-import org.springframework.web.bind.annotation.RequestBody;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestMethod;
-import org.springframework.web.bind.annotation.RestController;
-import org.springframework.web.client.RestClientException;
-import org.springframework.web.client.RestTemplate;
-import org.springframework.web.multipart.MultipartFile;
-import org.springframework.web.multipart.MultipartHttpServletRequest;
-import org.springframework.web.multipart.commons.CommonsMultipartResolver;
-
-@SuppressWarnings("unchecked")
-@RestController
-@org.springframework.context.annotation.Configuration
-@EnableAspectJAutoProxy
-@EPAuditLog
-public class WidgetsCatalogController extends EPRestrictedBaseController {
-
- private static final String HTTPS = "https://";
-
- EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(WidgetsCatalogController.class);
- RestTemplate template = new RestTemplate();
- String whatService = "widgets-service";
-
- @Autowired
- private ConsulHealthService consulHealthService;
-
- @Autowired
- private MicroserviceService microserviceService;
-
- @Autowired
- private WidgetParameterService widgetParameterService;
-
- @Bean
- public CommonsMultipartResolver multipartResolver() {
- return new CommonsMultipartResolver();
- }
-
- static {
- // for localhost testing only
- javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier(new javax.net.ssl.HostnameVerifier() {
-
- public boolean verify(String hostname, javax.net.ssl.SSLSession sslSession) {
- if (hostname.equals("localhost")) {
- return true;
- }
- return false;
- }
- });
- }
-
- @RequestMapping(value = { "/portalApi/microservices/widgetCatalog/{loginName}" }, method = RequestMethod.GET)
- public List<WidgetCatalog> getUserWidgetCatalog(HttpServletRequest request, HttpServletResponse response,
- @PathVariable("loginName") String loginName) throws RestClientException, Exception {
- List<WidgetCatalog> widgets = new ArrayList<>();
- try {
- ResponseEntity<ArrayList> ans = template.exchange(
- HTTPS + consulHealthService.getServiceLocation(whatService)
- + "/widget/microservices/widgetCatalog/" + loginName,
- HttpMethod.GET, new HttpEntity(WidgetServiceHeaders.getInstance()), ArrayList.class);
- widgets = ans.getBody();
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "getUserWidgetCatalog failed", e);
- // returning null because null help check on the UI if there was a
- // communication problem with Microservice.
- return null;
- }
- return widgets;
- }
-
- @RequestMapping(value = { "/portalApi/microservices/widgetCatalog" }, method = RequestMethod.GET)
- public List<WidgetCatalog> getWidgetCatalog(HttpServletRequest request, HttpServletResponse response)
- throws RestClientException, Exception {
- List<WidgetCatalog> widgets = new ArrayList<>();
- try {
- ResponseEntity<ArrayList> ans = template.exchange(
- HTTPS + consulHealthService.getServiceLocation(whatService)
- + "/widget/microservices/widgetCatalog",
- HttpMethod.GET, new HttpEntity(WidgetServiceHeaders.getInstance()), ArrayList.class);
- widgets = ans.getBody();
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "getWidgetCatalog failed", e);
- // returning null because null help check on the UI if there was a
- // communication problem with Microservice.
- return null;
- }
- return widgets;
- }
-
- @RequestMapping(value = {
- "/portalApi/microservices/widgetCatalog/{widgetId}" }, method = RequestMethod.PUT, produces = "application/json")
- public void updateWidgetCatalog(HttpServletRequest request, HttpServletResponse response,
- @RequestBody WidgetCatalog newWidgetCatalog, @PathVariable("widgetId") long widgetId)
- throws RestClientException, Exception {
- template.exchange(
- HTTPS + consulHealthService.getServiceLocation(whatService)
- + "/widget/microservices/widgetCatalog/" + widgetId,
- HttpMethod.PUT, new HttpEntity(newWidgetCatalog, WidgetServiceHeaders.getInstance()), String.class);
- }
-
- @RequestMapping(value = { "/portalApi/microservices/widgetCatalog/{widgetId}" }, method = RequestMethod.DELETE)
- public void deleteOnboardingWidget(HttpServletRequest request, HttpServletResponse response,
- @PathVariable("widgetId") long widgetId) throws RestClientException, Exception {
- template.exchange(
- HTTPS + consulHealthService.getServiceLocation(whatService)
- + "/widget/microservices/widgetCatalog/" + widgetId,
- HttpMethod.DELETE, new HttpEntity(WidgetServiceHeaders.getInstance()), String.class);
- }
-
- @RequestMapping(value = { "/portalApi/microservices/widgetCatalog/{widgetId}" }, method = RequestMethod.POST)
- public String updateWidgetCatalogWithFiles(HttpServletRequest request, HttpServletResponse response,
- @PathVariable("widgetId") long widgetId) throws RestClientException, Exception {
- MultipartHttpServletRequest mRequest;
- MultiValueMap<String, Object> multipartRequest = new LinkedMultiValueMap<>();
- String fileName;
- String tmp_folder = "/tmp/";
- String respond = null;
- FileOutputStream fo = null;
- try {
- mRequest = (MultipartHttpServletRequest) request;
- MultipartFile mFile = mRequest.getFile("file");
- fileName = mFile.getOriginalFilename();
- fo = new FileOutputStream(tmp_folder + fileName);
- fo.write(mFile.getBytes());
-
- HttpHeaders header = new HttpHeaders();
- header.setContentType(MediaType.MULTIPART_FORM_DATA);
- multipartRequest.add("file", new FileSystemResource(tmp_folder + fileName));
- multipartRequest.add("widget", request.getParameter("newWidget"));
- respond = template.postForObject(
- HTTPS + consulHealthService.getServiceLocation(whatService)
- + "/widget/microservices/widgetCatalog/" + widgetId,
- new HttpEntity<>(multipartRequest, WidgetServiceHeaders.getInstance()), String.class);
- File f = new File(tmp_folder + fileName);
- f.delete();
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "updateWidgetCatalogWithFiles failed", e);
- } finally {
- try {
- if (fo != null)
- fo.close();
- } catch (IOException e) {
- logger.error(EELFLoggerDelegate.errorLogger, "updateWidgetCatalogWithFiles failed 2", e);
- }
- }
- return respond;
- }
-
- @RequestMapping(value = { "/portalApi/microservices/widgetCatalog" }, method = RequestMethod.POST)
- public String createWidgetCatalog(HttpServletRequest request, HttpServletResponse response)
- throws RestClientException, Exception {
- MultipartHttpServletRequest mRequest;
- MultiValueMap<String, Object> multipartRequest = new LinkedMultiValueMap<>();
- String fileName;
- String tmp_folder = "/tmp/";
- String respond = null;
- FileOutputStream fo = null;
- try {
- mRequest = (MultipartHttpServletRequest) request;
- MultipartFile mFile = mRequest.getFile("file");
- fileName = mFile.getOriginalFilename();
- fo = new FileOutputStream(tmp_folder + fileName);
- fo.write(mFile.getBytes());
-
- HttpHeaders header = new HttpHeaders();
- header.setContentType(MediaType.MULTIPART_FORM_DATA);
- multipartRequest.add("file", new FileSystemResource(tmp_folder + fileName));
- multipartRequest.add("widget", request.getParameter("newWidget"));
-
- respond = template.postForObject(
- HTTPS + consulHealthService.getServiceLocation(whatService)
- + "/widget/microservices/widgetCatalog",
- new HttpEntity<>(multipartRequest, WidgetServiceHeaders.getInstance()), String.class);
- File f = new File(tmp_folder + fileName);
- f.delete();
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "createWidgetCatalog failed", e);
- } finally {
- try {
- if (fo != null)
- fo.close();
- } catch (IOException e) {
- logger.error(EELFLoggerDelegate.errorLogger, "createWidgetCatalog failed 2", e);
- }
- }
- return respond;
- }
-
- @RequestMapping(value = "/portalApi/microservices/{widgetId}/framework.js", method = RequestMethod.GET)
- public String getWidgetFramework(HttpServletRequest request, HttpServletResponse response,
- @PathVariable("widgetId") long widgetId) throws RestClientException, Exception {
- return template.getForObject(HTTPS + consulHealthService.getServiceLocation(whatService)
- + "/widget/microservices/" + widgetId + "/framework.js", String.class,
- WidgetServiceHeaders.getInstance());
- }
-
- @RequestMapping(value = "/portalApi/microservices/{widgetId}/controller.js", method = RequestMethod.GET)
- public String getWidgetController(HttpServletRequest request, HttpServletResponse response,
- @PathVariable("widgetId") long widgetId) throws RestClientException, Exception {
- return template.getForObject(HTTPS + consulHealthService.getServiceLocation(whatService)
- + "/widget/microservices/" + widgetId + "/controller.js", String.class,
- WidgetServiceHeaders.getInstance());
- }
-
- @RequestMapping(value = "/portalApi/microservices/{widgetId}/style.css", method = RequestMethod.GET)
- public String getWidgetCSS(HttpServletRequest request, HttpServletResponse response,
- @PathVariable("widgetId") long widgetId) throws RestClientException, Exception {
- return template.getForObject(HTTPS + consulHealthService.getServiceLocation(whatService)
- + "/widget/microservices/" + widgetId + "/styles.css", String.class,
- WidgetServiceHeaders.getInstance());
- }
-
- @RequestMapping(value = { "/portalApi/microservices/parameters/{widgetId}" }, method = RequestMethod.GET)
- public PortalRestResponse<List<WidgetParameterResult>> getWidgetParameterResult(HttpServletRequest request,
- HttpServletResponse response, @PathVariable("widgetId") long widgetId) throws Exception {
- EPUser user = EPUserUtils.getUserSession(request);
-
- List<WidgetParameterResult> list = new ArrayList<>();
- Long serviceId = template.exchange(
- HTTPS + consulHealthService.getServiceLocation(whatService)
- + "/widget/microservices/widgetCatalog/parameters/" + widgetId,
- HttpMethod.GET, new HttpEntity(WidgetServiceHeaders.getInstance()), Long.class).getBody();
- if (serviceId == null) {
- // return ok/sucess and no service parameter for this widget
- return new PortalRestResponse<List<WidgetParameterResult>>(PortalRestStatusEnum.WARN,
- "No service parameters for this widget", list);
- } else {
- List<MicroserviceParameter> defaultParam = microserviceService.getParametersById(serviceId);
- for (MicroserviceParameter param : defaultParam) {
- WidgetParameterResult user_result = new WidgetParameterResult();
- user_result.setParam_id(param.getId());
- user_result.setDefault_value(param.getPara_value());
- user_result.setParam_key(param.getPara_key());
- WidgetCatalogParameter userValue = widgetParameterService.getUserParamById(widgetId, user.getId(),
- param.getId());
- if (userValue == null)
- user_result.setUser_value(param.getPara_value());
- else {
- user_result.setUser_value(userValue.getUser_value());
- }
- list.add(user_result);
- }
- }
- return new PortalRestResponse<List<WidgetParameterResult>>(PortalRestStatusEnum.OK, "SUCCESS", list);
- }
-
- @RequestMapping(value = { "/portalApi/microservices/services/{paramId}" }, method = RequestMethod.GET)
- public List<WidgetCatalogParameter> getUserParameterById(HttpServletRequest request, HttpServletResponse response,
- @PathVariable("paramId") long paramId) throws Exception {
- List<WidgetCatalogParameter> list = widgetParameterService.getUserParameterById(paramId);
- return list;
- }
-
- @RequestMapping(value = { "/portalApi/microservices/services/{paramId}" }, method = RequestMethod.DELETE)
- public void deleteUserParameterById(HttpServletRequest request, HttpServletResponse response,
- @PathVariable("paramId") long paramId) throws Exception {
- widgetParameterService.deleteUserParameterById(paramId);
- }
-
- @RequestMapping(value = { "/portalApi/microservices/download/{widgetId}" }, method = RequestMethod.GET)
- public void doDownload(HttpServletRequest request, HttpServletResponse response,
- @PathVariable("widgetId") long widgetId) throws RestClientException, Exception {
-
- ServletContext context = request.getServletContext();
- byte[] byteFile = template.exchange(HTTPS + consulHealthService.getServiceLocation(whatService) + "/widget/microservices/download/" + widgetId,
- HttpMethod.GET, new HttpEntity(WidgetServiceHeaders.getInstance()), byte[].class).getBody();
- String fileLocation = widgetId + ".zip";
- FileOutputStream stream = new FileOutputStream(fileLocation);
- stream.write(byteFile);
- stream.close();
-
- File downloadFile = new File(fileLocation);
- FileInputStream inputStream = new FileInputStream(downloadFile);
- String mimeType = context.getMimeType(downloadFile.getPath());
- if (mimeType == null) {
- mimeType = "application/octet-stream";
- }
-
- response.setContentType(mimeType);
- response.setContentLength((int) downloadFile.length());
- String headerKey = "Content-Disposition";
- String headerValue = String.format("attachment; filename=\"%s\"", downloadFile.getName());
- downloadFile.delete();
- response.setHeader(headerKey, headerValue);
-
- OutputStream outStream = response.getOutputStream();
- byte[] buffer = new byte[32 * 1024];
- int bytesRead = -1;
- while ((bytesRead = inputStream.read(buffer)) != -1) {
- outStream.write(buffer, 0, bytesRead);
- }
-
- inputStream.close();
- outStream.close();
- }
-
- @RequestMapping(value = { "/portalApi/microservices/parameters" }, method = RequestMethod.POST)
- public PortalRestResponse<String> saveWidgetParameter(HttpServletRequest request, HttpServletResponse response,
- @RequestBody WidgetCatalogParameter widgetParameters) throws Exception {
- EPUser user = EPUserUtils.getUserSession(request);
- widgetParameters.setUserId(user.getId());
- try {
- WidgetCatalogParameter oldParam = widgetParameterService.getUserParamById(widgetParameters.getWidgetId(),
- widgetParameters.getUserId(), widgetParameters.getParamId());
- if (oldParam != null) {
- widgetParameters.setId(oldParam.getId());
- }
- widgetParameterService.saveUserParameter(widgetParameters);
-
- } catch (Exception e) {
- return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "FAILURE", e.getMessage());
- }
- return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "SUCCESS", "");
- }
-
-}
+/*-
+ * ================================================================================
+ * ECOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.controller;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.servlet.ServletContext;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.openecomp.portalapp.controller.EPRestrictedBaseController;
+import org.openecomp.portalapp.portal.domain.EPUser;
+import org.openecomp.portalapp.portal.domain.MicroserviceParameter;
+import org.openecomp.portalapp.portal.domain.WidgetCatalog;
+import org.openecomp.portalapp.portal.domain.WidgetCatalogParameter;
+import org.openecomp.portalapp.portal.domain.WidgetParameterResult;
+import org.openecomp.portalapp.portal.domain.WidgetServiceHeaders;
+import org.openecomp.portalapp.portal.ecomp.model.PortalRestResponse;
+import org.openecomp.portalapp.portal.ecomp.model.PortalRestStatusEnum;
+import org.openecomp.portalapp.portal.logging.aop.EPAuditLog;
+import org.openecomp.portalapp.portal.service.ConsulHealthService;
+import org.openecomp.portalapp.portal.service.MicroserviceService;
+import org.openecomp.portalapp.portal.service.WidgetParameterService;
+import org.openecomp.portalapp.util.EPUserUtils;
+import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.openecomp.portalsdk.core.util.SystemProperties;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.EnableAspectJAutoProxy;
+import org.springframework.core.io.FileSystemResource;
+import org.springframework.http.HttpEntity;
+import org.springframework.http.HttpHeaders;
+import org.springframework.http.HttpMethod;
+import org.springframework.http.MediaType;
+import org.springframework.http.ResponseEntity;
+import org.springframework.util.LinkedMultiValueMap;
+import org.springframework.util.MultiValueMap;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.client.RestClientException;
+import org.springframework.web.client.RestTemplate;
+import org.springframework.web.multipart.MultipartFile;
+import org.springframework.web.multipart.MultipartHttpServletRequest;
+import org.springframework.web.multipart.commons.CommonsMultipartResolver;
+
+@SuppressWarnings("unchecked")
+@RestController
+@org.springframework.context.annotation.Configuration
+@EnableAspectJAutoProxy
+@EPAuditLog
+public class WidgetsCatalogController extends EPRestrictedBaseController {
+
+ private static final String HTTPS = "https://";
+
+ EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(WidgetsCatalogController.class);
+ RestTemplate template = new RestTemplate();
+ String whatService = "widgets-service";
+
+ @Autowired
+ private ConsulHealthService consulHealthService;
+
+ @Autowired
+ private MicroserviceService microserviceService;
+
+ @Autowired
+ private WidgetParameterService widgetParameterService;
+
+ @Bean
+ public CommonsMultipartResolver multipartResolver() {
+ return new CommonsMultipartResolver();
+ }
+
+ static {
+ // for localhost testing only
+ javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier(new javax.net.ssl.HostnameVerifier() {
+
+ public boolean verify(String hostname, javax.net.ssl.SSLSession sslSession) {
+ if (hostname.equals("localhost")) {
+ return true;
+ }
+ return false;
+ }
+ });
+ }
+
+ @RequestMapping(value = { "/portalApi/microservices/widgetCatalog/{loginName}" }, method = RequestMethod.GET)
+ public List<WidgetCatalog> getUserWidgetCatalog(HttpServletRequest request, HttpServletResponse response,
+ @PathVariable("loginName") String loginName) throws RestClientException, Exception {
+ List<WidgetCatalog> widgets = new ArrayList<>();
+ try {
+ ResponseEntity<ArrayList> ans = template.exchange(
+ HTTPS + consulHealthService.getServiceLocation(whatService,
+ SystemProperties.getProperty("microservices.widget.local.port"))
+ + "/widget/microservices/widgetCatalog/" + loginName,
+ HttpMethod.GET, new HttpEntity(WidgetServiceHeaders.getInstance()), ArrayList.class);
+ widgets = ans.getBody();
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "getUserWidgetCatalog failed", e);
+ // returning null because null help check on the UI if there was a
+ // communication problem with Microservice.
+ return null;
+ }
+ return widgets;
+ }
+
+ @RequestMapping(value = { "/portalApi/microservices/widgetCatalog" }, method = RequestMethod.GET)
+ public List<WidgetCatalog> getWidgetCatalog(HttpServletRequest request, HttpServletResponse response)
+ throws RestClientException, Exception {
+ List<WidgetCatalog> widgets = new ArrayList<>();
+ try {
+ ResponseEntity<ArrayList> ans = template.exchange(
+ HTTPS + consulHealthService.getServiceLocation(whatService,
+ SystemProperties.getProperty("microservices.widget.local.port"))
+ + "/widget/microservices/widgetCatalog",
+ HttpMethod.GET, new HttpEntity(WidgetServiceHeaders.getInstance()), ArrayList.class);
+ widgets = ans.getBody();
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "getWidgetCatalog failed", e);
+ // returning null because null help check on the UI if there was a
+ // communication problem with Microservice.
+ return null;
+ }
+ return widgets;
+ }
+
+ @RequestMapping(value = {
+ "/portalApi/microservices/widgetCatalog/{widgetId}" }, method = RequestMethod.PUT, produces = "application/json")
+ public void updateWidgetCatalog(HttpServletRequest request, HttpServletResponse response,
+ @RequestBody WidgetCatalog newWidgetCatalog, @PathVariable("widgetId") long widgetId)
+ throws RestClientException, Exception {
+ template.exchange(
+ HTTPS + consulHealthService.getServiceLocation(whatService,
+ SystemProperties.getProperty("microservices.widget.local.port"))
+ + "/widget/microservices/widgetCatalog/" + widgetId,
+ HttpMethod.PUT, new HttpEntity(newWidgetCatalog, WidgetServiceHeaders.getInstance()), String.class);
+ }
+
+ @RequestMapping(value = { "/portalApi/microservices/widgetCatalog/{widgetId}" }, method = RequestMethod.DELETE)
+ public void deleteOnboardingWidget(HttpServletRequest request, HttpServletResponse response,
+ @PathVariable("widgetId") long widgetId) throws RestClientException, Exception {
+ template.exchange(
+ HTTPS + consulHealthService.getServiceLocation(whatService,
+ SystemProperties.getProperty("microservices.widget.local.port"))
+ + "/widget/microservices/widgetCatalog/" + widgetId,
+ HttpMethod.DELETE, new HttpEntity(WidgetServiceHeaders.getInstance()), String.class);
+ }
+
+ @RequestMapping(value = { "/portalApi/microservices/widgetCatalog/{widgetId}" }, method = RequestMethod.POST)
+ public String updateWidgetCatalogWithFiles(HttpServletRequest request, HttpServletResponse response,
+ @PathVariable("widgetId") long widgetId) throws RestClientException, Exception {
+ MultipartHttpServletRequest mRequest;
+ MultiValueMap<String, Object> multipartRequest = new LinkedMultiValueMap<>();
+ String fileName;
+ String tmp_folder = "/tmp/";
+ String respond = null;
+ FileOutputStream fo = null;
+ try {
+ mRequest = (MultipartHttpServletRequest) request;
+ MultipartFile mFile = mRequest.getFile("file");
+ fileName = mFile.getOriginalFilename();
+ fo = new FileOutputStream(tmp_folder + fileName);
+ fo.write(mFile.getBytes());
+
+ HttpHeaders header = new HttpHeaders();
+ header.setContentType(MediaType.MULTIPART_FORM_DATA);
+ multipartRequest.add("file", new FileSystemResource(tmp_folder + fileName));
+ multipartRequest.add("widget", request.getParameter("newWidget"));
+ respond = template.postForObject(
+ HTTPS + consulHealthService.getServiceLocation(whatService,
+ SystemProperties.getProperty("microservices.widget.local.port"))
+ + "/widget/microservices/widgetCatalog/" + widgetId,
+ new HttpEntity<>(multipartRequest, WidgetServiceHeaders.getInstance()), String.class);
+ File f = new File(tmp_folder + fileName);
+ f.delete();
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "updateWidgetCatalogWithFiles failed", e);
+ } finally {
+ try {
+ if (fo != null)
+ fo.close();
+ } catch (IOException e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "updateWidgetCatalogWithFiles failed 2", e);
+ }
+ }
+ return respond;
+ }
+
+ @RequestMapping(value = { "/portalApi/microservices/widgetCatalog" }, method = RequestMethod.POST)
+ public String createWidgetCatalog(HttpServletRequest request, HttpServletResponse response)
+ throws RestClientException, Exception {
+ MultipartHttpServletRequest mRequest;
+ MultiValueMap<String, Object> multipartRequest = new LinkedMultiValueMap<>();
+ String fileName;
+ String tmp_folder = "/tmp/";
+ String respond = null;
+ FileOutputStream fo = null;
+ try {
+ mRequest = (MultipartHttpServletRequest) request;
+ MultipartFile mFile = mRequest.getFile("file");
+ fileName = mFile.getOriginalFilename();
+ fo = new FileOutputStream(tmp_folder + fileName);
+ fo.write(mFile.getBytes());
+
+ HttpHeaders header = new HttpHeaders();
+ header.setContentType(MediaType.MULTIPART_FORM_DATA);
+ multipartRequest.add("file", new FileSystemResource(tmp_folder + fileName));
+ multipartRequest.add("widget", request.getParameter("newWidget"));
+
+ respond = template.postForObject(
+ HTTPS + consulHealthService.getServiceLocation(whatService,
+ SystemProperties.getProperty("microservices.widget.local.port"))
+ + "/widget/microservices/widgetCatalog",
+ new HttpEntity<>(multipartRequest, WidgetServiceHeaders.getInstance()), String.class);
+ File f = new File(tmp_folder + fileName);
+ f.delete();
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "createWidgetCatalog failed", e);
+ } finally {
+ try {
+ if (fo != null)
+ fo.close();
+ } catch (IOException e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "createWidgetCatalog failed 2", e);
+ }
+ }
+ return respond;
+ }
+
+ @RequestMapping(value = "/portalApi/microservices/{widgetId}/framework.js", method = RequestMethod.GET)
+ public String getWidgetFramework(HttpServletRequest request, HttpServletResponse response,
+ @PathVariable("widgetId") long widgetId) throws RestClientException, Exception {
+ return template.getForObject(HTTPS
+ + consulHealthService.getServiceLocation(whatService,
+ SystemProperties.getProperty("microservices.widget.local.port"))
+ + "/widget/microservices/" + widgetId + "/framework.js", String.class,
+ WidgetServiceHeaders.getInstance());
+ }
+
+ @RequestMapping(value = "/portalApi/microservices/{widgetId}/controller.js", method = RequestMethod.GET)
+ public String getWidgetController(HttpServletRequest request, HttpServletResponse response,
+ @PathVariable("widgetId") long widgetId) throws RestClientException, Exception {
+ return template.getForObject(HTTPS
+ + consulHealthService.getServiceLocation(whatService,
+ SystemProperties.getProperty("microservices.widget.local.port"))
+ + "/widget/microservices/" + widgetId + "/controller.js", String.class,
+ WidgetServiceHeaders.getInstance());
+ }
+
+ @RequestMapping(value = "/portalApi/microservices/{widgetId}/style.css", method = RequestMethod.GET)
+ public String getWidgetCSS(HttpServletRequest request, HttpServletResponse response,
+ @PathVariable("widgetId") long widgetId) throws RestClientException, Exception {
+ return template.getForObject(HTTPS
+ + consulHealthService.getServiceLocation(whatService,
+ SystemProperties.getProperty("microservices.widget.local.port"))
+ + "/widget/microservices/" + widgetId + "/styles.css", String.class,
+ WidgetServiceHeaders.getInstance());
+ }
+
+ @RequestMapping(value = { "/portalApi/microservices/parameters/{widgetId}" }, method = RequestMethod.GET)
+ public PortalRestResponse<List<WidgetParameterResult>> getWidgetParameterResult(HttpServletRequest request,
+ HttpServletResponse response, @PathVariable("widgetId") long widgetId) throws Exception {
+ EPUser user = EPUserUtils.getUserSession(request);
+
+ List<WidgetParameterResult> list = new ArrayList<>();
+ Long serviceId = template.exchange(
+ HTTPS + consulHealthService.getServiceLocation(whatService,
+ SystemProperties.getProperty("microservices.widget.local.port"))
+ + "/widget/microservices/widgetCatalog/parameters/" + widgetId,
+ HttpMethod.GET, new HttpEntity(WidgetServiceHeaders.getInstance()), Long.class).getBody();
+ if (serviceId == null) {
+ // return ok/sucess and no service parameter for this widget
+ return new PortalRestResponse<List<WidgetParameterResult>>(PortalRestStatusEnum.WARN,
+ "No service parameters for this widget", list);
+ } else {
+ List<MicroserviceParameter> defaultParam = microserviceService.getParametersById(serviceId);
+ for (MicroserviceParameter param : defaultParam) {
+ WidgetParameterResult user_result = new WidgetParameterResult();
+ user_result.setParam_id(param.getId());
+ user_result.setDefault_value(param.getPara_value());
+ user_result.setParam_key(param.getPara_key());
+ WidgetCatalogParameter userValue = widgetParameterService.getUserParamById(widgetId, user.getId(),
+ param.getId());
+ if (userValue == null)
+ user_result.setUser_value(param.getPara_value());
+ else {
+ user_result.setUser_value(userValue.getUser_value());
+ }
+ list.add(user_result);
+ }
+ }
+ return new PortalRestResponse<List<WidgetParameterResult>>(PortalRestStatusEnum.OK, "SUCCESS", list);
+ }
+
+ @RequestMapping(value = { "/portalApi/microservices/services/{paramId}" }, method = RequestMethod.GET)
+ public List<WidgetCatalogParameter> getUserParameterById(HttpServletRequest request, HttpServletResponse response,
+ @PathVariable("paramId") long paramId) throws Exception {
+ List<WidgetCatalogParameter> list = widgetParameterService.getUserParameterById(paramId);
+ return list;
+ }
+
+ @RequestMapping(value = { "/portalApi/microservices/services/{paramId}" }, method = RequestMethod.DELETE)
+ public void deleteUserParameterById(HttpServletRequest request, HttpServletResponse response,
+ @PathVariable("paramId") long paramId) throws Exception {
+ widgetParameterService.deleteUserParameterById(paramId);
+ }
+
+ @RequestMapping(value = { "/portalApi/microservices/download/{widgetId}" }, method = RequestMethod.GET)
+ public void doDownload(HttpServletRequest request, HttpServletResponse response,
+ @PathVariable("widgetId") long widgetId) throws RestClientException, Exception {
+
+ ServletContext context = request.getServletContext();
+ byte[] byteFile = template.exchange(
+ HTTPS + consulHealthService.getServiceLocation(whatService,
+ SystemProperties.getProperty("microservices.widget.local.port"))
+ + "/widget/microservices/download/" + widgetId,
+ HttpMethod.GET, new HttpEntity(WidgetServiceHeaders.getInstance()), byte[].class).getBody();
+
+ File downloadFile = File.createTempFile("temp", ".zip");
+ FileOutputStream stream = new FileOutputStream(downloadFile.getPath());
+ stream.write(byteFile);
+ stream.close();
+
+ FileInputStream inputStream = new FileInputStream(downloadFile);
+ String mimeType = context.getMimeType(downloadFile.getPath());
+ if (mimeType == null) {
+ mimeType = "application/octet-stream";
+ }
+
+ response.setContentType(mimeType);
+ response.setContentLength((int) downloadFile.length());
+ String headerKey = "Content-Disposition";
+ String headerValue = String.format("attachment; filename=\"%s\"", downloadFile.getName());
+ downloadFile.delete();
+ response.setHeader(headerKey, headerValue);
+
+ OutputStream outStream = response.getOutputStream();
+ byte[] buffer = new byte[32 * 1024];
+ int bytesRead = -1;
+ while ((bytesRead = inputStream.read(buffer)) != -1) {
+ outStream.write(buffer, 0, bytesRead);
+ }
+
+ inputStream.close();
+ outStream.close();
+ }
+
+ @RequestMapping(value = { "/portalApi/microservices/parameters" }, method = RequestMethod.POST)
+ public PortalRestResponse<String> saveWidgetParameter(HttpServletRequest request, HttpServletResponse response,
+ @RequestBody WidgetCatalogParameter widgetParameters) throws Exception {
+ EPUser user = EPUserUtils.getUserSession(request);
+ widgetParameters.setUserId(user.getId());
+ try {
+ WidgetCatalogParameter oldParam = widgetParameterService.getUserParamById(widgetParameters.getWidgetId(),
+ widgetParameters.getUserId(), widgetParameters.getParamId());
+ if (oldParam != null) {
+ widgetParameters.setId(oldParam.getId());
+ }
+ widgetParameterService.saveUserParameter(widgetParameters);
+
+ } catch (Exception e) {
+ return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "FAILURE", e.getMessage());
+ }
+ return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "SUCCESS", "");
+ }
+
+}
diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/WidgetsCatalogMarkupController.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/WidgetsCatalogMarkupController.java
index 78499ef8..b0bc9fc4 100644
--- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/WidgetsCatalogMarkupController.java
+++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/WidgetsCatalogMarkupController.java
@@ -1,83 +1,86 @@
-/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.controller;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.EnableAspectJAutoProxy;
-import org.springframework.web.bind.annotation.PathVariable;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestMethod;
-import org.springframework.web.bind.annotation.RestController;
-import org.springframework.web.client.RestClientException;
-import org.springframework.web.client.RestTemplate;
-import org.springframework.web.multipart.commons.CommonsMultipartResolver;
-
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalapp.controller.EPUnRestrictedBaseController;
-import org.openecomp.portalapp.portal.domain.WidgetServiceHeaders;
-import org.openecomp.portalapp.portal.logging.aop.EPAuditLog;
-import org.openecomp.portalapp.portal.service.ConsulHealthService;
-
-@SuppressWarnings("unchecked")
-@RestController
-@org.springframework.context.annotation.Configuration
-@EnableAspectJAutoProxy
-@EPAuditLog
-public class WidgetsCatalogMarkupController extends EPUnRestrictedBaseController {
-
- EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(WidgetsCatalogMarkupController.class);
- RestTemplate template = new RestTemplate();
- String whatService = "widgets-service";
-
-
- @Autowired
- private ConsulHealthService consulHealthService;
-
- @Bean
- public CommonsMultipartResolver multipartResolver() {
- return new CommonsMultipartResolver();
- }
-
- static {
- //for localhost testing only
- javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier(
- new javax.net.ssl.HostnameVerifier(){
-
- public boolean verify(String hostname,
- javax.net.ssl.SSLSession sslSession) {
- if (hostname.equals("localhost")) {
- return true;
- }
- return false;
- }
- });
- }
-
-
- @RequestMapping(value = "/portalApi/microservices/markup/{widgetId}", method = RequestMethod.GET)
- public String getWidgetMarkup(HttpServletRequest request, HttpServletResponse response,
- @PathVariable("widgetId") long widgetId) throws RestClientException, Exception {
- return template.getForObject("https://" + consulHealthService.getServiceLocation(whatService) + "/widget/microservices/markup/" + widgetId, String.class,
- WidgetServiceHeaders.getInstance());
- }
-}
+/*-
+ * ================================================================================
+ * ECOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.controller;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.openecomp.portalapp.controller.EPUnRestrictedBaseController;
+import org.openecomp.portalapp.portal.domain.WidgetServiceHeaders;
+import org.openecomp.portalapp.portal.logging.aop.EPAuditLog;
+import org.openecomp.portalapp.portal.service.ConsulHealthService;
+import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.openecomp.portalsdk.core.util.SystemProperties;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.EnableAspectJAutoProxy;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.client.RestClientException;
+import org.springframework.web.client.RestTemplate;
+import org.springframework.web.multipart.commons.CommonsMultipartResolver;
+
+@RestController
+@org.springframework.context.annotation.Configuration
+@EnableAspectJAutoProxy
+@EPAuditLog
+public class WidgetsCatalogMarkupController extends EPUnRestrictedBaseController {
+
+ private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(WidgetsCatalogMarkupController.class);
+
+ private RestTemplate template = new RestTemplate();
+
+ private final String whatService = "widgets-service";
+
+ @Autowired
+ private ConsulHealthService consulHealthService;
+
+ @Bean
+ public CommonsMultipartResolver multipartResolver() {
+ return new CommonsMultipartResolver();
+ }
+
+ static {
+ // for localhost testing only
+ javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier(new javax.net.ssl.HostnameVerifier() {
+
+ public boolean verify(String hostname, javax.net.ssl.SSLSession sslSession) {
+ if (hostname.equals("localhost")) {
+ return true;
+ }
+ return false;
+ }
+ });
+ }
+
+ @RequestMapping(value = "/portalApi/microservices/markup/{widgetId}", method = RequestMethod.GET)
+ public String getWidgetMarkup(HttpServletRequest request, HttpServletResponse response,
+ @PathVariable("widgetId") long widgetId) throws RestClientException, Exception {
+ return template
+ .getForObject(
+ "https://"
+ + consulHealthService.getServiceLocation(whatService,
+ SystemProperties.getProperty("microservices.widget.local.port"))
+ + "/widget/microservices/markup/" + widgetId,
+ String.class, WidgetServiceHeaders.getInstance());
+ }
+}