Example usage for org.apache.http.message BasicHeaderElementIterator BasicHeaderElementIterator

List of usage examples for org.apache.http.message BasicHeaderElementIterator BasicHeaderElementIterator

Introduction

In this page you can find the example usage for org.apache.http.message BasicHeaderElementIterator BasicHeaderElementIterator.

Prototype

public BasicHeaderElementIterator(HeaderIterator headerIterator) 

Source Link

Usage

From source file:org.aevans.goat.net.ConnectionUtils.java

public static ConnectionKeepAliveStrategy getConnectionKeepAliveStrategy(final int keepAlive) {
    return new ConnectionKeepAliveStrategy() {

        public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
            // Honor 'keep-alive' header
            HeaderElementIterator it = new BasicHeaderElementIterator(
                    response.headerIterator(HTTP.CONN_KEEP_ALIVE));
            while (it.hasNext()) {
                HeaderElement he = it.nextElement();
                String param = he.getName();
                String value = he.getValue();
                if (value != null && param.equalsIgnoreCase("timeout")) {
                    try {
                        return Long.parseLong(value) * 1000;
                    } catch (NumberFormatException ignore) {
                    }/*w w  w .  j  av a 2s. c  o  m*/
                }
            }

            return keepAlive * 1000;
        }

    };
}

From source file:code.google.restclient.core.CustomKeepAliveStrategy.java

public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
    // Honor 'keep-alive' header if present in response
    HeaderElementIterator it = new BasicHeaderElementIterator(response.headerIterator(HTTP.CONN_KEEP_ALIVE));
    while (it.hasNext()) {
        HeaderElement he = it.nextElement();
        String param = he.getName();
        String value = he.getValue();
        if (value != null && param.equalsIgnoreCase("timeout")) {
            try {
                return Long.parseLong(value) * 1000;
            } catch (NumberFormatException ignore) {
            }//from  w  ww. j a  va2 s  .c  om
        }
    }

    /*
    HttpHost target = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
    if ("www.naughty-server.com".equalsIgnoreCase(target.getHostName())) {
               
       return 5 * 1000;   // Keep alive for 5 seconds only
    }
    */

    return 10 * 1000; // Keep alive for 10 seconds
}

From source file:com.muk.services.web.client.DefaultKeepAliveStrategy.java

@Override
public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
    HeaderElementIterator it = new BasicHeaderElementIterator(response.headerIterator(HTTP.CONN_KEEP_ALIVE));
    while (it.hasNext()) {
        HeaderElement he = it.nextElement();
        String param = he.getName();
        String value = he.getValue();
        if (value != null && param.equalsIgnoreCase("timeout")) {
            return Long.parseLong(value) * 1000;
        }//from   w ww  .  j a va2s  .  c om
    }
    return 5 * 1000;
}

From source file:com.mashape.galileo.agent.network.AnalyticsConnKeepAliveStrategy.java

@Override
public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
    HeaderElementIterator it = new BasicHeaderElementIterator(response.headerIterator(HTTP.CONN_KEEP_ALIVE));
    while (it.hasNext()) {
        HeaderElement he = it.nextElement();
        String param = he.getName();
        String value = he.getValue();
        if (value != null && param.equalsIgnoreCase("timeout")) {
            try {
                return Long.parseLong(value) * 1000;
            } catch (NumberFormatException ignore) {
            }/*from w  w w. j av  a 2  s.  c o  m*/
        }
    }
    return keepAliveTime * 1000;
}

From source file:com.normalexception.app.rx8club.httpclient.KeepAliveStrategy.java

public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
    // Honor 'keep-alive' header
    HeaderElementIterator it = new BasicHeaderElementIterator(response.headerIterator(HTTP.CONN_KEEP_ALIVE));
    while (it.hasNext()) {
        HeaderElement he = it.nextElement();
        String param = he.getName();
        String value = he.getValue();
        if (value != null && param.equalsIgnoreCase("timeout")) {
            try {
                return Long.parseLong(value) * 1000;
            } catch (NumberFormatException ignore) {
            }//  ww w.  ja  va2s .  c  o  m
        }
    }

    //keep alive for 30 seconds
    return KAL_TIME * 1000;
}

