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.sourceforge.subsonic.backend.controller.RedirectionController.java

private String getRedirectTo(HttpServletRequest request, Redirection redirection) {

    // If the request comes from within the same LAN as the destination Subsonic
    // server, redirect using the local IP address of the server.

    String localRedirectTo = redirection.getLocalRedirectTo();
    if (localRedirectTo != null) {
        try {//from w w w  . j  a v a  2 s. c  o  m
            URL url = new URL(redirection.getRedirectTo());
            if (url.getHost().equals(request.getRemoteAddr())) {
                return localRedirectTo;
            }
        } catch (Throwable x) {
            LOG.error("Malformed local redirect URL.", x);
        }
    }

    return redirection.getRedirectTo();
}

From source file:au.org.ala.biocache.web.DownloadController.java

/**
 * Add a download to the offline queue/*from  w w  w . ja  v a 2s.c  om*/
 * @param requestParams
 * @param ip
 * @param apiKey
 * @param type
 * @param response
 * @param request
 * @return
 * @throws Exception
 */
@RequestMapping(value = "occurrences/offline/{type}/download*", method = RequestMethod.GET)
public String occurrenceDownload(DownloadRequestParams requestParams,
        @RequestParam(value = "ip", required = false) String ip,
        @RequestParam(value = "apiKey", required = false) String apiKey, @PathVariable("type") String type,
        HttpServletResponse response, HttpServletRequest request) throws Exception {

    boolean sensitive = false;
    if (apiKey != null) {
        if (shouldPerformOperation(apiKey, response, false)) {
            sensitive = true;
        }
    } else if (StringUtils.isEmpty(requestParams.getEmail())) {
        response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED,
                "Unable to perform an offline download without an email address");
    }

    ip = ip == null ? request.getRemoteAddr() : ip;
    DownloadType downloadType = "index".equals(type.toLowerCase()) ? DownloadType.RECORDS_INDEX
            : DownloadType.RECORDS_DB;
    //create a new task
    DownloadDetailsDTO dd = new DownloadDetailsDTO(requestParams, ip, downloadType);
    dd.setIncludeSensitive(sensitive);

    persistentQueueDAO.addDownloadToQueue(dd);
    return null;
}

From source file:com.google.sampling.experiential.server.PubExperimentServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    resp.setContentType("application/json;charset=UTF-8");
    DateTimeZone timezone = TimeUtil.getTimeZoneForClient(req);
    logPacoClientVersion(req);//from  ww  w.  j a v  a2 s  . c  om

    User user = AuthUtil.getWhoFromLogin();
    String email = null;
    if (user != null) {
        email = AuthUtil.getEmailOfUser(req, user);
    } else {
        email = req.getRemoteAddr();
    }

    processJsonUpload(req, resp, email);
}

