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.egov.infra.security.utils.captcha.CaptchaUtils.java

public boolean captchaIsValid(HttpServletRequest request) {
    try {/*from   w  ww  .  j  a  v  a  2 s .c om*/
        if (highlySecure) {
            List<NameValuePair> urlParameters = new ArrayList<>();
            urlParameters.add(new BasicNameValuePair(RECAPTCH_SECRET_KEY,
                    (String) request.getSession().getAttribute(CITY_CAPTCHA_PRIV_KEY)));
            urlParameters.add(
                    new BasicNameValuePair(RECAPTCHA_RESPONSE_KEY, request.getParameter(RECAPTCHA_RESPONSE)));
            urlParameters.add(new BasicNameValuePair(RECAPTCHA_REMOTEIP_KEY, request.getRemoteAddr()));
            HttpPost post = new HttpPost(captchaVerificationUrl);
            post.setEntity(new UrlEncodedFormEntity(urlParameters));
            String responseJson = IOUtils.toString(
                    HttpClientBuilder.create().build().execute(post).getEntity().getContent(),
                    Charset.defaultCharset());
            return Boolean.valueOf(
                    new GsonBuilder().create().fromJson(responseJson, HashMap.class).get("success").toString());
        } else {
            String captchaId = request.getParameter(J_CAPTCHA_KEY);
            String response = request.getParameter(J_CAPTCHA_RESPONSE);
            return captchaService.validateResponseForID(captchaId, response);
        }
    } catch (Exception e) {
        LOG.warn("Captcha verification failed", e);
        return false;
    }
}

From source file:com.versatus.jwebshield.filter.SecurityTokenFilter.java

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

    HttpServletRequest httpReq = (HttpServletRequest) request;
    HttpServletResponse httpRes = (HttpServletResponse) response;
    UrlExclusionList exclList = (UrlExclusionList) request.getServletContext()
            .getAttribute(SecurityConstant.CSRF_CHECK_URL_EXCL_LIST_ATTR_NAME);

    logger.debug("doFilter: request from IP address=" + httpReq.getRemoteAddr());

    if (httpReq.getSession(false) == null) {
        chain.doFilter(request, response);
        return;//  w  ww  .  ja v  a2 s  .  c o m
    }

    logger.debug("doFilter: matching " + httpReq.getRequestURI() + " to exclusions list "
            + exclList.getExclusionMap());

    try {
        if (!exclList.isEmpty() && exclList.isMatch(httpReq.getRequestURI())) {
            chain.doFilter(request, response);
            return;
        }
    } catch (Exception e) {

        logger.error("doFilter", e);
    }

    // Check the user session for the salt cache, if none is present we
    // create one
    Cache<SecurityInfo, SecurityInfo> csrfPreventionSaltCache = (Cache<SecurityInfo, SecurityInfo>) httpReq
            .getSession().getAttribute(SecurityConstant.SALT_CACHE_ATTR_NAME);

    if (csrfPreventionSaltCache == null) {
        if (tokenTimeout == -1) {
            csrfPreventionSaltCache = CacheBuilder.newBuilder().maximumSize(1000).build();
        } else {
            csrfPreventionSaltCache = CacheBuilder.newBuilder().maximumSize(1000)
                    .expireAfterAccess(tokenTimeout, TimeUnit.SECONDS).build();
        }

        httpReq.getSession().setAttribute(SecurityConstant.SALT_CACHE_ATTR_NAME, csrfPreventionSaltCache);

        String nameSalt = RandomStringUtils.random(10, 0, 0, true, true, null, new SecureRandom());
        httpReq.getSession().setAttribute(SecurityConstant.SALT_PARAM_NAME, nameSalt);
    }

    // Generate the salt and store it in the users cache
    String salt = RandomStringUtils.random(20, 0, 0, true, true, null, new SecureRandom());

    String saltNameAttr = (String) httpReq.getSession().getAttribute(SecurityConstant.SALT_PARAM_NAME);
    SecurityInfo si = new SecurityInfo(saltNameAttr, salt);

    if (SecurityTokenFilter.checkReferer) {
        String refHeader = StringUtils.defaultString(httpReq.getHeader("Referer"));
        logger.debug("doFilter: refHeader=" + refHeader);
        if (StringUtils.isNotBlank(refHeader)) {
            try {
                URL refUrl = new URL(refHeader);
                refHeader = refUrl.getHost();
            } catch (MalformedURLException mex) {
                logger.debug("doFilter: parsing referer header failed", mex);
            }
        }

        si.setRefererHost(refHeader);
    }

    logger.debug("doFilter: si=" + si.toString());

    csrfPreventionSaltCache.put(si, si);

    // Add the salt to the current request so it can be used
    // by the page rendered in this request
    httpReq.setAttribute(SecurityConstant.SALT_ATTR_NAME, si);

    // set CSRF cookie
    HttpSession session = httpReq.getSession(false);
    if (session != null && StringUtils.isNotBlank(csrfCookieName)) {

        if (logger.isDebugEnabled()) {
            Cookie[] cookies = httpReq.getCookies();
            // boolean cookiePresent = false;
            for (Cookie c : cookies) {
                String name = c.getName();
                logger.debug("doFilter: cookie domain=" + c.getDomain() + "|name=" + name + "|value="
                        + c.getValue() + "|path=" + c.getPath() + "|maxage=" + c.getMaxAge() + "|httpOnly="
                        + c.isHttpOnly());
                // if (csrfCookieName.equals(name)) {
                // cookiePresent = true;
                // break;
                // }
            }
        }
        // if (!cookiePresent) {
        byte[] hashSalt = new byte[32];
        SecureRandom sr = new SecureRandom();
        sr.nextBytes(hashSalt);

        String csrfHash = RandomStringUtils.random(64, 0, 0, true, true, null, sr);

        Cookie c = new Cookie(csrfCookieName, csrfHash);
        c.setMaxAge(1800);
        c.setSecure(false);
        c.setPath(httpReq.getContextPath());
        c.setHttpOnly(false);
        httpRes.addCookie(c);
        // session.setAttribute(SecurityConstant.CSRFCOOKIE_VALUE_PARAM,
        // hashStr);
        // }
    }

    chain.doFilter(request, response);
}

