Example usage for javax.servlet.http HttpServletRequest getRemoteAddr

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

Introduction

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

Prototype

public String getRemoteAddr();

Source Link

Document

Returns the Internet Protocol (IP) address of the client or last proxy that sent the request.

Usage

From source file:br.org.indt.ndg.servlets.PostResultsOpenRosa.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    m_openRosaBD.setPortAndAddress(SystemProperties.getServerAddress());

    InputStreamReader inputStreamReader = new InputStreamReader(request.getInputStream(), "UTF-8");
    boolean success = m_openRosaBD.parseAndPersistResult(inputStreamReader, request.getContentType());

    DataOutputStream dataOutputStream = new DataOutputStream(response.getOutputStream());
    if (success) {
        dataOutputStream.writeInt(SUCCESS);
        log.info("Successfully processed result stream from " + request.getRemoteAddr());
    } else {//w w  w  . jav  a2  s .co m
        dataOutputStream.writeInt(FAILURE);
        log.error("Failed processing result stream from " + request.getRemoteAddr());
    }
    dataOutputStream.close();
}

From source file:net.webpasswordsafe.server.report.JasperReportServlet.java

private boolean isAuthorizedReport(HttpServletRequest req, String reportName) {
    boolean isAuthorized = isAuthorized(req, Constants.VIEW_REPORT_PREFIX + reportName);
    User user = new User();
    user.setUsername((String) req.getSession().getAttribute(Constants.SESSION_KEY_USERNAME));
    AuditLogger auditLogger = (AuditLogger) WebApplicationContextUtils
            .getWebApplicationContext(getServletContext()).getBean("auditLogger");
    auditLogger.log(new Date(), user.getUsername(), req.getRemoteAddr(), "view report", reportName,
            isAuthorized, (isAuthorized ? "" : "not authorized"));
    return isAuthorized;
}

From source file:com.usefullc.platform.common.log.LogHandlerInterceptor.java

@Override
public void beforeHandler(ActionHandler actionHandler) {
    if (!this.monitor) { // ?
        return;//from  w w  w .  j av  a2  s. c  o m
    }
    Long userId = OnlineUserManager.getUserId();
    if (userId == null) { // 
        return;
    }
    HttpServletRequest request = actionHandler.getRequest();

    String url = request.getRequestURI();

    // ?
    if (!logInfoRemoteService.canRecord(url)) {
        return;
    }

    // 
    LogInfoDto domain = new LogInfoDto();
    domain.setRequestUrl(url);

    // ??
    String cnName = OnlineUserManager.getCnName();
    domain.setUserName(cnName);

    String remoteAddr = request.getRemoteAddr();
    domain.setRemoteAddr(remoteAddr);

    // request headers
    JSONObject jsonObj = new JSONObject();
    Enumeration<String> headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String headerName = headerNames.nextElement();
        Enumeration<String> headerValues = request.getHeaders(headerName);
        StringBuilder sb = new StringBuilder();
        while (headerValues.hasMoreElements()) {
            sb.append(headerValues.nextElement());
            sb.append(",");
        }
        if (sb.length() > 0) {
            sb.substring(0, sb.length() - 1);
        }
        jsonObj.put(headerName, sb.toString());
    }
    domain.setRequestHeader(jsonObj.toString());

    // request data
    jsonObj = new JSONObject();
    Map<String, String[]> paramMap = request.getParameterMap();
    if (MapUtils.isNotEmpty(paramMap)) {
        Set<Entry<String, String[]>> set = paramMap.entrySet();
        for (Entry<String, String[]> entry : set) {
            String key = entry.getKey();
            String value = ArrayUtils.toString(entry.getValue());
            jsonObj.put(key, value);
        }
    }
    domain.setRequestData(jsonObj.toString());
    threadLocal.set(domain);

}

From source file:com.kurento.kmf.jsonrpcconnector.internal.server.config.OAuthFiWareFilter.java

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
        FilterChain filterChain) throws ServletException, IOException {

    String fullUrl = request.getRequestURL().append('?').append(request.getQueryString()).toString();

    log.info("Client trying to stablish new websocket session with {}", fullUrl);

    if (!Strings.isNullOrEmpty(props.getKeystoneHost())) {
        String accessToken = parseAccessToken(request);
        if (Strings.isNullOrEmpty(accessToken)) {
            log.warn("Request from {} without OAuth token", request.getRemoteAddr());
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Access token not found in request");
        } else if (isTokenValid(accessToken)) {
            log.info("The request from {} was authorized", request.getRemoteAddr());
            filterChain.doFilter(request, response);
        } else {/*from   w  w  w. j  a v  a2 s .  c  o m*/
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unathorized request");
        }
    } else {
        log.info("Request from {} authorized: no keystone host configured", request.getRemoteAddr());
        filterChain.doFilter(request, response);
    }
}

