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:net.duckling.ddl.web.controller.UserNoticeCountController.java

private boolean validateIp(HttpServletRequest req) {
    String dChatIp = config.getProperty("dchat.ip");
    if (StringUtils.isEmpty(dChatIp)) {
        return false;
    }// w  w  w  . jav a  2  s  . c  o  m
    String[] ips = dChatIp.split(",");
    String id = req.getRemoteAddr();
    if (ipEquals(id, ips)) {
        return true;
    }
    String nginxIp = req.getHeader("x-real-ip");
    if (ipEquals(nginxIp, ips)) {
        return true;
    }

    return false;
}

From source file:csns.security.AuthenticationFailureHandler.java

@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
        AuthenticationException exception) throws IOException, ServletException {
    String username = request.getParameter("j_username");
    if (StringUtils.hasText(username))
        logger.info("Failed login attempt of " + username + " from " + request.getRemoteAddr());

    super.onAuthenticationFailure(request, response, exception);
}

From source file:org.ambraproject.action.article.MediaCoverageAction.java

/**
 * Validate the input from the form//from   ww w.ja  v a 2s  .  c om
 * @return true if everything is ok
 */
private boolean validateInput() {
    // TODO handle data better

    boolean isValid = true;

    if (StringUtils.isBlank(uri)) {
        isValid = false;
    }

    UrlValidator urlValidator = new UrlValidator();

    if (StringUtils.isBlank(link)) {
        addFieldError("link", "This field is required.");
        isValid = false;
    } else if (!urlValidator.isValid(link)) {
        addFieldError("link", "Invalid Media link URL");
        isValid = false;
    }

    if (StringUtils.isBlank(name)) {
        addFieldError("name", "This field is required.");
        isValid = false;
    }

    if (StringUtils.isBlank(email)) {
        addFieldError("email", "This field is required.");
        isValid = false;
    } else if (!EmailValidator.getInstance().isValid(email)) {
        addFieldError("email", "Invalid e-mail address");
        isValid = false;
    }

    HttpServletRequest request = ServletActionContext.getRequest();

    if (!captchaService.validateCaptcha(request.getRemoteAddr(), captchaChallenge, captchaResponse)) {
        addFieldError("captcha", "Verification is incorrect. Please try again.");
        isValid = false;
    }

    if (isValid) {
        this.link = this.link.substring(0, Math.min(this.link.length(), MAX_LENGTH));
        this.name = this.name.substring(0, Math.min(this.name.length(), MAX_LENGTH));
        this.email = this.email.substring(0, Math.min(this.email.length(), MAX_LENGTH));

        if (!StringUtils.isBlank(comment)) {
            this.comment = this.comment.substring(0, Math.min(this.comment.length(), MAX_LENGTH));
        }
    }

    return isValid;
}

From source file:com.all.tracker.controllers.DownloadMetricsController.java

@RequestMapping(method = PUT)
@ResponseBody//from   ww  w  .j  av a  2 s.c o  m
public String receiveMetricsByPut(@RequestBody String metrics, HttpServletRequest request) {
    try {
        saveMetrics(metrics, request.getRemoteAddr());
    } catch (InstantiationException e) {
        log.error(e, e);
    } catch (IllegalAccessException e) {
        log.error(e, e);
    }
    return "ok";
}

From source file:com.streamsets.pipeline.lib.http.HttpReceiverServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String requestor = req.getRemoteAddr() + ":" + req.getRemotePort();
    if (isShuttingDown()) {
        LOG.debug("Shutting down, discarding incoming request from '{}'", requestor);
        resp.setStatus(HttpServletResponse.SC_GONE);
    } else {//from  w  ww  . java 2s  . c o  m
        if (validatePostRequest(req, resp)) {
            long start = System.currentTimeMillis();
            LOG.debug("Request accepted from '{}'", requestor);
            try (InputStream in = req.getInputStream()) {
                InputStream is = in;
                String compression = req.getHeader(HttpConstants.X_SDC_COMPRESSION_HEADER);
                if (compression == null) {
                    compression = req.getHeader(HttpConstants.CONTENT_ENCODING_HEADER);
                }
                if (compression != null) {
                    switch (compression) {
                    case HttpConstants.SNAPPY_COMPRESSION:
                        is = new SnappyFramedInputStream(is, true);
                        break;
                    case HttpConstants.GZIP_COMPRESSION:
                        is = new GZIPInputStream(is);
                        break;
                    default:
                        throw new IOException(
                                Utils.format("It shouldn't happen, unexpected compression '{}'", compression));
                    }
                }
                LOG.debug("Processing request from '{}'", requestor);
                processRequest(req, is, resp);
            } catch (Exception ex) {
                errorQueue.offer(ex);
                errorRequestMeter.mark();
                LOG.warn("Error while processing request payload from '{}': {}", requestor, ex.toString(), ex);
                resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex.toString());
            } finally {
                requestTimer.update(System.currentTimeMillis() - start, TimeUnit.MILLISECONDS);
            }

        } else {
            invalidRequestMeter.mark();
        }
    }
}

From source file:com.starit.diamond.server.controller.ConfigController.java

public String getRemortIP(HttpServletRequest request) {
    if (request.getHeader("x-forwarded-for") == null) {
        return request.getRemoteAddr();
    }//from  ww  w.  ja v a2  s.c  o m
    return request.getHeader("x-forwarded-for");
}

