Example usage for javax.servlet.http HttpServletRequest getLocalAddr

List of usage examples for javax.servlet.http HttpServletRequest getLocalAddr

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest getLocalAddr.

Prototype

public String getLocalAddr();

Source Link

Document

Returns the Internet Protocol (IP) address of the interface on which the request was received.

Usage

From source file:org.bibalex.wamcp.application.WAMCPUiActionListener.java

public void generateMARCFiles(ActionEvent ev) {

    String dirUrlStr = URLPathStrUtils.appendParts(this.galleryBean.getGalleryRootUrlStr(), "XML");

    HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext()
            .getRequest();/*w ww  .  ja va2 s.  c  om*/
    String uri = request.getRequestURL().toString();
    String[] splited = uri.split("/");
    // host = http://172.16.0.17:80/
    //        String host = splited[0]+"//"+splited[2]+"/";
    String host = splited[0] + "//" + request.getLocalAddr() + ":" + request.getLocalPort() + "/";

    try {
        List<String> childrenFilesStr = BAGStorage.listChildren(dirUrlStr, FileType.FILE);
        int statusCode = 0;
        String XMLFilePath;
        for (String childStr : childrenFilesStr) {
            System.out.println("childStr: " + childStr);
            XMLFilePath = URLPathStrUtils.appendParts(dirUrlStr, childStr);

            //File XMLfile = new File(XMLFilePath);
            //   FileObject imageFO;

            //   imageFO = VFS.getManager().resolveFile(XMLFilePath);

            File XMLfile = null;
            try {
                XMLfile = File.createTempFile(FileUtils.makeSafeFileName(childStr), "msDescReleased");

                BAGStorage.readRemoteFile(XMLFilePath, new FileOutputStream(XMLfile));
            } catch (IOException e1) {
                this.handleException(e1);
            }

            //   URL url = new URL(XMLFilePath);
            //   InputStream is = url.openStream();

            try {
                WAMCPStorage.generateMARCFile(XMLfile, childStr, this.galleryBean.getGalleryRootUrlStr());
            } catch (WAMCPGeneralCorrectableException e) {
                // TODO Auto-generated catch block
                this.handleException(e);
            } catch (IOException e) {
                this.handleException(e);
            }

            //            int extIndx = childStr.indexOf('.');
            //            String localOaiId = childStr.substring(0, extIndx);
            //            
            //            BAOAIIDBuilder oaiIdBuilder = new BAOAIIDBuilder();
            //            String oaiId = oaiIdBuilder.buildId(localOaiId);
            //            System.out.println("oaiId: "+oaiId);
            //                        
            //            String urlMetadataHtml = host+"BAG-API/rest/desc/"+oaiId+"/transform?type=meta";
            //            statusCode = WAMCPStorage.myGetHttp(urlMetadataHtml);
            //            System.out.println(urlMetadataHtml +" ==> status code: "+statusCode);

        }

    } catch (BAGException e) {
        this.handleException(e);
    }
}

From source file:org.bibalex.wamcp.application.WAMCPUiActionListener.java

