Package controllers

Source Code of controllers.ContactsController

package controllers;

import be.objectify.deadbolt.java.actions.Group;
import be.objectify.deadbolt.java.actions.Restrict;
import com.fasterxml.jackson.databind.ObjectMapper;
import dao.DataAccessException;
import models.DaoManager;
import models.dto.*;
import models.entities.Contact;
import models.entities.Phone;
import play.Logger;
import play.db.jpa.Transactional;
import play.mvc.Controller;
import play.mvc.Result;
import utils.EmailManager;
import utils.Utilities;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import static play.libs.Json.toJson;

/**
* Created by Inspiron on 27.08.2014.
*/
@Restrict({@Group("manager"), @Group("admin"), @Group("supervisor")})
public class ContactsController extends Controller {

    @Transactional
    public static Result addContact() {
        String reqBody = request().body().asJson().toString();
        Logger.debug("addContact request body: " + reqBody);
        try {
            ContactDTO contactDTO = new ObjectMapper().readValue(reqBody, ContactDTO.class);
            Contact contact = new Contact();
            contactDTO.mapBack(contact);
            for(Phone p: contact.getPhones()) {
                DaoManager.getPhoneDao().persist(p);
            }
            DaoManager.getContactDao().persist(contact);
            Logger.info("new contact added: " + contact.getLastName() + " " +
                    contact.getFirstName() + " ID = " + contact.getId());
        } catch (IOException e) {
            Logger.error("failed to parse new contact json", e);
            return badRequest(Utilities.getJsonErrorNode("failed to parse new contact json"));
        } catch (DataAccessException e) {
            Logger.error("failed to save new contact", e);
            return badRequest(Utilities.getJsonErrorNode("failed to save new contact"));
        }
        return ok();
    }

