@Transactional
public static Result editContact(Integer contactID) {
String reqBody = request().body().asJson().toString();
try {
Contact contact = DaoManager.getContactDao().findById(contactID);
List<Phone> contactPhones = contact.getPhones();
List<PhoneListItemDTO> phones = PhoneListItemDTO.createList(contactPhones);
if (contact == null) {
return notFound(Utilities.getJsonErrorNode("Can't find contact with ID: " + contactID));
}
Logger.debug("editContact request body: " + reqBody);
ContactDTO contactDTO = new ObjectMapper().readValue(reqBody, ContactDTO.class);
contactDTO.mapBack(contact);
DaoManager.getContactDao().persist(contact);
List<Phone> editedPhones = new ArrayList<Phone>();
Phone p;
Logger.info("1");
for(PhoneListItemDTO phone: contactDTO.getPhones()) {
p = new Phone();
phone.mapBack(p);
p.setContact(contact);
editedPhones.add(p);
DaoManager.getPhoneDao().persist(p);
}
Logger.info("3");
loop: for(PhoneListItemDTO ph1: phones) {
Logger.info("4 "+ph1.getId());
for(Phone ph: editedPhones) {
Logger.info("5 "+ph.getId());
if(ph.getId()==ph1.getId())
continue loop;
}
Logger.info("6");
p = DaoManager.getPhoneDao().findById(ph1.getId());
DaoManager.getPhoneDao().remove(p);
}
Logger.info("contact edited : " + contact.getLastName() + " " +
contact.getFirstName() + " ID = " + contact.getId());
} catch (DataAccessException e) {
Logger.error("editContact method failed (find or save contact)", e);
return badRequest(Utilities.getJsonErrorNode("editContact method failed (find or save contact)"));
} catch (IOException e) {
Logger.error("failed to parse edited contact json", e);