public void generateImagePdfFiles(ActionEvent ev) {

    String dirUrlStr = URLPathStrUtils.appendParts(this.galleryBean.getGalleryRootUrlStr(), "XML");
    //      System.out.println("dirUrlStr: "+dirUrlStr);

    HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext()
            .getRequest();//from ww w  . j a va  2s  . co  m
    String uri = request.getRequestURL().toString();
    //        System.out.println("uri: "+uri);
    String[] splited = uri.split("/");
    // host = http://172.16.0.17:80/
    //      String host = splited[0]+"//"+splited[2]+"/";
    String host = splited[0] + "//" + request.getLocalAddr() + ":" + request.getLocalPort() + "/";

    //        System.out.println("Host: "+host);

    try {
        List<String> childrenFilesStr = BAGStorage.listChildren(dirUrlStr, FileType.FILE);
        //         String rootUrlStr = this.galleryBean.getGalleryRootUrlStr();
        //         String tempUserName = this.wamcpSessionBBean.getUserName();
        int statusCode = 0;

        for (String childStr : childrenFilesStr) {
            System.out.println("childStr: " + childStr);
            int extIndx = childStr.indexOf('.');
            String localOaiId = childStr.substring(0, extIndx);

            BAOAIIDBuilder oaiIdBuilder = new BAOAIIDBuilder();
            String oaiId = oaiIdBuilder.buildId(localOaiId);
            //            System.out.println("oaiId: "+oaiId);

            String urlImagesPdf = host + "BAG-API/rest/desc/" + oaiId + "/transform?type=img";
            statusCode = WAMCPStorage.myGetHttp(urlImagesPdf);
            System.out.println(urlImagesPdf + " ==> status code: " + statusCode);
            //            WAMCPStorage.transformXMLtoHTML(rootUrlStr, tempUserName,
            //                  localOaiId, true);
            //            WAMCPStorage.transformXMLtoHTML(rootUrlStr, tempUserName,
            //                  localOaiId, false);

        }

    } catch (BAGException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:com.esd.ps.RegListController.java

/**
 * ??/* w w w. j  a  v  a  2 s .  com*/
 * 
 * @param idArr
 * @param request
 * @return
 */
@RequestMapping(value = "/export", method = RequestMethod.POST)
@ResponseBody
public Map<String, Object> export(String beginDate, String endDate, HttpServletRequest request,
        HttpSession session) {
    Map<String, Object> map = new HashMap<>();
    boolean b = true;
    String FileDownloadPath = "null";
    int districtId = Integer.parseInt(session.getAttribute(Constants.ID).toString());
    SimpleDateFormat sdf = new SimpleDateFormat(Constants.DATE_FORMAT);
    SimpleDateFormat formatter = new SimpleDateFormat(Constants.DATE_FORMAT_HAVE_LINE);
    try {
        // 
        String url = request.getSession().getServletContext().getRealPath("/");
        // 
        File downloadPath = new File(url + Constants.EXCELTEMP);
        if (!(downloadPath.exists())) {
            downloadPath.mkdir();
        }
        // ??File.separator
        // String uuid = UUID.randomUUID().toString();
        String pinyin = session.getAttribute(Constants.PINYIN).toString();
        String exportPath = null, fileName = null;

        if (beginDate.isEmpty() || beginDate == null || beginDate.trim().length() == 0) {
            fileName = pinyin + "_" + sdf.format(new Date());
        } else {
            fileName = sdf.format(sdf.parse(beginDate)) + "-" + sdf.format(sdf.parse(endDate)) + "_" + pinyin
                    + "_" + sdf.format(new Date());
            Date myDate = formatter.parse(endDate);
            Calendar c = Calendar.getInstance();
            c.setTime(myDate);
            c.add(Calendar.DATE, 1);
            myDate = c.getTime();
            endDate = sdf.format(myDate);
        }
        exportPath = downloadPath + File.separator + fileName + ".xls";
        List<Registration> list = registrationService.getAllByTimeAndDistrictId(districtId, beginDate, endDate);
        // 
        b = PoiCreateExcel.createRegistrationExcel(exportPath, list);
        if (b) {
            String destPath = request.getLocalAddr() + ":" + request.getLocalPort() + request.getContextPath();
            FileDownloadPath = "http://" + destPath + "/" + Constants.EXCELTEMP + "/" + fileName + ".xls";
        }
    } catch (ParseException e) {
        e.printStackTrace();
    }
    map.clear();
    map.put(Constants.WRONGPATH, FileDownloadPath);
    return map;
}

From source file:com.jd.survey.web.survey.PublicSurveyController.java

/**
 * Prepares the edit survey page//  w ww. jav  a2 s  .  c o m
 * @param surveyId
 * @param order
 * @param uiModel
 * @param principal
 * @return
 */
@RequestMapping(value = "/{id}/{po}", produces = "text/html")
public String editSurveyPage(@PathVariable("id") Long surveyId, @PathVariable("po") Short order, Model uiModel,
        HttpServletRequest httpServletRequest) {
    log.info("editSurveyPage surveyId=" + surveyId + " pageOrder" + order);
    try {
        SurveyPage surveyPage = surveyService.surveyPage_get(surveyId, order,
                messageSource.getMessage(DATE_FORMAT, null, LocaleContextHolder.getLocale()));
        SurveyDefinition surveyDefinition = surveySettingsService
                .surveyDefinition_findById(surveyPage.getSurvey().getTypeId());

        //randomize the questions order
        if (surveyPage.getRandomizeQuestions()) {
            Collections.shuffle(surveyPage.getQuestionAnswers(), new Random(System.nanoTime()));
        }

        //randomize the questions options orders
        for (QuestionAnswer questionAnswer : surveyPage.getQuestionAnswers()) {
            questionAnswer.getQuestion()
                    .setOptionsList(new ArrayList<QuestionOption>(questionAnswer.getQuestion().getOptions()));
            if (questionAnswer.getQuestion().getRandomizeOptions()) {
                Collections.shuffle(questionAnswer.getQuestion().getOptionsList(),
                        new Random(System.nanoTime()));
            }
        }

        //survey definition not open to the public
        if (!surveyDefinition.getIsPublic()) {
            log.warn(SURVEY_NOT_PUBLIC_WARNING_MESSAGE + httpServletRequest.getPathInfo()
                    + FROM_IP_WARNING_MESSAGE + httpServletRequest.getLocalAddr());
            return "accessDenied";
        }
        //Attempt to access a survey from different IP Address
        if (!surveyPage.getSurvey().getIpAddress().equalsIgnoreCase(httpServletRequest.getLocalAddr())) {
            log.warn(UNAUTHORIZED_ATTEMPT_TO_ACCESS_SURVEY_WARNING_MESSAGE + httpServletRequest.getPathInfo()
                    + FROM_IP_WARNING_MESSAGE + httpServletRequest.getLocalAddr());
            return "accessDenied";
        }

        List<SurveyPage> surveyPages = surveyService.surveyPage_getAll(surveyId,
                messageSource.getMessage(DATE_FORMAT, null, LocaleContextHolder.getLocale()));
        uiModel.addAttribute("survey_base_path", "open");
        uiModel.addAttribute("survey", surveyPage.getSurvey());
        uiModel.addAttribute("surveyPage", surveyPage);
        uiModel.addAttribute("surveyDefinition",
                surveySettingsService.surveyDefinition_findById(surveyPage.getSurvey().getTypeId()));
        uiModel.addAttribute("surveyPages", surveyPages);
        return "surveys/page";
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw (new RuntimeException(e));
    }
}

From source file:com.jd.survey.web.reports.ReportController.java

/**
 * Exports survey data to an Excel file/*w w w.j a v  a2  s. c o m*/
 * @param surveyDefinitionId
 * @param principal
 * @param uiModel
 * @param httpServletRequest
 * @return
 */
@Secured({ "ROLE_ADMIN", "ROLE_SURVEY_ADMIN" })
@RequestMapping(value = "/{id}", params = "excel", produces = "text/html")
public ModelAndView surveyExcelExport(@PathVariable("id") Long surveyDefinitionId, Principal principal,
        Model uiModel, HttpServletResponse response, HttpServletRequest httpServletRequest) {
    try {
        SurveyDefinition surveyDefinition = surveySettingsService.surveyDefinition_findById(surveyDefinitionId);
        List<Map<String, Object>> surveys = reportDAO.getSurveyData(surveyDefinitionId);

        Map<String, String> messages = new TreeMap<String, String>();

        messages.put("surveyId", messageSource.getMessage(SURVEY_ID, null, LocaleContextHolder.getLocale()));
        messages.put("surveyName",
                messageSource.getMessage(SURVEY_NAME, null, LocaleContextHolder.getLocale()));
        messages.put("firstname", messageSource.getMessage(FIRST_NAME, null, LocaleContextHolder.getLocale()));
        messages.put("middlename",
                messageSource.getMessage(MIDDLE_NAME, null, LocaleContextHolder.getLocale()));
        messages.put("lastname", messageSource.getMessage(LAST_NAME, null, LocaleContextHolder.getLocale()));
        messages.put("submissionDate",
                messageSource.getMessage(SUBMISSION_DATE, null, LocaleContextHolder.getLocale()));
        messages.put("creationDate",
                messageSource.getMessage(CREATION_DATE, null, LocaleContextHolder.getLocale()));
        messages.put("lastUpdateDate",
                messageSource.getMessage(LAST_UPDATE, null, LocaleContextHolder.getLocale()));
        messages.put("ipaddress", messageSource.getMessage(IP_ADDRESS, null, LocaleContextHolder.getLocale()));

        String login = principal.getName();
        User user = userService.user_findByLogin(login);
        //Check if the user is authorized
        if (!securityService.userIsAuthorizedToManageSurvey(surveyDefinitionId, user)) {
            log.warn("Unauthorized access to url path " + httpServletRequest.getPathInfo()
                    + " attempted by user login:" + principal.getName() + "from IP:"
                    + httpServletRequest.getLocalAddr());
            response.sendRedirect("../accessDenied");

        }

        ModelAndView modelAndView = new ModelAndView("surveyList");
        modelAndView.addObject("surveyDefinition", surveyDefinition);
        modelAndView.addObject("surveys", surveys);
        modelAndView.addObject("messages", messages);
        return modelAndView;
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw new RuntimeException(e);
    }
}

From source file:org.openmrs.module.bom.web.controller.LoginPageOverrideController.java

@RequestMapping(value = "/myLogin.htm", method = RequestMethod.POST)
public String loginUser(ModelMap model, HttpSession session, HttpServletRequest request,
        HttpServletResponse response) {// www.ja v  a2s .c o m

    String redirect = null;

    try {
        String username = request.getParameter("uname");
        String password = request.getParameter("pw");

        // get the place to redirect: for touch screen this is simple
        redirect = determineRedirect(request);

        // only try to authenticate if they actually typed in a username
        if (username != null && username.length() > 0) {

            Context.authenticate(username, password);

            if (Context.isAuthenticated()) {

                User user = Context.getAuthenticatedUser();

                // load the user's default locale if possible
                if (user.getUserProperties() != null) {
                    if (user.getUserProperties().containsKey(OpenmrsConstants.USER_PROPERTY_DEFAULT_LOCALE)) {
                        String localeString = user
                                .getUserProperty(OpenmrsConstants.USER_PROPERTY_DEFAULT_LOCALE);
                        Locale locale = null;
                        if (localeString.length() == 5) {
                            //user's locale is language_COUNTRY (i.e. en_US)
                            String lang = localeString.substring(0, 2);
                            String country = localeString.substring(3, 5);
                            locale = new Locale(lang, country);
                        } else {
                            // user's locale is only the language (language plus greater than 2 char country code
                            locale = new Locale(localeString);
                        }
                        OpenmrsCookieLocaleResolver oclr = new OpenmrsCookieLocaleResolver();
                        oclr.setLocale(request, response, locale);
                    }
                }

                // In case the user has no preferences, make sure that the context has some locale set
                if (Context.getLocale() == null) {
                    Context.setLocale(OpenmrsConstants.GLOBAL_DEFAULT_LOCALE);
                }

            }

            if (log.isDebugEnabled()) {
                log.debug("Redirecting after login to: " + redirect);
                log.debug("Locale address: " + request.getLocalAddr());
            }

            response.sendRedirect(redirect);

            //return redirect;
        }
    } catch (ContextAuthenticationException e) {
        // set the error message for the user telling them
        // to try again
        //session.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "auth.password.invalid");
        log.error("failed to authenticate: ", e);
    } catch (Exception e) {
        log.error("Uexpected auth error", e);
    }

    // send the user back the login page because they either 
    // had a bad password or are locked out

    session.setAttribute(WebConstants.OPENMRS_MSG_ATTR,
            Context.getMessageSourceService().getMessage("rwandaprimarycare.loginFailed"));
    session.setAttribute(WebConstants.OPENMRS_LOGIN_REDIRECT_HTTPSESSION_ATTR, redirect);

    return "/module/bom/bomLogin";
}

From source file:org.apache.openaz.xacml.rest.XACMLPapServlet.java

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 *//*from  w w  w. j a v  a  2 s . co m*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {
        XACMLRest.dumpRequest(request);

        // Is this from the Admin Console?
        String groupId = request.getParameter("groupId");
        if (groupId != null) {
            // this is from the Admin Console, so handle separately
            doACGet(request, response, groupId);
            return;
        }
        //
        // Get the PDP's ID
        //
        String id = this.getPDPID(request);
        logger.info("doGet from: " + id);
        //
        // Get the PDP Object
        //
        PDP pdp = this.papEngine.getPDP(id);
        //
        // Is it known?
        //
        if (pdp == null) {
            //
            // Check if request came from localhost
            //
            String message = "Unknown PDP: " + id + " from " + request.getRemoteHost() + " us: "
                    + request.getLocalAddr();
            logger.info(message);
            if (request.getRemoteHost().equals("localhost") || request.getRemoteHost().equals("127.0.0.1") //NOPMD
                    || request.getRemoteHost().equals(request.getLocalAddr())) {
                //
                // Return status information - basically all the groups
                //
                Set<PDPGroup> groups = papEngine.getPDPGroups();

                // convert response object to JSON and include in the response
                ObjectMapper mapper = new ObjectMapper();
                mapper.writeValue(response.getOutputStream(), groups);
                response.setHeader("content-type", "application/json");
                response.setStatus(HttpServletResponse.SC_OK);
                return;
            }
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, message);
            return;
        }
        //
        // Get the PDP's Group
        //
        PDPGroup group = this.papEngine.getPDPGroup(pdp);
        if (group == null) {
            String message = "No group associated with pdp " + pdp.getId();
            logger.warn(message);
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, message);
            return;
        }
        //
        // Which policy do they want?
        //
        String policyId = request.getParameter("id");
        if (policyId == null) {
            String message = "Did not specify an id for the policy";
            logger.warn(message);
            response.sendError(HttpServletResponse.SC_NOT_FOUND, message);
            return;
        }
        PDPPolicy policy = group.getPolicy(policyId);
        if (policy == null) {
            String message = "Unknown policy: " + policyId;
            logger.warn(message);
            response.sendError(HttpServletResponse.SC_NOT_FOUND, message);
            return;
        }
        //
        // Get its stream
        //
        try (InputStream is = policy.getStream(); OutputStream os = response.getOutputStream()) {
            //
            // Send the policy back
            //
            IOUtils.copy(is, os);

            response.setStatus(HttpServletResponse.SC_OK);
        } catch (PAPException e) {
            String message = "Failed to open policy id " + policyId;
            logger.error(message);
            response.sendError(HttpServletResponse.SC_NOT_FOUND, message);
        }
    } catch (PAPException e) {
        logger.error("GET exception: " + e, e);
        response.sendError(500, e.getMessage());
        return;
    }
}

