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.settings.SurveyDefinitionController.java

/**
 * Publishes the survey definition, this will make the survey available from the external site.   
 * @param surveyDefinitionId/*  ww w  .j ava 2 s .co m*/
 * @param response
 * @param httpServletRequest
 * @param uiModel
 * @return
 */
@Secured({ "ROLE_ADMIN", "ROLE_SURVEY_ADMIN" })
@RequestMapping(value = "/{id}", params = "publish", produces = "text/html")
public String publishSurveyDefinition(@PathVariable("id") Long surveyDefinitionId, HttpServletResponse response,
        Principal principal, Model uiModel, HttpServletRequest httpServletRequest) {
    try {
        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());
            return "accessDenied";
        }

        //Validate Page, questions and questions options are not empty
        if (!surveySettingsService.surveyDefinition_ValidateSurveydefinitionForPublishing(surveyDefinitionId)) {
            uiModel.addAttribute("surveyDefinition",
                    surveySettingsService.surveyDefinition_findById(surveyDefinitionId));
            uiModel.addAttribute("isNotPublishReady", true);
            return "settings/surveyDefinitions/show";
        } else //All Pages, Questions and Question Options are valid
        {
            SurveyDefinition surveyDefinition = surveySettingsService
                    .surveyDefinition_publish(surveyDefinitionId);
            return "redirect:/settings/surveyDefinitions/"
                    + encodeUrlPathSegment(surveyDefinitionId.toString(), httpServletRequest);
        }
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw (new RuntimeException(e));
    }
}

From source file:com.jd.survey.web.settings.SurveyDefinitionController.java

@Secured({ "ROLE_ADMIN", "ROLE_SURVEY_ADMIN" })
@RequestMapping(value = "/importtemplate", produces = "text/html")
public String importTemplate(@RequestParam(value = "id", required = false) Long departmentId,
        @RequestParam(value = "templateId", required = false) Long templateId, Model uiModel,
        Principal principal, HttpServletRequest httpServletRequest) {
    try {/*  w  ww .  j  a v  a  2  s.  c om*/
        String login = principal.getName();
        User user = userService.user_findByLogin(login);

        //Check if the user is authorized
        if (departmentId != null && !securityService.userBelongsToDepartment(departmentId, user)) {
            log.warn("Unauthorized access to url path " + httpServletRequest.getPathInfo()
                    + " attempted by user login:" + principal.getName() + "from IP:"
                    + httpServletRequest.getLocalAddr());
            return "accessDenied";
        }
        uiModel.addAttribute("departments", surveySettingsService.department_findAll(user));
        uiModel.addAttribute("departmentId", departmentId);
        uiModel.addAttribute("sectors", surveySettingsService.sector_findAll());
        return "settings/surveyDefinitions/importtemplate";
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw (new RuntimeException(e));
    }
}

From source file:org.jasig.cas.web.StatisticsController.java

