hit-server-manager/backend/src/main/java/com/hitcommunications/servermanager/services/ServersService.java

89 lines
3.1 KiB
Java

package com.hitcommunications.servermanager.services;
import com.hitcommunications.servermanager.mappers.ServersMapper;
import com.hitcommunications.servermanager.model.Servers;
import com.hitcommunications.servermanager.model.dtos.NewServerDTO;
import com.hitcommunications.servermanager.model.dtos.ServerDTO;
import com.hitcommunications.servermanager.model.enums.Applications;
import com.hitcommunications.servermanager.model.enums.ServersType;
import com.hitcommunications.servermanager.repositories.ServersRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
@RequiredArgsConstructor
public class ServersService {
private final ServersMapper mapper;
private final ServersRepository repo;
public ServerDTO create(NewServerDTO createDTO) {
// Check if server with same IP and port already exists
repo.findByIpAndPort(createDTO.ip(), createDTO.port()).ifPresent(entity -> {
throw new RuntimeException("Server already exists with IP: " + createDTO.ip() + " and port: " + createDTO.port());
});
Servers entity = mapper.toEntity(createDTO);
entity = repo.save(entity);
return mapper.toDTO(entity);
}
public ServerDTO getById(String id) {
return repo.findById(id)
.map(mapper::toDTO)
.orElseThrow(() -> new RuntimeException("Server not found with id: " + id));
}
public ServerDTO getByName(String name) {
return repo.findByName(name)
.map(mapper::toDTO)
.orElseThrow(() -> new RuntimeException("Server not found with name: " + name));
}
public List<ServerDTO> getByType(ServersType type) {
return repo.findByType(type)
.stream()
.map(mapper::toDTO)
.toList();
}
public List<ServerDTO> getByApplication(Applications application) {
return repo.findByApplication(application)
.stream()
.map(mapper::toDTO)
.toList();
}
public List<ServerDTO> getAll() {
return repo.findAll()
.stream()
.map(mapper::toDTO)
.toList();
}
public ServerDTO update(String id, NewServerDTO updateDTO) {
Servers entity = repo.findById(id)
.orElseThrow(() -> new RuntimeException("Server not found with id: " + id));
// Check if IP/port combination already exists (excluding current server)
repo.findByIpAndPort(updateDTO.ip(), updateDTO.port()).ifPresent(existingServer -> {
if (!existingServer.getId().equals(id)) {
throw new RuntimeException("Server already exists with IP: " + updateDTO.ip() + " and port: " + updateDTO.port());
}
});
mapper.partialUpdate(updateDTO, entity);
entity = repo.save(entity);
return mapper.toDTO(entity);
}
public void delete(String id) {
if (!repo.existsById(id)) {
throw new RuntimeException("Server not found with id: " + id);
}
repo.deleteById(id);
}
}