Example usage for java.util Collections synchronizedMap

List of usage examples for java.util Collections synchronizedMap

Introduction

In this page you can find the example usage for java.util Collections synchronizedMap.

Prototype

public static <K, V> Map<K, V> synchronizedMap(Map<K, V> m) 

Source Link

Document

Returns a synchronized (thread-safe) map backed by the specified map.

Usage

From source file:com.yunmall.ymsdk.net.http.AsyncHttpClient.java

/**
 * Creates a new AsyncHttpClient.//from w  ww.  j av  a 2s.com
 *
 * @param schemeRegistry SchemeRegistry to be used
 */
public AsyncHttpClient(SchemeRegistry schemeRegistry) {

    BasicHttpParams httpParams = new BasicHttpParams();

    ConnManagerParams.setTimeout(httpParams, connectTimeout);
    ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(maxConnections));
    ConnManagerParams.setMaxTotalConnections(httpParams, DEFAULT_MAX_CONNECTIONS);

    HttpConnectionParams.setSoTimeout(httpParams, responseTimeout);
    HttpConnectionParams.setConnectionTimeout(httpParams, connectTimeout);
    HttpConnectionParams.setTcpNoDelay(httpParams, true);
    HttpConnectionParams.setSocketBufferSize(httpParams, DEFAULT_SOCKET_BUFFER_SIZE);

    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);

    ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry);

    threadPool = getDefaultThreadPool();
    requestMap = Collections.synchronizedMap(new WeakHashMap<Context, List<RequestHandle>>());
    clientHeaderMap = new HashMap<String, String>();

    httpContext = new SyncBasicHttpContext(new BasicHttpContext());
    httpClient = new DefaultHttpClient(cm, httpParams);
    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override
        public void process(HttpRequest request, HttpContext context) {
            if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
                request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
            }
            for (String header : clientHeaderMap.keySet()) {
                if (request.containsHeader(header)) {
                    Header overwritten = request.getFirstHeader(header);
                    YmLog.d(LOG_TAG,
                            String.format("Headers were overwritten! (%s | %s) overwrites (%s | %s)", header,
                                    clientHeaderMap.get(header), overwritten.getName(),
                                    overwritten.getValue()));

                    //remove the overwritten header
                    request.removeHeader(overwritten);
                }
                request.addHeader(header, clientHeaderMap.get(header));
            }
        }
    });

    httpClient.addResponseInterceptor(new HttpResponseInterceptor() {
        @Override
        public void process(HttpResponse response, HttpContext context) {
            final HttpEntity entity = response.getEntity();
            if (entity == null) {
                return;
            }
            final Header encoding = entity.getContentEncoding();
            if (encoding != null) {
                for (HeaderElement element : encoding.getElements()) {
                    if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) {
                        response.setEntity(new InflatingEntity(entity));
                        break;
                    }
                }
            }
        }
    });

    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override
        public void process(final HttpRequest request, final HttpContext context)
                throws HttpException, IOException {
            AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
            CredentialsProvider credsProvider = (CredentialsProvider) context
                    .getAttribute(ClientContext.CREDS_PROVIDER);
            HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);

            if (authState.getAuthScheme() == null) {
                AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
                Credentials creds = credsProvider.getCredentials(authScope);
                if (creds != null) {
                    authState.setAuthScheme(new BasicScheme());
                    authState.setCredentials(creds);
                }
            }
        }
    }, 0);

    httpClient
            .setHttpRequestRetryHandler(new RetryHandler(DEFAULT_MAX_RETRIES, DEFAULT_RETRY_SLEEP_TIME_MILLIS));
}

From source file:jdbc.pool.CPropertyManager.java