    @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);
            return badRequest(Utilities.getJsonErrorNode("failed to parse edited contact json"));
        }
        return ok();
    }

    @Transactional
    public static Result deleteContact(Integer contactID) {
        String reqBody = request().body().asJson().toString();
        try {
            Contact contact = DaoManager.getContactDao().findById(contactID);
            if (contact == null) {
                return notFound(Utilities.getJsonErrorNode("can't find contact with ID: " + contactID));
            }
            DaoManager.getContactDao().remove(contact);
            Logger.info("contact deleted : " + contact.getLastName() + " " +
                    contact.getFirstName() + " ID = " + contact.getId());

        } catch (DataAccessException e) {
            Logger.error("deleteContact method failed (save or edit contact)", e);
            return badRequest("deleteContact method failed (save or edit contact)");
        }
        return ok();
    }

    @Transactional
    public static Result deleteContacts() {
        String reqBody = request().body().asJson().toString();
        try {
            Integer[] selectedIds = new ObjectMapper().readValue(reqBody, Integer[].class);
            for (Integer id : selectedIds) {
                deleteContact(id);
            }
            Logger.info("List of selected contacts has been deleted");
            return ok();
        } catch (IOException e) {
            Logger.error("Failed to parse array of IDs. reqBody:" + reqBody, e);
            return badRequest(Utilities.getJsonErrorNode("failed to parse array of ids"));
        }
    }

    @Transactional
    public static Result getFilteredContacts(Integer pageNumber, Integer pageSize, String dto) {
        if (pageNumber == null || pageSize == null || pageNumber <= 0 || pageNumber <= 0) {
            Logger.error("Illegal page number or size");
            return badRequest(Utilities.getJsonErrorNode("Illegal page number or size"));
        }
        try {
            ContactSearchDTO contactDTO = new ObjectMapper().readValue(dto, ContactSearchDTO.class);

            List<Contact> contacts = DaoManager.getContactDao().search(pageNumber - 1, pageSize, contactDTO);
            if (contacts.size() == 0) {
                ContactsListDTO listDTO = ContactsListDTO.createFrom(new ArrayList<Contact>(), 1);
                return ok(toJson(listDTO));
            }
            Integer totalContacts = DaoManager.getContactDao().searchResultsCount(contactDTO);
            Integer totalPages = Double.valueOf(Math.ceil((double) totalContacts / pageSize)).intValue();
            ContactsListDTO listDTO = ContactsListDTO.createFrom(contacts, totalPages);
            return ok(toJson(listDTO));
        } catch (DataAccessException e) {
            Logger.error("Failed to get a batch of contacts. Page: " + pageNumber, e);
            return notFound("Can't get page " + pageNumber);
        } catch (IOException e) {
            Logger.error("Failed to read input contact to search");
            return notFound("Failed to read input contact to search" + pageNumber);
        }
    }

    @Transactional
    public static Result quickSearchContacts(Integer pageNumber, Integer pageSize, String term) {
        if (pageNumber == null || pageSize == null || pageNumber <= 0 || pageNumber <= 0) {
            Logger.error("Illegal page number or size");
            return badRequest(Utilities.getJsonErrorNode("Illegal page number or size"));
        }
        try {
            List<Contact> contacts = DaoManager.getContactDao().quickSearch(pageNumber - 1, pageSize, term);
            if (contacts.size() == 0) {
                return notFound("No one contact suits search parameters");
            }
            Integer totalContacts = DaoManager.getContactDao().quickSearchResultsCount(term);
            Integer totalPages = Double.valueOf(Math.ceil((double) totalContacts / pageSize)).intValue();
            ContactsListDTO listDTO = ContactsListDTO.createFrom(contacts, totalPages);
            return ok(toJson(listDTO));
        } catch (DataAccessException e) {
            Logger.error("Failed to get a batch of contacts. Page: " + pageNumber, e);
            return notFound("Can't get page " + pageNumber);
        }
    }

    @Transactional
    @Restrict({@Group("manager"), @Group("admin"), @Group("supervisor"), @Group("executor"), @Group("delivery-manager")})
    public static Result getList(Integer pageNumber, Integer pageSize) {
        if (pageNumber == null || pageSize == null || pageNumber <= 0 || pageNumber <= 0) {
            Logger.error("Illegal page number or size");
            return badRequest(Utilities.getJsonErrorNode("Illegal page number or size"));
        }
        try {
            List<Contact> contacts = DaoManager.getContactDao().getBatch(pageNumber - 1, pageSize);
            Integer totalContacts = DaoManager.getContactDao().totalEntities();
            Integer totalPages = totalContacts / pageSize + 1;
            ContactsListDTO listDTO = ContactsListDTO.createFrom(contacts, totalPages);
            return ok(toJson(listDTO));
        } catch (DataAccessException e) {
            Logger.error("Failed to get a batch of contacts. Page: " + pageNumber, e);
            return notFound("Can't get page " + pageNumber);
        }
    }

    @Transactional
    public static Result getContact(Integer id, boolean shortFormat) {
        try {
            Contact contact = DaoManager.getContactDao().findById(id);
            if (shortFormat) {
                return ok(toJson(ContactListItemDTO.createFrom(contact)));
            }
            return ok(toJson(ContactDTO.createFrom(contact)));

        } catch (DataAccessException e) {
            Logger.error("Can't find contact with ID: " + id, e);
            return notFound("Can't find contact with ID: " + id);
        }
    }

    @Transactional
    public static Result getContactPhones(Integer id) {
        Contact contact=null;
        try {
            contact = DaoManager.getContactDao().findById(id);
            List<Phone> contactPhones = contact.getPhones();
            List<PhoneListItemDTO> phones = PhoneListItemDTO.createList(contactPhones);
            return ok(toJson(phones));

        } catch (DataAccessException e) {
            Logger.error("Failed to get contact's phones. Contact: "+contact.getLastName()+" "+
                    contact.getFirstName()+", id = "+contact.getId(), e);
            return notFound("Failed to get contact's phones. Contact: "+contact.getLastName()+" "+
                    contact.getFirstName()+", id = "+contact.getId());
        }
    }

    @Transactional
    public static Result sendEmails() {
        String reqBody = request().body().asJson().toString();
        Logger.debug("email request body: " + reqBody);
        try {
            EmailsDto emailsDto = new ObjectMapper().readValue(reqBody, EmailsDto.class);
            emailsDto.setRecipientsList(new ObjectMapper().readValue(emailsDto.getRecipients(), Integer[].class));
            if (emailsDto.getRecipients().isEmpty()) {
                return badRequest(Utilities.getJsonErrorNode("The recipients list is empty."));
            }
            if (emailsDto.getSubject() == null || emailsDto.getSubject().isEmpty()
                    || emailsDto.getMessage() == null || emailsDto.getMessage().isEmpty()) {
                return badRequest(Utilities.getJsonErrorNode("Email subject and message should be specified."));
            }
            List<Contact> recipients = new ArrayList<>();
            for (Integer recipientId : emailsDto.getRecipientsList()) {
                recipients.add(DaoManager.getContactDao().findById(recipientId));
            }
            EmailManager.sendEmailTo(recipients, emailsDto.getSubject(), emailsDto.getMessage());
            return ok();
        } catch (IOException e) {
            Logger.error("failed to parse emails json", e);
            return badRequest(Utilities.getJsonErrorNode("failed to parse emails json"));
        } catch (DataAccessException e) {
            Logger.error("failed to get contacts for email", e);
            return badRequest(Utilities.getJsonErrorNode("failed to get contacts for email"));
        }
    }

    @Transactional
    public static Result getMails(String ids) {
        Logger.debug("Mails request IDs: " + ids);
        Contact contact;
        String stemp;
        List<String> mails = new ArrayList<String>();
        try {
//            Integer[] selectedIds = new ObjectMapper().readValue(ids, Integer[].class);
            StringTokenizer st = new StringTokenizer(ids,",");
            List<Integer> selectedIds = new ArrayList<Integer>();
            while (st.hasMoreTokens()) {
                selectedIds.add(Integer.valueOf(st.nextToken()));
            }
            for(Integer id: selectedIds) {
                contact = DaoManager.getContactDao().findById(id);
                stemp = contact.getEmail();
                if(stemp != null && !stemp.equals(""))
                    mails.add(contact.getEmail());
            }
            Logger.info("Mail addresses: "+mails);
            return ok(toJson(mails));
        } catch (DataAccessException e) {
            Logger.error("failed to find contact by ID", e);
            return badRequest(Utilities.getJsonErrorNode("failed to find contact by ID"));
        }
    }
}
TOP

Related Classes of controllers.ContactsController

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.