From source file:edu.uchicago.duo.web.DuoDeviceMgmtController.java

/**
 * **********************************************************
 *
 * Private Methods Below/*from w  ww  . j a va  2  s.co m*/
 *
 ***********************************************************
 */
private String getIPForLog(HttpServletRequest request) {
    String sourceIPAddr = request.getRemoteAddr();
    if (sourceIPAddr == null || sourceIPAddr.startsWith("127.")) {
        sourceIPAddr = request.getHeader("x-forwarded-for");
    }

    sourceIPAddr = "[" + sourceIPAddr + "]";

    return sourceIPAddr;
}

From source file:cn.newgxu.lab.info.controller.AuthController.java

/**
 * RESTful APIGETURI// w ww  . j av a 2  s  .c om
 * @param model
 * @param request
 * @param password
 * @param account
 * @return only json, or bad request!
 */
@RequestMapping(value = "/users", method = RequestMethod.GET)
public String login(Model model, HttpServletRequest request, @RequestParam("pwd") String password,
        @RequestParam("account") String account) {
    String ip = request.getRemoteAddr();
    AuthorizedUser au = authService.login(account, password, ip);
    request.getSession().setAttribute(Config.SESSION_USER, au);
    //      ??
    model.addAttribute(ViewConstants.AJAX_STATUS, "ok");
    return ViewConstants.BAD_REQUEST;
}

From source file:cn.com.sgcc.servlet.LicenseServlet.java

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    {//from  w w w.  jav a  2  s .c om
        // context
        AccessControlContext context = new AccessControlContext();
        context.setIp(request.getRemoteAddr());
        //context.setIp("127.0.0.1");

        // get rid
        String[] ridNames = { "RID", "rid", "Rid" };
        String rid = null;
        for (int i = 0; i < ridNames.length; ++i) {
            rid = request.getParameter(ridNames[i]);
            if (null != rid) {
                break;
            }
        }
        if (null == rid) {
            logger.error(new StringBuilder().append(context.getIp()).append(" no rid").toString());
            response.sendError(400, "no rid");
            return;
        }

        // get uid
        String[] uidNames = { "UID", "uid", "Uid" };
        String uid = null;
        for (int i = 0; i < uidNames.length; ++i) {
            uid = request.getParameter(uidNames[i]);
            if (null != uid) {
                break;
            }
        }
        /*   
           if (null == uid)
           {
           response.sendError(ErrorCode.PARAM_NULL_UID);
           return;
           }
           */

        // user
        User user = new User();
        user.setName(uid);

        // resource 
        Resource resource = new Resource();
        resource.setNameHash(rid);

        logger.info(new StringBuilder().append(context.getIp()).append(" ").append(rid)
                .append(" license request").toString());

        // execute access control
        License license = accessControl.execute(user, resource, context);
        if (null == license || null == license.toXmlString()) {
            logger.info(new StringBuilder().append(context.getIp()).append(" ").append(rid)
                    .append(" license deny").toString());
            response.sendError(400, "Bad request: no permission or rid not exists");
            return;
        }

        // response
        response.setContentType("text/xml;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.println(license.toXmlString());
        out.close();

        logger.info(new StringBuilder().append(context.getIp()).append(" ").append(rid)
                .append(" license return").toString());
    }
}

From source file:net.sourceforge.fenixedu.presentationTier.Action.externalServices.SetEmailDA.java

public ActionForward setEmail(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    final String host = HostAccessControl.getRemoteAddress(request);
    final String ip = request.getRemoteAddr();
    final String password = request.getParameter("password");
    final String userUId = request.getParameter("userUId");
    final String email = URLDecoder.decode(request.getParameter("email"), "UTF-8");

    String message = "ko";

    try {//  w ww . j  a v  a 2s. co  m

        SetEmail.run(host, ip, password, userUId, email);
        final User user = User.findByUsername(userUId);
        if (user.getPerson() != null && user.getPerson().getStudent() != null) {
            final Student student = user.getPerson().getStudent();
            for (final Registration registration : student.getRegistrationsSet()) {
                final StudentCandidacy candidacy = registration.getStudentCandidacy();
                if (candidacy != null
                        && (candidacy instanceof DegreeCandidacy || candidacy instanceof IMDCandidacy)
                        && candidacy.getExecutionYear().isCurrent()
                        && !candidacy.getCandidacySituationsSet().isEmpty()) {
                    new PDFGeneratorThread(candidacy.getExternalId(), request.getServerName(),
                            request.getServerPort(), request.getContextPath(), request.getServletPath())
                                    .start();
                }
            }
        }
        message = "ok";
    } catch (NotAuthorizedException ex) {
        message = "Not authorized";
    } catch (UserAlreadyHasEmailException ex) {
        message = "User already has email.";
    } catch (UserDoesNotExistException ex) {
        message = "User does not exist.";
    } catch (Throwable ex) {
        message = ex.getMessage();
        logger.error(ex.getMessage(), ex);
    } finally {
        final ServletOutputStream servletOutputStream = response.getOutputStream();
        response.setContentType("text/html");
        servletOutputStream.print(message);
        servletOutputStream.flush();
        response.flushBuffer();
    }

    return null;
}