Example usage for javax.servlet ServletRequest getRemoteAddr

List of usage examples for javax.servlet ServletRequest getRemoteAddr

Introduction

In this page you can find the example usage for javax.servlet ServletRequest 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.infoscoop.api.filter.ApiLogFilter.java

@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {
    String path = ((HttpServletRequest) req).getPathInfo().toString();
    String method = ((HttpServletRequest) req).getMethod().toString();
    String remote = req.getRemoteAddr();

    try {//from  ww  w .j a v  a2s.c  o m
        log.info(path + " " + method + " - " + remote);
        long start = System.currentTimeMillis();
        chain.doFilter(req, res);
        long stop = System.currentTimeMillis();
        log.info(path + " (" + (stop - start) + "ms) " + method + " - " + remote);
    } catch (Exception e) {
        log.warn(e.getMessage() + " - " + remote);
    }
}

From source file:com.earldouglas.filtre.Filtre.java

public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
        throws IOException, ServletException {

    boolean accessGranted = false;
    try {/*  w w  w  .ja  va  2  s .  co  m*/
        accessGranted = addressManager.isAccessPermitted(servletRequest.getRemoteAddr());
    } catch (AddressFormatException addressFormatException) {
        throw new ServletException(addressFormatException);
    } finally {
        logResult(servletRequest, accessGranted);
        if (accessGranted) {
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }
}

From source file:org.dspace.solr.filters.LocalHostRestrictionFilter.java

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

    if (enabled) {
        InetAddress ia = InetAddress.getLocalHost();
        String localAddr = ia.getHostAddress();
        String remoteAddr = request.getRemoteAddr();

        if (!(localAddr.equals(remoteAddr) || remoteAddr.equals("127.0.0.1")
                || remoteAddr.startsWith("0:0:0:0:0:0:0:1"))) {
            ((HttpServletResponse) response).sendError(403);
            return;
        }//from   w  ww .j  a va2s.  com

    }

    chain.doFilter(request, response);
}

From source file:org.openmrs.module.webservices.rest.web.filter.AuthorizationFilter.java

/**
 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
 *      javax.servlet.ServletResponse, javax.servlet.FilterChain)
 *//*from  w  w  w  .j  av a  2 s  .  c om*/
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    // check the IP address first.  If its not valid, return a 403
    if (!RestUtil.isIpAllowed(request.getRemoteAddr())) {
        // the ip address is not valid, set a 403 http error code
        HttpServletResponse httpresponse = (HttpServletResponse) response;
        httpresponse.sendError(HttpServletResponse.SC_FORBIDDEN,
                "IP address '" + request.getRemoteAddr() + "' is not authorized");
    }

    // skip if the session has timed out, we're already authenticated, or it's not an HTTP request
    if (request instanceof HttpServletRequest) {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        if (httpRequest.getRequestedSessionId() != null && !httpRequest.isRequestedSessionIdValid()) {
            HttpServletResponse httpResponse = (HttpServletResponse) response;
            httpResponse.sendError(HttpServletResponse.SC_FORBIDDEN, "Session timed out");
        }

        if (!Context.isAuthenticated()) {
            String basicAuth = httpRequest.getHeader("Authorization");
            if (basicAuth != null) {
                // this is "Basic ${base64encode(username + ":" + password)}"
                try {
                    basicAuth = basicAuth.substring(6); // remove the leading "Basic "
                    String decoded = new String(Base64.decodeBase64(basicAuth), Charset.forName("UTF-8"));
                    String[] userAndPass = decoded.split(":");
                    Context.authenticate(userAndPass[0], userAndPass[1]);
                    if (log.isDebugEnabled())
                        log.debug("authenticated " + userAndPass[0]);
                } catch (Exception ex) {
                    // This filter never stops execution. If the user failed to
                    // authenticate, that will be caught later.
                }
            }
        }
    }

    // continue with the filter chain in all circumstances
    chain.doFilter(request, response);
}

From source file:org.apache.camel.component.cxf.jaxrs.CxfRsConsumerTest.java

