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.ebay.pulsar.analytics.resources.PulsarQueryResource.java

@POST
@Path("sql/{dataSourceName}")
@Consumes(MediaType.APPLICATION_JSON)// ww  w . j a  v a 2s .  com
@Produces(MediaType.APPLICATION_JSON)
public Response sql(@Context HttpServletRequest request, @PathParam("dataSourceName") String dataSourceName,
        SQLRequest req) {
    if (logger.isDebugEnabled()) {
        logger.debug("SQL API called from IP: " + request.getRemoteAddr());
    }
    req.setNamespace(RequestNameSpace.sql);
    boolean trace = request.getParameter("debug") == null ? false : true;
    return processSqlRequest(req, dataSourceName, trace);
}

From source file:com.portfolio.security.LTIv2Servlet.java

@SuppressWarnings("unused")
protected void doRequest(HttpServletRequest request, HttpServletResponse response, HttpSession session,
        ServletContext application, String toolProxyPath, StringBuffer outTrace)
        throws ServletException, IOException {

    outTraceFormattedMessage(outTrace, "getServiceURL=" + getServiceURL(request));

    String ipAddress = request.getRemoteAddr();
    outTraceFormattedMessage(outTrace, "LTI Service request from IP=" + ipAddress);

    String rpi = request.getPathInfo();
    String uri = request.getRequestURI();
    String[] parts = uri.split("/");
    if (parts.length < 4) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        doErrorJSON(request, response, null, "Incorrect url format", null);
        return;/*from w  w  w  .  j  av  a 2  s. c  om*/
    }

    Map<String, Object> payload = LTIServletUtils.processRequest(request, outTrace);
    String url = getServiceURL(request);

    String controller = parts[3];
    if ("register".equals(controller)) {
        payload.put("base_url", url);
        payload.put("launch_url", url + "register");
        doRegister(response, payload, application, toolProxyPath, outTrace);
        return;
    } else if ("launch".equals(controller)) {
        doLaunch(request, response, session, payload, application, outTrace);
        return;
    }

    // Check if json request if valid
    IMSJSONRequest jsonRequest = new IMSJSONRequest(request);
    if (jsonRequest.valid) {
        outTraceFormattedMessage(outTrace, jsonRequest.getPostBody());
    }

    response.setStatus(HttpServletResponse.SC_NOT_IMPLEMENTED);
    M_log.warn("Unknown request=" + uri);
    doErrorJSON(request, response, null, "Unknown request=" + uri, null);
}

From source file:gallery.web.controller.pages.types.WallpaperRateType.java

@Override
public UrlBean execute(HttpServletRequest request, javax.servlet.http.HttpServletResponse response)
        throws Exception {
    /** bind command */
    WallpaperRating command = new WallpaperRating();
    ServletRequestDataBinder binder = new ServletRequestDataBinder(command);
    binder.setRequiredFields(REQUIRED_FIELDS);

    binder.bind(request);// w  ww . j ava2  s.  c o  m
    BindingResult res = binder.getBindingResult();

    int error = '1';
    if (res.hasErrors()) {
        common.CommonAttributes.addErrorMessage("form_errors", request);
    } else {
        //correcting rating
        gallery.web.support.wallpaper.rating.Utils.correctRate(command);

        command.setIp(request.getRemoteAddr());
        if (wallpaperService.getRowCount("id", command.getId_photo()) == 1) {
            Object[] values = new Object[] { command.getId_photo(), command.getIp() };
            if (wallpaperRatingService.getRowCount(RATE_WALLPAPER_WHERE, values) > 0) {
                common.CommonAttributes.addErrorMessage("duplicate_ip", request);
            } else {
                wallpaperRatingService.save(command);
                common.CommonAttributes.addHelpMessage("operation_succeed", request);
                error = '0';
            }
        } else {
            common.CommonAttributes.addErrorMessage("not_exists.wallpaper", request);
        }
    }
    OutputStream os = response.getOutputStream();
    os.write(error);
    os.flush();

    return null;
}

From source file:org.apache.archiva.redback.rest.services.interceptors.AuthenticationInterceptor.java

