Bulk upload changes and music health check apis
[portal.git] / ecomp-portal-BE-common / src / main / java / org / onap / portalapp / portal / service / UserRolesCommonServiceImpl.java
index c65b4af..1811f8d 100644 (file)
@@ -33,7 +33,7 @@
  *
  * ============LICENSE_END============================================
  *
- * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ * 
  */
 
 package org.onap.portalapp.portal.service;
@@ -63,7 +63,6 @@ import org.hibernate.SessionFactory;
 import org.hibernate.Transaction;
 import org.json.JSONArray;
 import org.json.JSONObject;
-import org.onap.portalapp.portal.service.SearchService;
 import org.onap.portalapp.externalsystemapproval.model.ExternalSystemRoleApproval;
 import org.onap.portalapp.externalsystemapproval.model.ExternalSystemUser;
 import org.onap.portalapp.portal.domain.EPApp;
@@ -75,6 +74,7 @@ import org.onap.portalapp.portal.domain.EPUserAppRoles;
 import org.onap.portalapp.portal.domain.EPUserAppRolesRequest;
 import org.onap.portalapp.portal.domain.EPUserAppRolesRequestDetail;
 import org.onap.portalapp.portal.domain.ExternalSystemAccess;
+import org.onap.portalapp.portal.exceptions.SyncUserRolesException;
 import org.onap.portalapp.portal.logging.aop.EPMetricsLog;
 import org.onap.portalapp.portal.logging.format.EPAppMessagesEnum;
 import org.onap.portalapp.portal.logging.logic.EPLogUtil;
@@ -90,6 +90,7 @@ import org.onap.portalapp.portal.transport.FieldsValidator;
 import org.onap.portalapp.portal.transport.FunctionalMenuItem;
 import org.onap.portalapp.portal.transport.FunctionalMenuRole;
 import org.onap.portalapp.portal.transport.RemoteRole;
+import org.onap.portalapp.portal.transport.RemoteRoleV1;
 import org.onap.portalapp.portal.transport.RemoteUserWithRoles;
 import org.onap.portalapp.portal.transport.RoleInAppForUser;
 import org.onap.portalapp.portal.transport.RolesInAppForUser;
@@ -97,6 +98,7 @@ import org.onap.portalapp.portal.transport.UserApplicationRoles;
 import org.onap.portalapp.portal.utils.EPCommonSystemProperties;
 import org.onap.portalapp.portal.utils.EcompPortalUtils;
 import org.onap.portalapp.portal.utils.PortalConstants;
+import org.onap.portalapp.util.SystemType;
 import org.onap.portalsdk.core.domain.Role;
 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
 import org.onap.portalsdk.core.restful.domain.EcompRole;
