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

Java tutorial

Introduction

Here is the source code for cz.muni.fi.dndtroopsweb.controllers.HeroController.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.dndtroops.enums.RoleName;
import cz.muni.fi.dndtroopsapi.dto.HeroCreateDTO;
import cz.muni.fi.dndtroopsapi.dto.HeroDTO;
import cz.muni.fi.dndtroopsapi.dto.TroopDTO;
import cz.muni.fi.dndtroopsapi.facade.HeroFacade;
import cz.muni.fi.dndtroopsapi.facade.TroopFacade;
import cz.muni.fi.dndtroopsweb.validation.HeroCreateDTOValidator;
import java.util.ArrayList;
import java.util.List;
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
 */
@Controller
@RequestMapping("/hero")
public class HeroController {

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

    @Autowired
    private HeroFacade heroFacade;
    @Autowired
    private TroopFacade troopFacade;

    /**
     * Lists all heroes in database
     *
     * @return list of heroes
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String list(Model model) {
        model.addAttribute("heroes", heroFacade.getAllHeroes());
        return "hero/list";
    }

    @ModelAttribute("existingTroops")
    public List<TroopDTO> troopList() {
        return troopFacade.getAllTroops();
    }

    @ModelAttribute("existingRoles")
    public List<String> roleList() {
        List<String> roles = new ArrayList();
        roles.add("BARBARIAN");
        roles.add("BARD");
        roles.add("CLERIC");
        roles.add("DRUID");
        roles.add("FIGHTER");
        roles.add("MONK");
        roles.add("PALADIN");
        roles.add("RANGER");
        roles.add("ROGUE");
        roles.add("SORCERER");
        roles.add("WIZARD");
        return roles;
    }

    /**
     * Deletes hero from database, if hero is in troop, he is removed from troop
     * first
     *
     * @param id id of hero to be deleted
     * @return redirects to list of heroes after deleting hero
     */
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.POST)
    public String delete(@PathVariable long id, Model model, UriComponentsBuilder uriBuilder,
            RedirectAttributes redirectAttributes) {
        HeroDTO hero = heroFacade.getHeroWithId(id);
        if (heroFacade.getHeroWithId(id).getTroop() != null) {
            heroFacade.removeTroop(id);
        }
        heroFacade.deleteHero(id);
        log.debug("delete({})", id);
        redirectAttributes.addFlashAttribute("alert_success", "Hero \"" + hero.getName() + "\" was deleted.");
        return "redirect:" + uriBuilder.path("/hero/list").toUriString();
    }

    /**
     * Removes selected hero from troop
     *
     * @param id of hero to be removed from troop
     * @return redirects to list of heroes after deleting hero
     */
    @RequestMapping(value = "/remove/{id}", method = RequestMethod.POST)
    public String remove(@PathVariable long id, Model model, UriComponentsBuilder uriBuilder,
            RedirectAttributes redirectAttributes) {
        HeroDTO hero = heroFacade.getHeroWithId(id);
        if (hero.getTroop() == null) {
            redirectAttributes.addFlashAttribute("alert_warning",
                    "Hero \"" + hero.getName() + "\" is not in troop");
            return "redirect:" + uriBuilder.path("/hero/details/" + id).toUriString();
        }
        heroFacade.removeTroop(id);
        log.debug("removeTroop({})", id);
        redirectAttributes.addFlashAttribute("alert_success",
                "Hero \"" + hero.getName() + "\" was removed from Troop.");
        return "redirect:" + uriBuilder.path("/hero/details/" + id).toUriString();
    }

    /**
     * Displays details about hero and additional actions available
     *
     * @param id id of hero
     * @return displays details about hero
     */
    @RequestMapping(value = "/details/{id}", method = RequestMethod.GET)
    public String details(@PathVariable long id, Model model) {
        log.debug("details({})", id);
        model.addAttribute("hero", heroFacade.getHeroWithId(id));
        return "hero/details";
    }

    /**
     * Displays form for new hero creation
     *
     * @return Form for creating hero
     */
    @RequestMapping(value = "/new", method = RequestMethod.GET)
    public String newHero(Model model) {
        log.debug("new()");
        model.addAttribute("heroCreate", new HeroCreateDTO());
        return "hero/new";
    }

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

    /**
     * Displays form for troop assignment for hero
     *
     * @param id id of hero
     * @return Form for troop assignment
     */
    @RequestMapping(value = "/troop/{id}", method = RequestMethod.POST)
    public String troop(@PathVariable long id, Model model) {
        log.debug("troop assignement()");
        HeroDTO mod = new HeroDTO();
        mod.setId(id);
        model.addAttribute("hero", mod);
        return "hero/troop";
    }

    /**
     * Insert hero into troop
     *
     * @param formBean hero to be added into troop
     * @return Details of hero who has been inserted
     */
    @RequestMapping(value = "/add/{id}", method = RequestMethod.POST)
    public String add(@PathVariable long id, @Valid @ModelAttribute("hero") HeroDTO formBean,
            BindingResult bindingResult, Model model, RedirectAttributes redirectAttributes,
            UriComponentsBuilder uriBuilder) {
        log.debug("add troop(hero={})", 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 "hero/troop";
        }
        if (heroFacade.getHeroWithId(id).getTroop() != null) {
            redirectAttributes.addFlashAttribute("alert_warning",
                    "Hero \"" + heroFacade.getHeroWithId(id).getName() + "\" is already in troop");
            return "redirect:" + uriBuilder.path("/hero/details/" + id).toUriString();
        }
        heroFacade.addTroop(id, formBean.getId());
        redirectAttributes.addFlashAttribute("alert_success", "Hero added into Troop");
        return "redirect:" + uriBuilder.path("/hero/details/{id}").buildAndExpand(id).encode().toUriString();
    }

    /**
     * Changes hero's role
     *
     * @param formBean hero whose role will be changed
     * @return Details of hero whose role has been changed
     */
    @RequestMapping(value = "/change/{id}", method = RequestMethod.POST)
    public String change(@PathVariable long id, @Valid @ModelAttribute("hero") HeroDTO formBean,
            BindingResult bindingResult, Model model, RedirectAttributes redirectAttributes,
            UriComponentsBuilder uriBuilder) {
        log.debug("change role(hero={})", 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 "hero/role";
        }
        heroFacade.changeRole(id, formBean.getRole());
        redirectAttributes.addFlashAttribute("alert_success", "Role was changed");
        return "redirect:" + uriBuilder.path("/hero/details/{id}").buildAndExpand(id).encode().toUriString();
    }

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

    /**
     * Creates hero based on filled form
     *
     * @param formBean hero to be created
     * @return Details of created hero
     */
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public String create(@Valid @ModelAttribute("heroCreate") HeroCreateDTO formBean, BindingResult bindingResult,
            Model model, RedirectAttributes redirectAttributes, UriComponentsBuilder uriBuilder) {
        log.debug("create(heroCreate={})", 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 "hero/new";
        }
        Long id = heroFacade.createHero(formBean);
        redirectAttributes.addFlashAttribute("alert_success", "Hero " + id + " was created");
        return "redirect:" + uriBuilder.path("/hero/details/{id}").buildAndExpand(id).encode().toUriString();
    }

}