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:me.smoe.lzy.filter.AccessLogFilter.java

private void logAccessAPI(HttpServletRequest request) {
    try {/*  w w w . jav  a2s . co  m*/
        User user = (User) request.getSession().getAttribute(Constants.SESSION_USER);
        String userId = user != null ? user.getId() : "NOT_LOGIN";
        String remoteAddr = request.getRemoteAddr();
        String method = request.getMethod();
        String requestURI = request.getRequestURI();
        String userAgent = StringUtils.defaultString(request.getHeader("User-Agent"));

        String queryString = request.getQueryString();
        if (queryString != null) {
            queryString = URLDecoder.decode(request.getQueryString(), Constants.CHARSET);
        }
        requestURI = requestURI
                + (StringUtils.isNotEmpty(queryString) ? ("?" + queryString) : StringUtils.EMPTY);

        Logger.getRestAccessLogger().info(
                String.format("[%s] [%s] [%s] %s [%s]", userId, remoteAddr, method, requestURI, userAgent));
    } catch (Exception e) {
        Logger.getRestAccessLogger().warn("AccessAPI logger error: " + e.getMessage(), e);
    }
}

From source file:com.ewcms.component.counter.web.CounterServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    Counter log = new Counter();
    log.setArticleId(getArticleId(request));
    String ip = request.getRemoteAddr();
    log.setIp(ip);/*  w  ww.  j a v a  2s.  c o  m*/
    int count = 10;
    if (!isArticleIdEmpty(log.getArticleId())) {
        CounterServiceable service = getCountSerivce();
        count = service.writeCountLog(log);
    }
    String encoding = getParameterValue(request, HEADER_ENCODING);
    encoding = (encoding == null ? DEFAULT_ENCODING : encoding);
    reponseCount(request, response, encoding, count);
}

From source file:com.enonic.cms.core.log.LogServiceImpl.java

@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public LogEntryKey storeNew(StoreNewLogEntryCommand command) {
    Assert.notNull(command.getType(), "type cannot be nul");
    Assert.notNull(command.getUser(), "user cannot be nul");
    Assert.notNull(command.getTitle(), "title cannot be nul");

    HttpServletRequest httpRequest = ServletRequestAccessor.getRequest();
    String clientInetAddress = null;
    if (httpRequest != null) {
        clientInetAddress = httpRequest.getRemoteAddr();
    }//from   w ww.j a v a 2  s  .  c o  m

    UserEntity user = userDao.findByKey(command.getUser());

    LogEntryEntity logEntry = new LogEntryEntity();
    logEntry.setType(command.getType().asInteger());
    logEntry.setTimestamp(timeService.getNowAsDateTime().toDate());
    logEntry.setInetAddress(clientInetAddress);
    logEntry.setUser(user);

    if (command.getTable() != null) {
        logEntry.setTableKey(command.getTable().asInteger());
        logEntry.setKeyValue(command.getTableKeyValue());
    }

    if (command.getSite() != null) {
        logEntry.setSite(command.getSite());
    }

    logEntry.setTitle(command.getTitle());

    if (command.getPath() != null) {
        logEntry.setPath(enshurePathWithinBoundary(command.getPath()));
    }

    if (command.getXmlData() != null) {
        logEntry.setXmlData(command.getXmlData());
    }

    else

    {
        logEntry.setXmlData(createEmptyXmlData());
    }

    logEntryDao.storeNew(logEntry);
    return logEntry.getKey();
}

From source file:com.formkiq.core.service.sign.SigningServiceImpl.java

/**
 * Create Docsign Result.//from w w  w. j av  a 2s  .  c om
 * @param request {@link HttpServletRequest}
 * @param workflow {@link Workflow}
 * @return {@link FormJSON}
 */
@Override
public FormJSON createDocsignResult(final HttpServletRequest request, final Workflow workflow) {

    String ipaddress = request.getRemoteAddr();
    String xforwardedfor = request.getHeader("X-FORWARDED-FOR");
    String latitude = request.getParameter("latitude");
    String longitude = request.getParameter("longitude");

    FormJSON form = new FormJSON();
    form.setUUID(UUID.randomUUID().toString());
    form.setParentUUID(workflow.getParentUUID());
    form.setBuiltintype(DOCSIGN_RESULT.toString());

    int i = 0;
    FormJSONField f0 = createFormField(++i, FormJSONFieldType.TEXTBOX, "Inserted Date", new Date());

    FormJSONField f1 = createFormField(++i, FormJSONFieldType.TEXTBOX, "IP Address", ipaddress);

    FormJSONField f2 = createFormField(++i, FormJSONFieldType.TEXTBOX, "X-FORWARDED-FOR",
            StringUtils.defaultString(xforwardedfor, ""));

    FormJSONField f3 = createFormField(++i, FormJSONFieldType.TEXTBOX, "Latitude", latitude);

    FormJSONField f4 = createFormField(++i, FormJSONFieldType.TEXTBOX, "Longitude", longitude);

    List<FormJSONField> fields = Arrays.asList(f0, f1, f2, f3, f4);

    FormJSONSection sect = buildFormJSONSection(null, fields);
    form.setSections(Arrays.asList(sect));

    return form;
}

