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:com.jd.survey.web.survey.PublicSurveyController.java

/**
 * Shows a previously submitted survey as read only
 * @param surveyId//from  w ww . j  av a2  s . c o m
 * @param uiModel
 * @param httpServletRequest
 * @return
 */
@RequestMapping(value = "/{id}", produces = "text/html")
public String showSurvey(@PathVariable("id") Long surveyId, Model uiModel,
        HttpServletRequest httpServletRequest) {
    log.info("showSurvey surveyId=" + surveyId + " no pageOrder");
    try {
        Survey survey = surveyService.survey_findById(surveyId);
        SurveyDefinition surveyDefinition = surveySettingsService.surveyDefinition_findById(survey.getTypeId());
        //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 (!survey.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()));
        if (survey.getStatus() == SurveyStatus.I) {
            return "redirect:/open/" + encodeUrlPathSegment(surveyId.toString(), httpServletRequest) + "/1";
        } else {
            uiModel.addAttribute("survey_base_path", "open");
            uiModel.addAttribute("survey", survey);
            uiModel.addAttribute("surveyDefinition",
                    surveySettingsService.surveyDefinition_findById(survey.getTypeId()));
            uiModel.addAttribute("surveyPages", surveyPages);
            return "surveys/survey";
        }

    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw (new RuntimeException(e));
    }
}

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

/**
 * Returns the survey logo image binary  
 * @param departmentId//from w w  w  .ja  va2 s.c o m
 * @param uiModel
 * @param httpServletRequest
 * @return
 */
@RequestMapping(value = "/logo/{id}", produces = "text/html")
public void getSurveyLogo(@PathVariable("id") Long surveyDefinitionId, Model uiModel, Principal principal,
        HttpServletRequest httpServletRequest, HttpServletResponse response) {
    try {
        uiModel.asMap().clear();
        //Check if the user is authorized
        SurveyDefinition surveyDefinition = surveySettingsService.surveyDefinition_findById(surveyDefinitionId);
        if (!surveyDefinition.getIsPublic()) {//survey definition not open to the public
            //attempt to access a private survey definition from a public open url 
            log.warn(SURVEY_NOT_PUBLIC_WARNING_MESSAGE + httpServletRequest.getPathInfo()
                    + FROM_IP_WARNING_MESSAGE + httpServletRequest.getLocalAddr());
            throw (new RuntimeException("Unauthorized access to logo"));
        } else {
            //response.setContentType("image/png");
            ServletOutputStream servletOutputStream = response.getOutputStream();
            servletOutputStream.write(surveyDefinition.getLogo());
            servletOutputStream.flush();
        }

    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw (new RuntimeException(e));
    }
}

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

/**
 * Checks that the user does not have a pending survey entry otherwise creates a new one     
 * @param surveyDefinitionId//from  w w w  .j  a v a2s .co  m
 * @param uiModel
 * @param httpServletRequest
 * @return
 */