From source file:net.webpasswordsafe.server.webservice.rest.PasswordController.java

@RequestMapping(value = "/passwords", method = RequestMethod.POST)
public ModelAndView addPassword(@RequestBody Map<String, Object> passwordMap, HttpServletRequest request,
        @RequestHeader(Constants.REST_AUTHN_USERNAME) String authnUsername,
        @RequestHeader(Constants.REST_AUTHN_PASSWORD) String authnPassword,
        @RequestHeader(Constants.REST_AUTHN_TOTP) String authnTOTP) {
    boolean isSuccess = false;
    String message = "";
    String passwordId = "";
    try {//from w ww. ja va 2  s. c o  m
        ServerSessionUtil.setIP(request.getRemoteAddr());
        AuthenticationStatus authStatus = loginService.login(authnUsername,
                Utils.buildCredentials(authnPassword, authnTOTP));
        if (AuthenticationStatus.SUCCESS == authStatus) {
            User loggedInUser = loginService.getLogin();
            Password password = new Password();
            password.setName(Utils.safeString(passwordMap.get("title")));
            password.setUsername(Utils.safeString(passwordMap.get("username")));
            PasswordData passwordDataItem = new PasswordData();
            passwordDataItem.setPassword(Utils.safeString(passwordMap.get("password")));
            password.addPasswordData(passwordDataItem);
            password.setNotes(Utils.safeString(passwordMap.get("notes")));
            password.setMaxHistory(-1);
            String active = Utils.safeString(passwordMap.get("active")).toLowerCase();
            password.setActive(
                    active.equals("") || active.equals("true") || active.equals("yes") || active.equals("y"));
            password.addPermission(new Permission(loggedInUser, AccessLevel.GRANT));
            password.addTagsAsString(Utils.safeString(passwordMap.get("tags")));
            if (passwordService.isPasswordTaken(password.getName(), password.getUsername(), password.getId())) {
                message = "Password title and username already exists";
            } else {
                passwordService.addPassword(password);
                passwordId = String.valueOf(password.getId());
                isSuccess = true;
            }
        } else {
            message = "Invalid authentication";
        }
        loginService.logout();
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
        isSuccess = false;
        message = e.getMessage();
    }
    return createModelAndView(isSuccess, message, "passwordId", passwordId);
}

From source file:org.kurento.jsonrpc.internal.server.config.OAuthFiWareFilter.java

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
        FilterChain filterChain) throws ServletException, IOException {

    String fullUrl = request.getRequestURL().append('?').append(request.getQueryString()).toString();

    log.trace("Client trying to stablish new websocket session with {}", fullUrl);

    if (!Strings.isNullOrEmpty(props.getKeystoneHost())) {
        String accessToken = parseAccessToken(request);
        if (Strings.isNullOrEmpty(accessToken)) {
            log.warn("Request from {} without OAuth token", request.getRemoteAddr());
            response.sendError(SC_UNAUTHORIZED, "Access token not found in request");
        } else if (isTokenValid(accessToken)) {
            log.trace("The request from {} was authorized", request.getRemoteAddr());
            filterChain.doFilter(request, response);
        } else {/*from  www. jav a 2  s.  co  m*/
            response.sendError(SC_UNAUTHORIZED, "Unathorized request");
        }
    } else {
        log.trace("Request from {} authorized: no keystone host configured", request.getRemoteAddr());
        filterChain.doFilter(request, response);
    }
}

From source file:com.amani.action.LoginAction.java

public String getRemortIP() {
    ActionContext ac = ActionContext.getContext();
    HttpServletRequest request = (HttpServletRequest) ac.get(ServletActionContext.HTTP_REQUEST);
    if (request.getHeader("x-forwarded-for") == null) {
        return request.getRemoteAddr();
    }/*from   ww w.  java  2  s  .c o  m*/
    return request.getHeader("x-forwarded-for");
}

