cz.muni.fi.dndtroopsweb.controllers.TroopController.java Source code

Java tutorial

Introduction

Here is the source code for cz.muni.fi.dndtroopsweb.controllers.TroopController.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.muni.fi.dndtroopsweb.controllers;

import cz.muni.fi.dndtroopsapi.dto.TroopCreateDTO;
import cz.muni.fi.dndtroopsapi.dto.TroopDTO;
import cz.muni.fi.dndtroopsapi.facade.TroopFacade;
import cz.muni.fi.dndtroopsweb.validation.TroopCreateDTOValidator;
import java.math.BigDecimal;
import javax.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.util.UriComponentsBuilder;

/**
 *
 * @author Karel Auf
 */
@Controller
@RequestMapping("/troop")
public class TroopController {

    final static Logger log = LoggerFactory.getLogger(TroopController.class);

    @Autowired
    private TroopFacade troopFacade;

    /**
     * Lists all troops in database
     *
     * @return list of troops
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String list(Model model) {
        model.addAttribute("troops", troopFacade.getAllTroops());
        return "troop/list";
    }

    /**
     * Displays form for new troop creation
     *
     * @return form for troop creation
     */
    @RequestMapping(value = "/new", method = RequestMethod.GET)
    public String newTroop(Model model) {
        log.debug("new()");
        model.addAttribute("troopCreate", new TroopCreateDTO());
        return "troop/new";
    }

    /**
     * Creates troop based on form provided
     *
     * @param formBean troop to be created
     * @return details of newly created troop
     */
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public String create(@Valid @ModelAttribute("troopCreate") TroopCreateDTO formBean, BindingResult bindingResult,
            Model model, RedirectAttributes redirectAttributes, UriComponentsBuilder uriBuilder) {
        log.debug("create(formBean={})", formBean);
        //in case of validation error forward back to the the form
        if (bindingResult.hasErrors()) {
            for (ObjectError ge : bindingResult.getGlobalErrors()) {
                log.trace("ObjectError: {}", ge);
            }
            for (FieldError fe : bindingResult.getFieldErrors()) {
                model.addAttribute(fe.getField() + "_error", true);
                log.trace("FieldError: {}", fe);
            }
            return "troop/new";
        }

        Long id = troopFacade.createTroop(formBean);

        redirectAttributes.addFlashAttribute("alert_success", "Troop " + id + " was created");
        return "redirect:" + uriBuilder.path("/troop/list").toUriString();
    }

    /**
     * Deletes troop from database if the troop is empty
     *
     * @param id of troop
     * @return list of troops after successful removal
     */
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.POST)
    public String delete(@PathVariable long id, Model model, UriComponentsBuilder uriBuilder,
            RedirectAttributes redirectAttributes) {
        TroopDTO troop = troopFacade.getTroopWithId(id);
        if (troopFacade.getTroopWithId(id).getMembers().isEmpty() == false) {
            redirectAttributes.addFlashAttribute("alert_warning", "Troop \"" + troop.getName() + "\" is not empty");
            return "redirect:" + uriBuilder.path("/troop/list").toUriString();
        }
        troopFacade.deleteTroop(id);
        log.debug("delete({})", id);
        redirectAttributes.addFlashAttribute("alert_success", "Troop \"" + troop.getName() + "\" was deleted.");
        return "redirect:" + uriBuilder.path("/troop/list").toUriString();
    }

    /**
     * Displays details of selected troop with additional actions
     *
     * @param id of troop
     * @return Detail page for selected troop
     */
    @RequestMapping(value = "/details/{id}", method = RequestMethod.GET)
    public String details(@PathVariable long id, Model model) {
        log.debug("details({})", id);
        model.addAttribute("troop", troopFacade.getTroopWithId(id));
        return "troop/details";
    }

    /**
     * Displays form for money modification for selected troop
     *
     * @param id id of troop
     * @return form for money modification
     */
    @RequestMapping(value = "/money/{id}", method = RequestMethod.POST)
    public String money(@PathVariable long id, Model model) {
        log.debug("role()");
        TroopDTO mod = new TroopDTO();
        mod.setId(id);
        model.addAttribute("troop", mod);
        return "troop/money";
    }

    /**
     * Changes money based on form for chosen troop
     *
     * @param formBean troop to be modified
     * @return details of modified troop
     */
    @RequestMapping(value = "/cash/{id}", method = RequestMethod.POST)
    public String cash(@PathVariable long id, @Valid @ModelAttribute("troop") TroopDTO formBean,
            BindingResult bindingResult, Model model, RedirectAttributes redirectAttributes,
            UriComponentsBuilder uriBuilder) {
        log.debug("update money(troop={})", formBean);
        //in case of validation error forward back to the the form
        if (bindingResult.hasErrors()) {
            for (ObjectError ge : bindingResult.getGlobalErrors()) {
                log.trace("ObjectError: {}", ge);
            }
            for (FieldError fe : bindingResult.getFieldErrors()) {
                model.addAttribute(fe.getField() + "_error", true);
                log.trace("FieldError: {}", fe);
            }
            return "troop/money";
        }
        troopFacade.changeMoney(id, formBean.getMoney());
        //Long id = formBean.getId();
        redirectAttributes.addFlashAttribute("alert_success", "Money updated");
        return "redirect:" + uriBuilder.path("/troop/details/{id}").buildAndExpand(id).encode().toUriString();
    }

    /**
     * Displays form for mission modification for selected troop
     *
     * @param id id of troop
     * @return form for mission modification
     */
    @RequestMapping(value = "/mission/{id}", method = RequestMethod.POST)
    public String mission(@PathVariable long id, Model model) {
        log.debug("role()");
        TroopDTO mod = new TroopDTO();
        mod.setId(id);
        model.addAttribute("troop", mod);
        return "troop/mission";
    }

    /**
     * Changes mission based on form for chosen troop
     *
     * @param formBean troop to be modified
     * @return details of modified troop
     */
    @RequestMapping(value = "/job/{id}", method = RequestMethod.POST)
    public String job(@Valid @ModelAttribute("hero") TroopDTO formBean, BindingResult bindingResult, Model model,
            RedirectAttributes redirectAttributes, UriComponentsBuilder uriBuilder) {
        log.debug("update mission(troop={})", formBean);
        //in case of validation error forward back to the the form
        if (bindingResult.hasErrors()) {
            for (ObjectError ge : bindingResult.getGlobalErrors()) {
                log.trace("ObjectError: {}", ge);
            }
            for (FieldError fe : bindingResult.getFieldErrors()) {
                model.addAttribute(fe.getField() + "_error", true);
                log.trace("FieldError: {}", fe);
            }
            return "troop/mission";
        }
        troopFacade.changeMission(formBean.getId(), formBean.getMission());
        Long id = formBean.getId();
        redirectAttributes.addFlashAttribute("alert_success", "Mission updated");
        return "redirect:" + uriBuilder.path("/troop/details/{id}").buildAndExpand(id).encode().toUriString();
    }

    /**
     * Binds validator for Troop creation
     */
    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        if (binder.getTarget() instanceof TroopCreateDTO) {
            binder.addValidators(new TroopCreateDTOValidator());
        }
    }
}