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:com.wisemapping.ncontroller.UsersController.java

private BindingResult validateRegistrationForm(@NotNull UserBean userBean, @NotNull HttpServletRequest request,
        @NotNull BindingResult bindingResult) {
    final UserValidator userValidator = new UserValidator();
    userValidator.setUserService(userService);
    userValidator.setCaptchaService(captchaService);
    userValidator.validate(userBean, bindingResult);

    // If captcha is enabled, generate it ...
    if (captchaEnabled) {
        final String challenge = request.getParameter("recaptcha_challenge_field");
        final String uresponse = request.getParameter("recaptcha_response_field");

        if (challenge != null && uresponse != null) {
            final String remoteAddr = request.getRemoteAddr();
            final ReCaptchaResponse reCaptchaResponse = captchaService.checkAnswer(remoteAddr, challenge,
                    uresponse);//w  ww. jav a2  s  .co  m

            if (!reCaptchaResponse.isValid()) {
                bindingResult.rejectValue("captcha", Messages.CAPTCHA_ERROR);
            }

        } else {
            bindingResult.rejectValue("captcha", Messages.CAPTCHA_LOADING_ERROR);
        }
    }
    return bindingResult;
}

From source file:com.sonymobile.jenkins.plugins.kerberossso.KerberosSSOFilter.java

/**
 * Filters every request made to the server to determine and set authentication of the user.
 * 1. Find out if the user is already authenticated (by checking the securityContext).
 * 2. Otherwise, authenticate the user from his Kerberos ticket and,
 * 3. Set him as authenticated by setting a new securityContext.
 * During the negotiation process used by Spnego, none of the filters after this one in the chain
 * will be allowed to execute.//from  w  w  w  . j a  v  a2  s  .  com
 *
 * @param request the Servlet request to serve
 * @param response the Servlet response to serve
 * @param chain the filter chain determining which filter will execute after ours.
 * @throws IOException if redirection goes wrong or if another filter in the chain fails.
 * @throws ServletException if the authentication fails.
 */
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    if ((!(request instanceof HttpServletRequest) || !(response instanceof HttpServletResponse))
            || containsBypassHeader(request)) {
        chain.doFilter(request, response);
        return;
    }

    HttpServletRequest httpRequest = (HttpServletRequest) request;
    String userContentPath = httpRequest.getContextPath() + "/userContent";

    if (httpRequest.getRequestURI().startsWith(userContentPath)) {
        chain.doFilter(request, response);
        return;
    }

    SpnegoHttpServletResponse spnegoHttpResponse = new SpnegoHttpServletResponse(
            (HttpServletResponse) response);

    if (PluginImpl.getInstance().isRedirectEnabled()
            && !httpRequest.getLocalAddr().equals(httpRequest.getRemoteAddr())) {
        // If Local and Remote address is the same, the user is Localhost and shouldn't be redirected.

        String requestedDomain = new URL(httpRequest.getRequestURL().toString()).getHost();
        String requestedURL = httpRequest.getRequestURL().toString();
        if (!requestedDomain.toLowerCase().contains(PluginImpl.getInstance().getRedirect().toLowerCase())) {

            String redirect = requestedURL.replaceFirst(requestedDomain,
                    requestedDomain + "." + PluginImpl.getInstance().getRedirect());
            spnegoHttpResponse.sendRedirect(redirect);
        }
    }

    // A user is "always" authenticated by Jenkins as anonymous when not authenticated in any other way.
    if (SecurityContextHolder.getContext().getAuthentication() == null
            || !SecurityContextHolder.getContext().getAuthentication().isAuthenticated()
            || Functions.isAnonymous()) {
        Functions.advertiseHeaders((HttpServletResponse) response); //Adds headers for CLI

        Principal principal;

        try {
            principal = authenticator.authenticate(httpRequest, spnegoHttpResponse);
        } catch (LoginException e) {
            logger.log(Level.WARNING, "Failed to fetch spnegoPrincipal name for user");
            chain.doFilter(request, spnegoHttpResponse);
            return;
        }

        // Expecting negotiation
        if (principal == null) {
            return;
        }

        String principalName = principal.getName();

        if (principalName.contains("@")) {
            principalName = principalName.substring(0, principalName.indexOf("@"));
        }

        try {
            SecurityRealm realm = Jenkins.getInstance().getSecurityRealm();
            UserDetails userDetails = realm.loadUserByUsername(principalName);
            Authentication authToken = new UsernamePasswordAuthenticationToken(userDetails.getUsername(),
                    userDetails.getPassword(), userDetails.getAuthorities());

            ACL.impersonate(authToken);
            if (Jenkins.getVersion().isNewerThan(new VersionNumber("1.568"))) {
                try {
                    Method fireLoggedIn = SecurityListener.class.getMethod("fireLoggedIn", String.class);
                    fireLoggedIn.invoke(null, userDetails.getUsername());
                } catch (Exception e) {
                    logger.log(Level.WARNING, "Failed to invoke fireLoggedIn method", e);
                }
            }
            logger.log(Level.FINE, "Authenticated user {0}", userDetails.getUsername());
        } catch (UsernameNotFoundException e) {
            logger.log(Level.WARNING, "Username {0} not registered by Jenkins", principalName);
        } catch (NullPointerException e) {
            logger.log(Level.WARNING, "User authentication failed");
            e.printStackTrace();
        } catch (DataAccessException e) {
            logger.log(Level.WARNING, "No access to user database");
            e.printStackTrace();
        }
    }

    chain.doFilter(request, response);
}