public void filter(ContainerRequestContext containerRequestContext) {

    Message message = JAXRSUtils.getCurrentMessage();

    RedbackAuthorization redbackAuthorization = getRedbackAuthorization(message);
    if (redbackAuthorization == null) {
        log.warn("http path {} doesn't contain any informations regarding permissions ",
                message.get(Message.REQUEST_URI));
        // here we failed to authenticate so 403 as there is no detail on karma for this
        // it must be marked as it's exposed
        containerRequestContext.abortWith(Response.status(Response.Status.FORBIDDEN).build());
        return;//w  w  w.  ja v  a2 s  .  c o m
    }
    HttpServletRequest request = getHttpServletRequest(message);
    HttpServletResponse response = getHttpServletResponse(message);

    if (redbackAuthorization.noRestriction()) {
        // maybe session exists so put it in threadLocal
        // some services need the current user if logged
        SecuritySession securitySession = httpAuthenticator.getSecuritySession(request.getSession(true));

        if (securitySession != null) {
            RedbackRequestInformation redbackRequestInformation = new RedbackRequestInformation(
                    securitySession.getUser(), request.getRemoteAddr());
            RedbackAuthenticationThreadLocal.set(redbackRequestInformation);
        } else {
            // maybe there is some authz in the request so try it but not fail so catch Exception !
            try {
                AuthenticationResult authenticationResult = httpAuthenticator.getAuthenticationResult(request,
                        response);

                if ((authenticationResult == null) || (!authenticationResult.isAuthenticated())) {
                    return;
                }

                User user = authenticationResult.getUser() == null
                        ? userManager.findUser(authenticationResult.getPrincipal())
                        : authenticationResult.getUser();
                RedbackRequestInformation redbackRequestInformation = new RedbackRequestInformation(user,
                        request.getRemoteAddr());

                RedbackAuthenticationThreadLocal.set(redbackRequestInformation);
                message.put(AuthenticationResult.class, authenticationResult);
            } catch (Exception e) {
                // ignore here
            }
        }
        return;
    }

    try {
        AuthenticationResult authenticationResult = httpAuthenticator.getAuthenticationResult(request,
                response);

        if ((authenticationResult == null) || (!authenticationResult.isAuthenticated())) {
            throw new HttpAuthenticationException("You are not authenticated.");
        }

        User user = authenticationResult.getUser() == null
                ? userManager.findUser(authenticationResult.getPrincipal())
                : authenticationResult.getUser();

        RedbackRequestInformation redbackRequestInformation = new RedbackRequestInformation(user,
                request.getRemoteAddr());

        RedbackAuthenticationThreadLocal.set(redbackRequestInformation);
        message.put(AuthenticationResult.class, authenticationResult);

        return;
    } catch (UserNotFoundException e) {
        log.debug("UserNotFoundException for path {}", message.get(Message.REQUEST_URI));
    } catch (AccountLockedException e) {
        log.debug("account locked for path {}", message.get(Message.REQUEST_URI));
    } catch (MustChangePasswordException e) {
        log.debug("must change password for path {}", message.get(Message.REQUEST_URI));
    } catch (AuthenticationException e) {
        log.debug("failed to authenticate for path {}", message.get(Message.REQUEST_URI));
    } catch (UserManagerException e) {
        log.debug("UserManagerException: {} for path", e.getMessage(), message.get(Message.REQUEST_URI));
    }
    containerRequestContext.abortWith(Response.status(Response.Status.FORBIDDEN).build());
}

From source file:fr.hoteia.qalingo.web.handler.security.ExtSimpleUrlAuthenticationSuccessHandler.java

