Example usage for javax.servlet.http HttpServletRequest getRemoteHost

List of usage examples for javax.servlet.http HttpServletRequest getRemoteHost

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest getRemoteHost.

Prototype

public String getRemoteHost();

Source Link

Document

Returns the fully qualified name of the client or the last proxy that sent the request.

Usage

From source file:org.josso.gateway.signon.SignonBaseAction.java

/**
 * This method knows how to build a SSO Context based on HTTP state: request, session, etc.
 * Some state is stored as sesion attributes
 *
 * @see #storeSSOParameters(javax.servlet.http.HttpServletRequest)
 */// w w  w  .ja  va2  s .  c o m
protected void prepareContext(HttpServletRequest request) throws SSOException, SSOAuthenticationException {

    // We need to store SSO parameters
    storeSSOParameters(request);

    // Use gateway to select a security domain
    SSOGateway gwy = getSSOGateway();

    // The first thing to do is to create the context and publish the security domain !!!
    MutableSSOContext ctx = (MutableSSOContext) gwy.prepareSSOContext(new SSORequestImpl(request));
    ctx.setUserLocation(request.getRemoteHost());

    // Store current SD name in session
    request.getSession().setAttribute(org.josso.gateway.signon.Constants.KEY_JOSSO_SECURITY_DOMAIN_NAME,
            ctx.getSecurityDomain().getName());
    if (logger.isDebugEnabled())
        logger.debug("[prepareContext()] Storing security domain name in session ["
                + KEY_JOSSO_SECURITY_DOMAIN_NAME + "] : " + ctx.getSecurityDomain().getName() + " ("
                + request.getSession().getId() + ")");

    // SSO Session
    String sessionId = getJossoSessionId(request);
    if (sessionId != null && !"".equals(sessionId)) {
        try {
            // If session is not valid, no current session will be available in context.
            ctx.setCurrentSession(gwy.findSession(sessionId));
        } catch (NoSuchSessionException e) {
            if (logger.isDebugEnabled())
                logger.debug("NoSuchSessionException : " + sessionId + " " + e.getMessage());
        }
    }

    // TODO : Detect Authentication scheme when user is already logged ...!
    String scheme = getSchemeName(request);
    logger.debug("Using authentication scheme : " + scheme);

    ctx.setScheme(scheme);

}

From source file:org.jasig.cas.client.integration.atlassian.Confluence35CasAuthenticator.java

public Principal getUser(final HttpServletRequest request, final HttpServletResponse response) {
    Principal existingUser = getUserFromSession(request);
    if (existingUser != null) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Session found; user already logged in.");
        }/*  w w  w  .j a va 2 s . c  o  m*/
        LoginReason.OK.stampRequestResponse(request, response);
        return existingUser;
    }

    final HttpSession session = request.getSession();
    final Assertion assertion = (Assertion) session.getAttribute(AbstractCasFilter.CONST_CAS_ASSERTION);

    if (assertion != null) {
        final String username = assertion.getPrincipal().getName();
        final Principal user = getUser(username);
        final String remoteIP = request.getRemoteAddr();
        final String remoteHost = request.getRemoteHost();

        if (user != null) {
            putPrincipalInSessionContext(request, user);
            getElevatedSecurityGuard().onSuccessfulLoginAttempt(request, username);
            // Firing this event is necessary to ensure the user's personal information is initialised correctly.
            getEventPublisher().publish(
                    new LoginEvent(this, username, request.getSession().getId(), remoteHost, remoteIP));
            LoginReason.OK.stampRequestResponse(request, response);
            if (LOG.isDebugEnabled()) {
                LOG.debug("Logging in [" + username + "] from CAS.");
            }
        } else {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Failed logging [" + username + "] from CAS.");
            }
            getElevatedSecurityGuard().onFailedLoginAttempt(request, username);
            getEventPublisher().publish(
                    new LoginFailedEvent(this, username, request.getSession().getId(), remoteHost, remoteIP));
        }
        return user;
    }

    return super.getUser(request, response);
}