public Map<String, CPoolAttribute> getAllPoolAttributes() throws ConfigurationException {
    StringTokenizer tokenizer = new StringTokenizer(properties_.getProperty("pools"), ";");
    Map<String, CPoolAttribute> map = Collections.synchronizedMap(new HashMap<String, CPoolAttribute>());
    while (tokenizer.hasMoreTokens()) {
        String strPoolName = tokenizer.nextToken();
        map.put(strPoolName, getPoolAttribute(strPoolName));
    }//from w  w  w .j a  v  a  2 s . c  o  m
    return map;
}

From source file:lib.asynchronous.AsyncHttpClient.java

/**
 * Creates a new AsyncHttpClient.//w ww  .  j  a  v a2s  . c om
 *
 * @param schemeRegistry SchemeRegistry to be used
 */
public AsyncHttpClient(SchemeRegistry schemeRegistry) {

    BasicHttpParams httpParams = new BasicHttpParams();

    ConnManagerParams.setTimeout(httpParams, connectTimeout);
    ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(maxConnections));
    ConnManagerParams.setMaxTotalConnections(httpParams, DEFAULT_MAX_CONNECTIONS);

    HttpConnectionParams.setSoTimeout(httpParams, responseTimeout);
    HttpConnectionParams.setConnectionTimeout(httpParams, connectTimeout);
    HttpConnectionParams.setTcpNoDelay(httpParams, true);
    HttpConnectionParams.setSocketBufferSize(httpParams, DEFAULT_SOCKET_BUFFER_SIZE);

    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);

    ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry);

    threadPool = getDefaultThreadPool();
    requestMap = Collections.synchronizedMap(new WeakHashMap<Context, List<RequestHandle>>());
    clientHeaderMap = new HashMap<String, String>();

    httpContext = new SyncBasicHttpContext(new BasicHttpContext());
    httpClient = new DefaultHttpClient(cm, httpParams);
    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override
        public void process(HttpRequest request, HttpContext context) {
            if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
                request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
            }
            for (String header : clientHeaderMap.keySet()) {
                if (request.containsHeader(header)) {
                    Header overwritten = request.getFirstHeader(header);
                    Log.d(LOG_TAG,
                            String.format("Headers were overwritten! (%s | %s) overwrites (%s | %s)", header,
                                    clientHeaderMap.get(header), overwritten.getName(),
                                    overwritten.getValue()));

                    //remove the overwritten header
                    request.removeHeader(overwritten);
                }
                request.addHeader(header, clientHeaderMap.get(header));
            } //end for 
        }
    });

    httpClient.addResponseInterceptor(new HttpResponseInterceptor() {
        @Override
        public void process(HttpResponse response, HttpContext context) {
            final HttpEntity entity = response.getEntity();
            if (entity == null) {
                return;
            }
            final Header encoding = entity.getContentEncoding();
            if (encoding != null) {
                for (HeaderElement element : encoding.getElements()) {
                    if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) {
                        response.setEntity(new InflatingEntity(entity));
                        break;
                    }
                } //end for
            }
        }
    });

    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override
        public void process(final HttpRequest request, final HttpContext context)
                throws HttpException, IOException {
            AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
            CredentialsProvider credsProvider = (CredentialsProvider) context
                    .getAttribute(ClientContext.CREDS_PROVIDER);
            HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);

            if (authState.getAuthScheme() == null) {
                AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
                Credentials creds = credsProvider.getCredentials(authScope);
                if (creds != null) {
                    authState.setAuthScheme(new BasicScheme());
                    authState.setCredentials(creds);
                }
            }
        }
    }, 0);

    httpClient
            .setHttpRequestRetryHandler(new RetryHandler(DEFAULT_MAX_RETRIES, DEFAULT_RETRY_SLEEP_TIME_MILLIS));
}

From source file:com.loopj.android.http.AsyncHttpClientQueue.java

/**
 * Creates a new AsyncHttpClient./*from www .  j  a v  a  2 s  . c  o m*/
 *
 * @param schemeRegistry SchemeRegistry to be used
 */
