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:fr.paris.lutece.plugins.extend.service.extender.history.ResourceExtenderHistoryService.java

/**
 * {@inheritDoc}/*from w w w  . j a va2s.co m*/
 */
@Override
public ResourceExtenderHistory create(String strExtenderType, String strIdExtendableResource,
        String strExtendableResourceType, HttpServletRequest request) {
    ResourceExtenderHistory history = new ResourceExtenderHistory();
    history.setExtenderType(strExtenderType);
    history.setIdExtendableResource(strIdExtendableResource);
    history.setExtendableResourceType(strExtendableResourceType);
    history.setIpAddress(request.getRemoteAddr());

    String strUserGuid = StringUtils.EMPTY;

    if (SecurityService.isAuthenticationEnable()) {
        LuteceUser user = SecurityService.getInstance().getRegisteredUser(request);

        if (user != null) {
            strUserGuid = user.getName();
        }
    }

    history.setUserGuid(strUserGuid);
    create(history);

    return history;
}

From source file:com.benfante.minimark.MinimarkExceptionResolver.java

@Override
public ModelAndView resolveException(HttpServletRequest req, HttpServletResponse res, Object object,
        Exception e) {//from  w  w  w  .  j  a  v a  2 s . c om
    try {
        if (!interceptedWithMinimalLogging(e)) {
            logger.error("Unexpected exception", e);
        }
        logger.info("Exception requesting URL: " + req.getRequestURL().toString());
        logger.info("  request from " + req.getRemoteHost() + "(" + req.getRemoteAddr() + ")");
        return super.resolveException(req, res, object, e);
    } catch (Exception ex) {
        logger.error("Error resolving exception", ex);
    }
    return new ModelAndView("redirect:/home/500page.html");
}

From source file:nl.dtls.fairdatapoint.api.config.ApplicationFilter.java

@Override
public void doFilter(ServletRequest sr, ServletResponse sr1, FilterChain fc)
        throws IOException, ServletException {
    HttpServletResponse response = (HttpServletResponse) sr1;
    HttpServletRequest request = (HttpServletRequest) sr;
    response.setHeader(HttpHeaders.SERVER, "FAIR data point (JAVA)");
    response.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
    response.setHeader(HttpHeaders.ALLOW, (RequestMethod.GET.name()));
    response.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, (HttpHeaders.ACCEPT));
    ThreadContext.put("ipAddress", request.getRemoteAddr());
    ThreadContext.put("responseStatus", String.valueOf(response.getStatus()));
    fc.doFilter(sr, sr1);/* w w  w .j  a v a  2s  .  co m*/
    ThreadContext.clearAll();
}

From source file:com.myjeeva.spring.security.secureuri.SecureServerURI.java

/**
  * {@inheritDoc}// ww  w .j ava 2s.  co m
  * 
  * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
  */
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    HttpServletResponse res = (HttpServletResponse) response;
    HttpServletRequest req = (HttpServletRequest) request;

    String et = req.getParameter("e");
    String h = req.getParameter("h");

    if (null == et || null == h) {
        badRequest(res);
        LOG.warn("et & h attributes are null; Bad request from IP: " + req.getRemoteAddr());
        return;
    }

    String baseUrl = req.getRequestURI();
    String passKey = secureUriMapper.getPassKey(baseUrl);

    String salt = passKey + baseUrl + "?e=" + et;
    String hash = SpringExtensionsUtil.getMD5(salt);
    if (!hash.trim().equals(h)) {
        badRequest(res);
        LOG.warn("Hash Value doesn't match; Bad request from IP: " + req.getRemoteAddr());
        return;
    }

    long expiryTime = Long.parseLong(et);
    if (expiryTime > 0 && !(new Date().getTime() <= expiryTime)) {
        badRequest(res);
        LOG.warn("Secure Link expried, link accessed from IP: " + req.getRemoteAddr());
        return;
    }

    /** making chain call for following filters*/
    chain.doFilter(request, response);
}

