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.slc.sli.dashboard.security.SLIAuthenticationEntryPoint.java

private void verifyingAuthentication(HttpServletRequest request, HttpServletResponse response,
        HttpSession session, OAuthService service) throws IOException {

    LOG.info(LOG_MESSAGE_AUTH_VERIFYING, new Object[] { request.getRemoteAddr() });

    Verifier verifier = new Verifier(request.getParameter(OAUTH_CODE));
    Token accessToken = service.getAccessToken(null, verifier);
    session.setAttribute(OAUTH_TOKEN, accessToken.getToken());
    Object entryUrl = session.getAttribute(ENTRY_URL);
    if (entryUrl != null) {
        response.sendRedirect(session.getAttribute(ENTRY_URL).toString());
    } else {/*from   www  . j  av a  2 s .com*/
        response.sendRedirect(request.getRequestURI());
    }
}

From source file:com.all.backend.web.controller.LoginServerController.java

@RequestMapping(method = POST, value = "/login")
@ResponseBody//  w  w w  .  ja  va 2s.co  m
public String login(@RequestBody String jsonLogin, HttpServletRequest request) {
    log.info("\nACTION:Login");
    LoginCommand loginCommand = JsonConverter.toBean(jsonLogin, LoginCommand.class);
    loginCommand.setPublicIp(request.getRemoteAddr());
    String pwd = loginCommand.getEncryptedPwd() == null || loginCommand.getEncryptedPwd().length() == 0
            ? loginCommand.getPassword()
            : loginCommand.getEncryptedPwd();
    LoginResponse loginResponse = loginService.login(loginCommand.getEmail(), pwd);
    if (loginResponse.isSuccessful()) {
        if (loginResponse.isFirstLogin()) {
            log.info(loginCommand.getEmail() + " has login for the first time.");
            for (ContactRequest pendingRequest : loginResponse.getPendingRequests()) {
                FriendshipRequestAlert alert = new FriendshipRequestAlert(pendingRequest);
                alertsService.save(alert);
            }
        }
        String version = loginCommand.getVersion();
        if (version != null) {
            saveLoginStats(loginCommand);
        }
    }
    log.debug("login response : " + ToStringBuilder.reflectionToString(loginResponse));
    return JsonConverter.toJson(loginResponse);
}

From source file:com.devnexus.ting.web.controller.EvaluationController.java

@RequestMapping(value = "/s/evaluations/add", method = RequestMethod.POST)
public String editEvent(@Valid Evaluation evaluation, BindingResult bindingResult, ModelMap model,
        HttpServletRequest request, RedirectAttributes redirectAttributes) {

    if (request.getParameter("cancel") != null) {
        return "redirect:/s/index";
    }//from   w  w  w  . java 2  s.c om

    final String reCaptchaEnabled = environment.getProperty("recaptcha.enabled");
    final String recaptchaPrivateKey = environment.getProperty("recaptcha.privateKey");

    if (Boolean.valueOf(reCaptchaEnabled)) {
        String remoteAddr = request.getRemoteAddr();
        ReCaptchaImpl reCaptcha = new ReCaptchaImpl();
        reCaptcha.setPrivateKey(recaptchaPrivateKey);

        String challenge = request.getParameter("recaptcha_challenge_field");
        String uresponse = request.getParameter("recaptcha_response_field");
        ReCaptchaResponse reCaptchaResponse = reCaptcha.checkAnswer(remoteAddr, challenge, uresponse);

        if (!reCaptchaResponse.isValid()) {
            ObjectError error = new ObjectError("error", "Please insert the correct CAPTCHA.");
            bindingResult.addError(error);
            prepareReferenceData(model);
            return "add-evaluation";
        }
    }

    if (bindingResult.hasErrors()) {
        prepareReferenceData(model);
        return "add-evaluation";
    }

    final Event eventFromDb = businessService.getCurrentEvent();

    final Evaluation evaluationToSave = new Evaluation();
    evaluationToSave.setComment(evaluation.getComment());
    evaluationToSave.setEvent(eventFromDb);
    evaluationToSave.setCreatedDate(new Date());
    evaluationToSave.setRating(evaluation.getRating());

    businessService.saveEvaluation(evaluationToSave);

    return "redirect:/s/add-evaluation-success";
}