public AsyncHttpClientQueue(SchemeRegistry schemeRegistry) {

    BasicHttpParams httpParams = new BasicHttpParams();

    ConnManagerParams.setTimeout(httpParams, connectTimeout);
    ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(maxConnections));
    ConnManagerParams.setMaxTotalConnections(httpParams, DEFAULT_MAX_CONNECTIONS);

    HttpConnectionParams.setSoTimeout(httpParams, responseTimeout);
    HttpConnectionParams.setConnectionTimeout(httpParams, connectTimeout);
    HttpConnectionParams.setTcpNoDelay(httpParams, true);
    HttpConnectionParams.setSocketBufferSize(httpParams, DEFAULT_SOCKET_BUFFER_SIZE);

    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);

    ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry);

    threadPool = getDefaultThreadPool();
    requestMap = Collections.synchronizedMap(new WeakHashMap<Context, List<RequestHandle>>());
    clientHeaderMap = new HashMap<String, String>();

    httpContext = new SyncBasicHttpContext(new BasicHttpContext());
    httpClient = new DefaultHttpClient(cm, httpParams);
    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override
        public void process(HttpRequest request, HttpContext context) {
            if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
                request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
            }
            for (String header : clientHeaderMap.keySet()) {
                if (request.containsHeader(header)) {
                    Header overwritten = request.getFirstHeader(header);
                    Log.d(LOG_TAG,
                            String.format("Headers were overwritten! (%s | %s) overwrites (%s | %s)", header,
                                    clientHeaderMap.get(header), overwritten.getName(),
                                    overwritten.getValue()));

                    //remove the overwritten header
                    request.removeHeader(overwritten);
                }
                request.addHeader(header, clientHeaderMap.get(header));
            }
        }
    });

    httpClient.addResponseInterceptor(new HttpResponseInterceptor() {
        @Override
        public void process(HttpResponse response, HttpContext context) {
            final HttpEntity entity = response.getEntity();
            if (entity == null) {
                return;
            }
            final Header encoding = entity.getContentEncoding();
            if (encoding != null) {
                for (HeaderElement element : encoding.getElements()) {
                    if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) {
                        response.setEntity(new InflatingEntity(entity));
                        break;
                    }
                }
            }
        }
    });

    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override
        public void process(final HttpRequest request, final HttpContext context)
                throws HttpException, IOException {
            AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
            CredentialsProvider credsProvider = (CredentialsProvider) context
                    .getAttribute(ClientContext.CREDS_PROVIDER);
            HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);

            if (authState.getAuthScheme() == null) {
                AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
                Credentials creds = credsProvider.getCredentials(authScope);
                if (creds != null) {
                    authState.setAuthScheme(new BasicScheme());
                    authState.setCredentials(creds);
                }
            }
        }
    }, 0);

    httpClient
            .setHttpRequestRetryHandler(new RetryHandler(DEFAULT_MAX_RETRIES, DEFAULT_RETRY_SLEEP_TIME_MILLIS));
}

From source file:com.fdwills.external.http.AsyncHttpClient.java

/**
 * Creates a new AsyncHttpClient.//  www. j a v a2  s.  c o  m
 *
 * @param schemeRegistry SchemeRegistry to be used
 */