From source file:org.apache.nifi.web.api.DataTransferResource.java

private Peer constructPeer(final HttpServletRequest req, final InputStream inputStream,
        final OutputStream outputStream, final String portId, final String transactionId) {
    String clientHostName = req.getRemoteHost();
    try {/*from w  w  w  . jav  a2s .c o  m*/
        // req.getRemoteHost returns IP address, try to resolve hostname to be consistent with RAW protocol.
        final InetAddress clientAddress = InetAddress.getByName(clientHostName);
        clientHostName = clientAddress.getHostName();
    } catch (UnknownHostException e) {
        logger.info("Failed to resolve client hostname {}, due to {}", clientHostName, e.getMessage());
    }
    final int clientPort = req.getRemotePort();

    final PeerDescription peerDescription = new PeerDescription(clientHostName, clientPort, req.isSecure());

    final NiFiUser user = NiFiUserUtils.getNiFiUser();
    final String userDn = user == null ? null : user.getIdentity();
    final HttpServerCommunicationsSession commSession = new HttpServerCommunicationsSession(inputStream,
            outputStream, transactionId, userDn);

    boolean useCompression = false;
    final String useCompressionStr = req.getHeader(HANDSHAKE_PROPERTY_USE_COMPRESSION);
    if (!isEmpty(useCompressionStr) && Boolean.valueOf(useCompressionStr)) {
        useCompression = true;
    }

    final String requestExpiration = req.getHeader(HANDSHAKE_PROPERTY_REQUEST_EXPIRATION);
    final String batchCount = req.getHeader(HANDSHAKE_PROPERTY_BATCH_COUNT);
    final String batchSize = req.getHeader(HANDSHAKE_PROPERTY_BATCH_SIZE);
    final String batchDuration = req.getHeader(HANDSHAKE_PROPERTY_BATCH_DURATION);

    commSession.putHandshakeParam(HandshakeProperty.PORT_IDENTIFIER, portId);
    commSession.putHandshakeParam(HandshakeProperty.GZIP, String.valueOf(useCompression));

    if (!isEmpty(requestExpiration)) {
        commSession.putHandshakeParam(REQUEST_EXPIRATION_MILLIS, requestExpiration);
    }
    if (!isEmpty(batchCount)) {
        commSession.putHandshakeParam(BATCH_COUNT, batchCount);
    }
    if (!isEmpty(batchSize)) {
        commSession.putHandshakeParam(BATCH_SIZE, batchSize);
    }
    if (!isEmpty(batchDuration)) {
        commSession.putHandshakeParam(BATCH_DURATION, batchDuration);
    }

    if (peerDescription.isSecure()) {
        final NiFiUser nifiUser = NiFiUserUtils.getNiFiUser();
        logger.debug("initiating peer, nifiUser={}", nifiUser);
        commSession.setUserDn(nifiUser.getIdentity());
    }

    // TODO: Followed how SocketRemoteSiteListener define peerUrl and clusterUrl, but it can be more meaningful values, especially for clusterUrl.
    final String peerUrl = "nifi://" + clientHostName + ":" + clientPort;
    final String clusterUrl = "nifi://localhost:" + req.getLocalPort();

    return new Peer(peerDescription, commSession, peerUrl, clusterUrl);
}

From source file:eu.eidas.springsecu.EidasAccessDeniedHandler.java