@Override
protected ModelAndView handleRequestInternal(final HttpServletRequest httpServletRequest,
        final HttpServletResponse httpServletResponse) throws Exception {
    final ModelAndView modelAndView = new ModelAndView(new InternalResourceView(viewPath));
    modelAndView.addObject("startTime", this.upTimeStartDate);
    final double difference = System.currentTimeMillis() - this.upTimeStartDate.getTime();

    modelAndView//from w  ww . jav  a2  s . c o m
            .addObject("upTime",
                    calculateUptime(difference,
                            new LinkedList<Integer>(Arrays.asList(NUMBER_OF_MILLISECONDS_IN_A_DAY,
                                    NUMBER_OF_MILLISECONDS_IN_AN_HOUR, NUMBER_OF_MILLISECONDS_IN_A_MINUTE,
                                    NUMBER_OF_MILLISECONDS_IN_A_SECOND, 1)),
                            new LinkedList<String>(
                                    Arrays.asList("day", "hour", "minute", "second", "millisecond"))));

    modelAndView.addObject("totalMemory", convertToMegaBytes(Runtime.getRuntime().totalMemory()));
    modelAndView.addObject("maxMemory", convertToMegaBytes(Runtime.getRuntime().maxMemory()));
    modelAndView.addObject("freeMemory", convertToMegaBytes(Runtime.getRuntime().freeMemory()));
    modelAndView.addObject("availableProcessors", Runtime.getRuntime().availableProcessors());
    modelAndView.addObject("serverHostName", httpServletRequest.getServerName());
    modelAndView.addObject("serverIpAddress", httpServletRequest.getLocalAddr());
    modelAndView.addObject("casTicketSuffix", this.casTicketSuffix);

    int unexpiredTgts = 0;
    int unexpiredSts = 0;
    int expiredTgts = 0;
    int expiredSts = 0;

    try {
        final Collection<Ticket> tickets = this.centralAuthenticationService
                .getTickets(TruePredicate.getInstance());

        for (final Ticket ticket : tickets) {
            if (ticket instanceof ServiceTicket) {
                if (ticket.isExpired()) {
                    expiredSts++;
                } else {
                    unexpiredSts++;
                }
            } else {
                if (ticket.isExpired()) {
                    expiredTgts++;
                } else {
                    unexpiredTgts++;
                }
            }
        }
    } catch (final UnsupportedOperationException e) {
        logger.trace("The ticket registry doesn't support this information.");
    }

    final Collection<GraphingStatisticsAppender> appenders = GraphingStatisticsAppender
            .getAllGraphingStatisticsAppenders();

    modelAndView.addObject("unexpiredTgts", unexpiredTgts);
    modelAndView.addObject("unexpiredSts", unexpiredSts);
    modelAndView.addObject("expiredTgts", expiredTgts);
    modelAndView.addObject("expiredSts", expiredSts);
    modelAndView.addObject("pageTitle", modelAndView.getViewName());
    modelAndView.addObject("graphingStatisticAppenders", appenders);

    return modelAndView;
}

From source file:org.jasig.cas.web.report.StatisticsController.java

/**
 * Handles the request./* w  ww .j  a  va2s.co m*/
 *
 * @param httpServletRequest the http servlet request
 * @param httpServletResponse the http servlet response
 * @return the model and view
 * @throws Exception the exception
 */
@RequestMapping(method = RequestMethod.GET)
protected ModelAndView handleRequestInternal(final HttpServletRequest httpServletRequest,
        final HttpServletResponse httpServletResponse) throws Exception {
    final ModelAndView modelAndView = new ModelAndView(MONITORING_VIEW_STATISTICS);
    modelAndView.addObject("startTime", this.upTimeStartDate);
    final double difference = System.currentTimeMillis() - this.upTimeStartDate.getTime();

    modelAndView
            .addObject("upTime",
                    calculateUptime(difference,
                            new LinkedList<Integer>(Arrays.asList(NUMBER_OF_MILLISECONDS_IN_A_DAY,
                                    NUMBER_OF_MILLISECONDS_IN_AN_HOUR, NUMBER_OF_MILLISECONDS_IN_A_MINUTE,
                                    NUMBER_OF_MILLISECONDS_IN_A_SECOND, 1)),
                            new LinkedList<String>(
                                    Arrays.asList("day", "hour", "minute", "second", "millisecond"))));

    modelAndView.addObject("totalMemory", convertToMegaBytes(Runtime.getRuntime().totalMemory()));
    modelAndView.addObject("maxMemory", convertToMegaBytes(Runtime.getRuntime().maxMemory()));
    modelAndView.addObject("freeMemory", convertToMegaBytes(Runtime.getRuntime().freeMemory()));
    modelAndView.addObject("availableProcessors", Runtime.getRuntime().availableProcessors());
    modelAndView.addObject("serverHostName", httpServletRequest.getServerName());
    modelAndView.addObject("serverIpAddress", httpServletRequest.getLocalAddr());
    modelAndView.addObject("casTicketSuffix", this.casTicketSuffix);

    int unexpiredTgts = 0;
    int unexpiredSts = 0;
    int expiredTgts = 0;
    int expiredSts = 0;

    try {
        final Collection<Ticket> tickets = this.centralAuthenticationService.getTickets(TruePredicate.INSTANCE);

        for (final Ticket ticket : tickets) {
            if (ticket instanceof ServiceTicket) {
                if (ticket.isExpired()) {
                    expiredSts++;
                } else {
                    unexpiredSts++;
                }
            } else {
                if (ticket.isExpired()) {
                    expiredTgts++;
                } else {
                    unexpiredTgts++;
                }
            }
        }
    } catch (final UnsupportedOperationException e) {
        logger.trace("The ticket registry doesn't support this information.");
    }

    modelAndView.addObject("unexpiredTgts", unexpiredTgts);
    modelAndView.addObject("unexpiredSts", unexpiredSts);
    modelAndView.addObject("expiredTgts", expiredTgts);
    modelAndView.addObject("expiredSts", expiredSts);
    modelAndView.addObject("pageTitle", modelAndView.getViewName());

    return modelAndView;
}