public AsyncHttpClient(SchemeRegistry schemeRegistry) {

    BasicHttpParams httpParams = new BasicHttpParams();

    ConnManagerParams.setTimeout(httpParams, connectTimeout);
    ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(maxConnections));
    ConnManagerParams.setMaxTotalConnections(httpParams, DEFAULT_MAX_CONNECTIONS);

    HttpConnectionParams.setSoTimeout(httpParams, responseTimeout);
    HttpConnectionParams.setConnectionTimeout(httpParams, connectTimeout);
    HttpConnectionParams.setTcpNoDelay(httpParams, true);
    HttpConnectionParams.setSocketBufferSize(httpParams, DEFAULT_SOCKET_BUFFER_SIZE);

    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);

    ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry);

    threadPool = getDefaultThreadPool();
    requestMap = Collections.synchronizedMap(new WeakHashMap<Context, List<RequestHandle>>());
    clientHeaderMap = new HashMap<String, String>();

    httpContext = new SyncBasicHttpContext(new BasicHttpContext());
    httpClient = new DefaultHttpClient(cm, httpParams);
    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override
        public void process(HttpRequest request, HttpContext context) {
            if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
                request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
            }
            for (String header : clientHeaderMap.keySet()) {
                if (request.containsHeader(header)) {
                    Header overwritten = request.getFirstHeader(header);
                    Log.d(LOG_TAG,
                            String.format("Headers were overwritten! (%s | %s) overwrites (%s | %s)", header,
                                    clientHeaderMap.get(header), overwritten.getName(),
                                    overwritten.getValue()));

                    //remove the overwritten header
                    request.removeHeader(overwritten);
                }
                request.addHeader(header, clientHeaderMap.get(header));
            }
        }
    });

    httpClient.addResponseInterceptor(new HttpResponseInterceptor() {
        @Override
        public void process(HttpResponse response, HttpContext context) {
            final HttpEntity entity = response.getEntity();
            if (entity == null) {
                return;
            }
            final Header encoding = entity.getContentEncoding();
            if (encoding != null) {
                for (HeaderElement element : encoding.getElements()) {
                    if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) {
                        response.setEntity(new InflatingEntity(entity));
                        break;
                    }
                }
            }
        }
    });

    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override
        public void process(final HttpRequest request, final HttpContext context)
                throws HttpException, IOException {
            AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
            CredentialsProvider credsProvider = (CredentialsProvider) context
                    .getAttribute(ClientContext.CREDS_PROVIDER);
            HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);

            if (authState.getAuthScheme() == null) {
                AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
                Credentials creds = credsProvider.getCredentials(authScope);
                if (creds != null) {
                    authState.setAuthScheme(new BasicScheme());
                    authState.setCredentials(creds);
                }
            }
        }
    }, 0);

    httpClient
            .setHttpRequestRetryHandler(new RetryHandler(DEFAULT_MAX_RETRIES, DEFAULT_RETRY_SLEEP_TIME_MILLIS));
}

From source file:org.eclipse.scanning.event.SubscriberImpl.java

private Map<Class, DiseminateHandler> createDiseminateHandlers() {

    Map<Class, DiseminateHandler> ret = Collections.synchronizedMap(new HashMap<Class, DiseminateHandler>(3));

    ret.put(IScanListener.class, new DiseminateHandler() {
        public void diseminate(Object bean, EventListener e) {

            if (!(bean instanceof ScanBean))
                return;
            // This listener must be used with events publishing ScanBean
            // If your scan does not publish ScanBean events then you
            // may listen to it with a standard IBeanListener.

            // Used casting because generics got silly
            ScanBean sbean = (ScanBean) bean;
            IScanListener l = (IScanListener) e;

            DeviceState now = sbean.getDeviceState();
            DeviceState was = sbean.getPreviousDeviceState();
            if (now != null && now != was) {
                execute(new DespatchEvent(l, new ScanEvent(sbean), true));
                return;
            } else {
                Status snow = sbean.getStatus();
                Status swas = sbean.getPreviousStatus();
                if (snow != null && snow != swas && swas != null) {
                    execute(new DespatchEvent(l, new ScanEvent(sbean), true));
                    return;
                }//from www  . j  ava2s .  co  m
            }
            execute(new DespatchEvent(l, new ScanEvent(sbean), false));
        }
    });
    ret.put(IHeartbeatListener.class, new DiseminateHandler() {
        public void diseminate(Object bean, EventListener e) {
            // Used casting because generics got silly
            HeartbeatBean hbean = (HeartbeatBean) bean;
            IHeartbeatListener l = (IHeartbeatListener) e;
            execute(new DespatchEvent(l, new HeartbeatEvent(hbean)));
        }
    });
    ret.put(IBeanListener.class, new DiseminateHandler() {
        public void diseminate(Object bean, EventListener e) {
            // Used casting because generics got silly
            @SuppressWarnings("unchecked")
            IBeanListener<Object> l = (IBeanListener<Object>) e;
            execute(new DespatchEvent(l, new BeanEvent<Object>(bean)));
        }
    });
    ret.put(ILocationListener.class, new DiseminateHandler() {
        public void diseminate(Object bean, EventListener e) {
            // Used casting because generics got silly
            ILocationListener l = (ILocationListener) e;
            execute(new DespatchEvent(l, new LocationEvent((Location) bean)));
        }
    });

    return ret;
}

