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:org.codeconsole.web.analytics.AnalyticsFilter.java

private String getIp(HttpServletRequest request) {
    String ip = request.getHeader("x-forwarded-for");
    if (ip == null)
        return request.getRemoteAddr();
    if (ip.indexOf(',') != -1)
        ip = ip.substring(ip.lastIndexOf(',') + 1).trim();
    return ip;//w ww .j a  va 2 s  .  c om
}

From source file:com.sdl.odata.controller.AbstractODataController.java

@RequestMapping(method = { GET, POST, PATCH, PUT, DELETE })
protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
        throws ServletException, IOException {
    if (LOG.isTraceEnabled()) {
        LOG.trace("Start processing request from: {}", servletRequest.getRemoteAddr());
    }//from   ww w . jav  a2  s.  com

    ODataResponse oDataResponse;
    try {
        ODataRequest oDataRequest = buildODataRequest(servletRequest);
        doWireLogging(oDataRequest);
        oDataResponse = oDataService.handleRequest(oDataRequest);
    } catch (ODataException e) {
        throw new ServletException(e);
    }

    fillServletResponse(oDataResponse, servletResponse);

    if (LOG.isTraceEnabled()) {
        LOG.trace("Finished processing request from: {}", servletRequest.getRemoteAddr());
    }
}

From source file:com.haulmont.restapi.auth.ClientProxyTokenStore.java

/**
 * Tries to find the session associated with the given {@code authentication}. If the session id is in the store and
 * exists then it is set to the {@link SecurityContext}. If the session id is not in the store or the session with
 * the id doesn't exist in the middleware, then the trusted login attempt is performed.
 *//*from  w  w  w .jav  a 2 s. co  m*/
protected void processSession(OAuth2Authentication authentication, String tokenValue) {
    RestUserSessionInfo sessionInfo = serverTokenStore.getSessionInfoByTokenValue(tokenValue);
    UUID sessionId = sessionInfo != null ? sessionInfo.getId() : null;
    if (sessionId == null) {
        @SuppressWarnings("unchecked")
        Map<String, String> userAuthenticationDetails = (Map<String, String>) authentication
                .getUserAuthentication().getDetails();
        //sessionId parameter was put in the CubaUserAuthenticationProvider
        String sessionIdStr = userAuthenticationDetails.get("sessionId");
        if (!Strings.isNullOrEmpty(sessionIdStr)) {
            sessionId = UUID.fromString(sessionIdStr);
        }
    }

    UserSession session = null;
    if (sessionId != null) {
        try {
            session = trustedClientService.findSession(restApiConfig.getTrustedClientPassword(), sessionId);
        } catch (LoginException e) {
            throw new RuntimeException("Unable to login with trusted client password");
        }
    }

    if (session == null) {
        @SuppressWarnings("unchecked")
        Map<String, String> userAuthenticationDetails = (Map<String, String>) authentication
                .getUserAuthentication().getDetails();
        String username = userAuthenticationDetails.get("username");
        try {
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
                    .currentRequestAttributes();
            Locale locale = sessionInfo != null ? sessionInfo.getLocale() : null;
            TrustedClientCredentials credentials = new TrustedClientCredentials(username,
                    restApiConfig.getTrustedClientPassword(), locale);
            credentials.setClientType(ClientType.REST_API);
            if (attributes != null) {
                HttpServletRequest request = attributes.getRequest();
                credentials.setIpAddress(request.getRemoteAddr());
                credentials.setClientInfo(makeClientInfo(request.getHeader(HttpHeaders.USER_AGENT)));
            } else {
                credentials.setClientInfo(makeClientInfo(""));
            }

            //if locale was not determined then use the user locale
            if (locale == null) {
                credentials.setOverrideLocale(false);
            }

            session = authenticationService.login(credentials).getSession();
        } catch (LoginException e) {
            throw new OAuth2Exception("Cannot login to the middleware");
        }
    }

    if (session != null) {
        serverTokenStore.putSessionInfo(tokenValue, new RestUserSessionInfo(session));
        AppContext.setSecurityContext(new SecurityContext(session));
    }
}

