mvc.parent.WebController.java Source code

Java tutorial

Introduction

Here is the source code for mvc.parent.WebController.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 mvc.parent;

import editors.DateEditor;
import entity.Admin;
import entity.Author;
import entity.Branch;
import entity.Direction;
import entity.Order;
import entity.OrderType;
import entity.PaymentType;
import entity.User;
import entity.orderStatus.OrderStatus;
import java.beans.PropertyEditor;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import mvc.OrderController;
import mvc.result.AjaxResult;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.access.WebInvocationPrivilegeEvaluator;
import org.springframework.stereotype.Controller;
import org.springframework.validation.Validator;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import rights.AuthorityWrapper;
import rights.BranchRightsHolder;
import rights.NotRightException;
import rights.Rights;
import rights.UserRightsUtil;
import service.BranchService;
import service.DirectionService;
import service.FileService;
import service.MessageService;
import service.OrderService;
import support.AuthManager;
import support.DateFormatter;
import support.ServiceResult;

/**
 *
 * @author Rice Pavel
 */
@Controller
public class WebController {

    protected Logger log = Logger.getLogger(this.getClass());

    @Autowired
    protected Validator validator;

    @Autowired
    private DateEditor dateEditor;

    @Autowired
    @Qualifier("paymentTypeEditor")
    private PropertyEditor paymentTypeEditor;

    @Autowired
    @Qualifier("orderTypeEditor")
    private PropertyEditor orderTypeEditor;

    @Autowired
    @Qualifier("directionEditor")
    private PropertyEditor directionEditor;

    @Autowired
    @Qualifier("branchEditor")
    private PropertyEditor branchEditor;

    @Autowired
    protected FileService fileService;

    @Autowired
    protected OrderService orderService;

    @Autowired
    protected BranchRightsHolder branchRightsHolder;

    @Autowired
    protected DirectionService directionService;

    @Autowired
    private BranchService branchService;

    @Autowired
    protected AuthManager authManager;

    @Autowired
    private MessageService messageService;

    protected final String ERRORS_LIST_NAME = "errors";

    @InitBinder
    public void standartInitBinder(WebDataBinder binder) {
        binder.registerCustomEditor(Date.class, dateEditor);
        binder.registerCustomEditor(Branch.class, branchEditor);
        binder.registerCustomEditor(PaymentType.class, paymentTypeEditor);
        binder.registerCustomEditor(OrderType.class, orderTypeEditor);
        binder.registerCustomEditor(Direction.class, directionEditor);
        binder.registerCustomEditor(Branch.class, branchEditor);
    }

    @ModelAttribute
    public void setBranchRightsHolder(Map<String, Object> model) {
        model.put("branchRightsHolder", branchRightsHolder);
    }

    protected List<OrderStatus> getRightsStatusList() {
        List<OrderStatus> list = new ArrayList();
        if (UserRightsUtil.isRight(Rights.STATUS_ARCHIVE)) {
            list.add(OrderStatus.ARCHIVE);
        }
        if (UserRightsUtil.isRight(Rights.STATUS_CHECK)) {
            list.add(OrderStatus.CHECK);
        }
        if (UserRightsUtil.isRight(Rights.STATUS_CONFIRMATION)) {
            list.add(OrderStatus.CONFIRMATION);
        }
        if (UserRightsUtil.isRight(Rights.STATUS_NEW)) {
            list.add(OrderStatus.NEW);
        }
        if (UserRightsUtil.isRight(Rights.STATUS_OTHER)) {
            list.add(OrderStatus.OTHER);
        }
        if (UserRightsUtil.isRight(Rights.STATUS_PRICED)) {
            list.add(OrderStatus.PRICED);
        }
        if (UserRightsUtil.isRight(Rights.MENU_READY)) {
            list.add(OrderStatus.READY);
        }
        if (UserRightsUtil.isRight(Rights.MENU_REJECTION)) {
            list.add(OrderStatus.REJECTION);
        }
        if (UserRightsUtil.isRight(Rights.STATUS_REWORK)) {
            list.add(OrderStatus.REWORK);
        }
        if (UserRightsUtil.isRight(Rights.STATUS_WORKING)) {
            list.add(OrderStatus.WORKING);
        }
        return list;
    }