From source file:strat.mining.multipool.stats.service.impl.DonationServiceImpl.java

/**
 * Update the map of donation transactions that have not been thanked yet.
 *///from  w w w.  ja  v  a  2 s. c  om
private void updateDonationsNotThanked() {
    Map<String, List<Transaction>> transactionsByAddress = Collections
            .synchronizedMap(new HashMap<String, List<Transaction>>());

    List<Address> donatorsAddresses = donationAddressDao.getAllAddressesSince(getFirstDayOfMonthDate());

    if (CollectionUtils.isNotEmpty(donatorsAddresses)) {
        for (Address address : donatorsAddresses) {
            List<Transaction> notThankedDonationTransactions = new ArrayList<>();

            if (address != null && CollectionUtils.isNotEmpty(address.getTransactionIds())) {
                for (String transactionId : address.getTransactionIds()) {
                    Transaction transaction = donationTransactionDao.getTransaction(transactionId);
                    if (transaction != null && !transaction.getHasBeenThanked()) {
                        notThankedDonationTransactions.add(transaction);
                    }
                }
            }

            // If the current address has some transactions not thanked. add
            // it.
            if (CollectionUtils.isNotEmpty(notThankedDonationTransactions)) {
                transactionsByAddress.put(address.getAddress(), notThankedDonationTransactions);
            }
        }
    }

    transactionsNotThankedByAddress = transactionsByAddress;
}

From source file:com.collabnet.ccf.core.transformer.XsltProcessor.java

/**
 * Hook to perform any validation of the component properties required by
 * the implementation. Default behaviour should be a no-op.
 *//*from  ww  w.  j  a  va  2 s . c o  m*/
@SuppressWarnings("unchecked")
public void validate(List exceptions) {
    // we have to make this map thread safe because it will be
    // updated asynchronously
    xsltFileNameTransformerMap = Collections.synchronizedMap(new HashMap<String, Transformer>());
    if (isListenForFileUpdates()) {
        try {
            fsManager = VFS.getManager();
        } catch (FileSystemException e) {
            exceptions
                    .add(new ValidationException("could not initialize file manager: " + e.getMessage(), this));
            return;
        }
        fileMonitor = new DefaultFileMonitor(new FileListener() {
            public void fileChanged(org.apache.commons.vfs.FileChangeEvent arg0) throws Exception {
                xsltFileNameTransformerMap.clear();
            }

            public void fileCreated(FileChangeEvent arg0) throws Exception {
                xsltFileNameTransformerMap.clear();
            }

            public void fileDeleted(FileChangeEvent arg0) throws Exception {
                xsltFileNameTransformerMap.clear();
            }
        });
    }

    String xsltDir = this.getXsltDir();
    String xsltFile = this.getXsltFile();
    if (!StringUtils.isEmpty(xsltDir)) {
        File xsltDirFile = new File(xsltDir);
        if (xsltDirFile.exists() && xsltDirFile.isDirectory()) {
            log.debug("xsltDir property " + xsltDir + " is a valid directory");
            if (listenForFileUpdates) {
                FileObject fileObject = null;
                try {
                    fileObject = fsManager.resolveFile(xsltDirFile.getAbsolutePath());
                } catch (FileSystemException e) {
                    exceptions.add(new ValidationException(
                            "xsltDir property " + xsltDir + " is not a valid directory: " + e.getMessage(),
                            this));
                    return;
                }
                fileMonitor.setRecursive(true);
                fileMonitor.addFile(fileObject);
                fileMonitor.start();
            }

        } else {
            exceptions.add(new ValidationException(
                    "xsltDir property " + xsltDir + " is not a valid directory...!", this));
            return;
        }
    } else if (!StringUtils.isEmpty(xsltFile)) {
        File xsltFileFile = new File(xsltFile);
        if (xsltFileFile.exists() && xsltFileFile.isFile()) {
            log.debug("xsltFile property " + xsltFile + " is a valid file");
            if (listenForFileUpdates) {
                FileObject fileObject = null;
                try {
                    fileObject = fsManager.resolveFile(xsltFileFile.getAbsolutePath());
                } catch (FileSystemException e) {
                    exceptions.add(new ValidationException(
                            "xsltFile property " + xsltFile + " is not a valid file...:" + e.getMessage(),
                            this));
                    return;
                }
                fileMonitor.addFile(fileObject);
                fileMonitor.start();
            }
        } else {
            exceptions.add(new ValidationException("xsltFile property " + xsltFile + " is not a valid file...!",
                    this));
            return;
        }
    }
}

