Fix null handling and validation in SamplingRate management

This commit addresses potential runtime exceptions and improves input validation:

- Replace Optional.of() with Optional.ofNullable() in SamplingRateRepository.findById()
  to properly handle cases where no sampling rate is found, preventing NullPointerException
- Add null validation for id parameter in SamplingRateService.deleteSamplingRate()
  to ensure proper error handling before repository operations
- Clean up code formatting in updateSamplingRate() validation block

These changes enhance the robustness of the sampling rate management feature
by preventing NPEs and providing clearer error messages for invalid inputs.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
Gustavo Henrique Santos Souza de Miranda 2025-12-06 22:18:40 -03:00
parent 4fa147282f
commit ff09d1b89a
2 changed files with 6 additions and 2 deletions

View File

@ -53,7 +53,7 @@ public class SamplingRateRepository {
EntityManager em = entityManagerFactory.createEntityManager(); EntityManager em = entityManagerFactory.createEntityManager();
try{ try{
SamplingRate samplingRate = em.find(SamplingRate.class, id); SamplingRate samplingRate = em.find(SamplingRate.class, id);
return Optional.of(samplingRate); return Optional.ofNullable(samplingRate);
}finally { }finally {
if (em.isOpen()) em.close(); if (em.isOpen()) em.close();
} }

View File

@ -42,7 +42,8 @@ public class SamplingRateService {
public Optional<SamplingRate> updateSamplingRate(Integer id, String value) { public Optional<SamplingRate> updateSamplingRate(Integer id, String value) {
logger.info("Updating sampling rate:{}", value); logger.info("Updating sampling rate:{}", value);
if (value == null || value.trim().isEmpty()) { if (value == null || value.trim().isEmpty()) {
throw new IllegalArgumentException("Sampling-Rate value cannot be null or empty");} throw new IllegalArgumentException("Sampling-Rate value cannot be null or empty");
}
Optional<SamplingRate> existingSamplingRate = repository.findById(id); Optional<SamplingRate> existingSamplingRate = repository.findById(id);
if(existingSamplingRate.isEmpty()) { if(existingSamplingRate.isEmpty()) {
logger.warn("Sampling rate not found with id:{}", id); logger.warn("Sampling rate not found with id:{}", id);
@ -55,6 +56,9 @@ public class SamplingRateService {
} }
public boolean deleteSamplingRate(Integer id) { public boolean deleteSamplingRate(Integer id) {
if (id == null) {
throw new IllegalArgumentException("Sampling rate id cannot be null");
}
logger.info("Deleting sampling rate:{}", id); logger.info("Deleting sampling rate:{}", id);
return repository.deleteById(id); return repository.deleteById(id);
} }