From source file:net.sf.appstatus.web.StatusWebHandler.java

/**
 * Handle a POST request.//  ww  w. jav a 2s  .c  o  m
 *
 * @param req
 * @param resp
 * @throws IOException
 */
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    if (allowIp != null) {
        if (!req.getRemoteAddr().equals(allowIp)) {
            resp.sendError(401, "IP not authorized");
            return;
        }
    }

    if (req.getParameter("p") != null && pages.containsKey(req.getParameter("p"))) {
        pages.get(req.getParameter("p")).doPost(this, req, resp);

    } else {
        pages.get("status").doPost(this, req, resp);
    }

    doGet(req, resp);
}

From source file:com.haulmont.cuba.restapi.LoginServiceController.java

protected void setSessionInfo(HttpServletRequest request, UserSession userSession) {
    userSessionService.setSessionAddress(userSession.getId(), request.getRemoteAddr());

    String serverInfo = "REST API (" + globalConfig.getWebHostName() + ":" + globalConfig.getWebPort() + "/"
            + globalConfig.getWebContextName() + ") ";
    userSessionService.setSessionClientInfo(userSession.getId(), serverInfo + request.getHeader("User-Agent"));
}

From source file:fr.univrouen.poste.web.ExceptionController.java

@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
        Exception ex) {/* ww  w.ja  v  a 2s.c om*/

    if (ex instanceof AccessDeniedException) {
        return this.deniedHandler(request, response);
    }

    String ip = request.getRemoteAddr();
    if (ex instanceof MultipartException) {
        log.warn("MultipartException with this client " + ip
                + ". We can assume that the client has canceled his request (because of a double-click / double-submit of the form for example).",
                ex);
    } else {
        log.error("Uncaught exception  with this client " + ip, ex);
    }

    // hack for logging uploads failed 
    if (request.getServletPath().matches("/postecandidatures/[0-9]*/addFile")) {
        String posteCandidatureId = request.getServletPath().replaceAll("/postecandidatures/([0-9]*)/addFile",
                "$1");
        PosteCandidature posteCandidature = PosteCandidature
                .findPosteCandidature(Long.valueOf(posteCandidatureId));
        logService.logActionFile(LogService.UPLOAD_FAILED_ACTION, posteCandidature, null, request, new Date());
    }

    //response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    ModelAndView modelAndview = new ModelAndView("uncaughtException");
    modelAndview.addObject("exception", ex);
    return modelAndview;
}

From source file:com.erudika.para.security.SimpleAuthenticationSuccessHandler.java

@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
        Authentication authentication) throws IOException, ServletException {
    User u = SecurityUtils.getAuthenticatedUser(authentication);
    if (u != null) {
        if (!StringUtils.equals(request.getRemoteAddr(), u.getLastIp())) {
            u.setLastIp(request.getRemoteAddr());
            u.update();/*from  w ww  .  j a v  a2s  .co  m*/
        }
    }
    if (isRestRequest(request)) {
        RestUtils.returnStatusResponse(response, HttpServletResponse.SC_NO_CONTENT, "Authentication success.");
    } else {
        super.onAuthenticationSuccess(request, response, authentication);
    }
}

From source file:net.sf.appstatus.web.StatusWebHandler.java

/**
 * Handle a GET request./*from  w  ww.  ja va  2  s  . c  om*/
 *
 * @param req
 * @param resp
 * @throws IOException
 */
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {

    if (allowIp != null) {
        if (!req.getRemoteAddr().equals(allowIp)) {
            resp.sendError(401, "IP not authorized");
            return;
        }
    }

    if (req.getParameter("icon") != null || req.getParameter("resource") != null) {
        Resources.doGet(this, req, resp);
        return;
    }

    if (req.getParameter("p") != null && pages.containsKey(req.getParameter("p"))) {
        pages.get(req.getParameter("p")).doGet(this, req, resp);

    } else {
        pages.get("status").doGet(this, req, resp);
    }
}

From source file:it.geosolutions.httpproxy.callback.HostChecker.java

/**
 * @param req/*from   w  w w. j  a  v a2 s.  c o m*/
 * @return String
 */
private String getRemoteAddr(HttpServletRequest req) {
    String forwardedFor = req.getHeader("X-Forwarded-For");
    if (forwardedFor != null) {
        String[] ips = forwardedFor.split(", ");
        return ips[0];
    } else {
        return req.getRemoteAddr();
    }
}