From source file:com.trsst.ui.AppServlet.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
    // FLAG: limit access only to local clients
    if (restricted && !request.getRemoteAddr().equals(request.getLocalAddr())) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN, "Non-local clients are not allowed.");
        return;/*from   ww  w.  java 2 s.  c o  m*/
    }

    // in case of any posted files
    InputStream inStream = null;

    // determine if supported command: pull, push, post
    String path = request.getPathInfo();
    System.err.println(new Date().toString() + " " + path);
    if (path != null) {
        // FLAG: limit only to pull and post
        if (path.startsWith("/pull/") || path.startsWith("/post")) {
            // FLAG: we're sending the user's keystore
            // password over the wire (over SSL)
            List<String> args = new LinkedList<String>();
            if (path.startsWith("/pull/")) {
                path = path.substring("/pull/".length());
                response.setContentType("application/atom+xml; type=feed; charset=utf-8");
                // System.out.println("doPull: " +
                // request.getParameterMap());
                args.add("pull");
                if (request.getParameterMap().size() > 0) {
                    boolean first = true;
                    for (Object name : request.getParameterMap().keySet()) {
                        // FLAG: don't allow "home" (server-abuse)
                        // FLAG: don't allow "attach" (file-system access)
                        if ("decrypt".equals(name) || "pass".equals(name)) {
                            for (String value : request.getParameterValues(name.toString())) {
                                args.add("--" + name.toString());
                                args.add(value);
                            }
                        } else {
                            for (String value : request.getParameterValues(name.toString())) {
                                if (first) {
                                    path = path + '?';
                                    first = false;
                                } else {
                                    path = path + '&';
                                }
                                path = path + name + '=' + value;
                            }
                        }
                    }
                }
                args.add(path);

            } else if (path.startsWith("/post")) {
                // System.out.println("doPost: " +
                // request.getParameterMap());
                args.add("post");

                try { // h/t http://stackoverflow.com/questions/2422468
                    List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory())
                            .parseRequest(request);
                    for (FileItem item : items) {
                        if (item.isFormField()) {
                            // process regular form field
                            String name = item.getFieldName();
                            String value = item.getString("UTF-8").trim();
                            // System.out.println("AppServlet: " + name
                            // + " : " + value);
                            if (value.length() > 0) {
                                // FLAG: don't allow "home" (server-abuse)
                                // FLAG: don't allow "attach" (file-system
                                // access)
                                if ("id".equals(name)) {
                                    if (value.startsWith("urn:feed:")) {
                                        value = value.substring("urn:feed:".length());
                                    }
                                    args.add(value);
                                } else if (!"home".equals(name) && !"attach".equals(name)) {
                                    args.add("--" + name);
                                    args.add(value);
                                }
                            } else {
                                log.debug("Empty form value for name: " + name);
                            }
                        } else if (item.getSize() > 0) {
                            // process form file field (input type="file").
                            // String filename = FilenameUtils.getName(item
                            // .getName());
                            if (item.getSize() > 1024 * 1024 * 10) {
                                throw new FileUploadException("Current maximum upload size is 10MB");
                            }
                            String name = item.getFieldName();
                            if ("icon".equals(name) || "logo".equals(name)) {
                                args.add("--" + name);
                                args.add("-");
                            }
                            inStream = item.getInputStream();
                            // NOTE: only handles one file!
                        } else {
                            log.debug("Ignored form field: " + item.getFieldName());
                        }
                    }
                } catch (FileUploadException e) {
                    response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                            "Could not parse multipart request: " + e);
                    return;
                }
            }

            // send post data if any to command input stream
            if (inStream != null) {
                args.add("--attach");
            }
            //System.out.println(args);

            // make sure we don't create another local server
            args.add("--host");
            args.add(request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
                    + "/feed");

            PrintStream outStream = new PrintStream(response.getOutputStream(), false, "UTF-8");
            int result = new Command().doBegin(args.toArray(new String[0]), outStream, inStream);
            if (result != 0) {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                        "Internal error code: " + result);
            } else {
                outStream.flush();
            }
            return;
        }

        // otherwise: determine if static resource request
        if (path.startsWith("/")) {
            path = path.substring(1);
        }

        byte[] result = resources.get(path);
        String mimetype = null;
        if (result == null) {
            // if ("".equals(path) || path.endsWith(".html")) {
            // treat all html requests with index doc
            result = resources.get("index.html");
            mimetype = "text/html";
            // }
        }
        if (result != null) {
            if (mimetype == null) {
                if (path.endsWith(".html")) {
                    mimetype = "text/html";
                } else if (path.endsWith(".css")) {
                    mimetype = "text/css";
                } else if (path.endsWith(".js")) {
                    mimetype = "application/javascript";
                } else if (path.endsWith(".png")) {
                    mimetype = "image/png";
                } else if (path.endsWith(".jpg")) {
                    mimetype = "image/jpeg";
                } else if (path.endsWith(".jpeg")) {
                    mimetype = "image/jpeg";
                } else if (path.endsWith(".gif")) {
                    mimetype = "image/gif";
                } else {
                    mimetype = new Tika().detect(result);
                }
            }
            if (request.getHeader("If-None-Match:") != null) {
                // client should always use cached version
                log.info("sending 304");
                response.setStatus(304); // Not Modified
                return;
            }
            // otherwise allow ETag/If-None-Match
            response.setHeader("ETag", Long.toHexString(path.hashCode()));
            if (mimetype != null) {
                response.setContentType(mimetype);
            }
            response.setContentLength(result.length);
            response.getOutputStream().write(result);
            return;
        }

    }

    // // otherwise: 404 Not Found
    // response.sendError(HttpServletResponse.SC_NOT_FOUND);
}