From source file:gov.nih.nci.cabig.caaers.web.filters.CsrfPreventionFilter.java

protected boolean isValidCsrfToken(HttpServletRequest req) {
    String csrfParamToken = getCSRFToken(req);
    String csrfSessionToken = req.getSession().getAttribute(CSRF_TOKEN).toString();
    if (!StringUtils.isEmpty(csrfParamToken) && !StringUtils.isEmpty(csrfSessionToken)
            && csrfParamToken.equals(csrfSessionToken)) {
        return true;
    } else {//from   w  w w  .java  2  s.c  o m
        //Log this as this can be a security threat
        logger.warn("Invalid security Token. Supplied token: " + csrfParamToken + ". Session token: "
                + csrfSessionToken + ". IP: " + req.getRemoteAddr());
        return false;
    }
}

From source file:net.webpasswordsafe.server.webservice.rest.PasswordController.java

@RequestMapping(value = "/passwords", method = RequestMethod.PUT)
public ModelAndView updatePassword(@RequestBody Map<String, Object> passwordMap, HttpServletRequest request,
        @RequestHeader(Constants.REST_AUTHN_USERNAME) String authnUsername,
        @RequestHeader(Constants.REST_AUTHN_PASSWORD) String authnPassword,
        @RequestHeader(Constants.REST_AUTHN_TOTP) String authnTOTP) {
    boolean isSuccess = false;
    String message = "";
    String passwordId = "";
    try {/*from  w ww . ja  v a 2s.  c  o  m*/
        ServerSessionUtil.setIP(request.getRemoteAddr());
        AuthenticationStatus authStatus = loginService.login(authnUsername,
                Utils.buildCredentials(authnPassword, authnTOTP));
        if (AuthenticationStatus.SUCCESS == authStatus) {
            passwordId = Utils.safeString(passwordMap.get("id"));
            int iPasswordId = Utils.safeInt(passwordId);
            if (iPasswordId > 0) {
                Password password = passwordService.getPassword(iPasswordId);
                if (null != password) {
                    Password updatePassword = password.cloneCopy();
                    updatePassword.setName(Utils.safeString(passwordMap.get("title")));
                    updatePassword.setUsername(Utils.safeString(passwordMap.get("username")));
                    PasswordData passwordDataItem = new PasswordData();
                    passwordDataItem.setPassword(Utils.safeString(passwordMap.get("password")));
                    updatePassword.addPasswordData(passwordDataItem);
                    updatePassword.setNotes(Utils.safeString(passwordMap.get("notes")));
                    String active = Utils.safeString(passwordMap.get("active")).toLowerCase();
                    updatePassword.setActive(active.equals("") || active.equals("true") || active.equals("yes")
                            || active.equals("y"));
                    updatePassword.addTagsAsString(Utils.safeString(passwordMap.get("tags")));
                    if (passwordService.isPasswordTaken(updatePassword.getName(), updatePassword.getUsername(),
                            updatePassword.getId())) {
                        message = "Password title and username already exists";
                    } else {
                        passwordService.updatePassword(updatePassword);
                        isSuccess = true;
                    }
                } else {
                    message = "invalid id or no access";
                }
            } else {
                message = "invalid id or no access";
            }
        } else {
            message = "Invalid authentication";
        }
        loginService.logout();
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
        isSuccess = false;
        message = e.getMessage();
    }
    return createModelAndView(isSuccess, message, "passwordId", passwordId);
}

From source file:com.ewcms.plugin.vote.manager.web.ResultServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    ServletOutputStream out = null;// ww w  . j a va2s . c o  m
    StringBuffer output = new StringBuffer();
    try {
        String id = req.getParameter("id");

        if (!id.equals("") && StringUtils.isNumeric(id)) {
            Long questionnaireId = new Long(id);

            ServletContext application = getServletContext();
            WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(application);
            VoteFacable voteFac = (VoteFacable) wac.getBean("voteFac");

            String ipAddr = req.getRemoteAddr();

            output = voteFac.getQuestionnaireResultClientToHtml(questionnaireId,
                    getServletContext().getContextPath(), ipAddr);
        }
        out = resp.getOutputStream();
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html; charset=UTF-8");
        out.write(output.toString().getBytes("UTF-8"));
        out.flush();
    } finally {
        if (out != null) {
            out.close();
            out = null;
        }
    }
}