From source file:com.jd.survey.web.settings.SurveyDefinitionController.java

/**
 * Renders the page for the survey definition import from a JSON file 
 * @param departmentId//from  www.  ja v  a 2s . c  o m
 * @param uiModel
 * @param httpServletRequest
 * @return
 */
@Secured({ "ROLE_ADMIN", "ROLE_SURVEY_ADMIN" })
@RequestMapping(value = "/upload", produces = "text/html")
public String uploadFromJson(@RequestParam(value = "id", required = false) Long departmentId, Model uiModel,
        Principal principal, HttpServletRequest httpServletRequest) {
    try {
        String login = principal.getName();
        User user = userService.user_findByLogin(login);

        //Check if the user is authorized
        if (departmentId != null && !securityService.userBelongsToDepartment(departmentId, user)) {
            log.warn("Unauthorized access to url path " + httpServletRequest.getPathInfo()
                    + " attempted by user login:" + principal.getName() + "from IP:"
                    + httpServletRequest.getLocalAddr());
            return "accessDenied";
        }
        Set<Department> departments = surveySettingsService.department_findAll(user);
        uiModel.addAttribute("departments", departments);
        uiModel.addAttribute("departmentId", departmentId);
        uiModel.addAttribute("jsonTemplates", surveySettingsService.surveyTemplate_findAll());

        return "settings/surveyDefinitions/upload";
    }

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

From source file:com.jd.survey.web.settings.SurveyDefinitionController.java

@Secured({ "ROLE_ADMIN", "ROLE_SURVEY_ADMIN" })
@RequestMapping(value = "/browsetemplate", method = RequestMethod.POST, produces = "text/html")
public String browseTemplatePost(@RequestParam(value = "id", required = false) Long departmentId,
        @RequestParam(value = "secId", required = false) Long sectorId,
        @RequestParam(value = "tempId", required = false) Long templateId,
        @RequestParam("name") String surveyName,
        @RequestParam(value = "_proceed", required = false) String proceed, Principal principal, Model uiModel,
        HttpServletRequest httpServletRequest) {
    try {/* ww  w  . j a v a2s.  c  o m*/
        String login = principal.getName();
        User user = userService.user_findByLogin(login);
        //Check if the user is authorized
        if (!securityService.userBelongsToDepartment(departmentId, user)) {
            log.warn("Unauthorized access to url path " + httpServletRequest.getPathInfo()
                    + " attempted by user login:" + principal.getName() + "from IP:"
                    + httpServletRequest.getLocalAddr());
            return "accessDenied";
        }

        if (proceed != null) {
            Department department = surveySettingsService.department_findById(departmentId);
            SurveyDefinition sdef = new SurveyDefinition(department, surveyName);

            if (!surveySettingsService.surveyDefinition_ValidateNameIsUnique(sdef)) {
                uiModel.addAttribute("department", surveySettingsService.department_findById(departmentId));
                uiModel.addAttribute("sector", surveySettingsService.sector_findById(sectorId));
                uiModel.addAttribute("templates",
                        surveySettingsService.surveyTemplate_findBySectorId(sectorId));
                uiModel.addAttribute("nameDuplicateError", true);
                return "settings/surveyDefinitions/browsetemplate";
            }
            if (surveyName != null && surveyName.trim().length() > 0 && surveyName.trim().length() < 250) {
                SurveyTemplate st = surveySettingsService.surveyTemplate_findById(templateId);
                String jsonString = st.getJson();
                SurveyDefinition surveyDefinition = jsonHelperService.deSerializeSurveyDefinition(jsonString);
                surveyDefinition.setName(surveyName);
                surveyDefinition = surveySettingsService.surveyDefinition_create(surveyDefinition,
                        departmentId);
                uiModel.asMap().clear();
                surveyDefinition = surveySettingsService.surveyDefinition_merge(surveyDefinition);
                return "redirect:/settings/surveyDefinitions/"
                        + encodeUrlPathSegment(surveyDefinition.getId().toString(), httpServletRequest);
            } else {
                uiModel.addAttribute("department", surveySettingsService.department_findById(departmentId));
                uiModel.addAttribute("sector", surveySettingsService.sector_findById(sectorId));
                uiModel.addAttribute("templates",
                        surveySettingsService.surveyTemplate_findBySectorId(sectorId));
                uiModel.addAttribute("nameError", true);
                return "settings/surveyDefinitions/browsetemplate";
            }
        }
        uiModel.addAttribute("departments", surveySettingsService.department_findAll(user));
        uiModel.addAttribute("departmentId", departmentId);
        uiModel.addAttribute("sectors", surveySettingsService.sector_findAll());
        return "settings/surveyDefinitions/importtemplate";
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw (new RuntimeException(e));
    }
}

From source file:com.jd.survey.web.settings.SurveyDefinitionController.java

/**
 * Returns the survey logo image binary  
 * @param departmentId/* w  w w  .  j  a v  a 2  s .c  o m*/
 * @param uiModel
 * @param httpServletRequest
 * @return
 */
@Secured({ "ROLE_ADMIN", "ROLE_SURVEY_ADMIN" })
@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();
        User user = userService.user_findByLogin(principal.getName());
        //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());
            throw (new RuntimeException("Unauthorized access to logo"));
        }
        SurveyDefinition surveyDefinition = surveySettingsService.surveyDefinition_findById(surveyDefinitionId);
        //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.settings.SurveyDefinitionController.java