From source file:com.versatus.jwebshield.filter.SecurityFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    // Assume its HTTP
    HttpServletRequest httpReq = (HttpServletRequest) request;

    String reqInfo = "J-WebShield Alert: CSRF attack detected! request URL="
            + httpReq.getRequestURL().toString() + "| from IP address=" + httpReq.getRemoteAddr();

    logger.debug("doFilter: IP address=" + httpReq.getRemoteAddr());
    logger.debug("doFilter: pathInfo=" + httpReq.getPathInfo());
    logger.debug("doFilter: queryString=" + httpReq.getQueryString());
    logger.debug("doFilter: requestURL=" + httpReq.getRequestURL().toString());
    logger.debug("doFilter: method=" + httpReq.getMethod());
    logger.debug("doFilter: Origin=" + httpReq.getHeader("Origin"));
    logger.info("doFilter: Referer=" + httpReq.getHeader("Referer"));
    logger.info("doFilter: " + csrfHeaderName + "=" + httpReq.getHeader(csrfHeaderName));

    UrlExclusionList exclList = (UrlExclusionList) request.getServletContext()
            .getAttribute(SecurityConstant.CSRF_CHECK_URL_EXCL_LIST_ATTR_NAME);
    HttpSession session = httpReq.getSession(false);
    if (session == null) {
        chain.doFilter(request, response);
        return;/* w  ww. j  a  va  2s.  com*/
    }

    logger.debug("doFilter: matching " + httpReq.getRequestURI() + " to exclusions list "
            + exclList.getExclusionMap());

    try {
        if (!exclList.isEmpty() && exclList.isMatch(httpReq.getRequestURI())) {
            chain.doFilter(request, response);
            return;
        }
    } catch (Exception e) {
        logger.error("doFilter", e);
    }
    // check CSRF cookie/header
    boolean csrfHeaderPassed = false;
    String rawCsrfHeaderVal = httpReq.getHeader(csrfHeaderName);
    if (useCsrfToken && StringUtils.isNotBlank(rawCsrfHeaderVal)) {
        String csrfHeader = StringUtils.strip(httpReq.getHeader(csrfHeaderName), "\"");
        logger.debug("doFilter: csrfHeader after decoding" + csrfHeader);
        Cookie[] cookies = httpReq.getCookies();
        for (Cookie c : cookies) {
            String name = c.getName();

            if (StringUtils.isNotBlank(csrfCookieName) && csrfCookieName.equals(name)) {

                logger.debug("doFilter: cookie domain=" + c.getDomain() + "|name=" + name + "|value="
                        + c.getValue() + "|path=" + c.getPath() + "|maxage=" + c.getMaxAge() + "|httpOnly="
                        + c.isHttpOnly());

                logger.debug("doFilter: string comp:" + StringUtils.difference(csrfHeader, c.getValue()));

                if (StringUtils.isNotBlank(csrfHeader) && csrfHeader.equals(c.getValue())) {

                    csrfHeaderPassed = true;
                    logger.info("Header " + csrfHeaderName + " value matches the cookie " + csrfCookieName);
                    break;
                } else {
                    logger.info(
                            "Header " + csrfHeaderName + " value does not match the cookie " + csrfCookieName);
                }
            }

        }
        // String csrfCookieVal = (String) session
        // .getAttribute(SecurityConstant.CSRFCOOKIE_VALUE_PARAM);
        // if (csrfCookieVal != null && csrfCookieVal.equals(csrfHeader)) {
        // // chain.doFilter(request, response);
        // // return;
        // csrfHeaderPassed = true;
        // } else {
        // // logger.info(reqInfo);
        // // sendSecurityReject(response);
        // }
    }

    if (useCsrfToken && csrfHeaderPassed) {
        chain.doFilter(request, response);
        return;
    }

    // Validate that the salt is in the cache
    Cache<SecurityInfo, SecurityInfo> csrfPreventionSaltCache = (Cache<SecurityInfo, SecurityInfo>) httpReq
            .getSession().getAttribute(SecurityConstant.SALT_CACHE_ATTR_NAME);

    if (csrfPreventionSaltCache != null) {
        // Get the salt sent with the request
        String saltName = (String) httpReq.getSession().getAttribute(SecurityConstant.SALT_PARAM_NAME);

        logger.debug("doFilter: csrf saltName=" + saltName);

        if (saltName != null) {

            String salt = httpReq.getParameter(saltName);

            logger.debug("doFilter: csrf salt=" + salt);

            if (salt != null) {

                SecurityInfo si = new SecurityInfo(saltName, salt);

                logger.debug("doFilter: csrf token=" + csrfPreventionSaltCache.getIfPresent(si));

                SecurityInfo cachedSi = csrfPreventionSaltCache.getIfPresent(si);
                if (cachedSi != null) {
                    // csrfPreventionSaltCache.invalidate(si);
                    if (SecurityTokenFilter.checkReferer) {
                        String refHeader = StringUtils.defaultString(httpReq.getHeader("Referer"));
                        logger.debug("doFilter: refHeader=" + refHeader);
                        if (StringUtils.isNotBlank(refHeader)) {
                            try {
                                URL refUrl = new URL(refHeader);
                                refHeader = refUrl.getHost();
                            } catch (MalformedURLException mex) {
                                logger.debug("doFilter: parsing referer header failed", mex);
                            }
                        }
                        if (!cachedSi.getRefererHost().isEmpty()
                                && !refHeader.equalsIgnoreCase(cachedSi.getRefererHost())) {
                            logger.info("Potential CSRF detected - Referer host does not match orignal! "
                                    + refHeader + " != " + cachedSi.getRefererHost());
                            sendSecurityReject(response);
                        }
                    }

                    chain.doFilter(request, response);
                } else {
                    logger.info(reqInfo);
                    sendSecurityReject(response);
                }
            } else if (httpMethodMatch(httpReq.getMethod())) {
                // let flow through
                chain.doFilter(request, response);
            } else {
                logger.info(reqInfo);
                sendSecurityReject(response);
            }
        }
    } else {
        chain.doFilter(request, response);
    }

}

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