From source file:com.mtgi.analytics.servlet.ServletRequestBehaviorTrackingAdapter.java

public BehaviorEvent start(ServletRequest request) {

    HttpServletRequest req = (HttpServletRequest) request;
    if (!match(req))
        return null;

    String eventName = getEventName(req);
    BehaviorEvent event = manager.createEvent(eventType, eventName);

    //log relevant request data and parameters to the event.
    EventDataElement data = event.addData();
    data.add("uri", req.getRequestURI());
    data.add("protocol", req.getProtocol());
    data.add("method", req.getMethod());
    data.add("remote-address", req.getRemoteAddr());
    data.add("remote-host", req.getRemoteHost());

    if (this.parameters != null) {
        EventDataElement parameters = data.addElement(PARAMETERS_ELEMENT);
        //include only configured parameters
        for (String name : this.parameters) {
            String[] values = request.getParameterValues(name);
            if (values != null)
                addParameter(parameters, name, values);
        }/*from   www  .  j ava  2  s . com*/
    } else {
        EventDataElement parameters = data.addElement(PARAMETERS_ELEMENT);
        //include all parameters
        for (Enumeration<?> params = request.getParameterNames(); params.hasMoreElements();) {
            String name = (String) params.nextElement();
            String[] values = request.getParameterValues(name);
            addParameter(parameters, name, values);
        }
    }

    manager.start(event);
    return event;
}

From source file:com.ibm.bluemix.mobilestarterkit.service.ServiceAPI.java

@Path("/login")
@POST//from ww w.  j a  v a2  s. co  m
public String checkLogin(@Context HttpServletRequest request, @Context UriInfo uriInfo, String creds) {

    System.out.println("checkLogin () ");

    // PAGE 
    String PAGE_ADDRESS = request.getRequestURL().toString();

    // IP_ADDRESS
    String IP_ADDRESS = request.getHeader("X-FORWARDED-FOR");
    if (IP_ADDRESS == null)
        IP_ADDRESS = request.getRemoteAddr();

    // ?
    String BROWSER = request.getHeader("User-Agent");

    // Insert log into LogTable
    saveLog(PAGE_ADDRESS, IP_ADDRESS, BROWSER);
    //System.out.println(">>> " + PAGE_ADDRESS + "  " + IP_ADDRESS + "  " + BROWSER);

    try {
        JSONObject credentials = new JSONObject(creds);
        String userID = credentials.getString("user_id");
        String password = credentials.getString("password");

        if (userID.equals("admin") && password.equals("password")) {
            return "Successful";
        } else {
            return "Failed";
        }

    } catch (JSONException e) {
        e.getStackTrace();
        return "Failed";

    }
}

From source file:com.sixt.service.framework.jetty.RpcReadException.java

