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:controllers.AdController.java

@RequestMapping("/watch")
@ResponseBody//w w  w .j  a  v a 2  s  .co m
public JsonResponse watch(Map<String, Object> model, HttpServletRequest request,
        @RequestParam(value = "adId", required = false) Long adId, RedirectAttributes ras) throws Exception {

    String ip = request.getRemoteAddr();
    adService.addWatchFromIp(adId, ip);

    JsonResponse res = new JsonResponse();
    res.setStatus(Boolean.TRUE);
    if (!adService.getErrors().isEmpty()) {
        res.setMessage(adService.getErrorsAsString());
        res.setStatus(Boolean.FALSE);
    }
    return res;
}

From source file:com.codeabovelab.dm.gateway.proxy.common.HttpProxy.java

private void setXForwardedForHeader(HttpServletRequest servletRequest, HttpRequest proxyRequest) {

    if (DO_FORWARD_IP) {
        String newHeader = servletRequest.getRemoteAddr();
        String existingHeader = servletRequest.getHeader(FORWARD_HEADER_NAME);
        if (existingHeader != null) {
            newHeader = existingHeader + ", " + newHeader;
        }/* w  w  w.j ava2 s.c  o m*/
        proxyRequest.setHeader(FORWARD_HEADER_NAME, newHeader);
    }
}

From source file:jeeves.server.sources.http.JeevesServlet.java

