mvc.PaymentController.java Source code

Java tutorial

Introduction

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

import entity.Order;
import entity.Payment;
import entity.PaymentType;
import entity.User;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import mvc.parent.WebController;
import mvc.result.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import rights.NotRightException;
import service.OrderService;
import service.PaymentService;
import service.PaymentTypeService;
import support.ErrorMess;
import support.ServiceResult;

/**
 *
 * @author Rice Pavel
 */
@Controller
@RequestMapping("/Payment")
public class PaymentController extends WebController {

    @Autowired
    private PaymentService paymentService;

    @Autowired
    private PaymentTypeService paymentTypeService;

    @Autowired
    private OrderService orderService;

    @ModelAttribute
    public void setInfo(Map<String, Object> model) {
        model.put("paymentTypeList", paymentTypeService.getActive());
        setInfoForCommonPage(model);
    }

    /*
     @RequestMapping(value = "/getAddPaymentFormToTable")
     public String getAddPaymentFormToTable(Map<String, Object> model,
     @RequestParam("orderId") Long orderId,
     @RequestParam("paymentSum") String paymentSum) {
     model.put("orderId", orderId);
     model.put("paymentSum", paymentSum);
     String userToString = getUserToString();
     model.put("currentUserToString", (userToString != null ? userToString : ""));
     String currentDateToString = getCurrentDateToString();
     model.put("currentDateToString", (currentDateToString != null ? currentDateToString : ""));
     List<PaymentType> list = paymentTypeService.getActive();
     model.put("paymentTypeList", (list != null ? list : new ArrayList()));
     return "Payment_addFormToTable";
     }
        
     private String getUserToString() {
     User authUser = authManager.getCurrentUser();
     String userString = "";
     if (authUser != null) {
     userString += authUser.getSurname() + " " + authUser.getName();
     }
     return userString;
     }
        
     private String getCurrentDateToString() {
     return (new SimpleDateFormat("dd/MM/yy").format(new Date()));
     }
         
     @RequestMapping(value = "/add", params = {"ajax", "notObject"})
     @ResponseBody
     public Map<String, Object> addajax(Map<String, Object> model,
     @RequestParam(value = "amount", required = false) String amountStr,
     @RequestParam(value = "paymentTypeId", required = false) String paymentTypeIdStr,
     @RequestParam("orderId") Long orderId,
     String submit,
     @RequestParam(value = "file", required = false) MultipartFile[] files
     ) {
     Map<String, Object> resultMap = new HashMap();
     String error = "";
     try {
     Payment payment = new Payment();
     Double amount = getDouble(amountStr);
     Long paymentTypeId = getLong(paymentTypeIdStr);
     PaymentType paymentType = null;
     if (paymentTypeId != null) {
     paymentType = paymentTypeService.getOne(paymentTypeId);
     }
     Order order = orderService.find(orderId);;
        
     payment.setAmount(amount);
     payment.setOrder(order);
     payment.setPaymentType(paymentType);
        
     ServiceResult serviceResult = paymentService.save(payment, orderId, files);
     if (serviceResult.hasErrors()) {
     error += serviceResult.getErrors().toString();
     }
     } catch (Exception e) {
     error += StringAdapter.getStackExeption(e);
     }
     if (error.isEmpty()) {
     Double paymentSum = 0.0;
     Order order = orderService.find(orderId);
     if (order != null) {
     paymentSum = order.getPaymentSum();
     }
     resultMap.put("newValue", paymentSum);
     }
     resultMap.put("error", error);
     return resultMap;
     }
        
     private Double getDouble(String str) {
     try {
     return Double.valueOf(str);
     } catch (Exception e) {
     return null;
     }
     }
        
     private Long getLong(String str) {
     try {
     return Long.valueOf(str);
     } catch (Exception e) {
     return null;
     }
     }
     */

    @RequestMapping(value = "/add", params = { "ajax" })
    @ResponseBody
    public Map<String, Object> addAjax(Map<String, Object> model, @ModelAttribute("obj") Payment obj,
            BindingResult result, String submit, @RequestParam("orderId") Long orderId, RedirectAttributes ra,
            HttpServletRequest req, @RequestParam(value = "file", required = false) MultipartFile[] files)
            throws NotRightException, IOException {
        Map<String, Object> resultMap = new HashMap();
        String error = "";
        try {
            checkBranchRight(orderId, "/Payment/add");
            if (!result.hasErrors()) {
                ServiceResult serviceResult = paymentService.save(obj, orderId, files);
                if (serviceResult.hasErrors()) {
                    error += serviceResult.getErrors().toString();
                }
            } else {
                String errorString = getErrors(result, req);
                error += errorString;
            }
        } catch (Exception exc) {
            error += exc.getMessage();
        }
        if (error.isEmpty()) {
            Double paymentSum = 0.0;
            Order order = orderService.find(orderId);
            if (order != null) {
                paymentSum = order.getPaymentSum();
            }
            resultMap.put("newValue", paymentSum);
        }
        resultMap.put("error", error);
        return resultMap;
    }