@@ -140,6 +142,9 @@ public class UserRolesCommonServiceImpl  {
        @Autowired
        private ExternalAccessRolesService externalAccessRolesService;
        
+       @Autowired
+       private AppsCacheService appsCacheService;
+       
        RestTemplate template = new RestTemplate();
        
        /**
@@ -246,7 +251,6 @@ public class UserRolesCommonServiceImpl  {
         */
        protected void syncUserRoles(SessionFactory sessionFactory, String userId, Long appId,
                        EcompRole[] userAppRoles, Boolean extRequestValue, String reqType) throws Exception {
-               boolean result = false;
                Session localSession = null;
                Transaction transaction = null;
                String roleActive = null;
@@ -346,7 +350,7 @@ public class UserRolesCommonServiceImpl  {
                                                /*
                                                 * for local app -- hack - always make sure fn_role
                                                 * table's app_id is null and not 1 for primary app in
-                                                * this case being ecomp portal app; reason: hibernate
+                                                * this case being onap portal app; reason: hibernate
                                                 * is rightly setting this to 1 while persisting to
                                                 * fn_role as per the mapping but SDK role management
                                                 * code expects the app_id to be null as there is no
@@ -361,23 +365,17 @@ public class UserRolesCommonServiceImpl  {
                                }
                        }
                        transaction.commit();
-                       result = true;
                } catch (Exception e) {
                        logger.error(EELFLoggerDelegate.errorLogger, "syncUserRoles failed", e);
                        EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
                        EcompPortalUtils.rollbackTransaction(transaction,
                                        "Exception occurred in syncUserRoles, Details: " + e.toString());
                        if("DELETE".equals(reqType)){
-                               throw new Exception(e.getMessage());
+                               throw new SyncUserRolesException(e.getMessage());
                        }
                } finally {
-                       if (localSession != null) {
-                               localSession.close();           
-                       }                               
-                       if (!result && !"DELETE".equals(reqType)) {
-                               throw new Exception(
-                                               "Exception occurred in syncUserRoles while closing database session for app: '" + appId + "'.");
-                       }
+                       if(localSession != null)
+                               localSession.close();
                }
        }
        
@@ -653,6 +651,24 @@ public class UserRolesCommonServiceImpl  {
                Set<EcompRole> updatedUserRolesinRemote = constructUsersRemoteAppRoles(roleInAppForUserList);
                Set<EcompRole> updateUserRolesInEcomp = constructUsersEcompRoles(roleInAppForUserList);
                String userRolesAsString = mapper.writeValueAsString(updatedUserRolesinRemote);
+        EPApp externalApp = null;
+        SystemType type = SystemType.APPLICATION;
+               externalApp = appsCacheService.getApp(appId);
+               String appBaseUri = null;
+               Set<RemoteRoleV1> updatedUserRolesinRemoteV1 = new TreeSet<>();
+               if (externalApp != null) {
+                        appBaseUri = (type == SystemType.APPLICATION) ? externalApp.getAppRestEndpoint() : "";
+               }
+               if(appBaseUri != null && appBaseUri.endsWith("/api")){
+                       for(EcompRole eprole :updatedUserRolesinRemote)
+                       {
+                               RemoteRoleV1 role = new RemoteRoleV1();
+                               role.setId(eprole.getId());
+                               role.setName(eprole.getName());
+                               updatedUserRolesinRemoteV1.add(role);
+                       }
+                       userRolesAsString = mapper.writeValueAsString(updatedUserRolesinRemoteV1);
+               }
                applicationsRestClientService.post(EcompRole.class, appId, userRolesAsString,
                                String.format("/user/%s/roles", userId));
                // TODO: We should add code that verifies that the post operation did
@@ -759,7 +775,7 @@ public class UserRolesCommonServiceImpl  {
        /*
         * (non-Javadoc)
         * 
-        * @see org.openecomp.portalapp.portal.service.UserRolesService#
+        * @see org.onap.portalapp.portal.service.UserRolesService#
         * importRolesFromRemoteApplication(java.lang.Long)
         */
        public List<EPRole> importRolesFromRemoteApplication(Long appId) throws HTTPException {
@@ -768,7 +784,7 @@ public class UserRolesCommonServiceImpl  {
                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
+                       // onap 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);
@@ -851,9 +867,9 @@ public class UserRolesCommonServiceImpl  {
        /*
         * (non-Javadoc)
         * 
-        * @see org.openecomp.portalapp.portal.service.UserRolesService#
-        * setAppWithUserRoleStateForUser(org.openecomp.portalapp.portal.domain.
-        * EPUser, org.openecomp.portalapp.portal.transport.AppWithRolesForUser)
+        * @see org.onap.portalapp.portal.service.UserRolesService#
+        * setAppWithUserRoleStateForUser(org.onap.portalapp.portal.domain.
+        * EPUser, org.onap.portalapp.portal.transport.AppWithRolesForUser)
         */
        public boolean setAppWithUserRoleStateForUser(EPUser user, AppWithRolesForUser newAppRolesForUser) {
                boolean result = false;
@@ -969,18 +985,7 @@ public class UserRolesCommonServiceImpl  {
                        ObjectMapper mapper = new ObjectMapper();
                        HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
                        HttpEntity<String> getUserRolesEntity = new HttpEntity<>(headers);
-                       logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to external system to get current user roles");
-                       ResponseEntity<String> getResponse = template
-                                       .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
-                                                       + "roles/user/" + name, HttpMethod.GET, getUserRolesEntity, String.class);
-                       if (getResponse.getStatusCode().value() == 200) {
-                               logger.debug(EELFLoggerDelegate.debugLogger, "updateUserRolesInExternalSystem: Finished GET user roles from external system and received user roles {}",
-                                               getResponse.getBody());
-
-                       }else{
-                               logger.error(EELFLoggerDelegate.errorLogger, "updateUserRolesInExternalSystem: Failed GET user roles from external system and received user roles {}",getResponse.getBody() );
-                               EPLogUtil.logExternalAuthAccessAlarm(logger, getResponse.getStatusCode());
-                       }
+                       ResponseEntity<String> getResponse = externalAccessRolesService.getUserRolesFromExtAuthSystem(name, getUserRolesEntity);
                        List<ExternalAccessUserRoleDetail> userRoleDetailList = new ArrayList<>();
                        String res = getResponse.getBody();
                        JSONObject jsonObj = null;
@@ -1572,7 +1577,7 @@ public class UserRolesCommonServiceImpl  {
        /*
         * (non-Javadoc)
         * 
-        * @see org.openecomp.portalapp.portal.service.UserRolesService#
+        * @see org.onap.portalapp.portal.service.UserRolesService#
         * getAppRolesForUser(java.lang.Long, java.lang.String)
         */
        @SuppressWarnings("unchecked")
@@ -1581,14 +1586,14 @@ public class UserRolesCommonServiceImpl  {
                List<RoleInAppForUser> rolesInAppForUser = null;
                EPApp app = appsService.getApp(appId);
                try {
-                       // for ecomp portal app, no need to make a remote call
+                       // for onap portal app, no need to make a remote call
                        List<Role> roleList = new ArrayList<>();
                        if (appId == PortalConstants.PORTAL_APP_ID) {           
                                if(app.getCentralAuth()){
                                        List<CentralV2Role> cenRoleList = externalAccessRolesService.getRolesForApp(app.getUebKey());
                                        for(CentralV2Role cenRole : cenRoleList){
                                                Role role = new Role();
-                                               role.setActive(cenRole.isActive());
+                                               role.setActive(cenRole.getActive());
                                                role.setId(cenRole.getId());
                                                role.setName(cenRole.getName());
                                                role.setPriority(cenRole.getPriority());
@@ -1606,7 +1611,7 @@ public class UserRolesCommonServiceImpl  {
                                                        activeRoleList.add(role);
                                                }
                                        }
-                                               
+                                               
                                }
                                EPUser localUser  = getUserFromApp(userId, app, applicationsRestClientService);
                                // If localUser does not exists return roles
@@ -1623,7 +1628,9 @@ public class UserRolesCommonServiceImpl  {
                        EcompRole[] appRoles = null;
                        List<EcompRole> roles = new ArrayList<>();
                        if(app.getCentralAuth()){
-                               List<EPRole> applicationRoles = dataAccessService.getList(EPRole.class, " where app_id = "+app.getId()+ " and active_yn = 'Y'", null, null);;
+                               final Map<String, Long> appParams =  new HashMap<>();
+                               appParams.put("appId", app.getId());
+                               List<EPRole> applicationRoles = dataAccessService.executeNamedQuery("getActiveRolesOfApplication", appParams, null);
                                for(EPRole role : applicationRoles){
                                        EcompRole ecompRole = new EcompRole();
                                        ecompRole.setId(role.getId());
@@ -1634,7 +1641,7 @@ public class UserRolesCommonServiceImpl  {
                        } else{
                                appRoles = applicationsRestClientService.get(EcompRole[].class, appId, "/roles");
                        }
-                       // Test this error case, for generating an internal Ecomp Portal
+                       // Test this error case, for generating an internal ONAP Portal
                        // error
                        // EcompRole[] appRoles = null;
                        // If there is an exception in the rest client api, then null will
@@ -1739,10 +1746,11 @@ public class UserRolesCommonServiceImpl  {
                return result;
        }
 
+       @SuppressWarnings("unchecked")
        public FieldsValidator putUserAppRolesRequest(AppWithRolesForUser userAppRolesData, EPUser user) {
                FieldsValidator fieldsValidator = new FieldsValidator();
                final Map<String, Long> params = new HashMap<>();
-               EPUserAppRoles  appRole= new EPUserAppRoles();
+               List<EPUserAppRoles>  appRole= null;
                try {
                        logger.error(EELFLoggerDelegate.errorLogger,"Should not be reached here, still the endpoint is yet to be defined");
                        boolean result = postUserRolesToMylogins(userAppRolesData, applicationsRestClientService, userAppRolesData.appId, user.getId());
@@ -1762,13 +1770,15 @@ public class UserRolesCommonServiceImpl  {
                                Boolean isAppliedVal = userAppRoles.isApplied;
                                params.put("appRoleId", userAppRoles.roleId);                           
                                if (isAppliedVal) {
-                                       appRole = (EPUserAppRoles) dataAccessService.executeNamedQuery("appRoles", params, null).get(0);
-                                       EPUserAppRolesRequestDetail epAppRoleDetail = new EPUserAppRolesRequestDetail();
-                                       epAppRoleDetail.setReqRoleId(appRole.getRoleId());
-                                       epAppRoleDetail.setReqType("P");
-                                       epAppRoleDetail.setEpRequestIdData(epAppRolesRequestData);
-                                       dataAccessService.saveDomainObject(epAppRoleDetail, null);
-                                       }                       
+                                       appRole = (List<EPUserAppRoles>) dataAccessService.executeNamedQuery("appRoles", params, null);
+                                       if (!appRole.isEmpty()) {
+                                               EPUserAppRolesRequestDetail epAppRoleDetail = new EPUserAppRolesRequestDetail();
+                                               epAppRoleDetail.setReqRoleId(appRole.get(0).getRoleId());
+                                               epAppRoleDetail.setReqType("P");
+                                               epAppRoleDetail.setEpRequestIdData(epAppRolesRequestData);
+                                               dataAccessService.saveDomainObject(epAppRoleDetail, null);
+                                       }
+                               }                       
                        }
                        epAppRolesRequestData.setEpRequestIdDetail(appRoleDetails);
                        fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
@@ -1831,9 +1841,10 @@ public class UserRolesCommonServiceImpl  {
        /*
         * (non-Javadoc)
         * 
-        * @see org.openecomp.portalapp.portal.service.UserRolesService#
+        * @see org.onap.portalapp.portal.service.UserRolesService#
         * getCachedAppRolesForUser(java.lang.Long, java.lang.Long)
         */
+       @SuppressWarnings("deprecation")
        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);