diff --git a/src/main/java/net/geant/nmaas/portal/api/info/DashboardController.java b/src/main/java/net/geant/nmaas/portal/api/info/DashboardController.java index 2e423bde14dc0e2a9d60d0b7f6007ab906bbd3a4..540733ce0baa7c853cbeeac352c79303a3db9b8b 100644 --- a/src/main/java/net/geant/nmaas/portal/api/info/DashboardController.java +++ b/src/main/java/net/geant/nmaas/portal/api/info/DashboardController.java @@ -1,9 +1,7 @@ package net.geant.nmaas.portal.api.info; -import lombok.AllArgsConstructor; +import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; -import net.geant.nmaas.portal.api.domain.ContentView; -import net.geant.nmaas.portal.persistent.entity.Content; import net.geant.nmaas.portal.service.DashboardService; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.GetMapping; @@ -15,38 +13,35 @@ import org.springframework.web.bind.annotation.RestController; import java.time.OffsetDateTime; @RestController -@AllArgsConstructor @RequestMapping("/api/dashboard") +@RequiredArgsConstructor @Slf4j public class DashboardController { - private DashboardService dashboardService; + private final DashboardService dashboardService; @GetMapping("/admin") @PreAuthorize("hasRole('ROLE_SYSTEM_ADMIN')") - public DashboardView getDashboardAdmin( @RequestParam("startDate") OffsetDateTime startDate, - @RequestParam("end") OffsetDateTime endDate) { - checkDate(startDate,endDate); - DashboardView view = dashboardService.getSystemDashboard(startDate,endDate); - log.error("View : {}", view.toString()); - - return view; + public DashboardView getDashboardAdmin(@RequestParam("startDate") OffsetDateTime startDate, + @RequestParam("end") OffsetDateTime endDate) { + validateRequestedPeriod(startDate, endDate); + return dashboardService.getSystemDashboard(startDate, endDate); } @GetMapping("/domain/{id}") public DomainDashboardView getDashboardDomain(@PathVariable Long id) { - DomainDashboardView view = dashboardService.getSystemDomainDashboard(id); - log.error("View : {}", view.toString()); - return view; + return dashboardService.getDomainDashboard(id); } - private void checkDate(OffsetDateTime startDate, OffsetDateTime endDate) { - if(startDate == null || endDate == null) { + private void validateRequestedPeriod(OffsetDateTime startDate, OffsetDateTime endDate) { + if (startDate == null) { throw new IllegalArgumentException("Start date can not be null"); } - - if(startDate.isAfter(endDate)) { + if (endDate == null) { + throw new IllegalArgumentException("End date can not be null"); + } + if (startDate.isAfter(endDate)) { throw new IllegalArgumentException("Start date is after end date."); } } -} +} \ No newline at end of file diff --git a/src/main/java/net/geant/nmaas/portal/persistent/entity/AppInstance.java b/src/main/java/net/geant/nmaas/portal/persistent/entity/AppInstance.java index 2bfe5aedce3c7bd727032af4ccec95e5e421247c..2aa48cf5cf5e8f4b937c5e2e0d9040f73bacec0d 100644 --- a/src/main/java/net/geant/nmaas/portal/persistent/entity/AppInstance.java +++ b/src/main/java/net/geant/nmaas/portal/persistent/entity/AppInstance.java @@ -1,17 +1,5 @@ package net.geant.nmaas.portal.persistent.entity; -import lombok.AccessLevel; -import lombok.Getter; -import lombok.NoArgsConstructor; -import lombok.Setter; -import net.geant.nmaas.orchestration.Identifier; -import org.hibernate.annotations.JdbcType; -import org.hibernate.annotations.Type; -import org.hibernate.type.descriptor.jdbc.VarcharJdbcType; -import org.springframework.data.annotation.CreatedBy; -import org.springframework.data.annotation.CreatedDate; -import org.springframework.data.jpa.domain.support.AuditingEntityListener; - import jakarta.persistence.Basic; import jakarta.persistence.Column; import jakarta.persistence.Entity; @@ -23,6 +11,17 @@ import jakarta.persistence.Id; import jakarta.persistence.Lob; import jakarta.persistence.ManyToMany; import jakarta.persistence.ManyToOne; +import lombok.AccessLevel; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import net.geant.nmaas.orchestration.Identifier; +import org.hibernate.annotations.JdbcType; +import org.hibernate.type.descriptor.jdbc.VarcharJdbcType; +import org.springframework.data.annotation.CreatedBy; +import org.springframework.data.annotation.CreatedDate; +import org.springframework.data.jpa.domain.support.AuditingEntityListener; + import java.io.Serializable; import java.util.HashSet; import java.util.Set; @@ -34,74 +33,66 @@ import java.util.Set; @Setter public class AppInstance extends DomainAware implements Serializable { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - Long id; - - String name; - - @ManyToOne(fetch = FetchType.LAZY, optional = false) - Application application; - - @Basic(fetch = FetchType.LAZY) - @Lob - @JdbcType(VarcharJdbcType.class) - @Column(columnDefinition = "TEXT") - String configuration; - - @CreatedDate - @Column(name = "created_at", nullable = false, updatable = false) - Long createdAt; - - @CreatedBy - @ManyToOne(fetch = FetchType.LAZY) - private User owner; - - @Basic - Identifier internalId; - - @Basic - private boolean autoUpgradesEnabled; - - @Column(name = "previous_application_id") - private Long previousApplicationId; - - @ManyToMany(fetch = FetchType.LAZY) - private Set<User> members = new HashSet<>(); - - public AppInstance(Application application, Domain domain, String name, boolean autoUpgradesEnabled) { - this.application = application; - this.domain = domain; - this.name = name; - this.autoUpgradesEnabled = autoUpgradesEnabled; - } - - public AppInstance(Long id, Application application, Domain domain, String name, boolean autoUpgradesEnabled) { - this(application, domain, name, autoUpgradesEnabled); - this.id = id; - } - - public AppInstance(Application application, String name, Domain domain, User owner, boolean autoUpgradesEnabled) { - this(application, domain, name, autoUpgradesEnabled); - this.owner = owner; - } - - protected AppInstance(Long id, Application application, String name, Domain domain, boolean autoUpgradesEnabled, User owner) { - this(application, name, domain, owner, autoUpgradesEnabled); - this.id = id; - } - - public void addMember(User user) { - members.add(user); - } - - public void removeMember(User user) { - members.remove(user); - } - - @Override - public String toString() { - return "AppInstance{id=" + id + "}"; - } + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + Long id; + + String name; + + @ManyToOne(fetch = FetchType.LAZY, optional = false) + Application application; + + @Basic(fetch = FetchType.LAZY) + @Lob + @JdbcType(VarcharJdbcType.class) + @Column(columnDefinition = "TEXT") + String configuration; + + @CreatedDate + @Column(name = "created_at", nullable = false, updatable = false) + Long createdAt; + + @CreatedBy + @ManyToOne(fetch = FetchType.LAZY) + private User owner; + + @Basic + Identifier internalId; + + @Basic + private boolean autoUpgradesEnabled; + + @Column(name = "previous_application_id") + private Long previousApplicationId; + + @ManyToMany(fetch = FetchType.LAZY) + private Set<User> members = new HashSet<>(); + + public AppInstance(Application application, Domain domain, String name, boolean autoUpgradesEnabled) { + this.application = application; + this.domain = domain; + this.name = name; + this.autoUpgradesEnabled = autoUpgradesEnabled; + } + + public AppInstance(Long id, Application application, Domain domain, String name, boolean autoUpgradesEnabled) { + this(application, domain, name, autoUpgradesEnabled); + this.id = id; + } + + public AppInstance(Application application, String name, Domain domain, User owner, boolean autoUpgradesEnabled) { + this(application, domain, name, autoUpgradesEnabled); + this.owner = owner; + } + + protected AppInstance(Long id, Application application, String name, Domain domain, boolean autoUpgradesEnabled, User owner) { + this(application, name, domain, owner, autoUpgradesEnabled); + this.id = id; + } + + @Override + public String toString() { + return "AppInstance{id=" + id + "}"; + } } diff --git a/src/main/java/net/geant/nmaas/portal/persistent/repositories/AppInstanceRepository.java b/src/main/java/net/geant/nmaas/portal/persistent/repositories/AppInstanceRepository.java index a502ee89db7b1e874753ce4fd667b1f2904ebce2..0618dddce5eb216fbdb42dd90bacd2022d72fd81 100644 --- a/src/main/java/net/geant/nmaas/portal/persistent/repositories/AppInstanceRepository.java +++ b/src/main/java/net/geant/nmaas/portal/persistent/repositories/AppInstanceRepository.java @@ -17,47 +17,51 @@ import java.util.Optional; public interface AppInstanceRepository extends JpaRepository<AppInstance, Long> { - Optional<AppInstance> findByInternalId(Identifier internalId); + Optional<AppInstance> findByInternalId(Identifier internalId); - List<AppInstance> findAllByOwner(User user); - List<AppInstance> findAllByDomain(Domain domain); - List<AppInstance> findAllByOwnerAndDomain(User owner, Domain domain); + List<AppInstance> findAllByOwner(User user); - Page<AppInstance> findAllByDomain(Domain domain, Pageable pageable); - Page<AppInstance> findAllByOwner(User owner, Pageable pageable); - Page<AppInstance> findAllByOwnerAndDomain(User owner, Domain domain, Pageable pageable); + List<AppInstance> findAllByDomain(Domain domain); - List<AppInstance> findAllByApplication(Application application); + List<AppInstance> findAllByOwnerAndDomain(User owner, Domain domain); - @Query("select count(ai.id) FROM AppInstance ai JOIN AppDeployment ad on ad.deploymentId = ai.internalId where ad.state = 'APPLICATION_DEPLOYMENT_VERIFIED'") - int countAllRunning(); + Page<AppInstance> findAllByDomain(Domain domain, Pageable pageable); - @Query("select count(ai.id) FROM AppInstance ai JOIN AppDeployment ad on ad.deploymentId = ai.internalId where ad.state = 'APPLICATION_DEPLOYMENT_VERIFIED' and ai.application.name = ?1") - int countRunningByName(String name); + Page<AppInstance> findAllByOwner(User owner, Pageable pageable); - @Modifying - @Query("update AppInstance ai set ai.application = :application, ai.previousApplicationId = :previousApplicationId where ai.id = :id") - void updateApplication(@Param(value = "id") long id, @Param(value = "previousApplicationId") long previousApplicationId, @Param(value = "application") Application application); + Page<AppInstance> findAllByOwnerAndDomain(User owner, Domain domain, Pageable pageable); - @Query("SELECT COUNT(ai.id) FROM AppInstance ai JOIN AppDeployment ad ON ad.deploymentId = ai.internalId WHERE ai.name = :name AND ai.domain.codename = :domain AND ad.state NOT IN" + - "('APPLICATION_REMOVED'," + - "'APPLICATION_CONFIGURATION_REMOVAL_IN_PROGRESS'," + - "'APPLICATION_CONFIGURATION_REMOVED'," + - "'FAILED_APPLICATION_REMOVED')" ) - int isNameAvailableInDomain(@Param(value = "name") String name, @Param(value = "domain") String domain); + List<AppInstance> findAllByApplication(Application application); - @Query("select count(ai.id) FROM AppInstance ai where ai.createdAt >= :sinceTime") - int countAllDeployedSinceTime(@Param("sinceTime") long sinceTime); + @Query("select count(ai.id) FROM AppInstance ai JOIN AppDeployment ad on ad.deploymentId = ai.internalId where ad.state = 'APPLICATION_DEPLOYMENT_VERIFIED'") + int countAllRunning(); - @Query("select count(ai.id) FROM AppInstance ai where ai.createdAt >= :sinceTime AND ai.createdAt < :endTime") - int countAllDeployedSinceTime(@Param("sinceTime") long sinceTime, @Param("endTime") long endTime); + @Query("select count(ai.id) FROM AppInstance ai JOIN AppDeployment ad on ad.deploymentId = ai.internalId where ad.state = 'APPLICATION_DEPLOYMENT_VERIFIED' and ai.application.name = ?1") + int countRunningByName(String name); - @Query("select count(ai.id) FROM AppInstance ai JOIN AppDeployment ad on ad.deploymentId = ai.internalId where ai.application.name = ?1") - int countByName(String name); + @Modifying + @Query("update AppInstance ai set ai.application = :application, ai.previousApplicationId = :previousApplicationId where ai.id = :id") + void updateApplication(@Param(value = "id") long id, @Param(value = "previousApplicationId") long previousApplicationId, @Param(value = "application") Application application); - @Query("select ai FROM AppInstance ai where ai.createdAt >= :sinceTime AND ai.createdAt <= :endTime") - List<AppInstance> findAllInTimePeriod(@Param("sinceTime") long start, @Param("endTime") long endTime); + @Query("SELECT COUNT(ai.id) FROM AppInstance ai JOIN AppDeployment ad ON ad.deploymentId = ai.internalId WHERE ai.name = :name AND ai.domain.codename = :domain AND ad.state NOT IN" + + "('APPLICATION_REMOVED'," + + "'APPLICATION_CONFIGURATION_REMOVAL_IN_PROGRESS'," + + "'APPLICATION_CONFIGURATION_REMOVED'," + + "'FAILED_APPLICATION_REMOVED')") + int isNameAvailableInDomain(@Param(value = "name") String name, @Param(value = "domain") String domain); - int countAllByOwner(User user); + @Query("SELECT COUNT(ai.id) FROM AppInstance ai WHERE ai.createdAt >= :sinceTime") + int countAllDeployedSince(@Param("sinceTime") long sinceTime); + + @Query("SELECT COUNT(ai.id) FROM AppInstance ai WHERE ai.createdAt >= :sinceTime AND ai.createdAt < :endTime") + int countAllDeployedInTimePeriod(@Param("sinceTime") long sinceTime, @Param("endTime") long endTime); + + @Query("SELECT COUNT(ai.id) FROM AppInstance ai JOIN AppDeployment ad ON ad.deploymentId = ai.internalId WHERE ai.application.name = ?1") + int countByName(String name); + + @Query("SELECT ai FROM AppInstance ai WHERE ai.createdAt >= :sinceTime AND ai.createdAt <= :endTime") + List<AppInstance> findAllInTimePeriod(@Param("sinceTime") long sinceTime, @Param("endTime") long endTime); + + int countAllByOwner(User user); } diff --git a/src/main/java/net/geant/nmaas/portal/service/DashboardService.java b/src/main/java/net/geant/nmaas/portal/service/DashboardService.java index 2c172aacac41010fb4b3e072ec1eb70b6afde746..16cc232b9d1956fa0c6c32e3401b005b9a840fd2 100644 --- a/src/main/java/net/geant/nmaas/portal/service/DashboardService.java +++ b/src/main/java/net/geant/nmaas/portal/service/DashboardService.java @@ -7,7 +7,8 @@ import java.time.OffsetDateTime; public interface DashboardService { - public DashboardView getSystemDashboard(OffsetDateTime startDate, OffsetDateTime endDate); + DashboardView getSystemDashboard(OffsetDateTime startDate, OffsetDateTime endDate); + + DomainDashboardView getDomainDashboard(Long domainId); - public DomainDashboardView getSystemDomainDashboard(Long domainId); } diff --git a/src/main/java/net/geant/nmaas/portal/service/impl/DashboardServiceImpl.java b/src/main/java/net/geant/nmaas/portal/service/impl/DashboardServiceImpl.java index 28fbdaf017c9710e0be7153591416501c59ce9aa..68fc4b82fc12972b6c600f9cdf2481c8b72837f4 100644 --- a/src/main/java/net/geant/nmaas/portal/service/impl/DashboardServiceImpl.java +++ b/src/main/java/net/geant/nmaas/portal/service/impl/DashboardServiceImpl.java @@ -17,18 +17,15 @@ import net.geant.nmaas.portal.service.ApplicationInstanceService; import net.geant.nmaas.portal.service.DashboardService; import net.geant.nmaas.portal.service.DomainService; import net.geant.nmaas.portal.service.UserLoginRegisterService; -import net.geant.nmaas.portal.service.UserService; import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Service; -import java.time.Duration; import java.time.OffsetDateTime; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; -import java.util.stream.Collectors; @Service @@ -36,105 +33,105 @@ import java.util.stream.Collectors; @Slf4j public class DashboardServiceImpl implements DashboardService { - private final UserService userService; private final UserRepository userRepository; private final DomainService domainService; private final DomainRepository domainRepository; private final ApplicationInstanceService applicationInstanceService; - private final AppInstanceRepository appInstanceRepo; + private final AppInstanceRepository appInstanceRepository; private final ApplicationBaseRepository applicationBaseRepository; private final UserLoginRegisterService userLoginRegisterService; @Override public DashboardView getSystemDashboard(OffsetDateTime startDate, OffsetDateTime endDate) { - - log.warn("Start date {} / end date {}", startDate, endDate); + log.info("Processing dashboard data request for period {} - {}", startDate, endDate); long startTimeStamp = startDate.toEpochSecond(); long endTimeStamp = endDate.toEpochSecond(); - + log.info("Period in timestamps: {} - {}", startTimeStamp, endTimeStamp); List<String> baseNames = applicationBaseRepository.findAllNames(); Map<String, Integer> applicationDeploymentCountPerName = new HashMap<>(); - List<DashboardDeploymentsView> deploymentsViews = appInstanceRepo.findAllInTimePeriod(startTimeStamp, endTimeStamp) - .stream().map(entry -> DashboardDeploymentsView.builder().user(entry.getOwner().getUsername()) + List<DashboardDeploymentsView> deploymentsViews = appInstanceRepository.findAllInTimePeriod(startTimeStamp, endTimeStamp).stream() + .map(entry -> DashboardDeploymentsView.builder().user(entry.getOwner().getUsername()) .domainName(entry.getDomain().getName()) .applicationName(entry.getApplication().getName()) - .applicationVersion(entry.getApplication().getVersion()).build()).toList(); + .applicationVersion(entry.getApplication().getVersion()) + .build()) + .toList(); baseNames.forEach(name -> { - applicationDeploymentCountPerName.put(name, appInstanceRepo.countByName(name)); + applicationDeploymentCountPerName.put(name, appInstanceRepository.countByName(name)); }); - //filter not deployed application + // filter not deployed application applicationDeploymentCountPerName.entrySet().removeIf(app -> app.getValue() == 0); - log.info("Start stamp {} / end stamp {}", startTimeStamp, endTimeStamp); - return DashboardView.builder() + DashboardView systemView = DashboardView.builder() .domainsCount(domainRepository.count()) .userCount(userRepository.count()) - .instanceCount(appInstanceRepo.count()) - .instanceCountInPeriod(appInstanceRepo.countAllDeployedSinceTime(startTimeStamp, endTimeStamp)) + .instanceCount(appInstanceRepository.count()) + .instanceCountInPeriod(appInstanceRepository.countAllDeployedInTimePeriod(startTimeStamp, endTimeStamp)) .instanceCountInPeriodDetails(deploymentsViews) .popularApps(applicationDeploymentCountPerName).build(); + log.info("Response: {}", systemView.toString()); + return systemView; } //TODO: Change username to pre @Override - public DomainDashboardView getSystemDomainDashboard(Long domainId) { + public DomainDashboardView getDomainDashboard(Long domainId) { + log.info("Processing dashboard data request for domain {}", domainId); Optional<Domain> domain = domainService.findDomain(domainId); Map<String, OffsetDateTime> userLogins = new HashMap<>(); Map<String, Integer> appsDeployed = new HashMap<>(); List<DomainDashboardView.DomainAppInstanceView> upgradePossible = new ArrayList<>(); - if(domain.isPresent()) { + if (domain.isPresent()) { Domain dom = domain.get(); List<User> domainUsers = domainService.getMembers(domainId); - List<AppInstance> apps = appInstanceRepo.findAllByDomain(dom); + List<AppInstance> apps = appInstanceRepository.findAllByDomain(dom); domainUsers.forEach(user -> { Optional<UserLoginRegister> register = userLoginRegisterService.getLastLogin(user); - if(register.isPresent()) { + if (register.isPresent()) { userLogins.put(this.getUserPreferredUsername(user), register.get().getDate()); - appsDeployed.put(this.getUserPreferredUsername(user), appInstanceRepo.countAllByOwner(user)); + appsDeployed.put(this.getUserPreferredUsername(user), appInstanceRepository.countAllByOwner(user)); } }); apps.forEach(app -> { - upgradePossible.add( DomainDashboardView.DomainAppInstanceView.builder() - .appId(app.getId()) - .appName(app.getApplication().getName()) - .instanceName(app.getName()) - .appVersion(app.getApplication().getVersion()) - .upgradePossible(applicationInstanceService.checkUpgradePossible(app.getId())).build()); + upgradePossible.add(DomainDashboardView.DomainAppInstanceView.builder() + .appId(app.getId()) + .appName(app.getApplication().getName()) + .instanceName(app.getName()) + .appVersion(app.getApplication().getVersion()) + .upgradePossible(applicationInstanceService.checkUpgradePossible(app.getId())).build()); }); - - - return DomainDashboardView.builder() + DomainDashboardView view = DomainDashboardView.builder() .userLogins(userLogins) .applicationDeployed(appsDeployed) .applicationUpgradeStatus(upgradePossible) .build(); + log.info("Response: {}", view.toString()); + return view; } else { - log.error("Domain {} not present. Returning empty...", domainId ); + log.error("Domain {} not present. Returning empty...", domainId); return DomainDashboardView.builder().build(); } } - private String getUserPreferredUsername(User user) { String preferredUsername; - - if (user == null || StringUtils.isEmpty(user.getUsername())) { + if (StringUtils.isEmpty(user.getUsername())) { throw new IllegalArgumentException("User or username is not set"); } - if(user.getFirstname() != null && !user.getFirstname().isEmpty()) { + if (user.getFirstname() != null && !user.getFirstname().isEmpty()) { preferredUsername = user.getFirstname() + " " + user.getLastname(); - }else{ + } else { preferredUsername = user.getUsername(); } return preferredUsername; diff --git a/src/test/java/net/geant/nmaas/portal/api/info/DashboardControllerTest.java b/src/test/java/net/geant/nmaas/portal/api/info/DashboardControllerTest.java index bc11435c61a1723aa7a7f9cb4b467e0d1e33bfa6..7a2983bdef38a223b4654c9998ae9b0a4626e8e8 100644 --- a/src/test/java/net/geant/nmaas/portal/api/info/DashboardControllerTest.java +++ b/src/test/java/net/geant/nmaas/portal/api/info/DashboardControllerTest.java @@ -1,7 +1,5 @@ package net.geant.nmaas.portal.api.info; -import net.geant.nmaas.portal.api.info.DashboardView; -import net.geant.nmaas.portal.api.info.DomainDashboardView; import net.geant.nmaas.portal.service.DashboardService; import org.junit.jupiter.api.Test; @@ -34,7 +32,7 @@ public class DashboardControllerTest { Long domainId = 1L; DomainDashboardView domainDashboardView = DomainDashboardView.builder().build(); - when(dashboardService.getSystemDomainDashboard(domainId)).thenReturn(domainDashboardView); + when(dashboardService.getDomainDashboard(domainId)).thenReturn(domainDashboardView); DomainDashboardView result = dashboardController.getDashboardDomain(domainId); diff --git a/src/test/java/net/geant/nmaas/portal/service/impl/DashboardServiceImplTest.java b/src/test/java/net/geant/nmaas/portal/service/impl/DashboardServiceImplTest.java index f35951e6cfdf5e61ca16780fabfdf728afd51910..bd43f5975e33642dbb284d918ed93c0501783053 100644 --- a/src/test/java/net/geant/nmaas/portal/service/impl/DashboardServiceImplTest.java +++ b/src/test/java/net/geant/nmaas/portal/service/impl/DashboardServiceImplTest.java @@ -13,7 +13,6 @@ import net.geant.nmaas.portal.persistent.repositories.UserRepository; import net.geant.nmaas.portal.service.ApplicationInstanceService; import net.geant.nmaas.portal.service.DomainService; import net.geant.nmaas.portal.service.UserLoginRegisterService; -import net.geant.nmaas.portal.service.UserService; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; @@ -25,43 +24,41 @@ import java.util.Optional; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; - public class DashboardServiceImplTest { - private final UserService userService = mock(UserService.class); private final UserRepository userRepository = mock(UserRepository.class); private final DomainService domainService = mock(DomainService.class); private final DomainRepository domainRepository = mock(DomainRepository.class); private final ApplicationInstanceService applicationInstanceService = mock(ApplicationInstanceService.class); - private final AppInstanceRepository appInstanceRepo = mock(AppInstanceRepository.class); + private final AppInstanceRepository appInstanceRepository = mock(AppInstanceRepository.class); private final ApplicationBaseRepository applicationBaseRepository = mock(ApplicationBaseRepository.class); private final UserLoginRegisterService userLoginRegisterService = mock(UserLoginRegisterService.class); private final DashboardServiceImpl dashboardService = new DashboardServiceImpl( - userService, userRepository, domainService, domainRepository, applicationInstanceService, - appInstanceRepo, + appInstanceRepository, applicationBaseRepository, userLoginRegisterService ); - @Test + @Test void getSystemDashboardShouldThrowExceptionWhenRepositoryFails() { when(domainRepository.count()).thenThrow(new RuntimeException("Database error")); - assertThrows(RuntimeException.class, () -> - dashboardService.getSystemDashboard(OffsetDateTime.now().minusDays(1), OffsetDateTime.now()) + assertThrows(RuntimeException.class, () -> + dashboardService.getSystemDashboard(OffsetDateTime.now().minusDays(1), OffsetDateTime.now()) ); } @Test - void getSystemDomainDashboardShouldReturnEmptyObjectWhenDomainIdIsNull() { - DomainDashboardView result = dashboardService.getSystemDomainDashboard(null); + void getDomainDashboardShouldReturnEmptyObjectWhenDomainIdIsNull() { + DomainDashboardView result = dashboardService.getDomainDashboard(null); assert result != null; assert result.getUserLogins() == null; @@ -70,15 +67,15 @@ public class DashboardServiceImplTest { } @Test - void getSystemDomainDashboardShouldHandleEmptyDomainUsers() { + void getDomainDashboardShouldHandleEmptyDomainUsers() { Long domainId = 1L; Domain domain = new Domain(domainId, "Test Domain", "test-domain"); when(domainService.findDomain(domainId)).thenReturn(Optional.of(domain)); when(domainService.getMembers(domainId)).thenReturn(Collections.emptyList()); - when(appInstanceRepo.findAllByDomain(domain)).thenReturn(Collections.emptyList()); + when(appInstanceRepository.findAllByDomain(domain)).thenReturn(Collections.emptyList()); - DomainDashboardView result = dashboardService.getSystemDomainDashboard(domainId); + DomainDashboardView result = dashboardService.getDomainDashboard(domainId); assert result != null; assert result.getUserLogins().isEmpty(); @@ -87,7 +84,7 @@ public class DashboardServiceImplTest { } @Test - void getSystemDomainDashboardShouldHandleEmptyAppInstances() { + void getDomainDashboardShouldHandleEmptyAppInstances() { Long domainId = 1L; Domain domain = new Domain(domainId, "Test Domain", "test-domain"); User user = new User("testUser", true); @@ -95,18 +92,18 @@ public class DashboardServiceImplTest { UserLoginRegister userLoginRegister = new UserLoginRegister( loginTime, user, - UserLoginRegisterType.SUCCESS, // Typ logowania - "127.0.0.1", // Adres IP + UserLoginRegisterType.SUCCESS, // login type + "127.0.0.1", // IP address "localhost", // Host "Mozilla/5.0" // User-Agent ); when(domainService.findDomain(domainId)).thenReturn(Optional.of(domain)); when(domainService.getMembers(domainId)).thenReturn(List.of(user)); - when(appInstanceRepo.findAllByDomain(domain)).thenReturn(Collections.emptyList()); + when(appInstanceRepository.findAllByDomain(domain)).thenReturn(Collections.emptyList()); when(userLoginRegisterService.getLastLogin(user)).thenReturn(Optional.of(userLoginRegister)); - DomainDashboardView result = dashboardService.getSystemDomainDashboard(domainId); + DomainDashboardView result = dashboardService.getDomainDashboard(domainId); assert result != null; assert !result.getUserLogins().isEmpty(); @@ -117,8 +114,8 @@ public class DashboardServiceImplTest { void getSystemDashboardShouldHandleEmptyBaseNames() { when(domainRepository.count()).thenReturn(5L); when(userRepository.count()).thenReturn(10L); - when(appInstanceRepo.count()).thenReturn(15L); - when(appInstanceRepo.countAllDeployedSinceTime(anyLong())).thenReturn((int) 3L); + when(appInstanceRepository.count()).thenReturn(15L); + when(appInstanceRepository.countAllDeployedInTimePeriod(anyLong(), anyLong())).thenReturn((int) 3L); when(applicationBaseRepository.findAllNames()).thenReturn(Collections.emptyList()); DashboardView result = dashboardService.getSystemDashboard(OffsetDateTime.now().minusDays(1), OffsetDateTime.now()); @@ -135,10 +132,10 @@ public class DashboardServiceImplTest { // Mock required repository methods when(domainRepository.count()).thenReturn(1L); when(userRepository.count()).thenReturn(1L); - when(appInstanceRepo.count()).thenReturn(1L); - when(appInstanceRepo.countAllDeployedSinceTime(org.mockito.ArgumentMatchers.anyLong(), org.mockito.ArgumentMatchers.anyLong())).thenReturn(1); + when(appInstanceRepository.count()).thenReturn(1L); + when(appInstanceRepository.countAllDeployedInTimePeriod(org.mockito.ArgumentMatchers.anyLong(), org.mockito.ArgumentMatchers.anyLong())).thenReturn(1); when(applicationBaseRepository.findAllNames()).thenReturn(Collections.emptyList()); - when(appInstanceRepo.findAllInTimePeriod(org.mockito.ArgumentMatchers.anyLong(), org.mockito.ArgumentMatchers.anyLong())).thenReturn(Collections.emptyList()); + when(appInstanceRepository.findAllInTimePeriod(org.mockito.ArgumentMatchers.anyLong(), org.mockito.ArgumentMatchers.anyLong())).thenReturn(Collections.emptyList()); // Call the method dashboardService.getSystemDashboard(startDate, endDate); @@ -147,7 +144,7 @@ public class DashboardServiceImplTest { ArgumentCaptor<Long> startCaptor = ArgumentCaptor.forClass(Long.class); ArgumentCaptor<Long> endCaptor = ArgumentCaptor.forClass(Long.class); - org.mockito.Mockito.verify(appInstanceRepo).countAllDeployedSinceTime(startCaptor.capture(), endCaptor.capture()); + verify(appInstanceRepository).countAllDeployedInTimePeriod(startCaptor.capture(), endCaptor.capture()); long startTimestamp = startCaptor.getValue(); long endTimestamp = endCaptor.getValue(); @@ -164,12 +161,12 @@ public class DashboardServiceImplTest { long toTime = 2000L; int expectedCount = 7; - when(appInstanceRepo.countAllDeployedSinceTime(sinceTime, toTime)).thenReturn(expectedCount); + when(appInstanceRepository.countAllDeployedInTimePeriod(sinceTime, toTime)).thenReturn(expectedCount); - int actualCount = appInstanceRepo.countAllDeployedSinceTime(sinceTime, toTime); + int actualCount = appInstanceRepository.countAllDeployedInTimePeriod(sinceTime, toTime); assert actualCount == expectedCount; - org.mockito.Mockito.verify(appInstanceRepo).countAllDeployedSinceTime(sinceTime, toTime); + verify(appInstanceRepository).countAllDeployedInTimePeriod(sinceTime, toTime); } @Test @@ -179,17 +176,17 @@ public class DashboardServiceImplTest { when(domainRepository.count()).thenReturn(1L); when(userRepository.count()).thenReturn(1L); - when(appInstanceRepo.count()).thenReturn(1L); - when(appInstanceRepo.countAllDeployedSinceTime(org.mockito.ArgumentMatchers.anyLong(), org.mockito.ArgumentMatchers.anyLong())).thenReturn(5); + when(appInstanceRepository.count()).thenReturn(1L); + when(appInstanceRepository.countAllDeployedInTimePeriod(org.mockito.ArgumentMatchers.anyLong(), org.mockito.ArgumentMatchers.anyLong())).thenReturn(5); when(applicationBaseRepository.findAllNames()).thenReturn(Collections.emptyList()); - when(appInstanceRepo.findAllInTimePeriod(org.mockito.ArgumentMatchers.anyLong(), org.mockito.ArgumentMatchers.anyLong())).thenReturn(Collections.emptyList()); + when(appInstanceRepository.findAllInTimePeriod(org.mockito.ArgumentMatchers.anyLong(), org.mockito.ArgumentMatchers.anyLong())).thenReturn(Collections.emptyList()); dashboardService.getSystemDashboard(startDate, endDate); ArgumentCaptor<Long> sinceCaptor = ArgumentCaptor.forClass(Long.class); ArgumentCaptor<Long> toCaptor = ArgumentCaptor.forClass(Long.class); - org.mockito.Mockito.verify(appInstanceRepo).countAllDeployedSinceTime(sinceCaptor.capture(), toCaptor.capture()); + verify(appInstanceRepository).countAllDeployedInTimePeriod(sinceCaptor.capture(), toCaptor.capture()); long sinceTime = sinceCaptor.getValue(); long toTime = toCaptor.getValue();