Null check for ClientResponse in PolicyUril.java
[portal.git] / ecomp-portal-BE-common / src / main / java / org / openecomp / portalapp / portal / service / PortalAdminServiceImpl.java
index 0963f04..bc4c339 100644 (file)
@@ -1,21 +1,39 @@
 /*-
- * ================================================================================
- * 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.
+ * ============LICENSE_START==========================================
+ * ONAP Portal
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software except in compliance with the License.
  * You may obtain a copy of the License at
- * 
- *      http://www.apache.org/licenses/LICENSE-2.0
- * 
+ *
+ *             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.
- * ================================================================================
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *             https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
  */
 package org.openecomp.portalapp.portal.service;
 
@@ -29,25 +47,34 @@ import javax.servlet.http.HttpServletResponse;
 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.EPUser;
 import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog;
+import org.openecomp.portalapp.portal.transport.ExternalAccessUser;
 import org.openecomp.portalapp.portal.transport.FieldsValidator;
 import org.openecomp.portalapp.portal.transport.PortalAdmin;
 import org.openecomp.portalapp.portal.transport.PortalAdminUserRole;
 import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties;
 import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
+import org.openecomp.portalapp.portal.utils.PortalConstants;
 import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
 import org.openecomp.portalsdk.core.service.DataAccessService;
 import org.openecomp.portalsdk.core.util.SystemProperties;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.context.annotation.EnableAspectJAutoProxy;
+import org.springframework.http.HttpEntity;
+import org.springframework.http.HttpHeaders;
+import org.springframework.http.HttpMethod;
 import org.springframework.stereotype.Service;
+import org.springframework.web.client.RestTemplate;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
 
 @Service("portalAdminService")
 @org.springframework.context.annotation.Configuration
 @EnableAspectJAutoProxy
 @EPMetricsLog