From source file:com.example.pierre.applicompanies.library_http.AsyncHttpClient.java

/**
 * Creates a new AsyncHttpClient.//ww  w  . j  a  va  2  s. c o m
 *
 * @param schemeRegistry SchemeRegistry to be used
 */
public AsyncHttpClient(SchemeRegistry schemeRegistry) {

    BasicHttpParams httpParams = new BasicHttpParams();

    ConnManagerParams.setTimeout(httpParams, connectTimeout);
    ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(maxConnections));
    ConnManagerParams.setMaxTotalConnections(httpParams, DEFAULT_MAX_CONNECTIONS);

    HttpConnectionParams.setSoTimeout(httpParams, responseTimeout);
    HttpConnectionParams.setConnectionTimeout(httpParams, connectTimeout);
    HttpConnectionParams.setTcpNoDelay(httpParams, true);
    HttpConnectionParams.setSocketBufferSize(httpParams, DEFAULT_SOCKET_BUFFER_SIZE);

    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);

    ClientConnectionManager cm = createConnectionManager(schemeRegistry, httpParams);
    Utils.asserts(cm != null,
            "Custom implementation of #createConnectionManager(SchemeRegistry, BasicHttpParams) returned null");

    threadPool = getDefaultThreadPool();
    requestMap = Collections.synchronizedMap(new WeakHashMap<Context, List<RequestHandle>>());
    clientHeaderMap = new HashMap<String, String>();

    httpContext = new SyncBasicHttpContext(new BasicHttpContext());
    httpClient = new DefaultHttpClient(cm, httpParams);
    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override
        public void process(HttpRequest request, HttpContext context) {
            if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
                request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
            }
            for (String header : clientHeaderMap.keySet()) {
                if (request.containsHeader(header)) {
                    Header overwritten = request.getFirstHeader(header);
                    Log.d(LOG_TAG,
                            String.format("Headers were overwritten! (%s | %s) overwrites (%s | %s)", header,
                                    clientHeaderMap.get(header), overwritten.getName(),
                                    overwritten.getValue()));

                    //remove the overwritten header
                    request.removeHeader(overwritten);
                }
                request.addHeader(header, clientHeaderMap.get(header));
            }
        }
    });

    httpClient.addResponseInterceptor(new HttpResponseInterceptor() {
        @Override
        public void process(HttpResponse response, HttpContext context) {
            final HttpEntity entity = response.getEntity();
            if (entity == null) {
                return;
            }
            final Header encoding = entity.getContentEncoding();
            if (encoding != null) {
                for (HeaderElement element : encoding.getElements()) {
                    if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) {
                        response.setEntity(new InflatingEntity(entity));
                        break;
                    }
                }
            }
        }
    });

    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override
        public void process(final HttpRequest request, final HttpContext context)
                throws HttpException, IOException {
            AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
            CredentialsProvider credsProvider = (CredentialsProvider) context
                    .getAttribute(ClientContext.CREDS_PROVIDER);
            HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);

            if (authState.getAuthScheme() == null) {
                AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
                Credentials creds = credsProvider.getCredentials(authScope);
                if (creds != null) {
                    authState.setAuthScheme(new BasicScheme());
                    authState.setCredentials(creds);
                }
            }
        }
    }, 0);

    httpClient
            .setHttpRequestRetryHandler(new RetryHandler(DEFAULT_MAX_RETRIES, DEFAULT_RETRY_SLEEP_TIME_MILLIS));
}