From source file:com.lm.lic.manager.controller.AbstractWithdrawLicController.java

/**
 * @param product//w  w  w  .  j  a  v a2  s.  c om
 * @param wlf
 * @param request
 * @return
 */
protected RequestForLicense findExistingLicWithdrawalRecord(Product product, WithdrawLicForm wlf,
        HttpServletRequest request) {
    String requestorIp = request.getRemoteAddr();
    String deviceId = wlf.getDeviceId();
    if (StringUtils.isEmpty(deviceId))
        deviceId = wlf.getPIN();
    RequestForLicense rfl = requestForLicenseService.findByDevIdProdId(deviceId, product.getId(), requestorIp);
    return rfl;
}

From source file:se.vgregion.portal.requestlogger.RequestLoggerController.java

private Map<String, String> getRequestInfo(PortletRequest request) {
    Map<String, String> requestResult = new TreeMap<String, String>();

    HttpServletRequest httpRequest = PortalUtil.getHttpServletRequest(request);

    requestResult.put("RemoteUser", httpRequest.getRemoteUser());
    requestResult.put("P3P.USER_LOGIN_ID", getRemoteUserId(request));
    requestResult.put("RemoteAddr", httpRequest.getRemoteAddr());
    requestResult.put("RemoteHost", httpRequest.getRemoteHost());
    requestResult.put("RemotePort", String.valueOf(httpRequest.getRemotePort()));
    requestResult.put("AuthType", httpRequest.getAuthType());
    requestResult.put("CharacterEncoding", httpRequest.getCharacterEncoding());
    requestResult.put("ContentLength", String.valueOf(httpRequest.getContentLength()));
    requestResult.put("ContentType", httpRequest.getContentType());
    requestResult.put("ContextPath", httpRequest.getContextPath());
    requestResult.put("LocalAddr", httpRequest.getLocalAddr());
    requestResult.put("Locale", httpRequest.getLocale().toString());
    requestResult.put("LocalName", httpRequest.getLocalName());
    requestResult.put("LocalPort", String.valueOf(httpRequest.getLocalPort()));
    requestResult.put("Method", httpRequest.getMethod());
    requestResult.put("PathInfo", httpRequest.getPathInfo());
    requestResult.put("PathTranslated", httpRequest.getPathTranslated());
    requestResult.put("Protocol", httpRequest.getProtocol());
    requestResult.put("QueryString", httpRequest.getQueryString());
    requestResult.put("RequestedSessionId", httpRequest.getRequestedSessionId());
    requestResult.put("RequestURI", httpRequest.getRequestURI());
    requestResult.put("Scheme", httpRequest.getScheme());
    requestResult.put("ServerName", httpRequest.getServerName());
    requestResult.put("ServerPort", String.valueOf(httpRequest.getServerPort()));
    requestResult.put("ServletPath", httpRequest.getServletPath());

    return requestResult;
}