From source file:org.openmrs.module.rwandaprimarycare.LoginController.java

@RequestMapping(method = RequestMethod.POST)
public String loginUser(ModelMap model, HttpSession session, HttpServletRequest request,
        HttpServletResponse response) {/*from   w  w w.  j a  va 2 s . c  o  m*/

    String redirect = null;

    try {
        String username = request.getParameter("uname");
        String password = request.getParameter("pw");

        // get the place to redirect: for touch screen this is simple
        redirect = determineRedirect(request);

        // only try to authenticate if they actually typed in a username
        if (username != null && username.length() > 0) {

            Context.authenticate(username, password);

            if (Context.isAuthenticated()) {

                User user = Context.getAuthenticatedUser();

                if (user.getUserProperties() != null && !user.getUserProperties().containsKey("keyboardType")) {
                    user.getUserProperties().put("keyboardType", "QWERTY"); //ABC is the other option
                    user = Context.getUserService().saveUser(user, null);
                }
                session.setAttribute("keyboardType", user.getUserProperty("keyboardType"));

                // load the user's default locale if possible
                if (user.getUserProperties() != null) {
                    if (user.getUserProperties().containsKey(OpenmrsConstants.USER_PROPERTY_DEFAULT_LOCALE)) {
                        String localeString = user
                                .getUserProperty(OpenmrsConstants.USER_PROPERTY_DEFAULT_LOCALE);
                        Locale locale = null;
                        if (localeString.length() == 5) {
                            //user's locale is language_COUNTRY (i.e. en_US)
                            String lang = localeString.substring(0, 2);
                            String country = localeString.substring(3, 5);
                            locale = new Locale(lang, country);
                        } else {
                            // user's locale is only the language (language plus greater than 2 char country code
                            locale = new Locale(localeString);
                        }
                        OpenmrsCookieLocaleResolver oclr = new OpenmrsCookieLocaleResolver();
                        oclr.setLocale(request, response, locale);
                    }
                }

                // In case the user has no preferences, make sure that the context has some locale set
                if (Context.getLocale() == null) {
                    Context.setLocale(OpenmrsConstants.GLOBAL_DEFAULT_LOCALE);
                }

            }

            if (log.isDebugEnabled()) {
                log.debug("Redirecting after login to: " + redirect);
                log.debug("Locale address: " + request.getLocalAddr());
            }

            response.sendRedirect(redirect);

            //return redirect;
        }
    } catch (ContextAuthenticationException e) {
        // set the error message for the user telling them
        // to try again
        //session.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "auth.password.invalid");
        log.error("failed to authenticate: ", e);
    } catch (Exception e) {
        log.error("Uexpected auth error", e);
    }

    // send the user back the login page because they either 
    // had a bad password or are locked out

    session.setAttribute(WebConstants.OPENMRS_MSG_ATTR,
            Context.getMessageSourceService().getMessage("rwandaprimarycare.loginFailed"));
    session.setAttribute(WebConstants.OPENMRS_LOGIN_REDIRECT_HTTPSESSION_ATTR, redirect);

    return "/module/rwandaprimarycare/login";
}