From source file:net.locosoft.fold.channel.fold.internal.FoldFinder.java

void receiveFoldPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    JsonObject jsonObject = JsonObject.readFrom(request.getReader());

    String senderName = jsonObject.getString("senderName", null);
    String message = jsonObject.getString("message", null);

    if ((senderName != null) && (message != null)) {
        String senderIpAddr = request.getRemoteAddr();
        IChatterChannel chatterChannel = _foldChannel.getChannelService().getChannel(IChatterChannel.class);
        JsonObject chatterData = new JsonObject();
        chatterData.add("senderIpAddr", senderIpAddr);
        chatterData.add("senderName", senderName);
        chatterData.add("message", message);

        long chatterItemOrdinal = chatterChannel
                .createChatterItem("received FoldFinder post from ${senderIpAddr}", "foldFinder", chatterData);

        HierarchyNode foldChannelNode = new HierarchyNode(_foldChannel.getChannelNodeId());
        long subnetsNodeId = foldChannelNode.getSubId("subnets", true);
        HierarchyNode subnetsNode = new HierarchyNode(subnetsNodeId);
        long ipAddrPrefixNodeId = subnetsNode.getSubId(getIpAddrPrefix(senderIpAddr), true);
        HierarchyNode ipAddrPrefixNode = new HierarchyNode(ipAddrPrefixNodeId);
        long ipAddrSuffixNodeId = ipAddrPrefixNode.getSubId(getIpAddrSuffix(senderIpAddr), true);
        PropertyAccessNode props = new PropertyAccessNode(ipAddrSuffixNodeId);
        props.setValue("lastReceive_senderName", senderName);
        props.setValue("lastReceive_chatterItemOrdinal", chatterItemOrdinal);
    }//from  w w w .  ja  v  a 2  s  . c o m
}

From source file:de.thm.arsnova.controller.LoginController.java

@RequestMapping(value = { "/auth/login", "/doLogin" }, method = { RequestMethod.POST, RequestMethod.GET })
public void doLogin(@RequestParam("type") final String type,
        @RequestParam(value = "user", required = false) String username,
        @RequestParam(required = false) final String password,
        @RequestParam(value = "role", required = false) final UserSessionService.Role role,
        final HttpServletRequest request, final HttpServletResponse response) throws IOException {
    String addr = request.getRemoteAddr();
    if (userService.isBannedFromLogin(addr)) {
        response.sendError(429, "Too Many Requests");

        return;/*from   w ww.  j a  v a  2s.c  om*/
    }

    userSessionService.setRole(role);

    if ("arsnova".equals(type)) {
        Authentication authRequest = new UsernamePasswordAuthenticationToken(username, password);
        try {
            Authentication auth = daoProvider.authenticate(authRequest);
            if (auth.isAuthenticated()) {
                SecurityContextHolder.getContext().setAuthentication(auth);
                request.getSession(true).setAttribute(
                        HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
                        SecurityContextHolder.getContext());

                return;
            }
        } catch (AuthenticationException e) {
            LOGGER.info("Authentication failed: {}", e.getMessage());
        }

        userService.increaseFailedLoginCount(addr);
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
    } else if ("ldap".equals(type)) {
        if (!"".equals(username) && !"".equals(password)) {
            org.springframework.security.core.userdetails.User user = new org.springframework.security.core.userdetails.User(
                    username, password, true, true, true, true, this.getAuthorities());

            Authentication token = new UsernamePasswordAuthenticationToken(user, password, getAuthorities());
            try {
                Authentication auth = ldapAuthenticationProvider.authenticate(token);
                if (auth.isAuthenticated()) {
                    SecurityContextHolder.getContext().setAuthentication(token);
                    request.getSession(true).setAttribute(
                            HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
                            SecurityContextHolder.getContext());

                    return;
                }
                LOGGER.info("LDAPLOGIN: {}", auth.isAuthenticated());
            } catch (AuthenticationException e) {
                LOGGER.info("No LDAP login: {}", e);
            }

            userService.increaseFailedLoginCount(addr);
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
        }
    } else if ("guest".equals(type)) {
        List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
        authorities.add(new SimpleGrantedAuthority("ROLE_GUEST"));
        if (username == null || !username.startsWith("Guest") || username.length() != MAX_USERNAME_LENGTH) {
            username = "Guest"
                    + Sha512DigestUtils.shaHex(request.getSession().getId()).substring(0, MAX_GUESTHASH_LENGTH);
        }
        org.springframework.security.core.userdetails.User user = new org.springframework.security.core.userdetails.User(
                username, "", true, true, true, true, authorities);
        Authentication token = new UsernamePasswordAuthenticationToken(user, null, authorities);

        SecurityContextHolder.getContext().setAuthentication(token);
        request.getSession(true).setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
                SecurityContextHolder.getContext());
    }
}