From source file:com.google.android.imageloader.ImageLoader.java

/**
 * Creates an {@link ImageLoader}./*from ww  w.j  a  v a  2 s  .  c  om*/
 *
 * @param taskLimit the maximum number of background tasks that may be
 *            active at one time.
 * @param streamFactory a {@link URLStreamHandlerFactory} for creating
 *            connections to special URLs such as {@code content://} URIs.
 *            This parameter can be {@code null} if the {@link ImageLoader}
 *            only needs to load images over HTTP or if a custom
 *            {@link URLStreamHandlerFactory} has already been passed to
 *            {@link URL#setURLStreamHandlerFactory(URLStreamHandlerFactory)}
 * @param bitmapHandler a {@link ContentHandler} for loading images.
 *            {@link ContentHandler#getContent(URLConnection)} must either
 *            return a {@link Bitmap} or throw an {@link IOException}. This
 *            parameter can be {@code null} to use the default
 *            {@link BitmapContentHandler}.
 * @param prefetchHandler a {@link ContentHandler} for caching a remote URL
 *            as a file, without parsing it or loading it into memory.
 *            {@link ContentHandler#getContent(URLConnection)} should always
 *            return {@code null}. If the URL passed to the
 *            {@link ContentHandler} is already local (for example,
 *            {@code file://}), this {@link ContentHandler} should do
 *            nothing. The {@link ContentHandler} can be {@code null} if
 *            pre-fetching is not required.
 * @param cacheSize the maximum size of the image cache (in bytes).
 * @param handler a {@link Handler} identifying the callback thread, or
 *            {@code} null for the main thread.
 * @throws NullPointerException if the factory is {@code null}.
 */
public ImageLoader(int taskLimit, URLStreamHandlerFactory streamFactory, ContentHandler bitmapHandler,
        ContentHandler prefetchHandler, long cacheSize, Handler handler) {
    if (taskLimit < 1) {
        throw new IllegalArgumentException("Task limit must be positive");
    }
    if (cacheSize < 1) {
        throw new IllegalArgumentException("Cache size must be positive");
    }
    mMaxTaskCount = taskLimit;
    mURLStreamHandlerFactory = streamFactory;
    mStreamHandlers = streamFactory != null ? new HashMap<String, URLStreamHandler>() : null;
    mBitmapContentHandler = bitmapHandler != null ? bitmapHandler : new BitmapContentHandler();
    mPrefetchContentHandler = prefetchHandler;

    mImageViewBinding = new WeakHashMap<ImageView, String>();

    mRequests = new LinkedList<ImageRequest>();

    // Use a LruCache to prevent the set of keys from growing too large.
    // The Maps must be synchronized because they are accessed
    // by the UI thread and by background threads.
    mBitmaps = Collections.synchronizedMap(new BitmapCache<String>(cacheSize));
    mErrors = Collections.synchronizedMap(new LruCache<String, ImageError>());
}