From source file:be.fedict.eid.applet.service.impl.handler.ClientEnvironmentMessageHandler.java

public Object handleMessage(ClientEnvironmentMessage message, Map<String, String> httpHeaders,
        HttpServletRequest request, HttpSession session) throws ServletException {
    SecureClientEnvironmentService secureClientEnvService = this.secureClientEnvServiceLocator.locateService();
    if (null == secureClientEnvService) {
        throw new ServletException("no secure client env service configured");
    }//  ww w  .j a  v a 2  s  . co  m
    String remoteAddress = request.getRemoteAddr();
    Integer sslKeySize = (Integer) request.getAttribute("javax.servlet.request.key_size");
    String userAgent = httpHeaders.get("user-agent");
    String sslCipherSuite = (String) request.getAttribute("javax.servlet.request.cipher_suite");
    try {
        secureClientEnvService.checkSecureClientEnvironment(message.javaVersion, message.javaVendor,
                message.osName, message.osArch, message.osVersion, userAgent, message.navigatorAppName,
                message.navigatorAppVersion, message.navigatorUserAgent, remoteAddress, sslKeySize,
                sslCipherSuite, message.readerList);
    } catch (InsecureClientEnvironmentException e) {
        return new InsecureClientMessage(e.isWarnOnly());
    }
    if (this.changePin || this.unblockPin) {
        AdministrationMessage administrationMessage = new AdministrationMessage(this.changePin, this.unblockPin,
                this.logoff, this.removeCard, this.requireSecureReader);
        return administrationMessage;
    }
    SignatureService signatureService = this.signatureServiceLocator.locateService();
    if (null != signatureService) {
        // TODO DRY refactor: is a copy-paste from HelloMessageHandler
        String filesDigestAlgo = signatureService.getFilesDigestAlgorithm();
        if (null != filesDigestAlgo) {
            LOG.debug("files digest algo: " + filesDigestAlgo);
            FilesDigestRequestMessage filesDigestRequestMessage = new FilesDigestRequestMessage();
            filesDigestRequestMessage.digestAlgo = filesDigestAlgo;
            return filesDigestRequestMessage;
        }
        if (true == this.includeCertificates) {
            LOG.debug("include signing certificate chain during pre-sign");
            IdentityIntegrityService identityIntegrityService = this.identityIntegrityServiceLocator
                    .locateService();
            boolean includeIntegrityData = null != identityIntegrityService;
            IdentityService identityService = this.identityServiceLocator.locateService();
            boolean includeIdentity;
            boolean includeAddress;
            boolean includePhoto;
            if (null != identityService) {
                IdentityRequest identityRequest = identityService.getIdentityRequest();
                includeIdentity = identityRequest.includeIdentity();
                includeAddress = identityRequest.includeAddress();
                includePhoto = identityRequest.includePhoto();
            } else {
                includeIdentity = this.includeIdentity;
                includeAddress = this.includeAddress;
                includePhoto = this.includePhoto;
            }
            RequestContext requestContext = new RequestContext(session);
            requestContext.setIncludeIdentity(includeIdentity);
            requestContext.setIncludeAddress(includeAddress);
            requestContext.setIncludePhoto(includePhoto);
            SignCertificatesRequestMessage signCertificatesRequestMessage = new SignCertificatesRequestMessage(
                    includeIdentity, includeAddress, includePhoto, includeIntegrityData);
            return signCertificatesRequestMessage;
        }

        DigestInfo digestInfo;
        try {
            digestInfo = signatureService.preSign(null, null);
        } catch (NoSuchAlgorithmException e) {
            throw new ServletException("no such algo: " + e.getMessage(), e);
        }

        // also save it in the session for later verification
        SignatureDataMessageHandler.setDigestValue(digestInfo.digestValue, digestInfo.digestAlgo, session);

        IdentityService identityService = this.identityServiceLocator.locateService();
        boolean removeCard;
        if (null != identityService) {
            IdentityRequest identityRequest = identityService.getIdentityRequest();
            removeCard = identityRequest.removeCard();
        } else {
            removeCard = this.removeCard;
        }

        SignRequestMessage signRequestMessage = new SignRequestMessage(digestInfo.digestValue,
                digestInfo.digestAlgo, digestInfo.description, this.logoff, removeCard,
                this.requireSecureReader);
        return signRequestMessage;
    }
    AuthenticationService authenticationService = this.authenticationServiceLocator.locateService();
    if (null != authenticationService) {
        byte[] challenge = AuthenticationChallenge.generateChallenge(session);
        IdentityIntegrityService identityIntegrityService = this.identityIntegrityServiceLocator
                .locateService();
        boolean includeIntegrityData = null != identityIntegrityService;
        boolean includeIdentity;
        boolean includeAddress;
        boolean includePhoto;
        boolean includeCertificates;
        boolean removeCard;
        IdentityService identityService = this.identityServiceLocator.locateService();
        if (null != identityService) {
            IdentityRequest identityRequest = identityService.getIdentityRequest();
            includeIdentity = identityRequest.includeIdentity();
            includeAddress = identityRequest.includeAddress();
            includePhoto = identityRequest.includePhoto();
            includeCertificates = identityRequest.includeCertificates();
            removeCard = identityRequest.removeCard();
        } else {
            includeIdentity = this.includeIdentity;
            includeAddress = this.includeAddress;
            includePhoto = this.includePhoto;
            includeCertificates = this.includeCertificates;
            removeCard = this.removeCard;
        }
        RequestContext requestContext = new RequestContext(session);
        requestContext.setIncludeIdentity(includeIdentity);
        requestContext.setIncludeAddress(includeAddress);
        requestContext.setIncludePhoto(includePhoto);
        requestContext.setIncludeCertificates(includeCertificates);

        String transactionMessage = null;
        SecureCardReaderService secureCardReaderService = this.secureCardReaderServiceLocator.locateService();
        if (null != secureCardReaderService) {
            transactionMessage = secureCardReaderService.getTransactionMessage();
            if (null != transactionMessage
                    && transactionMessage.length() > SecureCardReaderService.TRANSACTION_MESSAGE_MAX_SIZE) {
                transactionMessage = transactionMessage.substring(0,
                        SecureCardReaderService.TRANSACTION_MESSAGE_MAX_SIZE);
            }
            LOG.debug("transaction message: " + transactionMessage);
        }
        requestContext.setTransactionMessage(transactionMessage);

        AuthenticationRequestMessage authenticationRequestMessage = new AuthenticationRequestMessage(challenge,
                this.includeHostname, this.includeInetAddress, this.logoff, this.preLogoff, removeCard,
                this.sessionIdChannelBinding, this.serverCertificateChannelBinding, includeIdentity,
                includeCertificates, includeAddress, includePhoto, includeIntegrityData,
                this.requireSecureReader, transactionMessage);
        return authenticationRequestMessage;
    } else {
        IdentityIntegrityService identityIntegrityService = this.identityIntegrityServiceLocator
                .locateService();
        boolean includeIntegrityData = null != identityIntegrityService;
        PrivacyService privacyService = this.privacyServiceLocator.locateService();
        String identityDataUsage;
        if (null != privacyService) {
            String clientLanguage = HelloMessageHandler.getClientLanguage(session);
            identityDataUsage = privacyService.getIdentityDataUsage(clientLanguage);
        } else {
            identityDataUsage = null;
        }
        boolean includeAddress;
        boolean includePhoto;
        boolean includeCertificates;
        boolean removeCard;
        IdentityService identityService = this.identityServiceLocator.locateService();
        if (null != identityService) {
            IdentityRequest identityRequest = identityService.getIdentityRequest();
            includeAddress = identityRequest.includeAddress();
            includePhoto = identityRequest.includePhoto();
            includeCertificates = identityRequest.includeCertificates();
            removeCard = identityRequest.removeCard();
        } else {
            includeAddress = this.includeAddress;
            includePhoto = this.includePhoto;
            includeCertificates = this.includeCertificates;
            removeCard = this.removeCard;
        }
        RequestContext requestContext = new RequestContext(session);
        requestContext.setIncludeAddress(includeAddress);
        requestContext.setIncludePhoto(includePhoto);
        requestContext.setIncludeCertificates(includeCertificates);
        IdentificationRequestMessage responseMessage = new IdentificationRequestMessage(includeAddress,
                includePhoto, includeIntegrityData, includeCertificates, removeCard, identityDataUsage);
        return responseMessage;
    }
}