@Secured({ "ROLE_ADMIN", "ROLE_SURVEY_ADMIN" })
@RequestMapping(value = "/{id}", params = "savetemplate", produces = "text/html")
public String saveTemplate(@PathVariable("id") Long surveyDefinitionId, Principal principal, Model uiModel,
        HttpServletRequest httpServletRequest, HttpServletResponse response) {
    try {//w ww .jav  a  2s  . c  o m
        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");

        }
        Set<Sector> sectors;
        sectors = surveySettingsService.sector_findAll();
        if (sectors.size() <= 0) {
            uiModel.addAttribute("noSectors", true);
        }
        uiModel.addAttribute("sectors", sectors);
        uiModel.addAttribute("sid", surveyDefinitionId);
        return "settings/surveyDefinitions/savetemplate";
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw (new RuntimeException(e));
    }
}

From source file:com.jd.survey.web.settings.SurveyDefinitionController.java

/**
 * Imports survey definition from a JSON file, This feature may be used to migrate survey definitions from different environments,
 * For example from a test environment to a production environment   
 * @param file//from  w w  w  .  j  av a  2 s  . c om
 * @param departmentId
 * @param surveyName
 * @param proceed
 * @param uiModel
 * @param httpServletRequest
 * @return
 */
@Secured({ "ROLE_ADMIN", "ROLE_SURVEY_ADMIN" })
@RequestMapping(value = "/upload", method = RequestMethod.POST, produces = "text/html")
public String uploadFromJsonPost(@RequestParam("file") MultipartFile file,
        @RequestParam("id") Long departmentId, @RequestParam("name") String surveyName,
        @RequestParam(value = "_proceed", required = false) String proceed, Principal principal, Model uiModel,
        HttpServletRequest httpServletRequest) {
    try {
        String login = principal.getName();
        User user = userService.user_findByLogin(login);
        //Check if the user is authorized
        if (!securityService.userBelongsToDepartment(departmentId, user)) {
            log.warn("Unauthorized access to url path " + httpServletRequest.getPathInfo()
                    + " attempted by user login:" + principal.getName() + "from IP:"
                    + httpServletRequest.getLocalAddr());
            return "accessDenied";
        }

        if (proceed != null) {
            Long surveyDefinitionId = null;
            try {
                if (!surveySettingsService.surveyDefinition_ValidateNameIsUnique(new SurveyDefinition(
                        surveySettingsService.department_findById(departmentId), surveyName))) {
                    uiModel.addAttribute("departments", surveySettingsService.department_findAll(user));
                    uiModel.addAttribute("nameDuplicateError", true);
                    return "settings/surveyDefinitions/upload";
                }

                if (!file.isEmpty()) {
                    if (surveyName != null && surveyName.trim().length() > 0
                            && surveyName.trim().length() < 250) {
                        String jsonString = new String(file.getBytes(), "UTF8");
                        SurveyDefinition surveyDefinition = jsonHelperService
                                .deSerializeSurveyDefinition(jsonString);
                        surveyDefinition.setName(surveyName);
                        surveyDefinition = surveySettingsService.surveyDefinition_create(surveyDefinition,
                                departmentId);
                        surveyDefinitionId = surveyDefinition.getId();
                    } else {
                        uiModel.addAttribute("departments", surveySettingsService.department_findAll(user));
                        uiModel.addAttribute("nameError", true);
                        return "settings/surveyDefinitions/upload";
                    }
                } else {
                    uiModel.addAttribute("departments", surveySettingsService.department_findAll(user));
                    uiModel.addAttribute("emptyFileError", true);
                    return "settings/surveyDefinitions/upload";
                }

            }

            catch (Exception e) {
                log.error(e.getMessage(), e);
                uiModel.addAttribute("departments", surveySettingsService.department_findAll(user));
                uiModel.addAttribute("importError", true);
                return "settings/surveyDefinitions/upload";
            }
            return "redirect:/settings/surveyDefinitions/"
                    + encodeUrlPathSegment(surveyDefinitionId.toString(), httpServletRequest);
        } else {
            return "redirect:/settings/surveyDefinitions?page=1&size=25";

        }

    }

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

}