@VisibleForTesting
protected boolean validateAppId(HttpServletRequest req, HttpServletResponse res)
        throws ServletException, IOException {
    boolean valid = false;
    String ourAppId = null;//from w w  w. j  a  v  a  2  s.com
    try {
        ourAppId = getReceiver().getAppId().get();
    } catch (StageException e) {
        throw new IOException("Cant resolve credential value", e);
    }
    String requestor = req.getRemoteAddr() + ":" + req.getRemotePort();
    String reqAppId = req.getHeader(HttpConstants.X_SDC_APPLICATION_ID_HEADER);

    if (reqAppId == null && receiver.isAppIdViaQueryParamAllowed()) {
        reqAppId = getQueryParameters(req).get(HttpConstants.SDC_APPLICATION_ID_QUERY_PARAM)[0];
    }

    if (reqAppId == null) {
        LOG.warn("Request from '{}' missing appId, rejected", requestor);
        res.sendError(HttpServletResponse.SC_FORBIDDEN, "Missing 'appId'");
    } else if (!ourAppId.equals(reqAppId)) {
        LOG.warn("Request from '{}' invalid appId '{}', rejected", requestor, reqAppId);
        res.sendError(HttpServletResponse.SC_FORBIDDEN, "Invalid 'appId'");
    } else {
        valid = true;
    }
    return valid;
}

From source file:nz.co.fortytwo.signalk.processor.LoggerProcessor.java

@Override
public void process(Exchange exchange) throws Exception {

    logger.debug("LoggerProcessor starts");
    HttpServletRequest request = exchange.getIn(HttpMessage.class).getRequest();
    logger.debug("Session = " + request.getSession().getId());
    HttpSession session = request.getSession();
    if (logger.isDebugEnabled()) {

        logger.debug("Request = " + exchange.getIn().getHeader(Exchange.HTTP_SERVLET_REQUEST).getClass());
        logger.debug("Session = " + session.getId());
    }//w  w  w  .ja v  a  2  s  .c o m

    if (session.getId() != null) {

        String remoteAddress = request.getRemoteAddr();
        String localAddress = request.getLocalAddr();
        if (Util.sameNetwork(localAddress, remoteAddress)) {
            exchange.getIn().setHeader(SignalKConstants.MSG_TYPE, SignalKConstants.INTERNAL_IP);
        } else {
            exchange.getIn().setHeader(SignalKConstants.MSG_TYPE, SignalKConstants.EXTERNAL_IP);
        }

        if (exchange.getIn().getHeader(Exchange.HTTP_METHOD).equals("GET")) {
            processGet(exchange);
        }
        if (exchange.getIn().getHeader(Exchange.HTTP_METHOD).equals("POST")) {
            processPost(exchange);
        }
    } else {
        exchange.getIn().setHeader("Location", SignalKConstants.SIGNALK_AUTH);
        exchange.getIn().setBody("Authentication Required");
    }
}

From source file:fr.scc.elo.controller.EloController.java

private Map<String, Object> getMatchMap(HttpServletRequest http, Integer taille) {
    Map<String, Object> map = new HashMap<String, Object>();
    map.put("elotypes", EloType.values());
    map.put("taille", taille);
    String allTags = StringUtils.join(
            IntStream.range(1, taille + 1).mapToObj(i -> "#b" + i + ",#r" + i).collect(Collectors.toList()),
            ',');

    map.put("allTags", allTags);
    map.put("modif", connectionService.acceptIPUpdate(http.getRemoteAddr()));
    return map;/*from   ww  w  . ja v a2  s . co  m*/
}