public String toJson(HttpServletRequest req) {
    JsonObject obj = new JsonObject();

    Enumeration<String> h = req.getHeaderNames();
    while (h.hasMoreElements()) {
        String hKey = h.nextElement();
        String hValue = req.getHeader(hKey);
        obj.addProperty("request_header_" + hKey, hValue);
    }/*from  ww w.j a  v a 2s  .  c om*/

    obj.addProperty("exception_message", this.getMessage());
    obj.addProperty("request_query_string", req.getQueryString());
    obj.addProperty("request_url", req.getRequestURL().toString());
    obj.addProperty("request_remote_addr", req.getRemoteAddr());
    obj.addProperty("request_remote_port", req.getRemotePort());
    obj.addProperty("request_remote_host", req.getRemoteHost());
    obj.addProperty("request_remote_user", req.getRemoteUser());

    String readBody = "success";
    // read the whole remaining body and put the joined base64 encoded message into the json object
    try {
        byte[] ba = IOUtils.toByteArray(this.in);
        byte[] combined;
        if ((ba != null) && (this.incomplete != null)) {
            combined = new byte[ba.length + this.incomplete.length];
            System.arraycopy(incomplete, 0, combined, 0, this.incomplete.length);
            System.arraycopy(ba, 0, combined, this.incomplete.length, ba.length);
            obj.addProperty("request_body", Base64.getEncoder().encodeToString(combined));
        } else if (ba != null) {
            combined = ba;
        } else if (this.incomplete != null) {
            combined = this.incomplete;
        } else {
            readBody = "body is empty";
        }
    } catch (Exception ex) {
        readBody = String.format("failed because: %s", ex.getCause());
    }
    obj.addProperty("read_body", readBody);

    return obj.toString();
}

From source file:com.iLabs.spice.handler.LoginHandler.java

public String loginAction() throws IOException, ClassNotFoundException, SQLException {
    String result = "failure";
    try {/*from  ww  w.j  a  v  a2 s .com*/
        java.util.Date date = new java.util.Date();
        System.out.println("The Start Time (1): " + new Timestamp(date.getTime()));

        ProfileBean ownerProfile = (ProfileBean) getSessionScope().get("ownerProfile");
        ProfileBean currentProfile = (ProfileBean) getSessionScope().get("currentProfile");
        if (ownerProfile == null) {
            ownerProfile = new ProfileBean();
        }
        if (currentProfile == null) {
            currentProfile = new ProfileBean();
        }

        IPerson person = (IPerson) ServiceLocator.getService("PersonSvc");
        UserAuth authPerson = person.authenticateUser(currentProfile.getUserAuth().getUserName(),
                currentProfile.getUserAuth().getUserPassword());

        //This condition checks if the authPerson returned from authentication service is null or not.
        //If the user who enters the site is an authenticated user, the user's info and his friends info is stored in 
        //currentProfile as well as ownerProfile bean.
        if (authPerson != null && authPerson.getUserName() != null) {
            //Save the QoS Level of the user (Platinum, Gold or Silver)
            qoslevel = currentProfile.getUserAuth().getProfile().getProfileURL();

            ClientResource clientResource = new ClientResource("http://192.168.1.41:8180/sessions");

            Session session = new Session();

            ConnectionParty owner = new ConnectionParty();
            HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance()
                    .getExternalContext().getRequest();
            owner.setIp(request.getHeader("X-Forwarded-For"));
            owner.setPort(request.getRemotePort());
            System.out.println("Client address: " + request.getRemoteAddr());
            System.out.println("Client port: " + request.getRemotePort());
            if (qoslevel.equalsIgnoreCase("GOLD")) {
                owner.setSip_uri("sip:alice@openepc.test");
                session.setApplicationId("surveillance");
            } else {
                if (qoslevel.equalsIgnoreCase("Silver")) {
                    owner.setSip_uri("sip:bob@openepc.test");
                    session.setApplicationId("IMS");
                } else {
                    owner.setSip_uri("sip:charlie@openepc.test");
                    session.setApplicationId("YouTube");
                }
            }
            System.out.println("REQUEST  " + request.getRemoteAddr() + request.getRemoteHost()
                    + request.getLocalPort() + request.getRequestURI());
            System.out.println(request.getHeader("X-Forwarded-For"));
            ConnectionParty otherParty = new ConnectionParty();
            otherParty.setIp("192.168.1.41");
            otherParty.setPort(8080);
            otherParty.setSip_uri("");

            session.setSessionOwner(owner);
            session.setSessionOtherParty(otherParty);

            ServiceInfo serviceInfo = new ServiceInfo();
            //serviceInfo.setServiceId("Webcamstream");
            setBandwidthAndPriority(serviceInfo, qoslevel);
            serviceInfo.setMediaType(MediaType.DATA);
            serviceInfo.setLifeTime(6000);

            session.setServiceInfo(serviceInfo);

            Representation response = clientResource.post(session);
            String resp = response.getText();
            SI.setSessionID(resp.substring(70, 125));
            System.out.println("200 OK RESPONSE IS: " + resp);
            String s = SI.getSessionID();
            System.out.println("SESSION ID IS: " + s);

            UserFriends userFriends = person.getFriends(authPerson.getUserId());
            ownerProfile.setUserAuth(authPerson);
            ownerProfile.setUserFriends(userFriends);
            currentProfile.setUserAuth(authPerson);
            currentProfile.setUserFriends(userFriends);
            getSessionScope().put("ownerProfile", ownerProfile);
            getSessionScope().put("currentProfile", currentProfile);

            DatabaseConnector r = new DatabaseConnector();
            r.Write(s, authPerson.getUserId());
            //authPerson.getProfile().setProfileURL(s);
            System.out.println("User " + authPerson.getProfile().getFirstName() + " "
                    + authPerson.getProfile().getProfileURL());

            System.out.println("The Start Time (3): " + new Timestamp(date.getTime()));
            result = "success";
        } else { // if user is not an authenticate user, then error message is generated.
            FacesMessage message = new FacesMessage("Please Check Username and password");
            FacesContext.getCurrentInstance().addMessage("login:user_password", message);
        }

    } catch (SysException e) {
        e.printStackTrace();
    }
    return result;

}