@Override
public void handle(HttpServletRequest request, HttpServletResponse response,
        AccessDeniedException accessDeniedException) throws IOException, ServletException {
    logger.debug("Arrive dans handle error");
    EIDASAuthnResponse authnResponse = null;
    SAMLResponse = request.getParameter("SAMLresponse");
    if (SAMLResponse == null) {
        throw new IOException("Saml Response is null");
    }/*from www. j  a v a2  s  . co m*/
    if (SAMLResponse.isEmpty()) {
        throw new IOException("Saml Response is empty");
    }
    //Decodes SAML Response
    byte[] decSamlToken = EIDASUtil.decodeSAMLToken(SAMLResponse);

    //Get SAMLEngine instance

    try {
        EIDASSAMLEngine engine = SPUtil.createSAMLEngine(Constants.SP_CONF);
        //validate SAML Token
        authnResponse = engine.validateEIDASAuthnResponse(decSamlToken, request.getRemoteHost(), 0);

    } catch (EIDASSAMLEngineException e) {
        logger.error(e.getMessage());
        if (StringUtils.isEmpty(e.getErrorDetail())) {
            throw new IOException(SAML_VALIDATION_ERROR, e);
        } else {
            throw new IOException(SAML_VALIDATION_ERROR, e);
        }
    }

    if (authnResponse.isFail()) {
        throw new IOException("Saml Response is fail" + authnResponse.getMessage());
    } else {
        request.setAttribute("assertions", authnResponse.getAsserts());
        RequestDispatcher dispatch;
        dispatch = request.getRequestDispatcher("/saml");
        logger.debug("Avant forward vers saml");
        dispatch.forward(request, response);
    }

}

From source file:org.apache.cocoon.servlet.DebugFilter.java

/**
 * Log debug information about the current environment.
 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
 *///w w w .  jav a  2  s  .  c o m
public void doFilter(ServletRequest req, ServletResponse res, FilterChain filterChain)
        throws IOException, ServletException {
    // we don't do debug msgs if this is not a http servlet request
    if (!(req instanceof HttpServletRequest)) {
        filterChain.doFilter(req, res);
        return;
    }
    try {
        ++activeRequestCount;
        final HttpServletRequest request = (HttpServletRequest) req;

        if (getLogger().isDebugEnabled()) {
            final StringBuffer msg = new StringBuffer();

            msg.append("DEBUGGING INFORMATION:").append(lineSeparator);
            msg.append("REQUEST: ").append(request.getRequestURI()).append(lineSeparator).append(lineSeparator);
            msg.append("CONTEXT PATH: ").append(request.getContextPath()).append(lineSeparator);
            msg.append("SERVLET PATH: ").append(request.getServletPath()).append(lineSeparator);
            msg.append("PATH INFO: ").append(request.getPathInfo()).append(lineSeparator).append(lineSeparator);

            msg.append("REMOTE HOST: ").append(request.getRemoteHost()).append(lineSeparator);
            msg.append("REMOTE ADDRESS: ").append(request.getRemoteAddr()).append(lineSeparator);
            msg.append("REMOTE USER: ").append(request.getRemoteUser()).append(lineSeparator);
            msg.append("REQUEST SESSION ID: ").append(request.getRequestedSessionId()).append(lineSeparator);
            msg.append("REQUEST PREFERRED LOCALE: ").append(request.getLocale().toString())
                    .append(lineSeparator);
            msg.append("SERVER HOST: ").append(request.getServerName()).append(lineSeparator);
            msg.append("SERVER PORT: ").append(request.getServerPort()).append(lineSeparator)
                    .append(lineSeparator);

            msg.append("METHOD: ").append(request.getMethod()).append(lineSeparator);
            msg.append("CONTENT LENGTH: ").append(request.getContentLength()).append(lineSeparator);
            msg.append("PROTOCOL: ").append(request.getProtocol()).append(lineSeparator);
            msg.append("SCHEME: ").append(request.getScheme()).append(lineSeparator);
            msg.append("AUTH TYPE: ").append(request.getAuthType()).append(lineSeparator).append(lineSeparator);
            msg.append("CURRENT ACTIVE REQUESTS: ").append(activeRequestCount).append(lineSeparator);

            // log all of the request parameters
            final Enumeration e = request.getParameterNames();

            msg.append("REQUEST PARAMETERS:").append(lineSeparator).append(lineSeparator);

            while (e.hasMoreElements()) {
                String p = (String) e.nextElement();

                msg.append("PARAM: '").append(p).append("' ").append("VALUES: '");
                String[] params = request.getParameterValues(p);
                for (int i = 0; i < params.length; i++) {
                    msg.append("[" + params[i] + "]");
                    if (i != (params.length - 1)) {
                        msg.append(", ");
                    }
                }

                msg.append("'").append(lineSeparator);
            }

            // log all of the header parameters
            final Enumeration e2 = request.getHeaderNames();

            msg.append("HEADER PARAMETERS:").append(lineSeparator).append(lineSeparator);

            while (e2.hasMoreElements()) {
                String p = (String) e2.nextElement();

                msg.append("PARAM: '").append(p).append("' ").append("VALUES: '");
                Enumeration e3 = request.getHeaders(p);
                while (e3.hasMoreElements()) {
                    msg.append("[" + e3.nextElement() + "]");
                    if (e3.hasMoreElements()) {
                        msg.append(", ");
                    }
                }

                msg.append("'").append(lineSeparator);
            }

            msg.append(lineSeparator).append("SESSION ATTRIBUTES:").append(lineSeparator).append(lineSeparator);

            // log all of the session attributes
            final HttpSession session = ((HttpServletRequest) req).getSession(false);
            if (session != null) {
                // Fix bug #12139: Session can be modified while still
                // being enumerated here
                synchronized (session) {
                    final Enumeration se = session.getAttributeNames();
                    while (se.hasMoreElements()) {
                        String p = (String) se.nextElement();
                        msg.append("PARAM: '").append(p).append("' ").append("VALUE: '")
                                .append(session.getAttribute(p)).append("'").append(lineSeparator);
                    }
                }
            }
            getLogger().debug(msg.toString());
        }

        // Delegate
        filterChain.doFilter(request, res);
    } finally {
        --activeRequestCount;
    }
}

