com.nec.harvest.controller.LoginController.java Source code

Java tutorial

Introduction

Here is the source code for com.nec.harvest.controller.LoginController.java

Source

/*
 * 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.io.PrintWriter;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mobile.device.Device;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.WebAttributes;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.nec.core.exception.ObjectNotFoundException;
import com.nec.harvest.constant.Constants;
import com.nec.harvest.constant.MsgConstants;
import com.nec.harvest.exception.HarvestAuthenticationException;
import com.nec.harvest.exception.OrganizationNotFoundException;
import com.nec.harvest.exception.ServiceException;
import com.nec.harvest.helper.MessageHelper;
import com.nec.harvest.http.HttpServletContentType;
import com.nec.harvest.model.BusinessDay;
import com.nec.harvest.model.Message;
import com.nec.harvest.model.Organization;
import com.nec.harvest.model.User;
import com.nec.harvest.service.BusinessDayService;
import com.nec.harvest.service.OrganizationService;
import com.nec.harvest.stereotype.SessionAttribute;
import com.nec.harvest.stereotype.UserPrincipal;

/**
 * The controller provides some methods which accept or denied a request from
 * client
 * 
 * @author hungpd
 * 
 */
@Controller
public class LoginController extends BaseController
        implements AuthenticatedController, ViewRenderer, TitleRenderer {

    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);

    private BusinessDay businessDay = null;

    private final OrganizationService organizationService;

    private final BusinessDayService businessDayService;

    @Inject
    public LoginController(OrganizationService organizationService, BusinessDayService businessDayService) {
        this.organizationService = organizationService;
        this.businessDayService = businessDayService;
    }

    /** {@inheritDoc} */
    @RequestMapping(value = "", method = RequestMethod.GET)
    public String render() {
        logger.debug("Redering the login page without path ...");

        // Automatically redirect to the login page when end-user type wrong
        // path or not authenticate
        return "redirect:/login";
    }

    /**
     * The REST handle login event for the given username and password
     * 
     * @param request
     *            A HttpServletRequest
     * @param model
     *            Spring's model that can be used to render a view
     * @return A redirect URL
     */
    @RequestMapping(value = "/login**")
    public String login(@RequestParam(value = "error", required = false) boolean error,
            @SessionAttribute(WebAttributes.AUTHENTICATION_EXCEPTION) AuthenticationException authException,
            final HttpServletRequest request, final Model model) {
        if (logger.isDebugEnabled()) {
            logger.debug("Rendering the loggin page...");
        }

        // Get close confirm message when user click CLOSE application button on the login page
        model.addAttribute(Constants.CFM_CLOSE_APPLICATION_MESSAGE, getCloseAppMsg());

        // 
        if (error && authException != null) {
            logger.warn(authException.getMessage());

            Message message;

            // ??????????
            if (authException instanceof BadCredentialsException) {
                message = MessageHelper.get(MsgConstants.AF001_ENT_CHK_M01);
            } else {
                Throwable throwable = authException.getCause();
                if (throwable instanceof HarvestAuthenticationException) {
                    message = MessageHelper.get(MsgConstants.AF001_ENT_CHK_M01);
                } else if (throwable instanceof OrganizationNotFoundException) {
                    message = MessageHelper.get(MsgConstants.AF001_ENT_CHK_M02);
                } else if (authException instanceof AuthenticationServiceException) { // NOTE: This case is authentication method not supported: GET
                    logger.warn(authException.getMessage());

                    // This exception will be throw when end-user type directly or try to access
                    // by URL: .../j_spring_security_check
                    message = MessageHelper.get(MsgConstants.AF001_ENT_CHK_M01);
                } else {
                    message = getSystemError();
                    if (logger.isDebugEnabled()) {
                        logger.debug(authException.getMessage(), authException.getCause());
                    }

                    // 
                    logger.error(authException.getMessage(), authException.getCause());
                }
            }

            // 
            model.addAttribute(ERROR, true);
            model.addAttribute(ERROR_MESSAGE, message);

            // Clear authentication exception from the SESSION
            request.getSession().setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION, null);
        }

        return getViewName();
    }

    /**
     * ?
     * 
     * @param user
     * @param request
     * @param model
     * @param device
     * @return
     */
    @RequestMapping(value = "/j_spring_security_authen")
    public String authen(@UserPrincipal User user, final HttpServletResponse response, final Model model,
            final Device device) {
        if (user == null || StringUtils.isEmpty(user.getUsrCode())) {
            logger.equals("??????????");

            // ??????????
            model.addAttribute(ERROR, true);
            model.addAttribute(ERROR_MESSAGE, MessageHelper.get(MsgConstants.AF001_ENT_CHK_M01));
            return getViewName();
        }

        Organization userOrg = user.getOrganization();
        if (userOrg == null || StringUtils.isEmpty(userOrg.getStrCode())) {
            logger.equals("?????????????");

            // ?????????????
            model.addAttribute(ERROR, true);
            model.addAttribute(ERROR_MESSAGE, MessageHelper.get(MsgConstants.AF001_ENT_CHK_M02));
            return getViewName();
        }

        // Wait seconds... The system trying to check the organization code for authenticating user {usernameOrUsrCode}
        logger.info("Please wait second(s)... The system trying to check the organization code for authenticating "
                + "user " + user.getUsrName());

        try {
            Organization organization = organizationService.findByOrgCodeAndKaisoBango(userOrg.getStrCode(),
                    Constants.DEFAULT_DEPARTMENTAL_CODE);
            if (organization != null) {
                // LOG
            }
        } catch (IllegalArgumentException | ObjectNotFoundException ex) {
            logger.warn(ex.getMessage());

            // ?????????????
            model.addAttribute(ERROR, true);
            model.addAttribute(ERROR_MESSAGE, MessageHelper.get(MsgConstants.AF001_ENT_CHK_M02));
            return getViewName();
        } catch (ServiceException ex) {
            logger.error(ex.getMessage(), ex);

            // ???????????
            model.addAttribute(ERROR, true);
            model.addAttribute(ERROR_MESSAGE, getSystemError());
            return getViewName();
        }

        // Wait seconds... The system trying to check the business day for authenticating user {usernameOrUsrCode}
        logger.info("Please wait second(s)... The system trying to check the business day for authenticating user "
                + user.getUsrName());

        try {
            // ??(harvest
            // ???????????(MsgID:AF001.EntChk.M03)?????ID/PASS??????????
            businessDay = (BusinessDay) businessDayService.findByEigyobiCode(Constants.DEFAULT_BUSINESS_DAY_CODE);
            if (businessDay == null || businessDay.getEigDate() == null) {
                logger.warn("?????????????");

                // ?????????????
                model.addAttribute(ERROR, true);
                model.addAttribute(ERROR_MESSAGE, MessageHelper.get(MsgConstants.AF001_ENT_CHK_M03));
                return getViewName();
            }
        } catch (IllegalArgumentException | ObjectNotFoundException ex) {
            logger.warn(ex.getMessage());

            // ?????????????
            model.addAttribute(ERROR, true);
            model.addAttribute(ERROR_MESSAGE, MessageHelper.get(MsgConstants.AF001_ENT_CHK_M03));
            return getViewName();
        } catch (ServiceException ex) {
            logger.error(ex.getMessage(), ex);

            // ???????????
            model.addAttribute(ERROR, true);
            model.addAttribute(ERROR_MESSAGE, getSystemError());
            return getViewName();
        }

        // Fix QA 112 2014/07/19 SONDN
        // ??????????????
        // ??????????

        // ???????
        // ???????????(MsgID:AF001.EntChk.M04)?????ID/PASS??????????
        if (StringUtils.isEmpty(userOrg.getStrCodeUp())) {
            logger.warn("?????????????");

            // ?????????????
            model.addAttribute(ERROR, true);
            model.addAttribute(ERROR_MESSAGE, MessageHelper.get(MsgConstants.AF001_ENT_CHK_M04));
            return getViewName();
        }

        logger.info("Sucessfully logged-in by user {}", user.getUsrName());

        // True if this device is a tablet device such as an Apple iPad or a Motorola Xoom.
        // Could be used by a pre-handle interceptor to redirect the user to a dedicated tablet web site.
        // Could be used to apply a different page layout or stylesheet when the device is a tablet device.
        if (device.isTablet()) {
            return "redirect:/menu";
        }

        //
        response.setContentType(HttpServletContentType.PLAN_TEXT);

        try {
            PrintWriter out = response.getWriter();
            out.println("<html xmlns=\"http://www.w3.org/1999/xhtml\">");
            out.println("<head>");
            out.println("<title></title>");
            out.println("<script type=\"text/javascript\">");
            out.println("function forceFullscreen(strUrl) {");
            out.println(
                    "var newWindow = window.open (strUrl, \"_blank\", \"fullWindow,fullscreen=yes,left=0,top=0,toolbar=no,location=no,status=no,resizable=no,menubar=no,channelmode=yes,scrollbars=no,directories=no\");");
            out.println("if (window.focus) { newWindow.focus(); }");
            out.println("window.open(\"\",\"_parent\",\"\");");
            out.println("window.close();");
            out.println("return false; }");
            out.println("forceFullscreen(\"menu\");");
            out.println("</script>");
            out.println("</head>");
            out.println("<body>");
            out.println("<p>Please Wait, Loading...</p>");
            out.println("</body>");
            out.println("</html>");

            // ???
            out.close();
        } catch (IOException ex) {
            logger.error(ex.getMessage(), ex);
        }
        return null;
    }

    @RequestMapping(value = "/secure/denied")
    public String accessDeniedHandler() {
        logger.info(
                "Sorry, you don't have permission to access this url. Please login again with right permission");

        // If the end-user does not have permission to access a URL
        // then we will have to redirect to login page
        return "redirect:/login";
    }

    @Override
    public String getViewName() {
        return "login/login";
    }

    @Override
    public String getTitleName() {
        return "";
    }

}