From source file:com.streamsets.pipeline.stage.origin.sdcipctokafka.IpcToKafkaServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String requestor = req.getRemoteAddr() + ":" + req.getRemotePort();
    if (shuttingDown) {
        LOG.debug("Shutting down, discarding incoming request from '{}'", requestor);
        resp.setStatus(HttpServletResponse.SC_GONE);
    } else {/*from www  .  j  ava 2  s .  c o  m*/
        String appId = req.getHeader(Constants.X_SDC_APPLICATION_ID_HEADER);
        String compression = req.getHeader(Constants.X_SDC_COMPRESSION_HEADER);
        String contentType = req.getContentType();
        String json1Fragmentable = req.getHeader(Constants.X_SDC_JSON1_FRAGMENTABLE_HEADER);
        if (!Constants.APPLICATION_BINARY.equals(contentType)) {
            invalidRequestMeter.mark();
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST, Utils.format(
                    "Wrong content-type '{}', expected '{}'", contentType, Constants.APPLICATION_BINARY));
        } else if (!"true".equals(json1Fragmentable)) {
            invalidRequestMeter.mark();
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST, Utils.format(
                    "RPC client is not using a fragmentable JSON1 encoding, client;s SDC must be upgraded"));
        } else if (!configs.appId.equals(appId)) {
            invalidRequestMeter.mark();
            LOG.warn("IPC from '{}' invalid appId '{}', rejected", requestor, appId);
            resp.sendError(HttpServletResponse.SC_FORBIDDEN, "Invalid 'appId'");
        } else {
            long start = System.currentTimeMillis();
            LOG.debug("Request accepted from '{}'", requestor);
            try (InputStream in = req.getInputStream()) {
                InputStream is = in;
                boolean processRequest = true;
                if (compression != null) {
                    switch (compression) {
                    case Constants.SNAPPY_COMPRESSION:
                        is = new SnappyFramedInputStream(is, true);
                        break;
                    default:
                        invalidRequestMeter.mark();
                        LOG.warn("Invalid compression '{}' in request from '{}', returning error", compression,
                                requestor);
                        resp.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE,
                                "Unsupported compression: " + compression);
                        processRequest = false;
                    }
                }
                if (processRequest) {
                    LOG.debug("Processing request from '{}'", requestor);
                    List<byte[]> messages = SdcStreamFragmenter.fragment(is, maxMessageSize, maxRpcRequestSize);
                    LOG.debug("Request from '{}' broken into '{}' messages", requestor, messages.size());
                    long kStart = System.currentTimeMillis();
                    SdcKafkaProducer producer = getKafkaProducer();
                    long kafkaTime = System.currentTimeMillis() - kStart;
                    try {
                        for (byte[] message : messages) {
                            // we are using round robing partition strategy, partition key is ignored
                            kStart = System.currentTimeMillis();
                            producer.enqueueMessage(configs.topic, message, "");
                            kafkaTime += System.currentTimeMillis() - kStart;
                        }
                        kStart = System.currentTimeMillis();
                        producer.write();
                        kafkaTime += System.currentTimeMillis() - kStart;
                        resp.setStatus(HttpServletResponse.SC_OK);
                        requestMeter.mark();
                    } catch (StageException ex) {
                        LOG.warn("Kakfa producer error: {}", ex.toString(), ex);
                        errorQueue.offer(ex);
                        errorRequestMeter.mark();
                        LOG.warn("Error while reading payload from '{}': {}", requestor, ex.toString(), ex);
                        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex.toString());
                    } finally {
                        kStart = System.currentTimeMillis();
                        releaseKafkaProducer(producer);
                        kafkaTime += System.currentTimeMillis() - kStart;
                    }
                    kafkaTimer.update(kafkaTime, TimeUnit.MILLISECONDS);
                    kafkaMessagesMeter.mark(messages.size());
                }
            } catch (Exception ex) {
                errorRequestMeter.mark();
                LOG.warn("Error while reading payload from '{}': {}", requestor, ex.toString(), ex);
                resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex.toString());
            } finally {
                requestTimer.update(System.currentTimeMillis() - start, TimeUnit.MILLISECONDS);
            }
        }
    }
}