From source file:org.hoteia.qalingo.core.security.fo.component.SimpleUrlAuthenticationSuccessHandler.java

@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
        Authentication authentication) throws IOException, ServletException {

    try {/*from   w  ww. j  a va2  s  . c  om*/
        final RequestData requestData = requestUtil.getRequestData(request);
        // CUSTOMER
        Customer customer = customerService.getCustomerByLoginOrEmail(authentication.getName());

        // TODO : move the CustomerConnectionLog Save in an async process : save cost time
        // Persit the new CustomerConnectionLog
        CustomerConnectionLog customerConnectionLog = new CustomerConnectionLog();
        customerConnectionLog.setCustomerId(customer.getId());
        customerConnectionLog.setLoginDate(new Date());
        customerConnectionLog.setAppCode(Constants.APP_NAME_FO_MCOMMERCE_CODE);
        customerConnectionLog.setHost(request.getRemoteHost());

        customerConnectionLog.setPublicAddress(request.getHeader(Constants.X_FORWARDED_FOR));
        customerConnectionLog.setPrivateAddress(requestUtil.getRemoteAddr(request));

        customer.getConnectionLogs().add(customerConnectionLog);
        customerConnectionLogService.saveOrUpdateCustomerConnectionLog(customerConnectionLog);

        requestUtil.updateCurrentCustomer(request, customer);

        // UPDATE CART WITH THE CUSTOMER INFORMATIONS
        //            webManagementService.linkAndUpdateCartWithCustomer(requestData, customer);

        setUseReferer(false);
        String targetUrl = urlService.generateRedirectUrl(FoUrls.PERSONAL_DETAILS,
                requestUtil.getRequestData(request));
        String lastUrl = requestUtil.getCurrentRequestUrlNotSecurity(request);

        // SANITY CHECK
        if (StringUtils.isNotEmpty(lastUrl)) {
            targetUrl = lastUrl;
        }

        if (lastUrl.contains("cart-") || lastUrl.contains("checkout-")) {
            // STAY ON THE CHECKOUT - REDIRECT ON THE ADDRESSES PAGES
            targetUrl = urlService.generateRedirectUrl(FoUrls.CART_AUTH, requestUtil.getRequestData(request));
        }

        setDefaultTargetUrl(targetUrl);

        redirectStrategy.sendRedirect(request, response, targetUrl);

    } catch (Exception e) {
        logger.error("", e);
    }

}