private void execute(HttpServletRequest req, HttpServletResponse res) throws IOException {
    String ip = req.getRemoteAddr();
    // if we do have the optional x-forwarded-for request header then
    // use whatever is in it to record ip address of client
    String forwardedFor = req.getHeader("x-forwarded-for");
    if (forwardedFor != null)
        ip = forwardedFor;/*from   ww w .j  a  v  a 2 s  .c om*/

    Log.info(Log.REQUEST, "==========================================================");
    Log.info(Log.REQUEST, "HTML Request (from " + ip + ") : " + req.getRequestURI());
    if (Log.isDebugEnabled(Log.REQUEST)) {
        Log.debug(Log.REQUEST, "Method       : " + req.getMethod());
        Log.debug(Log.REQUEST, "Content type : " + req.getContentType());
        //      Log.debug(Log.REQUEST, "Context path : "+ req.getContextPath());
        //      Log.debug(Log.REQUEST, "Char encoding: "+ req.getCharacterEncoding());
        Log.debug(Log.REQUEST, "Accept       : " + req.getHeader("Accept"));
        //      Log.debug(Log.REQUEST, "Server name  : "+ req.getServerName());
        //      Log.debug(Log.REQUEST, "Server port  : "+ req.getServerPort());
    }
    //      for (Enumeration e = req.getHeaderNames(); e.hasMoreElements();) {
    //         String theHeader = (String)e.nextElement();
    //        if(Log.isDebugEnabled(Log.REQUEST)) {
    //         Log.debug(Log.REQUEST, "Got header: "+theHeader);   
    //         Log.debug(Log.REQUEST, "With value: "+req.getHeader(theHeader));
    //        }
    //      }
    HttpSession httpSession = req.getSession();
    if (Log.isDebugEnabled(Log.REQUEST))
        Log.debug(Log.REQUEST, "Session id is " + httpSession.getId());
    UserSession session = (UserSession) httpSession.getAttribute("session");

    //------------------------------------------------------------------------
    //--- create a new session if doesn't exist

    if (session == null) {
        //--- create session

        session = new UserSession();
        httpSession.setAttribute("session", session);
        if (Log.isDebugEnabled(Log.REQUEST))
            Log.debug(Log.REQUEST, "Session created for client : " + ip);
    }

    session.setProperty("realSession", httpSession);
    //------------------------------------------------------------------------
    //--- build service request

    ServiceRequest srvReq = null;

    //--- create request

    try {
        srvReq = ServiceRequestFactory.create(req, res, jeeves.getUploadDir(), jeeves.getMaxUploadSize());
    } catch (FileUploadTooBigEx e) {
        StringBuffer sb = new StringBuffer();
        sb.append("Opgeladen bestand overschrijdt de maximaal toegelaten grootte van "
                + jeeves.getMaxUploadSize() + " Mb\n");
        sb.append("Error : " + e.getClass().getName() + "\n");
        res.sendError(400, sb.toString());

        // now stick the stack trace on the end and log the whole lot
        sb.append("Stack :\n");
        sb.append(Util.getStackTrace(e));
        Log.error(Log.REQUEST, sb.toString());
        return;
    } catch (FileTypeNotAllowedEx e) {
        StringBuffer sb = new StringBuffer();
        sb.append("Bestand heeft niet het juiste type\n");
        sb.append("Error : " + e.getClass().getName() + "\n");
        res.sendError(400, sb.toString());

        // now stick the stack trace on the end and log the whole lot
        sb.append("Stack :\n");
        sb.append(Util.getStackTrace(e));
        Log.error(Log.REQUEST, sb.toString());
        return;
    } catch (Exception e) {
        StringBuffer sb = new StringBuffer();

        sb.append("Cannot build ServiceRequest\n");
        sb.append("Cause : " + e.getMessage() + "\n");
        sb.append("Error : " + e.getClass().getName() + "\n");
        res.sendError(400, sb.toString());

        // now stick the stack trace on the end and log the whole lot
        sb.append("Stack :\n");
        sb.append(Util.getStackTrace(e));
        Log.error(Log.REQUEST, sb.toString());
        return;
    }

    if ("user.agiv.login".equals(srvReq.getService())) {
        if (srvReq.getParams() != null && srvReq.getParams().getChild("wa") != null
                && srvReq.getParams().getChild("wa").getTextTrim().equals("wsignoutcleanup1.0")) {
            srvReq.setService("user.agiv.logout");
        } else {
            Principal p = req.getUserPrincipal();
            if (p != null
                    && p instanceof FederationPrincipal/* && SecurityTokenThreadLocal.getToken()==null*/) {
                FederationPrincipal fp = (FederationPrincipal) p;
                /*
                                  for (Claim c: fp.getClaims()) {
                                      System.out.println(c.getClaimType().toString() + ":" + (c.getValue()!=null ? c.getValue().toString() : ""));               
                                  }
                */
                Map<String, String> roleProfileMapping = new HashMap<String, String>();
                String profile = null;
                roleProfileMapping.put("Authenticated", "RegisteredUser");
                roleProfileMapping.put(nodeType + " Metadata Admin", "Administrator");
                roleProfileMapping.put(nodeType + " Metadata Editor", "Editor");
                roleProfileMapping.put(nodeType + " Metadata Hoofdeditor", "Hoofdeditor");
                List<String> roleListToCheck = Arrays.asList(nodeType + " Metadata Admin",
                        nodeType + " Metadata Hoofdeditor", nodeType + " Metadata Editor", "Authenticated");
                for (String item : roleListToCheck) {
                    if (req.isUserInRole(item)) {
                        profile = roleProfileMapping.get(item);
                        break;
                    }
                }
                String contactid = Util.getClaimValue(fp, "contactid");
                session.authenticate(contactid, contactid/* + "_" + Util.getClaimValue(fp,"name")*/,
                        Util.getClaimValue(fp, "givenname"), Util.getClaimValue(fp, "surname"),
                        profile != null ? profile : "RegisteredUser", Util.getClaimValue(fp, "emailaddress"));
                List<Map<String, String>> groups = new ArrayList<Map<String, String>>();
                Map<String, String> group = new HashMap<String, String>();
                String parentorganisationid = Util.getClaimValue(fp, "parentorganisationid");
                String parentorganisationdisplayname = Util.getClaimValue(fp, "parentorganisationdisplayname");
                group.put("name",
                        StringUtils.isBlank(parentorganisationid) ? Util.getClaimValue(fp, "organisationid")
                                : parentorganisationid);
                group.put("description",
                        StringUtils.isBlank(parentorganisationdisplayname)
                                ? (StringUtils.isBlank(parentorganisationid)
                                        ? Util.getClaimValue(fp, "organisationdisplayname")
                                        : parentorganisationid)
                                : parentorganisationdisplayname);
                groups.add(group);
                session.setProperty("groups", groups);
            } else {
                System.out.println("Principal is not instance of FederationPrincipal");
            }
        }
    }

    //--- execute request

    jeeves.dispatch(srvReq, session);
}

From source file:com.hypersocket.session.json.SessionUtils.java