protected RouteBuilder createRouteBuilder() throws Exception {
    return new RouteBuilder() {
        public void configure() {
            errorHandler(new NoErrorHandlerBuilder());
            from(CXF_RS_ENDPOINT_URI).process(new Processor() {

                public void process(Exchange exchange) throws Exception {
                    Message inMessage = exchange.getIn();
                    // Get the operation name from in message
                    String operationName = inMessage.getHeader(CxfConstants.OPERATION_NAME, String.class);
                    if ("getCustomer".equals(operationName)) {
                        String httpMethod = inMessage.getHeader(Exchange.HTTP_METHOD, String.class);
                        assertEquals("Get a wrong http method", "GET", httpMethod);
                        String path = inMessage.getHeader(Exchange.HTTP_PATH, String.class);
                        // The parameter of the invocation is stored in the body of in message
                        String id = inMessage.getBody(String.class);
                        if ("/customerservice/customers/126".equals(path)) {
                            Customer customer = new Customer();
                            customer.setId(Long.parseLong(id));
                            customer.setName("Willem");
                            // We just put the response Object into the out message body
                            exchange.getOut().setBody(customer);
                        } else {
                            if ("/customerservice/customers/400".equals(path)) {
                                // We return the remote client IP address this time
                                org.apache.cxf.message.Message cxfMessage = inMessage.getHeader(
                                        CxfConstants.CAMEL_CXF_MESSAGE, org.apache.cxf.message.Message.class);
                                ServletRequest request = (ServletRequest) cxfMessage.get("HTTP.REQUEST");
                                String remoteAddress = request.getRemoteAddr();
                                Response r = Response.status(200)
                                        .entity("The remoteAddress is " + remoteAddress).build();
                                exchange.getOut().setBody(r);
                                return;
                            }/*from w w  w  .j  a va 2s  . c  om*/
                            if ("/customerservice/customers/123".equals(path)) {
                                // send a customer response back
                                Response r = Response.status(200).entity("customer response back!").build();
                                exchange.getOut().setBody(r);
                                return;
                            }
                            if ("/customerservice/customers/456".equals(path)) {
                                Response r = Response.status(404)
                                        .entity("Can't found the customer with uri " + path).build();
                                throw new WebApplicationException(r);
                            } else {
                                throw new RuntimeCamelException("Can't found the customer with uri " + path);
                            }
                        }
                    }
                    if ("updateCustomer".equals(operationName)) {
                        assertEquals("Get a wrong customer message header", "header1;header2",
                                inMessage.getHeader("test"));
                        String httpMethod = inMessage.getHeader(Exchange.HTTP_METHOD, String.class);
                        assertEquals("Get a wrong http method", "PUT", httpMethod);
                        Customer customer = inMessage.getBody(Customer.class);
                        assertNotNull("The customer should not be null.", customer);
                        // Now you can do what you want on the customer object
                        assertEquals("Get a wrong customer name.", "Mary", customer.getName());
                        // set the response back
                        exchange.getOut().setBody(Response.ok().build());
                    }

                }

            });
        }
    };
}

From source file:ch.javaee.basicMvc.web.controller.UserController.java

@RequestMapping(value = "/public/signup_confirm", method = RequestMethod.POST)
@Transactional//from   w  ww. j  a v a2 s.c  o  m
public String createUser(Model model, @ModelAttribute("user") @Valid UserForm form, BindingResult result,
        @RequestParam(value = "recaptcha_challenge_field", required = false) String challangeField,
        @RequestParam(value = "recaptcha_response_field", required = false) String responseField,
        ServletRequest servletRequest) {
    logger.debug("Enter: createUser");
    if (reCaptcha != null) {
        String remoteAdress = servletRequest.getRemoteAddr();
        ReCaptchaResponse reCaptchaResponse = reCaptcha.checkAnswer(remoteAdress, challangeField,
                responseField);
        if (!reCaptchaResponse.isValid()) {
            this.create(model);
            return "view/public/signup";
        }
    }
    if (!result.hasErrors()) {

        // check if email already exists
        if (userRepository.isEmailAlreadyExists(form.getEmail())) {
            FieldError fieldError = new FieldError("user", "email", "email already exists");
            result.addError(fieldError);
            return "view/public/signup";
        }
        User user = new User();
        Md5PasswordEncoder encoder = new Md5PasswordEncoder();
        user.setUsername(form.getUsername());
        user.setEmail(form.getEmail());
        user.setEnabled(false);

        user.setPassword(encoder.encodePassword(form.getPassword(), user.getEmail()));
        Role role = new Role();
        role.setUser(user);
        role.setRole(2);

        SecurityCode securityCode = new SecurityCode();
        securityCode.setUser(user);
        securityCode.setTimeRequest(new Date());
        securityCode.setTypeActivationEnum(TypeActivationEnum.NEW_ACCOUNT);
        securityCode.setCode(SecureUtility.generateRandomCode());
        user.setRole(role);
        user.setSecurityCode(securityCode);

        userRepository.saveUser(user);
        //securityCodeRepository.persist(securityCode);
        mailSenderService.sendAuthorizationMail(user, user.getSecurityCode());

    } else {
        logger.debug("signup error");
        this.create(model);
        return "view/public/signup";

    }
    logger.debug("Exit: createUser");
    return "view/public/mailSent";
}

From source file:com.google.sampling.experiential.server.WhitelistFilter.java

@Override
public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
        throws IOException, ServletException {
    User user = UserServiceFactory.getUserService().getCurrentUser();
    String email = user == null ? null : user.getEmail().toLowerCase();
    if (!isDevServer((HttpServletRequest) arg0) && (user == null)) {
        log.info("Error logging in from: " + arg0.getRemoteAddr() + " user: "
                + (user != null ? email : "not logged in"));

        HttpServletResponse resp = (HttpServletResponse) arg1;
        String loginUrl = UserServiceFactory.getUserService()
                .createLoginURL(((HttpServletRequest) arg0).getRequestURL().toString(), "google.com");
        resp.sendRedirect(loginUrl);// ww  w . j a  va2s. co  m
    } else if (!allowed(email)) {
        ((HttpServletResponse) arg1).sendError(HttpStatus.SC_FORBIDDEN);
    } else {
        log.info("Allowing user: " + email);
        arg2.doFilter(arg0, arg1);
    }
}

