Skip to content
Snippets Groups Projects
Commit 9a21e743 authored by Lukasz Lopatowski's avatar Lukasz Lopatowski
Browse files

Some refactor around DashboardController

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