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.InvitationController.java

/**
 * prepares the page to import invitations from a csv file       
 * @param dataSetId// w w  w .  j a v a  2 s.c  o  m
 * @param principal
 * @param uiModel
 * @param httpServletRequest
 * @return
 */
@Secured({ "ROLE_ADMIN", "ROLE_SURVEY_ADMIN" })
@RequestMapping(value = "/import", produces = "text/html")
public String prepareForImport(@RequestParam(value = "id", required = false) Long surveyDefinitionId,
        Principal principal, Model uiModel, HttpServletRequest httpServletRequest) {
    try {
        User user = userService.user_findByLogin(principal.getName());
        Set<SurveyDefinition> surveyDefinitions = surveySettingsService
                .surveyDefinition_findAllCompletedInternal(user);
        uiModel.addAttribute("surveyDefinitions", surveyDefinitions);
        if (surveyDefinitionId != null) {
            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";
            }
            uiModel.addAttribute("surveyDefinition",
                    surveySettingsService.surveyDefinition_findById(surveyDefinitionId));
        }
        return "settings/invitations/upload";
    }

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

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

@Secured({ "ROLE_ADMIN", "ROLE_SURVEY_ADMIN" })
@RequestMapping(method = RequestMethod.POST, produces = "text/html")
public String createPost(Question question, BindingResult bindingResult,
        @RequestParam(value = "_proceed", required = false) String proceed, Principal principal, Model uiModel,
        HttpServletRequest httpServletRequest) {
    log.info("create(): handles " + RequestMethod.POST.toString());
    try {//from   w w  w. j  a  v  a2  s  . c o  m
        String login = principal.getName();
        User user = userService.user_findByLogin(login);
        //Check if the user is authorized
        if (!securityService.userIsAuthorizedToManageSurvey(surveySettingsService
                .question_findById(question.getId()).getPage().getSurveyDefinition().getId(), user)
                && !securityService
                        .userBelongsToDepartment(surveySettingsService.question_findById(question.getId())
                                .getPage().getSurveyDefinition().getDepartment().getId(), 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) {
            boolean isValid = true;
            for (int i = 0; i < question.getColumnLabelsList().size(); i++) {
                if (question.getColumnLabelsList().get(i).getLabel() != null
                        && question.getColumnLabelsList().get(i).getLabel().trim().length() > 0) {

                    if (question.getColumnLabelsList().get(i).getLabel().trim().length() == 0
                            || question.getColumnLabelsList().get(i).getLabel().trim().length() > 75) {
                        bindingResult.rejectValue("columnLabelsList[" + i + "].label", "invalidEntry");
                        isValid = false;

                    }
                } else {
                    //User is trying to save an empty MC form
                    if (i == 0) {
                        bindingResult.rejectValue("columnLabelsList[" + i + "].label", "invalidEntry");
                        isValid = false;
                    }
                }
            }

            if (!isValid) {
                return "settings/questionCols/update";
            } else {
                question = surveySettingsService.question_updateColumnLabels(question);
                return "settings/questionCols/saved";

            }
        } else {
            question = surveySettingsService.question_updateColumnLabels(question);
            return "redirect:/settings/surveyDefinitions/" + encodeUrlPathSegment(
                    question.getPage().getSurveyDefinition().getId().toString(), httpServletRequest);
        }

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

}

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

@Secured({ "ROLE_ADMIN", "ROLE_SURVEY_ADMIN" })
@RequestMapping(method = RequestMethod.POST, produces = "text/html")
public String createPost(Question question, BindingResult bindingResult,
        @RequestParam(value = "_proceed", required = false) String proceed, Principal principal, Model uiModel,
        HttpServletRequest httpServletRequest) {
    log.info("create(): handles " + RequestMethod.POST.toString());
    try {/*from www .ja v a2  s  .co  m*/

        String login = principal.getName();
        User user = userService.user_findByLogin(login);
        //Check if the user is authorized
        if (!securityService.userIsAuthorizedToManageSurvey(surveySettingsService
                .question_findById(question.getId()).getPage().getSurveyDefinition().getId(), user)
                && !securityService
                        .userBelongsToDepartment(surveySettingsService.question_findById(question.getId())
                                .getPage().getSurveyDefinition().getDepartment().getId(), 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) {
            boolean isValid = true;
            for (int i = 0; i < question.getRowLabelsList().size(); i++) {
                if (question.getRowLabelsList().get(i).getLabel() != null
                        && question.getRowLabelsList().get(i).getLabel().trim().length() > 0) {

                    if (question.getRowLabelsList().get(i).getLabel().trim().length() == 0
                            || question.getRowLabelsList().get(i).getLabel().trim().length() > 75) {
                        bindingResult.rejectValue("rowLabelsList[" + i + "].label", "invalidEntry");
                        isValid = false;

                    }
                } else {
                    //User is trying to save an empty MC form
                    if (i == 0) {
                        bindingResult.rejectValue("rowLabelsList[" + i + "].label", "invalidEntry");
                        isValid = false;
                    }
                }
            }

            if (!isValid) {
                return "settings/questionRows/update";
            } else {
                question = surveySettingsService.question_updateRowLabels(question);
                return "settings/questionRows/saved";

            }
        } else {
            question = surveySettingsService.question_updateRowLabels(question);
            return "redirect:/settings/surveyDefinitions/" + encodeUrlPathSegment(
                    question.getPage().getSurveyDefinition().getId().toString(), httpServletRequest);
        }

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

}

From source file:com.thinkgem.jeesite.modules.sys.interceptor.GlobalInterceptor.java

@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
        Exception ex) throws Exception {
    String uri = request.getRequestURI();
    String uriPrefix = request.getContextPath() + Global.ADMIN_PATH;
    // ??POST/*from  w w w  .j  a va2s .  c o  m*/
    if ("POST".equals(request.getMethod()) && uri.length() > uriPrefix.length()) {
        User user = UserUtils.getUser();
        if (user != null) {
            StringBuilder sb = new StringBuilder();
            sb.append("url: (" + request.getMethod() + ") " + uri);
            int index = 0;
            for (Object param : request.getParameterMap().keySet()) {
                sb.append((index++ == 0 ? "?" : "&") + param + "=");
                sb.append(StringUtils.abbreviate(request.getParameter((String) param), 100));
            }
            sb.append("; userId: " + user.getId());
            sb.append("; userName: " + user.getName());
            sb.append("; loginName: " + user.getLoginName());
            sb.append("; ipAddr: " + request.getLocalAddr());
            sb.append("; datetime: " + DateUtils.getDateTime());
            sb.append("; handler: " + handler.toString());
            logger.info(sb.toString());
        }
    }
}

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

@Secured({ "ROLE_ADMIN", "ROLE_SURVEY_ADMIN" })
@RequestMapping(value = "/{id}", produces = "text/html")
public String show(@PathVariable("id") Long id, Principal principal, HttpServletRequest httpServletRequest,
        Model uiModel) {//from w ww .java 2 s.  co  m
    log.info("show(): id=" + id);
    try {
        SurveyDefinitionPage page = surveySettingsService.surveyDefinitionPage_findById(id);

        String login = principal.getName();
        User user = userService.user_findByLogin(login);
        //Check if the user is authorized
        if (!securityService.userIsAuthorizedToManageSurvey(page.getSurveyDefinition().getId(), user)
                && !securityService.userBelongsToDepartment(page.getSurveyDefinition().getDepartment().getId(),
                        user)) {
            log.warn("Unauthorized access to url path " + httpServletRequest.getPathInfo()
                    + " attempted by user login:" + principal.getName() + "from IP:"
                    + httpServletRequest.getLocalAddr());
            return "accessDenied";
        }

        /*
        for (Question question: page.getQuestions()) {
           if (question.getType()== QuestionType.DATASET_DROP_DOWN){
              DataSet dataset = surveySettingsService.dataset_findByName(question.getDataSetCode());
              uiModel.addAttribute("datasetItems" + question.getOrder(),surveySettingsService.datasetItem_findByDataSetId(dataset.getId(), 0, 10));
           }
                   
        }
        */
        uiModel.addAttribute("page", page);
        return "settings/surveyDefinitionPages/show";
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw (new RuntimeException(e));
    }
}

From source file:cn.bc.web.util.DebugUtils.java

public static StringBuffer getDebugInfo(HttpServletRequest request, HttpServletResponse response) {
    @SuppressWarnings("rawtypes")
    Enumeration e;/*  w ww  .ja v a2 s. c  o  m*/
    String name;
    StringBuffer html = new StringBuffer();

    //session
    HttpSession session = request.getSession();
    html.append("<div><b>session:</b></div><ul>");
    html.append(createLI("Id", session.getId()));
    html.append(createLI("CreationTime", new Date(session.getCreationTime()).toString()));
    html.append(createLI("LastAccessedTime", new Date(session.getLastAccessedTime()).toString()));

    //session:attributes
    e = session.getAttributeNames();
    html.append("<li>attributes:<ul>\r\n");
    while (e.hasMoreElements()) {
        name = (String) e.nextElement();
        html.append(createLI(name, String.valueOf(session.getAttribute(name))));
    }
    html.append("</ul></li>\r\n");
    html.append("</ul>\r\n");

    //request
    html.append("<div><b>request:</b></div><ul>");
    html.append(createLI("URL", request.getRequestURL().toString()));
    html.append(createLI("QueryString", request.getQueryString()));
    html.append(createLI("Method", request.getMethod()));
    html.append(createLI("CharacterEncoding", request.getCharacterEncoding()));
    html.append(createLI("ContentType", request.getContentType()));
    html.append(createLI("Protocol", request.getProtocol()));
    html.append(createLI("RemoteAddr", request.getRemoteAddr()));
    html.append(createLI("RemoteHost", request.getRemoteHost()));
    html.append(createLI("RemotePort", request.getRemotePort() + ""));
    html.append(createLI("RemoteUser", request.getRemoteUser()));
    html.append(createLI("ServerName", request.getServerName()));
    html.append(createLI("ServletPath", request.getServletPath()));
    html.append(createLI("ServerPort", request.getServerPort() + ""));
    html.append(createLI("Scheme", request.getScheme()));
    html.append(createLI("LocalAddr", request.getLocalAddr()));
    html.append(createLI("LocalName", request.getLocalName()));
    html.append(createLI("LocalPort", request.getLocalPort() + ""));
    html.append(createLI("Locale", request.getLocale().toString()));

    //request:headers
    e = request.getHeaderNames();
    html.append("<li>Headers:<ul>\r\n");
    while (e.hasMoreElements()) {
        name = (String) e.nextElement();
        html.append(createLI(name, request.getHeader(name)));
    }
    html.append("</ul></li>\r\n");

    //request:parameters
    e = request.getParameterNames();
    html.append("<li>Parameters:<ul>\r\n");
    while (e.hasMoreElements()) {
        name = (String) e.nextElement();
        html.append(createLI(name, request.getParameter(name)));
    }
    html.append("</ul></li>\r\n");

    html.append("</ul>\r\n");

    //response
    html.append("<div><b>response:</b></div><ul>");
    html.append(createLI("CharacterEncoding", response.getCharacterEncoding()));
    html.append(createLI("ContentType", response.getContentType()));
    html.append(createLI("BufferSize", response.getBufferSize() + ""));
    html.append(createLI("Locale", response.getLocale().toString()));
    html.append("<ul>\r\n");
    return html;
}

From source file:com.datatorrent.stram.security.StramWSFilter.java

@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
        throws IOException, ServletException {
    if (!(req instanceof HttpServletRequest)) {
        throw new ServletException("This filter only works for HTTP/HTTPS");
    }//  w w w.  j  a  v a 2  s. c o  m

    HttpServletRequest httpReq = (HttpServletRequest) req;
    HttpServletResponse httpResp = (HttpServletResponse) resp;
    if (LOG.isDebugEnabled()) {
        LOG.debug("Remote address for request is: " + httpReq.getRemoteAddr());
    }
    String requestURI = httpReq.getRequestURI();
    if (LOG.isDebugEnabled()) {
        LOG.debug("Request path " + requestURI);
    }
    boolean authenticate = true;
    String user = null;
    if (getProxyAddresses().contains(httpReq.getRemoteAddr())) {
        if (httpReq.getCookies() != null) {
            for (Cookie c : httpReq.getCookies()) {
                if (WEBAPP_PROXY_USER.equals(c.getName())) {
                    user = c.getValue();
                    break;
                }
            }
        }
        if (requestURI.equals(WebServices.PATH) && (user != null)) {
            String token = createClientToken(user, httpReq.getLocalAddr());
            if (LOG.isDebugEnabled()) {
                LOG.debug("Create token " + token);
            }
            Cookie cookie = new Cookie(CLIENT_COOKIE, token);
            httpResp.addCookie(cookie);
        }
        authenticate = false;
    }
    if (authenticate) {
        Cookie cookie = null;
        if (httpReq.getCookies() != null) {
            for (Cookie c : httpReq.getCookies()) {
                if (c.getName().equals(CLIENT_COOKIE)) {
                    cookie = c;
                    break;
                }
            }
        }
        boolean valid = false;
        if (cookie != null) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Verifying token " + cookie.getValue());
            }
            user = verifyClientToken(cookie.getValue());
            valid = true;
            if (LOG.isDebugEnabled()) {
                LOG.debug("Token valid");
            }
        }
        if (!valid) {
            httpResp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }
    }

    if (user == null) {
        LOG.warn("Could not find " + WEBAPP_PROXY_USER + " cookie, so user will not be set");
        chain.doFilter(req, resp);
    } else {
        final StramWSPrincipal principal = new StramWSPrincipal(user);
        ServletRequest requestWrapper = new StramWSServletRequestWrapper(httpReq, principal);
        chain.doFilter(requestWrapper, resp);
    }
}

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

/**
 * Creates a new survey based on the passed surveyDefintionId 
 * @param surveyDefinitionId/*from  w ww.  j a  v  a 2 s .c  o m*/
 * @param uiModel
 * @param httpServletRequest
 * @return
 */

@RequestMapping(value = "/{id}", params = "create", produces = "text/html")
public String createSurvey(@PathVariable("id") Long surveyDefinitionId, Model uiModel, Principal principal,
        HttpServletRequest httpServletRequest) {
    log.info("create a new survey 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";
        }

        Survey survey = surveyService.survey_create(surveyDefinitionId, null,
                httpServletRequest.getRemoteAddr());

        return "redirect:/open/" + 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

/**
 * Returns the survey logo image binary  
 * @param departmentId/*from w  ww  .j a va2  s.  c  o m*/
 * @param uiModel
 * @param httpServletRequest
 * @return
 */
@Secured({ "ROLE_ADMIN", "ROLE_SURVEY_ADMIN", "ROLE_SURVEY_PARTICIPANT" })
@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.userIsAuthorizedToCreateSurvey(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"));
        } else {
            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:org.iwethey.forums.web.HeaderInterceptor.java

/**
 * Load the request attributes with the User object (if authenticated)
 * and start time for the page for audit purposes.
 * <p>/*from  w  ww  . j  a va  2  s  . c  om*/
 * @param request The servlet request object.
 * @param response The servlet response object.
 * @param handler The request handler processing this request.
 */
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {
    Date now = new Date();
    request.setAttribute("now", now);

    long start = now.getTime();
    request.setAttribute("start", new Long(start));

    Integer id = (Integer) WebUtils.getSessionAttribute(request, USER_ID_ATTRIBUTE);

    User user = null;

    if (id == null) {
        user = (User) WebUtils.getSessionAttribute(request, USER_ATTRIBUTE);

        if (user == null) {
            user = new User("Anonymous");
            WebUtils.setSessionAttribute(request, USER_ATTRIBUTE, user);
        }
    } else {
        user = mUserManager.getUserById(id.intValue());
        user.setLastPresent(new Date());
        mUserManager.saveUserAttributes(user);
    }

    request.setAttribute("username", user.getNickname());
    request.setAttribute(USER_ATTRIBUTE, user);

    System.out.println("Local Address  = [" + request.getLocalAddr() + "]");
    System.out.println("Local Name     = [" + request.getLocalName() + "]");
    System.out.println("Remote Address = [" + request.getRemoteAddr() + "]");
    System.out.println("Remote Host    = [" + request.getRemoteHost() + "]");
    System.out.println("Remote Port    = [" + request.getRemotePort() + "]");
    System.out.println("Remote User    = [" + request.getRemoteUser() + "]");
    System.out.println("Context Path   = [" + request.getContextPath() + "]");
    System.out.println("====================");

    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            Cookie cookie = cookies[i];

            System.out.println("Cookie Domain = [" + cookie.getDomain() + "]");
            System.out.println("Cookie Name   = [" + cookie.getName() + "]");
            System.out.println("Cookie Value  = [" + cookie.getValue() + "]");
            System.out.println("Cookie Expire = [" + cookie.getMaxAge() + "]");
            System.out.println("====================");

            if ("iwt_cookie".equals(cookie.getName())) {
                cookie.setMaxAge(1000 * 60 * 60 * 24 * 30 * 6);
                response.addCookie(cookie);
            }
        }
    } else {
        System.out.println("No cookies were found in the request");
    }

    Cookie newCookie = new Cookie("iwt_cookie", "harrr2!");
    newCookie.setPath(request.getContextPath());
    newCookie.setDomain(request.getLocalName());
    newCookie.setMaxAge(1000 * 60 * 60 * 24 * 30 * 6);
    response.addCookie(newCookie);

    request.setAttribute(HEADER_IMAGE_ATTRIBUTE, "/images/iwethey-lrpd-small.png");

    return true;
}