@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
        Authentication authentication) throws IOException, ServletException {

    // Find the current customer
    Customer customer = customerService.getCustomerByLoginOrEmail(authentication.getName());

    // Persit only the new CustomerConnectionLog
    CustomerConnectionLog customerConnectionLog = new CustomerConnectionLog();
    customerConnectionLog.setCustomerId(customer.getId());
    customerConnectionLog.setLoginDate(new Date());
    customerConnectionLog.setApp(Constants.APP_NAME_FO_MCOMMERCE_CODE);
    customerConnectionLog.setHost(request.getRemoteHost());
    customerConnectionLog.setAddress(request.getRemoteAddr());
    customerConnectionLogService.saveOrUpdateCustomerConnectionLog(customerConnectionLog);

    try {/*  w  w  w .j a va 2  s  . com*/
        // Update the Customer in Session
        customer.getConnectionLogs().add(customerConnectionLog);
        requestUtil.updateCurrentCustomer(request, customer);
        setUseReferer(false);
        String url = requestUtil.getCurrentRequestUrlNotSecurity(request);

        // SANITY CHECK
        if (StringUtils.isEmpty(url)) {
            url = urlService.generateUrl(FoUrls.HOME, requestUtil.getRequestData(request));
        } else {
            String cartDetails = "cart-details.html";
            if (url.contains(cartDetails)) {
                url = urlService.generateUrl(FoUrls.CART_DELIVERY, requestUtil.getRequestData(request));
            }
        }

        setDefaultTargetUrl(url);
        redirectStrategy.sendRedirect(request, response, url);

    } catch (Exception e) {
        LOG.error("", e);
    }

}

From source file:ch.ralscha.extdirectspring.provider.RemoteProviderSimple.java

@ExtDirectMethod
public Map<String, Object> method14(@DateTimeFormat(iso = ISO.DATE_TIME) Date endDate,
        final String normalParameter, HttpServletRequest request,
        @DateTimeFormat(iso = ISO.DATE) LocalDate aDate,
        @NumberFormat(style = NumberFormat.Style.PERCENT) BigDecimal percent) {

    Map<String, Object> result = new HashMap<String, Object>();
    result.put("endDate", endDate);
    result.put("jodaLocalDate", aDate);
    result.put("percent", percent);
    result.put("normalParameter", normalParameter);
    result.put("remoteAddr", request.getRemoteAddr());
    return result;
}

From source file:net.navasoft.madcoin.backend.services.controller.WorkRequestController.java

/**
 * Register order./* w w w  . j  a v  a  2  s.c o m*/
 * 
 * @param request
 *            the request
 * @param registerOrder
 *            the register order
 * @param fromSystem
 *            the from system
 * @param fromToken
 *            the from token
 * @param userAgent
 *            the user agent
 * @param category
 *            the category
 * @param subCategory
 *            the sub category
 * @return the success response vo
 * @since 25/08/2014, 11:01:03 PM
 */
@RequestMapping(value = "/{category}-{subCategory}/bookRequest", method = RequestMethod.PUT, headers = {
        "Content-Type=application/json", "Accept=application/json" })
@ResponseBody
public SuccessResponseVO registerOrder(HttpServletRequest request,
        @RequestBody(required = true) AskServiceSuccessRequestVO registerOrder,
        @RequestHeader("X-Origin-OS") String fromSystem, @RequestHeader("X-Origin-Token") String fromToken,
        @RequestHeader("User-Agent") String userAgent, @PathVariable String category,
        @PathVariable String subCategory) {
    String loadBalanceIP = request.getHeader("X-Forwarded-For");
    String ipAddress = request.getRemoteAddr();
    if (ipAddress.equals("127.0.0.1") || ipAddress.equals("localhost")) {
        registerOrder.setIpAddress(ipAddress);
    } else {
        registerOrder.setIpAddress(loadBalanceIP);
    }
    registerOrder.setGadget(userAgent);
    registerOrder.setOs(fromSystem);
    registerOrder.setSerial(fromToken);
    registerOrder.setVersion(userAgent);
    registerOrder.setCategory(category);
    registerOrder.setSubCategory(subCategory);
    return service.bookRequest(buildWrapper(registerOrder));
}

From source file:net.navasoft.madcoin.backend.services.controller.WorkRequestController.java

/**
 * Attend order.//from  w ww  .  j av  a  2  s.co  m
 * 
 * @param request
 *            the request
 * @param acceptedOrder
 *            the accepted order
 * @param fromSystem
 *            the from system
 * @param fromToken
 *            the from token
 * @param userAgent
 *            the user agent
 * @param category
 *            the category
 * @param subCategory
 *            the sub category
 * @return the success response vo
 * @since 8/09/2014, 03:16:01 AM
 */
@RequestMapping(value = "/{category}-{subCategory}/completeRequest", method = RequestMethod.POST, headers = {
        "Content-Type=application/json", "Accept=application/json" })
