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:com.esd.vs.controller.SMSController.java

/**
 * ?IP?/* w w  w .j a v a2 s .c  o  m*/
 * 
 * @param request
 * @return
 */
private String getRemoteAddress(HttpServletRequest request) {
    String ip = request.getHeader("x-forwarded-for");
    if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {
        ip = request.getHeader("Proxy-Client-IP");
    }
    if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {
        ip = request.getHeader("WL-Proxy-Client-IP");
    }
    if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {
        ip = request.getRemoteAddr();
    }
    return ip;
}

From source file:azkaban.webapp.servlet.LoginAbstractAzkabanServlet.java

private Session createSession(HttpServletRequest req) throws UserManagerException, ServletException {
    String username = getParam(req, "username");
    String password = getParam(req, "password");
    String ip = req.getRemoteAddr();

    return createSession(username, password, ip);
}

From source file:edu.lternet.pasta.gatekeeper.GatekeeperFilter.java

private void doDiagnostics(HttpServletRequest req) {

    String remoteAddr = req.getRemoteAddr();
    logger.info("Remote address: " + remoteAddr);

    String requestUri = req.getRequestURI();
    logger.info("Request URI: " + requestUri);

    Boolean noAuthPeek = true;/*from  w  w  w  .  j  av  a 2s. co m*/

    Integer contentLength = dumpHeader(req, noAuthPeek);
    //dumpBody(req, contentLength);

}

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

@GET
@Produces({ MediaType.TEXT_HTML })
@Path("/connections/sort/{sort}/{previous}/{updown}")
public Response checkConnectionsSorted(@Context HttpServletRequest http, @PathParam("sort") String sort,
        @PathParam("previous") String previous, @PathParam("updown") String prevUpdown) {

    Map<String, Object> map = new HashMap<>();
    List<ConnectionData> values = null;

    String updown = "up";
    if (StringUtils.equals(sort, previous) && StringUtils.equals(prevUpdown, "up")) {
        updown = "down";
    }//w  w  w .  j a  v  a  2s  .co  m
    if (connectionService.acceptIPUpdate(http.getRemoteAddr())) {
        Map<String, ConnectionData> connectionDataMap = ConnectionFilter.getConnectionDataMap();
        values = new ArrayList<>(connectionDataMap.values());
        Collections.sort(values, getComparator(sort, updown));
    } else {
        values = new ArrayList<>();
    }
    map.put("coData", values);
    map.put("previous", sort);
    map.put("updown", updown);
    return Response.ok(new Viewable("/allConnections", map)).build();
}

From source file:edu.indiana.d2i.htrc.oauth2.filter.OAuth2Filter.java

/**
 * Extract the access token from servlet request header and validate it via WSO2 IS. If token is invalid or
 * expired filter will throw a error and stop of handing over the request to next filter in chain. If there is no
 * token header filter will reject the request without any checks.
 * @param servletRequest in-coming request object
 * @param servletResponse servlet response object
 * @param filterChain servlet filter chain
 * @throws IOException//w ww  .j a v a2s .c om
 * @throws ServletException
 */
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
        throws IOException, ServletException {
    String errMsg = null;
    String requestId = randomUUID();

    HttpServletRequest req = (HttpServletRequest) servletRequest;
    HttpServletResponse res = (HttpServletResponse) servletResponse;
    OAuth2RequestWrapper modifiedRequest = new OAuth2RequestWrapper(req);

    modifiedRequest.setRequestId(requestId);
    modifiedRequest.setRemoteAddress(req.getRemoteAddr());

    ContextExtractor contextExtractor = new ContextExtractor(req);
    Auditor auditor = AuditorFactory.getAuditor(contextExtractor.getContextMap());

    String accessToken = null;
    OAuth2TokenValidationResponseDTO responseDTO = null;

    try {
        OAuthAccessResourceRequest accessResourceRequest = new OAuthAccessResourceRequest(req,
                TokenType.BEARER);
        accessToken = accessResourceRequest.getAccessToken();

        auditor.log("OAUTH2_FILTER_REQUEST_RECEIVED", requestId, accessToken);

        Enumeration headerNames = req.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = (String) headerNames.nextElement();
            auditor.log(headerName, ":", req.getHeader(headerName));
        }

        responseDTO = validateToken(accessToken);

        List<String> registered_user = new ArrayList<String>();

        registered_user.add(responseDTO.getAuthorizedUser());

        if (responseDTO.getAuthorizedUser() != null) {
            modifiedRequest.setRemoteUser(responseDTO.getAuthorizedUser());
        }

        Map<String, List<String>> contextMap = contextExtractor.getContextMap();
        if (responseDTO.getAuthorizedUser() != null) {
            contextMap.put(KEY_REMOTE_USER, registered_user);
        }

        // We need to create new auditor instance after we create the context map out of servlet request.
        auditor = AuditorFactory.getAuditor(contextMap);

        auditor.log("OAUTH2_FILTER_REQUEST_AUTHENTICATED", requestId, accessToken);
    } catch (OAuthProblemException e) {
        errMsg = "OAuth exception.";
        log.error(errMsg, e);
        auditor.log("OAUTH2_FILTER_UNAUTHENTICATED_REQUEST", requestId, accessToken);
        auditor.error(errMsg, accessToken, e.getError(), e.getMessage());
        respondWithError(res, e);
        return;
    } catch (OAuthSystemException e) {
        errMsg = "OAuth system exception.";
        log.error(errMsg, e);
        auditor.log("OAUTH2_FILTER_UNAUTHENTICATED_REQUEST", requestId, accessToken);
        auditor.error(errMsg, accessToken, e.getMessage());
        throw new ServletException(e);
    } catch (RemoteException re) {
        errMsg = "Error occurred while invoking token validation service.";
        log.error(errMsg, re);
        auditor.log("OAUTH2_FILTER_UNAUTHENTICATED_REQUEST", requestId, accessToken);
        auditor.error(errMsg, accessToken, re.getMessage());
        throw new ServletException(errMsg, re);
    }

    filterChain.doFilter(modifiedRequest, servletResponse);
}