From source file:com.streamsets.pipeline.stage.origin.ipctokafka.IpcToKafkaServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String requestor = req.getRemoteAddr() + ":" + req.getRemotePort();
    if (shuttingDown) {
        LOG.debug("Shutting down, discarding incoming request from '{}'", requestor);
        resp.setStatus(HttpServletResponse.SC_GONE);
    } else {/*from w ww.jav  a2s  .  c  om*/
        String appId = req.getHeader(Constants.X_SDC_APPLICATION_ID_HEADER);
        String compression = req.getHeader(Constants.X_SDC_COMPRESSION_HEADER);
        String contentType = req.getContentType();
        String json1Fragmentable = req.getHeader(Constants.X_SDC_JSON1_FRAGMENTABLE_HEADER);
        if (!Constants.APPLICATION_BINARY.equals(contentType)) {
            invalidRequestMeter.mark();
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST, Utils.format(
                    "Wrong content-type '{}', expected '{}'", contentType, Constants.APPLICATION_BINARY));
        } else if (!"true".equals(json1Fragmentable)) {
            invalidRequestMeter.mark();
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST, Utils.format(
                    "RPC client is not using a fragmentable JSON1 encoding, client;s SDC must be upgraded"));
        } else if (!configs.appId.equals(appId)) {
            invalidRequestMeter.mark();
            LOG.warn("IPC from '{}' invalid appId '{}', rejected", requestor, appId);
            resp.sendError(HttpServletResponse.SC_FORBIDDEN, "Invalid 'appId'");
        } else {
            long start = System.currentTimeMillis();
            LOG.debug("Request accepted from '{}'", requestor);
            try (InputStream in = req.getInputStream()) {
                InputStream is = in;
                boolean processRequest = true;
                if (compression != null) {
                    switch (compression) {
                    case Constants.SNAPPY_COMPRESSION:
                        is = new SnappyFramedInputStream(is, true);
                        break;
                    default:
                        invalidRequestMeter.mark();
                        LOG.warn("Invalid compression '{}' in request from '{}', returning error", compression,
                                requestor);
                        resp.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE,
                                "Unsupported compression: " + compression);
                        processRequest = false;
                    }
                }
                if (processRequest) {
                    LOG.debug("Processing request from '{}'", requestor);
                    List<byte[]> messages = SdcStreamFragmenter.fragment(is, maxMessageSize, maxRpcRequestSize);
                    LOG.debug("Request from '{}' broken into '{}' messages", requestor, messages.size());
                    long kStart = System.currentTimeMillis();
                    SdcKafkaProducer producer = getKafkaProducer();
                    long kafkaTime = System.currentTimeMillis() - kStart;
                    try {
                        for (byte[] message : messages) {
                            // we are using round robing partition strategy, partition key is ignored
                            kStart = System.currentTimeMillis();
                            producer.enqueueMessage(kafkaConfigBean.kafkaConfig.topic, message, "");
                            kafkaTime += System.currentTimeMillis() - kStart;
                        }
                        kStart = System.currentTimeMillis();
                        producer.write();
                        kafkaTime += System.currentTimeMillis() - kStart;
                        resp.setStatus(HttpServletResponse.SC_OK);
                        requestMeter.mark();
                    } catch (StageException ex) {
                        LOG.warn("Kakfa producer error: {}", ex.toString(), ex);
                        errorQueue.offer(ex);
                        errorRequestMeter.mark();
                        LOG.warn("Error while reading payload from '{}': {}", requestor, ex.toString(), ex);
                        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex.toString());
                    } finally {
                        kStart = System.currentTimeMillis();
                        releaseKafkaProducer(producer);
                        kafkaTime += System.currentTimeMillis() - kStart;
                    }
                    kafkaTimer.update(kafkaTime, TimeUnit.MILLISECONDS);
                    kafkaMessagesMeter.mark(messages.size());
                }
            } catch (Exception ex) {
                errorRequestMeter.mark();
                LOG.warn("Error while reading payload from '{}': {}", requestor, ex.toString(), ex);
                resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex.toString());
            } finally {
                requestTimer.update(System.currentTimeMillis() - start, TimeUnit.MILLISECONDS);
            }
        }
    }
}

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