From source file:it.av.youeat.web.pubsubhubbub.Publisher.java

/**
 * Constructor/*from  ww w  .  j  a va 2 s . c  om*/
 */
public Publisher() {
    HttpParams params = new BasicHttpParams();
    ConnManagerParams.setMaxTotalConnections(params, 200);
    ConnPerRouteBean connPerRoute = new ConnPerRouteBean(20);
    connPerRoute.setDefaultMaxPerRoute(50);
    ConnManagerParams.setMaxConnectionsPerRoute(params, connPerRoute);

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);
    httpClient = new DefaultHttpClient(cm, params);

    httpClient.setKeepAliveStrategy(new ConnectionKeepAliveStrategy() {

        public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
            HeaderElementIterator it = new BasicHeaderElementIterator(
                    response.headerIterator(HTTP.CONN_KEEP_ALIVE));
            while (it.hasNext()) {
                HeaderElement he = it.nextElement();
                String param = he.getName();
                String value = he.getValue();
                if (value != null && param.equalsIgnoreCase("timeout")) {
                    try {
                        return Long.parseLong(value) * 1000;
                    } catch (NumberFormatException ignore) {
                    }
                }
            }
            // default keepalive is 60 seconds. This is higher than usual
            // since the number of hubs it should be talking to should be
            // small
            return 30 * 1000;
        }
    });
}

From source file:com.github.luluvise.droid_utils.http.NetworkConstants.java

/**
 * Attempts to retrieve a "Keep-Alive" header from the passed
 * {@link HttpResponse}.//from   www . ja v a2s .c om
 * 
 * @return The keep alive time or -1 if not found
 */
public static long getKeepAliveHeader(@Nonnull HttpResponse response) {
    HeaderElementIterator it = new BasicHeaderElementIterator(response.headerIterator(HTTP.CONN_KEEP_ALIVE));
    while (it.hasNext()) {
        HeaderElement he = it.nextElement();
        String param = he.getName();
        String value = he.getValue();
        if (value != null && param.equalsIgnoreCase("timeout")) {
            try {
                return Long.parseLong(value) * 1000;
            } catch (NumberFormatException ignore) {
                return -1;
            }
        }
    }
    return -1;
}

From source file:org.frontcache.agent.FrontCacheAgent.java

public FrontCacheAgent(String frontcacheURL) {
    final RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(3000)
            .setCookieSpec(CookieSpecs.IGNORE_COOKIES).build();

    ConnectionKeepAliveStrategy keepAliveStrategy = new ConnectionKeepAliveStrategy() {
        @Override//  w ww.  jav a2s. c o m
        public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
            HeaderElementIterator it = new BasicHeaderElementIterator(
                    response.headerIterator(HTTP.CONN_KEEP_ALIVE));
            while (it.hasNext()) {
                HeaderElement he = it.nextElement();
                String param = he.getName();
                String value = he.getValue();
                if (value != null && param.equalsIgnoreCase("timeout")) {
                    return Long.parseLong(value) * 1000;
                }
            }
            return 10 * 1000;
        }
    };

    client = HttpClients.custom().setDefaultRequestConfig(requestConfig)
            .setRetryHandler(new DefaultHttpRequestRetryHandler(0, false))
            .setKeepAliveStrategy(keepAliveStrategy).setRedirectStrategy(new RedirectStrategy() {
                @Override
                public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context)
                        throws ProtocolException {
                    return false;
                }

                @Override
                public HttpUriRequest getRedirect(HttpRequest request, HttpResponse response,
                        HttpContext context) throws ProtocolException {
                    return null;
                }
            }).build();

    this.frontCacheURL = frontcacheURL;

    if (frontcacheURL.endsWith("/"))
        this.frontCacheURI = frontcacheURL + IO_URI;
    else
        this.frontCacheURI = frontcacheURL + "/" + IO_URI;
}

From source file:de.hshannover.f4.trust.iron.mapserver.communication.http.BasicChannelAuth.java