From source file:com.ycszh.ssh.service.veh.impl.SlgVehServiceImpl.java

public Integer insertOrUpdateSlgDrvXxcjb(DbjgZjxxb dbZjxxb, DydjYwsbspb dydjYwsbspb, HttpServletRequest request,
        File file1, File file2, File file01, File file02, File gpyfile0, File gpyfile1, File gpyfile2,
        File gpyfile3, File gpyfile4, File gpyfile5, File gpyfile6, File gpyfile7) throws Exception {
    int result = -1;
    if (dbZjxxb != null) {
        String id = dbZjxxb.getId();
        User user = (User) request.getSession().getAttribute(SysConst.USERBEAN);
        if ("1".equals(dbZjxxb.getBllx())) {
            dbZjxxb.setDbrsfzmmc("");
            dbZjxxb.setDbrSfzCardname1("");
            dbZjxxb.setDbrSfzCardsex1("");
            dbZjxxb.setDbrSfzCardno1("");
            dbZjxxb.setDbrSfzCardaddress1("");
            file2 = null;// www  .  j  a va2  s.c o m
        }
        dbZjxxb.setLrr(user.getName());
        dbZjxxb.setLrrxm(user.getYgxm());
        dbZjxxb.setLrbmdm(user.getBmid());
        dbZjxxb.setLrbmmc(user.getBmmc());
        dbZjxxb.setLrsj(new Date());
        dbZjxxb.setLrip(getLoginIp(request));
        dbZjxxb.setLrmac(request.getLocalAddr());
        String hphm = dbZjxxb.getHphm();
        if (!StringUtil.isNull(hphm)) {
            hphm = hphm.toUpperCase();
            if (hphm.contains("")) {
                hphm = hphm.replaceAll("", "");
            }
            dbZjxxb.setHphm(hphm);
        }
        if (id == null || "".equals(id)) {
            /********************************?*****************************************/
            String basePath = request.getRealPath("/");
            File f = new File(basePath + "\\images\\shuiyin.png");
            if (null != file1) {
                String strtemp = slgDrvFileUpload.uploadFile(file1);
                if (null != strtemp && !"".equals(strtemp)) {
                    dbZjxxb.setDsrSfzCardphoto1(strtemp);
                } else {
                    Exception etemp = new Exception(
                            ":?,??!");
                    throw etemp;
                }
            }
            if (null != file2) {
                String strtemp = slgDrvFileUpload.uploadFile(file2);
                if (null != strtemp && !"".equals(strtemp)) {
                    dbZjxxb.setDbrSfzCardphoto1(strtemp);
                } else {
                    Exception etemp = new Exception(
                            ":?,??!");
                    throw etemp;
                }
            }
            if (null != file01) {
                ImageUtils.pressImage(file01, f);
                String strtemp = slgDrvFileUpload.uploadFile(file01);
                if (null != strtemp && !"".equals(strtemp)) {
                    dbZjxxb.setDsrSfzSxtZp(strtemp);
                } else {
                    Exception etemp = new Exception(
                            ":?,??!");
                    throw etemp;
                }
            }
            if (null != file02) {
                ImageUtils.pressImage(file02, f);
                String strtemp = slgDrvFileUpload.uploadFile(file02);
                if (null != strtemp && !"".equals(strtemp)) {
                    dbZjxxb.setDsrSfzGpyZp(strtemp);
                } else {
                    Exception etemp = new Exception(
                            ":?,??!");
                    throw etemp;
                }
            }
            /********************************?*****************************************/
            String lsh = request.getParameter("lshval");
            String firtst = "";
            if (lsh != null && !"".equals(lsh)) {
                firtst = lsh.substring(0, 1);
            }
            if (lsh != null && !"".equals(lsh) && !"L".equals(firtst)) {
                if ("D".equals(firtst)) { //
                    //??????
                    DydjYwsbspbTemp dydjYwsbspb2 = dydjService.getDydjYwwbspByLsh(request, lsh);
                    if (dydjYwsbspb2 == null) {
                        return -1;
                    }

                    if ("11".equals(dydjYwsbspb2.getSqlx())) {
                        //???1?
                        dbZjxxb.setDsrSfzCardname1(dydjYwsbspb2.getDyrSfzCardname());
                        dbZjxxb.setDsrSfzCardno1(dydjYwsbspb2.getDyrSfzCardno());
                        dbZjxxb.setDsrSfzCardsex1(dydjYwsbspb2.getDyrSfzCardsex());
                        dbZjxxb.setDsrSfzCardaddress1(dydjYwsbspb2.getDyrSfzCardaddress());
                        //
                        if (!StringUtil.isNull(dydjYwsbspb2.getDyrSfzCardphotoId())) {
                            int photoid = Integer.parseInt(dydjYwsbspb2.getDyrSfzCardphotoId());
                            byte[] bytes = dydjService.getImageBlob(request, photoid);
                            if (bytes != null) {
                                String imgtemp = slgDrvFileUpload.uploadFileBybyte(bytes);
                                dbZjxxb.setDsrSfzCardphoto1(imgtemp);
                            }
                        }
                    } else if ("12".equals(dydjYwsbspb2.getSqlx())) {
                        //?????1?,???2?
                        dbZjxxb.setDsrZzjgZh1(dydjYwsbspb2.getDyrZzjgZh());
                        dbZjxxb.setDsrZzjgFrdb1(dydjYwsbspb2.getDyrZzjgFrdb());
                        dbZjxxb.setDsrZzjgYyzz1(dydjYwsbspb2.getDyrZzjgYyzz());
                        dbZjxxb.setDsrZzjgDwmc1(dydjYwsbspb2.getDyrZzjgDwmc());
                        dbZjxxb.setDsrZzjgDz1(dydjYwsbspb2.getDyrZzjgDz());
                        dbZjxxb.setDsrZzjgNjrq1(dydjYwsbspb2.getDyrZzjgNjrq());
                        dbZjxxb.setDsrZzjgNjyxq1(dydjYwsbspb2.getDyrZzjgNjyxq());

                        dbZjxxb.setDbrSfzCardname2(dydjYwsbspb2.getDyrSfzCardname());
                        dbZjxxb.setDbrSfzCardno2(dydjYwsbspb2.getDyrSfzCardno());
                        dbZjxxb.setDbrSfzCardsex2(dydjYwsbspb2.getDyrSfzCardsex());
                        dbZjxxb.setDbrSfzCardaddress2(dydjYwsbspb2.getDyrSfzCardaddress());
                        //
                        if (!StringUtil.isNull(dydjYwsbspb2.getDyrSfzCardphotoId())) {
                            int photoid = Integer.parseInt(dydjYwsbspb2.getDyrSfzCardphotoId());
                            byte[] bytes = dydjService.getImageBlob(request, photoid);
                            if (bytes != null) {
                                String imgtemp = slgDrvFileUpload.uploadFileBybyte(bytes);
                                dbZjxxb.setDbrSfzCardphoto2(imgtemp);
                            }
                        }

                    } else {
                        //???????????????
                        dbZjxxb.setDbrZzjgZh2(dbZjxxb.getDbrZzjgZh1());
                        dbZjxxb.setDbrZzjgFrdb2(dbZjxxb.getDbrZzjgFrdb1());
                        dbZjxxb.setDbrZzjgYyzz2(dbZjxxb.getDbrZzjgYyzz1());
                        dbZjxxb.setDbrZzjgDwmc2(dbZjxxb.getDbrZzjgDwmc1());
                        dbZjxxb.setDbrZzjgDz2(dbZjxxb.getDbrZzjgDz1());
                        dbZjxxb.setDbrZzjgNjrq2(dbZjxxb.getDbrZzjgNjrq1());
                        dbZjxxb.setDbrZzjgNjyxq2(dbZjxxb.getDbrZzjgNjyxq1());

                        dbZjxxb.setDbrSfzCardname2(dbZjxxb.getDbrSfzCardname1());
                        dbZjxxb.setDbrSfzCardno2(dbZjxxb.getDbrSfzCardno1());
                        dbZjxxb.setDbrSfzCardsex2(dbZjxxb.getDbrSfzCardsex1());
                        dbZjxxb.setDbrSfzCardaddress2(dbZjxxb.getDbrSfzCardaddress1());
                        dbZjxxb.setDbrSfzCardphoto2(dbZjxxb.getDbrSfzCardphoto1());
                    }

                    //????1
                    dbZjxxb.setDbrZzjgZh1(dydjYwsbspb2.getYhZzjgZh());
                    dbZjxxb.setDbrZzjgFrdb1(dydjYwsbspb2.getYhZzjgFrdb());
                    dbZjxxb.setDbrZzjgYyzz1(dydjYwsbspb2.getYhZzjgYyzz());
                    dbZjxxb.setDbrZzjgDwmc1(dydjYwsbspb2.getYhZzjgDwmc());
                    dbZjxxb.setDbrZzjgDz1(dydjYwsbspb2.getYhZzjgDz());
                    dbZjxxb.setDbrZzjgNjrq1(dydjYwsbspb2.getYhZzjgNjrq());
                    dbZjxxb.setDbrZzjgNjyxq1(dydjYwsbspb2.getYhZzjgNjyxq());
                    //????1?
                    dbZjxxb.setDbrSfzCardname1(dydjYwsbspb2.getYhSfzCardname());
                    dbZjxxb.setDbrSfzCardno1(dydjYwsbspb2.getYhSfzCardno());
                    dbZjxxb.setDbrSfzCardsex1(dydjYwsbspb2.getYhSfzCardsex());
                    dbZjxxb.setDbrSfzCardaddress1(dydjYwsbspb2.getYhSfzCardaddress());
                    //
                    if (!StringUtil.isNull(dydjYwsbspb2.getYhSfzCardphotoId())) {
                        int photoid = Integer.parseInt(dydjYwsbspb2.getYhSfzCardphotoId());
                        byte[] bytes = dydjService.getImageBlob(request, photoid);
                        if (bytes != null) {
                            String imgtemp = slgDrvFileUpload.uploadFileBybyte(bytes);
                            dbZjxxb.setDbrSfzCardphoto1(imgtemp);
                        }
                    }

                    dbZjxxb.setLsh(lsh);
                    DbjgZjxxb zjxxb1 = this.slgVehDao.addRepository(dbZjxxb);
                    //
                    DbjgZjxxbLog dZjxxbLog = new DbjgZjxxbLog();
                    dZjxxbLog = (DbjgZjxxbLog) getXclog(dZjxxbLog, zjxxb1);
                    dZjxxbLog.setCzr(user.getName());
                    dZjxxbLog.setCzrxm(user.getYgxm());
                    dZjxxbLog.setCzrbm(user.getBmid());
                    dZjxxbLog.setCznr("I");
                    dZjxxbLog.setCzsj(new Date());
                    dZjxxbLog.setCzip(getLoginIp(request));
                    dZjxxbLog.setCzmac("");
                    this.slgVehDao.addObj(dZjxxbLog, request);
                    //??DYDJ_YWSBSPB 
                    String upsql = "update dydj_ywsbspb set cg_yhdm = '" + user.getName() + "', cg_yhxm = '"
                            + user.getYgxm() + "', cg_ip = '" + getLoginIp(request)
                            + "', cg_yhsj = to_char(sysdate, 'yyyy-MM-dd HH24:mi:ss') where id = "
                            + dydjYwsbspb2.getId();
                    this.slgVehDao.updateRepositoryBySql(upsql);
                    //??DYDJ_YWSBSPB_log
                    DydjYwsbspbLog ywsbspbLog = new DydjYwsbspbLog();
                    ywsbspbLog = (DydjYwsbspbLog) getXclog(ywsbspbLog, dydjYwsbspb2);
                    ywsbspbLog.setCzr(user.getName());
                    ywsbspbLog.setCzrxm(user.getYgxm());
                    ywsbspbLog.setCzrbm(user.getBmid());
                    ywsbspbLog.setCzsj(new Date());
                    ywsbspbLog.setCznr("???");
                    ywsbspbLog.setCzip(getLoginIp(request));
                    this.slgVehDao.addObj(dZjxxbLog, request);
                    result = 1;

                } else {
                    //??
                    if ("D".equals(dbZjxxb.getYwlx()) && ("D:P".equals(dbZjxxb.getYwyy())
                            || "D:A".equals(dbZjxxb.getYwyy()) || "D:J".equals(dbZjxxb.getYwyy()))) {
                        //???outin
                        String sql = "insert into vehicle_temp_mid_write  select * from vehicle_temp_mid_read  where lsh= '"
                                + lsh + "'";
                        this.slgVehDao.updateRepositoryBySql(sql);
                    }
                    //???_in?
                    VehicleTempMidIn tempMidIn = getVehicleMidInByLsh(lsh, request);
                    //_test
                    if (tempMidIn != null) {
                        VehicleTempMidTest tempMidTest = new VehicleTempMidTest();
                        tempMidTest = (VehicleTempMidTest) getXclog(tempMidTest, tempMidIn);
                        tempMidTest.setLocalIshandle("1");
                        tempMidTest.setLocalOperat(dbZjxxb.getLrr());
                        tempMidTest.setLocalOpertime(new Date());
                        tempMidTest.setLocalName(dbZjxxb.getLrrxm());
                        this.slgVehDao.addObj(tempMidTest, request);
                        //_in
                        tempMidIn.setLocalIshandle("1");
                        tempMidIn.setLocalOperat(dbZjxxb.getLrr());
                        tempMidIn.setLocalOpertime(new Date());
                        tempMidIn.setLocalName(dbZjxxb.getLrrxm());
                        this.slgVehDao.updateObj(tempMidIn);

                        dbZjxxb.setLsh(lsh);
                        DbjgZjxxb zjxxb1 = this.slgVehDao.addRepository(dbZjxxb);
                        //
                        DbjgZjxxbLog dZjxxbLog = new DbjgZjxxbLog();
                        dZjxxbLog = (DbjgZjxxbLog) getXclog(dZjxxbLog, zjxxb1);
                        dZjxxbLog.setCzr(user.getName());
                        dZjxxbLog.setCzrxm(user.getYgxm());
                        dZjxxbLog.setCzrbm(user.getBmid());
                        dZjxxbLog.setCznr("I");
                        dZjxxbLog.setCzsj(new Date());
                        dZjxxbLog.setCzip(getLoginIp(request));
                        dZjxxbLog.setCzmac("");
                        this.slgVehDao.addObj(dZjxxbLog, request);
                        result = 1;
                    }
                }

                //?????
                YwlsglVehFlow ywFlow = (YwlsglVehFlow) this.defaultDao.getRepository(lsh, YwlsglVehFlow.class);
                if (ywFlow != null) {
                    ywFlow.setLszt("E");
                    this.defaultDao.updateRepository(ywFlow);
                    YwlsglVehFlowLog log = new YwlsglVehFlowLog();
                    log = (YwlsglVehFlowLog) getXclog(log, ywFlow);
                    log.setCzr(user.getYgid());
                    log.setCzrxm(user.getYgxm());
                    log.setCzrbm(user.getBmid());
                    log.setCzrbmKj(getDeptUpid(user.getBmid()));
                    log.setCzip(getLoginIp(request));
                    log.setCznr("U");
                    log.setCzsj(new Date());
                    this.defaultDao.addRepository(log);
                }

            } else {
                DbjgZjxxb zjxxb = this.slgVehDao.addRepository(dbZjxxb);
                //
                String filecount = request.getParameter("filecount");
                if (null != filecount) {
                    if (!"0".equals(filecount)) {
                        for (int i = 0; i < Integer.parseInt(filecount); i++) {
                            DbjgFzxp fzxpBean = new DbjgFzxp();
                            fzxpBean.setJdcxxcjid(zjxxb.getId());
                            fzxpBean.setYwlxid(zjxxb.getYwlx());
                            fzxpBean.setYwlxms(SlgVehServiceImpl.getYwlxMessage(zjxxb.getYwlx()));
                            fzxpBean.setPzid(request.getParameter("gpyid" + i));
                            fzxpBean.setPztitle(request.getParameter("gpytitle" + i));
                            //????
                            File file = null;
                            switch (i) {
                            case 0:
                                file = gpyfile0;
                                break;
                            case 1:
                                file = gpyfile1;
                                break;
                            case 2:
                                file = gpyfile2;
                                break;
                            case 3:
                                file = gpyfile3;
                                break;
                            case 4:
                                file = gpyfile4;
                                break;
                            case 5:
                                file = gpyfile5;
                                break;
                            case 6:
                                file = gpyfile6;
                                break;
                            case 7:
                                file = gpyfile7;
                                break;
                            default:
                                break;
                            }
                            if (null != file) {
                                ImageUtils.pressImage(file, f);
                                String twm = slgDrvFileUpload.uploadFile(file);
                                if (null != twm && !"".equals(twm)) {
                                    fzxpBean.setTwm(twm);
                                } else {
                                    Exception etemp = new Exception(
                                            ":?,??!");
                                    throw etemp;
                                }
                            }
                            fzxpBean.setCzr(user.getName());
                            fzxpBean.setCzrxm(user.getYgxm());
                            fzxpBean.setCzbm(user.getBmmc());
                            fzxpBean.setCzrq(new Date());
                            fzxpBean.setCzip(getLoginIp(request));
                            fzxpBean.setVehOrDrv("VEH");

                            this.defaultDao.addRepository(fzxpBean);
                        }
                    }
                }

                VehicleTempMidInJdc vehInJdc = new VehicleTempMidInJdc();
                vehInJdc.setLsh(zjxxb.getId());
                vehInJdc.setHphm(zjxxb.getHphm());
                vehInJdc.setHpzl(zjxxb.getHpzl());
                vehInJdc.setSfzmhm(zjxxb.getDsrsfzmhm());
                vehInJdc.setSyr(zjxxb.getDsrxm());
                vehInJdc.setNetSmzmhm(zjxxb.getDbrsfzmhm());
                vehInJdc.setNetXm(zjxxb.getDbrxm());
                vehInJdc.setLocalIshandle("1");
                vehInJdc.setLocalOperat(zjxxb.getLrr());
                vehInJdc.setLocalName(zjxxb.getLrrxm());
                vehInJdc.setLocalOpertime(new Date());
                vehInJdc.setPostZj("0");
                vehInJdc.setPostTp("0");
                vehInJdc.setYwlx("B");
                vehInJdc.setYwyy("B");
                String bzval = "";
                if (zjxxb.getYwyy() != null && !"".equals(zjxxb.getYwyy())) {
                    String ywlxval = "";
                    String ywyyval = "";
                    String[] ywyys = zjxxb.getYwyy().split(",");
                    if (ywyys != null && ywyys.length > 0) {
                        for (int m = 0; m < ywyys.length; m++) {
                            String ywlxs = ywyys[m];
                            if (ywlxs != null && !"".equals(ywlxs)) {
                                String[] ywyyarr = ywlxs.split(":");
                                ywlxval = ywyyarr[0];
                                ywyyval += ywyyarr[1] + ",";
                            }
                        }
                    }
                    if (ywyyval.endsWith(",")) {
                        ywyyval = ywyyval.substring(0, ywyyval.length() - 1);
                    }
                    bzval = ywlxval + ":" + ywyyval;
                } else {
                    bzval = zjxxb.getYwlx();
                }
                vehInJdc.setBz(bzval);
                this.slgVehDao.addObj(vehInJdc, request);
                //
                DbjgZjxxbLog dZjxxbLog = new DbjgZjxxbLog();
                dZjxxbLog = (DbjgZjxxbLog) getXclog(dZjxxbLog, zjxxb);
                dZjxxbLog.setCzr(user.getName());
                dZjxxbLog.setCzrxm(user.getYgxm());
                dZjxxbLog.setCzrbm(user.getBmid());
                dZjxxbLog.setCznr("I");
                dZjxxbLog.setCzsj(new Date());
                dZjxxbLog.setCzip(getLoginIp(request));
                dZjxxbLog.setCzmac("");
                this.slgVehDao.addObj(dZjxxbLog, request);
                result = 1;
            }

            //?
            String zbyzflag = request.getParameter("zbyzflag");
            if ("1".equals(zbyzflag)) {
                StringBuffer srcs = new StringBuffer("<request><head><dqgw>3</dqgw></head><body>");
                srcs.append("<lsh>" + (dbZjxxb.getLsh() == null ? "" : dbZjxxb.getLsh()) + "</lsh>");
                srcs.append("<hphm>" + (dbZjxxb.getHphm() == null ? "" : dbZjxxb.getHphm()) + "</hphm>");
                srcs.append("<hpzl>" + (dbZjxxb.getHpzl() == null ? "" : dbZjxxb.getHpzl()) + "</hpzl>");
                srcs.append("<syxz>" + (dbZjxxb.getSyxz() == null ? "" : dbZjxxb.getSyxz()) + "</syxz>");
                srcs.append("<sfzmmc>" + (dbZjxxb.getDsrsfzmmc() == null ? "" : dbZjxxb.getDsrsfzmmc())
                        + "</sfzmmc>");
                srcs.append("<sfzmhm>");
                srcs.append(dbZjxxb.getDsrsfzmhm() == null ? dbZjxxb.getDsrZzjgZh1() : dbZjxxb.getDsrsfzmhm());
                srcs.append("</sfzmhm>");
                srcs.append("<syr>");
                srcs.append(dbZjxxb.getDsrxm());
                srcs.append("</syr>");
                srcs.append("<ip>" + (dbZjxxb.getLrip() == null ? "" : dbZjxxb.getLrip()) + "</ip>");
                srcs.append("<sffq>" + (dbZjxxb.getSffq() == null ? "" : dbZjxxb.getSffq()) + "</sffq>");
                srcs.append("<jhzbh>" + (dbZjxxb.getJhzbh() == null ? "" : dbZjxxb.getJhzbh()) + "</jhzbh>");
                srcs.append("<ywlx>" + (dbZjxxb.getYwlx() == null ? "" : dbZjxxb.getYwlx()) + "</ywlx>");
                srcs.append("<ywyy>" + (dbZjxxb.getYwyy() == null ? "" : dbZjxxb.getYwyy()) + "</ywyy>");
                srcs.append("<hdfs>" + (dbZjxxb.getHdfs() == null ? "" : dbZjxxb.getHdfs()) + "</hdfs>");
                srcs.append(
                        "<tyblsh>" + (dbZjxxb.getTyblsh() == null ? "" : dbZjxxb.getTyblsh()) + "</tyblsh>");
                srcs.append("<clsbdh></clsbdh>");
                srcs.append("<cllx>" + (dbZjxxb.getCllx() == null ? "" : dbZjxxb.getCllx()) + "</cllx>");
                srcs.append("<syq></syq>");
                srcs.append("<glbm></glbm>");
                srcs.append("<zczxlsh>" + (dbZjxxb.getLsh() == null ? "" : dbZjxxb.getLsh()) + "</zczxlsh>");
                srcs.append("<zczxhfhljzyqchzx>"
                        + (dbZjxxb.getZczxhfhljzyqchzx() == null ? "" : dbZjxxb.getZczxhfhljzyqchzx())
                        + "</zczxhfhljzyqchzx>");
                srcs.append("<tbr>" + (dbZjxxb.getTbr() == null ? "" : dbZjxxb.getTbr()) + "</tbr>");
                srcs.append("<tbyy>" + (dbZjxxb.getTbyy() == null ? "" : dbZjxxb.getTbyy()) + "</tbyy>");
                srcs.append("<zblx>" + (dbZjxxb.getZblx() == null ? "" : dbZjxxb.getZblx()) + "</zblx>");
                srcs.append("<zbh>" + (dbZjxxb.getZbh() == null ? "" : dbZjxxb.getZbh()) + "</zbh>");
                srcs.append("</body></request>");
                String msg = this.slgVehDao.insertShenjiinfo(request,
                        StringUtil.isNull(dbZjxxb.getZjxxblsh()) ? dbZjxxb.getLsh() : dbZjxxb.getZjxxblsh(),
                        srcs.toString());
                if (!"[0000]".equals(msg.substring(0, 6))) {
                    throw new Exception(msg.substring(6));
                }
            }

        } else {
            //
            DbjgZjxxb dbZjxxb2 = this.slgVehDao.updateRepository(dbZjxxb);
            //
            DbjgZjxxbLog dZjxxbLog = new DbjgZjxxbLog();
            dZjxxbLog = (DbjgZjxxbLog) getXclog(dZjxxbLog, dbZjxxb2);
            dZjxxbLog.setCzr(user.getName());
            dZjxxbLog.setCzrxm(user.getYgxm());
            dZjxxbLog.setCzrbm(user.getBmid());
            dZjxxbLog.setCznr("U");
            dZjxxbLog.setCzsj(new Date());
            dZjxxbLog.setCzip(getLoginIp(request));
            dZjxxbLog.setCzmac("");
            this.slgVehDao.addObj(dZjxxbLog, request);
            result = 1;
        }
    }
    return result;
}