public <T> SessionResourceToken<T> authenticateSessionToken(HttpServletRequest request,
        HttpServletResponse response, String shortCode, Class<T> resourceClz)
        throws UnauthorizedException, SessionTimeoutException {

    SessionResourceToken<T> token = sessionService.getSessionToken(shortCode, resourceClz);

    if (token != null) {
        if (request.getRemoteAddr().equals(token.getSession().getRemoteAddress())) {

            // Preserve the session for future lookups in this request and session
            request.setAttribute(AUTHENTICATED_SESSION, token.getSession());
            request.getSession().setAttribute(AUTHENTICATED_SESSION, token.getSession());

            addAPISession(request, response, token.getSession());

            return token;
        }/*from   www  . j a v a  2  s.  com*/
    }

    throw new UnauthorizedException();
}

From source file:net.webpasswordsafe.server.webservice.rest.UserController.java

@RequestMapping(value = "/users", method = RequestMethod.POST)
public ModelAndView addUser(@RequestBody Map<String, Object> userMap, HttpServletRequest request,
        @RequestHeader(Constants.REST_AUTHN_USERNAME) String authnUsername,
        @RequestHeader(Constants.REST_AUTHN_PASSWORD) String authnPassword,
        @RequestHeader(Constants.REST_AUTHN_TOTP) String authnTOTP) {
    boolean isSuccess = false;
    String message = "";
    String userId = "";
    try {//from  w  w w . j  a  va2 s  .  c om
        ServerSessionUtil.setIP(request.getRemoteAddr());
        AuthenticationStatus authStatus = loginService.login(authnUsername,
                Utils.buildCredentials(authnPassword, authnTOTP));
        if (AuthenticationStatus.SUCCESS == authStatus) {
            User user = new User();
            user.setUsername(Utils.safeString(userMap.get("username")));
            user.updateAuthnPasswordValue(Utils.safeString(userMap.get("password")));
            user.setFullname(Utils.safeString(userMap.get("fullname")));
            user.setEmail(Utils.safeString(userMap.get("email")));
            String activeFlag = Utils.safeString(userMap.get("active")).toLowerCase();
            user.setActiveFlag(activeFlag.equals("true") || activeFlag.equals("yes") || activeFlag.equals("y"));

            boolean isUserTaken = userService.isUserTaken(user.getUsername());
            if (!isUserTaken) {
                userService.addUser(user);
                userId = String.valueOf(user.getId());
                isSuccess = true;
            } else {
                message = "Username already exists";
            }
        } else {
            message = "Invalid authentication";
        }
        loginService.logout();
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
        isSuccess = false;
        message = e.getMessage();
    }
    return createModelAndView(isSuccess, message, "userId", userId);
}

From source file:com.shenit.commons.utils.HttpUtils.java

/**
 * ?IP//from  w ww  . ja v a 2  s . c  om
 * 
 * @param req
 * @return
 */
public static String getClientIp(HttpServletRequest req) {
    String ip = req.getHeader(HEADER_REAL_IP);
    if (StringUtils.isBlank(ip)) {
        ip = req.getHeader(HEADER_FORWARDED_FOR);
    }
    if (StringUtils.isBlank(ip)) {
        ip = req.getRemoteAddr();
    }
    return ip;
}

From source file:org.realityforge.proxy_servlet.AbstractProxyServlet.java

private void setXForwardedForHeader(final HttpServletRequest servletRequest, final HttpRequest proxyRequest) {
    if (shouldForwardIP()) {
        String newHeader = servletRequest.getRemoteAddr();
        String existingHeader = servletRequest.getHeader(X_FORWARDED_FOR_HEADER);
        if (existingHeader != null) {
            newHeader = existingHeader + ", " + newHeader;
        }//from ww  w .j  a va 2 s .  c o m
        proxyRequest.setHeader(X_FORWARDED_FOR_HEADER, newHeader);
    }
}

From source file:com.thoughtworks.go.server.controller.AgentRegistrationController.java