    @ModelAttribute
    public void setInfoAboutUserInParentController(Map<String, Object> model) {
        User user = authManager.getCurrentUser();
        if (user != null) {
            if (user instanceof Author) {
                model.put("isAuthor", true);
            } else if (user instanceof Admin) {
                model.put("isAdmin", true);
            }
            model.put("fullNameOfAuthUser", getFullNameOfAuthUser(user));
        }
    }

    @ModelAttribute
    public void setRoles() {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        User authUser = authManager.getCurrentUser();
        if (authUser != null && auth != null) {
            if (authUser instanceof Admin) {
                AuthorityWrapper wrapper = new AuthorityWrapper(auth, new String[] { "ADMIN" });
                SecurityContextHolder.getContext().setAuthentication(wrapper);
            } else {
                AuthorityWrapper wrapper = new AuthorityWrapper(auth, new String[] { "AUTHOR" });
                SecurityContextHolder.getContext().setAuthentication(wrapper);
            }
        }
    }

    private String getFullNameOfAuthUser(User user) {
        if ((user.getSurname() == null || user.getSurname().isEmpty())
                && (user.getName() == null || user.getName().isEmpty())) {
            return user.getLogin();
        } else {
            return user.getSurname() + " " + user.getName();
        }
    }

    protected void setOrderInfoForMenu(Map<String, Object> model) {
        setOrderInfoForMenu(model, null);
    }

    /**
     * ?  ?  
     *
     * @param model
     * @param authorIdForSearch -  ,    ?.    null
     */
    protected void setOrderInfoForMenu(Map<String, Object> model, Long authorIdForSearch) {
        List<OrderStatus> rightStatusList = getRightsStatusList();
        datastructure.CountOrders countOrders = orderService.getCountOrders(authorIdForSearch, null,
                rightStatusList);

        model.put("Orders_ALL", countOrders.getCountAll());
        model.put("Orders_NEW", countOrders.counts.get(OrderStatus.NEW));
        model.put("Orders_PRICED", countOrders.countHaveCost);
        model.put("Orders_CONFIRMATION", countOrders.counts.get(OrderStatus.CONFIRMATION));
        model.put("Orders_ARCHIVE", countOrders.counts.get(OrderStatus.ARCHIVE));
        model.put("Orders_CHECK", countOrders.counts.get(OrderStatus.CHECK));
        model.put("Orders_CONFIRMATION", countOrders.counts.get(OrderStatus.CONFIRMATION));
        model.put("Orders_READY", countOrders.counts.get(OrderStatus.READY));
        model.put("Orders_REWORK", countOrders.counts.get(OrderStatus.REWORK));
        model.put("Orders_WORKING", countOrders.counts.get(OrderStatus.WORKING));
        model.put("Orders_REJECTION", countOrders.counts.get(OrderStatus.REJECTION));
        model.put("Orders_OTHER", countOrders.counts.get(OrderStatus.OTHER));

        if (authorIdForSearch != null) {
            model.put("authorIdForOrderMenu", authorIdForSearch);
        }

    }

    protected void setInfoForCommonPage(Map<String, Object> model) {
        setInfoForCommonPage(model, null);
    }

    protected void setInfoForCommonPage(Map<String, Object> model, Long authorIdForSearch) {
        setOrderInfoForMenu(model, authorIdForSearch);
        setCommonInfoInParentController(model);
    }

    /**
     *   ?  ??
     *
     * @param orders
     * @param status
     * @return
     */
    private int getSize(List<Order> orders, OrderStatus status) {
        int size = 0;
        if (status != null) {
            for (Order order : orders) {
                if (order.getStatus().equals(status)) {
                    size++;
                }
            }
        }
        return size;
    }

    @ModelAttribute
    public void setDateFormatter(Map<String, Object> model) {
        model.put("dateFormatter", new DateFormatter());
    }