From source file:com.yahoo.glimmer.web.QueryController.java

@RequestMapping(value = { "/query", "/v1/search" }, method = RequestMethod.GET)
public Map<String, ?> query(@ModelAttribute(INDEX_KEY) RDFIndex index, @Valid QueryCommand command,
        HttpServletRequest httpServletRequest)
        throws QueryParserException, QueryBuilderVisitorException, IOException {
    if (index == null) {
        throw new HttpMessageConversionException("No index given.");
    }/* w ww  . j a  v a  2 s .co m*/

    String query = command.getQuery();
    if (query == null || query.isEmpty()) {
        throw new HttpMessageConversionException("No query given.");
    }

    QueryResult result;
    if (queryFilter != null && queryFilter.filter(query)) {
        LOGGER.info("Blocking query:" + query + " from address:" + httpServletRequest.getRemoteAddr());
        throw new HttpMessageConversionException("Bad query given.");
    }

    query = decodeEntities(command.getQuery()).trim();
    query = encodeResources(index, query);

    Query parsedQuery;
    switch (command.getType()) {
    case MG4J:
        parsedQuery = new SimpleParser().parse(query);
        result = querier.doQuery(index, parsedQuery, command.getPageStart(), command.getPageSize(),
                command.isDeref(), defaultObjectLengthLimit);
        break;
    case YAHOO:
        if (query.startsWith(DOC_PSEUDO_FIELD)) {
            String idOrSubject = query.substring(DOC_PSEUDO_FIELD.length());
            Long id;
            if (Character.isDigit(idOrSubject.charAt(0))) {
                try {
                    id = Long.parseLong(idOrSubject);
                } catch (NumberFormatException e) {
                    throw new IllegalArgumentException(
                            "Query " + query + " failed to parse as a numeric subject ID(int)");
                }
            } else {
                id = index.getSubjectId(idOrSubject);
                if (id == null) {
                    throw new IllegalArgumentException("subject " + idOrSubject + " is not in collection.");
                }
            }
            result = querier.doQueryForDocId(index, id, command.isDeref(), null);
        } else {
            try {
                parsedQuery = index.getParser().parse(query);
            } catch (QueryParserException e) {
                throw new IllegalArgumentException("Query failed to parse:" + query, e);
            }
            result = querier.doQuery(index, parsedQuery, command.getPageStart(), command.getPageSize(),
                    command.isDeref(), defaultObjectLengthLimit);
        }
        break;
    default:
        throw new IllegalArgumentException("No query type given.");
    }

    return Collections.singletonMap(OBJECT_KEY, result);
}

