diff options
Diffstat (limited to 'ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal')
21 files changed, 3100 insertions, 0 deletions
diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/controller/AppsOSController.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/controller/AppsOSController.java new file mode 100644 index 00000000..89f9fe58 --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/controller/AppsOSController.java @@ -0,0 +1,116 @@ +/*- + * ================================================================================ + * 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.HashMap; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; + +import org.json.JSONObject; +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.PersUserAppService; +import org.openecomp.portalapp.portal.service.UserService; +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.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 AppsOSController extends AppsController { + + static final String FAILURE = "failure"; + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AppsOSController.class); + + @Autowired + AdminRolesService adminRolesService; + @Autowired + EPAppService appService; + @Autowired + PersUserAppService persUserAppService; + @Autowired + UserService userService; + + + + /** + * Create new application's contact us details. + * + * @param contactUs + * @return + */ + @RequestMapping(value = "/portalApi/saveNewUser", method = RequestMethod.POST, produces = "application/json") + public PortalRestResponse<String> saveNewUser(HttpServletRequest request,@RequestBody EPUser newUser) { + EPUser user = EPUserUtils.getUserSession(request); + if (newUser == null) + return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, FAILURE, + "New User cannot be null or empty"); + + if (!(adminRolesService.isSuperAdmin(user) || adminRolesService.isAccountAdmin(user))){ + if(!user.getLoginId().equalsIgnoreCase(newUser.getLoginId())) + return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, FAILURE, + "UnAuthorized"); + } + + String checkDuplicate = request.getParameter("isCheck"); + String saveNewUser = FAILURE; + try { + saveNewUser = userService.saveNewUser(newUser,checkDuplicate); + } catch (Exception e) { + return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, saveNewUser, e.getMessage()); + } + return new PortalRestResponse<String>(PortalRestStatusEnum.OK, saveNewUser, ""); + } + + @RequestMapping(value = { "/portalApi/currentUserProfile/{loginId}" }, method = RequestMethod.GET, produces = "application/json") + public String getCurrentUserProfile(HttpServletRequest request, @PathVariable("loginId") String loginId) { + + Map<String,String> map = new HashMap<String,String>(); + EPUser user = null; + try { + user = (EPUser) userService.getUserByUserId(loginId).get(0); + map.put("firstName", user.getFirstName()); + map.put("lastName", user.getLastName()); + map.put("email", user.getEmail()); + map.put("loginId", user.getLoginId()); + map.put("loginPwd",user.getLoginPwd()); + map.put("middleInitial",user.getMiddleInitial()); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "Failed to get user info", e); + } + + JSONObject j = new JSONObject(map);; + return j.toString(); + } + +}
\ No newline at end of file diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/controller/DashboardSearchResultController.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/controller/DashboardSearchResultController.java new file mode 100644 index 00000000..fe31066d --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/controller/DashboardSearchResultController.java @@ -0,0 +1,243 @@ +/*- + * ================================================================================ + * 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.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.ecomp.model.PortalRestResponse; +import org.openecomp.portalapp.portal.ecomp.model.PortalRestStatusEnum; +import org.openecomp.portalapp.portal.ecomp.model.SearchResultItem; +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.util.EPUserUtils; +import org.openecomp.portalsdk.core.domain.support.CollaborateList; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.springframework.beans.factory.annotation.Autowired; +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; + +@RestController +@RequestMapping("/portalApi/search") +public class DashboardSearchResultController extends EPRestrictedBaseController { + + private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(DashboardSearchResultController.class); + + @Autowired + private DashboardSearchService searchService; + + /** + * Gets all widgets by type: NEW or RESOURCE + * + * @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) { + return new PortalRestResponse<CommonWidgetMeta>(PortalRestStatusEnum.OK, "success", + searchService.getWidgetData(resourceType)); + } + + /** + * Saves all: news and 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"); + // 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: 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", + "Cateogry 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) { + try { + if (cw.getEventDate() != null && cw.getEventDate().trim().length() > 0) + yearMonthDayFormat.parse(cw.getEventDate()); + } catch (ParseException ex) { + return ex.toString(); + } + return null; + } + + /** + * Deletes one: 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. + */ + @RequestMapping(value = "/allPortal", method = RequestMethod.GET, produces = "application/json") + public PortalRestResponse<Map<String, List<SearchResultItem>>> searchPortal(HttpServletRequest request, + @RequestParam String searchString) { + + 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.trim().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); + 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 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-os/src/main/java/org/openecomp/portalapp/portal/controller/ExternalAppsRestfulController.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/controller/ExternalAppsRestfulController.java new file mode 100644 index 00000000..1d6b59ef --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/controller/ExternalAppsRestfulController.java @@ -0,0 +1,129 @@ +/*- + * ================================================================================ + * 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.List; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.openecomp.portalapp.controller.EPRestrictedRESTfulBaseController; +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.FunctionalMenuService; +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.EPSystemProperties; +import org.openecomp.portalapp.portal.utils.EcompPortalUtils; +import org.openecomp.portalapp.portal.utils.PortalConstants; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.slf4j.MDC; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping(PortalConstants.REST_AUX_API) +@org.springframework.context.annotation.Configuration +@EnableAspectJAutoProxy +@EPAuditLog +public class ExternalAppsRestfulController extends EPRestrictedRESTfulBaseController { + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ExternalAppsRestfulController.class); + + @Autowired + FunctionalMenuService functionalMenuService; + + @Autowired + EPLoginService epLoginService; + + @Autowired + AdminRolesService adminRolesService; + + @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(EPSystemProperties.MDC_LOGIN_ID); + userAgent = MDC.get(EPSystemProperties.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("/auxapi/getFavorites", "result = ", favorites); + } + + return favorites; + } + + @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(EPSystemProperties.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("/auxapi/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-os/src/main/java/org/openecomp/portalapp/portal/controller/PortalAdminController.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/controller/PortalAdminController.java new file mode 100644 index 00000000..76a9b40f --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/controller/PortalAdminController.java @@ -0,0 +1,117 @@ +/*- + * ================================================================================ + * 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.EPUser; +import org.openecomp.portalapp.portal.logging.aop.EPAuditLog; +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.EcompPortalUtils; +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.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 PortalAdminController extends EPRestrictedBaseController { + @Autowired + PortalAdminService portalAdminService; + @Autowired + AdminRolesService adminRolesService; + + 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("/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); + response.setStatus(fieldsValidator.httpStatusCode.intValue()); + } + EcompPortalUtils.logAndSerializeObject("/portalAdmin", "POST result =", response.getStatus()); + + return fieldsValidator; + } + + @RequestMapping(value = { "/portalApi/portalAdmin/{orgUserId}" }, method = RequestMethod.DELETE) + public FieldsValidator deletePortalAdmin(HttpServletRequest request, @PathVariable("orgUserId") Long orgUserId, + HttpServletResponse response) { + EPUser user = EPUserUtils.getUserSession(request); + FieldsValidator fieldsValidator = null; + if (!adminRolesService.isSuperAdmin(user)) { + EcompPortalUtils.setBadPermissions(user, response, "deletePortalAdmin"); + } else { + fieldsValidator = portalAdminService.deletePortalAdmin(orgUserId); + response.setStatus(fieldsValidator.httpStatusCode.intValue()); + } + EcompPortalUtils.logAndSerializeObject("/portalAdmin", "DELETE result =", response.getStatus()); + + return fieldsValidator; + } +} diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/interceptor/SessionTimeoutInterceptor.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/interceptor/SessionTimeoutInterceptor.java new file mode 100644 index 00000000..dc18f1ff --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/interceptor/SessionTimeoutInterceptor.java @@ -0,0 +1,101 @@ +/*- + * ================================================================================ + * 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.interceptor; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.openecomp.portalapp.authentication.LoginStrategy; +import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalapp.portal.utils.EcompPortalUtils; +import org.openecomp.portalapp.util.EPUserUtils; +import org.openecomp.portalapp.util.SessionCookieUtil; +import org.openecomp.portalsdk.core.controller.FusionBaseController; +import org.openecomp.portalsdk.core.domain.support.CollaborateList; +import org.openecomp.portalsdk.core.exception.SessionExpiredException; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.method.HandlerMethod; +import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; + +public class SessionTimeoutInterceptor extends HandlerInterceptorAdapter { + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SessionTimeoutInterceptor.class); + + @Autowired + private LoginStrategy loginStrategy; + + public SessionTimeoutInterceptor() { + } + + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) + throws Exception { + + if (!isHandlerMethod(handler)) + return false; + + HandlerMethod method = (HandlerMethod) handler; + + if (!isFusionController(method.getBean())) + return false; + + if (method.getBean() instanceof FusionBaseController) { + FusionBaseController controller = (FusionBaseController) method.getBean(); + + if (!controller.isAccessible()) { + try { + EPUser user = EPUserUtils.getUserSession(request); + + if (request.getRequestURI().indexOf("logout.htm") > -1) { + CollaborateList.delUserName(user.getOrgUserId()); + throw new SessionExpiredException(); + } else { + resetSessionMaxIdleTimeOut(request); + CollaborateList.addUserName(user.getOrgUserId()); + } + } catch (Exception see) { + logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(see)); + // return loginStrategy.login(request, response); + return false; + } + + } + + } + + return true; + } + + private void resetSessionMaxIdleTimeOut(HttpServletRequest request) { + SessionCookieUtil.resetSessionMaxIdleTimeOut(request); + + } + + private boolean isFusionController(Object controller) { + if (controller instanceof FusionBaseController) + return true; + return false; + } + + private boolean isHandlerMethod(Object controller) { + if (controller instanceof HandlerMethod) + return true; + return false; + } +}
\ No newline at end of file diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/logging/aop/EPEELFLoggerAspect.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/logging/aop/EPEELFLoggerAspect.java new file mode 100644 index 00000000..974272d0 --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/logging/aop/EPEELFLoggerAspect.java @@ -0,0 +1,204 @@ +/*- + * ================================================================================ + * 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.logging.aop; + +import org.aspectj.lang.ProceedingJoinPoint; +import org.aspectj.lang.annotation.Around; +import org.aspectj.lang.annotation.Aspect; +import org.aspectj.lang.annotation.Pointcut; +import org.openecomp.portalapp.portal.transport.FieldsValidator; +import org.openecomp.portalapp.portal.utils.EcompPortalUtils; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.util.SystemProperties.SecurityEventTypeEnum; +import org.springframework.beans.factory.annotation.Autowired; + +@Aspect +@org.springframework.context.annotation.Configuration +public class EPEELFLoggerAspect { + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(EPEELFLoggerAspect.class); + + @Autowired + EPEELFLoggerAdvice epAdvice; + + /* + * Point-cut expression to handle all INCOMING_REST_MESSAGES + */ + @Pointcut("execution(public * org.openecomp.portalapp.portal.controller.*.*(..))") + public void incomingAuditMessages() {} + + /* + * Handles all INCOMING_REST_MESSAGES from kpiDashboard + */ + @Pointcut("execution(public * org.openecomp.portalapp.kpidash.controller.*.*(..))") + public void kpiDashboardAuditMessages() {} + + /* + * Point-cut expression to handle all session management INCOMING_REST_MESSAGES + */ + @Pointcut("execution(public * org.openecomp.portalapp.controller.sessionmgt.*.*(..))") + public void sessionMgtIncomingAuditMessages() {} + + /* + * Point-cut expression to handle UserProfileController INCOMING_REST_MESSAGES + */ + @Pointcut("execution(public * org.openecomp.portalapp.controller.core.UserProfileController.*(..))") + public void userProfileIncomingAuditMessages() {} + + /* + * Point-cut expression to handle UserProfileController INCOMING_REST_MESSAGES + */ + @Pointcut("execution(public * org.openecomp.portalapp.controller.ONAPWelcomeController.*(..))") + public void welcomeIncomingAuditMessages() {} + + /* + * Point-cut expression to handle INCOMING Logout Rest Messages + */ + @Pointcut("execution(public * org.openecomp.portalapp.controller.ECOMPLogoutController.*(..))") + public void logoutAuditMessages() {} + + + /* + * Point-cut expression which handles all the OUTGOING_REST_MESSAGES. + */ + @Pointcut("execution(public * org.openecomp.portalapp.portal.service.ApplicationsRestClientServiceImpl.*(..))") + public void outgoingAuditMessages() {} + + /* + * Point-cut expression to handle all the session management OUTGOING_REST_MESSAGES. + */ + @Pointcut("execution(public * org.openecomp.portalapp.service.sessionmgt.SessionCommunication.*(..))") + public void sessionMgtOutgoingAuditMessages() {} + + /* + * Point-cut expression which handles all the LDAP_PHONEBOOK_USER_SEARCH calls. + */ + @Pointcut("execution(public * org.openecomp.portalapp.portal.service.EPLdapServiceImpl.*(..))") + public void phoneBookSearchAuditMessages() {} + + /* + * Handles Audit, Metrics & Debug logging for the point-cut + * expression defined at class-level + */ + @Around("(incomingAuditMessages() || kpiDashboardAuditMessages() || sessionMgtIncomingAuditMessages() || " + + "userProfileIncomingAuditMessages() || welcomeIncomingAuditMessages()) && @within(epAuditLog)") + public Object incomingAuditMessagesAroundClass(ProceedingJoinPoint joinPoint, EPAuditLog epAuditLog) throws Throwable { + return this.logAroundMethod(joinPoint, SecurityEventTypeEnum.INCOMING_REST_MESSAGE); + } + + /* + * Handles Audit, Metrics & Debug logging for the point-cut + * expression defined at class-level + */ + @Around("(outgoingAuditMessages() || sessionMgtOutgoingAuditMessages()) && @within(epAuditLog)") + public Object outgoingAuditMessagesAroundClass(ProceedingJoinPoint joinPoint, EPAuditLog epAuditLog) throws Throwable { + return this.logAroundMethod(joinPoint, SecurityEventTypeEnum.OUTGOING_REST_MESSAGE); + } + + + /* + * Handles Audit, Metrics & Debug logging for the point-cut + * expression defined at method-level + */ + @Around("(outgoingAuditMessages() || sessionMgtOutgoingAuditMessages()) && @annotation(epAuditLog)") + public Object outgoingAuditMessagesAroundMethod(ProceedingJoinPoint joinPoint, EPAuditLog epAuditLog) throws Throwable { + return this.logAroundMethod(joinPoint, SecurityEventTypeEnum.OUTGOING_REST_MESSAGE); + } + + /* + * Handles Audit, Metrics & Debug logging for the point-cut + * expression defined at method-level + */ + @Around("(incomingAuditMessages() || kpiDashboardAuditMessages() || sessionMgtIncomingAuditMessages() ||" + + "userProfileIncomingAuditMessages() || welcomeIncomingAuditMessages()) && @annotation(epAuditLog)") + public Object incomingAuditMessagesAroundMethod(ProceedingJoinPoint joinPoint, EPAuditLog epAuditLog) throws Throwable { + return this.logAroundMethod(joinPoint, SecurityEventTypeEnum.INCOMING_REST_MESSAGE); + } + + @Around("@annotation(epAuditLog)") + public Object loginAuditMessagesAroundMethod(ProceedingJoinPoint joinPoint, EPAuditLog epAuditLog) throws Throwable { + return this.logAroundMethod(joinPoint, SecurityEventTypeEnum.FE_LOGIN_ATTEMPT); + } + + @Around("logoutAuditMessages() && @annotation(epAuditLog)") + public Object logoutAuditMessagesAroundMethod(ProceedingJoinPoint joinPoint, EPAuditLog epAuditLog) throws Throwable { + return this.logAroundMethod(joinPoint, SecurityEventTypeEnum.FE_LOGOUT); + } + + @Around("phoneBookSearchAuditMessages() && @annotation(epAuditLog)") + public Object phonebookSearchAuditMessagesAroundMethod(ProceedingJoinPoint joinPoint, EPAuditLog epAuditLog) throws Throwable { + return this.logAroundMethod(joinPoint, SecurityEventTypeEnum.LDAP_PHONEBOOK_USER_SEARCH); + } + + private Object logAroundMethod(ProceedingJoinPoint joinPoint, SecurityEventTypeEnum securityEventType) throws Throwable { + //Before + Object[] passOnArgs = new Object[] {joinPoint.getSignature().getDeclaringType().getName(), joinPoint.getSignature().getName()}; + Object[] returnArgs = epAdvice.before(securityEventType, joinPoint.getArgs(), passOnArgs); + + //Call the actual method + Object result = null; + String statusCode = "COMPLETE"; + String responseCode = "200"; + try { + result = joinPoint.proceed(); + } catch(Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e)); + statusCode = "ERROR"; + responseCode = "500"; //Internal server error + } + + //Check the result + if (securityEventType!=null) { + if (result==null) { + statusCode = "ERROR"; + //Check if there is an internal response code + //and use it if the caller function has configured it. + responseCode = epAdvice.getInternalResponseCode(); + if (responseCode==null||responseCode=="") { + responseCode = "500"; //Internal server error + } + } else if (result instanceof FieldsValidator) { + FieldsValidator fieldsValidator = (FieldsValidator) result; + if (fieldsValidator!=null && fieldsValidator.httpStatusCode!=null) { + responseCode = fieldsValidator.httpStatusCode.toString(); + } + } + } + + //After + epAdvice.after(securityEventType, statusCode, responseCode, joinPoint.getArgs(), returnArgs, passOnArgs); + + return result; + } + + //Metrics Logging + @Pointcut("execution(* *(..))") + public void performMetricsLogging() {} + + @Around("performMetricsLogging() && @within(epMetricsLog)") + public Object metricsLoggingAroundClass(ProceedingJoinPoint joinPoint, EPMetricsLog epMetricsLog) throws Throwable { + return this.logAroundMethod(joinPoint, null); + } + + @Around("performMetricsLogging() && @annotation(epMetricsLog)") + public Object metricsLoggingAroundMethod(ProceedingJoinPoint joinPoint, EPMetricsLog epMetricsLog) throws Throwable { + return this.logAroundMethod(joinPoint, null); + } +} diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/ApplicationsRestClientService.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/ApplicationsRestClientService.java new file mode 100644 index 00000000..71542268 --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/ApplicationsRestClientService.java @@ -0,0 +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.service; + +import org.apache.cxf.transport.http.HTTPException; + +public interface ApplicationsRestClientService { + public <T> T get(Class<T> clazz, long app, String restPath) throws HTTPException; + public <T> T post(Class<T> clazz, long appId, Object payload, String restPath) throws HTTPException ; + public <T> T put(Class<T> clazz, long appId, Object payload, String restPath) throws HTTPException ; +} diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/ApplicationsRestClientServiceImpl.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/ApplicationsRestClientServiceImpl.java new file mode 100644 index 00000000..4626b17b --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/ApplicationsRestClientServiceImpl.java @@ -0,0 +1,267 @@ +/*- + * ================================================================================ + * 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.service; + +import static com.att.eelf.configuration.Configuration.MDC_KEY_REQUEST_ID; + +import java.lang.reflect.Type; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.Date; + +import javax.annotation.PostConstruct; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +import org.apache.cxf.jaxrs.client.WebClient; +import org.apache.cxf.transport.http.HTTPException; +import org.openecomp.portalapp.portal.domain.EPApp; +import org.openecomp.portalapp.portal.logging.aop.EPAuditLog; +import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog; +import org.openecomp.portalapp.portal.logging.format.EPAppMessagesEnum; +import org.openecomp.portalapp.portal.logging.logic.EPLogUtil; +import org.openecomp.portalapp.portal.utils.EPSystemProperties; +import org.openecomp.portalapp.portal.utils.EcompPortalUtils; +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.slf4j.MDC; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.stereotype.Service; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonParseException; + +@Service("applicationsRestClientService") +@org.springframework.context.annotation.Configuration +@EnableAspectJAutoProxy +@EPAuditLog +public class ApplicationsRestClientServiceImpl implements ApplicationsRestClientService{ + + private static final String PASSWORD_HEADER = "password"; + + private static final String APP_USERNAME_HEADER = "username"; + + private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ApplicationsRestClientServiceImpl.class); + + @Autowired + private AppsCacheService appsCacheService; + Gson gson = null; + + @PostConstruct + private void init(){ + logger.debug(EELFLoggerDelegate.debugLogger, "initializing"); + GsonBuilder builder = new GsonBuilder(); + + // Register an adapter to manage the date types as long values + builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() { + public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { + return new Date(json.getAsJsonPrimitive().getAsLong()); + } + }); + + gson = builder.create(); + } + + // TODO: do we need to do additional logging for remote API calls? + private static WebClient createClientForPath(String baseUri, String path) { + logger.info(EELFLoggerDelegate.debugLogger, "Creating web client for " + baseUri + " + " + path); + WebClient client = WebClient.create(baseUri); + client.type(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON); + client.path(path); + return client; + } + + @EPMetricsLog + private void verifyResponse(Response response) throws HTTPException { + int status = response.getStatus(); + logger.debug(EELFLoggerDelegate.debugLogger, "http response status=" + status); + MDC.put(EPSystemProperties.EXTERNAL_API_RESPONSE_CODE, Integer.toString(status)); + if (!isHttpSuccess(status)) { + String errMsg = "Failed. Status=" + status + "; [" + response.getStatusInfo().getReasonPhrase().toString() + "]"; + URL url = null; + try { + // must not be null to avoid NPE in HTTPException constructor + url = new URL("http://null"); + if (response.getLocation() != null) + url = response.getLocation().toURL(); + } catch (MalformedURLException e) { + // never mind. it is only for the debug message. + logger.warn(EELFLoggerDelegate.errorLogger, "Failed to build URL", e); + } + logger.error(EELFLoggerDelegate.errorLogger, "http response failed. " + errMsg + "; url=" + url); + EPLogUtil.logEcompError(EPAppMessagesEnum.BeIncorrectHttpStatusError); + throw new HTTPException(status, errMsg, url); + } + } + + private static boolean isHttpSuccess(int status){ + return status / 100 == 2; + } + + @EPMetricsLog + private WebClient createClientForApp(long appId, String restPath) { + logger.debug(EELFLoggerDelegate.debugLogger, "creating client for appId=" + appId + "; restPath=" + restPath); + EPApp externalApp = appsCacheService.getApp(appId); + if(externalApp != null){ + String appBaseUri = externalApp.getAppRestEndpoint(); + String username = externalApp.getUsername(); + String encriptedPwd = externalApp.getAppPassword(); + String decreptedAppPwd = ""; + + //Set local context + MDC.put(EPSystemProperties.PROTOCOL, EPSystemProperties.HTTP); + if (appBaseUri!=null && appBaseUri.contains("https")) { + MDC.put(EPSystemProperties.PROTOCOL, EPSystemProperties.HTTPS); + } + MDC.put(EPSystemProperties.FULL_URL, appBaseUri + restPath); + MDC.put(EPSystemProperties.TARGET_ENTITY, externalApp.getName()); + MDC.put(EPSystemProperties.TARGET_SERVICE_NAME, restPath); + + try { + decreptedAppPwd = CipherUtil.decrypt(encriptedPwd, SystemProperties.getProperty(SystemProperties.Decryption_Key)); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "Unable to decrypt App name = " + externalApp, EcompPortalUtils.getStackTrace(e)); + logger.error(EELFLoggerDelegate.errorLogger, "Unable to decrypt App name = " + externalApp, EcompPortalUtils.getStackTrace(e)); + } + logger.debug(EELFLoggerDelegate.debugLogger, String.format("App %d found, baseUri=[%s], Headers: [%s=%s, %s=%s]", appId, appBaseUri, APP_USERNAME_HEADER, username, PASSWORD_HEADER, encriptedPwd)); + WebClient client = createClientForPath(appBaseUri, restPath); + client.header(APP_USERNAME_HEADER, username); + client.header(PASSWORD_HEADER, decreptedAppPwd); + client.header(SystemProperties.ECOMP_REQUEST_ID, MDC.get(MDC_KEY_REQUEST_ID)); + client.header(SystemProperties.USERAGENT_NAME, EPSystemProperties.ECOMP_PORTAL_BE); + + return client; + } + return null; + } + + @Override + public <T> T get(Class<T> clazz, long appId, String restPath) throws HTTPException { + + WebClient webClient = null; + Response response = null; + T t = null; + + webClient = createClientForApp(appId, restPath); + EcompPortalUtils.logAndSerializeObject(restPath, "GET request =", "no-payload"); + + try { + if (webClient!=null) { + response = webClient.get(); + } else { + logger.error(EELFLoggerDelegate.errorLogger, "Unable to create the Webclient to make the '" + restPath + "' API call."); + } + } catch (Exception e) { + MDC.put(EPSystemProperties.EXTERNAL_API_RESPONSE_CODE, Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR)); + EPLogUtil.logEcompError(EPAppMessagesEnum.BeRestApiGeneralError); + logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while making the GET REST API call, Details: " + EcompPortalUtils.getStackTrace(e)); + } + + if (response!=null) { + verifyResponse(response); + String str = response.readEntity(String.class); + EcompPortalUtils.logAndSerializeObject(restPath, "GET result =", str); + try { t = gson.fromJson(str, clazz); } catch(Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e)); + EPLogUtil.logEcompError(EPAppMessagesEnum.BeInvalidJsonInput); + } + } + + return t; + } + + @Override + public <T> T post(Class<T> clazz, long appId, Object payload, String restPath) throws HTTPException { + WebClient client = null; + Response response = null; + T t = null; + + client = createClientForApp(appId, restPath); + EcompPortalUtils.logAndSerializeObject(restPath, "POST request =", payload); + + + try { + if (client!=null) { + response = client.post(payload); + } else { + logger.error(EELFLoggerDelegate.errorLogger, "Unable to create the Webclient to make the '" + restPath + "' API call."); + } + } catch (Exception e) { + MDC.put(EPSystemProperties.EXTERNAL_API_RESPONSE_CODE, Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR)); + EPLogUtil.logEcompError(EPAppMessagesEnum.BeRestApiGeneralError); + logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while making the POST REST API call, Details: " + EcompPortalUtils.getStackTrace(e)); + } + + if (response!=null) { + verifyResponse(response); + + //String contentType = response.getHeaderString("Content-Type"); + if(clazz != null) { + String str = response.readEntity(String.class); + EcompPortalUtils.logAndSerializeObject(restPath, "POST result =", str); + try { t = gson.fromJson(str, clazz); } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e)); + EPLogUtil.logEcompError(EPAppMessagesEnum.BeInvalidJsonInput); + } + } + } + return t; + } + + @Override + public <T> T put(Class<T> clazz, long appId, Object payload, String restPath) throws HTTPException { + WebClient client = null; + Response response = null; + T t = null; + + client = createClientForApp(appId, restPath); + EcompPortalUtils.logAndSerializeObject(restPath, "PUT request =", payload); + + try { + if (client!=null) { + response = client.put(payload); + } else { + logger.error(EELFLoggerDelegate.errorLogger, "Unable to create the Webclient to make the '" + restPath + "' API call."); + } + } catch(Exception e) { + MDC.put(EPSystemProperties.EXTERNAL_API_RESPONSE_CODE, Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR)); + EPLogUtil.logEcompError(EPAppMessagesEnum.BeRestApiGeneralError); + logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while making the PUT REST API call, Details: " + EcompPortalUtils.getStackTrace(e)); + } + + if (response!=null) { + verifyResponse(response); + String str = response.readEntity(String.class); + EcompPortalUtils.logAndSerializeObject(restPath, "PUT result =", str); + try { t = gson.fromJson(str, clazz); } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e)); + EPLogUtil.logEcompError(EPAppMessagesEnum.BeInvalidJsonInput); + } + } + return t; + } +} diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/AppsCacheService.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/AppsCacheService.java new file mode 100644 index 00000000..20939a9a --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/AppsCacheService.java @@ -0,0 +1,40 @@ +/*- + * ================================================================================ + * 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.service; + +import org.openecomp.portalapp.portal.domain.EPApp; + +public interface AppsCacheService { + + /** + * returns an app by id from the cache + * @param appId + * @return corresponding App + */ + EPApp getApp(Long appId); + + /** + * returns the corresponding application endpoint + * @param appId + * @return if appId exists in cache, then return corresponding application endpoint, null otherwise. + */ + String getAppEndpoint(Long appId); +} diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/AppsCacheServiceImple.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/AppsCacheServiceImple.java new file mode 100644 index 00000000..683017b1 --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/AppsCacheServiceImple.java @@ -0,0 +1,104 @@ +/*- + * ================================================================================ + * 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.service; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.annotation.PostConstruct; + +import org.openecomp.portalapp.portal.domain.EPApp; +import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.stereotype.Service; + +@Service("appsCacheService") +@org.springframework.context.annotation.Configuration +@EnableAspectJAutoProxy +@EPMetricsLog +public class AppsCacheServiceImple implements AppsCacheService { + @Autowired + EPAppService appsService; + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AppsCacheServiceImple.class); + + private static long updateTime = 0; + private static final int cacheUpdateIntervalInSeconds = 10; + + private static volatile Map<Long, EPApp> appsMap; + + @PostConstruct + public void init() { + this.refreshAppsMap(); + } + + private Map<Long, EPApp> refreshAppsMap() { + long now = System.currentTimeMillis(); + + if(noNeedToUpdate(now)) + return null; + + synchronized (this) { + if(noNeedToUpdate(now)) + return null; + List<EPApp> allApps = appsService.getAppsFullList(); + Map<Long, EPApp> newAppsMap = new HashMap<Long, EPApp>(); + for (EPApp app : allApps) { + newAppsMap.put(app.getId(), app); + } + // Switch cache with the new one. + appsMap = newAppsMap; + updateTime = now; + } + + return appsMap; + } + + private boolean noNeedToUpdate(long now) { + long secondsPassed = (now - updateTime)/1000; + if(secondsPassed < cacheUpdateIntervalInSeconds){ + logger.debug(EELFLoggerDelegate.debugLogger, "no need to refresh yet, seconds since last refresh: " + secondsPassed + ", refresh interval (sec) = " + cacheUpdateIntervalInSeconds); + return true; // no need to update cache + } + return false; // its time to update + } + + @Override + public String getAppEndpoint(Long appId) { + refreshAppsMap(); + EPApp app = appsMap.get(appId); + if(app != null) + return app.getAppRestEndpoint(); + return null; + } + + @Override + public EPApp getApp(Long appId) { + refreshAppsMap(); + EPApp app = appsMap.get(appId); + if(app != null) + return app; + return null; + } + +} diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/EPAppServiceImpl.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/EPAppServiceImpl.java new file mode 100644 index 00000000..074821f6 --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/EPAppServiceImpl.java @@ -0,0 +1,71 @@ +/*- + * ================================================================================ + * 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.service; + + +import java.util.ArrayList; +import java.util.List; +import java.util.TreeSet; + +import org.openecomp.portalapp.portal.domain.EPApp; +import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.service.DataAccessService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service("epAppService") +@Transactional +@org.springframework.context.annotation.Configuration +@EnableAspectJAutoProxy +@EPMetricsLog +public class EPAppServiceImpl extends EPAppCommonServiceImpl implements EPAppService { + + private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(EPAppServiceImpl.class); + + @Autowired + private DataAccessService dataAccessService; + + @Override + public List<EPApp> getUserRemoteApps(String id) { + + StringBuilder query = new StringBuilder(); + + query.append("SELECT * FROM FN_APP join FN_USER_ROLE ON FN_USER_ROLE.APP_ID = FN_APP.APP_ID where "); + query.append( + "FN_USER_ROLE.USER_ID = " + id + " AND FN_USER_ROLE.ROLE_ID != " + SUPER_ADMIN_ROLE_ID); + query.append(" AND FN_APP.ENABLED = 'Y'"); + + TreeSet<EPApp> distinctApps = new TreeSet<EPApp>(); + + @SuppressWarnings("unchecked") + List<EPApp> adminApps = dataAccessService.executeSQLQuery(query.toString(), EPApp.class, null); + for (EPApp app : adminApps) { + distinctApps.add(app); + } + + List<EPApp> userApps = new ArrayList<EPApp>(); + userApps.addAll(distinctApps); + return userApps; + + } +}
\ No newline at end of file diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/SearchService.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/SearchService.java new file mode 100644 index 00000000..94937dc4 --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/SearchService.java @@ -0,0 +1,40 @@ +/*- + * ================================================================================ + * 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.service; + +import java.util.List; + +import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalapp.portal.transport.UserWithNameSurnameTitle; + +public interface SearchService { + + + public String searchUsersInPhoneBook(String searchString); + + public String searchUsersInFnTable(String searchString); + + public List<UserWithNameSurnameTitle> searchUsersByName(EPUser attrUser); + + public List<UserWithNameSurnameTitle> searchUsersByUserId(EPUser attrUser); + + public EPUser searchUserByUserId(String orgUserId); + +} diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/SearchServiceImpl.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/SearchServiceImpl.java new file mode 100644 index 00000000..35fc00bd --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/SearchServiceImpl.java @@ -0,0 +1,192 @@ +/*- + * ================================================================================ + * 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.service; + +import java.util.ArrayList; +import java.util.List; + +import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog; +import org.openecomp.portalapp.portal.transport.UserWithNameSurnameTitle; +import org.openecomp.portalapp.portal.utils.EcompPortalUtils; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +@Service("searchService") +@Transactional +@org.springframework.context.annotation.Configuration +@EnableAspectJAutoProxy +@EPMetricsLog +public class SearchServiceImpl implements SearchService { + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SearchServiceImpl.class); + + // TODO: the values below should be defined in other place + private static final int maxSizeOfSearchResult = 100; + + @Autowired + UserService userService; + + @Override + public String searchUsersInPhoneBook(String searchString) { + return searchUsersInFnTable(searchString); + } + + @Override + public String searchUsersInFnTable(String searchString) { + String orgUserId = null; + List<String> tokens = EcompPortalUtils.parsingByRegularExpression(searchString, " "); + for (int i = 0; i < tokens.size(); i++) { // find userid if possible and remove it from tokens + if (tokens.get(i).matches(".*\\d+.*")) { + orgUserId = tokens.get(i); + tokens.remove(i); + } + } + while (tokens.size() > 2) { // we use no more then first 2 tokens (userId is removed, see above) + tokens.remove(tokens.size() - 1); + } + EPUser attrUser = new EPUser(); + attrUser.setOrgUserId(orgUserId); + List<UserWithNameSurnameTitle> resultOfSearch = new ArrayList<UserWithNameSurnameTitle>(), resultOfAdditionalSearch = null; + if (tokens.size() == 2) { + attrUser.setFirstName(tokens.get(0)); + attrUser.setLastName(tokens.get(1)); + resultOfSearch = this.searchUsersByName(attrUser); + resultOfSearch = this.removeWrongFirstNames(resultOfSearch, tokens.get(0)); + resultOfSearch = this.removeWrongLastNames(resultOfSearch, tokens.get(1)); + if (resultOfSearch.size() < maxSizeOfSearchResult) { + attrUser.setFirstName(tokens.get(1)); + attrUser.setLastName(tokens.get(0)); + resultOfAdditionalSearch = this.searchUsersByName(attrUser); + resultOfAdditionalSearch = this.removeWrongFirstNames(resultOfAdditionalSearch, tokens.get(1)); + resultOfAdditionalSearch = this.removeWrongLastNames(resultOfAdditionalSearch, tokens.get(0)); + } + } else if (tokens.size() == 1) { + attrUser.setFirstName(tokens.get(0)); + resultOfSearch = this.searchUsersByName(attrUser); + resultOfSearch = this.removeWrongFirstNames(resultOfSearch, tokens.get(0)); + if (resultOfSearch.size() < maxSizeOfSearchResult) { + attrUser.setFirstName(null); + attrUser.setLastName(tokens.get(0)); + resultOfAdditionalSearch = this.searchUsersByName(attrUser); + resultOfAdditionalSearch = this.removeWrongLastNames(resultOfAdditionalSearch, tokens.get(0)); + } + } else if (orgUserId != null) { + resultOfSearch = this.searchUsersByUserId(attrUser); + } + if (resultOfAdditionalSearch != null) { + resultOfSearch.addAll(resultOfAdditionalSearch); + } + resultOfSearch = this.cutSearchResultToMaximumSize(resultOfSearch); + ObjectMapper mapper = new ObjectMapper(); + String result = "[]"; + try { + result = mapper.writeValueAsString(resultOfSearch); + } catch (JsonProcessingException e) { + logger.error(EELFLoggerDelegate.errorLogger, "searchUsersInPhoneBook Exception = " + EcompPortalUtils.getStackTrace(e)); + } + return result; + } + + + @SuppressWarnings("rawtypes") + public List<UserWithNameSurnameTitle> searchUsersByUserId(EPUser attrUser) { + List<UserWithNameSurnameTitle> foundUsers = new ArrayList<UserWithNameSurnameTitle>(); + try { + List searchResult = this.userService.getUserByUserId(attrUser.getOrgUserId()); + for (Object obj : searchResult) { + EPUser user = (EPUser) obj; + UserWithNameSurnameTitle foundUser = new UserWithNameSurnameTitle(user.getOrgUserId(), user.getFirstName(), user.getLastName(), user.getJobTitle()); + foundUsers.add(foundUser); + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "searchInPhoneBookWithToken Exception = " + EcompPortalUtils.getStackTrace(e)); + } + return foundUsers; + } + + @SuppressWarnings("rawtypes") + public List<UserWithNameSurnameTitle> searchUsersByName(EPUser attrUser) { + List<UserWithNameSurnameTitle> foundUsers = new ArrayList<UserWithNameSurnameTitle>(); + try { + List searchResult = this.userService.getUserByFirstLastName(attrUser.getFirstName(),attrUser.getLastName()); + for (Object obj : searchResult) { + EPUser user = (EPUser) obj; + UserWithNameSurnameTitle foundUser = new UserWithNameSurnameTitle(user.getOrgUserId(), user.getFirstName(), user.getLastName(), user.getJobTitle()); + foundUsers.add(foundUser); + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "searchInPhoneBookWithToken Exception = " + EcompPortalUtils.getStackTrace(e)); + } + return foundUsers; + } + + private List<UserWithNameSurnameTitle> removeWrongFirstNames(List<UserWithNameSurnameTitle> resultOfSearch, String firstName) { + firstName = firstName.toUpperCase(); + for (int i = resultOfSearch.size() - 1; i >= 0; i--) { + UserWithNameSurnameTitle user = resultOfSearch.get(i); + if ((user.firstName == null) || !user.firstName.toUpperCase().startsWith(firstName)) { + resultOfSearch.remove(i); + } + } + return resultOfSearch; + } + + private List<UserWithNameSurnameTitle> removeWrongLastNames(List<UserWithNameSurnameTitle> resultOfSearch, String lastName) { + lastName = lastName.toUpperCase(); + for (int i = resultOfSearch.size() - 1; i >= 0; i--) { + UserWithNameSurnameTitle user = resultOfSearch.get(i); + if ((user.lastName == null) || !user.lastName.toUpperCase().startsWith(lastName)) { + resultOfSearch.remove(i); + } + } + return resultOfSearch; + } + + private List<UserWithNameSurnameTitle> cutSearchResultToMaximumSize(List<UserWithNameSurnameTitle> resultOfSearch) { + for (int i = resultOfSearch.size() - 1; i >= maxSizeOfSearchResult; i--) { + resultOfSearch.remove(i); + } + return resultOfSearch; + } + + + @SuppressWarnings("rawtypes") + @Override + public EPUser searchUserByUserId(String orgUserId) { + List<EPUser> foundUsers = new ArrayList<EPUser>(); + try { + List searchResult = this.userService.getUserByUserId(orgUserId); + for (Object obj : searchResult) { + EPUser user = (EPUser) obj; + foundUsers.add(user); + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "searchInPhoneBookWithToken Exception = " + EcompPortalUtils.getStackTrace(e)); + } + return foundUsers.get(0); + } + +} diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/UserRolesService.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/UserRolesService.java new file mode 100644 index 00000000..b285051c --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/UserRolesService.java @@ -0,0 +1,58 @@ +/*- + * ================================================================================ + * 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.service; + +import java.util.List; + +import org.apache.cxf.transport.http.HTTPException; +import org.openecomp.portalapp.portal.domain.EPRole; +import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalapp.portal.domain.EPUserApp; +import org.openecomp.portalapp.portal.transport.AppWithRolesForUser; +import org.openecomp.portalapp.portal.transport.RoleInAppForUser; +import org.openecomp.portalapp.portal.transport.UserApplicationRoles; + +public interface UserRolesService { + + public List<RoleInAppForUser> getAppRolesForUser(Long appId, String userId); + + public boolean setAppWithUserRoleStateForUser(EPUser user, AppWithRolesForUser newAppRolesForUser); + + public List<UserApplicationRoles> getUsersFromAppEndpoint(Long appId) throws HTTPException; + + public List<EPRole> importRolesFromRemoteApplication(Long appId) throws HTTPException; + + + /** + * Gets entries from the local fn_user_role table for the specified user and + * app. + * + * @param appId + * ID of row in fn_app + * @param userid + * ID of row in fn_user + * @return List of EPRole; empty if none found. + */ + public List<EPUserApp> getCachedAppRolesForUser(Long appId, Long userId); + + public String updateRemoteUserProfile(String orgUserId, Long appId); + + +} diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/UserRolesServiceImpl.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/UserRolesServiceImpl.java new file mode 100644 index 00000000..a0aac922 --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/UserRolesServiceImpl.java @@ -0,0 +1,726 @@ +/*- + * ================================================================================ + * 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.service; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.TreeSet; + +import javax.annotation.PostConstruct; + +import org.apache.commons.lang.StringUtils; +import org.apache.cxf.transport.http.HTTPException; +import org.hibernate.Query; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; +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.domain.EPUserApp; +import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog; +import org.openecomp.portalapp.portal.logging.format.EPAppMessagesEnum; +import org.openecomp.portalapp.portal.logging.logic.EPLogUtil; +import org.openecomp.portalapp.portal.transport.AppWithRolesForUser; +import org.openecomp.portalapp.portal.transport.FunctionalMenuItem; +import org.openecomp.portalapp.portal.transport.FunctionalMenuRole; +import org.openecomp.portalapp.portal.transport.RemoteUserWithRoles; +import org.openecomp.portalapp.portal.transport.RoleInAppForUser; +import org.openecomp.portalapp.portal.transport.RolesInAppForUser; +import org.openecomp.portalapp.portal.transport.UserApplicationRoles; +import org.openecomp.portalapp.portal.utils.EPSystemProperties; +import org.openecomp.portalapp.portal.utils.EcompPortalUtils; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.restful.domain.EcompRole; +import org.openecomp.portalsdk.core.service.DataAccessService; +import org.openecomp.portalsdk.core.service.UserProfileService; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; + +@Service("userRolesService") +@Transactional +@org.springframework.context.annotation.Configuration +@EnableAspectJAutoProxy +@EPMetricsLog +public class UserRolesServiceImpl implements UserRolesService { + private static Long ACCOUNT_ADMIN_ROLE_ID = 999L; + + private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(UserRolesServiceImpl.class); + + @Autowired + private SessionFactory sessionFactory; + @Autowired + private DataAccessService dataAccessService; + @Autowired + SearchService searchService; + @Autowired + EPAppService appsService; + @Autowired + EPLdapService ldapService; + @Autowired + ApplicationsRestClientService applicationsRestClientService; + @Autowired + EPRoleService epRoleService; + @Autowired + UserProfileService userProfileService; + + @PostConstruct + private void init() { + try { + ACCOUNT_ADMIN_ROLE_ID = Long + .valueOf(SystemProperties.getProperty(EPSystemProperties.ACCOUNT_ADMIN_ROLE_ID)); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e)); + } + } + + private static HashMap<Long, EcompRole> hashMapFromEcompRoles(EcompRole[] ecompRoles) { + HashMap<Long, EcompRole> result = new HashMap<Long, EcompRole>(); + if (ecompRoles != null) { + for (int i = 0; i < ecompRoles.length; i++) { + if (ecompRoles[i].getId() != null) { + result.put(ecompRoles[i].getId(), ecompRoles[i]); + } + } + } + return result; + } + + private void createLocalUserIfNecessary(String orgUserId) { + if (StringUtils.isEmpty(orgUserId)) { + logger.error(EELFLoggerDelegate.errorLogger, "createLocalUserIfNecessary : empty orgUserId!"); + return; + } + Session localSession = null; + Transaction transaction = null; + try { + localSession = sessionFactory.openSession(); + transaction = localSession.beginTransaction(); + @SuppressWarnings("unchecked") + List<EPUser> userList = localSession + .createQuery("from " + EPUser.class.getName() + " where org_user_id='" + orgUserId + "'").list(); + if (userList.size() == 0) { + EPUser client = searchService.searchUserByUserId(orgUserId); + if (client == null) { + String msg = "cannot create user " + orgUserId + ", because he cannot be found in phonebook"; + logger.error(EELFLoggerDelegate.errorLogger, msg); + } else { + client.setLoginId(orgUserId); + client.setActive(true); + localSession.save(client); + } + } + transaction.commit(); + } catch (Exception e) { + EPLogUtil.logEcompError(EPAppMessagesEnum.BeDaoSystemError); + EcompPortalUtils.rollbackTransaction(transaction, "searchOrCreateUser rollback, exception = " + e); + } finally { + EcompPortalUtils.closeLocalSession(localSession, "searchOrCreateUser"); + } + } + + private static void syncUserRoles(SessionFactory sessionFactory, String orgUserId, Long appId, + EcompRole[] userAppRoles) throws Exception { + HashMap<Long, EcompRole> newUserAppRolesMap = hashMapFromEcompRoles(userAppRoles); + boolean result = false; + Session localSession = null; + Transaction transaction = null; + + try { + localSession = sessionFactory.openSession(); + transaction = localSession.beginTransaction(); + @SuppressWarnings("unchecked") + List<EPUser> userList = localSession + .createQuery("from " + EPUser.class.getName() + " where org_user_id='" + orgUserId + "'").list(); + if (userList.size() > 0) { + EPUser client = userList.get(0); + @SuppressWarnings("unchecked") + List<EPUserApp> userRoles = localSession.createQuery("from " + EPUserApp.class.getName() + + " where app.id=" + appId + " and userId=" + client.getId()).list(); + for (EPUserApp userRole : userRoles) { + if (!userRole.getRoleId().equals(ACCOUNT_ADMIN_ROLE_ID)) { + + Long userAppRoleId = userRole.getAppRoleId(); + if (!newUserAppRolesMap.containsKey(userAppRoleId)) { + localSession.delete(userRole); + } else { + newUserAppRolesMap.remove(userAppRoleId); + } + } + } + Collection<EcompRole> newRolesToAdd = newUserAppRolesMap.values(); + if (newRolesToAdd.size() > 0) { + EPApp app = (EPApp) localSession.get(EPApp.class, appId); + @SuppressWarnings("unchecked") + List<EPRole> roles = localSession + .createQuery("from " + EPRole.class.getName() + " where appId=" + appId).list(); + HashMap<Long, EPRole> rolesMap = new HashMap<Long, EPRole>(); + for (EPRole role : roles) { + rolesMap.put(role.getAppRoleId(), role); + } + for (EcompRole userRole : newRolesToAdd) { + EPUserApp userApp = new EPUserApp(); + userApp.setUserId(client.getId()); + userApp.setApp(app); + userApp.setRole(rolesMap.get(userRole.getId())); + localSession.save(userApp); + } + } + } + transaction.commit(); + result = true; + } catch (Exception e) { + EPLogUtil.logEcompError(EPAppMessagesEnum.BeDaoSystemError); + EcompPortalUtils.rollbackTransaction(transaction, + "Exception occurred in syncUserRoles, Details: " + EcompPortalUtils.getStackTrace(e)); + } finally { + localSession.close(); + if (!result) { + throw new Exception( + "Exception occurred in syncUserRoles while closing database session for app: '" + appId + "'."); + } + } + } + + // Called when getting the list of roles for the user + private List<RoleInAppForUser> constructRolesInAppForUserGet(EcompRole[] appRoles, EcompRole[] userAppRoles) { + List<RoleInAppForUser> rolesInAppForUser = new ArrayList<RoleInAppForUser>(); + + Set<Long> userAppRolesMap = new HashSet<Long>(); + if (userAppRoles != null) { + for (EcompRole ecompRole : userAppRoles) { + userAppRolesMap.add(ecompRole.getId()); + } + } else { + String message = String + .format("UserRolesServiceImpl.constructRolesInAppForUserGet has received userAppRoles list empty."); + logger.info(EELFLoggerDelegate.errorLogger, message); + } + + if (appRoles != null) { + for (EcompRole ecompRole : appRoles) { + RoleInAppForUser roleForUser = new RoleInAppForUser(ecompRole.getId(), ecompRole.getName()); + roleForUser.isApplied = userAppRolesMap.contains(ecompRole.getId()); + rolesInAppForUser.add(roleForUser); + } + } else { + String message = String + .format("UserRolesServiceImpl.constructRolesInAppForUser has received appRoles list empty."); + logger.info(EELFLoggerDelegate.errorLogger, message); + } + return rolesInAppForUser; + } + + public List<RoleInAppForUser> getAppRolesForUser(Long appId, String orgUserId) { + List<RoleInAppForUser> rolesInAppForUser = null; + try { + EcompRole[] appRoles = applicationsRestClientService.get(EcompRole[].class, appId, "/roles"); + + // Test this error case, for generating an internal Ecomp Portal + // error + // EcompRole[] appRoles = null; + // If there is an exception in the rest client api, then null will + // be returned. + if (appRoles != null) { + syncAppRoles(sessionFactory, appId, appRoles); + EcompRole[] userAppRoles; + try { + userAppRoles = applicationsRestClientService.get(EcompRole[].class, appId, + String.format("/user/%s/roles", orgUserId)); + if (userAppRoles == null) { + if (EcompPortalUtils.getExternalAppResponseCode() == 400) { + EcompPortalUtils.setExternalAppResponseCode(200); + logger.error(EELFLoggerDelegate.errorLogger, + "400 returned from /user/{userid}/roles, assuming user doesn't exist, app is framework SDK based, and things are ok. Overriding to 200 until framework SDK returns a useful response."); + logger.debug(EELFLoggerDelegate.debugLogger, + "400 returned from /user/{userid}/roles, assuming user doesn't exist, app is framework SDK based, and things are ok. Overriding to 200 until framework SDK returns a useful response."); + } + } + // If the remote application isn't down we MUST to sync user + // roles here in case we have this user here! + syncUserRoles(sessionFactory, orgUserId, appId, userAppRoles); + } catch (Exception e) { + // TODO: we may need to check if user exists, maybe remote + // app is down. + logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e)); + logger.error(EELFLoggerDelegate.errorLogger, + "LR: user " + orgUserId + " does not exist in remote application: " + appId + "."); + userAppRoles = new EcompRole[0]; + } + rolesInAppForUser = constructRolesInAppForUserGet(appRoles, userAppRoles); + // Test this error case, for generating an external app error + // EcompPortalUtils.setResponseCode(404); + } + } catch (Exception e) { + String message = String.format( + "Received an exception while performing getAppRolesForUser for the User %s, and for the AppId %s, Details: %s", + orgUserId, Long.toString(appId), EcompPortalUtils.getStackTrace(e)); + logger.error(EELFLoggerDelegate.errorLogger, message); + } + return rolesInAppForUser; + + } + + // copies of methods in GetAppsWithUserRoleState + private void syncAppRoles(SessionFactory sessionFactory, Long appId, EcompRole[] appRoles) throws Exception { + logger.debug(EELFLoggerDelegate.debugLogger, "entering syncAppRoles for appId: " + appId); + HashMap<Long, EcompRole> newRolesMap = hashMapFromEcompRoles(appRoles); + boolean result = false; + Session localSession = null; + Transaction transaction = null; + + try { + localSession = sessionFactory.openSession(); + transaction = localSession.beginTransaction(); + // Attention! All roles from remote application supposed to be + // active! + @SuppressWarnings("unchecked") + List<EPRole> currentAppRoles = localSession + .createQuery("from " + EPRole.class.getName() + " where appId=" + appId).list(); + List<EPRole> obsoleteRoles = new ArrayList<EPRole>(); + for (int i = 0; i < currentAppRoles.size(); i++) { + EPRole oldAppRole = currentAppRoles.get(i); + if (oldAppRole.getAppRoleId() != null) { + EcompRole role = null; + role = newRolesMap.get(oldAppRole.getAppRoleId()); + if (role != null) { + if (!(role.getName() == null || oldAppRole.getName().equals(role.getName()))) { + oldAppRole.setName(role.getName()); + localSession.update(oldAppRole); + } + newRolesMap.remove(oldAppRole.getAppRoleId()); + } else { + obsoleteRoles.add(oldAppRole); + } + } else { + obsoleteRoles.add(oldAppRole); + } + } + Collection<EcompRole> newRolesToAdd = newRolesMap.values(); + for (EcompRole role : newRolesToAdd) { + logger.debug(EELFLoggerDelegate.debugLogger, "about to add missing role: " + role.toString()); + EPRole newRole = new EPRole(); + // Attention! All roles from remote application supposed to be + // active! + newRole.setActive(true); + newRole.setName(role.getName()); + newRole.setAppId(appId); + newRole.setAppRoleId(role.getId()); + localSession.save(newRole); + } + if (obsoleteRoles.size() > 0) { + logger.debug(EELFLoggerDelegate.debugLogger, "we have obsolete roles to delete"); + for (EPRole role : obsoleteRoles) { + logger.debug(EELFLoggerDelegate.debugLogger, "obsolete role: " + role.toString()); + Long roleId = role.getId(); + // delete obsolete roles here + // Must delete all records with foreign key constraints on + // fn_role: + // fn_user_role, fn_role_composite, fn_role_function, + // fn_user_pseudo_role, fn_menu_functional_roles. + // And for fn_menu_functional, if no other roles for that + // menu item, remove the url. + + // Delete from fn_user_role + @SuppressWarnings("unchecked") + List<EPUserApp> userRoles = localSession.createQuery( + "from " + EPUserApp.class.getName() + " where app.id=" + appId + " and role_id=" + roleId) + .list(); + + logger.debug(EELFLoggerDelegate.debugLogger, "number of userRoles to delete: " + userRoles.size()); + for (EPUserApp userRole : userRoles) { + logger.debug(EELFLoggerDelegate.debugLogger, + "about to delete userRole: " + userRole.toString()); + localSession.delete(userRole); + logger.debug(EELFLoggerDelegate.debugLogger, + "finished deleting userRole: " + userRole.toString()); + } + + // Delete from fn_menu_functional_roles + @SuppressWarnings("unchecked") + List<FunctionalMenuRole> funcMenuRoles = localSession + .createQuery("from " + FunctionalMenuRole.class.getName() + " where roleId=" + roleId) + .list(); + int numMenuRoles = funcMenuRoles.size(); + logger.debug(EELFLoggerDelegate.debugLogger, + "number of funcMenuRoles for roleId: " + roleId + ": " + numMenuRoles); + for (FunctionalMenuRole funcMenuRole : funcMenuRoles) { + Long menuId = funcMenuRole.menuId; + // If this is the only role for this menu item, then the + // app and roles will be gone, + // so must null out the url too, to be consistent + @SuppressWarnings("unchecked") + List<FunctionalMenuRole> funcMenuRoles2 = localSession + .createQuery("from " + FunctionalMenuRole.class.getName() + " where menuId=" + menuId) + .list(); + int numMenuRoles2 = funcMenuRoles2.size(); + logger.debug(EELFLoggerDelegate.debugLogger, + "number of funcMenuRoles for menuId: " + menuId + ": " + numMenuRoles2); + localSession.delete(funcMenuRole); + if (numMenuRoles2 == 1) { + // If this is the only role for this menu item, then + // the app and roles will be gone, + // so must null out the url too, to be consistent + logger.debug(EELFLoggerDelegate.debugLogger, + "There is exactly 1 menu item for this role, so emptying the url"); + @SuppressWarnings("unchecked") + List<FunctionalMenuItem> funcMenuItems = localSession + .createQuery( + "from " + FunctionalMenuItem.class.getName() + " where menuId=" + menuId) + .list(); + if (funcMenuItems.size() > 0) { + logger.debug(EELFLoggerDelegate.debugLogger, "got the menu item"); + FunctionalMenuItem funcMenuItem = funcMenuItems.get(0); + funcMenuItem.url = ""; + localSession.update(funcMenuItem); + } + } + } + + // Delete from fn_role_function + String sql = "DELETE FROM fn_role_function WHERE role_id=" + roleId; + logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql); + Query query = localSession.createSQLQuery(sql); + query.executeUpdate(); + + // Delete from fn_role_composite + sql = "DELETE FROM fn_role_composite WHERE parent_role_id=" + roleId + " OR child_role_id=" + + roleId; + logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql); + query = localSession.createSQLQuery(sql); + query.executeUpdate(); + + // Delete from fn_user_pseudo_role + sql = "DELETE FROM fn_user_pseudo_role WHERE pseudo_role_id=" + roleId; + logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql); + query = localSession.createSQLQuery(sql); + query.executeUpdate(); + + logger.debug(EELFLoggerDelegate.debugLogger, "about to delete the role: " + role.toString()); + localSession.delete(role); + logger.debug(EELFLoggerDelegate.debugLogger, "deleted the role"); + } + } + logger.debug(EELFLoggerDelegate.debugLogger, "about to commit the transaction"); + transaction.commit(); + logger.debug(EELFLoggerDelegate.debugLogger, "committed the transaction"); + result = true; + } catch (Exception e) { + EPLogUtil.logEcompError(EPAppMessagesEnum.BeDaoSystemError); + EcompPortalUtils.rollbackTransaction(transaction, + "Exception occurred in syncAppRoles, Details: " + EcompPortalUtils.getStackTrace(e)); + } finally { + localSession.close(); + if (!result) { + throw new Exception( + "Exception occurred in syncAppRoles while closing database session for app: '" + appId + "'."); + } + } + } + + // Called when updating the list of roles for the user + private RolesInAppForUser constructRolesInAppForUserUpdate(String orgUserId, Long appId, + Set<EcompRole> userRolesInRemoteApp) { + RolesInAppForUser result; + result = new RolesInAppForUser(); + result.appId = appId; + result.orgUserId = orgUserId; + for (EcompRole role : userRolesInRemoteApp) { + RoleInAppForUser roleInAppForUser = new RoleInAppForUser(); + roleInAppForUser.roleId = role.getId(); + roleInAppForUser.roleName = role.getName(); + roleInAppForUser.isApplied = new Boolean(true); + result.roles.add(roleInAppForUser); + } + return result; + } + + private EPUser getUserFromRemoteApp(String orgUserId, EPApp app, + ApplicationsRestClientService applicationsRestClientService) throws HTTPException { + EPUser user = applicationsRestClientService.get(EPUser.class, app.getId(), + String.format("/user/%s", orgUserId)); + return user; + } + + private boolean remoteUserShouldBeCreated(List<RoleInAppForUser> roleInAppForUserList) { + for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) { + if (roleInAppForUser.isApplied.booleanValue()) { + return true; + } + } + return false; + } + + private Set<EcompRole> postUsersRolesToRemoteApp(List<RoleInAppForUser> roleInAppForUserList, ObjectMapper mapper, + ApplicationsRestClientService applicationsRestClientService, Long appId, String orgUserId) + throws JsonProcessingException, HTTPException { + Set<EcompRole> updatedUserRoles = constructUsersEcompRoles(roleInAppForUserList); + String userRolesAsString = mapper.writeValueAsString(updatedUserRoles); + applicationsRestClientService.post(EcompRole.class, appId, userRolesAsString, + String.format("/user/%s/roles", orgUserId)); + // TODO: We should add code that verifies that the post operation did + // succeed. Because the SDK may still return 200 OK with an html page + // even when it fails! + return updatedUserRoles; + } + + private Set<EcompRole> constructUsersEcompRoles(List<RoleInAppForUser> roleInAppForUserList) { + Set<EcompRole> existingUserRoles = new TreeSet<EcompRole>(); + for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) { + if (roleInAppForUser.isApplied) { + EcompRole ecompRole = new EcompRole(); + ecompRole.setId(roleInAppForUser.roleId); + ecompRole.setName(roleInAppForUser.roleName); + existingUserRoles.add(ecompRole); + } + } + return existingUserRoles; + } + + private static void createNewUserOnRemoteApp(String orgUserId, EPApp app, + ApplicationsRestClientService applicationsRestClientService, SearchService searchService, + ObjectMapper mapper) throws Exception { + EPUser client = searchService.searchUserByUserId(orgUserId); + if (client == null) { + String msg = "cannot create user " + orgUserId + ", because he/she cannot be found in phonebook."; + logger.error(EELFLoggerDelegate.errorLogger, msg); + throw new Exception(msg); + } + client.setLoginId(orgUserId); + client.setActive(true); + // The remote doesn't care about other apps, and this has caused + // serialization problems - infinite recursion. + client.getEPUserApps().clear(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + String userAsString = mapper.writeValueAsString(client); + logger.debug(EELFLoggerDelegate.debugLogger, + "about to post new client to remote application, users json = " + userAsString); + applicationsRestClientService.post(EPUser.class, app.getId(), userAsString, String.format("/user", orgUserId)); + } + + public String updateRemoteUserProfile(String orgUserId, Long appId) { + + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + EPUser client = searchService.searchUserByUserId(orgUserId); + EPUser newUser = new EPUser(); + newUser.setActive(client.getActive()); + newUser.setFirstName(client.getFirstName()); + newUser.setLastName(client.getLastName()); + newUser.setLoginId(client.getLoginId()); + newUser.setLoginPwd(client.getLoginPwd()); + newUser.setMiddleInitial(client.getMiddleInitial()); + newUser.setEmail(client.getEmail()); + newUser.setOrgUserId(client.getLoginId()); + try { + String userAsString = mapper.writeValueAsString(newUser); + List<EPApp> appList = appsService.getUserRemoteApps(client.getId().toString()); + // applicationsRestClientService.post(EPUser.class, appId, + // userAsString, String.format("/user", orgUserId)); + for (EPApp eachApp : appList) { + try { + applicationsRestClientService.post(EPUser.class, eachApp.getId(), userAsString, + String.format("/user/%s", orgUserId)); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "Failed to update user: " + client.getOrgUserId() + + " in remote app. appId = " + eachApp.getId()); + } + } + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + return "failure"; + } + + return "success"; + + } + + private static final Object syncRests = new Object(); + + @Override + public boolean setAppWithUserRoleStateForUser(EPUser user, AppWithRolesForUser newAppRolesForUser) { + boolean result = false; + String orgUserId = ""; + if (newAppRolesForUser != null && newAppRolesForUser.orgUserId != null) { + orgUserId = newAppRolesForUser.orgUserId.trim(); + } + Long appId = newAppRolesForUser.appId; + List<RoleInAppForUser> roleInAppForUserList = newAppRolesForUser.appRoles; + if (orgUserId.length() > 0) { + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + + try { + EPApp app = appsService.getApp(appId); + EPUser remoteAppUser = getUserFromRemoteApp(orgUserId, app, applicationsRestClientService); + if (remoteAppUser == null) { + if (remoteUserShouldBeCreated(roleInAppForUserList)) { + createNewUserOnRemoteApp(orgUserId, app, applicationsRestClientService, searchService, mapper); + // If we succeed, we know that the new user was + // persisted on remote app. + remoteAppUser = getUserFromRemoteApp(orgUserId, app, applicationsRestClientService); + if (remoteAppUser == null) { + logger.error(EELFLoggerDelegate.errorLogger, + "Failed to persist new user: " + orgUserId + " in remote app. appId = " + appId); + // return null; + } + } + } + if (remoteAppUser != null) { + Set<EcompRole> userRolesInRemoteApp = postUsersRolesToRemoteApp(roleInAppForUserList, mapper, + applicationsRestClientService, appId, orgUserId); + RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, appId, + userRolesInRemoteApp); + result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser); + } + } catch (Exception e) { + String message = String.format( + "Failed to create user or update user roles for the User %s, and for the AppId %s, Details: %s", + orgUserId, Long.toString(appId), EcompPortalUtils.getStackTrace(e)); + logger.error(EELFLoggerDelegate.errorLogger, message); + result = false; + } + + } + return result; + } + + // This is for a single app + private boolean applyChangesInUserRolesForAppToEcompDB(RolesInAppForUser rolesInAppForUser) { + boolean result = false; + String orgUserId = rolesInAppForUser.orgUserId; + Long appId = rolesInAppForUser.appId; + synchronized (syncRests) { + if (rolesInAppForUser != null) { + createLocalUserIfNecessary(orgUserId); + } + + if (rolesInAppForUser != null) { + EcompRole[] userAppRoles = new EcompRole[rolesInAppForUser.roles.size()]; + for (int i = 0; i < rolesInAppForUser.roles.size(); i++) { + RoleInAppForUser roleInAppForUser = rolesInAppForUser.roles.get(i); + EcompRole role = new EcompRole(); + role.setId(roleInAppForUser.roleId); + role.setName(roleInAppForUser.roleName); + userAppRoles[i] = role; + } + try { + syncUserRoles(sessionFactory, orgUserId, appId, userAppRoles); + result = true; + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, + "applyChangesInUserRolesForAppToEcompDB syncUserRoles, orgUserId = " + orgUserId); + logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e)); + } + } + } + return result; + } + + @Override + public List<UserApplicationRoles> getUsersFromAppEndpoint(Long appId) throws HTTPException { + RemoteUserWithRoles[] remoteUsers = applicationsRestClientService.get(RemoteUserWithRoles[].class, appId, + "/users"); + ArrayList<UserApplicationRoles> userApplicationRoles = new ArrayList<UserApplicationRoles>(); + for (RemoteUserWithRoles remoteUser : remoteUsers) { + UserApplicationRoles userWithRemoteAppRoles = convertToUserApplicationRoles(appId, remoteUser); + if(userWithRemoteAppRoles.getRoles()!=null && userWithRemoteAppRoles.getRoles().size()>0) { + userApplicationRoles.add(userWithRemoteAppRoles); + } else { + logger.debug(EELFLoggerDelegate.debugLogger, "User " + userWithRemoteAppRoles.getOrgUserId() + + " doesn't have any roles assigned to any app."); + + } + } + + return userApplicationRoles; + } + + private UserApplicationRoles convertToUserApplicationRoles(Long appId, RemoteUserWithRoles remoteUser) { + UserApplicationRoles userWithRemoteAppRoles = new UserApplicationRoles(); + userWithRemoteAppRoles.setAppId(appId); + userWithRemoteAppRoles.setOrgUserId(remoteUser.getLoginId()); + userWithRemoteAppRoles.setFirstName(remoteUser.getFirstName()); + userWithRemoteAppRoles.setLastName(remoteUser.getLastName()); + userWithRemoteAppRoles.setRoles(remoteUser.getRoles()); + return userWithRemoteAppRoles; + } + + public static void persistExternalRoleInEcompDb(EPRole externalAppRole, Long appId, EPRoleService roleService) { + externalAppRole.setAppId(appId); + externalAppRole.setAppRoleId(externalAppRole.getId()); + externalAppRole.setId(null); // We will persist a new role, with ecomp + // role id which will be different than + // external app role id. + + roleService.saveRole(externalAppRole); + logger.debug(EELFLoggerDelegate.debugLogger, + String.format("ECOMP persists role from app:%d, app roleId: %d, roleName: %s", appId, + externalAppRole.getAppRoleId(), externalAppRole.getName())); + } + + @Override + public List<EPRole> importRolesFromRemoteApplication(Long appId) throws HTTPException { + EPRole[] appRolesFull = applicationsRestClientService.get(EPRole[].class, appId, "/rolesFull"); + List<EPRole> rolesList = Arrays.asList(appRolesFull); + for (EPRole externalAppRole : rolesList) { + + // Try to find an existing extern role for the app in the local + // ecomp DB. If so, then use its id to update the existing external + // application role record. + Long externAppId = externalAppRole.getId(); + EPRole existingAppRole = epRoleService.getRole(appId, externAppId); + if (existingAppRole != null) { + logger.debug(EELFLoggerDelegate.debugLogger, + String.format("ecomp role already exists for app=%s; appRoleId=%s. No need to import this one.", + appId, externAppId)); + continue; + } + // persistExternalRoleInEcompDb(externalAppRole, appId, + // roleService); + } + + return rolesList; + } + + @Override + public List<EPUserApp> getCachedAppRolesForUser(Long appId, Long userId) { + // Find the records for this user-app combo, if any + String filter = " where user_id = " + Long.toString(userId) + " and app_id = " + Long.toString(appId); + @SuppressWarnings("unchecked") + List<EPUserApp> roleList = dataAccessService.getList(EPUserApp.class, filter, null, null); + logger.debug(EELFLoggerDelegate.debugLogger, "getCachedAppRolesForUser: list size is {}", roleList.size()); + return roleList; + } + +} diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/UserService.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/UserService.java new file mode 100644 index 00000000..bd8949f3 --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/UserService.java @@ -0,0 +1,34 @@ +/*- + * ================================================================================ + * 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.service; + +import java.util.List; + +import org.openecomp.portalapp.portal.domain.EPUser; + +public interface UserService { + + List getUserByUserId(String orgUserId); + + List getUserByFirstLastName(String firstName, String lastName); + + public String saveNewUser(EPUser newUser, String checkDuplicate) throws Exception; + +} diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/UserServiceImpl.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/UserServiceImpl.java new file mode 100644 index 00000000..225f3a7a --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/UserServiceImpl.java @@ -0,0 +1,260 @@ +/*- + * ================================================================================ + * 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.service; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.HttpURLConnection; +import java.net.URL; +import java.util.ArrayList; +import java.util.List; + +import org.json.JSONArray; +import org.json.JSONObject; +import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalapp.portal.utils.EPSystemProperties; +import org.openecomp.portalapp.portal.utils.EcompPortalUtils; +import org.openecomp.portalsdk.core.FusionObject.Utilities; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.service.DataAccessService; +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.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service("userService") +@Transactional +public class UserServiceImpl implements UserService { + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(UserServiceImpl.class); + + @Autowired + private DataAccessService dataAccessService; + + public DataAccessService getDataAccessService() { + return dataAccessService; + } + + public void setDataAccessService(DataAccessService dataAccessService) { + this.dataAccessService = dataAccessService; + } + + @SuppressWarnings("rawtypes") + @Override + public List getUserByUserId(String userId) { + + + if(SystemProperties.getProperty(SystemProperties.AUTHENTICATION_MECHANISM).trim().equalsIgnoreCase("OIDC")){ + List<EPUser> users=new ArrayList<EPUser>(); + List<EPUser> filterdUsers=new ArrayList<EPUser>(); + BufferedReader in = null; + HttpURLConnection con = null; + try{ + String url = EPSystemProperties.getProperty(EPSystemProperties.AUTH_USER_SERVER); + URL obj = new URL(url); + + con = (HttpURLConnection) obj.openConnection(); + + // optional default is GET + con.setRequestMethod("GET"); + con.setConnectTimeout(3000); + con.setReadTimeout(8000); + + StringBuffer response = new StringBuffer(); + + in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8")); + String inputLine; + while ((inputLine = in.readLine()) != null) + response.append(inputLine); + JSONObject jObject = new JSONObject(response.toString()); // json + JSONArray jsonUsers = jObject.getJSONArray("response"); // get data object + for (int i = 0; i < jsonUsers.length(); i++) { + JSONObject eachObject = jsonUsers.getJSONObject(i); + EPUser eachUser = new EPUser(); + eachUser.setOrgUserId(eachObject.get("id").toString());// getString("id")); + eachUser.setFirstName(eachObject.get("givenName").toString()); + eachUser.setLastName(eachObject.get("familyName").toString()); + eachUser.setEmail(eachObject.get("email").toString()); + users.add(eachUser); + } + + for(int i = 0 ; i < users.size(); i ++){ + + if(Utilities.nvl(userId).length() > 0){ + if(!userId.equalsIgnoreCase(users.get(i).getOrgUserId())){ + continue; + } + } + filterdUsers.add(users.get(i)); + + } + + }catch (Exception e){ + logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e)); + }finally{ + try { + in.close(); + con.disconnect(); + } catch (IOException e) { + logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e)); + } + } + + return filterdUsers; + + }else{ + + List list = null; + StringBuffer criteria = new StringBuffer(); + criteria.append(" where org_user_id = '").append(userId).append("'"); + list = getDataAccessService().getList(EPUser.class, criteria.toString(), null, null); + return (list == null || list.size() == 0) ? null : list; + + } + + } + + @SuppressWarnings("rawtypes") + @Override + public List getUserByFirstLastName(String firstName, String lastName) { + + if(!SystemProperties.getProperty(SystemProperties.AUTHENTICATION_MECHANISM).trim().equalsIgnoreCase("OIDC")){ + + List list = null; + StringBuffer criteria = new StringBuffer(); + if(firstName!=null) + criteria.append(" where first_name = '").append(firstName).append("'"); + if(lastName!=null) + criteria.append(" where last_name = '").append(lastName).append("'"); + list = getDataAccessService().getList(EPUser.class, criteria.toString(), null, null); + return (list == null || list.size() == 0) ? null : list; + + }else{ + + List<EPUser> users=new ArrayList<EPUser>(); + List<EPUser> filterdUsers=new ArrayList<EPUser>(); + BufferedReader in = null; + HttpURLConnection con = null; + try{ + String url = EPSystemProperties.getProperty(EPSystemProperties.AUTH_USER_SERVER); + URL obj = new URL(url); + + con = (HttpURLConnection) obj.openConnection(); + + // optional default is GET + con.setRequestMethod("GET"); + con.setConnectTimeout(3000); + con.setReadTimeout(8000); + + StringBuffer response = new StringBuffer(); + + in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8")); + String inputLine; + while ((inputLine = in.readLine()) != null) + response.append(inputLine); + JSONObject jObject = new JSONObject(response.toString()); // json + JSONArray jsonUsers = jObject.getJSONArray("response"); // get data object + for (int i = 0; i < jsonUsers.length(); i++) { + JSONObject eachObject = jsonUsers.getJSONObject(i); + EPUser eachUser = new EPUser(); + eachUser.setOrgUserId(eachObject.get("id").toString());// getString("id")); + eachUser.setFirstName(eachObject.get("givenName").toString()); + eachUser.setLastName(eachObject.get("familyName").toString()); + eachUser.setEmail(eachObject.get("email").toString()); + users.add(eachUser); + } + + for(int i = 0 ; i < users.size(); i ++){ + + if(Utilities.nvl(firstName).length() > 0){ + if(!firstName.equalsIgnoreCase(users.get(i).getFirstName())){ + continue; + } + } + if(Utilities.nvl(lastName).length() > 0){ + if(!lastName.equalsIgnoreCase(users.get(i).getLastName())){ + continue; + } + } + + + filterdUsers.add(users.get(i)); + + } + + }catch (Exception e){ + logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e)); + }finally{ + try { + in.close(); + con.disconnect(); + } catch (IOException e) { + logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e)); + } + } + + return filterdUsers; + } + + } + + public String saveNewUser(EPUser newUser, String checkDuplicate) throws Exception{ + + try{ + + List list = null; + StringBuffer criteria = new StringBuffer(); + criteria.append(" where org_user_id = '").append(newUser.getLoginId()).append("'"); + list = getDataAccessService().getList(EPUser.class, criteria.toString(), null, null); + if(list == null || list.size()==0){ + newUser.setActive(true); + newUser.setOrgUserId(newUser.getLoginId()); + newUser.setLoginPwd(CipherUtil.encrypt(newUser.getLoginPwd())); + getDataAccessService().saveDomainObject(newUser, null); + }else{ + if(checkDuplicate.equals("Yes")){ + // userId already exist in database + return "Record already exist"; + }else{ + + EPUser oldUser = (EPUser) list.get(0); + oldUser.setFirstName(newUser.getFirstName()); + oldUser.setLastName(newUser.getLastName()); + oldUser.setMiddleInitial(newUser.getMiddleInitial()); + if(!oldUser.getLoginPwd().equals(newUser.getLoginPwd())) + oldUser.setLoginPwd(CipherUtil.encrypt(newUser.getLoginPwd())); + else + oldUser.setLoginPwd(newUser.getLoginPwd()); + getDataAccessService().saveDomainObject(oldUser, null); + + } + + } + + }catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "", e); + throw new Exception(e); + } + return "success"; + }; + +} diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/transport/OnboardingApp.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/transport/OnboardingApp.java new file mode 100644 index 00000000..4c97a52d --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/transport/OnboardingApp.java @@ -0,0 +1,83 @@ +/*- + * ================================================================================ + * 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.transport; + +public class OnboardingApp { + + public Long id; + + public String name; + + public String imageUrl; + + public String description; + + public String notes; + + public String url; + + public String alternateUrl; + + public String restUrl; + + public Boolean isOpen; + + public Boolean isEnabled; + + public String username; + + public String appPassword; + + public String thumbnail; + + public String uebTopicName; + + public String uebKey; + + public String uebSecret; + + public Boolean restrictedApp; + + public void normalize() { + this.name = (this.name == null) ? "" : this.name.trim(); + this.username = (this.username == null) ? "" : this.username.trim(); + this.appPassword = (this.appPassword == null) ? "" : this.appPassword.trim(); + } + + public void setUebTopicName(String topicName) { + this.uebTopicName = topicName; + } + + public void setUebKey(String key) { + this.uebKey = key; + } + + public void setUebSecret(String secret) { + this.uebSecret = secret; + } + + // Hide the implementation of restricted and normal app from the front end. + // The json sent and received will include restrictedApp but not appType. + + public void setRestrictedApp(Boolean restrictedApp) { + this.restrictedApp = restrictedApp; + } +} + diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/ueb/EPUebHelper.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/ueb/EPUebHelper.java new file mode 100644 index 00000000..1162cf20 --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/ueb/EPUebHelper.java @@ -0,0 +1,218 @@ +/*- + * ================================================================================ + * 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.ueb; + +import java.net.HttpURLConnection; +import java.net.URL; +import java.util.LinkedList; +import java.util.List; + +import javax.annotation.PostConstruct; + +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.openecomp.portalapp.portal.domain.EPApp; +import org.openecomp.portalapp.portal.domain.EcompApp; +import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog; +import org.openecomp.portalapp.portal.logging.format.EPAppMessagesEnum; +import org.openecomp.portalapp.portal.logging.logic.EPLogUtil; +import org.openecomp.portalapp.portal.service.EPAppService; +import org.openecomp.portalapp.portal.utils.EcompPortalUtils; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.onboarding.util.PortalApiConstants; +import org.openecomp.portalsdk.core.onboarding.util.PortalApiProperties; +import org.openecomp.portalsdk.core.onboarding.ueb.Helper; +import org.openecomp.portalsdk.core.onboarding.ueb.Publisher; +import org.openecomp.portalsdk.core.onboarding.ueb.UebException; +import org.openecomp.portalsdk.core.onboarding.ueb.UebManager; +import org.openecomp.portalsdk.core.onboarding.ueb.UebMsg; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.stereotype.Component; +import org.springframework.transaction.annotation.Transactional; + +@Component +@Transactional +@org.springframework.context.annotation.Configuration +@EnableAspectJAutoProxy +public class EPUebHelper { + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(EPUebHelper.class); + + @Autowired + EPAppService appsService; + + + @Autowired + private SessionFactory sessionFactory; + + @SuppressWarnings("unused") + private Publisher epPublisher; + + public EPUebHelper() { + + } + // + // This should only be called by the ECOMP Portal App, other Apps have just one publisher and use appPublisher + // + @SuppressWarnings("unused") + @EPMetricsLog + public void refreshPublisherList() + { + Session localSession = null; + boolean addedPublisher = false; + + try { + localSession = sessionFactory.openSession(); + + List<EcompApp> apps = appsService.getEcompAppAppsFullList(); + for (int i = 0; i < apps.size(); i++) + { + if ((apps.get(i).isEnabled()) && + (apps.get(i).getUebTopicName() != null) && + !(apps.get(i).getUebTopicName().toUpperCase().contains("ECOMP-PORTAL-INBOX"))) + { + logger.debug(EELFLoggerDelegate.debugLogger, "UEBManager adding publisher for " + apps.get(i).getUebTopicName()); + UebManager.getInstance().addPublisher(apps.get(i).getUebTopicName()); + addedPublisher = true; + } + else if ((apps.get(i).getId() != 1) && // App may have been disabled, remove the publisher + !(apps.get(i).isEnabled())) + { + if(apps.get(i).getUebTopicName()!=null){ + UebManager.getInstance().removePublisher(apps.get(i).getUebTopicName()); + } + } + } + } + catch (Exception e) + { + EPLogUtil.logEcompError(EPAppMessagesEnum.BeUebSystemError, "add/remove Publisher"); + String stackTrace = EcompPortalUtils.getStackTrace(e); + logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while refreshing the publisher list. Details: " + stackTrace); + } + + //publisherList.print(); + + if (addedPublisher == true) // Give publishers time to initialize + { + Helper.sleep(400); + } + } + + //@PostConstruct + //@EPMetricsLog + public void initUeb() { + try { + epPublisher = new Publisher(PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY), + PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_SECRET), + PortalApiProperties.getProperty(PortalApiConstants.ECOMP_PORTAL_INBOX_NAME)); + } catch (Exception e) { + EPLogUtil.logEcompError(EPAppMessagesEnum.BeUebConnectionError, e.getMessage()); + String stackTrace = EcompPortalUtils.getStackTrace(e); + logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while initializing the publisher. Details: " + stackTrace); + } + + Thread thread = new Thread("EPUebManager: postConstructMethod - refreshPublisherList") { + public void run(){ + refreshPublisherList(); + } + }; + if (thread != null) { + thread.start(); + } + } + + @EPMetricsLog + public void addPublisher(EPApp app) { + // TODO Auto-generated method stub + try { + UebManager.getInstance().addPublisher(app.getUebTopicName()); + } catch (UebException e) { + String stackTrace = EcompPortalUtils.getStackTrace(e); + logger.error(EELFLoggerDelegate.errorLogger, "Exception while adding a publisher. Details: " + stackTrace); + } + } + + public boolean checkAvailability() { + + // + // Test existence of topic at UEB url + // + // + // + boolean available = true; + LinkedList<String> urlList = Helper.uebUrlList(); + if (!urlList.isEmpty()) { + String url = "http://" + urlList.getFirst() + ":3904/topics/" + PortalApiProperties.getProperty(PortalApiConstants.ECOMP_PORTAL_INBOX_NAME); + if (!url.isEmpty()) { + try { + URL siteURL = new URL(url); + HttpURLConnection connection = (HttpURLConnection) siteURL.openConnection(); + connection.setRequestMethod("GET"); + connection.connect(); + + int code = connection.getResponseCode(); + if (code == 200) { + available = true; + } + else { + EPLogUtil.logEcompError(EPAppMessagesEnum.BeUebConnectionError, url); + available = false; + logger.warn(EELFLoggerDelegate.errorLogger, "Warning! UEB topic existence check failed, topic = " + url ); + logger.debug(EELFLoggerDelegate.debugLogger, "Warning! UEB topic existence check failed, topic = " + url ); + } + } + catch (Exception e) { + available = false; + String stackTrace = EcompPortalUtils.getStackTrace(e); + logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while performing the UEB Healthcheck. Details: " + stackTrace); + } + } + } + return available; + } + + public boolean MessageCanBeSentToTopic() { + + boolean sentMsgSuccessfully = false; + + UebMsg msg = new UebMsg(); + msg.putSourceTopicName(PortalApiProperties.getProperty(PortalApiConstants.ECOMP_PORTAL_INBOX_NAME)); + msg.putPayload("Pinging topic for health check"); + msg.putMsgType(EPUebMsgTypes.UEB_MSG_TYPE_HEALTH_CHECK); + + try { + // epPublisher.send(msg); + sentMsgSuccessfully = true; + } + catch (Exception e) { + EPLogUtil.logEcompError(EPAppMessagesEnum.BeHealthCheckUebClusterError); + String stackTrace = EcompPortalUtils.getStackTrace(e); + sentMsgSuccessfully = false; + logger.warn(EELFLoggerDelegate.errorLogger, "Warning! could not successfully publish a UEB msg to " + + PortalApiProperties.getProperty(PortalApiConstants.ECOMP_PORTAL_INBOX_NAME) + " exception : " + stackTrace); + } + + return sentMsgSuccessfully; + } + +} + + diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/ueb/EPUebMsgTypes.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/ueb/EPUebMsgTypes.java new file mode 100644 index 00000000..d6eb9eb9 --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/ueb/EPUebMsgTypes.java @@ -0,0 +1,27 @@ +/*- + * ================================================================================ + * 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.ueb; + +import org.openecomp.portalsdk.core.onboarding.ueb.UebMsgTypes; + +public interface EPUebMsgTypes extends UebMsgTypes { + + public static final String UEB_MSG_TYPE_HEALTH_CHECK = "uebHealthCheckPing"; +} diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/utils/EPSystemProperties.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/utils/EPSystemProperties.java new file mode 100644 index 00000000..b187c010 --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/utils/EPSystemProperties.java @@ -0,0 +1,42 @@ +/*- + * ================================================================================ + * 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.utils; + +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; +import org.springframework.context.annotation.PropertySources; + +@Configuration +@PropertySources({ + @PropertySource ("/WEB-INF/conf/system.properties"), + @PropertySource ("/WEB-INF/conf/sql.properties"), + @PropertySource ("/WEB-INF/fusion/conf/fusion.properties"), + @PropertySource (value = "file:${catalina.home}/conf/system.properties", ignoreResourceNotFound = true), + @PropertySource (value = "file:${catalina.home}/conf/fusion.properties", ignoreResourceNotFound = true) + }) + +/** + * Contains properties specific to the ONAP version of the ECOMP Portal. + */ +public class EPSystemProperties extends EPCommonSystemProperties { + public static final String CONTACT_US_URL = "contact_us_link"; + public static final String ECOMP_CONTEXT_ROOT = "context_root"; + +}
\ No newline at end of file |