Java tutorial
/** * Copyright(C) 2014 * NEC Corporation All rights reserved. * * No permission to use, copy, modify and distribute this software * and its documentation for any purpose is granted. * This software is provided under applicable license agreement only. */ package com.nec.harvest.controller; import java.io.IOException; import java.net.URI; import java.text.ParseException; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.List; import javax.inject.Inject; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.type.TypeReference; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.format.annotation.DateTimeFormat; import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.util.UriComponents; import org.springframework.web.util.UriComponentsBuilder; import com.nec.core.exception.ObjectNotFoundException; import com.nec.core.exception.TooManyObjectsException; import com.nec.harvest.bean.mapping.FixedSystemCostBean; import com.nec.harvest.bean.mapping.ProcessingTypeBean; import com.nec.harvest.bean.mapping.json.JSONBean; import com.nec.harvest.bean.mapping.json.JSONFixedSystemCost; import com.nec.harvest.constant.Constants; import com.nec.harvest.constant.MsgConstants; import com.nec.harvest.exception.ServiceException; import com.nec.harvest.helper.BusinessDayHelper; import com.nec.harvest.helper.MessageHelper; import com.nec.harvest.menu.group.MasterManagementProGroup; import com.nec.harvest.model.Account; import com.nec.harvest.model.Tighten; import com.nec.harvest.model.User; import com.nec.harvest.service.AccountService; import com.nec.harvest.service.FixedSystemCostService; import com.nec.harvest.service.TightenService; import com.nec.harvest.stereotype.MaskFormat; import com.nec.harvest.stereotype.SessionAttribute; import com.nec.harvest.stereotype.UserPrincipal; import com.nec.harvest.util.DateFormatUtil; import com.nec.harvest.util.DateFormatUtil.DateFormat; import com.nec.harvest.util.DateUtil; /** * This is a controller which allow handle all events on the Fixed System Cost * screen * * @author vuta * */ @Controller @RequestMapping(value = Constants.KOTEI_PATH) public class KoteiController extends MasterManagementProGroup implements AbstractRenderer, TitleRenderer { private static final Logger logger = LoggerFactory.getLogger(KoteiController.class); private static final String FIXEDSYSTEMCOST = "fixedSystemCosts"; private static final String ITEMS = "items"; private static final String PROCESS_TYPES = "processingTypes"; private static final String IS_COPY = "isCopy"; private static final String PREVIOUS_MONTH_DATA_STATUS = "perviousMonthDataStatus"; private final TightenService tightenService; private final FixedSystemCostService fixedSystemCostService; private final AccountService accountService; @Value(Constants.PROCESSING_TYPE_NAME) private String classifyProcessing; @Inject public KoteiController(FixedSystemCostService fixedSystemCostService, TightenService tightenService, AccountService accountService) { this.fixedSystemCostService = fixedSystemCostService; this.tightenService = tightenService; this.accountService = accountService; } /** * Default mapping without path variables for KOTEI screen * * @param userOrgCode * @param businessDay * @param proGNo * @param request * @param response * @param model * @return String redirect Uri */ @Override @RequestMapping(value = "", method = RequestMethod.GET) public String render(@SessionAttribute(Constants.SESS_ORGANIZATION_CODE) String userOrgCode, @SessionAttribute(Constants.SESS_BUSINESS_DAY) Date businessDay, @PathVariable String proGNo) { if (logger.isDebugEnabled()) { logger.debug("Redering kotei report without parameters..."); } // Automatically build a redirect link UriComponents uriComponents = UriComponentsBuilder .fromUriString(Constants.KOTEI_PATH + "/{orgCode}/{month}").build(); String businessMonth = DateFormatUtil.format(businessDay, DateFormat.DATE_WITHOUT_DAY); URI uri = uriComponents.expand(proGNo, userOrgCode, businessMonth).encode().toUri(); return "redirect:" + uri.toString(); } /** * This function will be mapped with URL {@link /kotei/{orgCode} * /{businessDay}/{copy}}, it can be used to render the Sales report with a month for a * shop. Will be displayed a message when have a exception or an error * occurred. * * @param orgCode * Shop's code * @param businessDay * Business Day (Date time with format yyyyMM) * @param copy * Copy status for get data (Date time with format yyyyMM) * @param model * Spring's model that can be used to render a view * @return A view name */ @RequestMapping(value = "/{orgCode:[a-z0-9]+}/{monthly:[\\d]+}", method = RequestMethod.GET) public String render(@SessionAttribute(Constants.SESS_ORGANIZATION_CODE) String userOrgCode, @SessionAttribute(Constants.SESS_BUSINESS_DAY) Date businessDay, @PathVariable String proGNo, @PathVariable String orgCode, @PathVariable @DateTimeFormat(pattern = "yyyyMM") Date monthly, final Model model) { if (logger.isDebugEnabled()) { logger.debug("Redering kotei page..."); } logger.info("Trying to generate the kotei template for monthly {} and organization code {}", monthly, orgCode); // String monthYear = null; try { monthYear = DateFormatUtil.format(monthly, DateFormat.DATE_WITHOUT_DAY); model.addAttribute(PROCESSING_MONTH, monthly); } catch (IllegalArgumentException | ObjectNotFoundException ex) { logger.warn(ex.getMessage()); } catch (ServiceException ex) { logger.error(ex.getMessage(), ex); // ??????????? model.addAttribute(ERROR, Boolean.TRUE); model.addAttribute(ERROR_MESSAGE, getSystemError()); return getViewName(); } // initiate account and processing type list initData(model); try { List<FixedSystemCostBean> fixedSystemCosts = new ArrayList<FixedSystemCostBean>(); monthYear = DateFormatUtil.format(monthly, DateFormat.DATE_WITHOUT_DAY); fixedSystemCosts = fixedSystemCostService.findByOrgCodeAndMonth(orgCode, monthYear, false); model.addAttribute(IS_COPY, false); if (CollectionUtils.isEmpty(fixedSystemCosts)) { model.addAttribute(ERROR, true); model.addAttribute(ERROR_MESSAGE, MessageHelper.get(MsgConstants.CM_QRY_M01)); } else { model.addAttribute(FIXEDSYSTEMCOST, fixedSystemCosts); } } catch (IllegalArgumentException | ObjectNotFoundException ex) { logger.warn(ex.getMessage()); // model.addAttribute(ERROR, true); model.addAttribute(ERROR_MESSAGE, MessageHelper.get(MsgConstants.CM_QRY_M01)); } catch (ServiceException ex) { logger.error(ex.getMessage(), ex); // ??????????? model.addAttribute(ERROR_MESSAGE, getSystemError()); model.addAttribute(ERROR, true); return getViewName(); } // The following source code will be detected the end-user can be changed // the sales data or not. If the data already pushed into Tighten table // so that means end-user can not modify the data. Otherwise that is TRUE Tighten tighten = null; Date monthsToSubtract; try { try { String formatBusinessDay = DateFormatUtil.format(businessDay, DateFormat.DATE_WITHOUT_DAY); Date dateBusinessDay = DateFormatUtil.parse(formatBusinessDay, DateFormat.DATE_WITHOUT_DAY); if (monthly.after(dateBusinessDay)) { model.addAttribute(EDITABLE, Boolean.FALSE); } else { tighten = tightenService.findByClassifyAndMonth("1"); // NOTE: fixed value is 1 // The final month year of tighten String getSudoOfTighten = tighten.getGetSudo(); Date monthlyOfTighten = DateFormatUtil.parse(getSudoOfTighten, DateFormat.DATE_WITHOUT_DAY); model.addAttribute(EDITABLE, monthly.after(monthlyOfTighten)); } } catch (NullPointerException | ParseException ex) { logger.warn(ex.getMessage(), ex); // The default is can't be edited model.addAttribute(EDITABLE, Boolean.FALSE); } } catch (IllegalArgumentException | ObjectNotFoundException ex) { logger.warn(ex.getMessage()); monthsToSubtract = DateUtil.monthsToSubtract(businessDay, 3); model.addAttribute(EDITABLE, monthly.after(monthsToSubtract)); } catch (TooManyObjectsException ex) { logger.warn(ex.getMessage(), ex); // The default is can be edited model.addAttribute(EDITABLE, Boolean.TRUE); } catch (ServiceException ex) { logger.error(ex.getMessage(), ex); // ??????????? model.addAttribute(ERROR, Boolean.TRUE); model.addAttribute(ERROR_MESSAGE, getSystemError()); return getViewName(); } // 13 months to subtract based on current month (processing month) monthsToSubtract = DateUtil.monthsToSubtract(businessDay, 12); // ??????????? String previousMonthly = null; if (monthly.after(monthsToSubtract)) { previousMonthly = BusinessDayHelper.getPreviousMonthly(monthYear, DateFormat.DATE_WITHOUT_DAY); } // ?????????? String nextMontly = BusinessDayHelper.getNextMonthly(monthYear, DateFormat.DATE_WITHOUT_DAY); Date tempNextMontly = null; try { tempNextMontly = DateFormatUtil.parse(nextMontly, DateFormat.DATE_WITHOUT_DAY); } catch (NullPointerException | IllegalArgumentException | ParseException ex) { logger.warn(ex.getMessage()); } if (tempNextMontly == null || tempNextMontly.after(businessDay)) { nextMontly = null; } model.addAttribute(PREVIOUS_MONTH, previousMonthly); model.addAttribute(NEXT_MONTH, nextMontly); if (previousMonthly != null) { try { fixedSystemCostService.findByOrgCodeAndMonth(orgCode, previousMonthly, true); } catch (IllegalArgumentException | ObjectNotFoundException ex) { logger.warn(ex.getMessage()); // model.addAttribute(PREVIOUS_MONTH_DATA_STATUS, 1); } catch (ServiceException ex) { logger.error(ex.getMessage(), ex); // ??????????? model.addAttribute(ERROR, Boolean.TRUE); model.addAttribute(ERROR_MESSAGE, getSystemError()); return getViewName(); } } // logger.info("Successfully rendered the kotei view for organization {}", userOrgCode); return getViewName(); } /** * This function will be mapped with URL {@link /kotei/{orgCode}{copy} * /{businessDay}/{copy}}, it can be used to render the Sales report with a month for a * shop. Will be displayed a message when have a exception or an error * occurred. * * @param orgCode * Shop's code * @param businessDay * Business Day (Date time with format yyyyMM) * @param copy * Copy status for get data (Date time with format yyyyMM) * @param model * Spring's model that can be used to render a view * @return A view name */ @RequestMapping(value = "/{orgCode:[a-z0-9]+}/{monthly:[\\d]+}/{copy:[0-9]+}", method = RequestMethod.GET) public String render(@SessionAttribute(Constants.SESS_ORGANIZATION_CODE) String userOrgCode, @SessionAttribute(Constants.SESS_BUSINESS_DAY) Date businessDay, @PathVariable String proGNo, @PathVariable String orgCode, @PathVariable @DateTimeFormat(pattern = "yyyyMM") Date monthly, @PathVariable String copy, final Model model) { if (logger.isDebugEnabled()) { logger.debug("Redering kotei page..."); } logger.info("Trying to generate the kotei template for monthly {} and organization code {}", monthly, orgCode); if (StringUtils.isEmpty(userOrgCode)) { logger.warn("?????????????"); // ????????????? model.addAttribute(ERROR, true); model.addAttribute(ERROR_MESSAGE, MessageHelper.get(MsgConstants.AF001_ENT_CHK_M02)); return getViewName(); } if (businessDay == null) { logger.warn("?????????????"); // ????????????? model.addAttribute(ERROR, true); model.addAttribute(ERROR_MESSAGE, MessageHelper.get(MsgConstants.AF001_ENT_CHK_M03)); return getViewName(); } // initiate account and processing type list initData(model); String monthYear = null; try { monthYear = DateFormatUtil.format(monthly, DateFormat.DATE_WITHOUT_DAY); model.addAttribute(PROCESSING_MONTH, monthly); } catch (IllegalArgumentException | ObjectNotFoundException ex) { logger.warn(ex.getMessage()); } catch (ServiceException ex) { logger.error(ex.getMessage(), ex); // ??????????? model.addAttribute(ERROR, Boolean.TRUE); model.addAttribute(ERROR_MESSAGE, getSystemError()); return getViewName(); } try { List<FixedSystemCostBean> fixedSystemCosts = new ArrayList<FixedSystemCostBean>(); monthYear = DateFormatUtil.format(monthly, DateFormat.DATE_WITHOUT_DAY); fixedSystemCosts = fixedSystemCostService.findByOrgCodeAndMonth(orgCode, monthYear, copy.equals("1")); // model.addAttribute(IS_COPY, true); if (CollectionUtils.isEmpty(fixedSystemCosts)) { model.addAttribute(ERROR, true); model.addAttribute(ERROR_MESSAGE, MessageHelper.get(MsgConstants.CM_QRY_M01)); } else { model.addAttribute(FIXEDSYSTEMCOST, fixedSystemCosts); } } catch (IllegalArgumentException | ObjectNotFoundException ex) { logger.warn(ex.getMessage()); // model.addAttribute(ERROR, true); model.addAttribute(ERROR_MESSAGE, MessageHelper.get(MsgConstants.CM_QRY_M01)); } catch (ServiceException ex) { logger.error(ex.getMessage(), ex); // ??????????? model.addAttribute(ERROR_MESSAGE, getSystemError()); model.addAttribute(ERROR, true); return getViewName(); } // logger.info("Successfully rendered the kotei view for organization {}", userOrgCode); return getViewName(); } /** * This function will be mapped with URL {@link /kotei/save/ * organizationCode} /{businessDay}/{copyStatus}}, it can be used to save * sales data changed. Will be displayed a message when have a exception or * an error occurred. * * @param orgCode * @param monthly * @param params * @param model * @return JSonBean */ @RequestMapping(value = "/save/{orgCode:[a-z0-9]+}/{monthly:[\\d]+}", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE) public @ResponseBody JSONBean saveKoteiData(@UserPrincipal User user, @PathVariable String proGNo, @PathVariable String orgCode, @PathVariable @MaskFormat("######") String monthly, @RequestBody final JSONFixedSystemCost[] jSONFixedSystemCost, final Model model) { if (logger.isDebugEnabled()) { logger.debug("Saving sales data on month: " + monthly + " of organizetion code: " + orgCode); } try { return fixedSystemCostService.handleData(monthly, jSONFixedSystemCost); } catch (IllegalArgumentException ex) { logger.warn(ex.getMessage()); // return new JSONBean(Boolean.FALSE, 2, MessageHelper.get(MsgConstants.CM_UPD_M03)); } } public String getClassifyProcessing() { return classifyProcessing; } public void setClassifyProcessing(String classifyProcessing) { this.classifyProcessing = classifyProcessing; } public void initData(Model model) { try { ObjectMapper objectMapper = new ObjectMapper(); List<ProcessingTypeBean> listOfProcessingTypes = objectMapper.readValue(getClassifyProcessing(), new TypeReference<List<ProcessingTypeBean>>() { }); model.addAttribute(PROCESS_TYPES, listOfProcessingTypes); logger.info("Classify processing: {}", listOfProcessingTypes); } catch (IOException ex) { logger.warn(ex.getMessage()); } try { List<Account> accounts = accountService.findByKoteiKbnAndDelKbn(Constants.DEFAULT_KBN, Constants.DEFAULT_DEL_KBN); model.addAttribute(ITEMS, accounts); } catch (IllegalArgumentException | ObjectNotFoundException | ServiceException ex) { logger.warn(ex.getMessage()); // model.addAttribute(ITEMS, Collections.emptyList()); } } @Override public String getViewName() { return "kotei/kotei"; } @Override public String getTitleName() { return ""; } }