@RequestMapping(value = "/admin/agent", method = RequestMethod.POST)
public ResponseEntity agentRequest(@RequestParam("hostname") String hostname, @RequestParam("uuid") String uuid,
        @RequestParam("location") String location, @RequestParam("usablespace") String usablespaceAsString,
        @RequestParam("operatingSystem") String operatingSystem,
        @RequestParam("agentAutoRegisterKey") String agentAutoRegisterKey,
        @RequestParam("agentAutoRegisterResources") String agentAutoRegisterResources,
        @RequestParam("agentAutoRegisterEnvironments") String agentAutoRegisterEnvironments,
        @RequestParam("agentAutoRegisterHostname") String agentAutoRegisterHostname,
        @RequestParam("elasticAgentId") String elasticAgentId,
        @RequestParam("elasticPluginId") String elasticPluginId,
        @RequestParam(value = "supportsBuildCommandProtocol", required = false, defaultValue = "false") boolean supportsBuildCommandProtocol,
        @RequestParam("token") String token, HttpServletRequest request) {
    final String ipAddress = request.getRemoteAddr();
    LOG.debug("Processing registration request from agent [{}/{}]", hostname, ipAddress);
    Registration keyEntry;//from   ww  w  .  j av  a  2s  .c o  m
    String preferredHostname = hostname;

    try {
        if (!encodeBase64String(hmac().doFinal(uuid.getBytes())).equals(token)) {
            String message = "Not a valid token.";
            LOG.error(
                    "Rejecting request for registration. Error: HttpCode=[{}] Message=[{}] UUID=[{}] Hostname=[{}]"
                            + "ElasticAgentID=[{}] PluginID=[{}]",
                    FORBIDDEN, message, uuid, hostname, elasticAgentId, elasticPluginId);
            return new ResponseEntity<>(message, FORBIDDEN);
        }

        if (goConfigService.serverConfig().shouldAutoRegisterAgentWith(agentAutoRegisterKey)) {
            preferredHostname = getPreferredHostname(agentAutoRegisterHostname, hostname);
        } else {
            if (elasticAgentAutoregistrationInfoPresent(elasticAgentId, elasticPluginId)) {
                String message = String.format(
                        "Elastic agent registration requires an auto-register agent key to be"
                                + " setup on the server. Agent-id: [%s], Plugin-id: [%s]",
                        elasticAgentId, elasticPluginId);
                LOG.error(
                        "Rejecting request for registration. Error: HttpCode=[{}] Message=[{}] UUID=[{}] Hostname=[{}]"
                                + "ElasticAgentID=[{}] PluginID=[{}]",
                        UNPROCESSABLE_ENTITY, message, uuid, hostname, elasticAgentId, elasticPluginId);
                return new ResponseEntity<>(message, UNPROCESSABLE_ENTITY);
            }
        }

        AgentConfig agentConfig = new AgentConfig(uuid, preferredHostname, ipAddress);

        if (partialElasticAgentAutoregistrationInfo(elasticAgentId, elasticPluginId)) {
            String message = "Elastic agents must submit both elasticAgentId and elasticPluginId.";
            LOG.error(
                    "Rejecting request for registration. Error: HttpCode=[{}] Message=[{}] UUID=[{}] Hostname=[{}]"
                            + "ElasticAgentID=[{}] PluginID=[{}]",
                    UNPROCESSABLE_ENTITY, message, uuid, hostname, elasticAgentId, elasticPluginId);
            return new ResponseEntity<>(message, UNPROCESSABLE_ENTITY);
        }

        if (elasticAgentIdAlreadyRegistered(elasticAgentId, elasticPluginId)) {
            String message = "Duplicate Elastic agent Id used to register elastic agent.";
            LOG.error(
                    "Rejecting request for registration. Error: HttpCode=[{}] Message=[{}] UUID=[{}] Hostname=[{}]"
                            + "ElasticAgentID=[{}] PluginID=[{}]",
                    UNPROCESSABLE_ENTITY, message, uuid, hostname, elasticAgentId, elasticPluginId);
            return new ResponseEntity<>(message, UNPROCESSABLE_ENTITY);
        }

        if (elasticAgentAutoregistrationInfoPresent(elasticAgentId, elasticPluginId)) {
            agentConfig.setElasticAgentId(elasticAgentId);
            agentConfig.setElasticPluginId(elasticPluginId);
        }

        if (goConfigService.serverConfig().shouldAutoRegisterAgentWith(agentAutoRegisterKey)
                && !goConfigService.hasAgent(uuid)) {
            LOG.info("[Agent Auto Registration] Auto registering agent with uuid {} ", uuid);
            GoConfigDao.CompositeConfigCommand compositeConfigCommand = new GoConfigDao.CompositeConfigCommand(
                    new AgentConfigService.AddAgentCommand(agentConfig),
                    new UpdateResourceCommand(uuid, agentAutoRegisterResources),
                    new UpdateEnvironmentsCommand(uuid, agentAutoRegisterEnvironments));
            HttpOperationResult result = new HttpOperationResult();
            agentConfig = agentConfigService.updateAgent(compositeConfigCommand, uuid, result,
                    agentService.agentUsername(uuid, ipAddress, preferredHostname));
            if (!result.isSuccess()) {
                List<ConfigErrors> errors = ErrorCollector.getAllErrors(agentConfig);

                ConfigErrors e = new ConfigErrors();
                e.add("resultMessage", result.detailedMessage());

                errors.add(e);
                throw new GoConfigInvalidException(null, new AllConfigErrors(errors).asString());
            }
        }

        boolean registeredAlready = goConfigService.hasAgent(uuid);
        long usableSpace = Long.parseLong(usablespaceAsString);

        AgentRuntimeInfo agentRuntimeInfo = AgentRuntimeInfo.fromServer(agentConfig, registeredAlready,
                location, usableSpace, operatingSystem, supportsBuildCommandProtocol);

        if (elasticAgentAutoregistrationInfoPresent(elasticAgentId, elasticPluginId)) {
            agentRuntimeInfo = ElasticAgentRuntimeInfo.fromServer(agentRuntimeInfo, elasticAgentId,
                    elasticPluginId);
        }

        keyEntry = agentService.requestRegistration(
                agentService.agentUsername(uuid, ipAddress, preferredHostname), agentRuntimeInfo);

        final HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        return new ResponseEntity<>(RegistrationJSONizer.toJson(keyEntry), httpHeaders,
                keyEntry.isValid() ? OK : ACCEPTED);
    } catch (Exception e) {
        LOG.error(
                "Error occurred during agent registration process. Error: HttpCode=[{}] Message=[{}] UUID=[{}] "
                        + "Hostname=[{}] ElasticAgentID=[{}] PluginID=[{}]",
                UNPROCESSABLE_ENTITY, getErrorMessage(e), uuid, hostname, elasticAgentId, elasticPluginId, e);
        return new ResponseEntity<>(
                String.format("Error occurred during agent registration process: %s", getErrorMessage(e)),
                UNPROCESSABLE_ENTITY);
    }
}

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