@RequestMapping(value = "/{id}", params = "list", produces = "text/html")
public String listSurveyEntries(@PathVariable("id") Long surveyDefinitionId, Model uiModel, Principal principal,
        HttpServletRequest httpServletRequest) {
    log.info("listSurveyEntries of type id=" + surveyDefinitionId);
    try {
        SurveyDefinition surveyDefinition = surveySettingsService.surveyDefinition_findById(surveyDefinitionId);
        if (!surveyDefinition.getIsPublic()) {//survey definition not open to the public
            //attempt to access a private survey definition from a public open url 
            log.warn(SURVEY_NOT_PUBLIC_WARNING_MESSAGE + httpServletRequest.getPathInfo()
                    + FROM_IP_WARNING_MESSAGE + httpServletRequest.getLocalAddr());
            return "accessDenied";
        }

        Set<Survey> userSurveyEntries = surveyService.survey_findUserEntriesByTypeIdAndIpAddress(
                surveyDefinitionId, httpServletRequest.getRemoteAddr());
        if (surveyDefinition.getAllowMultipleSubmissions()) {//allow multiple submissions of this survey from the same client IP Address
            if (userSurveyEntries == null || userSurveyEntries.size() == 0) { //No User entries for this survey, create a new one
                Survey survey = surveyService.survey_create(surveyDefinitionId, null,
                        httpServletRequest.getRemoteAddr());
                return "redirect:/open/" + encodeUrlPathSegment(survey.getId().toString(), httpServletRequest)
                        + "/1";
            } else {//entries found 
                if (userSurveyEntries.size() == 1) {
                    //only on entry found 
                    Iterator<Survey> it = userSurveyEntries.iterator();
                    Survey survey = it.next(); // get the first and only element in the set
                    if (survey.getStatus() == SurveyStatus.I || survey.getStatus() == SurveyStatus.R) { //survey is incomplete or reopened
                        //go directly to the survey first page
                        return "redirect:/open/"
                                + encodeUrlPathSegment(survey.getId().toString(), httpServletRequest) + "/1";
                    }
                }
                //multiple entries found
                uiModel.addAttribute("survey_base_path", "open");
                uiModel.addAttribute("surveyDefinition", surveyDefinition);
                uiModel.addAttribute("userSurveyEntries", userSurveyEntries);
                return "surveys/entries";
            }
        } else {
            //do not allow multiple submissions of this survey from the same client IP Address
            if (userSurveyEntries == null || userSurveyEntries.size() == 0) {
                //No User entries for this survey, create a new one
                Survey survey = surveyService.survey_create(surveyDefinitionId, null,
                        httpServletRequest.getRemoteAddr());
                return "redirect:/open/" + encodeUrlPathSegment(survey.getId().toString(), httpServletRequest)
                        + "/1";
            } else {
                if (userSurveyEntries.size() == 1) {
                    //only on entry found 
                    Iterator<Survey> it = userSurveyEntries.iterator();
                    Survey survey = it.next(); // get the first and only element in the set
                    if (survey.getStatus() == SurveyStatus.I || survey.getStatus() == SurveyStatus.R) { //survey is incomplete or reopened
                        //go directly to the survey first page
                        return "redirect:/open/"
                                + encodeUrlPathSegment(survey.getId().toString(), httpServletRequest) + "/1";
                    }
                }
                //otherwise you have already completed the survey
                log.warn(IP_ADDRESS_USED_ALREADY_WARNING_MESSAGE + httpServletRequest.getPathInfo()
                        + FROM_IP_WARNING_MESSAGE + httpServletRequest.getLocalAddr());
                return "surveyAlreadyTaken";
            }
        }

    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw (new RuntimeException(e));
    }
}

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

/**
 * Shows the submit page//from   www  .  j  av a 2  s.c  o m
 * @param surveyId
 * @param uiModel
 * @param httpServletRequest
 * @return
 */