From source file:io.mapzone.controller.vm.http.HttpRequestForwarder.java

protected void setXForwardedForHeader(HttpServletRequest servletRequest) {
    String headerName = "X-Forwarded-For";
    if (doForwardIP.get()) {
        String newHeader = servletRequest.getRemoteAddr();
        String existingHeader = servletRequest.getHeader(headerName);
        if (existingHeader != null) {
            newHeader = existingHeader + ", " + newHeader;
        }//from  w w w .ja v  a 2  s.  c o m
        proxyRequest.setHeader(headerName, newHeader);
    }
}

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

/**
 * ??:[0]-IP?,[1]-??,[2]-User Agent,[3]-mac
 * //from  w w w .  ja  va  2s  .  c  o m
 * @param request
 * @return
 */
public static String[] getClient(HttpServletRequest request) {
    String[] client = new String[] { null, null, null, null };

    // User Agent?
    client[2] = request.getHeader("User-Agent");

    // ?????X-Forwarded-For?Ip,?unknownIPIP
    String key = "X-Forwarded-For";

    String clientIp = request.getHeader(key);
    if (clientIp == null || clientIp.length() == 0 || "unknown".equalsIgnoreCase(clientIp)) {
        key = "Proxy-Client-IP";
        clientIp = request.getHeader(key);
    }
    if (clientIp == null || clientIp.length() == 0 || "unknown".equalsIgnoreCase(clientIp)) {
        key = "WL-Proxy-Client-IP"; // Weblogic?IP
        clientIp = request.getHeader(key);
    }
    if (clientIp == null || clientIp.length() == 0 || "unknown".equalsIgnoreCase(clientIp)) {
        key = "RemoteAddr";
        clientIp = request.getRemoteAddr();// ??ip?
    }
    client[0] = clientIp;
    if (trace) {// name+ip??+mac
        logger.info("start traceClientMachine...:clientIp=" + clientIp);
        if ("127.0.0.1".equals(clientIp) || "localhost".equals(clientIp)) {
            // ?()
            client[1] = clientIp + "|" + key;
            logger.info("skip traceClientMachine because local machine");
        } else {
            client[1] = request.getRemoteHost();// ???ip????(?)
            try {
                // ?mac?
                client[3] = WebUtils.getMac(clientIp);
                client[1] = key + "|" + client[3];
            } catch (Exception e) {
                logger.info(e.getMessage(), e);
                client[1] = "notrace:" + key;
                client[3] = "notrace:";
            }
        }
        logger.info("finished traceClientMachine");
    } else {
        client[1] = clientIp + "|" + key;
        client[3] = "notrace:";
    }
    return client;
}

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

@RequestMapping(value = "/reports", method = RequestMethod.GET)
public void getReport(HttpServletRequest request, HttpServletResponse response,
        @RequestHeader(Constants.REST_AUTHN_USERNAME) String authnUsername,
        @RequestHeader(Constants.REST_AUTHN_PASSWORD) String authnPassword,
        @RequestHeader(Constants.REST_AUTHN_TOTP) String authnTOTP) {
    try {/*  ww w  . j  a  va 2  s . c  om*/
        ServerSessionUtil.setIP(request.getRemoteAddr());
        AuthenticationStatus authStatus = loginService.login(authnUsername,
                Utils.buildCredentials(authnPassword, authnTOTP));
        if (AuthenticationStatus.SUCCESS == authStatus) {
            JasperReportServlet servlet = new JasperReportServlet();
            servlet.doPost(request, response);
        } else {
        }
        loginService.logout();
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
    }

}

From source file:de.hybris.platform.security.captcha.ReCaptchaAspect.java