From source file:Properties.java

public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    PrintWriter out = resp.getWriter();
    out.println("<html>");
    out.println("<head>");
    out.println("<title>My First Servlet</title>");
    out.println("</head>");
    out.println("<h2><center>");
    out.println("Information About You</center></h2>");
    out.println("<br>");

    out.println("<center><table border>");
    out.println("<tr>");
    out.println("<td>Method</td>");
    out.println("<td>" + req.getMethod() + "</td>");
    out.println("</tr>");

    out.println("<tr>");
    out.println("<td>User</td>");
    out.println("<td>" + req.getRemoteUser() + "</td>");
    out.println("</tr>");

    out.println("<tr>");
    out.println("<td>Client</td>");
    out.println("<td>" + req.getRemoteHost() + "</td>");
    out.println("</tr>");

    out.println("<tr>");
    out.println("<td>Protocol</td>");
    out.println("<td>" + req.getProtocol() + "</td>");
    out.println("</tr>");

    java.util.Enumeration e = req.getParameterNames();
    while (e.hasMoreElements()) {
        String name = (String) e.nextElement();
        out.println("<tr>");
        out.println("<td>Parameter '" + name + "'</td>");
        out.println("<td>" + req.getParameter(name) + "</td>");
        out.println("</tr>");
    }/*w w  w.  j  av a  2s  .c om*/

    out.println("</table></center><br><hr><br>");

    out.println("<h2><center>");
    out.println("Server Properties</center></h2>");
    out.println("<br>");

    out.println("<center><table border width=80%>");

    java.util.Properties props = System.getProperties();
    e = props.propertyNames();

    while (e.hasMoreElements()) {
        String name = (String) e.nextElement();
        out.println("<tr>");
        out.println("<td>" + name + "</td>");
        out.println("<td>" + props.getProperty(name) + "</td>");
        out.println("</tr>");
    }
    out.println("</table></center>");

    out.println("</html>");
    out.flush();
}

From source file:com.netspective.sparx.security.HttpLoginManager.java

protected void registerLogout(HttpServletValueContext hsvc, MutableAuthenticatedUser user) {
    hsvc.getProject().broadcastActivity(new HttpLogoutActivity(hsvc.getProject(), hsvc));

    user.registerLogout(hsvc, AuthenticatedUserLogoutType.USER_REQUEST);
    activeUsers.remove(user);/*from   w w  w .  ja  va 2 s.  co m*/

    if (log.isInfoEnabled()) {
        HttpServletRequest req = hsvc.getHttpRequest();
        String userId = user.getUserId().toString();
        StringBuffer info = new StringBuffer();
        info.append("logout");
        info.append(MONITOR_ENTRY_FIELD_SEPARATOR);
        info.append(userId);
        info.append(MONITOR_ENTRY_FIELD_SEPARATOR);
        info.append(req.getRemoteUser());
        info.append(MONITOR_ENTRY_FIELD_SEPARATOR);
        info.append(req.getRemoteHost());
        info.append(MONITOR_ENTRY_FIELD_SEPARATOR);
        info.append(req.getRemoteAddr());
        info.append(MONITOR_ENTRY_FIELD_SEPARATOR);
        BitSet perms = user.getUserPermissions();
        info.append(perms != null ? user.getUserPermissions().toString() : "{}");
        info.append(MONITOR_ENTRY_FIELD_SEPARATOR);
        String[] roles = user.getUserRoleNames();
        if (roles != null) {
            for (int r = 0; r < roles.length; r++) {
                if (r > 0)
                    info.append(MONITOR_ENTRY_FIELD_SEPARATOR);
                info.append(roles[r]);
            }
        }
        log.info(info);
    }
}