From source file:aiai.ai.launchpad.server.ServerController.java

@PostMapping("/rest-anon/srv")
public ExchangeData processRequestAnon(HttpServletResponse response, @RequestBody ExchangeData data,
        HttpServletRequest request) throws IOException {
    log.debug("processRequestAnon(), globals.isSecureRestUrl: {}, data: {}", globals.isSecureRestUrl, data);
    if (globals.isSecureRestUrl) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return null;
    }/*  w ww. j  a  v a2  s  .  c  om*/
    return serverService.processRequest(data, request.getRemoteAddr());
}

From source file:com.evolveum.midpoint.gui.impl.util.ReportPeerQueryInterceptor.java

private boolean checkRequest(HttpServletRequest request, HttpServletResponse response, String operation) {

    String userAgent = request.getHeader("User-Agent");
    if (!ReportTypeUtil.HEADER_USERAGENT.equals(userAgent)) {
        LOGGER.debug("Invalid user-agent: {}", userAgent);
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        return false;
    }/*from  ww  w .j  a v  a 2s . c  o  m*/

    if (!nodeAuthenticator.authenticate(request.getRemoteHost(), request.getRemoteAddr(), operation)) {
        LOGGER.debug("Unknown node, host: {} ", request.getRemoteHost());
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        return false;
    }

    return true;
}

From source file:com.nkapps.billing.controllers.AuthController.java

@RequestMapping(value = "/nonce", method = RequestMethod.POST)
public @ResponseBody HashMap<String, Object> nonce(HttpServletRequest request, HttpServletResponse response) {
    HashMap<String, Object> resMap = new LinkedHashMap<>();

    String serialNumber = request.getParameter("serialNumber");

    if (serialNumber == null || serialNumber.trim().isEmpty()) {
        resMap.put("success", false);
        resMap.put("reason",
                messageSource.getMessage("auth.serial_number_invalid", null, LocaleContextHolder.getLocale()));

    } else {//www.j a  v  a2s  .  c  o m
        String nonce = authenticationService.getNonce(serialNumber, request.getRemoteAddr());
        resMap.put("success", true);
        resMap.put("nonce", nonce);
    }
    return resMap;
}

From source file:net.yacy.http.ProxyHandler.java

/**
 * adds specific header elements for the connection of the internal
 * httpclient to the remote server according to local config
 *
 * @param header header for http client (already preset with headers from
 * original ServletRequest)//  w w  w  .  j  ava2s  . c  om
 * @param origServletRequest original request/header
 */
private void setProxyHeaderForClient(final HttpServletRequest origServletRequest,
        final HeaderFramework header) {

    header.remove(RequestHeader.KEEP_ALIVE);
    header.remove(HeaderFramework.CONTENT_LENGTH);

    // setting the X-Forwarded-For header
    if (sb.getConfigBool("proxy.sendXForwardedForHeader", true)) {
        String ip = origServletRequest.getRemoteAddr();
        if (!Domains.isThisHostIP(ip)) { // if originator is local host no user ip to forward (= request from localhost)
            header.put(HeaderFramework.X_FORWARDED_FOR, origServletRequest.getRemoteAddr());
        }
    }

    String httpVersion = origServletRequest.getProtocol();
    HTTPDProxyHandler.modifyProxyHeaders(header, httpVersion);
}