PersUserWidgetServiceAOP and tests up 44/100244/1
authorDominik Mizyn <d.mizyn@samsung.com>
Mon, 13 Jan 2020 11:45:18 +0000 (12:45 +0100)
committerDominik Mizyn <d.mizyn@samsung.com>
Mon, 13 Jan 2020 11:52:13 +0000 (12:52 +0100)
PersUserWidgetServiceAOP tests WidgetCatalogPersonalization object
requied in
org.onap.portal.service.PersUserWidgetService.setPersUserAppValue()
method

Issue-ID: PORTAL-710
Change-Id: I7e66b05296ef7ceea0093ef98684dc80303c99a0
Signed-off-by: Dominik Mizyn <d.mizyn@samsung.com>
portal-BE/src/main/java/org/onap/portal/aop/service/PersUserWidgetServiceAOP.java
portal-BE/src/main/java/org/onap/portal/aop/service/WidgetServiceAOP.java
portal-BE/src/main/java/org/onap/portal/controller/WidgetsController.java
portal-BE/src/main/java/org/onap/portal/domain/db/ep/EpPersUserWidgetSel.java
portal-BE/src/main/java/org/onap/portal/domain/db/ep/EpWidgetCatalog.java
portal-BE/src/main/java/org/onap/portal/domain/dto/transport/WidgetCatalogPersonalization.java
portal-BE/src/main/java/org/onap/portal/service/PersUserWidgetService.java
portal-BE/src/main/java/org/onap/portal/service/persUserWidgetSel/EpPersUserWidgetSelService.java
portal-BE/src/main/java/org/onap/portal/service/user/FnUserService.java
portal-BE/src/main/java/org/onap/portal/service/widget/WidgetService.java
portal-BE/src/test/java/org/onap/portal/service/PersUserWidgetServiceTest.java [new file with mode: 0644]

index 7932661..904e070 100644 (file)
@@ -63,9 +63,10 @@ public class PersUserWidgetServiceAOP {
               this.dataValidator = dataValidator;
        }
 