@Secured({ "ROLE_ADMIN", "ROLE_SURVEY_ADMIN", "ROLE_SURVEY_PARTICIPANT" })
@RequestMapping(value = "submit/{id}", produces = "text/html")
public String preparesubmitSurvey(@PathVariable("id") Long surveyId, Model uiModel, Principal principal,
        HttpServletRequest httpServletRequest) {
    try {
        String login = principal.getName();
        Survey survey = surveyService.survey_findById(surveyId);
        //Check if the user is authorized
        if (!survey.getLogin().equals(login)) {
            log.warn(UNAUTHORIZED_ATTEMPT_TO_ACCESS_SURVEY_WARNING_MESSAGE + surveyId
                    + REQUEST_PATH_WARNING_MESSAGE + httpServletRequest.getPathInfo()
                    + FROM_USER_LOGIN_WARNING_MESSAGE + principal.getName() + FROM_IP_WARNING_MESSAGE
                    + httpServletRequest.getLocalAddr());
            return "accessDenied";

        }

        //Check that the survey was not submitted
        if (!(survey.getStatus().equals(SurveyStatus.I) || survey.getStatus().equals(SurveyStatus.R))) {
            log.warn(UNAUTHORIZED_ATTEMPT_TO_EDIT_SUBMITTED_SURVEY_WARNING_MESSAGE + surveyId
                    + REQUEST_PATH_WARNING_MESSAGE + httpServletRequest.getPathInfo()
                    + FROM_USER_LOGIN_WARNING_MESSAGE + principal.getName() + 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", "private");
        uiModel.addAttribute("survey", survey);
        uiModel.addAttribute("surveyDefinition",
                surveySettingsService.surveyDefinition_findById(survey.getTypeId()));
        uiModel.addAttribute("surveyPages", surveyPages);
        uiModel.addAttribute("order", surveyPages.size() + 1);
        return "surveys/submit";

    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw (new RuntimeException(e));
    }
}

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

/**
 * Shows the submit page//from w  w w  .  java  2  s.c o m
 * @param surveyId
 * @param uiModel
 * @param httpServletRequest
 * @return
 */
@RequestMapping(value = "submit/{id}", produces = "text/html")
public String prepareSubmitSurvey(@PathVariable("id") Long surveyId, Model uiModel,
        HttpServletRequest httpServletRequest) {
    log.info("Submit survey  id=" + surveyId);
    try {
        Survey survey = surveyService.survey_findById(surveyId);
        SurveyDefinition surveyDefinition = surveySettingsService.surveyDefinition_findById(survey.getTypeId());
        if (!surveyDefinition.getIsPublic()) {//survey definition not open to the public
            //attempt to access a private survey definition from a public open url 
            log.warn(SURVEY_NOT_PUBLIC_WARNING_MESSAGE + httpServletRequest.getPathInfo()
                    + FROM_IP_WARNING_MESSAGE + httpServletRequest.getLocalAddr());
            return "accessDenied";
        }

        if (!survey.getIpAddress().equalsIgnoreCase(httpServletRequest.getLocalAddr())) {
            //Attempt to access a survey from different IP Address 
            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", survey);
        uiModel.addAttribute("surveyDefinition",
                surveySettingsService.surveyDefinition_findById(survey.getTypeId()));
        uiModel.addAttribute("surveyPages", surveyPages);
        uiModel.addAttribute("order", surveyPages.size() + 1);
        return "surveys/submit";

    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw (new RuntimeException(e));
    }
}

From source file:com.gs.config.ItemBasedAuthenticationFailureHandler.java

@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
        AuthenticationException exception) throws IOException, ServletException {
    UsernamePasswordAuthenticationToken user = (UsernamePasswordAuthenticationToken) exception
            .getAuthentication();/*from  www .ja  va2s .c  o m*/
    //System.out.println("Mensaje del error: "+exception.getMessage());
    //        PrincipalsessionInformaction user = request.getUserPrincipal();
    System.out.println("-----------------------------INTENTO FALLIDO-----------------------------");

    //Causas de la autenticacin fallida
    if (exception.getClass().isAssignableFrom(UsernameNotFoundException.class)) {
        //            System.out.println("INTENTO FALLIDO: El usuario no est registrado en la base de datos ");
        request.setAttribute("ERRORSESSION", "Usuario no registrado, verifique con el administrador");
        request.getRequestDispatcher("login?err=1").forward(request, response);
        //response.sendRedirect("login?err=1");
    } else if (exception.getClass().isAssignableFrom(BadCredentialsException.class)) {
        sessionFailDaoImp.insertUserSessionFail(user.getName(), request.getLocalAddr());
        usuarioConIntentoFallido.addIntentoUsuario(user.getName());
        //            System.out.println("INTENTO FALLIDO: Creedenciales erroneas");
        request.setAttribute("ERRORSESSION", "Contrasea incorrecta, intente nuevamente");
        request.getRequestDispatcher("login?err=1").forward(request, response);
        //response.sendRedirect("login?err=2");
    } else if (exception.getClass().isAssignableFrom(DisabledException.class)) {
        //            System.out.println("INTENTO FALLIDO: Usuario desabilitado");
        request.setAttribute("ERRORSESSION", "Usuario deshabilitado, verifique con el administrador");
        request.getRequestDispatcher("login?err=1").forward(request, response);
        //response.sendRedirect("login?err=3");
    } else if (exception.getClass().isAssignableFrom(SessionAuthenticationException.class)) {
        //            System.out.println("INTENTO FALLIDO: Usuario ya logeado");
        request.setAttribute("ERRORSESSION", "Ya existe una sesin abierta con este usuario");
        request.getRequestDispatcher("login?err=1").forward(request, response);
        //response.sendRedirect("login?err=4");
    } else if (exception.getClass().isAssignableFrom(IntentLimitExceeded.class)) {
        //            System.out.println("INTENTO FALLIDO: NMERO DE INTENTOS EXCEDIDOS");
        //Elimino al usuario de la listo de los intentos y se agrega a la lista de usuarios bloqueados
        usuarioConIntentoFallido.removeUsuario(user.getName());
        //Se crea el hilo para desbloquear al usuario
        listUsersLockoutIntentFail.addBlockUserFail(user.getName(), tiempoLockout);
        //request.setAttribute("ERRORSESSION", "Ha excedido el lmite de intentos. Por favor espere unos minutos e intente nuevamente");
        request.getRequestDispatcher("intentlimit").forward(request, response);
    } else {
        //            System.out.println("INTENTO FALLIDO: NO SE QUE PASO");
        request.setAttribute("ERRORSESSION", "No ha sido posible iniciar sesin");
        request.getRequestDispatcher("login?err=1").forward(request, response);
    }
}

From source file:org.openmrs.module.sdmxhddataexport.web.controller.report.ReportDataElementController.java

@RequestMapping(value = "/module/sdmxhddataexport/downloadExecutedReport.form", method = RequestMethod.GET)
public String downloadExecutedReport(@RequestParam(value = "reportId", required = false) Integer reportId,
        @RequestParam(value = "startDate", required = false) String startDate,
        @RequestParam(value = "endDate", required = false) String endDate,
        @RequestParam(value = "outputType", required = false) String outputType, HttpServletRequest request,
        HttpServletResponse response, Model model) throws ParseException, IOException {
    String u = request.getParameter("url");
    System.out.print("i think it is a url - " + u);
    //String s=(u.split("/")[2]).split(":")[0];
    String urlToRead = "http://" + u + request.getContextPath()
            + "/module/sdmxhddataexport/resultExecuteReport.form?reportId=" + reportId + "&startDate="
            + startDate + "&endDate=" + endDate;
    //       String urlToRead = "http://" + "127.0.0.1" + ":"
    //        + request.getLocalPort() + request.getContextPath()
    //        + "/module/sdmxhddataexport/resultExecuteReport.form?reportId="
    //        + reportId + "&startDate=" + startDate + "&endDate=" + endDate;
    URL url;// w  w w.j  ava  2s .c om

    System.out.println("http servlet request" + u + request.getLocalAddr() + "," + request.getLocalName());
    HttpURLConnection conn;
    InputStream rd = null;
    String contents = "";
    try {
        url = new URL(urlToRead);
        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        rd = conn.getInputStream();
        byte[] bytes = new byte[1024];
        int bytesRead;
        boolean firstRead = true;

        while ((bytesRead = rd.read(bytes)) != -1) {
            String str = new String(bytes);
            str = str.substring(0, bytesRead);
            //if(firstRead){
            firstRead = false;
            str = str.replaceAll("^\\s+", "");
            System.out.print(str);
            //}
            contents = contents.concat(str);

        }
        //rd.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

    if (outputType.contentEquals("download")) {
        //           File fil1=new File("/sdmx-temp-sdmx.xml");
        //           FileOutputStream fos = new FileOutputStream("sdmx-temp-sdmx.xml");
        File file = File.createTempFile("sdmx", "report");
        Writer output = new BufferedWriter(new FileWriter(file));
        output.write(contents);
        output.flush();
        //           output = new BufferedWriter(new FileWriter(fil1));
        //           output.write(contents);
        //           output.flush();

        output.close();
        System.out.println("these are contents ------------------------");
        System.out.println(contents);
        System.out.println("these wre contents ------------------------");
        response.setContentType("application/download");
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-hh-mm-ss");
        response.setHeader("Content-Disposition",
                "attachment; filename=\"" + "sdmxhd-" + formatter.format(new Date()) + ".xml" + "\"");
        FileCopyUtils.copy(new FileInputStream(file), response.getOutputStream());
        file.delete();

    }

    if (outputType.equals("view")) {
        try {
            contents = transform(contents);
        } catch (Exception e) {
            System.out.println("some error" + contents);
            e.printStackTrace();
        }
        model.addAttribute("contents", contents);
        System.out.println("Now contents---------------------------" + contents + ":");
        return "/module/sdmxhddataexport/report/resultView";
    } else if (outputType.equals("send")) {
        HttpSession httpSession = request.getSession();

        String urlStr = Context.getAdministrationService().getGlobalProperty("sdmxhddataexport.reportUrl");
        String[] paramName = { "report1" };
        String[] paramVal = new String[10];
        paramVal[0] = contents;
        try {
            String Response = HttpRestUtil.httpRestPost(urlStr, paramName, paramVal);
            System.out.println("Response:" + Response);
            String temp = "Report Sent Successfully";
            httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR,
                    StringUtils.isBlank(temp) ? "sdmxhddataexport.dataElement.deleted" : temp);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return "/module/sdmxhddataexport/report/list";
}

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

/**
 * Creates a new survey based on the passed surveyDefintionId 
 * @param surveyDefinitionId/*from w w w.j  ava  2 s.c  o  m*/
 * @param uiModel
 * @param httpServletRequest
 * @return
 */
@Secured({ "ROLE_ADMIN", "ROLE_SURVEY_ADMIN", "ROLE_SURVEY_PARTICIPANT" })
@RequestMapping(value = "/{id}", params = "create", produces = "text/html")
public String createSurvey(@PathVariable("id") Long surveyDefinitionId, Model uiModel, Principal principal,
        HttpServletRequest httpServletRequest) {
    try {
        String login = principal.getName();
        User user = userService.user_findByLogin(login);
        //Check if the user is authorized
        if (!securityService.userIsAuthorizedToCreateSurvey(surveyDefinitionId, user)) {
            log.warn(UNAUTHORIZED_ATTEMPT_TO_CREATE_SURVEY_WARNING_MESSAGE + surveyDefinitionId
                    + REQUEST_PATH_WARNING_MESSAGE + httpServletRequest.getPathInfo()
                    + FROM_USER_LOGIN_WARNING_MESSAGE + principal.getName() + FROM_IP_WARNING_MESSAGE
                    + httpServletRequest.getLocalAddr());
            return "accessDenied";

        }
        Survey survey = surveyService.survey_create(surveyDefinitionId, login,
                httpServletRequest.getRemoteAddr());
        return "redirect:/private/" + encodeUrlPathSegment(survey.getId().toString(), httpServletRequest)
                + "/1";
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw (new RuntimeException(e));
    }
}

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

/**
 * Handles the post from the submit page
 * @param proceed// w  w  w. j  a v  a2s .  co  m
 * @param survey
 * @param bindingResult
 * @param uiModel
 * @param httpServletRequest
 * @return
 */
@Secured({ "ROLE_ADMIN", "ROLE_SURVEY_ADMIN", "ROLE_SURVEY_PARTICIPANT" })
@RequestMapping(value = "/submit", method = RequestMethod.POST, produces = "text/html")
public String submitSurvey(@RequestParam(value = "id", required = true) Long surveyId,
        @RequestParam(value = "_submit", required = false) String proceedAction, Principal principal,
        Model uiModel, HttpServletRequest httpServletRequest) {

    log.info("submitPost(): id= " + surveyId);

    try {

        String login = principal.getName();
        //Check if the user is authorized
        if (!surveyService.survey_findById(surveyId).getLogin().equals(login)) {
            log.warn(UNAUTHORIZED_ATTEMPT_TO_ACCESS_SURVEY_WARNING_MESSAGE + surveyId
                    + REQUEST_PATH_WARNING_MESSAGE + httpServletRequest.getPathInfo()
                    + FROM_USER_LOGIN_WARNING_MESSAGE + principal.getName() + FROM_IP_WARNING_MESSAGE
                    + httpServletRequest.getLocalAddr());
            return "accessDenied";

        }

        //Check that the survey was not submitted
        Survey dbSurvey = surveyService.survey_findById(surveyId);
        if (!(dbSurvey.getStatus().equals(SurveyStatus.I) || dbSurvey.getStatus().equals(SurveyStatus.R))) {
            log.warn(UNAUTHORIZED_ATTEMPT_TO_EDIT_SUBMITTED_SURVEY_WARNING_MESSAGE + surveyId
                    + REQUEST_PATH_WARNING_MESSAGE + httpServletRequest.getPathInfo()
                    + FROM_USER_LOGIN_WARNING_MESSAGE + principal.getName() + FROM_IP_WARNING_MESSAGE
                    + httpServletRequest.getLocalAddr());
            return "accessDenied";

        }

        if (proceedAction != null) { //submit button
            uiModel.asMap().clear();
            Survey survey = surveyService.survey_submit(surveyId);
            return "redirect:/private/"
                    + encodeUrlPathSegment(survey.getTypeId().toString(), httpServletRequest) + "?list";
        } else {
            uiModel.asMap().clear();
            Survey survey = surveyService.survey_findById(surveyId);
            List<SurveyPage> surveyPages = surveyService.surveyPage_getAll(surveyId,
                    messageSource.getMessage(DATE_FORMAT, null, LocaleContextHolder.getLocale()));
            Short order = (short) surveyPages.size();
            return "redirect:/private/" + encodeUrlPathSegment(survey.getId().toString(), httpServletRequest)
                    + "/" + encodeUrlPathSegment(order.toString(), httpServletRequest);
        }

    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw (new RuntimeException(e));
    }

}

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

/**
 * Shows the survey submissions page if not entries found it will create a new one. if only one entry found will redirect to the survey show page  
 * @param surveyDefinitionId//  w w w.  ja  v a 2s  . c  o m
 * @param uiModel
 * @param httpServletRequest
 * @return
 */
@Secured({ "ROLE_ADMIN", "ROLE_SURVEY_ADMIN", "ROLE_SURVEY_PARTICIPANT" })
@RequestMapping(value = "/{id}", params = "list", produces = "text/html")
public String listSurveyEntries(@PathVariable("id") Long surveyDefinitionId, Model uiModel, Principal principal,
        HttpServletRequest httpServletRequest) {
    try {
        String login = principal.getName();
        User user = userService.user_findByLogin(login);
        //Check if the user is authorized
        if (!securityService.userIsAuthorizedToCreateSurvey(surveyDefinitionId, user)) {
            log.warn(UNAUTHORIZED_ATTEMPT_TO_CREATE_SURVEY_WARNING_MESSAGE + surveyDefinitionId
                    + REQUEST_PATH_WARNING_MESSAGE + httpServletRequest.getPathInfo()
                    + FROM_USER_LOGIN_WARNING_MESSAGE + principal.getName() + FROM_IP_WARNING_MESSAGE
                    + httpServletRequest.getLocalAddr());
            return "accessDenied";

        }

        SurveyDefinition surveyDefinition = surveySettingsService.surveyDefinition_findById(surveyDefinitionId);
        Set<Survey> userSurveyEntries = surveyService.survey_findUserEntriesByTypeIdAndLogin(surveyDefinitionId,
                login);

        if (userSurveyEntries == null || userSurveyEntries.size() == 0) {
            //No User entries for this survey, create a new one
            Survey survey = surveyService.survey_create(surveyDefinitionId, login,
                    httpServletRequest.getRemoteAddr());
            return "redirect:/private/" + encodeUrlPathSegment(survey.getId().toString(), httpServletRequest)
                    + "/1";
        }
        //entries found
        else {
            if (userSurveyEntries.size() == 1) {
                //only on entry found
                Iterator<Survey> it = userSurveyEntries.iterator();
                Survey survey = it.next(); // get the first and only element in the set
                if (survey.getStatus() == SurveyStatus.I || survey.getStatus() == SurveyStatus.R) {
                    //survey is incomplete or reopened
                    return "redirect:/private/"
                            + encodeUrlPathSegment(survey.getId().toString(), httpServletRequest) + "/1";
                } else {
                    //List all entries
                    uiModel.addAttribute("survey_base_path", "private");
                    uiModel.addAttribute("surveyDefinition", surveyDefinition);
                    uiModel.addAttribute("userSurveyEntries", userSurveyEntries);
                    return "surveys/entries";
                }
            } else {
                //multiple entries found
                uiModel.addAttribute("survey_base_path", "private");
                uiModel.addAttribute("surveyDefinition", surveyDefinition);
                uiModel.addAttribute("userSurveyEntries", userSurveyEntries);
                return "surveys/entries";
            }
        }

    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw (new RuntimeException(e));
    }
}