From source file:com.oneops.daq.web.PerfAndLogController.java

/**
 * reportsMetricCounts/*from w w w .  j  a v  a  2s  .  com*/
 *
 * @param request the request
 * @param response the response
 * @return string
 * @throws Exception the exception
 */
@RequestMapping("/reportMetricCounts")
public void reportMetricCounts(HttpServletRequest request, HttpServletResponse response) throws Exception {

    long startTime = System.currentTimeMillis();
    perfDataAccessor.reportMetricCounts();
    long endTime = System.currentTimeMillis();
    long duration = endTime - startTime;
    logger.debug(request.getRemoteAddr() + " took " + duration + " ms");

    response.getOutputStream().print("done.\n");
    response.setStatus(200);
}

From source file:com.google.ie.web.controller.ProjectCommentController.java

/**
 * Handles request to add comment on a Project.
 * //from  w  w  w  . j ava 2  s.  com
 * @param projectComment key of the Project on which the comment is to be
 *        added.
 * @param user the User object
 * @throws IOException
 */
@RequestMapping(value = "/postProjectComments", method = RequestMethod.POST)
public void postCommentOnProject(HttpServletRequest request, @ModelAttribute ProjectComment projectComment,
        BindingResult result, Map<String, Object> map, @RequestParam String recaptchaChallengeField,
        @RequestParam String recaptchaResponseField, HttpSession session) throws IOException {
    ViewStatus viewStatus = new ViewStatus();
    Boolean captchaValidation = reCaptchaUtility.verifyCaptcha(request.getRemoteAddr(), recaptchaChallengeField,
            recaptchaResponseField);
    /* call CommentValidator to validate input ProjectComment object */
    getCommentValidator().validate(projectComment, result);
    if (result.hasErrors() || !captchaValidation) {
        logger.warn("Comment object has " + result.getErrorCount() + " validation errors");
        viewStatus.setStatus(WebConstants.ERROR);
        /* Add a message if the captcha validation fails */
        if (!captchaValidation) {
            viewStatus.addMessage(WebConstants.CAPTCHA, WebConstants.CAPTCHA_MISMATCH);
        }
        /* Iterate the errors and add a message for each error */
        for (Iterator<FieldError> iterator = result.getFieldErrors().iterator(); iterator.hasNext();) {
            FieldError fieldError = iterator.next();
            viewStatus.addMessage(fieldError.getField(), fieldError.getDefaultMessage());
            logger.warn("Error found in field: " + fieldError.getField() + " Message :"
                    + fieldError.getDefaultMessage());
        }

    } else {
        User user = (User) session.getAttribute(WebConstants.USER);
        Comment comment = commentService.addComment(projectComment, user);
        if (comment != null) {
            viewStatus.setStatus(WebConstants.SUCCESS);
            viewStatus.addMessage(WebConstants.COMMENTS, WebConstants.COMMENT_SUCCESSFULL);
        } else {
            viewStatus.setStatus(WebConstants.ERROR);
            viewStatus.addMessage(WebConstants.COMMENTS, WebConstants.COMMENT_FAILED);
        }
    }
    map.remove("projectComment");
    map.put(WebConstants.VIEW_STATUS, viewStatus);
}

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

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

    String email = request.getParameter("email");
    Long date = ServletRequestUtils.getLongParameter(request, "date");

    boolean valid = isLicenseValid(email, date);
    Date expirationDate = getLicenseExpirationDate(email);
    LOG.info(request.getRemoteAddr() + " asked to validate license for " + email + ". Result: " + valid
            + ", expires: " + expirationDate);

    PrintWriter writer = response.getWriter();
    writer.println(valid);/* www. j a  va2s  .com*/
    if (expirationDate != null) {
        writer.println(expirationDate.getTime());
    }

    return null;
}