-       @Before("execution(* org.onap.portal.service.PersUserWidgetService.setPersUserAppValue(..)) && args(user, personalization)")
-       public void setOnboardingWidget(FnUser user, WidgetCatalogPersonalization personalization) {
+       @Before("execution(* org.onap.portal.service.PersUserWidgetService.setPersUserAppValue(..)) && args(userId, personalization)")
+       public void setPersUserAppValue(final long userId, final WidgetCatalogPersonalization personalization) {
               if (!dataValidator.isValid(personalization)) {
+                     LOGGER.error("IllegalArgumentException for user " + userId);
                      throw new IllegalArgumentException(dataValidator.getConstraintViolationsString(personalization));
               }
        }
index c19d923..6902abb 100644 (file)
@@ -27,6 +27,7 @@ public class WidgetServiceAOP {
        @Before("execution(* org.onap.portal.service.widget.WidgetService.setOnboardingWidget(..)) && args(userId, onboardingWidget)")
        public void setOnboardingWidget(final Long userId, OnboardingWidget onboardingWidget) {
               if (!dataValidator.isValid(onboardingWidget)) {
+                     LOGGER.error("IllegalArgumentException for user " + userId + "method" + "setOnboardingWidget()");
                      throw new IllegalArgumentException(dataValidator.getConstraintViolationsString(onboardingWidget));
               }
        }
@@ -34,6 +35,7 @@ public class WidgetServiceAOP {
        @Before("execution(* org.onap.portal.service.widget.WidgetService.saveOne(..)) && args(widget)")
        public void saveOne(final FnWidget widget) {
               if (!dataValidator.isValid(widget)) {
+                     LOGGER.error("IllegalArgumentException");
                      throw new IllegalArgumentException(dataValidator.getConstraintViolationsString(widget));
               }
        }
index 5620204..2149463 100644 (file)
@@ -51,12 +51,11 @@ import org.onap.portal.domain.dto.transport.OnboardingWidget;
 import org.onap.portal.domain.dto.transport.WidgetCatalogPersonalization;
 import org.onap.portal.logging.aop.EPAuditLog;
 import org.onap.portal.service.PersUserWidgetService;
-import org.onap.portal.service.widget.WidgetService;
 import org.onap.portal.service.user.FnUserService;
+import org.onap.portal.service.widget.WidgetService;
 import org.onap.portal.utils.EcompPortalUtils;
 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
 import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.EnableAspectJAutoProxy;
 import org.springframework.http.MediaType;
 import org.springframework.security.access.prepost.PreAuthorize;
 import org.springframework.web.bind.annotation.DeleteMapping;
@@ -113,7 +112,7 @@ public class WidgetsController {
        public FieldsValidator putOnboardingWidget(Principal principal, @PathVariable("widgetId") Long widgetId,
                @RequestBody OnboardingWidget onboardingWidget, HttpServletResponse response) {
               FnUser user = fnUserService.loadUserByUsername(principal.getName());
-              FieldsValidator fieldsValidator = null;
+              FieldsValidator fieldsValidator;
 
               assert onboardingWidget != null;
               onboardingWidget.setId(widgetId);
@@ -183,7 +182,7 @@ public class WidgetsController {
               try {
                      assert persRequest != null;
                      persUserWidgetService
-                             .setPersUserAppValue(user, persRequest);
+                             .setPersUserAppValue(user.getId(), persRequest);
               } catch (IllegalArgumentException iae) {
                      logger.error(EELFLoggerDelegate.errorLogger, "Failed in putAppCatalogSelection", iae);
                      response.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE, iae.getMessage());
index 2d4c76f..71d8da0 100644 (file)
@@ -97,13 +97,13 @@ public class EpPersUserWidgetSel extends DomainVo implements Serializable {
        private FnUser userId;
        @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.MERGE)
        @JoinColumn(name = "widget_id", nullable = false)
-       @NotNull
+       @NotNull(message = "widgetId may not be null")
        @Valid
        private EpWidgetCatalog widgetId;
        @Column(name = "status_cd", length = 1, nullable = false)
        @Size(max = 1)
-       @NotNull
-       @SafeHtml
+       @NotNull(message = "status may not be null")
+       @SafeHtml(message = "status must be safeHtml")
        private String statusCd;
 
 }
index 0aee615..cd906cf 100644 (file)
@@ -93,7 +93,7 @@ public class EpWidgetCatalog implements Serializable {
        @Size(max = 100)
        @NotNull
        @SafeHtml
-       private String wdgName;
+       private String wdgName = "?";
        @Column(name = "service_id", length = 11)
        @Digits(integer = 11, fraction = 0)
        private Long serviceId;
@@ -105,10 +105,10 @@ public class EpWidgetCatalog implements Serializable {
        @Size(max = 256)
        @NotNull
        @SafeHtml
-       private String wdgFileLoc;
+       private String wdgFileLoc = "?";
        @Column(name = "all_user_flag", length = 1, columnDefinition = "boolean default false", nullable = false)
        @NotNull
-       private Boolean allUserFlag;
+       private Boolean allUserFlag = false;
        @ManyToMany(cascade = CascadeType.MERGE, fetch = FetchType.LAZY)
        @JoinTable(
                name = "ep_widget_microservice",
index d9053f0..3625fed 100644 (file)
@@ -45,16 +45,18 @@ import lombok.AllArgsConstructor;
 import lombok.Getter;
 import lombok.NoArgsConstructor;
 import lombok.Setter;
+import lombok.ToString;
 
 @Getter
 @Setter
+@ToString
 @NoArgsConstructor
 @AllArgsConstructor
 public class WidgetCatalogPersonalization {
 
-       @NotNull
+       @NotNull(message = "widgetId may not be null")
        private Long widgetId;
-       @NotNull
+       @NotNull(message = "select may not be null")
        private Boolean select;
 
 }
index 2a5d0ae..afaccfd 100644 (file)
@@ -45,65 +45,69 @@ import java.util.List;
 import java.util.stream.Collectors;
 import org.onap.portal.domain.db.ep.EpPersUserWidgetSel;
 import org.onap.portal.domain.db.ep.EpWidgetCatalog;
-import org.onap.portal.domain.db.fn.FnUser;
 import org.onap.portal.domain.dto.ecomp.PersUserWidgetSelection;
 import org.onap.portal.domain.dto.transport.WidgetCatalogPersonalization;
 import org.onap.portal.service.persUserWidgetSel.EpPersUserWidgetSelService;
+import org.onap.portal.service.user.FnUserService;
 import org.onap.portal.service.widgetCatalog.EpWidgetCatalogService;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 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
 @Transactional
+@EnableAspectJAutoProxy
 public class PersUserWidgetService {
 
        private static final Logger LOGGER = LoggerFactory.getLogger(PersUserWidgetService.class);
        private final EpPersUserWidgetSelService epPersUserWidgetSelService;
        private final EpWidgetCatalogService epWidgetCatalogService;
+       private final FnUserService fnUserService;
 
        @Autowired
        public PersUserWidgetService(final EpPersUserWidgetSelService epPersUserWidgetSelService,
-               final EpWidgetCatalogService epWidgetCatalogService) {
+           final EpWidgetCatalogService epWidgetCatalogService,
+           FnUserService fnUserService) {
               this.epPersUserWidgetSelService = epPersUserWidgetSelService;
               this.epWidgetCatalogService = epWidgetCatalogService;
+              this.fnUserService = fnUserService;
        }
 
-       public void setPersUserAppValue(FnUser user, WidgetCatalogPersonalization personalization) {
-              List<PersUserWidgetSelection> persList = getUserWidgetSelction(user, personalization.getWidgetId());
+       public void setPersUserAppValue(final long userId, final WidgetCatalogPersonalization personalization) {
+              List<PersUserWidgetSelection> persList = getUserWidgetSelction(userId, personalization.getWidgetId());
               LOGGER.info("Error: " + persList.size());
               // Key constraint limits to 1 row
               PersUserWidgetSelection persRow;
               if (persList.size() == 1) {
                      persRow = persList.get(0);
               } else {
-                     persRow = new PersUserWidgetSelection(null, user.getId(), personalization.getWidgetId(), null);
+                     persRow = new PersUserWidgetSelection(null, userId, personalization.getWidgetId(), null);
               }
-
               if (persRow.getId() != null) {
                      epPersUserWidgetSelService.deleteById(persRow.getId());
               }
-
               persRow.setStatusCode(personalization.getSelect() ? "S" : "H"); // Show / Hide
               EpPersUserWidgetSel epPersUserWidgetSel = new EpPersUserWidgetSel();
-              epPersUserWidgetSel.setUserId(user);
-              epPersUserWidgetSel.setWidgetId(
-                      epWidgetCatalogService.findById(personalization.getWidgetId()).orElse(new EpWidgetCatalog()));
+              epPersUserWidgetSel.setUserId(fnUserService.getUser(userId).get());
+              EpWidgetCatalog catalog = epWidgetCatalogService.findById(personalization.getWidgetId()).orElse(new EpWidgetCatalog());
+              epWidgetCatalogService.save(catalog);
+              epPersUserWidgetSel.setWidgetId(catalog);
               epPersUserWidgetSelService.saveAndFlush(epPersUserWidgetSel);
        }
 
-       private List<PersUserWidgetSelection> getUserWidgetSelction(FnUser user, Long widgetId) {
+       private List<PersUserWidgetSelection> getUserWidgetSelction(final long userId, final long widgetId) {
               return epPersUserWidgetSelService
-                      .getEpPersUserWidgetSelForUserIdAndWidgetId(user.getId(), widgetId)
+                      .getEpPersUserWidgetSelForUserIdAndWidgetId(userId, widgetId)
                       .orElse(new ArrayList<>())
                       .stream()
                       .map(this::epPersUserWidgetSelToPersUserWidgetSelection)
                       .collect(Collectors.toList());
        }
 
-       private PersUserWidgetSelection epPersUserWidgetSelToPersUserWidgetSelection(EpPersUserWidgetSel widgetSel) {
+       private PersUserWidgetSelection epPersUserWidgetSelToPersUserWidgetSelection(final EpPersUserWidgetSel widgetSel) {
               return new PersUserWidgetSelection(widgetSel.getId(), widgetSel.getUserId().getId(),
                       widgetSel.getWidgetId().getWidgetId(), widgetSel.getStatusCd());
        }
index cd940d1..307ef28 100644 (file)
@@ -2,6 +2,7 @@ package org.onap.portal.service.persUserWidgetSel;
 
 import org.onap.portal.domain.db.ep.EpPersUserWidgetSel;
 import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.EnableAspectJAutoProxy;
 import org.springframework.stereotype.Service;
 
 import java.util.ArrayList;
@@ -9,24 +10,25 @@ import java.util.List;
 import java.util.Optional;
 
 @Service
+@EnableAspectJAutoProxy
 public class EpPersUserWidgetSelService {
 
     private final EpPersUserWidgetSelDao epPersUserWidgetSelDao;
 
     @Autowired
-    public EpPersUserWidgetSelService(EpPersUserWidgetSelDao epPersUserWidgetSelDao) {
+    public EpPersUserWidgetSelService(final EpPersUserWidgetSelDao epPersUserWidgetSelDao) {
         this.epPersUserWidgetSelDao = epPersUserWidgetSelDao;
     }
 
-    public void deleteById(Long id) {
+    public void deleteById(final long id) {
         epPersUserWidgetSelDao.deleteById(id);
     }
 
-    public EpPersUserWidgetSel saveAndFlush(EpPersUserWidgetSel epPersUserWidgetSel) {
+    public EpPersUserWidgetSel saveAndFlush(final EpPersUserWidgetSel epPersUserWidgetSel) {
         return epPersUserWidgetSelDao.saveAndFlush(epPersUserWidgetSel);
     }
 
-    public Optional<List<EpPersUserWidgetSel>> getEpPersUserWidgetSelForUserIdAndWidgetId(Long id, Long widgetId) {
+    public Optional<List<EpPersUserWidgetSel>> getEpPersUserWidgetSelForUserIdAndWidgetId(final long id, final long widgetId) {
         return epPersUserWidgetSelDao.getEpPersUserWidgetSelForUserIdAndWidgetId(id, widgetId);
     }
 }
index 912453c..23732d6 100644 (file)
@@ -55,7 +55,7 @@ import org.springframework.transaction.annotation.Transactional;
 @Transactional
 public class FnUserService implements UserDetailsService {
 
-       private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(FnUserService.class);
+       private final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(FnUserService.class);
 
        private final FnUserDao fnUserDao;
 
@@ -64,10 +64,6 @@ public class FnUserService implements UserDetailsService {
               this.fnUserDao = fnUserDao;
        }
 
-       public FnUser saveFnUser(final FnUser fnUser) {
-              return fnUserDao.save(fnUser);
-       }
-
        @Override
        public FnUser loadUserByUsername(final String username) throws UsernameNotFoundException {
               Optional<FnUser> fnUser = fnUserDao.findByLoginId(username);
@@ -78,6 +74,10 @@ public class FnUserService implements UserDetailsService {
               }
        }
 
+       public FnUser saveFnUser(final FnUser fnUser) {
+              return fnUserDao.save(fnUser);
+       }
+
        public Optional<FnUser> getUser(final Long id) {
               return Optional.of(fnUserDao.getOne(id));
        }
@@ -90,7 +90,6 @@ public class FnUserService implements UserDetailsService {
               return fnUserDao.getUsersByOrgIds(orgIds).orElse(new ArrayList<>());
        }
 
-
        public List<FnUser> getActiveUsers() {
               return fnUserDao.getActiveUsers().orElse(new ArrayList<>());
        }
@@ -107,15 +106,15 @@ public class FnUserService implements UserDetailsService {
               return fnUserDao.findAll();
        }
 
-       public List<FnUser> saveAll(List<FnUser> fnUsers) {
+       public List<FnUser> saveAll(final List<FnUser> fnUsers) {
               return fnUserDao.saveAll(fnUsers);
        }
 
-       public FnUser save(FnUser user) {
+       public FnUser save(final FnUser user) {
               return fnUserDao.save(user);
        }
 
-       public void delete(FnUser user) {
+       public void delete(final FnUser user) {
               fnUserDao.delete(user);
        }
 }
index 1d4fdd6..9f515d2 100644 (file)
@@ -67,8 +67,8 @@ import org.springframework.transaction.annotation.Transactional;
 @EnableAspectJAutoProxy
 public class WidgetService {
 
-       private final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(WidgetService.class);
-       private final Long ACCOUNT_ADMIN_ROLE_ID = 999L;
+       private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(WidgetService.class);
+       private static final Long ACCOUNT_ADMIN_ROLE_ID = 999L;
 
        private static final String baseSqlToken =
            " new org.onap.portal.domain.dto.transport.OnboardingWidget("
@@ -76,15 +76,28 @@ public class WidgetService {
                + "app.APP_NAME,widget.WDG_WIDTH,widget.WDG_HEIGHT,"
                + "widget.WDG_URL, widget.WIDGET_ID,widget.WDG_NAME,widget.APP_ID,app.APP_NAME,widget.WDG_WIDTH,widget.WDG_HEIGHT,widget.WDG_URL) from FN_WIDGET widget join FN_APP app ON widget.APP_ID = app.APP_ID";
 
+       private static final String sqlWidgetsForAllApps = "SELECT" + baseSqlToken;
+
+       private static final String sqlWidgetsForAllAppsWhereUserIsAdmin =
+              "SELECT" + baseSqlToken
+                  + " join FN_USER_ROLE ON FN_USER_ROLE.APP_ID = app.APP_ID where FN_USER_ROLE.USER_ID = :USERID AND FN_USER_ROLE.ROLE_ID = "
+                  + ACCOUNT_ADMIN_ROLE_ID;
+
+       private static final String sqlWidgetsForAllAppsWhereUserHasAnyRole =
+              "SELECT DISTINCT" + baseSqlToken
+                  + " join FN_USER_ROLE ON FN_USER_ROLE.APP_ID = app.APP_ID where FN_USER_ROLE.USER_ID = "
+                  + ":USERID";
+
        private static final String urlField = "url";
-       private static final Long DUBLICATED_FIELD_VALUE_ECOMP_ERROR = new Long(
-           EPCommonSystemProperties.DUBLICATED_FIELD_VALUE_ECOMP_ERROR);
+       private static final Long DUBLICATED_FIELD_VALUE_ECOMP_ERROR = Long
+           .valueOf(EPCommonSystemProperties.DUBLICATED_FIELD_VALUE_ECOMP_ERROR);
        private static final String nameField = "name";
        private final AdminRolesService adminRolesService;
        private final EntityManager entityManager;
        private final FnWidgetDao fnWidgetDao;
        private final FnUserService fnUserService;
        private final FnUserRoleService fnUserRoleService;
+
        private static final Object syncRests = new Object();
 
        @Autowired
@@ -106,16 +119,16 @@ public class WidgetService {
        public List<OnboardingWidget> getOnboardingWidgets(final String orgUserId, final long userId,  final boolean managed) {
               FnUser user = fnUserService.getUser(userId).get();
               if (adminRolesService.isSuperAdmin(orgUserId)){
-                     return entityManager.createQuery(sqlWidgetsForAllApps(), OnboardingWidget.class).getResultList();
+                     return entityManager.createQuery(sqlWidgetsForAllApps, OnboardingWidget.class).getResultList();
               } else if (managed) {
                      if (adminRolesService.isAccountAdmin(user.getId(), user.getOrgUserId(), user.getUserApps())) {
                             return entityManager
-                                .createQuery(sqlWidgetsForAllAppsWhereUserIsAdmin(), OnboardingWidget.class)
+                                .createQuery(sqlWidgetsForAllAppsWhereUserIsAdmin, OnboardingWidget.class)
                                 .setParameter("USERID", userId).getResultList();
                      }
               } else if (adminRolesService.isAccountAdmin(user.getId(), user.getOrgUserId(), user.getUserApps()) || adminRolesService.isUser(userId)) {
                      return entityManager
-                         .createQuery(sqlWidgetsForAllAppsWhereUserHasAnyRole(), OnboardingWidget.class)
+                         .createQuery(sqlWidgetsForAllAppsWhereUserHasAnyRole, OnboardingWidget.class)
                          .setParameter("USERID", userId).getResultList();
               }
               return new ArrayList<>();
@@ -144,27 +157,11 @@ public class WidgetService {
               return fieldsValidator;
        }
 
-       public Optional<FnWidget> getOne(Long id) {
+       public Optional<FnWidget> getOne(final long id) {
               return Optional.of(fnWidgetDao.getOne(id));
        }
 
-       private String sqlWidgetsForAllApps() {
-              return "SELECT" + baseSqlToken;
-       }
-
-       private String sqlWidgetsForAllAppsWhereUserIsAdmin() {
-              return "SELECT" + baseSqlToken
-                  + " join FN_USER_ROLE ON FN_USER_ROLE.APP_ID = app.APP_ID where FN_USER_ROLE.USER_ID = :USERID AND FN_USER_ROLE.ROLE_ID = "
-                  + ACCOUNT_ADMIN_ROLE_ID;
-       }
-
-       private String sqlWidgetsForAllAppsWhereUserHasAnyRole() {
-              return "SELECT DISTINCT" + baseSqlToken
-                  + " join FN_USER_ROLE ON FN_USER_ROLE.APP_ID = app.APP_ID where FN_USER_ROLE.USER_ID = "
-                  + ":USERID";
-       }
-
-       private FieldsValidator updateOrSaveWidget(boolean superAdmin, Long userId, OnboardingWidget onboardingWidget) {
+       private FieldsValidator updateOrSaveWidget(final boolean superAdmin, final long userId, final OnboardingWidget onboardingWidget) {
               FieldsValidator fieldsValidator = new FieldsValidator();
               if (!this.isUserAdminOfAppForWidget(superAdmin, userId, onboardingWidget.getAppId())) {
                      fieldsValidator.setHttpStatusCode((long) HttpServletResponse.SC_FORBIDDEN);
diff --git a/portal-BE/src/test/java/org/onap/portal/service/PersUserWidgetServiceTest.java b/portal-BE/src/test/java/org/onap/portal/service/PersUserWidgetServiceTest.java
new file mode 100644 (file)
index 0000000..3595205
--- /dev/null
@@ -0,0 +1,48 @@
+package org.onap.portal.service;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+import javax.transaction.Transactional;
+import org.junit.jupiter.api.Test;
+import org.junit.runner.RunWith;
+import org.onap.portal.domain.dto.transport.WidgetCatalogPersonalization;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.test.context.TestPropertySource;
+import org.springframework.test.context.junit4.SpringRunner;
+
+@RunWith(SpringRunner.class)
+@SpringBootTest
+@Transactional
+@TestPropertySource(locations = "classpath:test.properties")
+class PersUserWidgetServiceTest {
+
+    @Autowired
+    private PersUserWidgetService persUserWidgetService;
+
+    @Test
+    void setPersUserAppValueInvalidWidgetIdDataTest() {
+        WidgetCatalogPersonalization catalog = getWidgetCatalog();
+        catalog.setSelect(true);
+        try {
+            persUserWidgetService.setPersUserAppValue(1, catalog);
+        }catch (IllegalArgumentException e){
+            assertEquals("widgetId may not be null", e.getMessage());
+        }
+    }
+
+    @Test
+    void setPersUserAppValueInvalidSelectDataTest() {
+        WidgetCatalogPersonalization catalog = getWidgetCatalog();
+        catalog.setWidgetId(1L);
+        try {
+            persUserWidgetService.setPersUserAppValue(1, catalog);
+        }catch (IllegalArgumentException e){
+            assertEquals("select may not be null", e.getMessage());
+        }
+    }
+
+    private WidgetCatalogPersonalization getWidgetCatalog(){
+        return new WidgetCatalogPersonalization();
+    }
+}