/**
 * Log out request - the format should be close to Apache access log format
 * // w  w w . j  a va  2 s  .  c o m
 * @param req
 * @param session
 */
private void logRequest(HttpServletRequest req, Session session) {
    StringBuilder buf = new StringBuilder();
    buf.append(req.getRemoteAddr()).append(" ");
    if (session != null && session.getUser() != null) {
        buf.append(session.getUser().getUserId()).append(" ");
    } else {
        buf.append(" - ").append(" ");
    }

    buf.append("\"");
    buf.append(req.getMethod()).append(" ");
    buf.append(req.getRequestURI()).append(" ");
    if (req.getQueryString() != null) {
        buf.append(req.getQueryString()).append(" ");
    } else {
        buf.append("-").append(" ");
    }
    buf.append(req.getProtocol()).append("\" ");

    String userAgent = req.getHeader("User-Agent");
    if (shouldLogRawUserAgent) {
        buf.append(userAgent);
    } else {
        // simply log a short string to indicate browser or not
        if (StringUtils.isFromBrowser(userAgent)) {
            buf.append("browser");
        } else {
            buf.append("not-browser");
        }
    }

    logger.info(buf.toString());
}

From source file:simplestorage.controllers.HashtableController.java

@RequestMapping(value = "/hashtable/{key}", method = RequestMethod.POST)
public ModelAndView put(HttpServletRequest request, HttpServletResponse response, @PathVariable String key)
        throws IOException {
    // If I can't read from input stream, there is nothing I can do about it.
    InputStream input = request.getInputStream();
    int length = request.getContentLength();
    if (length != -1) {
        byte[] value = new byte[length];
        input.read(value, 0, request.getContentLength());
        String userIP = request.getRemoteAddr();
        int userPort = request.getRemotePort();
        hashtableSvc.put(key, new String(value, "UTF-8"), String.format("%s:%s", userIP, userPort));
        return constructModelAndView(gson.toJson(Boolean.TRUE));
    } else {//  www.  jav a  2 s .  c  o  m
        throw new IOException("Content-Length unknown.");
    }
}