protected boolean checkAnswer(final HttpServletRequest request, final String challengeFieldValue,
        final String responseFieldValue) {
    final ReCaptchaImpl reCaptcha = new ReCaptchaImpl();
    reCaptcha.setPrivateKey(getSiteConfigService().getProperty(RECAPTCHA_PRIVATE_KEY_PROPERTY));
    final ReCaptchaResponse reCaptchaResponse = reCaptcha.checkAnswer(request.getRemoteAddr(),
            challengeFieldValue, responseFieldValue);
    return reCaptchaResponse.isValid();
}

From source file:ee.ria.xroad.proxy.serverproxy.ServerProxyHandler.java

@Override
public void handle(String target, Request baseRequest, final HttpServletRequest request,
        final HttpServletResponse response) throws IOException, ServletException {
    OpMonitoringData opMonitoringData = new OpMonitoringData(PRODUCER, getEpochMillisecond());

    long start = PerformanceLogger.log(log, "Received request from " + request.getRemoteAddr());

    if (!SystemProperties.isServerProxySupportClientsPooledConnections()) {
        // if the header is added, the connections are closed and cannot be reused on the client side
        response.addHeader("Connection", "close");
    }/*  w  ww  .  j  a va2  s.  c  o  m*/

    try {
        if (!request.getMethod().equalsIgnoreCase("POST")) {
            throw new CodedException(X_INVALID_HTTP_METHOD, "Must use POST request method instead of %s",
                    request.getMethod());
        }

        GlobalConf.verifyValidity();

        logProxyVersion(request);

        ServerMessageProcessor processor = createRequestProcessor(request, response, start, opMonitoringData);
        processor.process();
    } catch (Throwable e) { // We want to catch serious errors as well
        CodedException cex = translateWithPrefix(SERVER_SERVERPROXY_X, e);

        log.error("Request processing error ({})", cex.getFaultDetail(), e);

        opMonitoringData.setSoapFault(cex);

        failure(response, cex);
    } finally {
        baseRequest.setHandled(true);

        opMonitoringData.setResponseOutTs(getEpochMillisecond());
        OpMonitoring.store(opMonitoringData);

        PerformanceLogger.log(log, start, "Request handled");
    }
}

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

/**
 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
 */// ww  w .  jav  a  2s . c  o  m
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest httpReq = (HttpServletRequest) request;
    HttpServletResponse httpRes = (HttpServletResponse) response;
    String reqInfo = "J-WebShield Alert: Session check failed! request URL="
            + httpReq.getRequestURL().toString() + "| from IP address=" + httpReq.getRemoteAddr();

    logger.debug("doFilter: RequestURL=" + httpReq.getRequestURL().toString());

    UrlExclusionList exclList = (UrlExclusionList) request.getServletContext()
            .getAttribute(SecurityConstant.SESSION_CHECK_URL_EXCL_LIST_ATTR_NAME);

    try {
        if (!exclList.isEmpty() && exclList.isMatch(httpReq.getRequestURI())) {
            logger.info("doFilter: request (" + httpReq.getRequestURL().toString()
                    + " matches exclusion pattern, skipping session check");
            chain.doFilter(request, response);
            return;
        }
    } catch (Exception e) {
        logger.error("doFilter", e);
    }

    HttpSession session = httpReq.getSession(false);
    logger.debug("doFilter: session=" + session);
    logger.debug("doFilter: session attr. " + attributeToCheck + "="
            + (session != null ? session.getAttribute(attributeToCheck) : ""));

    if (session == null || session.getAttribute(attributeToCheck) == null) {
        if (send401) {
            // TODO this is not working for regular requests, only for WS
            // calls
            httpRes.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        } else {
            logger.info(reqInfo + " redirecting to " + redirectPage);

            RequestDispatcher rd = httpReq.getRequestDispatcher(redirectPage);
            if (rd != null) {
                rd.forward(request, response);
            }
            return;
        }

    }

    logger.info("doFilter: session check complete");

    // pass the request along the filter chain
    chain.doFilter(request, response);
}