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.javiermoreno.springboot.rest.AuthenticationTokenProcessingFilter.java

@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) req;
    String encryptedToken = request.getHeader("X-Auth-Token");
    if (SecurityContextHolder.getContext().getAuthentication() == null && encryptedToken != null) {
        Token token = new Token(cryptoService, encryptedToken);
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null) {
            ip = request.getRemoteAddr();
        }/*ww  w.j  a  va 2s .c  o  m*/
        if (ip.equals(token.getIp()) == true && token.isExpired() == false) {
            UserDetails userDetails = userDetailsService.loadUserByUsername(token.getUsername());
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                    userDetails.getUsername(), userDetails.getPassword());
            authentication.setDetails(
                    new WebAuthenticationDetailsSource().buildDetails((HttpServletRequest) request));
            SecurityContextHolder.getContext()
                    .setAuthentication(authenticationManager.authenticate(authentication));
        }

    }
    chain.doFilter(req, res);
}

From source file:net.morphbank.mbsvc3.webservices.RestService.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (!isIPAllowed(request.getRemoteAddr())) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN,
                "This IP is not allowed. Current IP used:" + request.getRemoteAddr());
        return;//  ww w .  ja  v a  2s .c o m
    }
    PrintWriter out = response.getWriter();
    MorphbankConfig.SYSTEM_LOGGER.info("starting post from ip:" + request.getRemoteAddr());
    MorphbankConfig.ensureWorkingConnection();
    response.setContentType("text/xml");
    MorphbankConfig.SYSTEM_LOGGER.info("<!-- persistence: " + MorphbankConfig.getPersistenceUnit() + " -->");
    MorphbankConfig.SYSTEM_LOGGER.info("<!-- filepath: " + folderPath + " -->");
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    //      response.setContentType("text/html");

    String parameter = request.getParameter("uploadxml");
    if (parameter != null) {
        ServletContext context = getServletContext();
        InputStream fis = context.getResourceAsStream(parameter);
        processRequest(fis, out, request.getParameter("fileName"));
    } else {
        try {
            // Process the uploaded items
            List<?> /* FileItem */ items = upload.parseRequest(request);
            Iterator<?> iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();

                if (item.isFormField()) {
                    // processFormField(item);
                } else {
                    // processUploadedFile(item);
                    String paramName = item.getFieldName();
                    String fileName = item.getName();
                    InputStream stream = item.getInputStream();
                    MorphbankConfig.SYSTEM_LOGGER.info("Processing file " + fileName);
                    processRequest(stream, out, fileName);
                    MorphbankConfig.SYSTEM_LOGGER.info("Processing complete");
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.datatorrent.stram.security.StramWSFilter.java

@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
        throws IOException, ServletException {
    if (!(req instanceof HttpServletRequest)) {
        throw new ServletException("This filter only works for HTTP/HTTPS");
    }//from  w w  w .j ava  2s  .  c  o m

    HttpServletRequest httpReq = (HttpServletRequest) req;
    HttpServletResponse httpResp = (HttpServletResponse) resp;
    if (LOG.isDebugEnabled()) {
        LOG.debug("Remote address for request is: " + httpReq.getRemoteAddr());
    }
    String requestURI = httpReq.getRequestURI();
    if (LOG.isDebugEnabled()) {
        LOG.debug("Request path " + requestURI);
    }
    boolean authenticate = true;
    String user = null;
    if (getProxyAddresses().contains(httpReq.getRemoteAddr())) {
        if (httpReq.getCookies() != null) {
            for (Cookie c : httpReq.getCookies()) {
                if (WEBAPP_PROXY_USER.equals(c.getName())) {
                    user = c.getValue();
                    break;
                }
            }
        }
        if (requestURI.equals(WebServices.PATH) && (user != null)) {
            String token = createClientToken(user, httpReq.getLocalAddr());
            if (LOG.isDebugEnabled()) {
                LOG.debug("Create token " + token);
            }
            Cookie cookie = new Cookie(CLIENT_COOKIE, token);
            httpResp.addCookie(cookie);
        }
        authenticate = false;
    }
    if (authenticate) {
        Cookie cookie = null;
        if (httpReq.getCookies() != null) {
            for (Cookie c : httpReq.getCookies()) {
                if (c.getName().equals(CLIENT_COOKIE)) {
                    cookie = c;
                    break;
                }
            }
        }
        boolean valid = false;
        if (cookie != null) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Verifying token " + cookie.getValue());
            }
            user = verifyClientToken(cookie.getValue());
            valid = true;
            if (LOG.isDebugEnabled()) {
                LOG.debug("Token valid");
            }
        }
        if (!valid) {
            httpResp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }
    }

    if (user == null) {
        LOG.warn("Could not find " + WEBAPP_PROXY_USER + " cookie, so user will not be set");
        chain.doFilter(req, resp);
    } else {
        final StramWSPrincipal principal = new StramWSPrincipal(user);
        ServletRequest requestWrapper = new StramWSServletRequestWrapper(httpReq, principal);
        chain.doFilter(requestWrapper, resp);
    }
}

From source file:webim.service.WebimModel.java

/**
 * // w w w  .  jav  a 2  s  .c om
 * @param vid
 * @param request
 * @return
 */
public WebimVisitor createVisitor(String vid, HttpServletRequest request) {
    Map<String, String> data = new HashMap<String, String>();
    data.put("name", vid);
    data.put("ipaddr", request.getRemoteAddr());
    data.put("referer", request.getHeader("referrer"));
    return visitorDao.insert(data);
}

From source file:com.cisco.step.jenkins.plugins.jenkow.JenkowWorkflowRepository.java

/**
 * Requires the admin access to be able to push
 *//* ww w. j a va  2  s . c om*/
@Override
public ReceivePack createReceivePack(HttpServletRequest context, Repository db)
        throws ServiceNotEnabledException, ServiceNotAuthorizedException {
    Authentication a = Jenkins.getAuthentication();
    ReceivePack rp = createReceivePack(db);
    rp.setRefLogIdent(new PersonIdent(a.getName(), a.getName() + "@" + context.getRemoteAddr()));
    return rp;
}

From source file:org.unidle.web.LocationMethodArgumentResolver.java

@Override
public Object resolveArgument(final MethodParameter methodParameter,
        final ModelAndViewContainer modelAndViewContainer, final NativeWebRequest nativeWebRequest,
        final WebDataBinderFactory webDataBinderFactory) throws Exception {

    final HttpServletRequest httpServletRequest = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
    final Cookie cookie = WebUtils.getCookie(httpServletRequest, "address");

    final String address = cookie != null ? cookie.getValue()
            : hasText(nativeWebRequest.getHeader("X-Forwarded-For"))
                    ? nativeWebRequest.getHeader("X-Forwarded-For")
                    : httpServletRequest.getRemoteAddr();

    return locationService.locateAddress(address);
}

From source file:net.sourceforge.subsonic.backend.controller.MultiController.java

public ModelAndView version(HttpServletRequest request, HttpServletResponse response) throws Exception {

    String localVersion = request.getParameter("v");
    LOG.info(request.getRemoteAddr() + " asked for latest version. Local version: " + localVersion);

    PrintWriter writer = response.getWriter();

    writer.println("SUBSONIC_VERSION_BEGIN" + SUBSONIC_VERSION + "SUBSONIC_VERSION_END");
    writer.println("SUBSONIC_FULL_VERSION_BEGIN" + SUBSONIC_VERSION + "SUBSONIC_FULL_VERSION_END");
    writer.println("SUBSONIC_BETA_VERSION_BEGIN" + SUBSONIC_BETA_VERSION + "SUBSONIC_BETA_VERSION_END");

    return null;//from   w ww .ja  va 2s  .  co m
}

From source file:se.vgregion.portal.auditlog.AuditLogInfoContainerFactoryImpl.java

private String getRemoteIpAddress(HttpServletRequest request) {
    StringBuilder ipAddress = new StringBuilder();

    Enumeration forwardedForEnum = request.getHeaders(HEADER_X_FORWARDED_FOR);
    while (forwardedForEnum.hasMoreElements()) {
        ipAddress.append(forwardedForEnum.nextElement()).append(" ");
    }// w w w  . j  ava2  s  . c  o  m
    if (ipAddress.length() == 0) {
        ipAddress.append(request.getRemoteAddr()).append(" [Default]");
    }

    return ipAddress.toString().trim();
}

From source file:com.liferay.petra.doulos.servlet.DoulosServlet.java

@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws IOException {

    String remoteAddr = request.getRemoteAddr();

    if (_log.isInfoEnabled()) {
        _log.info("Remote address: " + remoteAddr);
    }//from w w  w.j av a  2 s . c  o  m

    if (!isValidIP(remoteAddr)) {
        sendError(response, "IP " + remoteAddr + " is invalid.");

        return;
    }

    String pathInfo = request.getPathInfo();

    if (pathInfo.length() > 1) {
        if (pathInfo.endsWith("/")) {
            pathInfo = pathInfo.substring(0, pathInfo.length() - 1);
        }
    }

    for (Map.Entry<String, DoulosRequestProcessor> entry : _doulosRequestProcessors.entrySet()) {

        String doulosRequestProcessorKey = entry.getKey();

        if (!pathInfo.startsWith(doulosRequestProcessorKey)) {
            continue;
        }

        DoulosRequestProcessor doulosRequestProcessor = entry.getValue();

        if (_log.isInfoEnabled()) {
            _log.info(StringBundler.concat("Processing ", String.valueOf(request.getRequestURL()), " with ",
                    String.valueOf(doulosRequestProcessor)));
        }

        try {
            String payload = request.getParameter("payload");

            if (_log.isInfoEnabled()) {
                _log.info("Payload parameter: " + payload);
            }

            if (payload == null) {
                StringBuilder sb = new StringBuilder();

                String line = null;

                BufferedReader bufferedReader = request.getReader();

                while ((line = bufferedReader.readLine()) != null) {
                    sb.append(line);
                }

                bufferedReader.close();

                payload = sb.toString();

                if (_log.isInfoEnabled()) {
                    _log.info("Payload body: " + payload);
                }
            }

            JSONObject payloadJSONObject = null;

            if (payload.length() > 0) {
                payloadJSONObject = new JSONObject(payload);
            } else {
                payloadJSONObject = new JSONObject();
            }

            JSONObject responseJSONObject = new JSONObject();

            doulosRequestProcessor.process(request.getMethod(),
                    pathInfo.substring(doulosRequestProcessorKey.length()), request.getParameterMap(),
                    payloadJSONObject, responseJSONObject);

            String redirect = responseJSONObject.optString("doulosRedirect");

            if (!isBlank(redirect)) {
                response.sendRedirect(redirect);

                return;
            }

            String json = responseJSONObject.toString();

            write(response, new ByteArrayInputStream(json.getBytes("UTF-8")));
        } catch (Exception e) {
            StringWriter stringWriter = new StringWriter();

            PrintWriter printWriter = new PrintWriter(stringWriter);

            e.printStackTrace(printWriter);

            String output = stringWriter.toString();

            if (_log.isInfoEnabled()) {
                _log.info(output);
            }

            sendError(response, output);
        }

        return;
    }

    sendError(response, "Unregistered path " + request.getPathInfo() + ".");
}