From source file:org.jets3t.servlets.gatekeeper.GatekeeperServlet.java

/**
 * Handles POST requests that contain Gatekeeper messages encoded as POST form properties, and
 * sends a plain text response document containing the Gatekeeper response message encoded as
 * a properties file./*w ww .  j av a  2 s.c om*/
 */
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (log.isDebugEnabled()) {
        log.debug("Handling POST request");
    }
    try {
        // Build Gatekeeper request from POST form parameters.
        GatekeeperMessage gatekeeperMessage = GatekeeperMessage.decodeFromProperties(request.getParameterMap());

        // Obtain client information
        ClientInformation clientInformation = new ClientInformation(request.getRemoteAddr(),
                request.getRemoteHost(), request.getRemoteUser(), request.getRemotePort(),
                request.getSession(false), request.getUserPrincipal(), request.getHeader("User-Agent"),
                request);

        // Generate Transaction ID, and store it in the message.
        String transactionId = transactionIdProvider.getTransactionId(gatekeeperMessage, clientInformation);
        if (transactionId != null) {
            gatekeeperMessage.addMessageProperty(GatekeeperMessage.PROPERTY_TRANSACTION_ID, transactionId);
        }

        if (!isInitCompleted) {
            if (log.isWarnEnabled()) {
                log.warn("Cannot process POST request as Gatekeeper servlet did not initialize correctly");
            }
            gatekeeperMessage.addApplicationProperty(GatekeeperMessage.APP_PROPERTY_GATEKEEPER_ERROR_CODE,
                    "GatekeeperInitializationError");
        } else if (gatekeeperMessage.getApplicationProperties()
                .containsKey(GatekeeperMessage.LIST_OBJECTS_IN_BUCKET_FLAG)) {
            // Handle "limited listing" requests.
            if (log.isDebugEnabled()) {
                log.debug("Listing objects");
            }
            boolean allowed = authorizer.allowBucketListingRequest(gatekeeperMessage, clientInformation);
            if (allowed) {
                bucketLister.listObjects(gatekeeperMessage, clientInformation);
            }
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Processing " + gatekeeperMessage.getSignatureRequests().length
                        + " object signature requests");
            }
            // Process each signature request.
            for (int i = 0; i < gatekeeperMessage.getSignatureRequests().length; i++) {
                SignatureRequest signatureRequest = gatekeeperMessage.getSignatureRequests()[i];

                // Determine whether the request will be allowed. If the request is not allowed, the
                // reason will be made available in the signature request object (with signatureRequest.declineRequest())
                boolean allowed = authorizer.allowSignatureRequest(gatekeeperMessage, clientInformation,
                        signatureRequest);

                // Sign requests when they are allowed. When a request is signed, the signed URL is made available
                // in the SignatureRequest object.
                if (allowed) {
                    String signedUrl = null;
                    if (SignatureRequest.SIGNATURE_TYPE_GET.equals(signatureRequest.getSignatureType())) {
                        signedUrl = urlSigner.signGet(gatekeeperMessage, clientInformation, signatureRequest);
                    } else if (SignatureRequest.SIGNATURE_TYPE_HEAD
                            .equals(signatureRequest.getSignatureType())) {
                        signedUrl = urlSigner.signHead(gatekeeperMessage, clientInformation, signatureRequest);
                    } else if (SignatureRequest.SIGNATURE_TYPE_PUT
                            .equals(signatureRequest.getSignatureType())) {
                        signedUrl = urlSigner.signPut(gatekeeperMessage, clientInformation, signatureRequest);
                    } else if (SignatureRequest.SIGNATURE_TYPE_DELETE
                            .equals(signatureRequest.getSignatureType())) {
                        signedUrl = urlSigner.signDelete(gatekeeperMessage, clientInformation,
                                signatureRequest);
                    } else if (SignatureRequest.SIGNATURE_TYPE_ACL_LOOKUP
                            .equals(signatureRequest.getSignatureType())) {
                        signedUrl = urlSigner.signGetAcl(gatekeeperMessage, clientInformation,
                                signatureRequest);
                    } else if (SignatureRequest.SIGNATURE_TYPE_ACL_UPDATE
                            .equals(signatureRequest.getSignatureType())) {
                        signedUrl = urlSigner.signPutAcl(gatekeeperMessage, clientInformation,
                                signatureRequest);
                    }
                    signatureRequest.signRequest(signedUrl);
                }
            }
        }

        // Build response as a set of properties, and return this document.
        Properties responseProperties = gatekeeperMessage.encodeToProperties();
        if (log.isDebugEnabled()) {
            log.debug("Sending response message as properties: " + responseProperties);
        }

        // Serialize properties to bytes.
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        responseProperties.store(baos, "");

        // Send successful response.
        response.setStatus(200);
        response.setContentType("text/plain");
        response.getOutputStream().write(baos.toByteArray());
    } catch (Exception e) {
        if (log.isErrorEnabled()) {
            log.error("Gatekeeper failed to send valid response", e);
        }
        response.setStatus(500);
        response.setContentType("text/plain");
        response.getWriter().println(e.toString());
    }
}