@ResponseBody
public SuccessResponseVO attendOrder(HttpServletRequest request,
        @RequestBody(required = true) AcceptServiceSuccessRequestVO acceptedOrder,
        @RequestHeader("X-Origin-OS") String fromSystem, @RequestHeader("X-Origin-Token") String fromToken,
        @RequestHeader("User-Agent") String userAgent, @PathVariable String category,
        @PathVariable String subCategory) {
    String loadBalanceIP = request.getHeader("X-Forwarded-For");
    String ipAddress = request.getRemoteAddr();
    if (ipAddress.equals("127.0.0.1") || ipAddress.equals("localhost")) {
        acceptedOrder.setIpAddress(ipAddress);
    } else {
        acceptedOrder.setIpAddress(loadBalanceIP);
    }
    acceptedOrder.setGadget(userAgent);
    acceptedOrder.setOs(fromSystem);
    acceptedOrder.setSerial(fromToken);
    acceptedOrder.setVersion(userAgent);
    acceptedOrder.setCategory(category);
    acceptedOrder.setSubCategory(subCategory);
    return service.acceptRequest(buildWrapper(acceptedOrder));
}

From source file:bbdn.lti2.LTI2Servlet.java

@SuppressWarnings("unused")
protected void doRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    System.out.println("getServiceURL=" + getServiceURL(request));

    String ipAddress = request.getRemoteAddr();
    System.out.println("LTI Service request from IP=" + ipAddress);

    String rpi = request.getPathInfo();
    String uri = request.getRequestURI();
    String[] parts = uri.split("/");
    if (parts.length < 5) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        doErrorJSON(request, response, null, "Incorrect url format", null);
        return;/*from  ww w  . j  ava  2  s .  co m*/
    }
    String controller = parts[4];
    if ("register".equals(controller)) {
        doRegister(request, response);
        return;
    } else if ("launch".equals(controller)) {
        doLaunch(request, response);
        return;
    } else if (SVC_tc_profile.equals(controller) && parts.length == 6) {
        String profile_id = parts[5];
        getToolConsumerProfile(request, response, profile_id);
        return;
    } else if (SVC_tc_registration.equals(controller) && parts.length == 6) {
        String profile_id = parts[5];
        registerToolProviderProfile(request, response, profile_id);
        return;
    } else if (SVC_Result.equals(controller) && parts.length == 6) {
        String sourcedid = parts[5];
        handleResultRequest(request, response, sourcedid);
        return;
    } else if (SVC_Settings.equals(controller) && parts.length >= 7) {
        handleSettingsRequest(request, response, parts);
        return;
    }

    IMSJSONRequest jsonRequest = new IMSJSONRequest(request);
    if (jsonRequest.valid) {
        System.out.println(jsonRequest.getPostBody());
    }

    response.setStatus(HttpServletResponse.SC_NOT_IMPLEMENTED);
    M_log.warn("Unknown request=" + uri);
    doErrorJSON(request, response, null, "Unknown request=" + uri, null);
}

From source file:com.janrain.servlet.ProcessTimeLoggingFilter.java

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

    HttpServletRequest servletRequest = (HttpServletRequest) request;
    if (servletRequest.getRequestURL().indexOf("http://localhost") != 0) {

        long start = System.currentTimeMillis();
        chain.doFilter(request, response);
        long stop = System.currentTimeMillis();

        StringBuilder output = new StringBuilder();
        output.append("Time [ ").append(stop - start).append(" ms ]");
        output.append(" Request [").append(servletRequest.getRequestURL());
        if (servletRequest.getQueryString() != null) {
            output.append("?").append(servletRequest.getQueryString());
        }// www. j a  v a 2s .  c  om
        output.append("]");
        output.append(" Remote Addr [ ").append(servletRequest.getRemoteAddr()).append(" ] ");

        String referer = servletRequest.getHeader("referer");
        if (StringUtils.isNotBlank(referer)) {
            output.append(" Referer [ ").append(referer).append(" ] ");
        }

        String userAgent = servletRequest.getHeader("user-agent");
        if (StringUtils.isNotBlank(userAgent)) {
            output.append(" [ ").append(userAgent).append(" ] ");
        }

        logger.debug(output);
    } else {
        chain.doFilter(request, response);
    }

}