From source file:com.sap.prd.mobile.ios.ota.webapp.OtaHtmlService.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    //TODO: REWORK. PlistService now uses Base64+URLEncoded parameters, and no URL Parameters but slashes!

    try {//w w w  .j ava2  s  .co m

        Map<String, String> params = getParametersAndReferer(request, response, true);

        LOG.info(format("GET request from '%s' with referer '%s', action:qrcode and parameters %s",
                request.getRemoteAddr(), params.get(KEY_REFERER), params));

        final String action = params.get(KEY_ACTION);
        if (StringUtils.equals(action, KEY_QRCODE)) {

            URL htmlServiceUrl = equalsIgnoreCase(params.get(KEY_REMOVE_OUTER_FRAME), "true")
                    ? generateHtmlServiceUrl(getHtmlServiceBaseUrl(request), params)
                    : new URL(params.get(KEY_REFERER));

            LOG.fine("Sending QRCode for " + htmlServiceUrl.toString());
            sendQRCode(request, response, htmlServiceUrl.toString(), getMatrixToImageConfig(request),
                    new Dimension(400, 400));

        } else {

            URL plistUrl = OtaPlistGenerator.generatePlistRequestUrl(getPlistServiceBaseUrl(request), params);
            URL htmlServiceQrcodeUrl = generateHtmlServiceQRCodeUrl(request, params);

            String htmlTemplatePath = getInitParameter(HTML_TEMPLATE_PATH_KEY);
            final boolean DEBUG = equalsIgnoreCase(getInitParameter(Constants.KEY_DEBUG), "true");

            response.setContentType("text/html");
            PrintWriter writer = response.getWriter();
            OtaHtmlGenerator generator = OtaHtmlGenerator.getInstance(htmlTemplatePath, DEBUG);
            LOG.finer("Using HTML Template: " + generator.getTemplateName() + " (configured: "
                    + htmlTemplatePath + ")");
            generator.generate(writer,
                    new Parameters(plistUrl, htmlServiceQrcodeUrl, params, getInitParameters()));
            writer.flush();
        }

    } catch (Exception e) {
        LOG.log(SEVERE, format("Exception while processing GET request from '%s' (%s)", request.getRemoteAddr(),
                getRequestInfosForLog(request)), e);
    }
}

From source file:com.liusoft.dlog4j.UserLoginManager.java

/**
 *  Velocity?//w  w w .j  av  a  2 s  . c o m
 * 
 * @param request
 * @param response
 * @param uuid
 * @param verify_host
 * @return
 * @see com.liusoft.dlog4j.velocity.DLOG_VelocityTool#verify_login_cookie(String,
 *      boolean)
 */
public static SessionUserObject getLoginUser(HttpServletRequest request, HttpServletResponse response,
        boolean verify_host) {
    // sessionsession?
    Cookie uuidCookie = null;
    HttpSession ssn = request.getSession(false);
    if (ssn != null) {
        SessionUserObject user = (SessionUserObject) ssn.getAttribute(SESSION_USER_KEY);
        if (user != null) {
            uuidCookie = getUuidCookie(request);
            //sessioncookie?
            //(?s1s2?)
            if (uuidCookie != null)
                return user;
            ssn.invalidate();
            return null;
        }
    }
    String uuid = null;
    if (uuidCookie == null)
        uuidCookie = getUuidCookie(request);
    if (uuidCookie != null)
        uuid = uuidCookie.getValue();
    if (StringUtils.isEmpty(uuid))
        return null;
    // session?
    try {
        UUID oUUID = new UUID(uuid);
        String new_host = request.getRemoteAddr();
        if (verify_host && !StringUtils.equals(new_host, oUUID.host))
            return null;
        UserBean user = UserDAO.getUserByID(oUUID.uid);
        // ?
        if (user == null || user.getStatus() != UserBean.STATUS_NORMAL
                || user.getPassword().hashCode() != oUUID.pwdCode) {
            RequestUtils.setCookie(request, response, COOKIE_UUID_KEY, "", 0);
            RequestUtils.setCookie(request, response, COOKIE_LASTLOGIN_KEY, "", 0);
            return null;
        }
        int keep_days = user.getKeepDays();
        if (keep_days < 1)
            keep_days = 365;
        return loginUser(request, response, user, keep_days);
    } catch (Exception e) {
        log.error("Exception occur when get current user.", e);
    }

    return null;
}

From source file:com.liusoft.dlog4j.action.TrackBackAction.java

/**
 * /* w ww.jav  a 2  s. c om*/
 */
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest req,
        HttpServletResponse res) throws Exception {
    TrackBackForm tbf = (TrackBackForm) form;
    String msg = validate(tbf);
    if (msg == null) {
        try {
            TrackBackBean tbb = new TrackBackBean();
            tbb.setBlogName(tbf.getBlog_name());
            tbb.setExcerpt(tbf.getExcerpt());
            tbb.setParentId(tbf.getId());
            tbb.setParentType(tbf.getType());
            tbb.setRemoteAddr(req.getRemoteAddr());
            tbb.setTitle(tbf.getTitle());
            tbb.setTrackTime(new Date());
            tbb.setUrl(tbf.getUrl());
            TrackBackDAO.create(tbb);
        } catch (Exception e) {
            getServlet().log("TrackBackAction.execute failed.", e);
            msg = e.getMessage();
        }
    }
    String xml = getResponse(msg != null, msg);
    res.getWriter().print(xml);
    return null;
}