From source file:org.meerkat.ws.MeerkatWebService.java

/**
 * getRequestClientIP/*w  ww.j  a  va  2s . c  om*/
 * @return
 */
public final String getRequestClientIP() {
    MessageContext mc = wsContext.getMessageContext();
    HttpServletRequest req = null;
    String remoteAddr = "";
    try {
        req = (HttpServletRequest) mc.get(MessageContext.SERVLET_REQUEST);
        remoteAddr = req.getRemoteAddr();
    } catch (Exception e) {
        log.warn("Unable to get client request remote address. " + e.getMessage());
        return "";
    }
    return remoteAddr;
}

From source file:com.wisemapping.mail.NotificationService.java

private void sendNotification(@NotNull Map<String, String> model, @Nullable User user,
        @NotNull HttpServletRequest request) {
    model.put("fullName", (user != null ? user.getFullName() : "'anonymous'"));
    final String userEmail = user != null ? user.getEmail() : "'anonymous'";

    model.put("email", userEmail);
    model.put("userAgent", request.getHeader(SupportedUserAgent.USER_AGENT_HEADER));
    model.put("server", request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort());
    model.put("requestURI", request.getRequestURI());
    model.put("method", request.getMethod());
    model.put("remoteAddress", request.getRemoteAddr());

    try {/*from   w  ww. j a va 2s .  com*/
        final String errorReporterEmail = mailer.getErrorReporterEmail();
        if (errorReporterEmail != null && !errorReporterEmail.isEmpty()) {

            if (!notificationFilter.hasBeenSend(userEmail, model)) {
                mailer.sendEmail(mailer.getServerSenderEmail(), errorReporterEmail,
                        "[WiseMapping] Bug from '" + (user != null ? user.getEmail() + "'" : "'anonymous'"),
                        model, "errorNotification.vm");
            }
        }
    } catch (Exception e) {
        handleException(e);
    }
}