From source file:jp.aegif.alfresco.online_webdav.WebDAVHelper.java

/**
 * Check that the destination path is on this server and is a valid WebDAV
 * path for this server//from w w w .  ja v  a2  s.c  o  m
 * 
 * @param request The request made against the WebDAV server.
 * @param urlStr String
 * @exception WebDAVServerException
 */
public void checkDestinationURL(HttpServletRequest request, String urlStr) throws WebDAVServerException {
    try {
        // Parse the URL

        URL url = new URL(urlStr);

        // Check if the path is on this WebDAV server

        boolean localPath = true;

        if (url.getPort() != -1 && url.getPort() != request.getServerPort()) {
            // Debug

            if (logger.isDebugEnabled())
                logger.debug("Destination path, different server port");

            localPath = false;
        } else if (url.getHost().equalsIgnoreCase(request.getServerName()) == false
                && url.getHost().equals(request.getLocalAddr()) == false) {
            // The target host may contain a domain or be specified as a numeric IP address

            String targetHost = url.getHost();

            if (IPAddress.isNumericAddress(targetHost) == false) {
                String localHost = request.getServerName();

                int pos = targetHost.indexOf(".");
                if (pos != -1)
                    targetHost = targetHost.substring(0, pos);

                pos = localHost.indexOf(".");
                if (pos != -1)
                    localHost = localHost.substring(0, pos);

                // compare the host names

                if (targetHost.equalsIgnoreCase(localHost) == false)
                    localPath = false;
            } else {
                try {
                    // Check if the target IP address is a local address

                    InetAddress targetAddr = InetAddress.getByName(targetHost);
                    if (NetworkInterface.getByInetAddress(targetAddr) == null)
                        localPath = false;
                } catch (Exception ex) {
                    // DEBUG

                    if (logger.isDebugEnabled())
                        logger.debug("Failed to check target IP address, " + targetHost);

                    localPath = false;
                }
            }

            // Debug

            if (localPath == false && logger.isDebugEnabled()) {
                logger.debug("Destination path, different server name/address");
                logger.debug("  URL host=" + url.getHost() + ", ServerName=" + request.getServerName()
                        + ", localAddr=" + request.getLocalAddr());
            }
        } else if (!url.getPath().startsWith(getUrlPathPrefix(request))) {
            // Debug

            if (logger.isDebugEnabled())
                logger.debug("Destination path, different serlet path");

            localPath = false;
        }

        // If the URL does not refer to this WebDAV server throw an
        // exception

        if (localPath != true)
            throw new WebDAVServerException(HttpServletResponse.SC_BAD_GATEWAY);
    } catch (MalformedURLException ex) {
        // Debug

        if (logger.isDebugEnabled())
            logger.debug("Bad destination path, " + urlStr);

        throw new WebDAVServerException(HttpServletResponse.SC_BAD_GATEWAY);
    }
}