From source file:com.oakhole.auth.web.LoginController.java

@RequestMapping(method = RequestMethod.GET)
public String login(ServletRequest servletRequest) {
    ShiroDbRealm.ShiroUser shiroUser = (ShiroDbRealm.ShiroUser) SecurityUtils.getSubject().getPrincipal();
    if (shiroUser != null) {

        // //from   w w w  .java  2  s. co m
        SignLog signLog = new SignLog();
        signLog.setUsername(shiroUser.getLoginName());
        signLog.setSignTime(Calendars.getNow());
        signLog.setSignIp(servletRequest.getRemoteAddr());
        signLog.setSignType("web");
        signLogService.save(signLog);

        return "redirect:/";
    }
    return "login";
}

From source file:com.iisigroup.cap.base.aop.CapAuditLog4HandlerAdvice.java

private AuditLog loggedFunction(String TITLE, String targetName, Class clazz, Request params) {

    // ???( SysParm)
    String sysparmDisableData = sysProp.get(targetName + "." + DISABLE_TYPE);
    String dtype = CapString.trimNull(sysparmDisableData, DisableType.CANCEL.getCode());
    sysProp.put(targetName + "." + DISABLE_TYPE, dtype);
    if (DisableType.ALL.isEquals(dtype)) {
        logger.trace("{} {} DISABLE_AUDITLOG ALL!!", TITLE, targetName);
        return null;
    }/*from w  ww  .ja  v  a2 s.  c  om*/

    Authentication auth = SecurityContextHolder.getContext().getAuthentication();

    Method method = CapBeanUtil.findMethod(clazz, params.get(CapConstants.P_FORM_ACTION), (Class<?>) null);
    String action = null, function = null;
    boolean haveToAudit = false;
    if (method != null) {
        CapAuditLogAction auditLogAction = method.getAnnotation(CapAuditLogAction.class);

        action = (auditLogAction != null && auditLogAction.actionType() != null)
                ? auditLogAction.actionType().toString()
                : null;
        function = (auditLogAction != null && auditLogAction.functionCode() != null)
                ? auditLogAction.functionCode().getCode()
                : null;
        if (action != null && function != null) {
            haveToAudit = true;
        }
    }

    String uid = null, ipAddress = null;

    CapUserDetails user = CapSecurityContext.getUser();
    if (user != null) {
        uid = user.getUserId();
        // ipAddress = user.getIpAddress();
    } else {
        uid = auth.getPrincipal().toString();
    }

    if (CapString.isEmpty(ipAddress) && auth != null && auth.getDetails() instanceof WebAuthenticationDetails) {
        WebAuthenticationDetails details = (WebAuthenticationDetails) auth.getDetails();
        ipAddress = details.getRemoteAddress();
    }
    if (CapString.isEmpty(ipAddress)) {
        ServletRequest req = params.getServletRequest();
        ipAddress = req.getRemoteAddr();
    }

    AuditLog auditLog = null;
    if (haveToAudit) {
        auditLog = new AuditLog();
        auditLog.setId(UUIDGenerator.getUUID());
        auditLog.setUserId(uid);
        auditLog.setIpAddress(trimByLen(CapString.trimNull(ipAddress), 50));
        auditLog.setFunctionId(trimByLen(function, 20));
        auditLog.setAction(trimByLen(action.toLowerCase(), 20));
        // auditLog.setRemark(trimByLen(CapString.trimNull(params.toString()),
        // 50));

        long tstart = NumberUtils.toLong(CapString.trimNull(params.get(CapConstants.C_AUDITLOG_START_TS)));
        if (tstart > 0) {
            auditLog.setExecuteDate(new Timestamp(tstart));
            if (logger.isTraceEnabled()) {
                logger.trace("{} AuditLog={}", TITLE, auditLog);
            }
        }
    }
    return auditLog;
}

From source file:ru.org.linux.auth.CaptchaService.java

public void checkCaptcha(ServletRequest request, Errors errors) {
    String captchaChallenge = request.getParameter("recaptcha_challenge_field");
    String captchaResponse = request.getParameter("recaptcha_response_field");

    if (captchaChallenge == null || captchaResponse == null) {
        errors.reject(null, "   ");
        return;/*from  w  w w. j  a  va  2 s.  com*/
    }

    try {
        ReCaptchaResponse response = captcha.checkAnswer(request.getRemoteAddr(), captchaChallenge,
                captchaResponse);

        if (!response.isValid()) {
            errors.reject(null, "   ?");
        }
    } catch (ReCaptchaException e) {
        logger.warn("Unable to check captcha", e);

        errors.reject(null, "Unable to check captcha: " + e.getMessage());
    }
}