    @ModelAttribute
    public void setDateFormats(Map<String, Object> model) {
        model.put("dateFormat", "dd.MM.yyyy");
        model.put("dateTimeFormat", "dd.MM.yyyy HH:mm");
    }

    public void setCommonInfoInParentController(Map<String, Object> model) {
        Set<Long> branchIds = branchRightsHolder.getBranchIds("/Order/search");
        model.put("branchListForMenu", branchService.getList(branchIds));
        model.put("directionListForMenu", directionService.getAll());
        //model.put("notReadyAuthorMessages", countNotReadyAuthorMessages());
        model.put("overdueOrderCount", orderService.getOverdueCount());
    }

    private int countNotReadyAuthorMessages() {
        Set<Long> rightBranchIds = branchRightsHolder.getBranchIds(OrderController.getUrlForOrderSearch());
        return messageService.countAllNotReadyMessages(rightBranchIds);
    }

    protected void _deleteFile(Long fileId) {
        fileService.deleteFile(fileId);
    }

    protected void _getFile(HttpServletResponse response, Long fileId) throws IOException {
        File file = fileService.getFile(fileId);
        String fileName = fileService.getTransliterateFileName(fileId);
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
        IOUtils.copy(new FileInputStream(file), response.getOutputStream());
    }

    protected void _getFile(HttpServletResponse response, String fileName, byte[] bytes) throws IOException {
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
        response.getOutputStream().write(bytes);
    }

    protected boolean hasBranchRight(Long orderId, String url) {
        try {
            WebController.this.checkBranchRight(orderId, url);
            return true;
        } catch (NotRightException exc) {
            return false;
        }
    }

    /**
     * , ?    url
     *
     * @param orderId  
     * @param url
     * @throws NotRightException
     */
    protected void checkBranchRight(Long orderId, String url) throws NotRightException {
        Order obj = orderService.find(orderId);
        if (obj != null) {
            branchRightsHolder.checkRight(url, obj.getBranch().getBranchId());
        } else {
            throw new NotRightException();
        }
    }

    /**
     * , ?    url
     *
     * @param obj 
     * @param url
     * @throws NotRightException
     */
    protected void checkBranchRight(Order obj, String url) throws NotRightException {
        branchRightsHolder.checkRight(url, obj.getBranch().getBranchId());
    }

    protected AjaxResult getAjaxResult(ServiceResult result) {
        AjaxResult ar = new AjaxResult();
        if (result.hasErrors()) {
            ar.setError(result.getErrors().toString());
        }
        ar.setErrorCode(result.getErrorCode());
        ar.setValue(result.getValue());
        return ar;
    }

    protected void addErrorsToModel(Map<String, Object> model, ServiceResult res) {
        model.put(ERRORS_LIST_NAME, res.getErrors());
    }

    protected void addErrorsToRedirect(RedirectAttributes ra, ServiceResult res) {
        ra.addFlashAttribute(ERRORS_LIST_NAME, res.getErrors());
    }

    protected void addErrorToRedirecrt(RedirectAttributes ra, String error) {
        List<String> errors = new ArrayList();
        errors.add(error);
        ra.addFlashAttribute(ERRORS_LIST_NAME, errors);
    }

    /**
     * ?      url
     *
     * @param url
     * @param branchId
     * @param request
     * @return
     */
    protected boolean hasAllRights(String url, Long branchId, HttpServletRequest request) {
        return hasCommonRights(url, request) && hasFilialRights(url, branchId);
    }

    private boolean hasCommonRights(String url, HttpServletRequest request) {
        WebInvocationPrivilegeEvaluator wipe = (WebInvocationPrivilegeEvaluator) WebApplicationContextUtils
                .getWebApplicationContext(request.getServletContext())
                .getBean(WebInvocationPrivilegeEvaluator.class);
        return wipe.isAllowed(url, SecurityContextHolder.getContext().getAuthentication());
    }

    private boolean hasFilialRights(String url, Long branchId) {
        return branchRightsHolder.isRight(url, branchId);
    }

}