From source file:fr.xebia.servlet.filter.XForwardedFilterTest.java

/**
 * Test {@link XForwardedFilter} in Jetty
 *//*from   w  ww  .java2  s . c o  m*/
@Test
public void testWithJetty() throws Exception {

    // SETUP
    int port = 6666;
    Server server = new Server(port);
    Context context = new Context(server, "/", Context.SESSIONS);

    // mostly default configuration : enable "x-forwarded-proto"
    XForwardedFilter xforwardedFilter = new XForwardedFilter();
    MockFilterConfig filterConfig = new MockFilterConfig();
    filterConfig.addInitParameter(XForwardedFilter.PROTOCOL_HEADER_PARAMETER, "x-forwarded-proto");
    // Following is needed on ipv6 stacks..
    filterConfig.addInitParameter(XForwardedFilter.INTERNAL_PROXIES_PARAMETER,
            InetAddress.getByName("localhost").getHostAddress());
    xforwardedFilter.init(filterConfig);
    context.addFilter(new FilterHolder(xforwardedFilter), "/*", Handler.REQUEST);

    MockHttpServlet mockServlet = new MockHttpServlet();
    context.addServlet(new ServletHolder(mockServlet), "/test");

    server.start();
    try {
        // TEST
        HttpURLConnection httpURLConnection = (HttpURLConnection) new URL("http://localhost:" + port + "/test")
                .openConnection();
        String expectedRemoteAddr = "my-remote-addr";
        httpURLConnection.addRequestProperty("x-forwarded-for", expectedRemoteAddr);
        httpURLConnection.addRequestProperty("x-forwarded-proto", "https");

        // VALIDATE

        Assert.assertEquals(HttpURLConnection.HTTP_OK, httpURLConnection.getResponseCode());
        HttpServletRequest request = mockServlet.getRequest();
        Assert.assertNotNull(request);

        // VALIDATE X-FOWARDED-FOR
        Assert.assertEquals(expectedRemoteAddr, request.getRemoteAddr());
        Assert.assertEquals(expectedRemoteAddr, request.getRemoteHost());

        // VALIDATE X-FORWARDED-PROTO
        Assert.assertTrue(request.isSecure());
        Assert.assertEquals("https", request.getScheme());
        Assert.assertEquals(443, request.getServerPort());
    } finally {
        server.stop();
    }
}