    private String getErrors(BindingResult result, HttpServletRequest req) {
        String errorString = "";
        ApplicationContext applicationContext = WebApplicationContextUtils
                .getWebApplicationContext(req.getServletContext());
        ResourceBundleMessageSource rbms = applicationContext.getBean(ResourceBundleMessageSource.class);
        for (FieldError error : result.getFieldErrors()) {
            errorString += rbms.getMessage(error.getCode(), null, Locale.US);
        }
        return errorString;
    }

    @RequestMapping(value = "/add")
    public String add(Map<String, Object> model, @ModelAttribute("obj") Payment obj, BindingResult result,
            String submit, @RequestParam("orderId") Long orderId, RedirectAttributes ra, HttpServletRequest req,
            @RequestParam(value = "file", required = false) MultipartFile[] files)
            throws NotRightException, IOException {
        String error = "";
        if (!result.hasErrors()) {
            ServiceResult serviceResult = paymentService.save(obj, orderId, files);
            if (serviceResult.hasErrors()) {
                error += serviceResult.getErrors().toString();
            }
        } else {
            error += getErrors(result, req);
        }
        if (!error.isEmpty()) {
            ra.addFlashAttribute("Payment_error", error);
        }
        return "redirect:/Order/get?orderId=" + orderId;
    }

    @RequestMapping("/delete")
    public String delete(Map<String, Object> model, String submit, @RequestParam("id") Long id,
            @RequestParam("orderId") Long orderId, RedirectAttributes ra) throws NotRightException {
        try {
            Payment payment = paymentService.getOne(id);
            branchRightsHolder.checkRight("/Payment/delete", payment.getOrder().getBranch().getBranchId());
            // ? ?
            paymentService.delete(id);
        } catch (DataIntegrityViolationException e) {
            addErrorToRedirecrt(ra, ErrorMess.EXIST_RELATED_ENTITY);
        }
        return "redirect:/Order/get?orderId=" + orderId;
    }

    @RequestMapping(value = "/delete", params = { "ajax" })
    @ResponseBody
    public AjaxResult deleteByAjax(Map<String, Object> model, @RequestParam("id") Long id,
            @RequestParam("orderId") Long orderId) throws NotRightException {
        try {
            Payment payment = paymentService.getOne(id);
            if (!branchRightsHolder.isRight("/Payment/delete", payment.getOrder().getBranch().getBranchId())) {
                return new AjaxResult("?? ");
            }
            paymentService.delete(id);
            return new AjaxResult();
        } catch (Exception e) {
            return new AjaxResult(e.getMessage());
        }
    }

    /**
     * ?, ? ?  
     *
     * @param model
     * @param orderId
     * @return
     */
    @RequestMapping(value = "/search", params = { "fromOrder" })
    public String searchFromOrder(Map<String, Object> model, @RequestParam("orderId") Long orderId) {
        Order order = orderService.find(orderId);
        Long branchId = 0L;
        if (order != null && order.getBranch() != null) {
            branchId = order.getBranch().getBranchId();
        }
        model.put("order", order);
        model.put("branchId", branchId);
        model.put("obj", new Payment());
        return "Payment_search";
    }

    /**
     * ?, ? ?  ? 
     */
    @RequestMapping("/search")
    public String search(Map<String, Object> model, @RequestParam("orderId") Long orderId) {
        List<Payment> list = paymentService.getByOrderId(orderId);
        model.put("list", list);
        model.put("branchId", getBranchId(orderId));
        model.put("obj", new Payment());
        model.put("orderId", orderId);
        return "Payment_search_window";
    }

    /**
     *  
     */
    @RequestMapping("/getFile")
    public void getFile(@RequestParam("fileId") Long fileId, HttpServletResponse response) throws IOException {
        _getFile(response, fileId);
    }

    private Long getBranchId(Long orderId) {
        Order order = orderService.find(orderId);
        return order.getBranch().getBranchId();
    }

}