From source file:org.spirit.spring.BotListRubyDAOHandler.java

/**
 * To call, use://from  www . jav  a  2  s  .  co m
 * 
 */
public void auditLogPage(HttpServletRequest request, String curPage) {
    if (userVisitAudit != null) {
        BotListUserVisitLog link = new BotListUserVisitLog();
        link.setRequestUri(request.getRequestURI());
        link.setRequestPage(curPage);
        link.setHost(request.getHeader("host"));
        link.setReferer(request.getHeader("referer"));
        link.setRemoteHost(request.getRemoteAddr());
        link.setUserAgent(request.getHeader("user-agent"));
        userVisitAudit.createVisitLog(link);
    }
}

From source file:net.naijatek.myalumni.framework.struts.MyAlumniDispatchAction.java

/**
 * Get current IP Address//from  w w  w  . j  a v  a 2 s  .  co  m
 * 
 * @param request
 * @return
 */
protected String getCurrentIPAddress(final HttpServletRequest request) {
    return request.getRemoteAddr();
}

From source file:org.imsglobal.lti2.LTI2Servlet.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {/*w ww  .  j ava  2  s  .  co  m*/
        doRequest(request, response);
    } catch (Exception e) {
        String ipAddress = request.getRemoteAddr();
        String uri = request.getRequestURI();
        M_log.log(Level.WARNING, "General LTI2 Failure URI=" + uri + " IP=" + ipAddress);
        e.printStackTrace();
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        doErrorJSON(request, response, null, "General failure", e);
    }
}

From source file:com.roncoo.controller.BaseController.java

/**
 * ?IP?/*  w  w w .  j  a v  a  2 s.c o  m*/
 * 
 * @return
 */
public String getIpAddr(HttpServletRequest request) {
    String ipAddress = null;
    ipAddress = request.getHeader("x-forwarded-for");
    if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
        ipAddress = request.getHeader("Proxy-Client-IP");
    }
    if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
        ipAddress = request.getHeader("WL-Proxy-Client-IP");
    }
    if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
        ipAddress = request.getRemoteAddr();
        if (ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")) {
            // ????IP
            InetAddress inet = null;
            try {
                inet = InetAddress.getLocalHost();
            } catch (UnknownHostException e) {
                e.printStackTrace();
            }
            ipAddress = inet.getHostAddress();
        }

    }

    // ?IPIP,IP','
    if (ipAddress != null && ipAddress.length() > 15) {
        if (ipAddress.indexOf(",") > 0) {
            ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
        }
    }
    return ipAddress;
}