From source file:com.sangupta.httpd.HttpdHandler.java

/**
 * Log the request details to screen//  w  w  w  . j  a v a  2 s .  c o  m
 * 
 * @param request
 * @param response
 * @param requestTime 
 */
private void logRequest(HttpServletRequest request, HttpServletResponse response, long requestTime) {
    SimpleDateFormat format = new SimpleDateFormat("dd/MMM/yyyy hh:mm:ss");

    StringBuilder builder = new StringBuilder(1024);
    builder.append(request.getRemoteAddr());
    builder.append(" - [");
    builder.append(format.format(new Date(requestTime)));
    builder.append("] \"");
    builder.append(request.getMethod());
    builder.append(' ');
    builder.append(request.getRequestURI());
    builder.append(' ');
    builder.append(request.getProtocol());
    builder.append(" - ");
    builder.append(response.getStatus());
    builder.append(" - ");

    String length = response.getHeader("Content-Length");
    if (length == null) {
        length = "0";
    }

    builder.append(length);

    System.out.println(builder.toString());
}

From source file:edu.uiuc.ideals.sead.BaseResource.java

/**
 * <p>Create a DSpace {@link org.dspace.core.Context}.</p>
 *
 * @param request {@link HttpServletRequest}
 * @return {@link org.dspace.core.Context}
 *//*from w  w w. j av a  2 s . c  o m*/
protected org.dspace.core.Context createContext(HttpServletRequest request) {

    try {
        context = new org.dspace.core.Context();
    } catch (SQLException e) {
        log.error(e);
        return null;
    }

    String ip = request.getRemoteAddr();

    //Set the session ID and IP address
    context.setExtraLogInfo("session_id=0:ip_addr=" + ip);
    return context;
}

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

/**
 * Login./*from  w  w  w.  j  a  va  2 s .  co m*/
 * 
 * @param request
 *            the request
 * @param fromSystem
 *            the from system
 * @param fromToken
 *            the from token
 * @param userAgent
 *            the user agent
 * @param login_type
 *            the login_type
 * @return the success response vo
 * @since 18/08/2014, 07:52:45 PM
 */
@RequestMapping(value = { login }, method = RequestMethod.POST, headers = { "Content-Type=application/json",
        "Accept=application/json" })
@ResponseStatus(value = HttpStatus.OK)
public @ResponseBody SuccessResponseVO login(HttpServletRequest request,
        @RequestHeader("X-Origin-OS") String fromSystem, @RequestHeader("X-Origin-Token") String fromToken,
        @RequestHeader("User-Agent") String userAgent,
        @RequestBody(required = true) AppLoginSuccessRequestVO login_type) {
    String loadBalanceIP = request.getHeader("X-Forwarded-For");
    String ipAddress = request.getRemoteAddr();
    if (ipAddress.equals("127.0.0.1") || ipAddress.equals("localhost")) {
        login_type.setIpAddress(loadBalanceIP);
    } else {
        login_type.setIpAddress(ipAddress);
    }
    login_type.setGadget(userAgent);
    login_type.setOs(fromSystem);
    login_type.setSerial(fromToken);
    login_type.setVersion(userAgent);
    return service.login(buildWrapper(login_type));
}

From source file:net.groupbuy.controller.admin.ConsultationController.java

/**
 * ?//from   w  ww .ja  v a 2  s . c  o  m
 */
@RequestMapping(value = "/reply", method = RequestMethod.POST)
public String reply(Long id, String content, HttpServletRequest request,
        RedirectAttributes redirectAttributes) {
    if (!isValid(Consultation.class, "content", content)) {
        return ERROR_VIEW;
    }
    Consultation consultation = consultationService.find(id);
    if (consultation == null) {
        return ERROR_VIEW;
    }
    Consultation replyConsultation = new Consultation();
    replyConsultation.setContent(content);
    replyConsultation.setIp(request.getRemoteAddr());
    consultationService.reply(consultation, replyConsultation);

    addFlashMessage(redirectAttributes, SUCCESS_MESSAGE);
    return "redirect:reply.jhtml?id=" + id;
}