From source file:org.openmrs.web.servlet.LoginServlet.java

/**
 * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse)
 *//* w ww  .  j a  v a 2  s .  co m*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    HttpSession httpSession = request.getSession();

    String ipAddress = request.getRemoteAddr();
    Integer loginAttempts = loginAttemptsByIP.get(ipAddress);
    if (loginAttempts == null) {
        loginAttempts = 1;
    }

    loginAttempts++;

    boolean lockedOut = false;
    // look up the allowed # of attempts per IP
    Integer allowedLockoutAttempts = 100;

    String allowedLockoutAttemptsGP = Context.getAdministrationService()
            .getGlobalProperty(GP_ALLOWED_LOGIN_ATTEMPTS_PER_IP, "100");
    try {
        allowedLockoutAttempts = Integer.valueOf(allowedLockoutAttemptsGP.trim());
    } catch (NumberFormatException nfe) {
        log.error("Unable to format '" + allowedLockoutAttemptsGP + "' from global property "
                + GP_ALLOWED_LOGIN_ATTEMPTS_PER_IP + " as an integer");
    }

    // allowing for configurable login attempts here in case network setups are such that all users have the same IP address. 
    if (allowedLockoutAttempts > 0 && loginAttempts > allowedLockoutAttempts) {
        lockedOut = true;

        Date lockedOutTime = lockoutDateByIP.get(ipAddress);
        if (lockedOutTime != null && System.currentTimeMillis() - lockedOutTime.getTime() > 300000) {
            lockedOut = false;
            loginAttempts = 0;
            lockoutDateByIP.put(ipAddress, null);
        } else {
            // they haven't been locked out before, or they're trying again
            // within the time limit.  Set the locked-out date to right now
            lockoutDateByIP.put(ipAddress, new Date());
        }

    }

    // get the place to redirect to either now, or after they eventually
    // authenticate correctly
    String redirect = determineRedirect(request);

    if (lockedOut) {
        httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "auth.login.tooManyAttempts");
    } else {
        try {

            String username = request.getParameter("uname");
            String password = request.getParameter("pw");

            // only try to authenticate if they actually typed in a username
            if (username == null || username.length() == 0) {
                throw new ContextAuthenticationException("Unable to authenticate with an empty username");
            }

            Context.authenticate(username, password);

            if (Context.isAuthenticated()) {
                regenerateSession(request);
                httpSession = request.getSession();//get the newly generated session
                httpSession.setAttribute("loginAttempts", 0);
                User user = Context.getAuthenticatedUser();

                // load the user's default locale if possible
                if (user.getUserProperties() != null && user.getUserProperties()
                        .containsKey(OpenmrsConstants.USER_PROPERTY_DEFAULT_LOCALE)) {
                    String localeString = user.getUserProperty(OpenmrsConstants.USER_PROPERTY_DEFAULT_LOCALE);
                    Locale locale = WebUtil.normalizeLocale(localeString);
                    // if locale object is valid we should store it
                    if (locale != null) {
                        OpenmrsCookieLocaleResolver oclr = new OpenmrsCookieLocaleResolver();
                        oclr.setLocale(request, response, locale);
                    }
                }

                if (new UserProperties(user.getUserProperties()).isSupposedToChangePassword()) {
                    httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.password.change");
                    redirect = request.getContextPath() + "/changePassword.form";
                }

                // In case the user has no preferences, make sure that the context has some locale set
                if (Context.getLocale() == null) {
                    Context.setLocale(LocaleUtility.getDefaultLocale());
                }

                CurrentUsers.addUser(httpSession, user);

                if (log.isDebugEnabled()) {
                    log.debug("Redirecting after login to: " + redirect);
                    log.debug("Locale address: " + request.getLocalAddr());
                }

                response.sendRedirect(redirect);

                httpSession.setAttribute(WebConstants.OPENMRS_CLIENT_IP_HTTPSESSION_ATTR,
                        request.getLocalAddr());
                httpSession.removeAttribute(WebConstants.OPENMRS_LOGIN_REDIRECT_HTTPSESSION_ATTR);

                // unset login attempts by this user because they were
                // able to successfully log in

                loginAttemptsByIP.remove(ipAddress);

                return;
            }
        } catch (ContextAuthenticationException e) {
            // set the error message for the user telling them
            // to try again
            httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "auth.password.invalid");
        }

    }

    // send the user back the login page because they either 
    // had a bad password or are locked out
    loginAttemptsByIP.put(ipAddress, loginAttempts);
    httpSession.setAttribute(WebConstants.OPENMRS_LOGIN_REDIRECT_HTTPSESSION_ATTR, redirect);
    response.sendRedirect(request.getContextPath() + "/login.htm");
}