@Override
public void authenticate(HttpRequest request) throws ChannelAuthException {
    HeaderElementIterator it = new BasicHeaderElementIterator(request.headerIterator("Authorization"));
    HeaderElement elem;//from w w  w .ja v a 2 s.  c  o  m

    if (it.hasNext()) {
        elem = it.nextElement();
    } else {
        throw new ChannelAuthException("no authorization field found");
    }

    // split the value of the Authorization header. split[0] should be
    // basic and split[1] the base64 stuff.
    String split[] = elem.getName().split(" ");

    if (split.length != 2 || !split[0].equals("Basic")) {
        throw new ChannelAuthException("Bad Authorization header value!");
    }

    String base64 = split[1];
    String[] creds = new String(Base64.decodeBase64(base64)).split(":");

    if (creds.length != 2) {
        throw new ChannelAuthException("Wrong credentials, not authenticated!");
    }

    String user = creds[0];
    String pass = creds[1];

    if (!mBasicAuthProvider.verify(user, pass)) {
        throw new ChannelAuthException("Bad username/password");
    } else {
        ClientIdentifier newClId = new ClientIdentifier(user);
        // this checks, whether the username is the same as given on the
        // first call. If this is the first call, set the mClientId field
        // appropriately.
        if (mClientId != null) {
            if (!mClientId.equals(newClId)) {
                throw new ChannelAuthException("Username/password was changed");
            }
        } else {
            mClientId = newClId;
        }
    }
}

From source file:org.alfresco.cacheserver.http.CacheHttpClient.java

private CloseableHttpClient getHttpClient(HttpHost target, HttpClientContext localContext, String username,
        String password) {//from w ww.  j a v  a 2 s  . com
    ConnectionKeepAliveStrategy keepAliveStrategy = new ConnectionKeepAliveStrategy() {

        public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
            // Honor 'keep-alive' header
            HeaderElementIterator it = new BasicHeaderElementIterator(
                    response.headerIterator(HTTP.CONN_KEEP_ALIVE));
            while (it.hasNext()) {
                HeaderElement he = it.nextElement();
                String param = he.getName();
                String value = he.getValue();
                if (value != null && param.equalsIgnoreCase("timeout")) {
                    try {
                        return Long.parseLong(value) * 1000;
                    } catch (NumberFormatException ignore) {
                    }
                }
            }
            HttpHost target = (HttpHost) context.getAttribute(HttpClientContext.HTTP_TARGET_HOST);
            if ("www.naughty-server.com".equalsIgnoreCase(target.getHostName())) {
                // Keep alive for 5 seconds only
                return 5 * 1000;
            } else {
                // otherwise keep alive for 30 seconds
                return 30 * 1000;
            }
        }

    };

    HttpRequestRetryHandler retryHandler = new HttpRequestRetryHandler() {

        public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
            if (executionCount >= 5) {
                // Do not retry if over max retry count
                return false;
            }
            if (exception instanceof InterruptedIOException) {
                // Timeout
                return false;
            }
            if (exception instanceof UnknownHostException) {
                // Unknown host
                return false;
            }
            if (exception instanceof ConnectTimeoutException) {
                // Connection refused
                return false;
            }
            if (exception instanceof SSLException) {
                // SSL handshake exception
                return false;
            }
            HttpClientContext clientContext = HttpClientContext.adapt(context);
            HttpRequest request = clientContext.getRequest();
            boolean idempotent = !(request instanceof HttpEntityEnclosingRequest);
            if (idempotent) {
                // Retry if the request is considered idempotent
                return true;
            }
            return false;
        }
    };

    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(target.getHostName(), target.getPort()),
            new UsernamePasswordCredentials(username, password));
    RequestConfig defaultRequestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT)
            .setExpectContinueEnabled(true)
            //                .setStaleConnectionCheckEnabled(true)
            .setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC))
            .setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)).build();
    CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig)
            .setDefaultCredentialsProvider(credsProvider).setKeepAliveStrategy(keepAliveStrategy)
            .setRetryHandler(retryHandler).build();
    return httpclient;
}