@RequestMapping(method = RequestMethod.GET)
public String initForm(HttpServletRequest request, Principal principal, ModelMap model,
        @ModelAttribute DuoPersonObj duoperson, HttpSession session, SessionStatus status) {

    String userId = null;//w  w w.ja  v a 2  s .  com

    String sourceIPAddr = request.getRemoteAddr();
    if (sourceIPAddr == null || sourceIPAddr.startsWith("127.")) {
        sourceIPAddr = request.getHeader("x-forwarded-for");
    }

    //Below getting SSO Attributes for Shibboleth Support(UChicago)
    //      duoperson.setUsername(principal.getName());
    //      duoperson.setFullName(request.getHeader("givenName")+ " " + request.getHeader("sn"));
    //      duoperson.setEmail(request.getHeader("mail"));
    //      duoperson.setChicagoID(request.getHeader("chicagoID"));

    //Below setting Static Attributes for Local Testing
    duoperson.setUsername("DuoTestUser");
    duoperson.setFullName("DUO Testuser");
    duoperson.setEmail("testuser@duotest.com");

    logger.info("2FA Info - " + getIPForLog(request) + " - " + "Username:" + duoperson.getUsername() + "|SID:"
            + request.getSession().getId());

    if (session.getAttribute("duoUserId") == null) {
        userId = duoUsrService.getObjByParam(duoperson.getUsername(), null, "userId");
        if (userId == null) {
            logger.info("2FA Info - " + getIPForLog(request) + " - " + "Username:" + duoperson.getUsername()
                    + " has not yet register with DUO!");
            model.addAttribute("DuoPerson", duoperson); //Initalize Model with some variables and push that into SessionAttribute
            return "DuoPortal"; //return form view
        }
        logger.debug("2FA Debug - " + "Assigned UserID via DUO API Query");
    } else {
        userId = session.getAttribute("duoUserId").toString();
        logger.debug("2FA Debug - " + "Assigned UserID via Session Variable");
    }

    duoperson.setUser_id(userId);
    duoperson.setPhones(duoPhoneService.getAllPhones(userId));
    duoperson.setTablets(duoTabletService.getAllTablets(userId));
    duoperson.setTokens(duoTokenService.getAllTokens(userId));

    //Initalize Model with some variables and push that into SessionAttribute
    model.addAttribute("DuoPerson", duoperson);

    if (duoperson.getPhones().isEmpty() && duoperson.getTablets().isEmpty()
            && duoperson.getTokens().isEmpty()) {
        //return form view
        return "DuoPortal";
    } else {
        //return form view
        return "redirect:/secure/devicemgmt";
    }

}

From source file:com.enonic.cms.core.portal.datasource.handler.context.GetHttpContextHandler.java

private Element createHttpElement(final HttpServletRequest request) {
    final Element httpEl = new Element("http");

    if (request != null) {
        httpEl.setAttribute("action", request.getMethod());
        httpEl.addContent(new Element("user-agent").setText(request.getHeader("user-agent")));
        httpEl.addContent(new Element("client-ip").setText(request.getRemoteAddr()));
        httpEl.addContent(new Element("referer").setText(request.getHeader("referer")));

        // accept
        final Element acceptElem = new Element("accept");
        httpEl.addContent(acceptElem);/*from  w w  w . j a v  a 2 s . c o m*/

        // language
        final String acceptLanguage = request.getHeader("accept-language");
        if (acceptLanguage != null) {
            final String[] languages = StringUtils.split(acceptLanguage, ",");
            for (String languageStr : languages) {
                if (languageStr.indexOf(";") > 0) {
                    final Element langElem = new Element("language");
                    langElem.setText(languageStr.substring(0, languageStr.indexOf(";")));
                    langElem.setAttribute("q", languageStr.substring(languageStr.indexOf(";") + 3));
                    acceptElem.addContent(langElem);
                } else {
                    acceptElem.addContent(new Element("language").setText(languageStr));
                }
            }
        }
    }
    return httpEl;
}

From source file:com.predic8.membrane.servlet.embedded.HttpServletHandler.java

public HttpServletHandler(HttpServletRequest request, HttpServletResponse response, Transport transport)
        throws IOException {
    super(transport);
    this.request = request;
    this.response = response;
    remoteAddr = InetAddress.getByName(request.getRemoteAddr());
    localAddr = InetAddress.getByName(request.getLocalAddr());
    exchange = new Exchange(this);

    exchange.setProperty(Exchange.HTTP_SERVLET_REQUEST, request);
}