-public class PortalAdminServiceImpl implements PortalAdminService {
+public class PortalAdminServiceImpl implements PortalAdminService {    
 
        private String SYS_ADMIN_ROLE_ID = "1";
        private String ECOMP_APP_ID = "1";
@@ -60,7 +87,11 @@ public class PortalAdminServiceImpl implements PortalAdminService {
        private DataAccessService dataAccessService;
        @Autowired
        SearchService searchService;
-
+       @Autowired
+       private EPAppService epAppService;
+       
+       RestTemplate template = new RestTemplate();
+       
        @PostConstruct
        private void init() {
                SYS_ADMIN_ROLE_ID = SystemProperties.getProperty(SystemProperties.SYS_ADMIN_ROLE_ID);
@@ -77,9 +108,7 @@ public class PortalAdminServiceImpl implements PortalAdminService {
                        logger.debug(EELFLoggerDelegate.debugLogger, "getPortalAdmins was successful");
                        return portalAdmins;
                } catch (Exception e) {
-                       logger.error(EELFLoggerDelegate.errorLogger,
-                                       "Exception occurred while performing getPortalAdmins operation, Details: "
-                                                       + EcompPortalUtils.getStackTrace(e));
+                       logger.error(EELFLoggerDelegate.errorLogger, "getPortalAdmins failed", e);
                        return null;
                }
        }
@@ -130,10 +159,14 @@ public class PortalAdminServiceImpl implements PortalAdminService {
                                }
 
                                transaction.commit();
-                               result = true;
+                               // Add role in the external central auth system
+                               if(user != null)
+                                       result = addPortalAdminInExternalCentralAuth(user.getOrgUserId(), PortalConstants.PORTAL_ADMIN_ROLE);
+                               else
+                                       logger.error(EELFLoggerDelegate.errorLogger, "PortalAdminServiceImpl createPortalAdmin: failed to Add role in the external central auth system since User obj is null" );
                        } catch (Exception e) {
-                               EcompPortalUtils.rollbackTransaction(transaction, "createPortalAdmin rollback, exception = " + e);
-                               logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
+                               logger.error(EELFLoggerDelegate.errorLogger, "createPortalAdmin failed", e);
+                               EcompPortalUtils.rollbackTransaction(transaction, "createPortalAdmin rollback, exception = " + e.toString());
                        } finally {
                                EcompPortalUtils.closeLocalSession(localSession, "createPortalAdmin");
                        }
@@ -147,6 +180,42 @@ public class PortalAdminServiceImpl implements PortalAdminService {
                }
                return fieldsValidator;
        }
+       
+       private boolean addPortalAdminInExternalCentralAuth(String loginId, String portalAdminRole){
+               boolean result = false;
+               try{
+                       String name = "";
+                       if (EPCommonSystemProperties.containsProperty(
+                                       EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) {
+                               name = loginId + SystemProperties
+                                               .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
+                       }
+                       EPApp app = epAppService.getApp(PortalConstants.PORTAL_APP_ID);
+                       String extRole = app.getNameSpace()+"."+portalAdminRole.replaceAll(" ", "_");
+                       ObjectMapper addUserRoleMapper = new ObjectMapper();
+                       ExternalAccessUser extUser = new ExternalAccessUser(name, extRole);
+                       String userRole = addUserRoleMapper.writeValueAsString(extUser);
+                       HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
+
+                       HttpEntity<String> addUserRole = new HttpEntity<>(userRole, headers);
+                       template.exchange(
+                                       SystemProperties.getProperty(
+                                                       EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
+                                                       + "userRole",
+                                       HttpMethod.POST, addUserRole, String.class);
+                       result = true;
+               } catch (Exception e) {
+                       // This happens only if role already exists in external central access system but not in local DB thats where we logging here
+                       if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
+                               result = true;
+                               logger.debug(EELFLoggerDelegate.debugLogger, "Portal Admin role already exists", e.getMessage());
+                       } else{
+                               logger.error(EELFLoggerDelegate.errorLogger, "Failed to add Portal Admin role ", e);
+                               result = false;
+                       }
+               }
+               return result;
+       }
 
        public FieldsValidator deletePortalAdmin(Long userId) {
                FieldsValidator fieldsValidator = new FieldsValidator();
@@ -161,10 +230,10 @@ public class PortalAdminServiceImpl implements PortalAdminService {
                        dataAccessService.deleteDomainObjects(PortalAdminUserRole.class,
                                        "user_id='" + userId + "' AND role_id='" + SYS_ADMIN_ROLE_ID + "'", null);
                        transaction.commit();
-                       result = true;
+                       result = deletePortalAdminInExternalCentralAuth(userId, PortalConstants.PORTAL_ADMIN_ROLE);
                } catch (Exception e) {
-                       EcompPortalUtils.rollbackTransaction(transaction, "deletePortalAdmin rollback, exception = " + e);
-                       logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
+                       logger.error(EELFLoggerDelegate.errorLogger, "deletePortalAdmin failed", e);
+                       EcompPortalUtils.rollbackTransaction(transaction, "deletePortalAdmin rollback, exception = " + e.toString());
                } finally {
                        EcompPortalUtils.closeLocalSession(localSession, "deletePortalAdmin");
                }
@@ -177,6 +246,40 @@ public class PortalAdminServiceImpl implements PortalAdminService {
                return fieldsValidator;
        }
 
+       
+       @SuppressWarnings("unchecked")
+       private boolean deletePortalAdminInExternalCentralAuth(Long userId, String portalAdminRole){
+               boolean result = false;
+               try{                                                                    
+                       String name = "";
+                       List<EPUser> localUserList = dataAccessService.getList(EPUser.class, " where user_id = " + userId,
+                                       null, null);
+                       if (EPCommonSystemProperties.containsProperty(
+                                       EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) {
+                               name = localUserList.get(0).getOrgUserId() + SystemProperties
+                                               .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
+                       }
+                       EPApp app = epAppService.getApp(PortalConstants.PORTAL_APP_ID);
+                       String extRole = app.getNameSpace()+"."+portalAdminRole.replaceAll(" ", "_");
+                       HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
+                       HttpEntity<String> addUserRole = new HttpEntity<>(headers);
+                       template.exchange(
+                                       SystemProperties.getProperty(
+                                                       EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
+                                                       + "userRole/"+name+"/"+extRole,
+                                       HttpMethod.DELETE, addUserRole, String.class);
+                       result = true;
+               } catch (Exception e) {
+                       if (e.getMessage().equalsIgnoreCase("404 Not Found")) {
+                               logger.debug(EELFLoggerDelegate.debugLogger, "Portal Admin role already deleted or may not be found", e.getMessage());
+                       } else{
+                               logger.error(EELFLoggerDelegate.errorLogger, "Failed to add Portal Admin role ", e);
+                               result = false;
+                       }
+               }
+               return result;
+       }
+       
        private void logQuery(String sql) {
                logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
        }
@@ -198,9 +301,7 @@ public class PortalAdminServiceImpl implements PortalAdminService {
                        return true;
 
                } catch (Exception e) {
-                       logger.error(EELFLoggerDelegate.errorLogger,
-                                       "Exception occurred while performing isLoggedInUserPortalAdmin operation, Details: "
-                                                       + EcompPortalUtils.getStackTrace(e));
+                       logger.error(EELFLoggerDelegate.errorLogger, "isLoggedInUserPortalAdmin failed", e);
                        return false;
                }
        }