public void updateCompany(CompanyDTO dto) throws Exception { Company company = getCompany(dto.id); validate(dto); List<String> beneficiaryIds = company .getBeneficiaries() .stream() .map(beneficiary -> beneficiary.getId().toString()) .collect(Collectors.toList()); for (BeneficiaryDTO beneDTO : dto.beneficiaries) { Beneficiary bene = new Beneficiary(beneDTO.name, company); Integer id = beneDTO.id; if (id != null) { bene.setId(id); String idString = id.toString(); if (!beneDao.idExists(idString)) { throw new RequestException("beneficiary with id %s does not exist", id); } beneDao.update(bene); beneficiaryIds.remove(idString); } else { beneDao.create(bene); } } if (beneficiaryIds.size() > 0) { beneDao.deleteIds(beneficiaryIds); } company = JsonUtil.fromJson(dto.toJson(), Company.class); dao.update(company); }
public void createCompany(CompanyDTO dto) throws Exception { validate(dto); Boolean exists = dao.idExists(dto.id); if (exists) { throw new RequestException("Company with id %s already exists", dto.id); } Company company = JsonUtil.fromJson(dto.toJson(), Company.class); company.setCreatedAt(); dao.create(company); for (BeneficiaryDTO beneDTO : dto.beneficiaries) { beneDao.create(new Beneficiary(beneDTO.name, company)); } }
private void validate(CompanyDTO dto) throws RequestException { ArrayList<String> errors = new ArrayList<String>(); List<String> required = Arrays.asList("id", "name", "address", "city", "country"); JsonObject json = dto.toJsonObject(); required .stream() .forEach( (property) -> { JsonElement value = json.get(property); if (value == null) { errors.add(property + " field is required"); } }); if (dto.beneficiaries == null || dto.beneficiaries.size() == 0) { errors.add("At least one beneficiary is required"); } if (errors.size() > 0) { throw new RequestException(errors); } }